1 import { raw } from "@medusajs/framework/mikro-orm/core"
2 import {
3 Context,
4 CreateTranslationDTO,
5 CreateTranslationSettingsDTO,
6 DAL,
7 FilterableTranslationProps,
8 FindConfig,
9 ITranslationModuleService,
10 LocaleDTO,
11 ModulesSdkTypes,
12 TranslationTypes,
13 UpdateTranslationSettingsDTO,
14 } from "@medusajs/framework/types"
15 import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
16 import {
17 arrayDifference,
18 DmlEntity,
19 EmitEvents,
20 InjectManager,
21 MedusaContext,
22 MedusaError,
23 MedusaErrorTypes,
24 MedusaService,
25 normalizeLocale,
26 toSnakeCase,
27 } from "@medusajs/framework/utils"
28 import Locale from "@models/locale"
29 import Translation from "@models/translation"
30 import Settings from "@models/settings"
31 import { computeTranslatedFieldCount } from "@utils/compute-translated-field-count"
32 import { filterTranslationFields } from "@utils/filter-translation-fields"
33
34 type InjectedDependencies = {
35 baseRepository: DAL.RepositoryService
36 translationService: ModulesSdkTypes.IMedusaInternalService<typeof Translation>
37 localeService: ModulesSdkTypes.IMedusaInternalService<typeof Locale>
38 translationSettingsService: ModulesSdkTypes.IMedusaInternalService<
39 typeof Settings
40 >
41 }
42
43 export default class TranslationModuleService
44 extends MedusaService<{
45 Locale: {
46 dto: TranslationTypes.LocaleDTO
47 }
48 Translation: {
49 dto: TranslationTypes.TranslationDTO
50 }
51 TranslationSettings: {
52 dto: TranslationTypes.TranslationSettingsDTO
53 }
54 }>({
55 Locale,
56 Translation,
57 TranslationSettings: Settings,
58 })
59 implements ITranslationModuleService
60 {
61 protected baseRepository_: DAL.RepositoryService
62 protected translationService_: ModulesSdkTypes.IMedusaInternalService<
63 typeof Translation
64 >
65 protected localeService_: ModulesSdkTypes.IMedusaInternalService<
66 typeof Locale
67 >
68 protected settingsService_: ModulesSdkTypes.IMedusaInternalService<
69 typeof Settings
70 >
71
72 constructor({
73 baseRepository,
74 translationService,
75 localeService,
76 translationSettingsService,
77 }: InjectedDependencies) {
78 super(...arguments)
79 this.baseRepository_ = baseRepository
80 this.translationService_ = translationService
81 this.localeService_ = localeService
82 this.settingsService_ = translationSettingsService
83 }
84
85 __hooks = {
86 onApplicationStart: async () => {
87 return this.onApplicationStart_()
88 },
89 }
90
91 protected async onApplicationStart_() {
92 const translatableEntities = DmlEntity.getTranslatableEntities()
93 const translatableEntitiesSet = new Set(
94 translatableEntities.map((entity) => toSnakeCase(entity.entity))
95 )
96
97 const currentTranslationSettings = await this.settingsService_.list()
98 const currentTranslationSettingsSet = new Set(
99 currentTranslationSettings.map((setting) => setting.entity_type)
100 )
101
102 const settingsToUpsert: (
103 | CreateTranslationSettingsDTO
104 | UpdateTranslationSettingsDTO
105 )[] = []
106
107 for (const setting of currentTranslationSettings) {
108 if (
109 !translatableEntitiesSet.has(setting.entity_type) &&
110 setting.is_active
111 ) {
112 settingsToUpsert.push({
113 id: setting.id,
114 is_active: false,
115 })
116 }
117 }
118
119 for (const entity of translatableEntities) {
120 const snakeCaseEntityType = toSnakeCase(entity.entity)
121 const hasCurrentSettings =
122 currentTranslationSettingsSet.has(snakeCaseEntityType)
123 if (!hasCurrentSettings) {
124 settingsToUpsert.push({
125 entity_type: snakeCaseEntityType,
126 fields: entity.fields,
127 })
128 }
129 }
130
131 await this.settingsService_.upsert(settingsToUpsert)
132 }
133
134 @InjectManager()
135 async getTranslatableFields(
136 entityType?: string,
137 @MedusaContext() sharedContext: Context = {}
138 ): Promise<Record<string, string[]>> {
139 const filters = entityType ? { entity_type: entityType } : {}
140 const settings = await this.settingsService_.list(
141 filters,
142 {},
143 sharedContext
144 )
145 return settings.reduce((acc, setting) => {
146 acc[setting.entity_type] = setting.is_active
147 ? (setting.fields as unknown as string[])
148 : []
149 return acc
150 }, {} as Record<string, string[]>)
151 }
152
153 @InjectManager()
154 async getInactiveTranslatableFields(
155 entityType?: string,
156 @MedusaContext() sharedContext: Context = {}
157 ): Promise<Record<string, string[]>> {
158 const translatableFields = await this.getTranslatableFields(
159 entityType,
160 sharedContext
161 )
162 return Object.entries(translatableFields).reduce(
163 (acc, [entityType, fields]) => {
164 const entity = DmlEntity.getTranslatableEntities().find(
165 (entity) => toSnakeCase(entity.entity) === entityType
166 )
167 if (!entity) {
168 return acc
169 }
170
171 acc[entityType] = arrayDifference(entity.fields, fields)
172 return acc
173 },
174 {} as Record<string, string[]>
175 )
176 }
177
178 static prepareFilters(
179 filters: FilterableTranslationProps
180 ): FilterableTranslationProps {
181 let { q, ...restFilters } = filters
182
183 if (q) {
184 restFilters = {
185 ...restFilters,
186 [raw(`translations::text ILIKE ?`, [`%${q}%`])]: [],
187 }
188 }
189
190 return restFilters
191 }
192
193 @InjectManager()
194 // @ts-expect-error
195 async retrieveTranslation(
196 id: string,
197 config: FindConfig<TranslationTypes.TranslationDTO> = {},
198 @MedusaContext() sharedContext: Context = {}
199 ): Promise<TranslationTypes.TranslationDTO> {
200 const configWithReference =
201 TranslationModuleService.ensureReferenceFieldInConfig(config)
202
203 const result = await this.translationService_.retrieve(
204 id,
205 configWithReference,
206 sharedContext
207 )
208
209 const serialized =
210 await this.baseRepository_.serialize<TranslationTypes.TranslationDTO>(
211 result
212 )
213
214 const translatableFieldsConfig = await this.getTranslatableFields(
215 undefined,
216 sharedContext
217 )
218
219 return filterTranslationFields([serialized], translatableFieldsConfig)[0]
220 }
221
222 /**
223 * Ensures the 'reference' field is included in the select config.
224 * This is needed for filtering translations by translatable fields.
225 */
226 static ensureReferenceFieldInConfig(
227 config: FindConfig<TranslationTypes.TranslationDTO>
228 ): FindConfig<TranslationTypes.TranslationDTO> {
229 if (!config?.select?.length) {
230 return config
231 }
232
233 const select = config.select as string[]
234 if (!select.includes("reference")) {
235 return { ...config, select: [...select, "reference"] }
236 }
237
238 return config
239 }
240
241 @InjectManager()
242 // @ts-expect-error
243 async listTranslations(
244 filters: FilterableTranslationProps = {},
245 config: FindConfig<TranslationTypes.TranslationDTO> = {},
246 @MedusaContext() sharedContext: Context = {}
247 ): Promise<TranslationTypes.TranslationDTO[]> {
248 const preparedFilters = TranslationModuleService.prepareFilters(filters)
249 const configWithReference =
250 TranslationModuleService.ensureReferenceFieldInConfig(config)
251
252 const results = await this.translationService_.list(
253 preparedFilters,
254 configWithReference,
255 sharedContext
256 )
257
258 const serialized = await this.baseRepository_.serialize<
259 TranslationTypes.TranslationDTO[]
260 >(results)
261
262 const translatableFieldsConfig = await this.getTranslatableFields(
263 undefined,
264 sharedContext
265 )
266
267 return filterTranslationFields(serialized, translatableFieldsConfig)
268 }
269
270 @InjectManager()
271 // @ts-expect-error
272 async listAndCountTranslations(
273 filters: FilterableTranslationProps = {},
274 config: FindConfig<TranslationTypes.TranslationDTO> = {},
275 @MedusaContext() sharedContext: Context = {}
276 ): Promise<[TranslationTypes.TranslationDTO[], number]> {
277 const preparedFilters = TranslationModuleService.prepareFilters(filters)
278 const configWithReference =
279 TranslationModuleService.ensureReferenceFieldInConfig(config)
280
281 const [results, count] = await this.translationService_.listAndCount(
282 preparedFilters,
283 configWithReference,
284 sharedContext
285 )
286
287 const serialized = await this.baseRepository_.serialize<
288 TranslationTypes.TranslationDTO[]
289 >(results)
290
291 const translatableFieldsConfig = await this.getTranslatableFields(
292 undefined,
293 sharedContext
294 )
295
296 return [
297 filterTranslationFields(serialized, translatableFieldsConfig),
298 count,
299 ]
300 }
301
302 // @ts-expect-error
303 createLocales(
304 data: TranslationTypes.CreateLocaleDTO[],
305 sharedContext?: Context
306 ): Promise<TranslationTypes.LocaleDTO[]>
307 // @ts-expect-error
308 createLocales(
309 data: TranslationTypes.CreateLocaleDTO,
310 sharedContext?: Context
311 ): Promise<TranslationTypes.LocaleDTO>
312
313 @InjectManager()
314 @EmitEvents()
315 // @ts-expect-error
316 async createLocales(
317 data: TranslationTypes.CreateLocaleDTO | TranslationTypes.CreateLocaleDTO[],
318 @MedusaContext() sharedContext: Context = {}
319 ): Promise<TranslationTypes.LocaleDTO | TranslationTypes.LocaleDTO[]> {
320 const dataArray = Array.isArray(data) ? data : [data]
321 const normalizedData = dataArray.map((locale) => ({
322 ...locale,
323 code: normalizeLocale(locale.code),
324 }))
325
326 const createdLocales = await this.localeService_.create(
327 normalizedData,
328 sharedContext
329 )
330
331 const serialized = await this.baseRepository_.serialize<LocaleDTO[]>(
332 createdLocales
333 )
334 return Array.isArray(data) ? serialized : serialized[0]
335 }
336
337 // @ts-expect-error
338 createTranslations(
339 data: CreateTranslationDTO,
340 sharedContext?: Context
341 ): Promise<TranslationTypes.TranslationDTO>
342
343 // @ts-expect-error
344 createTranslations(
345 data: CreateTranslationDTO[],
346 sharedContext?: Context
347 ): Promise<TranslationTypes.TranslationDTO[]>
348
349 @InjectManager()
350 @EmitEvents()
351 // @ts-expect-error
352 async createTranslations(
353 data: CreateTranslationDTO | CreateTranslationDTO[],
354 @MedusaContext() sharedContext: Context = {}
355 ): Promise<
356 TranslationTypes.TranslationDTO | TranslationTypes.TranslationDTO[]
357 > {
358 const dataArray = Array.isArray(data) ? data : [data]
359 const translatableFieldsConfig = await this.getTranslatableFields(
360 undefined,
361 sharedContext
362 )
363 const normalizedData = dataArray.map((translation) => ({
364 ...translation,
365 locale_code: normalizeLocale(translation.locale_code),
366 translated_field_count: computeTranslatedFieldCount(
367 translation.translations as Record<string, unknown>,
368 translatableFieldsConfig[translation.reference]
369 ),
370 }))
371
372 const createdTranslations = await this.translationService_.create(
373 normalizedData,
374 sharedContext
375 )
376
377 const serialized = await this.baseRepository_.serialize<
378 TranslationTypes.TranslationDTO[]
379 >(createdTranslations)
380
381 return Array.isArray(data) ? serialized : serialized[0]
382 }
383
384 // @ts-expect-error
385 updateTranslations(
386 data: TranslationTypes.UpdateTranslationDTO,
387 sharedContext?: Context
388 ): Promise<TranslationTypes.TranslationDTO>
389 // @ts-expect-error
390 updateTranslations(
391 data: TranslationTypes.UpdateTranslationDTO[],
392 sharedContext?: Context
393 ): Promise<TranslationTypes.TranslationDTO[]>
394
395 @InjectManager()
396 @EmitEvents()
397 // @ts-expect-error
398 async updateTranslations(
399 data:
400 | TranslationTypes.UpdateTranslationDTO
401 | TranslationTypes.UpdateTranslationDTO[],
402 @MedusaContext() sharedContext: Context = {}
403 ): Promise<
404 TranslationTypes.TranslationDTO | TranslationTypes.TranslationDTO[]
405 > {
406 const dataArray = Array.isArray(data) ? data : [data]
407
408 const updatesWithTranslations = dataArray.filter((d) => d.translations)
409
410 if (updatesWithTranslations.length) {
411 const idsNeedingReference = updatesWithTranslations
412 .filter((d) => !d.reference)
413 .map((d) => d.id)
414
415 let referenceMap: Record<string, string> = {}
416
417 if (idsNeedingReference.length) {
418 const existingTranslations = await this.translationService_.list(
419 { id: idsNeedingReference },
420 { select: ["id", "reference"] },
421 sharedContext
422 )
423 referenceMap = Object.fromEntries(
424 existingTranslations.map((t) => [t.id, t.reference])
425 )
426 }
427
428 const translatableFieldsConfig = await this.getTranslatableFields(
429 undefined,
430 sharedContext
431 )
432
433 for (const update of dataArray) {
434 if (update.translations) {
435 const reference = update.reference || referenceMap[update.id]
436 ;(
437 update as TranslationTypes.UpdateTranslationDTO & {
438 translated_field_count: number
439 }
440 ).translated_field_count = computeTranslatedFieldCount(
441 update.translations as Record<string, unknown>,
442 translatableFieldsConfig[reference] || []
443 )
444 }
445 }
446 }
447
448 const updatedTranslations = await this.translationService_.update(
449 dataArray,
450 sharedContext
451 )
452
453 const serialized = await this.baseRepository_.serialize<
454 TranslationTypes.TranslationDTO[]
455 >(updatedTranslations)
456
457 return Array.isArray(data) ? serialized : serialized[0]
458 }
459
460 @InjectManager()
461 @EmitEvents()
462 // @ts-expect-error
463 async createTranslationSettings(
464 data: CreateTranslationSettingsDTO[] | CreateTranslationSettingsDTO,
465 @MedusaContext() sharedContext: Context = {}
466 ): Promise<
467 | TranslationTypes.TranslationSettingsDTO
468 | TranslationTypes.TranslationSettingsDTO[]
469 > {
470 const dataArray = Array.isArray(data) ? data : [data]
471
472 const normalizedData = await this.ensureEntityType_(
473 dataArray,
474 sharedContext
475 )
476 TranslationModuleService.validateSettings(normalizedData)
477
478 // @ts-expect-error TS can't match union type to overloads
479 return await super.createTranslationSettings(data, sharedContext)
480 }
481
482 @InjectManager()
483 @EmitEvents()
484 // @ts-expect-error
485 async updateTranslationSettings(
486 data: UpdateTranslationSettingsDTO | UpdateTranslationSettingsDTO[],
487 @MedusaContext() sharedContext: Context = {}
488 ): Promise<
489 | TranslationTypes.TranslationSettingsDTO[]
490 | TranslationTypes.TranslationSettingsDTO
491 > {
492 const dataArray = Array.isArray(data) ? data : [data]
493
494 const normalizedData = await this.ensureEntityType_(
495 dataArray,
496 sharedContext
497 )
498 TranslationModuleService.validateSettings(normalizedData)
499
500 const updatedSettings = await this.settingsService_.update(
501 data,
502 sharedContext
503 )
504
505 const entityTypes = [
506 ...new Set(normalizedData.map((setting) => setting.entity_type)),
507 ]
508
509 const translatableFieldsConfig = await this.getTranslatableFields(
510 undefined,
511 sharedContext
512 )
513
514 const translations = await this.translationService_.list({
515 reference: entityTypes,
516 })
517
518 const toUpdate = translations.map((translation) => ({
519 id: translation.id,
520 translated_field_count: computeTranslatedFieldCount(
521 translation.translations,
522 translatableFieldsConfig[translation.reference] ?? []
523 ),
524 }))
525
526 if (toUpdate.length) {
527 await this.translationService_.update(toUpdate, sharedContext)
528 }
529
530 const serialized = await this.baseRepository_.serialize<
531 TranslationTypes.TranslationSettingsDTO[]
532 >(updatedSettings)
533
534 return Array.isArray(data) ? serialized : serialized[0]
535 }
536
537 @InjectManager()
538 async getStatistics(
539 input: TranslationTypes.TranslationStatisticsInput,
540 @MedusaContext() sharedContext: Context = {}
541 ): Promise<TranslationTypes.TranslationStatisticsOutput> {
542 const { locales, entities } = input
543
544 if (!locales || !locales.length) {
545 throw new MedusaError(
546 MedusaError.Types.INVALID_DATA,
547 "At least one locale must be provided"
548 )
549 }
550
551 if (!entities || !Object.keys(entities).length) {
552 throw new MedusaError(
553 MedusaError.Types.INVALID_DATA,
554 "At least one entity type must be provided"
555 )
556 }
557
558 const normalizedLocales = locales.map(normalizeLocale)
559
560 const manager = (sharedContext.transactionManager ??
561 sharedContext.manager) as SqlEntityManager
562 const knex = manager.getKnex()
563
564 const translatableFieldsConfig = await this.getTranslatableFields(
565 undefined,
566 sharedContext
567 )
568
569 const result: TranslationTypes.TranslationStatisticsOutput = {}
570 const entityTypes: string[] = []
571
572 for (const entityType of Object.keys(entities)) {
573 const translatableFields = translatableFieldsConfig[entityType]
574
575 if (!translatableFields || translatableFields.length === 0) {
576 result[entityType] = {
577 expected: 0,
578 translated: 0,
579 missing: 0,
580 by_locale: Object.fromEntries(
581 normalizedLocales.map((locale) => [
582 locale,
583 { expected: 0, translated: 0, missing: 0 },
584 ])
585 ),
586 }
587 } else {
588 entityTypes.push(entityType)
589 }
590 }
591
592 if (!entityTypes.length) {
593 return result
594 }
595
596 const { rows } = await knex.raw(
597 `
598 SELECT
599 reference,
600 locale_code,
601 COALESCE(SUM(translated_field_count), 0)::int AS translated_field_count
602 FROM translation
603 WHERE reference = ANY(?)
604 AND locale_code = ANY(?)
605 AND deleted_at IS NULL
606 GROUP BY reference, locale_code
607 `,
608 [entityTypes, normalizedLocales]
609 )
610
611 for (const entityType of entityTypes) {
612 const translatableFields = translatableFieldsConfig[entityType]
613 const fieldsPerEntity = translatableFields.length
614 const entityCount = entities[entityType].count
615 const expectedPerLocale = entityCount * fieldsPerEntity
616
617 result[entityType] = {
618 expected: expectedPerLocale * normalizedLocales.length,
619 translated: 0,
620 missing: expectedPerLocale * normalizedLocales.length,
621 by_locale: Object.fromEntries(
622 normalizedLocales.map((locale) => [
623 locale,
624 {
625 expected: expectedPerLocale,
626 translated: 0,
627 missing: expectedPerLocale,
628 },
629 ])
630 ),
631 }
632 }
633
634 for (const row of rows) {
635 const entityType = row.reference
636 const localeCode = row.locale_code
637 const translatedCount = parseInt(row.translated_field_count, 10) || 0
638
639 result[entityType].by_locale[localeCode].translated = translatedCount
640 result[entityType].by_locale[localeCode].missing =
641 result[entityType].by_locale[localeCode].expected - translatedCount
642 result[entityType].translated += translatedCount
643 }
644
645 for (const entityType of entityTypes) {
646 result[entityType].missing =
647 result[entityType].expected - result[entityType].translated
648 }
649
650 return result
651 }
652
653 /**
654 * Validates the translation settings to create or update against the translatable entities and their translatable fields configuration.
655 * @param dataToValidate - The data to validate.
656 */
657 static validateSettings(
658 dataToValidate: (
659 | CreateTranslationSettingsDTO
660 | (UpdateTranslationSettingsDTO & { entity_type: string })
661 )[]
662 ) {
663 const translatableEntities = DmlEntity.getTranslatableEntities()
664 const translatableEntitiesMap = new Map(
665 translatableEntities.map((entity) => [toSnakeCase(entity.entity), entity])
666 )
667
668 const invalidSettings: {
669 entity_type: string
670 is_invalid_entity: boolean
671 invalidFields?: string[]
672 }[] = []
673
674 for (const item of dataToValidate) {
675 const entityType = item.entity_type
676 const entity = translatableEntitiesMap.get(entityType)
677
678 if (!entity) {
679 invalidSettings.push({
680 entity_type: entityType,
681 is_invalid_entity: true,
682 })
683 } else {
684 const invalidFields = arrayDifference(item.fields ?? [], entity.fields)
685 if (invalidFields.length) {
686 invalidSettings.push({
687 entity_type: entityType,
688 is_invalid_entity: false,
689 invalidFields,
690 })
691 }
692 }
693 }
694
695 if (invalidSettings.length) {
696 throw new MedusaError(
697 MedusaErrorTypes.INVALID_DATA,
698 "Invalid translation settings:\n" +
699 invalidSettings
700 .map(
701 (setting) =>
702 `- ${setting.entity_type} ${
703 setting.is_invalid_entity
704 ? "is not a translatable entity"
705 : `doesn't have the following fields set as translatable: ${setting.invalidFields?.join(
706 ", "
707 )}`
708 }`
709 )
710 .join("\n")
711 )
712 }
713 }
714
715 /**
716 * Ensures the entity type is set for the settings to be created or updated. This is useful for validation purposes and recomputing the translated field count.
717 * @param settings - The settings to ensure the entity type for.
718 * @param sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
719 * @returns The settings with the entity type set.
720 */
721 protected async ensureEntityType_(
722 settings: (CreateTranslationSettingsDTO | UpdateTranslationSettingsDTO)[],
723 @MedusaContext() sharedContext: Context = {}
724 ): Promise<
725 (
726 | CreateTranslationSettingsDTO
727 | (UpdateTranslationSettingsDTO & { entity_type: string })
728 )[]
729 > {
730 const idsNeedingResolution = settings
731 .filter((setting) => !setting.entity_type && "id" in setting)
732 .map((setting) => (setting as UpdateTranslationSettingsDTO).id)
733
734 let entityTypeMap: Record<string, string> = {}
735
736 if (idsNeedingResolution.length) {
737 const existingSettings = await this.settingsService_.list(
738 { id: idsNeedingResolution },
739 { select: ["id", "entity_type"] },
740 sharedContext
741 )
742 entityTypeMap = Object.fromEntries(
743 existingSettings.map((s) => [s.id, s.entity_type])
744 )
745 }
746
747 return settings.map((setting) => {
748 const entityType =
749 setting.entity_type ||
750 entityTypeMap[(setting as UpdateTranslationSettingsDTO).id]
751 return { ...setting, entity_type: entityType }
752 })
753 }
754 }