@open-mercato/core 0.10.1-develop.7994.1.c9f31972aa → 0.10.1-develop.8022.1.b6753de892

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 (76) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/audit_logs/components/AuditLogsActions.js +80 -50
  3. package/dist/modules/audit_logs/components/AuditLogsActions.js.map +3 -3
  4. package/dist/modules/audit_logs/lib/rowPresentation.js +82 -0
  5. package/dist/modules/audit_logs/lib/rowPresentation.js.map +7 -0
  6. package/dist/modules/catalog/commands/variants.js +89 -16
  7. package/dist/modules/catalog/commands/variants.js.map +2 -2
  8. package/dist/modules/catalog/seed/examples.js +7 -0
  9. package/dist/modules/catalog/seed/examples.js.map +2 -2
  10. package/dist/modules/customers/api/interactions/route.js +2 -2
  11. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  12. package/dist/modules/customers/components/detail/AssignRoleDialog.js +10 -21
  13. package/dist/modules/customers/components/detail/AssignRoleDialog.js.map +2 -2
  14. package/dist/modules/customers/migrations/Migration20260825140000_customers.js +17 -10
  15. package/dist/modules/customers/migrations/Migration20260825140000_customers.js.map +2 -2
  16. package/dist/modules/entities/cli.js +138 -66
  17. package/dist/modules/entities/cli.js.map +3 -3
  18. package/dist/modules/integrations/lib/state-service.js +1 -1
  19. package/dist/modules/integrations/lib/state-service.js.map +2 -2
  20. package/dist/modules/promotions/commands/codes.js +18 -3
  21. package/dist/modules/promotions/commands/codes.js.map +2 -2
  22. package/dist/modules/query_index/cli.js +17 -1
  23. package/dist/modules/query_index/cli.js.map +2 -2
  24. package/dist/modules/query_index/lib/reindexer.js +23 -5
  25. package/dist/modules/query_index/lib/reindexer.js.map +2 -2
  26. package/dist/modules/resources/commands/resource-types.js +42 -15
  27. package/dist/modules/resources/commands/resource-types.js.map +2 -2
  28. package/dist/modules/resources/commands/resources.js +54 -3
  29. package/dist/modules/resources/commands/resources.js.map +2 -2
  30. package/dist/modules/resources/lib/resourceTypeLock.js +15 -0
  31. package/dist/modules/resources/lib/resourceTypeLock.js.map +7 -0
  32. package/dist/modules/sales/commands/configuration.js +30 -16
  33. package/dist/modules/sales/commands/configuration.js.map +2 -2
  34. package/dist/modules/sales/components/documents/AddressesSection.js +36 -15
  35. package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
  36. package/dist/modules/sales/seed/examples.js +35 -6
  37. package/dist/modules/sales/seed/examples.js.map +2 -2
  38. package/package.json +7 -7
  39. package/src/modules/audit_logs/components/AuditLogsActions.tsx +85 -48
  40. package/src/modules/audit_logs/i18n/de.json +16 -0
  41. package/src/modules/audit_logs/i18n/en.json +16 -0
  42. package/src/modules/audit_logs/i18n/es.json +16 -0
  43. package/src/modules/audit_logs/i18n/ko.json +16 -0
  44. package/src/modules/audit_logs/i18n/pl.json +16 -0
  45. package/src/modules/audit_logs/lib/rowPresentation.ts +92 -0
  46. package/src/modules/catalog/commands/variants.ts +96 -17
  47. package/src/modules/catalog/seed/examples.ts +7 -0
  48. package/src/modules/customers/api/interactions/route.ts +2 -2
  49. package/src/modules/customers/components/detail/AssignRoleDialog.tsx +9 -12
  50. package/src/modules/customers/i18n/de.json +2 -1
  51. package/src/modules/customers/i18n/en.json +2 -1
  52. package/src/modules/customers/i18n/es.json +2 -1
  53. package/src/modules/customers/i18n/ko.json +2 -1
  54. package/src/modules/customers/i18n/pl.json +2 -1
  55. package/src/modules/customers/migrations/Migration20260825140000_customers.ts +21 -10
  56. package/src/modules/entities/cli.ts +144 -65
  57. package/src/modules/integrations/lib/state-service.ts +1 -1
  58. package/src/modules/promotions/commands/codes.ts +19 -4
  59. package/src/modules/query_index/cli.ts +17 -1
  60. package/src/modules/query_index/lib/reindexer.ts +55 -6
  61. package/src/modules/resources/commands/resource-types.ts +47 -15
  62. package/src/modules/resources/commands/resources.ts +74 -3
  63. package/src/modules/resources/i18n/de.json +3 -0
  64. package/src/modules/resources/i18n/en.json +3 -0
  65. package/src/modules/resources/i18n/es.json +3 -0
  66. package/src/modules/resources/i18n/ko.json +3 -0
  67. package/src/modules/resources/i18n/pl.json +3 -0
  68. package/src/modules/resources/lib/resourceTypeLock.ts +14 -0
  69. package/src/modules/sales/commands/configuration.ts +35 -16
  70. package/src/modules/sales/components/documents/AddressesSection.tsx +51 -20
  71. package/src/modules/sales/i18n/de.json +3 -0
  72. package/src/modules/sales/i18n/en.json +3 -0
  73. package/src/modules/sales/i18n/es.json +3 -0
  74. package/src/modules/sales/i18n/ko.json +3 -0
  75. package/src/modules/sales/i18n/pl.json +4 -1
  76. package/src/modules/sales/seed/examples.ts +41 -6
@@ -187,6 +187,56 @@ function reportColumnProbeFailure(error: unknown, tableName: string): void {
187
187
  }
188
188
  }
189
189
 
190
+ type ReindexSourceMetadata = ReturnType<typeof resolveQueryIndexSourceTableMetadata>
191
+
192
+ function writesGlobalReindexProjection(
193
+ entityType: string,
194
+ columns: Set<string>,
195
+ source: ReindexSourceMetadata,
196
+ ): boolean {
197
+ return columns.has('id')
198
+ && !columns.has('tenant_id')
199
+ && !columns.has('organization_id')
200
+ && !source?.tenantColumn
201
+ && !source?.organizationColumn
202
+ && isTenantGlobalEntityType(entityType)
203
+ }
204
+
205
+ function resolveTenantlessRefusal(
206
+ entityType: string,
207
+ columns: Set<string>,
208
+ source: ReindexSourceMetadata,
209
+ ): Exclude<ReindexRefusalReason, 'column-probe-failed'> | null {
210
+ if (columns.has('tenant_id')) return null
211
+ if (writesGlobalReindexProjection(entityType, columns, source)) return null
212
+ return isTenantGlobalEntityType(entityType) ? 'declared-global-but-org-scoped' : 'no-tenant-column'
213
+ }
214
+
215
+ /**
216
+ * Answers, without logging, whether a tenant-scoped sweep of `entityType` would be refused
217
+ * because its source table has no `tenant_id` column and the type is not a declared
218
+ * tenant-global catalogue. Callers that enumerate every registered entity type for one
219
+ * tenant (e.g. `mercato query_index reindex --tenant <id>` during `mercato init`) use it to
220
+ * leave such types out up front, so the guard inside `reindexEntity()` keeps warning only
221
+ * for callers that genuinely aimed a tenant-scoped sweep at a tenant-less table.
222
+ *
223
+ * Deliberately narrow: an unregistered type, a failed column probe, or a tenant-global
224
+ * declaration that cannot be honoured all return `false`, so those still reach the guard
225
+ * and surface their own diagnostics.
226
+ */
227
+ export async function isTenantlessReindexTarget(
228
+ em: EntityManager,
229
+ entityType: string,
230
+ ): Promise<boolean> {
231
+ if (!entityType) return false
232
+ const source = resolveQueryIndexSourceTableMetadata(em, entityType)
233
+ if (!source?.table) return false
234
+ const db = em.getKysely<Record<string, Record<string, unknown>>>()
235
+ const columns = await getColumnSet(db, source.tableName ?? source.table, source.schema)
236
+ if (columns === null) return false
237
+ return resolveTenantlessRefusal(entityType, columns, source) === 'no-tenant-column'
238
+ }
239
+
190
240
  export async function reindexEntity(
191
241
  em: EntityManager,
192
242
  options: ReindexJobOptions,
@@ -306,8 +356,7 @@ export async function reindexEntity(
306
356
  // Only the PROJECTION scope moves. `jobScope` keeps the caller's tenant and organization:
307
357
  // it records who ran the sweep, so two tenants reindexing the catalogue remain two jobs
308
358
  // rather than one that blocks the other behind the active-job guard.
309
- const writesGlobalProjection =
310
- columns.has('id') && !hasTenantCol && !hasOrgCol && !source?.tenantColumn && !source?.organizationColumn && isTenantGlobalEntityType(entityType)
359
+ const writesGlobalProjection = writesGlobalReindexProjection(entityType, columns, source)
311
360
  const projectionTenantId = writesGlobalProjection ? null : tenantId
312
361
  const projectionOrganizationId = writesGlobalProjection ? null : organizationId
313
362
  // Vector work keeps the caller's scope even where the projection moves. Its consumers -
@@ -324,10 +373,10 @@ export async function reindexEntity(
324
373
  // through would silently drop the tenant predicate and stamp the caller's tenant - the
325
374
  // exact defect the guard exists for - while the author believes the declaration took
326
375
  // effect. Fail closed and name it, in the spirit of the allowlist itself.
327
- if (!hasTenantCol && tenantId != null && !writesGlobalProjection) {
328
- const declaredButOrgScoped = isTenantGlobalEntityType(entityType)
376
+ const tenantlessRefusal = tenantId != null ? resolveTenantlessRefusal(entityType, columns, source) : null
377
+ if (tenantlessRefusal) {
329
378
  logger.warn(
330
- declaredButOrgScoped
379
+ tenantlessRefusal === 'declared-global-but-org-scoped'
331
380
  ? 'Refusing tenant-scoped reindex: entity type is declared tenant-global but its table has an organization_id column'
332
381
  : 'Refusing tenant-scoped reindex of a table with no tenant_id column',
333
382
  { entityType, table, tenantId },
@@ -337,7 +386,7 @@ export async function reindexEntity(
337
386
  total: 0,
338
387
  tenantScopes: [],
339
388
  scopes: [],
340
- refused: declaredButOrgScoped ? 'declared-global-but-org-scoped' : 'no-tenant-column',
389
+ refused: tenantlessRefusal,
341
390
  }
342
391
  }
343
392
 
@@ -6,6 +6,7 @@ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
6
6
  import { buildChanges, emitCrudSideEffects, emitCrudUndoSideEffects, parseWithCustomFields, setCustomFieldsIfAny } from '@open-mercato/shared/lib/commands/helpers'
7
7
  import { buildCustomFieldResetMap, diffCustomFieldChanges, loadCustomFieldSnapshot, type CustomFieldSnapshot } from '@open-mercato/shared/lib/commands/customFieldSnapshots'
8
8
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
9
+ import { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'
9
10
  import type { DataEngine } from '@open-mercato/shared/lib/data/engine'
10
11
  import type { CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'
11
12
  import { ResourcesResource, ResourcesResourceType } from '../data/entities'
@@ -16,6 +17,7 @@ import {
16
17
  type ResourcesResourceTypeUpdateInput,
17
18
  } from '../data/validators'
18
19
  import { resourcesResourceTypeCrudEvents } from '../lib/crud'
20
+ import { lockResourceType } from '../lib/resourceTypeLock'
19
21
  import { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'
20
22
  import { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'
21
23
  import { E } from '#generated/entities.ids.generated'
@@ -72,6 +74,25 @@ async function loadResourceTypeCustomSnapshot(em: EntityManager, snapshot: Resou
72
74
  })
73
75
  }
74
76
 
77
+ async function assertNoAssignedResources(
78
+ em: EntityManager,
79
+ resourceType: ResourcesResourceType,
80
+ status: 400 | 409,
81
+ ): Promise<void> {
82
+ const assignedCount = await em.count(ResourcesResource, {
83
+ resourceTypeId: resourceType.id,
84
+ deletedAt: null,
85
+ tenantId: resourceType.tenantId,
86
+ organizationId: resourceType.organizationId,
87
+ })
88
+ if (assignedCount === 0) return
89
+ const { translate } = await resolveTranslations()
90
+ throw new CrudHttpError(status, {
91
+ error: translate('resources.resourceTypes.errors.deleteAssigned', 'Resource type has assigned resources.'),
92
+ code: 'resources.resourceTypes.errors.deleteAssigned',
93
+ })
94
+ }
95
+
75
96
  const createResourceTypeCommand: CommandHandler<ResourcesResourceTypeCreateInput, { resourceTypeId: string }> = {
76
97
  id: 'resources.resourceTypes.create',
77
98
  async execute(rawInput, ctx) {
@@ -152,9 +173,24 @@ const createResourceTypeCommand: CommandHandler<ResourcesResourceTypeCreateInput
152
173
  const em = (ctx.container.resolve('em') as EntityManager).fork()
153
174
  const resourceType = await em.findOne(ResourcesResourceType, { id: after.id })
154
175
  if (resourceType) {
155
- resourceType.deletedAt = new Date()
156
- resourceType.updatedAt = new Date()
157
- await em.flush()
176
+ let deleted = false
177
+ await withAtomicFlush(em, [
178
+ async () => {
179
+ await lockResourceType(em, resourceType.id)
180
+ const isLive = await em.count(ResourcesResourceType, {
181
+ id: resourceType.id,
182
+ tenantId: resourceType.tenantId,
183
+ organizationId: resourceType.organizationId,
184
+ deletedAt: null,
185
+ }) > 0
186
+ if (!isLive) return
187
+ await assertNoAssignedResources(em, resourceType, 409)
188
+ resourceType.deletedAt = new Date()
189
+ resourceType.updatedAt = new Date()
190
+ deleted = true
191
+ },
192
+ ], { transaction: true })
193
+ if (!deleted) return
158
194
 
159
195
  const dataEngine = (ctx.container.resolve('dataEngine') as DataEngine)
160
196
  await emitCrudUndoSideEffects({
@@ -361,18 +397,14 @@ const deleteResourceTypeCommand: CommandHandler<{ id?: string }, { resourceTypeI
361
397
  if (!record) throw new CrudHttpError(404, { error: 'Resources resource type not found.' })
362
398
  ensureTenantScope(ctx, record.tenantId)
363
399
  ensureOrganizationScope(ctx, record.organizationId)
364
- const assignedCount = await em.count(ResourcesResource, {
365
- resourceTypeId: record.id,
366
- deletedAt: null,
367
- tenantId: record.tenantId,
368
- organizationId: record.organizationId,
369
- })
370
- if (assignedCount > 0) {
371
- throw new CrudHttpError(400, { error: 'Resource type has assigned resources.' })
372
- }
373
- record.deletedAt = new Date()
374
- record.updatedAt = new Date()
375
- await em.flush()
400
+ await withAtomicFlush(em, [
401
+ async () => {
402
+ await lockResourceType(em, record.id)
403
+ await assertNoAssignedResources(em, record, 400)
404
+ record.deletedAt = new Date()
405
+ record.updatedAt = new Date()
406
+ },
407
+ ], { transaction: true })
376
408
 
377
409
  const dataEngine = (ctx.container.resolve('dataEngine') as DataEngine)
378
410
  await emitCrudSideEffects({
@@ -11,7 +11,7 @@ import type { DataEngine } from '@open-mercato/shared/lib/data/engine'
11
11
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
12
12
  import type { CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'
13
13
  import { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'
14
- import { ResourcesResource, ResourcesResourceTag, ResourcesResourceTagAssignment } from '../data/entities'
14
+ import { ResourcesResource, ResourcesResourceTag, ResourcesResourceTagAssignment, ResourcesResourceType } from '../data/entities'
15
15
  import {
16
16
  resourcesResourceCreateSchema,
17
17
  resourcesResourceUpdateSchema,
@@ -19,6 +19,7 @@ import {
19
19
  type ResourcesResourceUpdateInput,
20
20
  } from '../data/validators'
21
21
  import { resourcesResourceCrudEvents } from '../lib/crud'
22
+ import { lockResourceType } from '../lib/resourceTypeLock'
22
23
  import { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'
23
24
  import { RESOURCES_CAPACITY_UNIT_DICTIONARY_KEY } from '../lib/capacityUnits'
24
25
  import { E } from '#generated/entities.ids.generated'
@@ -209,6 +210,70 @@ async function syncResourcesResourceTags(em: EntityManager, params: {
209
210
  }
210
211
  }
211
212
 
213
+ type ResourceScope = { tenantId: string; organizationId: string }
214
+
215
+ async function countResourceTypes(
216
+ em: EntityManager,
217
+ resourceTypeId: string,
218
+ scope: ResourceScope,
219
+ state: 'live' | 'deleted',
220
+ ): Promise<number> {
221
+ return em.count(ResourcesResourceType, {
222
+ id: resourceTypeId,
223
+ tenantId: scope.tenantId,
224
+ organizationId: scope.organizationId,
225
+ deletedAt: state === 'live' ? null : { $ne: null },
226
+ })
227
+ }
228
+
229
+ async function assertResourceTypeAssignable(
230
+ em: EntityManager,
231
+ resourceTypeId: string | null | undefined,
232
+ scope: ResourceScope,
233
+ ): Promise<void> {
234
+ if (!resourceTypeId) return
235
+ await lockResourceType(em, resourceTypeId)
236
+ if (await countResourceTypes(em, resourceTypeId, scope, 'live') > 0) return
237
+ throw await resourceTypeUnavailableError(400)
238
+ }
239
+
240
+ async function resourceTypeUnavailableError(status: 400 | 409): Promise<CrudHttpError> {
241
+ const { translate } = await resolveTranslations()
242
+ return new CrudHttpError(status, {
243
+ error: translate('resources.resources.errors.resourceTypeUnavailable', 'The selected resource type is no longer available.'),
244
+ code: 'resources.resources.errors.resourceTypeUnavailable',
245
+ })
246
+ }
247
+
248
+ async function assertResourceTypeRestorable(
249
+ em: EntityManager,
250
+ record: ResourcesResource | null,
251
+ resourceTypeId: string | null | undefined,
252
+ scope: ResourceScope,
253
+ ): Promise<void> {
254
+ if (!resourceTypeId) return
255
+ await lockResourceType(em, resourceTypeId)
256
+ if (record && await em.count(ResourcesResource, {
257
+ id: record.id,
258
+ tenantId: scope.tenantId,
259
+ organizationId: scope.organizationId,
260
+ resourceTypeId,
261
+ deletedAt: null,
262
+ }) > 0) return
263
+ if (await countResourceTypes(em, resourceTypeId, scope, 'live') > 0) return
264
+ if (await countResourceTypes(em, resourceTypeId, scope, 'deleted') === 0) {
265
+ throw await resourceTypeUnavailableError(409)
266
+ }
267
+ const { translate } = await resolveTranslations()
268
+ throw new CrudHttpError(409, {
269
+ error: translate(
270
+ 'resources.resources.errors.resourceTypeDeleted',
271
+ 'This would put the resource on a deleted resource type. Restore the resource type first.',
272
+ ),
273
+ code: 'resources.resources.errors.resourceTypeDeleted',
274
+ })
275
+ }
276
+
212
277
  const createResourceCommand: CommandHandler<ResourcesResourceCreateInput, { resourceId: string }> = {
213
278
  id: 'resources.resources.create',
214
279
  async execute(rawInput, ctx) {
@@ -244,6 +309,7 @@ const createResourceCommand: CommandHandler<ResourcesResourceCreateInput, { reso
244
309
  })
245
310
  await withAtomicFlush(em, [
246
311
  async () => {
312
+ await assertResourceTypeAssignable(em, parsed.resourceTypeId, parsed)
247
313
  em.persist(record)
248
314
  await em.flush()
249
315
  },
@@ -345,6 +411,7 @@ const createResourceCommand: CommandHandler<ResourcesResourceCreateInput, { reso
345
411
  let record = await em.findOne(ResourcesResource, { id: after.id })
346
412
  await withAtomicFlush(em, [
347
413
  async () => {
414
+ await assertResourceTypeRestorable(em, record, after.resourceTypeId, after)
348
415
  if (!record) {
349
416
  record = em.create(ResourcesResource, {
350
417
  id: after.id,
@@ -450,6 +517,7 @@ const updateResourceCommand: CommandHandler<ResourcesResourceUpdateInput, { reso
450
517
  if (!record) throw new CrudHttpError(404, { error: 'Resources resource not found.' })
451
518
  ensureTenantScope(ctx, record.tenantId)
452
519
  ensureOrganizationScope(ctx, record.organizationId)
520
+ const resourceTypeChanged = parsed.resourceTypeId !== undefined && parsed.resourceTypeId !== record.resourceTypeId
453
521
 
454
522
  let capacityUnit: CapacityUnitSnapshot | null | undefined
455
523
  if (parsed.capacityUnitValue !== undefined) {
@@ -464,7 +532,8 @@ const updateResourceCommand: CommandHandler<ResourcesResourceUpdateInput, { reso
464
532
  : null
465
533
  }
466
534
  await withAtomicFlush(em, [
467
- () => {
535
+ async () => {
536
+ if (resourceTypeChanged) await assertResourceTypeAssignable(em, parsed.resourceTypeId, record)
468
537
  if (parsed.capacityUnitValue !== undefined) {
469
538
  record.capacityUnitValue = capacityUnit?.value ?? null
470
539
  record.capacityUnitName = capacityUnit?.name ?? null
@@ -579,7 +648,8 @@ const updateResourceCommand: CommandHandler<ResourcesResourceUpdateInput, { reso
579
648
  const record = await em.findOne(ResourcesResource, { id: before.id })
580
649
  if (!record) return
581
650
  await withAtomicFlush(em, [
582
- () => {
651
+ async () => {
652
+ await assertResourceTypeRestorable(em, record, before.resourceTypeId, before)
583
653
  record.name = before.name
584
654
  record.description = before.description ?? null
585
655
  record.resourceTypeId = before.resourceTypeId ?? null
@@ -710,6 +780,7 @@ const deleteResourceCommand: CommandHandler<{ id?: string }, { resourceId: strin
710
780
  let record = await em.findOne(ResourcesResource, { id: before.id })
711
781
  await withAtomicFlush(em, [
712
782
  async () => {
783
+ await assertResourceTypeRestorable(em, record, before.resourceTypeId, before)
713
784
  if (!record) {
714
785
  record = em.create(ResourcesResource, {
715
786
  id: before.id,
@@ -259,6 +259,7 @@
259
259
  "resources.resources.availability.scope.label": "Anwenden auf",
260
260
  "resources.resources.availability.scope.weekday": "Wochentag:",
261
261
  "resources.resources.availability.scope.weekdayShort": "Alle {{weekday}}",
262
+ "resources.resources.availability.section.title": "Verfügbarkeit",
262
263
  "resources.resources.availability.timezone": "Zeitzone",
263
264
  "resources.resources.availability.timezone.placeholder": "Zeitzonen durchsuchen...",
264
265
  "resources.resources.availability.timezone.saveError": "Zeitzone konnte nicht gespeichert werden.",
@@ -443,6 +444,8 @@
443
444
  "resources.resources.detail.tabs.activities": "Aktivitäten",
444
445
  "resources.resources.detail.tabs.notes": "Notizen",
445
446
  "resources.resources.detail.untitled": "Unbenannte Ressource",
447
+ "resources.resources.errors.resourceTypeDeleted": "Dadurch würde die Ressource einem gelöschten Ressourcentyp zugeordnet. Stellen Sie zuerst den Ressourcentyp wieder her.",
448
+ "resources.resources.errors.resourceTypeUnavailable": "Der ausgewählte Ressourcentyp ist nicht mehr verfügbar.",
446
449
  "resources.resources.flash.createdAvailability": "Gespeichert. Du kannst jetzt die Verfügbarkeit festlegen.",
447
450
  "resources.resources.form.actions.create": "Erstellen",
448
451
  "resources.resources.form.appearance.colorClear": "Farbe entfernen",
@@ -259,6 +259,7 @@
259
259
  "resources.resources.availability.scope.label": "Apply to",
260
260
  "resources.resources.availability.scope.weekday": "Weekday:",
261
261
  "resources.resources.availability.scope.weekdayShort": "All {{weekday}}s",
262
+ "resources.resources.availability.section.title": "Availability",
262
263
  "resources.resources.availability.timezone": "Timezone",
263
264
  "resources.resources.availability.timezone.placeholder": "Search timezones...",
264
265
  "resources.resources.availability.timezone.saveError": "Failed to save timezone.",
@@ -443,6 +444,8 @@
443
444
  "resources.resources.detail.tabs.activities": "Activities",
444
445
  "resources.resources.detail.tabs.notes": "Notes",
445
446
  "resources.resources.detail.untitled": "Unnamed resource",
447
+ "resources.resources.errors.resourceTypeDeleted": "This would put the resource on a deleted resource type. Restore the resource type first.",
448
+ "resources.resources.errors.resourceTypeUnavailable": "The selected resource type is no longer available.",
446
449
  "resources.resources.flash.createdAvailability": "Saved. You can now set availability.",
447
450
  "resources.resources.form.actions.create": "Create",
448
451
  "resources.resources.form.appearance.colorClear": "Clear color",
@@ -259,6 +259,7 @@
259
259
  "resources.resources.availability.scope.label": "Aplicar a",
260
260
  "resources.resources.availability.scope.weekday": "Día de la semana:",
261
261
  "resources.resources.availability.scope.weekdayShort": "Todos los {{weekday}}",
262
+ "resources.resources.availability.section.title": "Disponibilidad",
262
263
  "resources.resources.availability.timezone": "Zona horaria",
263
264
  "resources.resources.availability.timezone.placeholder": "Buscar zonas horarias...",
264
265
  "resources.resources.availability.timezone.saveError": "No se pudo guardar la zona horaria.",
@@ -443,6 +444,8 @@
443
444
  "resources.resources.detail.tabs.activities": "Actividades",
444
445
  "resources.resources.detail.tabs.notes": "Notas",
445
446
  "resources.resources.detail.untitled": "Recurso sin nombre",
447
+ "resources.resources.errors.resourceTypeDeleted": "Esto asignaría el recurso a un tipo de recurso eliminado. Restaura primero el tipo de recurso.",
448
+ "resources.resources.errors.resourceTypeUnavailable": "El tipo de recurso seleccionado ya no está disponible.",
446
449
  "resources.resources.flash.createdAvailability": "Guardado. Ahora puedes establecer la disponibilidad.",
447
450
  "resources.resources.form.actions.create": "Crear",
448
451
  "resources.resources.form.appearance.colorClear": "Limpiar color",
@@ -259,6 +259,7 @@
259
259
  "resources.resources.availability.scope.label": "적용 대상",
260
260
  "resources.resources.availability.scope.weekday": "요일:",
261
261
  "resources.resources.availability.scope.weekdayShort": "매주 {{weekday}}",
262
+ "resources.resources.availability.section.title": "가용성",
262
263
  "resources.resources.availability.timezone": "시간대",
263
264
  "resources.resources.availability.timezone.placeholder": "시간대 검색...",
264
265
  "resources.resources.availability.timezone.saveError": "시간대를 저장하지 못했습니다.",
@@ -443,6 +444,8 @@
443
444
  "resources.resources.detail.tabs.activities": "활동",
444
445
  "resources.resources.detail.tabs.notes": "메모",
445
446
  "resources.resources.detail.untitled": "이름 없는 리소스",
447
+ "resources.resources.errors.resourceTypeDeleted": "이 작업은 리소스를 삭제된 리소스 유형에 연결합니다. 먼저 리소스 유형을 복원하세요.",
448
+ "resources.resources.errors.resourceTypeUnavailable": "선택한 리소스 유형을 더 이상 사용할 수 없습니다.",
446
449
  "resources.resources.flash.createdAvailability": "저장되었습니다. 이제 가용성을 설정할 수 있습니다.",
447
450
  "resources.resources.form.actions.create": "생성",
448
451
  "resources.resources.form.appearance.colorClear": "색상 지우기",
@@ -259,6 +259,7 @@
259
259
  "resources.resources.availability.scope.label": "Zastosuj do",
260
260
  "resources.resources.availability.scope.weekday": "Dzień tygodnia:",
261
261
  "resources.resources.availability.scope.weekdayShort": "Wszystkie {{weekday}}",
262
+ "resources.resources.availability.section.title": "Dostępność",
262
263
  "resources.resources.availability.timezone": "Strefa czasowa",
263
264
  "resources.resources.availability.timezone.placeholder": "Szukaj stref czasowych...",
264
265
  "resources.resources.availability.timezone.saveError": "Nie udało się zapisać strefy czasowej.",
@@ -443,6 +444,8 @@
443
444
  "resources.resources.detail.tabs.activities": "Działania",
444
445
  "resources.resources.detail.tabs.notes": "Notatki",
445
446
  "resources.resources.detail.untitled": "Nienazwany zasób",
447
+ "resources.resources.errors.resourceTypeDeleted": "Spowodowałoby to przypisanie zasobu do usuniętego typu zasobu. Najpierw przywróć typ zasobu.",
448
+ "resources.resources.errors.resourceTypeUnavailable": "Wybrany typ zasobu nie jest już dostępny.",
446
449
  "resources.resources.flash.createdAvailability": "Zapisano. Możesz teraz ustawić dostępność.",
447
450
  "resources.resources.form.actions.create": "Utwórz",
448
451
  "resources.resources.form.appearance.colorClear": "Wyczyść kolor",
@@ -0,0 +1,14 @@
1
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
+
3
+ const RESOURCE_TYPE_LOCK_SQL = 'select pg_advisory_xact_lock(hashtextextended(?, 0))'
4
+
5
+ export function resourceTypeLockKey(resourceTypeId: string): string {
6
+ return `resources:resource-type:${resourceTypeId.toLowerCase()}`
7
+ }
8
+
9
+ export async function lockResourceType(em: EntityManager, resourceTypeId: string): Promise<void> {
10
+ if (!em.isInTransaction()) {
11
+ throw new Error('[internal] lockResourceType requires an open transaction')
12
+ }
13
+ await em.execute(RESOURCE_TYPE_LOCK_SQL, [resourceTypeLockKey(resourceTypeId)])
14
+ }
@@ -590,6 +590,35 @@ async function deactivateOtherDefaultTaxRates(em: EntityManager, record: SalesTa
590
590
  )
591
591
  }
592
592
 
593
+ async function restoreTaxRateFromSnapshot(
594
+ em: EntityManager,
595
+ before: TaxRateSnapshot,
596
+ options: { keepCurrentIsDefault: boolean },
597
+ ) {
598
+ await em.transactional(async (tx) => {
599
+ let record = await findOneWithDecryption(
600
+ tx,
601
+ SalesTaxRate,
602
+ { id: before.id, tenantId: before.tenantId, organizationId: before.organizationId },
603
+ {},
604
+ { tenantId: before.tenantId, organizationId: before.organizationId },
605
+ )
606
+ if (!record) {
607
+ record = tx.create(SalesTaxRate, taxRateSeedFromSnapshot(before))
608
+ tx.persist(record)
609
+ }
610
+ const currentIsDefault = record.isDefault
611
+ applyTaxRateSnapshot(record, before)
612
+ if (options.keepCurrentIsDefault) {
613
+ record.isDefault = currentIsDefault
614
+ }
615
+ await tx.flush()
616
+ if (record.isDefault) {
617
+ await deactivateOtherDefaultTaxRates(tx, record)
618
+ }
619
+ })
620
+ }
621
+
593
622
  const createChannelCommand: CommandHandler<ChannelCreateInput, { channelId: string }> = {
594
623
  id: 'sales.channels.create',
595
624
  async execute(rawInput, ctx) {
@@ -2059,16 +2088,12 @@ const updateTaxRateCommand: CommandHandler<TaxRateUpdateInput, { taxRateId: stri
2059
2088
  const payload = extractUndoPayload<UndoPayload<TaxRateSnapshot>>(logEntry)
2060
2089
  const before = payload?.before
2061
2090
  if (!before) return
2062
- const em = (ctx.container.resolve('em') as EntityManager).fork()
2063
- let record = await em.findOne(SalesTaxRate, { id: before.id })
2064
- if (!record) {
2065
- record = em.create(SalesTaxRate, taxRateSeedFromSnapshot(before))
2066
- em.persist(record)
2067
- }
2068
2091
  ensureTenantScope(ctx, before.tenantId)
2069
2092
  ensureOrganizationScope(ctx, before.organizationId)
2070
- applyTaxRateSnapshot(record, before)
2071
- await em.flush()
2093
+ const em = (ctx.container.resolve('em') as EntityManager).fork()
2094
+ await restoreTaxRateFromSnapshot(em, before, {
2095
+ keepCurrentIsDefault: Boolean(payload?.after && payload.after.isDefault === before.isDefault),
2096
+ })
2072
2097
  const resetValues = buildCustomFieldResetMap(before.custom ?? undefined, payload?.after?.custom ?? undefined)
2073
2098
  if (Object.keys(resetValues).length) {
2074
2099
  await setCustomFieldsIfAny({
@@ -2145,16 +2170,10 @@ const deleteTaxRateCommand: CommandHandler<
2145
2170
  const payload = extractUndoPayload<UndoPayload<TaxRateSnapshot>>(logEntry)
2146
2171
  const before = payload?.before
2147
2172
  if (!before) return
2148
- const em = (ctx.container.resolve('em') as EntityManager).fork()
2149
- let record = await em.findOne(SalesTaxRate, { id: before.id })
2150
- if (!record) {
2151
- record = em.create(SalesTaxRate, taxRateSeedFromSnapshot(before))
2152
- em.persist(record)
2153
- }
2154
2173
  ensureTenantScope(ctx, before.tenantId)
2155
2174
  ensureOrganizationScope(ctx, before.organizationId)
2156
- applyTaxRateSnapshot(record, before)
2157
- await em.flush()
2175
+ const em = (ctx.container.resolve('em') as EntityManager).fork()
2176
+ await restoreTaxRateFromSnapshot(em, before, { keepCurrentIsDefault: false })
2158
2177
  if (before.custom && Object.keys(before.custom).length) {
2159
2178
  await setCustomFieldsIfAny({
2160
2179
  dataEngine: ctx.container.resolve('dataEngine'),
@@ -16,6 +16,7 @@ import {
16
16
  SelectValue,
17
17
  } from '@open-mercato/ui/primitives/select'
18
18
  import { SwitchField } from '@open-mercato/ui/primitives/switch-field'
19
+ import { SegmentedControl, SegmentedControlItem } from '@open-mercato/ui/primitives/segmented-control'
19
20
  import { useT } from '@open-mercato/shared/lib/i18n/context'
20
21
  import { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'
21
22
  import { AddressEditor, type AddressEditorDraft } from '@open-mercato/core/modules/customers/components/AddressEditor'
@@ -328,6 +329,22 @@ export function SalesDocumentAddressesSection({
328
329
  )
329
330
 
330
331
  const customerRequired = !customerId
332
+ const hasSavedAddresses = addressOptions.length > 0
333
+ // With no saved addresses the only thing the form can do is define a new one, so it
334
+ // opens straight on the address fields instead of an empty select (#6194). The choice
335
+ // follows the saved addresses as they load, until the user picks a side themselves.
336
+ const additionalModeTouchedRef = React.useRef(false)
337
+ const openAdditionalForm = React.useCallback(() => {
338
+ additionalModeTouchedRef.current = false
339
+ setAdditionalUseCustom(!hasSavedAddresses)
340
+ setAdditionalSelectedId('')
341
+ setAdditionalFormOpen(true)
342
+ }, [hasSavedAddresses])
343
+ React.useEffect(() => {
344
+ if (!additionalFormOpen || addressesLoading) return
345
+ if (!hasSavedAddresses) setAdditionalUseCustom(true)
346
+ else if (!additionalModeTouchedRef.current) setAdditionalUseCustom(false)
347
+ }, [additionalFormOpen, addressesLoading, hasSavedAddresses])
331
348
  const addressOptionsMap = React.useMemo(() => {
332
349
  const map = new Map<string, AddressOption>()
333
350
  addressOptions.forEach((entry) => map.set(entry.id, entry))
@@ -1244,16 +1261,18 @@ export function SalesDocumentAddressesSection({
1244
1261
  )}
1245
1262
  </p>
1246
1263
  </div>
1247
- <Button
1248
- type="button"
1249
- variant="outline"
1250
- size="sm"
1251
- onClick={() => setAdditionalFormOpen(true)}
1252
- disabled={customerRequired || locked}
1253
- >
1254
- <Plus className="mr-2 h-4 w-4" />
1255
- {t('sales.documents.detail.addresses.add', 'Add address')}
1256
- </Button>
1264
+ {documentAddressesLoading || documentAddresses.length > 0 || additionalFormOpen ? (
1265
+ <Button
1266
+ type="button"
1267
+ variant="outline"
1268
+ size="sm"
1269
+ onClick={openAdditionalForm}
1270
+ disabled={customerRequired || locked || additionalFormOpen}
1271
+ >
1272
+ <Plus className="mr-2 h-4 w-4" />
1273
+ {t('sales.documents.detail.addresses.add', 'Add address')}
1274
+ </Button>
1275
+ ) : null}
1257
1276
  </div>
1258
1277
 
1259
1278
  {documentAddressesLoading ? (
@@ -1272,7 +1291,7 @@ export function SalesDocumentAddressesSection({
1272
1291
  )}
1273
1292
  action={{
1274
1293
  label: t('sales.documents.detail.addresses.add', 'Add address'),
1275
- onClick: () => setAdditionalFormOpen(true),
1294
+ onClick: openAdditionalForm,
1276
1295
  disabled: customerRequired || locked,
1277
1296
  }}
1278
1297
  />
@@ -1380,7 +1399,7 @@ export function SalesDocumentAddressesSection({
1380
1399
  </div>
1381
1400
 
1382
1401
  {additionalFormOpen ? (
1383
- <div className="space-y-3 rounded border border-dashed p-3">
1402
+ <div className="space-y-3 rounded border border-dashed p-3" data-testid="additional-address-form">
1384
1403
  <div className="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">
1385
1404
  <p className="text-sm font-semibold">
1386
1405
  {t('sales.documents.detail.addresses.new', 'Add a new address')}
@@ -1400,13 +1419,25 @@ export function SalesDocumentAddressesSection({
1400
1419
  </Button>
1401
1420
  </div>
1402
1421
 
1403
- <SwitchField
1404
- label={t('sales.documents.form.shipping.custom', 'Define new address')}
1405
- flip
1406
- checked={additionalUseCustom}
1407
- onCheckedChange={(checked) => setAdditionalUseCustom(checked)}
1408
- disabled={customerRequired || locked}
1409
- />
1422
+ {hasSavedAddresses ? (
1423
+ <SegmentedControl
1424
+ value={additionalUseCustom ? 'new' : 'saved'}
1425
+ onValueChange={(next) => {
1426
+ additionalModeTouchedRef.current = true
1427
+ setAdditionalUseCustom(next === 'new')
1428
+ }}
1429
+ size="sm"
1430
+ disabled={customerRequired || locked}
1431
+ aria-label={t('sales.documents.detail.addresses.mode.label', 'Address source')}
1432
+ >
1433
+ <SegmentedControlItem value="saved">
1434
+ {t('sales.documents.detail.addresses.mode.saved', 'Saved address')}
1435
+ </SegmentedControlItem>
1436
+ <SegmentedControlItem value="new">
1437
+ {t('sales.documents.detail.addresses.mode.new', 'New address')}
1438
+ </SegmentedControlItem>
1439
+ </SegmentedControl>
1440
+ ) : null}
1410
1441
 
1411
1442
  {!additionalUseCustom
1412
1443
  ? renderAddressSelect(
@@ -1435,7 +1466,7 @@ export function SalesDocumentAddressesSection({
1435
1466
  >
1436
1467
  {additionalSaving
1437
1468
  ? t('sales.documents.form.address.saving', 'Saving…')
1438
- : t('sales.documents.detail.addresses.add', 'Add address')}
1469
+ : t('sales.documents.detail.addresses.save', 'Save address')}
1439
1470
  </Button>
1440
1471
  </div>
1441
1472
  </div>
@@ -519,6 +519,9 @@
519
519
  "sales.documents.detail.addresses.line1Required": "Fügen Sie Adresszeile 1 hinzu, um fortzufahren.",
520
520
  "sales.documents.detail.addresses.loadError": "Adressen konnten nicht geladen werden.",
521
521
  "sales.documents.detail.addresses.loading": "Dokumentadressen werden geladen…",
522
+ "sales.documents.detail.addresses.mode.label": "Adressquelle",
523
+ "sales.documents.detail.addresses.mode.new": "Neue Adresse",
524
+ "sales.documents.detail.addresses.mode.saved": "Gespeicherte Adresse",
522
525
  "sales.documents.detail.addresses.new": "Neue Adresse hinzufügen",
523
526
  "sales.documents.detail.addresses.removed": "Adresse wurde entfernt.",
524
527
  "sales.documents.detail.addresses.save": "Adresse speichern",
@@ -519,6 +519,9 @@
519
519
  "sales.documents.detail.addresses.line1Required": "Add address line 1 to continue.",
520
520
  "sales.documents.detail.addresses.loadError": "Failed to load addresses.",
521
521
  "sales.documents.detail.addresses.loading": "Loading document addresses…",
522
+ "sales.documents.detail.addresses.mode.label": "Address source",
523
+ "sales.documents.detail.addresses.mode.new": "New address",
524
+ "sales.documents.detail.addresses.mode.saved": "Saved address",
522
525
  "sales.documents.detail.addresses.new": "Add a new address",
523
526
  "sales.documents.detail.addresses.removed": "Address unassigned.",
524
527
  "sales.documents.detail.addresses.save": "Save address",