1 import {
2 Context,
3 DAL,
4 HttpTypes,
5 InferEntityType,
6 InternalModuleDeclaration,
7 ModulesSdkTypes,
8 SettingsTypes,
9 } from "@medusajs/framework/types"
10 import {
11 EmitEvents,
12 InjectManager,
13 InjectTransactionManager,
14 MedusaContext,
15 MedusaError,
16 MedusaService,
17 } from "@medusajs/framework/utils"
18 import { MedusaModule } from "@medusajs/framework/modules-sdk"
19 import {
20 ViewConfiguration,
21 UserPreference,
22 PropertyLabel,
23 LayoutConfiguration,
24 } from "@/models"
25 import {
26 EntityDiscoveryService,
27 generateEntityColumns,
28 getComputedColumnRegistry,
29 getEntityOverrideRegistry,
30 PropertyLabel as PropertyLabelType,
31 } from "@/utils"
32 import { SettingsModuleOptions } from "@/types"
33
34 type InjectedDependencies = {
35 baseRepository: DAL.RepositoryService
36 viewConfigurationService: ModulesSdkTypes.IMedusaInternalService<any>
37 propertyLabelService: ModulesSdkTypes.IMedusaInternalService<any>
38 layoutConfigurationService: ModulesSdkTypes.IMedusaInternalService<any>
39 }
40
41 export default class SettingsModuleService
42 extends MedusaService<{
43 ViewConfiguration: { dto: SettingsTypes.ViewConfigurationDTO }
44 UserPreference: { dto: SettingsTypes.UserPreferenceDTO }
45 PropertyLabel: { dto: SettingsTypes.PropertyLabelDTO }
46 LayoutConfiguration: { dto: SettingsTypes.LayoutConfigurationDTO }
47 }>({ ViewConfiguration, UserPreference, PropertyLabel, LayoutConfiguration })
48 implements SettingsTypes.ISettingsModuleService
49 {
50 protected baseRepository_: DAL.RepositoryService
51 // viewConfigurationService_ is needed for special JSON update handling (upsertWithReplace)
52 protected readonly viewConfigurationService_: ModulesSdkTypes.IMedusaInternalService<
53 InferEntityType<typeof ViewConfiguration>
54 >
55 protected readonly propertyLabelService_: ModulesSdkTypes.IMedusaInternalService<
56 InferEntityType<typeof PropertyLabel>
57 >
58 // layoutConfigurationService_ is needed for special JSON update handling (upsertWithReplace)
59 protected readonly layoutConfigurationService_: ModulesSdkTypes.IMedusaInternalService<
60 InferEntityType<typeof LayoutConfiguration>
61 >
62 protected entityDiscoveryService_: EntityDiscoveryService
63
64 constructor(
65 {
66 baseRepository,
67 viewConfigurationService,
68 propertyLabelService,
69 layoutConfigurationService,
70 }: InjectedDependencies,
71 options: SettingsModuleOptions = {},
72 protected readonly moduleDeclaration: InternalModuleDeclaration
73 ) {
74 super(...arguments)
75 this.baseRepository_ = baseRepository
76 this.viewConfigurationService_ = viewConfigurationService
77 this.propertyLabelService_ = propertyLabelService
78 this.layoutConfigurationService_ = layoutConfigurationService
79 this.entityDiscoveryService_ = new EntityDiscoveryService()
80
81 this.registerColumnCustomizations_(options)
82 }
83
84 /**
85 * Merge module-provided entity overrides and computed columns into the shared
86 * registries so generated columns reflect user customizations.
87 */
88 protected registerColumnCustomizations_(
89 options: SettingsModuleOptions
90 ): void {
91 const overrideRegistry = getEntityOverrideRegistry()
92 const computedColumnRegistry = getComputedColumnRegistry()
93
94 for (const [entity, override] of Object.entries(
95 options.entityOverrides ?? {}
96 )) {
97 const existingOverride = overrideRegistry.get(entity) ?? {}
98 overrideRegistry.register(entity, {
99 ...existingOverride,
100 ...override,
101 })
102 if (override.computedColumns?.length) {
103 computedColumnRegistry.register(entity, override.computedColumns)
104 }
105 }
106 }
107
108 __hooks = {
109 onApplicationStart: async () => {
110 // Initialize entity discovery with joiner configs
111 const joinerConfigs = MedusaModule.getAllJoinerConfigs()
112 this.entityDiscoveryService_.initialize(joinerConfigs)
113 },
114 }
115
116 @InjectManager()
117 @EmitEvents()
118 // @ts-expect-error
119 async createViewConfigurations(
120 data:
121 | SettingsTypes.CreateViewConfigurationDTO
122 | SettingsTypes.CreateViewConfigurationDTO[],
123 @MedusaContext() sharedContext: Context = {}
124 ): Promise<
125 SettingsTypes.ViewConfigurationDTO | SettingsTypes.ViewConfigurationDTO[]
126 > {
127 // Convert to array for validation only
128 const isArrayInput = Array.isArray(data)
129 const dataArray = isArrayInput ? data : [data]
130
131 // Validate system defaults
132 for (const config of dataArray) {
133 if (config.is_system_default && config.user_id) {
134 throw new MedusaError(
135 MedusaError.Types.INVALID_DATA,
136 "System default view configurations cannot have a user_id"
137 )
138 }
139
140 if (config.is_system_default) {
141 // Check if a system default already exists for this entity
142 const existingDefault = await this.viewConfigurationService_.list(
143 {
144 entity: config.entity,
145 is_system_default: true,
146 },
147 { select: ["id"] },
148 sharedContext
149 )
150
151 if (existingDefault.length > 0) {
152 throw new MedusaError(
153 MedusaError.Types.DUPLICATE_ERROR,
154 `A system default view configuration already exists for entity: ${config.entity}`
155 )
156 }
157 }
158 }
159
160 const result = await super.createViewConfigurations(
161 dataArray,
162 sharedContext
163 )
164
165 return await this.baseRepository_.serialize<
166 SettingsTypes.ViewConfigurationDTO[] | SettingsTypes.ViewConfigurationDTO
167 >(isArrayInput ? result : result[0])
168 }
169
170 @InjectManager()
171 @EmitEvents()
172 // @ts-expect-error
173 async updateViewConfigurations(
174 idOrSelector: string | SettingsTypes.FilterableViewConfigurationProps,
175 data: SettingsTypes.UpdateViewConfigurationDTO,
176 @MedusaContext() sharedContext: Context = {}
177 ): Promise<
178 SettingsTypes.ViewConfigurationDTO | SettingsTypes.ViewConfigurationDTO[]
179 > {
180 const updated = await this.updateViewConfigurations_(
181 idOrSelector,
182 data,
183 sharedContext
184 )
185
186 const serialized = await this.baseRepository_.serialize<
187 SettingsTypes.ViewConfigurationDTO[] | SettingsTypes.ViewConfigurationDTO
188 >(updated)
189
190 return typeof idOrSelector === "string" ? serialized[0] : serialized
191 }
192
193 @InjectTransactionManager()
194 protected async updateViewConfigurations_(
195 idOrSelector: string | SettingsTypes.FilterableViewConfigurationProps,
196 data: SettingsTypes.UpdateViewConfigurationDTO,
197 @MedusaContext() sharedContext: Context = {}
198 ): Promise<InferEntityType<typeof ViewConfiguration>[]> {
199 let selector: SettingsTypes.FilterableViewConfigurationProps = {}
200
201 if (typeof idOrSelector === "string") {
202 selector = { id: idOrSelector }
203 } else {
204 selector = idOrSelector
205 }
206
207 // Special handling for configuration updates to ensure replacement instead of merge
208 if (data.configuration) {
209 // First, get the entities to update
210 const entities = await this.viewConfigurationService_.list(
211 selector,
212 {},
213 sharedContext
214 )
215
216 if (entities.length === 0) {
217 return typeof idOrSelector === "string" ? [] : []
218 }
219
220 // Use upsertWithReplace to update the configuration field without merging
221 const updateDataArray = entities.map((entity) => ({
222 id: entity.id,
223 ...data,
224 configuration: {
225 visible_columns: data.configuration?.visible_columns ?? [],
226 column_order: data.configuration?.column_order ?? [],
227 column_widths:
228 data.configuration?.column_widths !== undefined
229 ? data.configuration.column_widths
230 : {},
231 filters:
232 data.configuration?.filters !== undefined
233 ? data.configuration.filters
234 : {},
235 sorting:
236 data.configuration?.sorting !== undefined
237 ? data.configuration.sorting
238 : null,
239 search:
240 data.configuration?.search !== undefined
241 ? data.configuration.search
242 : "",
243 },
244 }))
245
246 // Use upsertWithReplace which uses nativeUpdateMany internally and doesn't merge JSON fields
247 const { entities: updatedEntities } =
248 await this.viewConfigurationService_.upsertWithReplace(
249 updateDataArray,
250 { relations: [] },
251 sharedContext
252 )
253
254 return updatedEntities
255 }
256
257 // For non-configuration updates, use the standard update method
258 const updated = await this.viewConfigurationService_.update(
259 { selector, data },
260 sharedContext
261 )
262
263 return updated as unknown as InferEntityType<typeof ViewConfiguration>[]
264 }
265
266 @InjectManager()
267 async getUserPreference(
268 userId: string,
269 key: string,
270 @MedusaContext() sharedContext: Context = {}
271 ): Promise<SettingsTypes.UserPreferenceDTO | null> {
272 const prefs = await this.listUserPreferences(
273 { user_id: userId, key },
274 { take: 1 },
275 sharedContext
276 )
277 return prefs.length > 0 ? prefs[0] : null
278 }
279
280 @InjectManager()
281 @EmitEvents()
282 async setUserPreference(
283 userId: string,
284 key: string,
285 value: any,
286 @MedusaContext() sharedContext: Context = {}
287 ): Promise<SettingsTypes.UserPreferenceDTO> {
288 const existing = await this.listUserPreferences(
289 { user_id: userId, key },
290 { take: 1, select: ["id"] },
291 sharedContext
292 )
293
294 if (existing.length > 0) {
295 const [updated] = await this.updateUserPreferences(
296 [{ id: existing[0].id, value }],
297 sharedContext
298 )
299 return updated
300 } else {
301 const created = await this.createUserPreferences(
302 { user_id: userId, key, value },
303 sharedContext
304 )
305 return Array.isArray(created) ? created[0] : created
306 }
307 }
308
309 @InjectManager()
310 async getActiveViewConfiguration(
311 entity: string,
312 userId: string,
313 @MedusaContext() sharedContext: Context = {}
314 ): Promise<SettingsTypes.ViewConfigurationDTO | null> {
315 // Check if user has an active view preference
316 const activeViewPref = await this.getUserPreference(
317 userId,
318 `active_view.${entity}`,
319 sharedContext
320 )
321
322 // Check if we have a preference with a view configuration ID (not explicitly null)
323 if (
324 activeViewPref &&
325 activeViewPref.value?.viewConfigurationId &&
326 activeViewPref.value.viewConfigurationId !== null
327 ) {
328 try {
329 return await this.retrieveViewConfiguration(
330 activeViewPref.value.viewConfigurationId,
331 {},
332 sharedContext
333 )
334 } catch (error) {
335 // View configuration might have been deleted
336 }
337 }
338
339 // If we have an explicit null preference, or no preference, or a deleted view
340 // We should check for defaults in this order:
341
342 // Check if user has any personal views (only if no explicit null preference)
343 if (!activeViewPref || activeViewPref.value?.viewConfigurationId !== null) {
344 const [personalView] = await this.listViewConfigurations(
345 { entity, user_id: userId },
346 { take: 1, order: { created_at: "ASC" } },
347 sharedContext
348 )
349
350 if (personalView) {
351 return personalView
352 }
353 }
354
355 // Fall back to system default
356 const systemDefaults = await this.listViewConfigurations(
357 { entity, is_system_default: true },
358 {},
359 sharedContext
360 )
361
362 return systemDefaults.length > 0 ? systemDefaults[0] : null
363 }
364
365 @InjectManager()
366 @EmitEvents()
367 async setActiveViewConfiguration(
368 entity: string,
369 userId: string,
370 viewConfigurationId: string,
371 @MedusaContext() sharedContext: Context = {}
372 ): Promise<void> {
373 // Verify the view configuration exists and user has access
374 const viewConfig = await this.retrieveViewConfiguration(
375 viewConfigurationId,
376 {},
377 sharedContext
378 )
379
380 if (viewConfig.entity !== entity) {
381 throw new MedusaError(
382 MedusaError.Types.INVALID_DATA,
383 `View configuration ${viewConfigurationId} is not for entity ${entity}`
384 )
385 }
386
387 if (viewConfig.user_id && viewConfig.user_id !== userId) {
388 throw new MedusaError(
389 MedusaError.Types.NOT_ALLOWED,
390 `User ${userId} does not have access to view configuration ${viewConfigurationId}`
391 )
392 }
393
394 await this.setUserPreference(
395 userId,
396 `active_view.${entity}`,
397 { viewConfigurationId },
398 sharedContext
399 )
400 }
401
402 @InjectManager()
403 async getSystemDefaultViewConfiguration(
404 entity: string,
405 @MedusaContext() sharedContext: Context = {}
406 ): Promise<SettingsTypes.ViewConfigurationDTO | null> {
407 const systemDefaults = await this.listViewConfigurations(
408 { entity, is_system_default: true },
409 {},
410 sharedContext
411 )
412
413 return systemDefaults.length > 0 ? systemDefaults[0] : null
414 }
415
416 @InjectManager()
417 @EmitEvents()
418 async clearActiveViewConfiguration(
419 entity: string,
420 userId: string,
421 @MedusaContext() sharedContext: Context = {}
422 ): Promise<void> {
423 await this.setUserPreference(
424 userId,
425 `active_view.${entity}`,
426 { viewConfigurationId: null },
427 sharedContext
428 )
429 }
430
431 @InjectManager()
432 async getSystemDefaultLayoutConfiguration(
433 zone: string,
434 @MedusaContext() sharedContext: Context = {}
435 ): Promise<SettingsTypes.LayoutConfigurationDTO | null> {
436 const [systemDefault] = await this.listLayoutConfigurations(
437 { zone, is_system_default: true },
438 { take: 1 },
439 sharedContext
440 )
441
442 return systemDefault ?? null
443 }
444
445 @InjectManager()
446 @EmitEvents()
447 async setLayoutConfiguration(
448 zone: string,
449 userId: string,
450 configuration: SettingsTypes.LayoutConfigurationData,
451 @MedusaContext() sharedContext: Context = {}
452 ): Promise<SettingsTypes.LayoutConfigurationDTO> {
453 const upserted = await this.upsertLayoutConfiguration_(
454 { zone, user_id: userId, is_system_default: false },
455 configuration,
456 sharedContext
457 )
458
459 return await this.baseRepository_.serialize<SettingsTypes.LayoutConfigurationDTO>(
460 upserted
461 )
462 }
463
464 @InjectManager()
465 @EmitEvents()
466 async setSystemDefaultLayoutConfiguration(
467 zone: string,
468 configuration: SettingsTypes.LayoutConfigurationData,
469 @MedusaContext() sharedContext: Context = {}
470 ): Promise<SettingsTypes.LayoutConfigurationDTO> {
471 const upserted = await this.upsertLayoutConfiguration_(
472 { zone, user_id: null, is_system_default: true },
473 configuration,
474 sharedContext
475 )
476
477 return await this.baseRepository_.serialize<SettingsTypes.LayoutConfigurationDTO>(
478 upserted
479 )
480 }
481
482 @InjectTransactionManager()
483 protected async upsertLayoutConfiguration_(
484 selector: {
485 zone: string
486 user_id: string | null
487 is_system_default: boolean
488 },
489 configuration: SettingsTypes.LayoutConfigurationData,
490 @MedusaContext() sharedContext: Context = {}
491 ): Promise<InferEntityType<typeof LayoutConfiguration>> {
492 const [existing] = await this.layoutConfigurationService_.list(
493 { zone: selector.zone, user_id: selector.user_id },
494 { select: ["id"], take: 1 },
495 sharedContext
496 )
497
498 // Replace the configuration JSON wholesale rather than merging, so removing
499 // a widget override actually drops it.
500 const normalized = { widgets: configuration?.widgets ?? {} }
501
502 const payload = existing
503 ? { id: existing.id, configuration: normalized }
504 : {
505 zone: selector.zone,
506 user_id: selector.user_id,
507 is_system_default: selector.is_system_default,
508 configuration: normalized,
509 }
510
511 const { entities } =
512 await this.layoutConfigurationService_.upsertWithReplace(
513 [payload],
514 { relations: [] },
515 sharedContext
516 )
517
518 return entities[0]
519 }
520
521 @InjectManager()
522 @EmitEvents()
523 async clearLayoutConfiguration(
524 zone: string,
525 userId: string,
526 @MedusaContext() sharedContext: Context = {}
527 ): Promise<void> {
528 const existing = await this.layoutConfigurationService_.list(
529 { zone, user_id: userId },
530 { select: ["id"] },
531 sharedContext
532 )
533
534 if (existing.length) {
535 await this.deleteLayoutConfigurations(
536 existing.map((c) => c.id),
537 sharedContext
538 )
539 }
540 }
541
542 protected getActiveLayoutScopeKey(zone: string): string {
543 return `active_layout.${zone}`
544 }
545
546 @InjectManager()
547 async getActiveLayoutScope(
548 zone: string,
549 userId: string,
550 @MedusaContext() sharedContext: Context = {}
551 ): Promise<"personal" | "default" | null> {
552 const pref = await this.getUserPreference(
553 userId,
554 this.getActiveLayoutScopeKey(zone),
555 sharedContext
556 )
557
558 const scope = pref?.value?.scope
559 return scope === "personal" || scope === "default" ? scope : null
560 }
561
562 @InjectManager()
563 async setActiveLayoutScope(
564 zone: string,
565 userId: string,
566 scope: "personal" | "default" | null,
567 @MedusaContext() sharedContext: Context = {}
568 ): Promise<void> {
569 await this.setUserPreference(
570 userId,
571 this.getActiveLayoutScopeKey(zone),
572 { scope },
573 sharedContext
574 )
575 }
576
577 @InjectManager()
578 async upsertPropertyLabels(
579 data: SettingsTypes.UpsertPropertyLabelDTO[],
580 @MedusaContext() sharedContext: Context = {}
581 ): Promise<SettingsTypes.PropertyLabelDTO[]> {
582 const upserted = await this.propertyLabelService_.upsert(
583 data,
584 sharedContext
585 )
586 return await this.baseRepository_.serialize<
587 SettingsTypes.PropertyLabelDTO[]
588 >(upserted)
589 }
590
591 /**
592 * Check if entity discovery has been initialized.
593 */
594 isEntityDiscoveryInitialized(): boolean {
595 return this.entityDiscoveryService_.isInitialized()
596 }
597
598 /**
599 * List all discoverable entities.
600 */
601 @InjectManager()
602 async listDiscoverableEntities(
603 @MedusaContext() sharedContext: Context = {}
604 ): Promise<HttpTypes.AdminEntityInfo[]> {
605 if (!this.entityDiscoveryService_.isInitialized()) {
606 return []
607 }
608
609 const entities = this.entityDiscoveryService_.discoverEntities()
610
611 const labels = await this.propertyLabelService_.list(
612 {},
613 { select: ["entity"] },
614 sharedContext
615 )
616 const entitiesWithLabels = new Set(labels.map((label) => label.entity))
617
618 return entities.map((entity) =>
619 this.entityDiscoveryService_.getEntityInfo(
620 entity,
621 entitiesWithLabels.has(entity.name)
622 )
623 )
624 }
625
626 /**
627 * Check if an entity exists by name.
628 */
629 hasEntity(name: string): boolean {
630 return this.entityDiscoveryService_.hasEntity(name)
631 }
632
633 /**
634 * Generate columns for an entity.
635 */
636 @InjectManager()
637 async generateEntityColumns(
638 entityKey: string,
639 @MedusaContext() sharedContext: Context = {}
640 ): Promise<SettingsTypes.ViewConfigurationColumnDTO[] | null> {
641 if (!this.entityDiscoveryService_.isInitialized()) {
642 return null
643 }
644
645 const entity = this.entityDiscoveryService_.getEntity(entityKey)
646 if (!entity) {
647 return null
648 }
649
650 const labels = await this.propertyLabelService_.list(
651 { entity: entity.name },
652 {},
653 sharedContext
654 )
655
656 const propertyLabelsMap = new Map<string, PropertyLabelType>()
657 for (const label of labels) {
658 propertyLabelsMap.set(label.property, {
659 id: label.id,
660 entity: label.entity,
661 property: label.property,
662 label: label.label,
663 description: label.description,
664 })
665 }
666
667 const columns = generateEntityColumns(
668 this.entityDiscoveryService_,
669 entityKey,
670 propertyLabelsMap
671 )
672
673 return await this.baseRepository_.serialize<
674 SettingsTypes.ViewConfigurationColumnDTO[]
675 >(columns)
676 }
677 }