@porulle/core 0.10.6 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/config/types.d.ts +3 -0
  2. package/dist/config/types.d.ts.map +1 -1
  3. package/dist/hooks/checkout.d.ts +2 -0
  4. package/dist/hooks/checkout.d.ts.map +1 -1
  5. package/dist/hooks/checkout.js +2 -0
  6. package/dist/index.d.ts +3 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -0
  9. package/dist/interfaces/rest/index.d.ts.map +1 -1
  10. package/dist/interfaces/rest/index.js +4 -0
  11. package/dist/interfaces/rest/routes/admin/custom-field-proposals.d.ts +5 -0
  12. package/dist/interfaces/rest/routes/admin/custom-field-proposals.d.ts.map +1 -0
  13. package/dist/interfaces/rest/routes/admin/custom-field-proposals.js +22 -0
  14. package/dist/interfaces/rest/routes/admin/entity-field-definitions.d.ts +5 -0
  15. package/dist/interfaces/rest/routes/admin/entity-field-definitions.d.ts.map +1 -0
  16. package/dist/interfaces/rest/routes/admin/entity-field-definitions.js +39 -0
  17. package/dist/interfaces/rest/routes/catalog.d.ts.map +1 -1
  18. package/dist/interfaces/rest/routes/catalog.js +37 -2
  19. package/dist/interfaces/rest/routes/checkout.d.ts.map +1 -1
  20. package/dist/interfaces/rest/routes/checkout.js +7 -1
  21. package/dist/interfaces/rest/routes/payments.d.ts.map +1 -1
  22. package/dist/interfaces/rest/routes/payments.js +48 -30
  23. package/dist/interfaces/rest/routes/search.d.ts.map +1 -1
  24. package/dist/interfaces/rest/routes/search.js +12 -0
  25. package/dist/interfaces/rest/schemas/admin-custom-field-proposals.d.ts +134 -0
  26. package/dist/interfaces/rest/schemas/admin-custom-field-proposals.d.ts.map +1 -0
  27. package/dist/interfaces/rest/schemas/admin-custom-field-proposals.js +26 -0
  28. package/dist/interfaces/rest/schemas/admin-entity-field-definitions.d.ts +592 -0
  29. package/dist/interfaces/rest/schemas/admin-entity-field-definitions.d.ts.map +1 -0
  30. package/dist/interfaces/rest/schemas/admin-entity-field-definitions.js +109 -0
  31. package/dist/interfaces/rest/schemas/catalog.d.ts +1364 -401
  32. package/dist/interfaces/rest/schemas/catalog.d.ts.map +1 -1
  33. package/dist/interfaces/rest/schemas/catalog.js +86 -0
  34. package/dist/interfaces/rest/schemas/pricing.d.ts +1 -0
  35. package/dist/interfaces/rest/schemas/pricing.d.ts.map +1 -1
  36. package/dist/interfaces/rest/schemas/search.d.ts +1 -0
  37. package/dist/interfaces/rest/schemas/search.d.ts.map +1 -1
  38. package/dist/interfaces/rest/schemas/search.js +1 -0
  39. package/dist/kernel/error-mapper.d.ts.map +1 -1
  40. package/dist/kernel/error-mapper.js +3 -0
  41. package/dist/modules/catalog/entity-service.d.ts +5 -3
  42. package/dist/modules/catalog/entity-service.d.ts.map +1 -1
  43. package/dist/modules/catalog/entity-service.js +73 -22
  44. package/dist/modules/catalog/module.d.ts +6 -1
  45. package/dist/modules/catalog/module.d.ts.map +1 -1
  46. package/dist/modules/catalog/module.js +6 -1
  47. package/dist/modules/catalog/ownership.d.ts +5 -0
  48. package/dist/modules/catalog/ownership.d.ts.map +1 -0
  49. package/dist/modules/catalog/ownership.js +11 -0
  50. package/dist/modules/catalog/repository/index.d.ts +52 -1
  51. package/dist/modules/catalog/repository/index.d.ts.map +1 -1
  52. package/dist/modules/catalog/repository/index.js +321 -2
  53. package/dist/modules/catalog/revision.d.ts +4 -0
  54. package/dist/modules/catalog/revision.d.ts.map +1 -0
  55. package/dist/modules/catalog/revision.js +33 -0
  56. package/dist/modules/catalog/schema.d.ts +979 -110
  57. package/dist/modules/catalog/schema.d.ts.map +1 -1
  58. package/dist/modules/catalog/schema.js +112 -2
  59. package/dist/modules/catalog/schemas.d.ts +2 -0
  60. package/dist/modules/catalog/schemas.d.ts.map +1 -1
  61. package/dist/modules/catalog/schemas.js +2 -0
  62. package/dist/modules/catalog/service.d.ts +66 -3
  63. package/dist/modules/catalog/service.d.ts.map +1 -1
  64. package/dist/modules/catalog/service.js +512 -11
  65. package/dist/modules/channels/adapter.d.ts +85 -0
  66. package/dist/modules/channels/adapter.d.ts.map +1 -1
  67. package/dist/modules/channels/adapter.js +9 -1
  68. package/dist/modules/media/module.d.ts +68 -0
  69. package/dist/modules/media/module.d.ts.map +1 -1
  70. package/dist/modules/media/module.js +2 -0
  71. package/dist/modules/media/schema.d.ts +70 -0
  72. package/dist/modules/media/schema.d.ts.map +1 -1
  73. package/dist/modules/media/schema.js +20 -2
  74. package/dist/modules/media/service.d.ts +8 -1
  75. package/dist/modules/media/service.d.ts.map +1 -1
  76. package/dist/modules/media/service.js +66 -18
  77. package/dist/modules/orders/service.d.ts +2 -0
  78. package/dist/modules/orders/service.d.ts.map +1 -1
  79. package/dist/modules/orders/service.js +1 -0
  80. package/dist/modules/pricing/schema.d.ts +17 -0
  81. package/dist/modules/pricing/schema.d.ts.map +1 -1
  82. package/dist/modules/pricing/schema.js +1 -0
  83. package/dist/modules/pricing/schemas.d.ts +1 -0
  84. package/dist/modules/pricing/schemas.d.ts.map +1 -1
  85. package/dist/modules/pricing/schemas.js +1 -0
  86. package/dist/modules/pricing/service.d.ts.map +1 -1
  87. package/dist/modules/pricing/service.js +6 -1
  88. package/dist/modules/search/adapter.d.ts +2 -0
  89. package/dist/modules/search/adapter.d.ts.map +1 -1
  90. package/dist/modules/search/module.d.ts.map +1 -1
  91. package/dist/modules/search/module.js +2 -0
  92. package/dist/modules/search/service.d.ts +4 -0
  93. package/dist/modules/search/service.d.ts.map +1 -1
  94. package/dist/modules/search/service.js +74 -5
  95. package/dist/runtime/kernel-modules.d.ts +73 -0
  96. package/dist/runtime/kernel-modules.d.ts.map +1 -1
  97. package/dist/utils/id.d.ts +1 -0
  98. package/dist/utils/id.d.ts.map +1 -1
  99. package/dist/utils/id.js +8 -0
  100. package/package.json +1 -1
  101. package/src/config/types.ts +3 -0
  102. package/src/hooks/checkout.ts +4 -0
  103. package/src/index.ts +14 -0
  104. package/src/interfaces/rest/index.ts +4 -0
  105. package/src/interfaces/rest/routes/admin/custom-field-proposals.ts +37 -0
  106. package/src/interfaces/rest/routes/admin/entity-field-definitions.ts +89 -0
  107. package/src/interfaces/rest/routes/catalog.ts +85 -0
  108. package/src/interfaces/rest/routes/checkout.ts +7 -1
  109. package/src/interfaces/rest/routes/payments.ts +55 -35
  110. package/src/interfaces/rest/routes/search.ts +16 -0
  111. package/src/interfaces/rest/schemas/admin-custom-field-proposals.ts +29 -0
  112. package/src/interfaces/rest/schemas/admin-entity-field-definitions.ts +120 -0
  113. package/src/interfaces/rest/schemas/catalog.ts +92 -0
  114. package/src/interfaces/rest/schemas/search.ts +2 -0
  115. package/src/kernel/error-mapper.ts +3 -0
  116. package/src/modules/catalog/entity-service.ts +73 -20
  117. package/src/modules/catalog/module.ts +15 -0
  118. package/src/modules/catalog/ownership.ts +17 -0
  119. package/src/modules/catalog/repository/index.ts +547 -1
  120. package/src/modules/catalog/revision.ts +35 -0
  121. package/src/modules/catalog/schema.ts +169 -1
  122. package/src/modules/catalog/schemas.ts +2 -0
  123. package/src/modules/catalog/service.ts +738 -13
  124. package/src/modules/channels/adapter.ts +107 -1
  125. package/src/modules/media/module.ts +2 -0
  126. package/src/modules/media/schema.ts +23 -2
  127. package/src/modules/media/service.ts +84 -23
  128. package/src/modules/orders/service.ts +3 -0
  129. package/src/modules/pricing/schema.ts +1 -0
  130. package/src/modules/pricing/schemas.ts +1 -0
  131. package/src/modules/pricing/service.ts +7 -2
  132. package/src/modules/search/adapter.ts +2 -0
  133. package/src/modules/search/module.ts +2 -0
  134. package/src/modules/search/service.ts +87 -6
  135. package/src/utils/id.ts +11 -0
  136. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -1,22 +1,358 @@
1
+ import { resolveOrgId } from "../../auth/org.js";
2
+ import { assertPermission } from "../../auth/permissions.js";
3
+ import { Err, Ok } from "../../kernel/result.js";
4
+ import { CommerceConflictError, CommerceNotFoundError, CommerceValidationError, toCommerceError } from "../../kernel/errors.js";
5
+ import { createTxContext } from "../../kernel/database/tx-context.js";
6
+ import { isValidFieldPath, validateFieldPath } from "./ownership.js";
7
+ import { comparableSerialize } from "./revision.js";
1
8
  import { EntityService } from "./entity-service.js";
2
9
  import { CategoryService } from "./category-service.js";
3
10
  import { BrandService } from "./brand-service.js";
11
+ function isUniqueViolation(error) {
12
+ if (error == null || typeof error !== "object")
13
+ return false;
14
+ const value = error;
15
+ if (value.code === "23505")
16
+ return true;
17
+ return isUniqueViolation(value.cause);
18
+ }
4
19
  export class CatalogServiceImpl {
5
20
  repository;
21
+ database;
22
+ config;
6
23
  entities;
7
24
  categories;
8
25
  brands;
9
26
  constructor(deps) {
10
27
  this.repository = deps.repository;
11
- this.entities = new EntityService(deps);
28
+ this.database = deps.database;
29
+ this.config = deps.config;
30
+ this.entities = new EntityService(deps, this.resolveEntityFieldDefinitions.bind(this));
12
31
  this.categories = new CategoryService(deps);
13
32
  this.brands = new BrandService(deps);
14
33
  }
34
+ codeFieldDefinition(entityType, name) {
35
+ return this.config.entities?.[entityType]?.fields.find((field) => field.name === name);
36
+ }
37
+ runtimeFieldDefinition(row) {
38
+ return {
39
+ name: row.name,
40
+ type: row.type,
41
+ ...(row.unit != null ? { unit: row.unit } : {}),
42
+ ...(row.options != null ? { options: row.options } : {}),
43
+ ...(row.target != null ? { target: row.target } : {}),
44
+ filterable: row.filterable,
45
+ localized: row.localized,
46
+ sortOrder: row.sortOrder,
47
+ };
48
+ }
49
+ async resolveEntityFieldDefinitions(entityType, actorOrOrg, ctx) {
50
+ const orgId = typeof actorOrOrg === "string"
51
+ ? actorOrOrg
52
+ : resolveOrgId(actorOrOrg ?? ctx?.actor ?? null);
53
+ const codeFields = this.config.entities?.[entityType]?.fields ?? [];
54
+ const merged = new Map(codeFields.map((field) => [field.name, { ...field }]));
55
+ const runtimeFields = await this.repository.findActiveEntityFieldDefinitions(orgId, entityType, ctx);
56
+ for (const row of runtimeFields) {
57
+ const codeField = merged.get(row.name);
58
+ if (!codeField) {
59
+ merged.set(row.name, this.runtimeFieldDefinition(row));
60
+ continue;
61
+ }
62
+ merged.set(row.name, {
63
+ ...codeField,
64
+ ...(row.options != null ? { options: row.options } : {}),
65
+ filterable: row.filterable,
66
+ localized: row.localized,
67
+ sortOrder: row.sortOrder,
68
+ });
69
+ }
70
+ return [...merged.values()].sort((first, second) => (first.sortOrder ?? 0) - (second.sortOrder ?? 0));
71
+ }
72
+ listEntityFieldDefinitions(actor, entityType, ctx) {
73
+ const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
74
+ return this.withMutationResult(actor ?? ctx?.actor ?? null, ctx, async (txCtx) => Ok(await this.repository.findEntityFieldDefinitions(orgId, entityType, txCtx)));
75
+ }
76
+ createEntityFieldDefinition(input, actor, ctx) {
77
+ if (input.entityType.length === 0 || input.name.length === 0) {
78
+ return Promise.resolve(Err(new CommerceValidationError("Entity type and field name are required.")));
79
+ }
80
+ assertPermission(actor, "catalog:update");
81
+ const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
82
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
83
+ const codeField = this.codeFieldDefinition(input.entityType, input.name);
84
+ if (codeField && input.type !== codeField.type) {
85
+ return Err(new CommerceValidationError("Code-defined fields only allow options, filterable, localized, and sortOrder overrides."));
86
+ }
87
+ return Ok(await this.repository.createEntityFieldDefinition({
88
+ organizationId: orgId,
89
+ entityType: input.entityType,
90
+ name: input.name,
91
+ type: input.type,
92
+ // A shadow row over a code field inherits the code values for anything
93
+ // omitted, so creating one never silently flips a code default.
94
+ ...(codeField?.unit !== undefined || input.unit !== undefined
95
+ ? { unit: codeField ? codeField.unit ?? null : input.unit }
96
+ : {}),
97
+ ...(codeField?.target !== undefined || input.target !== undefined
98
+ ? { target: codeField ? codeField.target ?? null : input.target }
99
+ : {}),
100
+ ...(input.options !== undefined
101
+ ? { options: input.options }
102
+ : codeField?.options !== undefined ? { options: codeField.options } : {}),
103
+ ...(input.filterable !== undefined
104
+ ? { filterable: input.filterable }
105
+ : codeField?.filterable !== undefined ? { filterable: codeField.filterable } : {}),
106
+ ...(input.localized !== undefined ? { localized: input.localized } : {}),
107
+ ...(input.sortOrder !== undefined ? { sortOrder: input.sortOrder } : {}),
108
+ }, txCtx));
109
+ });
110
+ }
111
+ updateEntityFieldDefinition(id, input, actor, ctx) {
112
+ assertPermission(actor, "catalog:update");
113
+ const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
114
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
115
+ const existing = await this.repository.findEntityFieldDefinitionById(orgId, id, txCtx);
116
+ if (!existing)
117
+ return Err(new CommerceNotFoundError("Entity field definition not found."));
118
+ const codeField = this.codeFieldDefinition(existing.entityType, existing.name);
119
+ if (codeField && (input.entityType !== undefined || input.name !== undefined || input.type !== undefined || input.unit !== undefined || input.target !== undefined)) {
120
+ return Err(new CommerceValidationError("Code-defined fields only allow options, filterable, localized, and sortOrder updates."));
121
+ }
122
+ const data = {
123
+ ...(input.entityType !== undefined ? { entityType: input.entityType } : {}),
124
+ ...(input.name !== undefined ? { name: input.name } : {}),
125
+ ...(input.type !== undefined ? { type: input.type } : {}),
126
+ ...(input.unit !== undefined ? { unit: input.unit } : {}),
127
+ ...(input.options !== undefined ? { options: input.options } : {}),
128
+ ...(input.target !== undefined ? { target: input.target } : {}),
129
+ ...(input.filterable !== undefined ? { filterable: input.filterable } : {}),
130
+ ...(input.localized !== undefined ? { localized: input.localized } : {}),
131
+ ...(input.sortOrder !== undefined ? { sortOrder: input.sortOrder } : {}),
132
+ };
133
+ const updated = await this.repository.updateEntityFieldDefinition(orgId, id, data, txCtx);
134
+ if (!updated)
135
+ return Err(new CommerceNotFoundError("Entity field definition not found."));
136
+ return Ok(updated);
137
+ });
138
+ }
139
+ archiveEntityFieldDefinition(id, actor, ctx) {
140
+ assertPermission(actor, "catalog:update");
141
+ const orgId = resolveOrgId(actor ?? ctx?.actor ?? null);
142
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
143
+ const existing = await this.repository.findEntityFieldDefinitionById(orgId, id, txCtx);
144
+ if (!existing)
145
+ return Err(new CommerceNotFoundError("Entity field definition not found."));
146
+ if (this.codeFieldDefinition(existing.entityType, existing.name)) {
147
+ return Err(new CommerceValidationError("Code-defined fields cannot be archived."));
148
+ }
149
+ if (existing.status === "archived")
150
+ return Ok(existing);
151
+ const updated = await this.repository.updateEntityFieldDefinition(orgId, id, { status: "archived" }, txCtx);
152
+ if (!updated)
153
+ return Err(new CommerceNotFoundError("Entity field definition not found."));
154
+ return Ok(updated);
155
+ });
156
+ }
157
+ async withMutation(actor, ctx, fn) {
158
+ if (ctx?.tx != null)
159
+ return fn(ctx);
160
+ for (let attempt = 0; attempt < 3; attempt += 1) {
161
+ try {
162
+ return await this.database.transaction(async (tx) => fn(createTxContext(tx, { actor })));
163
+ }
164
+ catch (error) {
165
+ if (!isUniqueViolation(error) || attempt === 2)
166
+ throw error;
167
+ }
168
+ }
169
+ throw new Error("Catalog mutation retry limit reached.");
170
+ }
171
+ async withMutationResult(actor, ctx, fn) {
172
+ try {
173
+ return await this.withMutation(actor, ctx, fn);
174
+ }
175
+ catch (error) {
176
+ if (isUniqueViolation(error))
177
+ return Err(new CommerceConflictError("A resource with those values already exists."));
178
+ return Err(toCommerceError(error));
179
+ }
180
+ }
181
+ async captureRevision(entityId, actor, reason, ctx, force = false) {
182
+ const snapshot = await this.repository.snapshotEntity(entityId, ctx);
183
+ const latest = await this.repository.findLatestRevision(entityId, ctx);
184
+ if (!(force || reason === "push") && latest && comparableSerialize(latest.snapshot) === comparableSerialize(snapshot))
185
+ return latest;
186
+ const revisionActor = actor ?? ctx.actor;
187
+ const organizationId = typeof snapshot.entity.organizationId === "string"
188
+ ? snapshot.entity.organizationId
189
+ : resolveOrgId(revisionActor);
190
+ return this.repository.createRevision({
191
+ organizationId,
192
+ entityId,
193
+ snapshot,
194
+ reason,
195
+ actorId: revisionActor?.userId ?? null,
196
+ actorType: revisionActor?.type ?? null,
197
+ requestId: ctx.requestId,
198
+ }, ctx);
199
+ }
200
+ async recordEntityRevision(entityId, actor, reason = "update", ctx) {
201
+ try {
202
+ return await this.withMutation(actor, ctx, async (txCtx) => {
203
+ const revisionActor = actor ?? txCtx.actor;
204
+ assertPermission(revisionActor, "catalog:update");
205
+ const entity = await this.repository.findEntityById(entityId, txCtx);
206
+ if (!entity)
207
+ return Err(new CommerceNotFoundError("Entity not found."));
208
+ if (entity.organizationId !== resolveOrgId(revisionActor)) {
209
+ return Err(new CommerceNotFoundError("Entity not found."));
210
+ }
211
+ return Ok(await this.captureRevision(entityId, revisionActor, reason, txCtx));
212
+ });
213
+ }
214
+ catch (error) {
215
+ return Err(toCommerceError(error));
216
+ }
217
+ }
218
+ restoreDate(value) {
219
+ if (value == null)
220
+ return null;
221
+ return value instanceof Date ? value : new Date(String(value));
222
+ }
223
+ async applyRevisionSnapshot(entityId, snapshot, ctx) {
224
+ const entity = snapshot.entity;
225
+ const entityData = {
226
+ sourceStoreId: entity.sourceStoreId,
227
+ type: entity.type,
228
+ slug: entity.slug,
229
+ status: entity.status,
230
+ isVisible: entity.isVisible,
231
+ taxClass: entity.taxClass,
232
+ metadata: entity.metadata,
233
+ publishedAt: this.restoreDate(snapshot.entity.publishedAt),
234
+ };
235
+ await this.repository.updateEntity(entityId, entityData, ctx);
236
+ await this.repository.deleteAttributesByEntityId(entityId, ctx);
237
+ for (const row of snapshot.attributes) {
238
+ await this.repository.createAttribute({
239
+ id: row.id,
240
+ entityId,
241
+ locale: row.locale,
242
+ title: row.title,
243
+ subtitle: row.subtitle,
244
+ description: row.description,
245
+ richDescription: row.richDescription,
246
+ seoTitle: row.seoTitle,
247
+ seoDescription: row.seoDescription,
248
+ }, ctx);
249
+ }
250
+ await this.repository.deleteCustomFieldsByEntityId(entityId, ctx);
251
+ for (const row of snapshot.customFields) {
252
+ await this.repository.createCustomField({
253
+ id: row.id,
254
+ entityId,
255
+ fieldName: row.fieldName,
256
+ fieldType: row.fieldType,
257
+ source: row.source,
258
+ status: row.status,
259
+ confidence: row.confidence,
260
+ evidence: row.evidence,
261
+ locale: row.locale,
262
+ approvedAt: this.restoreDate(row.approvedAt),
263
+ approvedBy: row.approvedBy,
264
+ textValue: row.textValue,
265
+ numberValue: row.numberValue,
266
+ booleanValue: row.booleanValue,
267
+ dateValue: this.restoreDate(row.dateValue),
268
+ jsonValue: row.jsonValue,
269
+ createdAt: this.restoreDate(row.createdAt) ?? new Date(),
270
+ updatedAt: this.restoreDate(row.updatedAt) ?? new Date(),
271
+ }, ctx);
272
+ }
273
+ await this.repository.deleteEntityCategoriesByEntityId(entityId, ctx);
274
+ for (const row of snapshot.categories) {
275
+ await this.repository.addEntityToCategory(entityId, row.categoryId, row.sortOrder, ctx);
276
+ }
277
+ await this.repository.deleteEntityBrandsByEntityId(entityId, ctx);
278
+ for (const row of snapshot.brands) {
279
+ await this.repository.addEntityToBrand(entityId, row.brandId, row.sortOrder, ctx);
280
+ }
281
+ // Snapshots written before tags existed carry no key; restoring one must
282
+ // not delete tag links the snapshot never saw.
283
+ if (snapshot.tags) {
284
+ await this.repository.deleteEntityTagsByEntityId(entityId, ctx);
285
+ for (const row of snapshot.tags) {
286
+ await this.repository.addEntityTag(entityId, row.tagId, ctx);
287
+ }
288
+ }
289
+ await this.repository.deleteEntityMediaByEntityId(entityId, ctx);
290
+ for (const row of snapshot.media) {
291
+ await this.repository.createEntityMedia({
292
+ entityId,
293
+ mediaAssetId: row.mediaAssetId,
294
+ role: row.role,
295
+ sortOrder: row.sortOrder,
296
+ variantId: row.variantId,
297
+ }, ctx);
298
+ }
299
+ }
300
+ async restoreEntityRevision(entityId, revisionId, actor, ctx) {
301
+ try {
302
+ return await this.withMutation(actor, ctx, async (txCtx) => {
303
+ const revisionActor = actor ?? txCtx.actor;
304
+ assertPermission(revisionActor, "catalog:update");
305
+ const entity = await this.repository.findEntityById(entityId, txCtx);
306
+ if (!entity)
307
+ return Err(new CommerceNotFoundError("Entity not found."));
308
+ if (entity.organizationId !== resolveOrgId(revisionActor)) {
309
+ return Err(new CommerceNotFoundError("Entity not found."));
310
+ }
311
+ if (entity.sourceStoreId != null)
312
+ assertPermission(revisionActor, "catalog:sync");
313
+ const revision = await this.repository.findRevisionById(entityId, revisionId, txCtx);
314
+ if (!revision)
315
+ return Err(new CommerceNotFoundError("Revision not found."));
316
+ await this.applyRevisionSnapshot(entityId, revision.snapshot, txCtx);
317
+ const restored = await this.entities.getById(entityId, { includeAttributes: true, includeCategories: true, includeBrands: true, includeMedia: true }, revisionActor, txCtx);
318
+ if (!restored.ok)
319
+ return restored;
320
+ await this.captureRevision(entityId, revisionActor, "restore", txCtx, true);
321
+ return restored;
322
+ });
323
+ }
324
+ catch (error) {
325
+ return Err(toCommerceError(error));
326
+ }
327
+ }
328
+ async trimEntityRevisions(actor, olderThanDays = 90, ctx) {
329
+ try {
330
+ return await this.withMutation(actor, ctx, async (txCtx) => {
331
+ const revisionActor = actor ?? txCtx.actor;
332
+ assertPermission(revisionActor, "catalog:update");
333
+ const cutoff = new Date(Date.now() - olderThanDays * 24 * 60 * 60 * 1000);
334
+ return Ok(await this.repository.deleteRevisionsOlderThan(resolveOrgId(revisionActor), cutoff, txCtx));
335
+ });
336
+ }
337
+ catch (error) {
338
+ return Err(toCommerceError(error));
339
+ }
340
+ }
15
341
  create(input, actor, ctx) {
16
- return this.entities.create(input, actor, ctx);
342
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
343
+ const result = await this.entities.create(input, actor, txCtx);
344
+ if (result.ok)
345
+ await this.captureRevision(result.value.id, actor, "create", txCtx);
346
+ return result;
347
+ });
17
348
  }
18
349
  update(id, input, actor, ctx) {
19
- return this.entities.update(id, input, actor, ctx);
350
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
351
+ const result = await this.entities.update(id, input, actor, txCtx);
352
+ if (result.ok)
353
+ await this.captureRevision(id, actor, "update", txCtx);
354
+ return result;
355
+ });
20
356
  }
21
357
  delete(id, actor, ctx) {
22
358
  return this.entities.delete(id, actor, ctx);
@@ -30,17 +366,162 @@ export class CatalogServiceImpl {
30
366
  list(params, actor, ctx) {
31
367
  return this.entities.list(params, actor, ctx);
32
368
  }
369
+ async resolveFieldOwner(entityId, fieldPath, storeId, ctx, variantId) {
370
+ if (!isValidFieldPath(fieldPath))
371
+ return undefined;
372
+ const rows = await this.repository.findFieldOwnershipForResolution(entityId, storeId, variantId ?? null, ctx);
373
+ let selected;
374
+ let selectedPriority = -1;
375
+ for (const row of rows) {
376
+ if (row.fieldPath !== fieldPath)
377
+ continue;
378
+ const priority = (row.variantId === variantId && variantId != null ? 2 : 0)
379
+ + (row.storeId === storeId ? 1 : 0);
380
+ if (priority > selectedPriority) {
381
+ selected = row;
382
+ selectedPriority = priority;
383
+ }
384
+ }
385
+ return selected?.owner;
386
+ }
387
+ async resolveFieldOwners(entityId, storeId, ctx) {
388
+ const rows = await this.repository.findFieldOwnershipForResolution(entityId, storeId, null, ctx);
389
+ const resolved = new Map();
390
+ for (const row of rows) {
391
+ const priority = row.storeId === storeId ? 1 : 0;
392
+ const current = resolved.get(row.fieldPath);
393
+ if (!current || priority > current.priority) {
394
+ resolved.set(row.fieldPath, { owner: row.owner, priority });
395
+ }
396
+ }
397
+ return new Map([...resolved].map(([fieldPath, value]) => [fieldPath, value.owner]));
398
+ }
399
+ setFieldOwner(entityId, fieldPath, storeId, owner, actor, ctx, variantId) {
400
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
401
+ const setter = actor ?? txCtx.actor;
402
+ assertPermission(setter, "catalog:update");
403
+ validateFieldPath(fieldPath);
404
+ const entity = await this.repository.findEntityById(entityId, txCtx);
405
+ if (!entity)
406
+ return Err(new CommerceNotFoundError("Entity not found."));
407
+ if (entity.organizationId !== resolveOrgId(setter)) {
408
+ return Err(new CommerceNotFoundError("Entity not found."));
409
+ }
410
+ if (entity.sourceStoreId != null)
411
+ assertPermission(setter, "catalog:sync");
412
+ await this.repository.upsertFieldOwnership({
413
+ organizationId: entity.organizationId,
414
+ entityId,
415
+ ...(variantId != null ? { variantId } : {}),
416
+ ...(storeId != null ? { storeId } : {}),
417
+ fieldPath,
418
+ owner,
419
+ }, txCtx);
420
+ return Ok(undefined);
421
+ });
422
+ }
423
+ listFieldOwnership(entityId, actor, ctx, storeId) {
424
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
425
+ const reader = actor ?? txCtx.actor;
426
+ assertPermission(reader, "catalog:read");
427
+ const entity = await this.repository.findEntityById(entityId, txCtx);
428
+ if (!entity)
429
+ return Err(new CommerceNotFoundError("Entity not found."));
430
+ if (entity.organizationId !== resolveOrgId(reader)) {
431
+ return Err(new CommerceNotFoundError("Entity not found."));
432
+ }
433
+ return Ok(await this.repository.findFieldOwnership(entityId, txCtx, storeId));
434
+ });
435
+ }
436
+ seedImportedFieldOwnership(entityId, storeId, fieldPaths, ctx) {
437
+ return this.withMutationResult(null, ctx, async (txCtx) => {
438
+ const entity = await this.repository.findEntityById(entityId, txCtx);
439
+ if (!entity)
440
+ return Err(new CommerceNotFoundError("Entity not found."));
441
+ const rows = fieldPaths.map((fieldPath) => ({
442
+ organizationId: entity.organizationId,
443
+ entityId,
444
+ storeId,
445
+ fieldPath: validateFieldPath(fieldPath),
446
+ owner: "store",
447
+ }));
448
+ await this.repository.seedFieldOwnership(rows, txCtx);
449
+ return Ok(undefined);
450
+ });
451
+ }
33
452
  publish(id, actor, ctx) {
34
- return this.entities.publish(id, actor, ctx);
453
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
454
+ const result = await this.entities.publish(id, actor, txCtx);
455
+ if (result.ok)
456
+ await this.captureRevision(id, actor, "update", txCtx);
457
+ return result;
458
+ });
35
459
  }
36
460
  archive(id, actor, ctx) {
37
- return this.entities.archive(id, actor, ctx);
461
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
462
+ const result = await this.entities.archive(id, actor, txCtx);
463
+ if (result.ok)
464
+ await this.captureRevision(id, actor, "update", txCtx);
465
+ return result;
466
+ });
38
467
  }
39
468
  discontinue(id, actor, ctx) {
40
- return this.entities.discontinue(id, actor, ctx);
469
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
470
+ const result = await this.entities.discontinue(id, actor, txCtx);
471
+ if (result.ok)
472
+ await this.captureRevision(id, actor, "update", txCtx);
473
+ return result;
474
+ });
41
475
  }
42
476
  setAttributes(entityId, locale, attrs, actor, ctx) {
43
- return this.entities.setAttributes(entityId, locale, attrs, actor, ctx);
477
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
478
+ const result = await this.entities.setAttributes(entityId, locale, attrs, actor, txCtx);
479
+ if (result.ok)
480
+ await this.captureRevision(entityId, actor, "update", txCtx);
481
+ return result;
482
+ });
483
+ }
484
+ reviewCustomField(status, entityId, fieldName, locale, actor, ctx) {
485
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
486
+ const reviewer = actor ?? txCtx.actor;
487
+ assertPermission(reviewer, "catalog:update");
488
+ const entity = await this.repository.findEntityById(entityId, txCtx);
489
+ if (!entity)
490
+ return Err(new CommerceNotFoundError("Entity not found."));
491
+ if (entity.organizationId !== resolveOrgId(reviewer)) {
492
+ return Err(new CommerceNotFoundError("Entity not found."));
493
+ }
494
+ if (entity.sourceStoreId != null)
495
+ assertPermission(reviewer, "catalog:sync");
496
+ const proposal = await this.repository.findProposedCustomField(entityId, fieldName, locale, txCtx);
497
+ if (!proposal)
498
+ return Err(new CommerceNotFoundError("Custom field proposal not found."));
499
+ if (status === "approved") {
500
+ await this.repository.deleteCustomField(entityId, fieldName, locale, txCtx);
501
+ }
502
+ const updated = await this.repository.updateProposedCustomField(proposal.id, {
503
+ status,
504
+ ...(status === "approved"
505
+ ? { approvedAt: new Date(), approvedBy: reviewer?.userId ?? null }
506
+ : {}),
507
+ }, txCtx);
508
+ // Throw, never return Err, past this point: the approved-row delete above
509
+ // must roll back when the proposal was already resolved by a concurrent
510
+ // reviewer, or the live value is lost with no replacement.
511
+ if (!updated)
512
+ throw new CommerceNotFoundError("Custom field proposal not found.");
513
+ if (status === "approved") {
514
+ await this.repository.rejectOtherProposedCustomFields(entityId, fieldName, locale, updated.id, txCtx);
515
+ }
516
+ await this.captureRevision(entityId, reviewer, "update", txCtx);
517
+ return Ok(updated);
518
+ });
519
+ }
520
+ approveCustomField(entityId, fieldName, locale, actor, ctx) {
521
+ return this.reviewCustomField("approved", entityId, fieldName, locale, actor, ctx);
522
+ }
523
+ rejectCustomField(entityId, fieldName, locale, actor, ctx) {
524
+ return this.reviewCustomField("rejected", entityId, fieldName, locale, actor, ctx);
44
525
  }
45
526
  getAttributes(entityId, locale, ctx) {
46
527
  return this.entities.getAttributes(entityId, locale, ctx);
@@ -64,10 +545,20 @@ export class CatalogServiceImpl {
64
545
  return this.categories.deleteCategory(id, actor, ctx);
65
546
  }
66
547
  addToCategory(entityId, categoryId, actor, ctx) {
67
- return this.categories.addToCategory(entityId, categoryId, actor, ctx);
548
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
549
+ const result = await this.categories.addToCategory(entityId, categoryId, actor, txCtx);
550
+ if (result.ok)
551
+ await this.captureRevision(entityId, actor, "update", txCtx);
552
+ return result;
553
+ });
68
554
  }
69
555
  removeFromCategory(entityId, categoryId, actor, ctx) {
70
- return this.categories.removeFromCategory(entityId, categoryId, actor, ctx);
556
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
557
+ const result = await this.categories.removeFromCategory(entityId, categoryId, actor, txCtx);
558
+ if (result.ok)
559
+ await this.captureRevision(entityId, actor, "update", txCtx);
560
+ return result;
561
+ });
71
562
  }
72
563
  listBrands(ctx) {
73
564
  return this.brands.listBrands(ctx);
@@ -82,10 +573,20 @@ export class CatalogServiceImpl {
82
573
  return this.brands.deleteBrand(id, actor, ctx);
83
574
  }
84
575
  addToBrand(entityId, brandId, actor, ctx) {
85
- return this.brands.addToBrand(entityId, brandId, actor, ctx);
576
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
577
+ const result = await this.brands.addToBrand(entityId, brandId, actor, txCtx);
578
+ if (result.ok)
579
+ await this.captureRevision(entityId, actor, "update", txCtx);
580
+ return result;
581
+ });
86
582
  }
87
583
  removeFromBrand(entityId, brandId, actor, ctx) {
88
- return this.brands.removeFromBrand(entityId, brandId, actor, ctx);
584
+ return this.withMutationResult(actor, ctx, async (txCtx) => {
585
+ const result = await this.brands.removeFromBrand(entityId, brandId, actor, txCtx);
586
+ if (result.ok)
587
+ await this.captureRevision(entityId, actor, "update", txCtx);
588
+ return result;
589
+ });
89
590
  }
90
591
  createOptionType(input, actor, ctx) {
91
592
  return this.entities.createOptionType(input, actor, ctx);