@open-mercato/core 0.6.6-develop.6256.1.9fc16aedc4 → 0.6.6-develop.6286.1.d985c5c374
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.
- package/.turbo/turbo-build.log +2 -2
- package/dist/generated/entities/carrier_shipment_idempotency_key/index.js +19 -0
- package/dist/generated/entities/carrier_shipment_idempotency_key/index.js.map +7 -0
- package/dist/generated/entities.ids.generated.js +2 -1
- package/dist/generated/entities.ids.generated.js.map +2 -2
- package/dist/generated/entity-fields-registry.js +10 -0
- package/dist/generated/entity-fields-registry.js.map +2 -2
- package/dist/modules/catalog/lib/productResolution.js +45 -0
- package/dist/modules/catalog/lib/productResolution.js.map +7 -0
- package/dist/modules/communication_channels/workers/channel-import-history.js +1 -1
- package/dist/modules/communication_channels/workers/channel-import-history.js.map +2 -2
- package/dist/modules/currencies/api/fetch-configs/route.js +34 -0
- package/dist/modules/currencies/api/fetch-configs/route.js.map +2 -2
- package/dist/modules/currencies/components/CurrencyFetchingConfig.js +17 -15
- package/dist/modules/currencies/components/CurrencyFetchingConfig.js.map +2 -2
- package/dist/modules/customers/api/companies/[id]/route.js +176 -161
- package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
- package/dist/modules/customers/api/people/[id]/route.js +75 -59
- package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
- package/dist/modules/customers/backend/config/customers/pipeline-stages/page.js +17 -10
- package/dist/modules/customers/backend/config/customers/pipeline-stages/page.js.map +2 -2
- package/dist/modules/customers/components/detail/ActivitiesAddNewMenu.js +6 -4
- package/dist/modules/customers/components/detail/ActivitiesAddNewMenu.js.map +2 -2
- package/dist/modules/customers/components/detail/AiActionChips.js +5 -2
- package/dist/modules/customers/components/detail/AiActionChips.js.map +2 -2
- package/dist/modules/customers/components/detail/schedule/ParticipantsField.js +19 -21
- package/dist/modules/customers/components/detail/schedule/ParticipantsField.js.map +2 -2
- package/dist/modules/data_sync/api/runs/[id]/cancel.js +1 -1
- package/dist/modules/data_sync/api/runs/[id]/cancel.js.map +2 -2
- package/dist/modules/data_sync/backend/data-sync/page.js +9 -45
- package/dist/modules/data_sync/backend/data-sync/page.js.map +2 -2
- package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js +11 -17
- package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js.map +2 -2
- package/dist/modules/data_sync/components/IntegrationScheduleTab.js +12 -10
- package/dist/modules/data_sync/components/IntegrationScheduleTab.js.map +2 -2
- package/dist/modules/data_sync/lib/id-mapping.js +46 -1
- package/dist/modules/data_sync/lib/id-mapping.js.map +2 -2
- package/dist/modules/data_sync/lib/sync-engine.js +2 -2
- package/dist/modules/data_sync/lib/sync-engine.js.map +2 -2
- package/dist/modules/data_sync/lib/syncRunStatus.js +30 -0
- package/dist/modules/data_sync/lib/syncRunStatus.js.map +7 -0
- package/dist/modules/entities/api/records.js +6 -0
- package/dist/modules/entities/api/records.js.map +2 -2
- package/dist/modules/feature_toggles/api/global/route.js +17 -15
- package/dist/modules/feature_toggles/api/global/route.js.map +2 -2
- package/dist/modules/feature_toggles/api/openapi.js +2 -2
- package/dist/modules/feature_toggles/api/openapi.js.map +2 -2
- package/dist/modules/feature_toggles/commands/global.js +14 -0
- package/dist/modules/feature_toggles/commands/global.js.map +2 -2
- package/dist/modules/inbox_ops/backend/inbox-ops/page.js +6 -0
- package/dist/modules/inbox_ops/backend/inbox-ops/page.js.map +2 -2
- package/dist/modules/messages/api/[id]/conversation/archive/route.js +25 -7
- package/dist/modules/messages/api/[id]/conversation/archive/route.js.map +2 -2
- package/dist/modules/messages/api/[id]/conversation/read/route.js +24 -6
- package/dist/modules/messages/api/[id]/conversation/read/route.js.map +2 -2
- package/dist/modules/messages/api/[id]/route.js +13 -1
- package/dist/modules/messages/api/[id]/route.js.map +2 -2
- package/dist/modules/messages/api/openapi.js +3 -1
- package/dist/modules/messages/api/openapi.js.map +2 -2
- package/dist/modules/messages/commands/conversation.js +77 -0
- package/dist/modules/messages/commands/conversation.js.map +2 -2
- package/dist/modules/messages/components/MessageDetailPageClient.js +16 -4
- package/dist/modules/messages/components/MessageDetailPageClient.js.map +2 -2
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetails.js +3 -1
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetails.js.map +2 -2
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsActions.js +29 -4
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsActions.js.map +2 -2
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsQueries.js +10 -1
- package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsQueries.js.map +2 -2
- package/dist/modules/messages/components/message-detail/panels/MainMessageHeader.js +13 -11
- package/dist/modules/messages/components/message-detail/panels/MainMessageHeader.js.map +2 -2
- package/dist/modules/payment_gateways/api/cancel/route.js +5 -0
- package/dist/modules/payment_gateways/api/cancel/route.js.map +2 -2
- package/dist/modules/payment_gateways/api/capture/route.js +5 -0
- package/dist/modules/payment_gateways/api/capture/route.js.map +2 -2
- package/dist/modules/payment_gateways/api/refund/route.js +5 -0
- package/dist/modules/payment_gateways/api/refund/route.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +52 -25
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
- package/dist/modules/payment_gateways/lib/status-machine.js +13 -0
- package/dist/modules/payment_gateways/lib/status-machine.js.map +2 -2
- package/dist/modules/perspectives/api/[tableId]/route.js +8 -2
- package/dist/modules/perspectives/api/[tableId]/route.js.map +2 -2
- package/dist/modules/perspectives/data/entities.js +33 -3
- package/dist/modules/perspectives/data/entities.js.map +2 -2
- package/dist/modules/perspectives/migrations/Migration20260619120000_perspectives_live_row_uniqueness.js +63 -0
- package/dist/modules/perspectives/migrations/Migration20260619120000_perspectives_live_row_uniqueness.js.map +7 -0
- package/dist/modules/perspectives/services/perspectiveService.js +17 -0
- package/dist/modules/perspectives/services/perspectiveService.js.map +2 -2
- package/dist/modules/planner/commands/availability-weekly.js +33 -1
- package/dist/modules/planner/commands/availability-weekly.js.map +2 -2
- package/dist/modules/planner/components/AvailabilityRulesEditor.js +14 -2
- package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
- package/dist/modules/progress/api/active/route.js +1 -1
- package/dist/modules/progress/api/active/route.js.map +2 -2
- package/dist/modules/progress/lib/progressService.js.map +1 -1
- package/dist/modules/progress/lib/progressServiceImpl.js +33 -8
- package/dist/modules/progress/lib/progressServiceImpl.js.map +2 -2
- package/dist/modules/query_index/api/status.js +19 -24
- package/dist/modules/query_index/api/status.js.map +3 -3
- package/dist/modules/query_index/lib/coverage.js +35 -0
- package/dist/modules/query_index/lib/coverage.js.map +2 -2
- package/dist/modules/query_index/lib/engine.js +11 -6
- package/dist/modules/query_index/lib/engine.js.map +2 -2
- package/dist/modules/resources/api/resource-types.js +5 -37
- package/dist/modules/resources/api/resource-types.js.map +2 -2
- package/dist/modules/resources/api/resourceTypeCounts.js +35 -0
- package/dist/modules/resources/api/resourceTypeCounts.js.map +7 -0
- package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js +1 -1
- package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js.map +1 -1
- package/dist/modules/resources/backend/resources/resource-types/page.js +2 -1
- package/dist/modules/resources/backend/resources/resource-types/page.js.map +2 -2
- package/dist/modules/sales/components/documents/ReturnDialog.js +4 -1
- package/dist/modules/sales/components/documents/ReturnDialog.js.map +2 -2
- package/dist/modules/sales/components/documents/ShipmentDialog.js +17 -2
- package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
- package/dist/modules/sales/di.js +4 -0
- package/dist/modules/sales/di.js.map +2 -2
- package/dist/modules/sales/services/salesOrderService.js +26 -0
- package/dist/modules/sales/services/salesOrderService.js.map +7 -0
- package/dist/modules/shipping_carriers/api/shipments/route.js +8 -0
- package/dist/modules/shipping_carriers/api/shipments/route.js.map +2 -2
- package/dist/modules/shipping_carriers/data/entities.js +38 -0
- package/dist/modules/shipping_carriers/data/entities.js.map +2 -2
- package/dist/modules/shipping_carriers/data/validators.js +2 -1
- package/dist/modules/shipping_carriers/data/validators.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipment-idempotency.js +76 -0
- package/dist/modules/shipping_carriers/lib/shipment-idempotency.js.map +7 -0
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/shipmentApi.js +2 -1
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/shipmentApi.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/useShipmentWizard.js +20 -2
- package/dist/modules/shipping_carriers/lib/shipment-wizard/hooks/useShipmentWizard.js.map +2 -2
- package/dist/modules/shipping_carriers/lib/shipping-service.js +82 -43
- package/dist/modules/shipping_carriers/lib/shipping-service.js.map +2 -2
- package/dist/modules/shipping_carriers/migrations/Migration20260618173616_shipping_carriers.js +14 -0
- package/dist/modules/shipping_carriers/migrations/Migration20260618173616_shipping_carriers.js.map +7 -0
- package/dist/modules/staff/lib/timesheets-ui/ListView.js +15 -6
- package/dist/modules/staff/lib/timesheets-ui/ListView.js.map +2 -2
- package/dist/modules/translations/components/TranslationManager.js +9 -18
- package/dist/modules/translations/components/TranslationManager.js.map +2 -2
- package/generated/entities/carrier_shipment_idempotency_key/index.ts +8 -0
- package/generated/entities.ids.generated.ts +2 -1
- package/generated/entity-fields-registry.ts +10 -0
- package/package.json +9 -8
- package/src/modules/catalog/lib/productResolution.ts +75 -0
- package/src/modules/communication_channels/workers/channel-import-history.ts +1 -1
- package/src/modules/currencies/api/fetch-configs/route.ts +36 -0
- package/src/modules/currencies/components/CurrencyFetchingConfig.tsx +20 -17
- package/src/modules/currencies/i18n/de.json +2 -1
- package/src/modules/currencies/i18n/en.json +2 -1
- package/src/modules/currencies/i18n/es.json +2 -1
- package/src/modules/currencies/i18n/pl.json +2 -1
- package/src/modules/customers/api/companies/[id]/route.ts +214 -189
- package/src/modules/customers/api/people/[id]/route.ts +106 -80
- package/src/modules/customers/backend/config/customers/pipeline-stages/page.tsx +19 -12
- package/src/modules/customers/components/detail/ActivitiesAddNewMenu.tsx +8 -6
- package/src/modules/customers/components/detail/AiActionChips.tsx +6 -3
- package/src/modules/customers/components/detail/schedule/ParticipantsField.tsx +16 -18
- package/src/modules/data_sync/api/runs/[id]/cancel.ts +1 -1
- package/src/modules/data_sync/backend/data-sync/page.tsx +11 -58
- package/src/modules/data_sync/backend/data-sync/runs/[id]/page.tsx +13 -20
- package/src/modules/data_sync/components/IntegrationScheduleTab.tsx +10 -8
- package/src/modules/data_sync/lib/id-mapping.ts +58 -1
- package/src/modules/data_sync/lib/sync-engine.ts +2 -2
- package/src/modules/data_sync/lib/syncRunStatus.ts +39 -0
- package/src/modules/entities/api/records.ts +14 -0
- package/src/modules/feature_toggles/api/global/route.ts +16 -14
- package/src/modules/feature_toggles/api/openapi.ts +2 -2
- package/src/modules/feature_toggles/commands/global.ts +15 -0
- package/src/modules/inbox_ops/backend/inbox-ops/page.tsx +7 -0
- package/src/modules/messages/api/[id]/conversation/archive/route.ts +29 -6
- package/src/modules/messages/api/[id]/conversation/read/route.ts +29 -6
- package/src/modules/messages/api/[id]/route.ts +15 -0
- package/src/modules/messages/api/openapi.ts +2 -0
- package/src/modules/messages/commands/conversation.ts +87 -0
- package/src/modules/messages/components/MessageDetailPageClient.tsx +16 -4
- package/src/modules/messages/components/message-detail/hooks/useMessageDetails.ts +2 -0
- package/src/modules/messages/components/message-detail/hooks/useMessageDetailsActions.ts +39 -4
- package/src/modules/messages/components/message-detail/hooks/useMessageDetailsQueries.ts +15 -1
- package/src/modules/messages/components/message-detail/panels/MainMessageHeader.tsx +29 -14
- package/src/modules/messages/components/message-detail/types.ts +2 -0
- package/src/modules/messages/i18n/de.json +4 -0
- package/src/modules/messages/i18n/en.json +4 -0
- package/src/modules/messages/i18n/es.json +4 -0
- package/src/modules/messages/i18n/pl.json +4 -0
- package/src/modules/payment_gateways/api/cancel/route.ts +5 -0
- package/src/modules/payment_gateways/api/capture/route.ts +5 -0
- package/src/modules/payment_gateways/api/refund/route.ts +5 -0
- package/src/modules/payment_gateways/lib/gateway-service.ts +58 -25
- package/src/modules/payment_gateways/lib/status-machine.ts +16 -0
- package/src/modules/perspectives/api/[tableId]/route.ts +8 -2
- package/src/modules/perspectives/data/entities.ts +43 -3
- package/src/modules/perspectives/migrations/.snapshot-open-mercato.json +69 -25
- package/src/modules/perspectives/migrations/Migration20260619120000_perspectives_live_row_uniqueness.ts +65 -0
- package/src/modules/perspectives/services/perspectiveService.ts +17 -0
- package/src/modules/planner/commands/availability-weekly.ts +48 -1
- package/src/modules/planner/components/AvailabilityRulesEditor.tsx +31 -10
- package/src/modules/progress/api/active/route.ts +1 -1
- package/src/modules/progress/lib/progressService.ts +2 -2
- package/src/modules/progress/lib/progressServiceImpl.ts +33 -8
- package/src/modules/query_index/api/status.ts +28 -32
- package/src/modules/query_index/lib/coverage.ts +63 -0
- package/src/modules/query_index/lib/engine.ts +37 -24
- package/src/modules/resources/api/resource-types.ts +4 -44
- package/src/modules/resources/api/resourceTypeCounts.ts +74 -0
- package/src/modules/resources/backend/resources/resource-types/[id]/edit/page.tsx +1 -1
- package/src/modules/resources/backend/resources/resource-types/page.tsx +1 -0
- package/src/modules/sales/components/documents/ReturnDialog.tsx +4 -1
- package/src/modules/sales/components/documents/ShipmentDialog.tsx +20 -2
- package/src/modules/sales/di.ts +6 -0
- package/src/modules/sales/services/salesOrderService.ts +38 -0
- package/src/modules/shipping_carriers/api/shipments/route.ts +8 -0
- package/src/modules/shipping_carriers/data/entities.ts +33 -0
- package/src/modules/shipping_carriers/data/validators.ts +1 -0
- package/src/modules/shipping_carriers/i18n/de.json +1 -0
- package/src/modules/shipping_carriers/i18n/en.json +1 -0
- package/src/modules/shipping_carriers/i18n/es.json +1 -0
- package/src/modules/shipping_carriers/i18n/pl.json +1 -0
- package/src/modules/shipping_carriers/lib/shipment-idempotency.ts +119 -0
- package/src/modules/shipping_carriers/lib/shipment-wizard/hooks/shipmentApi.ts +3 -1
- package/src/modules/shipping_carriers/lib/shipment-wizard/hooks/useShipmentWizard.ts +24 -2
- package/src/modules/shipping_carriers/lib/shipping-service.ts +87 -43
- package/src/modules/shipping_carriers/migrations/.snapshot-open-mercato.json +197 -0
- package/src/modules/shipping_carriers/migrations/Migration20260618173616_shipping_carriers.ts +14 -0
- package/src/modules/staff/i18n/de.json +1 -0
- package/src/modules/staff/i18n/en.json +1 -0
- package/src/modules/staff/i18n/es.json +1 -0
- package/src/modules/staff/i18n/pl.json +1 -0
- package/src/modules/staff/lib/timesheets-ui/ListView.tsx +15 -7
- package/src/modules/translations/components/TranslationManager.tsx +17 -24
- package/src/modules/translations/i18n/de.json +1 -0
- package/src/modules/translations/i18n/en.json +1 -0
- package/src/modules/translations/i18n/es.json +1 -0
- package/src/modules/translations/i18n/pl.json +1 -0
|
@@ -8,7 +8,7 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
8
8
|
if (kind && result) __defProp(target, key, result);
|
|
9
9
|
return result;
|
|
10
10
|
};
|
|
11
|
-
import { Entity, Index, PrimaryKey, Property
|
|
11
|
+
import { Entity, Index, PrimaryKey, Property } from "@mikro-orm/decorators/legacy";
|
|
12
12
|
let Perspective = class {
|
|
13
13
|
constructor() {
|
|
14
14
|
this.isDefault = false;
|
|
@@ -51,7 +51,22 @@ __decorateClass([
|
|
|
51
51
|
Perspective = __decorateClass([
|
|
52
52
|
Entity({ tableName: "perspectives" }),
|
|
53
53
|
Index({ name: "perspectives_user_scope_idx", properties: ["userId", "tenantId", "organizationId", "tableId"] }),
|
|
54
|
-
|
|
54
|
+
Index({
|
|
55
|
+
name: "perspectives_live_user_org_uq",
|
|
56
|
+
expression: 'create unique index "perspectives_live_user_org_uq" on "perspectives" ("user_id", "tenant_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is not null'
|
|
57
|
+
}),
|
|
58
|
+
Index({
|
|
59
|
+
name: "perspectives_live_user_tenant_uq",
|
|
60
|
+
expression: 'create unique index "perspectives_live_user_tenant_uq" on "perspectives" ("user_id", "tenant_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is null'
|
|
61
|
+
}),
|
|
62
|
+
Index({
|
|
63
|
+
name: "perspectives_live_user_org_only_uq",
|
|
64
|
+
expression: 'create unique index "perspectives_live_user_org_only_uq" on "perspectives" ("user_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is not null'
|
|
65
|
+
}),
|
|
66
|
+
Index({
|
|
67
|
+
name: "perspectives_live_user_global_uq",
|
|
68
|
+
expression: 'create unique index "perspectives_live_user_global_uq" on "perspectives" ("user_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is null'
|
|
69
|
+
})
|
|
55
70
|
], Perspective);
|
|
56
71
|
let RolePerspective = class {
|
|
57
72
|
constructor() {
|
|
@@ -95,7 +110,22 @@ __decorateClass([
|
|
|
95
110
|
RolePerspective = __decorateClass([
|
|
96
111
|
Entity({ tableName: "role_perspectives" }),
|
|
97
112
|
Index({ name: "role_perspectives_role_scope_idx", properties: ["roleId", "tenantId", "organizationId", "tableId"] }),
|
|
98
|
-
|
|
113
|
+
Index({
|
|
114
|
+
name: "role_perspectives_live_role_org_uq",
|
|
115
|
+
expression: 'create unique index "role_perspectives_live_role_org_uq" on "role_perspectives" ("role_id", "tenant_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is not null'
|
|
116
|
+
}),
|
|
117
|
+
Index({
|
|
118
|
+
name: "role_perspectives_live_role_tenant_uq",
|
|
119
|
+
expression: 'create unique index "role_perspectives_live_role_tenant_uq" on "role_perspectives" ("role_id", "tenant_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is null'
|
|
120
|
+
}),
|
|
121
|
+
Index({
|
|
122
|
+
name: "role_perspectives_live_role_org_only_uq",
|
|
123
|
+
expression: 'create unique index "role_perspectives_live_role_org_only_uq" on "role_perspectives" ("role_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is not null'
|
|
124
|
+
}),
|
|
125
|
+
Index({
|
|
126
|
+
name: "role_perspectives_live_role_global_uq",
|
|
127
|
+
expression: 'create unique index "role_perspectives_live_role_global_uq" on "role_perspectives" ("role_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is null'
|
|
128
|
+
})
|
|
99
129
|
], RolePerspective);
|
|
100
130
|
export {
|
|
101
131
|
Perspective,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/perspectives/data/entities.ts"],
|
|
4
|
-
"sourcesContent": ["import { Entity, Index, PrimaryKey, Property
|
|
5
|
-
"mappings": ";;;;;;;;;;AAAA,SAAS,QAAQ,OAAO,YAAY,
|
|
4
|
+
"sourcesContent": ["import { Entity, Index, PrimaryKey, Property } from '@mikro-orm/decorators/legacy'\n\n@Entity({ tableName: 'perspectives' })\n@Index({ name: 'perspectives_user_scope_idx', properties: ['userId', 'tenantId', 'organizationId', 'tableId'] })\n// Live-row uniqueness is owned by partial indexes; ordinary unique decorators cannot express these scope rules.\n@Index({\n name: 'perspectives_live_user_org_uq',\n expression:\n 'create unique index \"perspectives_live_user_org_uq\" on \"perspectives\" (\"user_id\", \"tenant_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is not null',\n})\n@Index({\n name: 'perspectives_live_user_tenant_uq',\n expression:\n 'create unique index \"perspectives_live_user_tenant_uq\" on \"perspectives\" (\"user_id\", \"tenant_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is null',\n})\n@Index({\n name: 'perspectives_live_user_org_only_uq',\n expression:\n 'create unique index \"perspectives_live_user_org_only_uq\" on \"perspectives\" (\"user_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is not null',\n})\n@Index({\n name: 'perspectives_live_user_global_uq',\n expression:\n 'create unique index \"perspectives_live_user_global_uq\" on \"perspectives\" (\"user_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is null',\n})\nexport class Perspective {\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'user_id', type: 'uuid' })\n userId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid', nullable: true })\n tenantId?: string | null\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'table_id', type: 'text' })\n tableId!: string\n\n @Property({ type: 'text' })\n name!: string\n\n @Property({ name: 'settings_json', type: 'json' })\n settingsJson!: unknown\n\n @Property({ name: 'is_default', type: 'boolean', default: false })\n isDefault: boolean = false\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date(), nullable: true })\n updatedAt?: Date | null\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n@Entity({ tableName: 'role_perspectives' })\n@Index({ name: 'role_perspectives_role_scope_idx', properties: ['roleId', 'tenantId', 'organizationId', 'tableId'] })\n// Live-row uniqueness is owned by partial indexes; ordinary unique decorators cannot express these scope rules.\n@Index({\n name: 'role_perspectives_live_role_org_uq',\n expression:\n 'create unique index \"role_perspectives_live_role_org_uq\" on \"role_perspectives\" (\"role_id\", \"tenant_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is not null',\n})\n@Index({\n name: 'role_perspectives_live_role_tenant_uq',\n expression:\n 'create unique index \"role_perspectives_live_role_tenant_uq\" on \"role_perspectives\" (\"role_id\", \"tenant_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is null',\n})\n@Index({\n name: 'role_perspectives_live_role_org_only_uq',\n expression:\n 'create unique index \"role_perspectives_live_role_org_only_uq\" on \"role_perspectives\" (\"role_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is not null',\n})\n@Index({\n name: 'role_perspectives_live_role_global_uq',\n expression:\n 'create unique index \"role_perspectives_live_role_global_uq\" on \"role_perspectives\" (\"role_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is null',\n})\nexport class RolePerspective {\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'role_id', type: 'uuid' })\n roleId!: string\n\n @Property({ name: 'tenant_id', type: 'uuid', nullable: true })\n tenantId?: string | null\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'table_id', type: 'text' })\n tableId!: string\n\n @Property({ type: 'text' })\n name!: string\n\n @Property({ name: 'settings_json', type: 'json' })\n settingsJson!: unknown\n\n @Property({ name: 'is_default', type: 'boolean', default: false })\n isDefault: boolean = false\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date(), nullable: true })\n updatedAt?: Date | null\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;AAAA,SAAS,QAAQ,OAAO,YAAY,gBAAgB;AAyB7C,IAAM,cAAN,MAAkB;AAAA,EAAlB;AAuBL,qBAAqB;AAGrB,qBAAkB,oBAAI,KAAK;AAAA;AAO7B;AA/BE;AAAA,EADC,WAAW,EAAE,MAAM,QAAQ,YAAY,oBAAoB,CAAC;AAAA,GADlD,YAEX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,WAAW,MAAM,OAAO,CAAC;AAAA,GAJhC,YAKX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,a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,SAAS,EAAE,CAAC;AAAA,EAEnH,MAAM;AAAA,IACL,MAAM;AAAA,IACN,YACE;AAAA,EACJ,CAAC;AAAA,EACA,MAAM;AAAA,IACL,MAAM;AAAA,IACN,YACE;AAAA,EACJ,CAAC;AAAA,EACA,MAAM;AAAA,IACL,MAAM;AAAA,IACN,YACE;AAAA,EACJ,CAAC;AAAA,EACA,MAAM;AAAA,IACL,MAAM;AAAA,IACN,YACE;AAAA,EACJ,CAAC;AAAA,GACY;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Migration } from "@mikro-orm/migrations";
|
|
2
|
+
class Migration20260619120000_perspectives_live_row_uniqueness extends Migration {
|
|
3
|
+
async up() {
|
|
4
|
+
this.addSql(`
|
|
5
|
+
with ranked as (
|
|
6
|
+
select id,
|
|
7
|
+
row_number() over (
|
|
8
|
+
partition by user_id, tenant_id, organization_id, table_id, name
|
|
9
|
+
order by coalesce(updated_at, created_at) desc, created_at desc, id desc
|
|
10
|
+
) as rn
|
|
11
|
+
from perspectives
|
|
12
|
+
where deleted_at is null
|
|
13
|
+
)
|
|
14
|
+
update perspectives
|
|
15
|
+
set deleted_at = now(), is_default = false
|
|
16
|
+
from ranked
|
|
17
|
+
where perspectives.id = ranked.id and ranked.rn > 1;
|
|
18
|
+
`);
|
|
19
|
+
this.addSql(`alter table "perspectives" drop constraint if exists "perspectives_user_id_tenant_id_organization_id_ta_2d725_unique";`);
|
|
20
|
+
this.addSql(`alter table "perspectives" drop constraint if exists "perspectives_user_id_tenant_id_organization_id_ta_0c702_unique";`);
|
|
21
|
+
this.addSql(`create unique index if not exists "perspectives_live_user_org_uq" on "perspectives" ("user_id", "tenant_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is not null;`);
|
|
22
|
+
this.addSql(`create unique index if not exists "perspectives_live_user_tenant_uq" on "perspectives" ("user_id", "tenant_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is null;`);
|
|
23
|
+
this.addSql(`create unique index if not exists "perspectives_live_user_org_only_uq" on "perspectives" ("user_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is not null;`);
|
|
24
|
+
this.addSql(`create unique index if not exists "perspectives_live_user_global_uq" on "perspectives" ("user_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is null;`);
|
|
25
|
+
this.addSql(`
|
|
26
|
+
with ranked as (
|
|
27
|
+
select id,
|
|
28
|
+
row_number() over (
|
|
29
|
+
partition by role_id, tenant_id, organization_id, table_id, name
|
|
30
|
+
order by coalesce(updated_at, created_at) desc, created_at desc, id desc
|
|
31
|
+
) as rn
|
|
32
|
+
from role_perspectives
|
|
33
|
+
where deleted_at is null
|
|
34
|
+
)
|
|
35
|
+
update role_perspectives
|
|
36
|
+
set deleted_at = now(), is_default = false
|
|
37
|
+
from ranked
|
|
38
|
+
where role_perspectives.id = ranked.id and ranked.rn > 1;
|
|
39
|
+
`);
|
|
40
|
+
this.addSql(`alter table "role_perspectives" drop constraint if exists "role_perspectives_role_id_tenant_id_organization__c5467_unique";`);
|
|
41
|
+
this.addSql(`alter table "role_perspectives" drop constraint if exists "role_perspectives_role_id_tenant_id_organization__f0fc6_unique";`);
|
|
42
|
+
this.addSql(`create unique index if not exists "role_perspectives_live_role_org_uq" on "role_perspectives" ("role_id", "tenant_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is not null;`);
|
|
43
|
+
this.addSql(`create unique index if not exists "role_perspectives_live_role_tenant_uq" on "role_perspectives" ("role_id", "tenant_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is not null and "organization_id" is null;`);
|
|
44
|
+
this.addSql(`create unique index if not exists "role_perspectives_live_role_org_only_uq" on "role_perspectives" ("role_id", "organization_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is not null;`);
|
|
45
|
+
this.addSql(`create unique index if not exists "role_perspectives_live_role_global_uq" on "role_perspectives" ("role_id", "table_id", "name") where "deleted_at" is null and "tenant_id" is null and "organization_id" is null;`);
|
|
46
|
+
}
|
|
47
|
+
async down() {
|
|
48
|
+
this.addSql(`drop index if exists "perspectives_live_user_org_uq";`);
|
|
49
|
+
this.addSql(`drop index if exists "perspectives_live_user_tenant_uq";`);
|
|
50
|
+
this.addSql(`drop index if exists "perspectives_live_user_org_only_uq";`);
|
|
51
|
+
this.addSql(`drop index if exists "perspectives_live_user_global_uq";`);
|
|
52
|
+
this.addSql(`alter table "perspectives" add constraint "perspectives_user_id_tenant_id_organization_id_ta_2d725_unique" unique ("user_id", "tenant_id", "organization_id", "table_id", "name");`);
|
|
53
|
+
this.addSql(`drop index if exists "role_perspectives_live_role_org_uq";`);
|
|
54
|
+
this.addSql(`drop index if exists "role_perspectives_live_role_tenant_uq";`);
|
|
55
|
+
this.addSql(`drop index if exists "role_perspectives_live_role_org_only_uq";`);
|
|
56
|
+
this.addSql(`drop index if exists "role_perspectives_live_role_global_uq";`);
|
|
57
|
+
this.addSql(`alter table "role_perspectives" add constraint "role_perspectives_role_id_tenant_id_organization__c5467_unique" unique ("role_id", "tenant_id", "organization_id", "table_id", "name");`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export {
|
|
61
|
+
Migration20260619120000_perspectives_live_row_uniqueness
|
|
62
|
+
};
|
|
63
|
+
//# sourceMappingURL=Migration20260619120000_perspectives_live_row_uniqueness.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/perspectives/migrations/Migration20260619120000_perspectives_live_row_uniqueness.ts"],
|
|
4
|
+
"sourcesContent": ["import { Migration } from '@mikro-orm/migrations';\n\nexport class Migration20260619120000_perspectives_live_row_uniqueness extends Migration {\n\n override async up(): Promise<void> {\n this.addSql(`\n with ranked as (\n select id,\n row_number() over (\n partition by user_id, tenant_id, organization_id, table_id, name\n order by coalesce(updated_at, created_at) desc, created_at desc, id desc\n ) as rn\n from perspectives\n where deleted_at is null\n )\n update perspectives\n set deleted_at = now(), is_default = false\n from ranked\n where perspectives.id = ranked.id and ranked.rn > 1;\n `);\n this.addSql(`alter table \"perspectives\" drop constraint if exists \"perspectives_user_id_tenant_id_organization_id_ta_2d725_unique\";`);\n this.addSql(`alter table \"perspectives\" drop constraint if exists \"perspectives_user_id_tenant_id_organization_id_ta_0c702_unique\";`);\n this.addSql(`create unique index if not exists \"perspectives_live_user_org_uq\" on \"perspectives\" (\"user_id\", \"tenant_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is not null;`);\n this.addSql(`create unique index if not exists \"perspectives_live_user_tenant_uq\" on \"perspectives\" (\"user_id\", \"tenant_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is null;`);\n this.addSql(`create unique index if not exists \"perspectives_live_user_org_only_uq\" on \"perspectives\" (\"user_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is not null;`);\n this.addSql(`create unique index if not exists \"perspectives_live_user_global_uq\" on \"perspectives\" (\"user_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is null;`);\n\n this.addSql(`\n with ranked as (\n select id,\n row_number() over (\n partition by role_id, tenant_id, organization_id, table_id, name\n order by coalesce(updated_at, created_at) desc, created_at desc, id desc\n ) as rn\n from role_perspectives\n where deleted_at is null\n )\n update role_perspectives\n set deleted_at = now(), is_default = false\n from ranked\n where role_perspectives.id = ranked.id and ranked.rn > 1;\n `);\n this.addSql(`alter table \"role_perspectives\" drop constraint if exists \"role_perspectives_role_id_tenant_id_organization__c5467_unique\";`);\n this.addSql(`alter table \"role_perspectives\" drop constraint if exists \"role_perspectives_role_id_tenant_id_organization__f0fc6_unique\";`);\n this.addSql(`create unique index if not exists \"role_perspectives_live_role_org_uq\" on \"role_perspectives\" (\"role_id\", \"tenant_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is not null;`);\n this.addSql(`create unique index if not exists \"role_perspectives_live_role_tenant_uq\" on \"role_perspectives\" (\"role_id\", \"tenant_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is not null and \"organization_id\" is null;`);\n this.addSql(`create unique index if not exists \"role_perspectives_live_role_org_only_uq\" on \"role_perspectives\" (\"role_id\", \"organization_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is not null;`);\n this.addSql(`create unique index if not exists \"role_perspectives_live_role_global_uq\" on \"role_perspectives\" (\"role_id\", \"table_id\", \"name\") where \"deleted_at\" is null and \"tenant_id\" is null and \"organization_id\" is null;`);\n }\n\n override async down(): Promise<void> {\n this.addSql(`drop index if exists \"perspectives_live_user_org_uq\";`);\n this.addSql(`drop index if exists \"perspectives_live_user_tenant_uq\";`);\n this.addSql(`drop index if exists \"perspectives_live_user_org_only_uq\";`);\n this.addSql(`drop index if exists \"perspectives_live_user_global_uq\";`);\n this.addSql(`alter table \"perspectives\" add constraint \"perspectives_user_id_tenant_id_organization_id_ta_2d725_unique\" unique (\"user_id\", \"tenant_id\", \"organization_id\", \"table_id\", \"name\");`);\n\n this.addSql(`drop index if exists \"role_perspectives_live_role_org_uq\";`);\n this.addSql(`drop index if exists \"role_perspectives_live_role_tenant_uq\";`);\n this.addSql(`drop index if exists \"role_perspectives_live_role_org_only_uq\";`);\n this.addSql(`drop index if exists \"role_perspectives_live_role_global_uq\";`);\n this.addSql(`alter table \"role_perspectives\" add constraint \"role_perspectives_role_id_tenant_id_organization__c5467_unique\" unique (\"role_id\", \"tenant_id\", \"organization_id\", \"table_id\", \"name\");`);\n }\n\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAEnB,MAAM,iEAAiE,UAAU;AAAA,EAEtF,MAAe,KAAoB;AACjC,SAAK,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAcX;AACD,SAAK,OAAO,wHAAwH;AACpI,SAAK,OAAO,wHAAwH;AACpI,SAAK,OAAO,+OAA+O;AAC3P,SAAK,OAAO,2NAA2N;AACvO,SAAK,OAAO,mOAAmO;AAC/O,SAAK,OAAO,0MAA0M;AAEtN,SAAK,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAcX;AACD,SAAK,OAAO,6HAA6H;AACzI,SAAK,OAAO,6HAA6H;AACzI,SAAK,OAAO,yPAAyP;AACrQ,SAAK,OAAO,qOAAqO;AACjP,SAAK,OAAO,6OAA6O;AACzP,SAAK,OAAO,oNAAoN;AAAA,EAClO;AAAA,EAEA,MAAe,OAAsB;AACnC,SAAK,OAAO,uDAAuD;AACnE,SAAK,OAAO,0DAA0D;AACtE,SAAK,OAAO,4DAA4D;AACxE,SAAK,OAAO,0DAA0D;AACtE,SAAK,OAAO,oLAAoL;AAEhM,SAAK,OAAO,4DAA4D;AACxE,SAAK,OAAO,+DAA+D;AAC3E,SAAK,OAAO,iEAAiE;AAC7E,SAAK,OAAO,+DAA+D;AAC3E,SAAK,OAAO,yLAAyL;AAAA,EACvM;AAEF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -169,6 +169,23 @@ async function saveUserPerspective(em, cache, options) {
|
|
|
169
169
|
current: entity.updatedAt ?? null,
|
|
170
170
|
request: options.request ?? null
|
|
171
171
|
});
|
|
172
|
+
if (entity.name !== input.name) {
|
|
173
|
+
const duplicate = await em.findOne(Perspective, {
|
|
174
|
+
userId: scope.userId,
|
|
175
|
+
tenantId,
|
|
176
|
+
organizationId,
|
|
177
|
+
tableId,
|
|
178
|
+
name: input.name,
|
|
179
|
+
id: { $ne: entity.id },
|
|
180
|
+
deletedAt: null
|
|
181
|
+
});
|
|
182
|
+
if (duplicate) {
|
|
183
|
+
throw new CrudHttpError(409, {
|
|
184
|
+
error: "A view with this name already exists.",
|
|
185
|
+
code: "duplicate_name"
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
172
189
|
} else {
|
|
173
190
|
entity = await em.findOne(Perspective, {
|
|
174
191
|
userId: scope.userId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/perspectives/services/perspectiveService.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n buildOptimisticLockConflictBody,\n enforceCommandOptimisticLock,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { Perspective, RolePerspective } from '../data/entities'\nimport type {\n PerspectiveSettings,\n PerspectiveSaveInput,\n RolePerspectiveSaveInput,\n} from '../data/validators'\n\nexport type PerspectiveScope = {\n userId: string\n tenantId?: string | null\n organizationId?: string | null\n}\n\nexport type ResolvedPerspective = {\n id: string\n name: string\n tableId: string\n settings: PerspectiveSettings\n isDefault: boolean\n createdAt: string\n updatedAt?: string | null\n}\n\nexport type ResolvedRolePerspective = {\n id: string\n roleId: string\n tableId: string\n name: string\n settings: PerspectiveSettings\n isDefault: boolean\n tenantId: string | null\n organizationId: string | null\n createdAt: string\n updatedAt?: string | null\n}\n\nexport type PerspectivesState = {\n tableId: string\n personal: ResolvedPerspective[]\n personalDefaultId: string | null\n rolePerspectives: ResolvedRolePerspective[]\n}\n\ntype ExpectedUpdatedAtById = Record<string, string | Date | null | undefined>\n\nconst PERSPECTIVE_RESOURCE_KIND = 'perspectives.perspective'\nconst ROLE_PERSPECTIVE_RESOURCE_KIND = 'perspectives.role_perspective'\n\nfunction resolveRoleLockInput(\n expectedUpdatedAtByRoleId: ExpectedUpdatedAtById | null | undefined,\n roleId: string,\n request: Request | Headers | null | undefined,\n): Pick<Parameters<typeof enforceCommandOptimisticLock>[0], 'expected' | 'request'> {\n if (expectedUpdatedAtByRoleId && Object.prototype.hasOwnProperty.call(expectedUpdatedAtByRoleId, roleId)) {\n return { expected: expectedUpdatedAtByRoleId[roleId] ?? null, request: null }\n }\n return { expected: undefined, request: request ?? null }\n}\n\nfunction resolveRoleRecordLockInput(\n expectedUpdatedAtByPerspectiveId: ExpectedUpdatedAtById | null | undefined,\n expectedUpdatedAtByRoleId: ExpectedUpdatedAtById | null | undefined,\n record: RolePerspective,\n request: Request | Headers | null | undefined,\n): Pick<Parameters<typeof enforceCommandOptimisticLock>[0], 'expected' | 'request'> {\n if (expectedUpdatedAtByPerspectiveId && Object.prototype.hasOwnProperty.call(expectedUpdatedAtByPerspectiveId, record.id)) {\n return { expected: expectedUpdatedAtByPerspectiveId[record.id] ?? null, request: null }\n }\n return resolveRoleLockInput(expectedUpdatedAtByRoleId, record.roleId, request)\n}\n\nfunction firstExpectedUpdatedAt(expectedUpdatedAtById: ExpectedUpdatedAtById | null | undefined): string | Date | null {\n if (!expectedUpdatedAtById) return null\n for (const value of Object.values(expectedUpdatedAtById)) {\n if (value instanceof Date) return value\n if (typeof value === 'string' && value.trim().length > 0) return value\n }\n return null\n}\n\nfunction throwMissingRoleRecordVersionConflict(record: RolePerspective): never {\n const current = record.updatedAt instanceof Date && Number.isFinite(record.updatedAt.getTime())\n ? record.updatedAt.toISOString()\n : new Date(0).toISOString()\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(current, current))\n}\n\nconst CACHE_TTL_MS = 5 * 60 * 1000\n\nconst nullish = <T extends string | null | undefined>(value: T): string | null =>\n value == null ? null : value\n\nconst scopeKey = (scope: PerspectiveScope) =>\n `${scope.userId}:${scope.tenantId ?? 'null'}:${scope.organizationId ?? 'null'}`\n\nconst userCacheKey = (scope: PerspectiveScope, tableId: string, roleIds: string[]) =>\n `perspectives:user-state:${scopeKey(scope)}:${tableId}:${roleIds.sort((a, b) => a.localeCompare(b)).join(',')}`\n\nconst userTag = (scope: PerspectiveScope, tableId?: string) =>\n tableId\n ? `perspectives:user:${scopeKey(scope)}:${tableId}`\n : `perspectives:user:${scopeKey(scope)}`\n\nconst roleTag = (roleId: string, tableId?: string, tenantId?: string | null) => {\n const tenant = tenantId ?? 'null'\n return tableId ? `perspectives:role:${roleId}:${tenant}:${tableId}` : `perspectives:role:${roleId}:${tenant}`\n}\n\nfunction isResolvedPerspective(value: unknown): value is ResolvedPerspective {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<ResolvedPerspective>\n return typeof record.id === 'string'\n && typeof record.name === 'string'\n && typeof record.tableId === 'string'\n && typeof record.isDefault === 'boolean'\n && typeof record.createdAt === 'string'\n}\n\nfunction isResolvedRolePerspective(value: unknown): value is ResolvedRolePerspective {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<ResolvedRolePerspective>\n return typeof record.id === 'string'\n && typeof record.roleId === 'string'\n && typeof record.tableId === 'string'\n && typeof record.name === 'string'\n && typeof record.isDefault === 'boolean'\n && typeof record.createdAt === 'string'\n}\n\nfunction isPerspectivesState(value: unknown): value is PerspectivesState {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<PerspectivesState>\n if (typeof record.tableId !== 'string') return false\n if (!Array.isArray(record.personal) || record.personal.some((item) => !isResolvedPerspective(item))) return false\n if (record.personalDefaultId !== null && typeof record.personalDefaultId !== 'string') return false\n if (!Array.isArray(record.rolePerspectives) || record.rolePerspectives.some((item) => !isResolvedRolePerspective(item))) return false\n return true\n}\n\n/**\n * Defensive migration for legacy filter state shapes captured before the\n * advanced-filter tree (SPEC-048). Existing perspectives only store either\n * advanced-filter URL params (tree shape with `v:2` or a `root` key) or\n * undefined \u2014 this helper is a safety net for legacy `FilterValues`-shaped\n * records (flat key/value records of column filters) that could only appear\n * if old saved-view JSON were imported.\n *\n * - Tree-shaped state (`v:2` or `root` key) is passed through unchanged.\n * - Undefined / null filters are passed through unchanged.\n * - Legacy `FilterValues`-shaped records are dropped (set to `undefined`)\n * because there is no reliable mapping back to the new operator model;\n * the user sees an empty tree and can recreate.\n */\nexport function maybeMigrateLegacyFilterValues(settings: PerspectiveSettings): PerspectiveSettings {\n const filters = settings.filters\n if (!filters || typeof filters !== 'object') return settings\n const record = filters as Record<string, unknown>\n if ('v' in record && record.v === 2) return settings\n if ('root' in record) return settings\n if (typeof console !== 'undefined') {\n console.warn('[perspectives] Dropping legacy filterValues shape; please re-create the perspective with the new filter UI.')\n }\n return { ...settings, filters: undefined }\n}\n\nfunction toResolvedPerspective(entity: Perspective): ResolvedPerspective {\n const settings = maybeMigrateLegacyFilterValues((entity.settingsJson ?? {}) as PerspectiveSettings)\n return {\n id: entity.id,\n name: entity.name,\n tableId: entity.tableId,\n isDefault: !!entity.isDefault,\n settings,\n createdAt: entity.createdAt.toISOString(),\n updatedAt: entity.updatedAt ? entity.updatedAt.toISOString() : null,\n }\n}\n\nfunction toResolvedRolePerspective(entity: RolePerspective): ResolvedRolePerspective {\n const settings = maybeMigrateLegacyFilterValues((entity.settingsJson ?? {}) as PerspectiveSettings)\n return {\n id: entity.id,\n roleId: entity.roleId,\n tableId: entity.tableId,\n name: entity.name,\n isDefault: !!entity.isDefault,\n settings,\n tenantId: nullish(entity.tenantId),\n organizationId: nullish(entity.organizationId),\n createdAt: entity.createdAt.toISOString(),\n updatedAt: entity.updatedAt ? entity.updatedAt.toISOString() : null,\n }\n}\n\nexport async function loadPerspectivesState(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: { scope: PerspectiveScope; tableId: string; roleIds?: string[] },\n): Promise<PerspectivesState> {\n const { scope, tableId } = options\n const roleIds = Array.isArray(options.roleIds) ? options.roleIds.filter((id) => id && id.length > 0) : []\n const uniqueRoles = Array.from(new Set(roleIds))\n const cacheKey = cache && uniqueRoles.length <= 16 ? userCacheKey(scope, tableId, uniqueRoles) : null\n\n if (cache && cacheKey) {\n const cached = await cache.get(cacheKey)\n if (cached && isPerspectivesState(cached)) return cached\n }\n\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n\n const [personal, roleRecords] = await Promise.all([\n em.find(Perspective, {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n deletedAt: null,\n }, { orderBy: { updatedAt: 'desc' } }),\n uniqueRoles.length\n ? em.find(RolePerspective, {\n roleId: { $in: uniqueRoles as any },\n tableId,\n deletedAt: null,\n $and: [\n { $or: [{ tenantId }, { tenantId: null }] },\n { $or: [{ organizationId }, { organizationId: null }] },\n ],\n } as any, { orderBy: { updatedAt: 'desc' } })\n : [],\n ])\n\n const personalResolved = personal.map(toResolvedPerspective)\n const personalDefaultId = personalResolved.find((p) => p.isDefault)?.id ?? null\n const roleResolved = roleRecords.map(toResolvedRolePerspective)\n\n const state: PerspectivesState = {\n tableId,\n personal: personalResolved,\n personalDefaultId,\n rolePerspectives: roleResolved,\n }\n\n if (cache && cacheKey) {\n await cache.set(cacheKey, state, {\n ttl: CACHE_TTL_MS,\n tags: [\n userTag(scope, tableId),\n ...uniqueRoles.map((roleId) => roleTag(roleId, tableId, tenantId)),\n ],\n })\n }\n\n return state\n}\n\nexport async function saveUserPerspective(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n scope: PerspectiveScope\n tableId: string\n input: PerspectiveSaveInput\n request?: Request | Headers | null\n },\n): Promise<ResolvedPerspective> {\n const { scope, tableId, input } = options\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n\n let entity: Perspective | null = null\n if (input.perspectiveId) {\n entity = await em.findOne(Perspective, {\n id: input.perspectiveId,\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n deletedAt: null,\n })\n if (!entity) {\n throw Object.assign(new Error('Perspective not found'), { code: 'NOT_FOUND' })\n }\n enforceCommandOptimisticLock({\n resourceKind: PERSPECTIVE_RESOURCE_KIND,\n resourceId: entity.id,\n current: entity.updatedAt ?? null,\n request: options.request ?? null,\n })\n } else {\n entity = await em.findOne(Perspective, {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n name: input.name,\n deletedAt: null,\n })\n }\n\n const now = new Date()\n if (!entity) {\n entity = em.create(Perspective, {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n name: input.name,\n settingsJson: input.settings,\n isDefault: Boolean(input.isDefault),\n createdAt: now,\n updatedAt: now,\n })\n em.persist(entity)\n } else {\n entity.name = input.name\n entity.settingsJson = input.settings\n entity.updatedAt = now\n if (input.isDefault === true) entity.isDefault = true\n if (input.isDefault === false) entity.isDefault = false\n }\n\n if (input.isDefault === true) {\n await em.nativeUpdate(\n Perspective,\n {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n id: { $ne: entity.id } as any,\n deletedAt: null,\n },\n { isDefault: false, updatedAt: now },\n )\n entity.isDefault = true\n }\n\n await em.flush()\n\n if (cache?.deleteByTags) {\n await cache.deleteByTags([userTag(scope, tableId)])\n }\n\n return toResolvedPerspective(entity)\n}\n\nexport async function deleteUserPerspective(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n scope: PerspectiveScope\n tableId: string\n perspectiveId: string\n request?: Request | Headers | null\n },\n): Promise<boolean> {\n const { scope, tableId, perspectiveId } = options\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n\n const existing = await em.findOne(Perspective, {\n id: perspectiveId,\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n deletedAt: null,\n })\n if (!existing) {\n enforceRecordGoneIsConflict({\n resourceKind: PERSPECTIVE_RESOURCE_KIND,\n resourceId: perspectiveId,\n request: options.request ?? null,\n })\n return false\n }\n\n enforceCommandOptimisticLock({\n resourceKind: PERSPECTIVE_RESOURCE_KIND,\n resourceId: existing.id,\n current: existing.updatedAt ?? null,\n request: options.request ?? null,\n })\n\n existing.deletedAt = new Date()\n existing.isDefault = false\n await em.flush()\n\n if (cache?.deleteByTags) {\n await cache.deleteByTags([userTag(scope, tableId)])\n }\n\n return true\n}\n\nexport async function saveRolePerspectives(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n tableId: string\n tenantId?: string | null\n organizationId?: string | null\n input: RolePerspectiveSaveInput\n expectedUpdatedAtByRoleId?: ExpectedUpdatedAtById\n expectedUpdatedAtByPerspectiveId?: ExpectedUpdatedAtById\n request?: Request | Headers | null\n },\n): Promise<ResolvedRolePerspective[]> {\n const { tableId, input } = options\n const tenantId = options.tenantId ?? null\n const organizationId = options.organizationId ?? null\n const now = new Date()\n const touchedRoleIds = new Set<string>()\n\n const resultRecords: RolePerspective[] = []\n\n // Prefetch every matching role perspective in a single query, then index by role id\n // so the loop resolves create/update without a lookup per role.\n const recordByRole = new Map<string, RolePerspective>()\n if (input.roleIds.length) {\n const existingRecords = await em.find(RolePerspective, {\n roleId: { $in: input.roleIds },\n tableId,\n tenantId,\n organizationId,\n name: input.name,\n deletedAt: null,\n })\n for (const existing of existingRecords) recordByRole.set(existing.roleId, existing)\n }\n const defaultRecordsByRole = new Map<string, RolePerspective[]>()\n if (input.setDefault === true && input.roleIds.length) {\n const existingDefaultRecords = await em.find(RolePerspective, {\n roleId: { $in: input.roleIds },\n tableId,\n tenantId,\n organizationId,\n isDefault: true,\n deletedAt: null,\n })\n for (const existing of existingDefaultRecords) {\n const records = defaultRecordsByRole.get(existing.roleId) ?? []\n records.push(existing)\n defaultRecordsByRole.set(existing.roleId, records)\n }\n }\n\n for (const roleId of input.roleIds) {\n let record = recordByRole.get(roleId) ?? null\n if (!record) {\n record = em.create(RolePerspective, {\n roleId,\n tableId,\n tenantId,\n organizationId,\n name: input.name,\n settingsJson: input.settings,\n isDefault: Boolean(input.setDefault),\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n recordByRole.set(roleId, record)\n } else {\n enforceCommandOptimisticLock({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: record.id,\n current: record.updatedAt ?? null,\n ...resolveRoleRecordLockInput(\n options.expectedUpdatedAtByPerspectiveId,\n options.expectedUpdatedAtByRoleId,\n record,\n options.request ?? null,\n ),\n })\n record.settingsJson = input.settings\n record.updatedAt = now\n if (input.setDefault === true) record.isDefault = true\n if (input.setDefault === false) record.isDefault = false\n }\n\n if (input.setDefault === true) {\n for (const defaultRecord of defaultRecordsByRole.get(roleId) ?? []) {\n if (defaultRecord.id === record.id) continue\n enforceCommandOptimisticLock({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: defaultRecord.id,\n current: defaultRecord.updatedAt ?? null,\n ...resolveRoleRecordLockInput(\n options.expectedUpdatedAtByPerspectiveId,\n options.expectedUpdatedAtByRoleId,\n defaultRecord,\n options.request ?? null,\n ),\n })\n }\n await em.nativeUpdate(\n RolePerspective,\n {\n roleId,\n tableId,\n tenantId,\n organizationId,\n id: { $ne: record.id } as any,\n isDefault: true,\n deletedAt: null,\n },\n { isDefault: false, updatedAt: now },\n )\n record.isDefault = true\n }\n\n touchedRoleIds.add(roleId)\n resultRecords.push(record)\n }\n\n if (input.roleIds.length) {\n await em.flush()\n }\n\n if (cache?.deleteByTags && touchedRoleIds.size > 0) {\n const tags = Array.from(touchedRoleIds).map((roleId) => roleTag(roleId, tableId, tenantId))\n await cache.deleteByTags(tags)\n }\n\n return resultRecords.map(toResolvedRolePerspective)\n}\n\nexport async function clearRolePerspectives(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n tableId: string\n tenantId?: string | null\n organizationId?: string | null\n roleIds: string[]\n expectedUpdatedAtByRoleId?: ExpectedUpdatedAtById\n expectedUpdatedAtByPerspectiveId?: ExpectedUpdatedAtById\n request?: Request | Headers | null\n },\n): Promise<number> {\n const { tableId, roleIds } = options\n const tenantId = options.tenantId ?? null\n const organizationId = options.organizationId ?? null\n if (!roleIds.length) return 0\n\n const existingRecords = await em.find(RolePerspective, {\n roleId: { $in: roleIds as any },\n tableId,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n const recordsByRole = new Map<string, RolePerspective[]>()\n for (const record of existingRecords) {\n const records = recordsByRole.get(record.roleId) ?? []\n records.push(record)\n recordsByRole.set(record.roleId, records)\n }\n\n for (const roleId of roleIds) {\n const records = recordsByRole.get(roleId) ?? []\n const lockInput = resolveRoleLockInput(options.expectedUpdatedAtByRoleId, roleId, options.request ?? null)\n if (!records.length) {\n const expected = firstExpectedUpdatedAt(options.expectedUpdatedAtByPerspectiveId)\n enforceRecordGoneIsConflict({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: roleId,\n expected: expected ?? lockInput.expected,\n request: expected ? null : lockInput.request,\n })\n continue\n }\n for (const record of records) {\n if (\n options.expectedUpdatedAtByPerspectiveId\n && !Object.prototype.hasOwnProperty.call(options.expectedUpdatedAtByPerspectiveId, record.id)\n ) {\n throwMissingRoleRecordVersionConflict(record)\n }\n enforceCommandOptimisticLock({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: record.id,\n current: record.updatedAt ?? null,\n ...resolveRoleRecordLockInput(\n options.expectedUpdatedAtByPerspectiveId,\n options.expectedUpdatedAtByRoleId,\n record,\n options.request ?? null,\n ),\n })\n }\n }\n\n const affected = await em.nativeUpdate(\n RolePerspective,\n {\n roleId: { $in: roleIds as any },\n tableId,\n tenantId,\n organizationId,\n deletedAt: null,\n },\n { deletedAt: new Date(), isDefault: false },\n )\n\n if (cache?.deleteByTags) {\n const tags = roleIds.map((roleId) => roleTag(roleId, tableId, tenantId))\n await cache.deleteByTags(tags)\n }\n\n return affected\n}\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,uBAAuB;AA6C7C,MAAM,4BAA4B;AAClC,MAAM,iCAAiC;AAEvC,SAAS,qBACP,2BACA,QACA,SACkF;AAClF,MAAI,6BAA6B,OAAO,UAAU,eAAe,KAAK,2BAA2B,MAAM,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AU;AAAA,MACvC,CAAC;AACD;AAAA,IACF;AACA,eAAW,UAAU,SAAS;AAC5B,UACE,QAAQ,oCACL,CAAC,OAAO,UAAU,eAAe,KAAK,QAAQ,kCAAkC,OAAO,EAAE,GAC5F;AACA,8CAAsC,MAAM;AAAA,MAC9C;AACA,mCAA6B;AAAA,QAC3B,cAAc;AAAA,QACd,YAAY,OAAO;AAAA,QACnB,SAAS,OAAO,aAAa;AAAA,QAC7B,GAAG;AAAA,UACD,QAAQ;AAAA,UACR,QAAQ;AAAA,UACR;AAAA,UACA,QAAQ,WAAW;AAAA,QACrB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,GAAG;AAAA,IACxB;AAAA,IACA;AAAA,MACE,QAAQ,EAAE,KAAK,QAAe;AAAA,MAC9B;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,IACb;AAAA,IACA,EAAE,WAAW,oBAAI,KAAK,GAAG,WAAW,MAAM;AAAA,EAC5C;AAEA,MAAI,OAAO,cAAc;AACvB,UAAM,OAAO,QAAQ,IAAI,CAAC,WAAW,QAAQ,QAAQ,SAAS,QAAQ,CAAC;AACvE,UAAM,MAAM,aAAa,IAAI;AAAA,EAC/B;AAEA,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n buildOptimisticLockConflictBody,\n enforceCommandOptimisticLock,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { Perspective, RolePerspective } from '../data/entities'\nimport type {\n PerspectiveSettings,\n PerspectiveSaveInput,\n RolePerspectiveSaveInput,\n} from '../data/validators'\n\nexport type PerspectiveScope = {\n userId: string\n tenantId?: string | null\n organizationId?: string | null\n}\n\nexport type ResolvedPerspective = {\n id: string\n name: string\n tableId: string\n settings: PerspectiveSettings\n isDefault: boolean\n createdAt: string\n updatedAt?: string | null\n}\n\nexport type ResolvedRolePerspective = {\n id: string\n roleId: string\n tableId: string\n name: string\n settings: PerspectiveSettings\n isDefault: boolean\n tenantId: string | null\n organizationId: string | null\n createdAt: string\n updatedAt?: string | null\n}\n\nexport type PerspectivesState = {\n tableId: string\n personal: ResolvedPerspective[]\n personalDefaultId: string | null\n rolePerspectives: ResolvedRolePerspective[]\n}\n\ntype ExpectedUpdatedAtById = Record<string, string | Date | null | undefined>\n\nconst PERSPECTIVE_RESOURCE_KIND = 'perspectives.perspective'\nconst ROLE_PERSPECTIVE_RESOURCE_KIND = 'perspectives.role_perspective'\n\nfunction resolveRoleLockInput(\n expectedUpdatedAtByRoleId: ExpectedUpdatedAtById | null | undefined,\n roleId: string,\n request: Request | Headers | null | undefined,\n): Pick<Parameters<typeof enforceCommandOptimisticLock>[0], 'expected' | 'request'> {\n if (expectedUpdatedAtByRoleId && Object.prototype.hasOwnProperty.call(expectedUpdatedAtByRoleId, roleId)) {\n return { expected: expectedUpdatedAtByRoleId[roleId] ?? null, request: null }\n }\n return { expected: undefined, request: request ?? null }\n}\n\nfunction resolveRoleRecordLockInput(\n expectedUpdatedAtByPerspectiveId: ExpectedUpdatedAtById | null | undefined,\n expectedUpdatedAtByRoleId: ExpectedUpdatedAtById | null | undefined,\n record: RolePerspective,\n request: Request | Headers | null | undefined,\n): Pick<Parameters<typeof enforceCommandOptimisticLock>[0], 'expected' | 'request'> {\n if (expectedUpdatedAtByPerspectiveId && Object.prototype.hasOwnProperty.call(expectedUpdatedAtByPerspectiveId, record.id)) {\n return { expected: expectedUpdatedAtByPerspectiveId[record.id] ?? null, request: null }\n }\n return resolveRoleLockInput(expectedUpdatedAtByRoleId, record.roleId, request)\n}\n\nfunction firstExpectedUpdatedAt(expectedUpdatedAtById: ExpectedUpdatedAtById | null | undefined): string | Date | null {\n if (!expectedUpdatedAtById) return null\n for (const value of Object.values(expectedUpdatedAtById)) {\n if (value instanceof Date) return value\n if (typeof value === 'string' && value.trim().length > 0) return value\n }\n return null\n}\n\nfunction throwMissingRoleRecordVersionConflict(record: RolePerspective): never {\n const current = record.updatedAt instanceof Date && Number.isFinite(record.updatedAt.getTime())\n ? record.updatedAt.toISOString()\n : new Date(0).toISOString()\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(current, current))\n}\n\nconst CACHE_TTL_MS = 5 * 60 * 1000\n\nconst nullish = <T extends string | null | undefined>(value: T): string | null =>\n value == null ? null : value\n\nconst scopeKey = (scope: PerspectiveScope) =>\n `${scope.userId}:${scope.tenantId ?? 'null'}:${scope.organizationId ?? 'null'}`\n\nconst userCacheKey = (scope: PerspectiveScope, tableId: string, roleIds: string[]) =>\n `perspectives:user-state:${scopeKey(scope)}:${tableId}:${roleIds.sort((a, b) => a.localeCompare(b)).join(',')}`\n\nconst userTag = (scope: PerspectiveScope, tableId?: string) =>\n tableId\n ? `perspectives:user:${scopeKey(scope)}:${tableId}`\n : `perspectives:user:${scopeKey(scope)}`\n\nconst roleTag = (roleId: string, tableId?: string, tenantId?: string | null) => {\n const tenant = tenantId ?? 'null'\n return tableId ? `perspectives:role:${roleId}:${tenant}:${tableId}` : `perspectives:role:${roleId}:${tenant}`\n}\n\nfunction isResolvedPerspective(value: unknown): value is ResolvedPerspective {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<ResolvedPerspective>\n return typeof record.id === 'string'\n && typeof record.name === 'string'\n && typeof record.tableId === 'string'\n && typeof record.isDefault === 'boolean'\n && typeof record.createdAt === 'string'\n}\n\nfunction isResolvedRolePerspective(value: unknown): value is ResolvedRolePerspective {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<ResolvedRolePerspective>\n return typeof record.id === 'string'\n && typeof record.roleId === 'string'\n && typeof record.tableId === 'string'\n && typeof record.name === 'string'\n && typeof record.isDefault === 'boolean'\n && typeof record.createdAt === 'string'\n}\n\nfunction isPerspectivesState(value: unknown): value is PerspectivesState {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<PerspectivesState>\n if (typeof record.tableId !== 'string') return false\n if (!Array.isArray(record.personal) || record.personal.some((item) => !isResolvedPerspective(item))) return false\n if (record.personalDefaultId !== null && typeof record.personalDefaultId !== 'string') return false\n if (!Array.isArray(record.rolePerspectives) || record.rolePerspectives.some((item) => !isResolvedRolePerspective(item))) return false\n return true\n}\n\n/**\n * Defensive migration for legacy filter state shapes captured before the\n * advanced-filter tree (SPEC-048). Existing perspectives only store either\n * advanced-filter URL params (tree shape with `v:2` or a `root` key) or\n * undefined \u2014 this helper is a safety net for legacy `FilterValues`-shaped\n * records (flat key/value records of column filters) that could only appear\n * if old saved-view JSON were imported.\n *\n * - Tree-shaped state (`v:2` or `root` key) is passed through unchanged.\n * - Undefined / null filters are passed through unchanged.\n * - Legacy `FilterValues`-shaped records are dropped (set to `undefined`)\n * because there is no reliable mapping back to the new operator model;\n * the user sees an empty tree and can recreate.\n */\nexport function maybeMigrateLegacyFilterValues(settings: PerspectiveSettings): PerspectiveSettings {\n const filters = settings.filters\n if (!filters || typeof filters !== 'object') return settings\n const record = filters as Record<string, unknown>\n if ('v' in record && record.v === 2) return settings\n if ('root' in record) return settings\n if (typeof console !== 'undefined') {\n console.warn('[perspectives] Dropping legacy filterValues shape; please re-create the perspective with the new filter UI.')\n }\n return { ...settings, filters: undefined }\n}\n\nfunction toResolvedPerspective(entity: Perspective): ResolvedPerspective {\n const settings = maybeMigrateLegacyFilterValues((entity.settingsJson ?? {}) as PerspectiveSettings)\n return {\n id: entity.id,\n name: entity.name,\n tableId: entity.tableId,\n isDefault: !!entity.isDefault,\n settings,\n createdAt: entity.createdAt.toISOString(),\n updatedAt: entity.updatedAt ? entity.updatedAt.toISOString() : null,\n }\n}\n\nfunction toResolvedRolePerspective(entity: RolePerspective): ResolvedRolePerspective {\n const settings = maybeMigrateLegacyFilterValues((entity.settingsJson ?? {}) as PerspectiveSettings)\n return {\n id: entity.id,\n roleId: entity.roleId,\n tableId: entity.tableId,\n name: entity.name,\n isDefault: !!entity.isDefault,\n settings,\n tenantId: nullish(entity.tenantId),\n organizationId: nullish(entity.organizationId),\n createdAt: entity.createdAt.toISOString(),\n updatedAt: entity.updatedAt ? entity.updatedAt.toISOString() : null,\n }\n}\n\nexport async function loadPerspectivesState(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: { scope: PerspectiveScope; tableId: string; roleIds?: string[] },\n): Promise<PerspectivesState> {\n const { scope, tableId } = options\n const roleIds = Array.isArray(options.roleIds) ? options.roleIds.filter((id) => id && id.length > 0) : []\n const uniqueRoles = Array.from(new Set(roleIds))\n const cacheKey = cache && uniqueRoles.length <= 16 ? userCacheKey(scope, tableId, uniqueRoles) : null\n\n if (cache && cacheKey) {\n const cached = await cache.get(cacheKey)\n if (cached && isPerspectivesState(cached)) return cached\n }\n\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n\n const [personal, roleRecords] = await Promise.all([\n em.find(Perspective, {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n deletedAt: null,\n }, { orderBy: { updatedAt: 'desc' } }),\n uniqueRoles.length\n ? em.find(RolePerspective, {\n roleId: { $in: uniqueRoles as any },\n tableId,\n deletedAt: null,\n $and: [\n { $or: [{ tenantId }, { tenantId: null }] },\n { $or: [{ organizationId }, { organizationId: null }] },\n ],\n } as any, { orderBy: { updatedAt: 'desc' } })\n : [],\n ])\n\n const personalResolved = personal.map(toResolvedPerspective)\n const personalDefaultId = personalResolved.find((p) => p.isDefault)?.id ?? null\n const roleResolved = roleRecords.map(toResolvedRolePerspective)\n\n const state: PerspectivesState = {\n tableId,\n personal: personalResolved,\n personalDefaultId,\n rolePerspectives: roleResolved,\n }\n\n if (cache && cacheKey) {\n await cache.set(cacheKey, state, {\n ttl: CACHE_TTL_MS,\n tags: [\n userTag(scope, tableId),\n ...uniqueRoles.map((roleId) => roleTag(roleId, tableId, tenantId)),\n ],\n })\n }\n\n return state\n}\n\nexport async function saveUserPerspective(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n scope: PerspectiveScope\n tableId: string\n input: PerspectiveSaveInput\n request?: Request | Headers | null\n },\n): Promise<ResolvedPerspective> {\n const { scope, tableId, input } = options\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n\n let entity: Perspective | null = null\n if (input.perspectiveId) {\n entity = await em.findOne(Perspective, {\n id: input.perspectiveId,\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n deletedAt: null,\n })\n if (!entity) {\n throw Object.assign(new Error('Perspective not found'), { code: 'NOT_FOUND' })\n }\n enforceCommandOptimisticLock({\n resourceKind: PERSPECTIVE_RESOURCE_KIND,\n resourceId: entity.id,\n current: entity.updatedAt ?? null,\n request: options.request ?? null,\n })\n if (entity.name !== input.name) {\n const duplicate = await em.findOne(Perspective, {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n name: input.name,\n id: { $ne: entity.id } as any,\n deletedAt: null,\n })\n if (duplicate) {\n throw new CrudHttpError(409, {\n error: 'A view with this name already exists.',\n code: 'duplicate_name',\n })\n }\n }\n } else {\n entity = await em.findOne(Perspective, {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n name: input.name,\n deletedAt: null,\n })\n }\n\n const now = new Date()\n if (!entity) {\n entity = em.create(Perspective, {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n name: input.name,\n settingsJson: input.settings,\n isDefault: Boolean(input.isDefault),\n createdAt: now,\n updatedAt: now,\n })\n em.persist(entity)\n } else {\n entity.name = input.name\n entity.settingsJson = input.settings\n entity.updatedAt = now\n if (input.isDefault === true) entity.isDefault = true\n if (input.isDefault === false) entity.isDefault = false\n }\n\n if (input.isDefault === true) {\n await em.nativeUpdate(\n Perspective,\n {\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n id: { $ne: entity.id } as any,\n deletedAt: null,\n },\n { isDefault: false, updatedAt: now },\n )\n entity.isDefault = true\n }\n\n await em.flush()\n\n if (cache?.deleteByTags) {\n await cache.deleteByTags([userTag(scope, tableId)])\n }\n\n return toResolvedPerspective(entity)\n}\n\nexport async function deleteUserPerspective(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n scope: PerspectiveScope\n tableId: string\n perspectiveId: string\n request?: Request | Headers | null\n },\n): Promise<boolean> {\n const { scope, tableId, perspectiveId } = options\n const tenantId = scope.tenantId ?? null\n const organizationId = scope.organizationId ?? null\n\n const existing = await em.findOne(Perspective, {\n id: perspectiveId,\n userId: scope.userId,\n tenantId,\n organizationId,\n tableId,\n deletedAt: null,\n })\n if (!existing) {\n enforceRecordGoneIsConflict({\n resourceKind: PERSPECTIVE_RESOURCE_KIND,\n resourceId: perspectiveId,\n request: options.request ?? null,\n })\n return false\n }\n\n enforceCommandOptimisticLock({\n resourceKind: PERSPECTIVE_RESOURCE_KIND,\n resourceId: existing.id,\n current: existing.updatedAt ?? null,\n request: options.request ?? null,\n })\n\n existing.deletedAt = new Date()\n existing.isDefault = false\n await em.flush()\n\n if (cache?.deleteByTags) {\n await cache.deleteByTags([userTag(scope, tableId)])\n }\n\n return true\n}\n\nexport async function saveRolePerspectives(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n tableId: string\n tenantId?: string | null\n organizationId?: string | null\n input: RolePerspectiveSaveInput\n expectedUpdatedAtByRoleId?: ExpectedUpdatedAtById\n expectedUpdatedAtByPerspectiveId?: ExpectedUpdatedAtById\n request?: Request | Headers | null\n },\n): Promise<ResolvedRolePerspective[]> {\n const { tableId, input } = options\n const tenantId = options.tenantId ?? null\n const organizationId = options.organizationId ?? null\n const now = new Date()\n const touchedRoleIds = new Set<string>()\n\n const resultRecords: RolePerspective[] = []\n\n // Prefetch every matching role perspective in a single query, then index by role id\n // so the loop resolves create/update without a lookup per role.\n const recordByRole = new Map<string, RolePerspective>()\n if (input.roleIds.length) {\n const existingRecords = await em.find(RolePerspective, {\n roleId: { $in: input.roleIds },\n tableId,\n tenantId,\n organizationId,\n name: input.name,\n deletedAt: null,\n })\n for (const existing of existingRecords) recordByRole.set(existing.roleId, existing)\n }\n const defaultRecordsByRole = new Map<string, RolePerspective[]>()\n if (input.setDefault === true && input.roleIds.length) {\n const existingDefaultRecords = await em.find(RolePerspective, {\n roleId: { $in: input.roleIds },\n tableId,\n tenantId,\n organizationId,\n isDefault: true,\n deletedAt: null,\n })\n for (const existing of existingDefaultRecords) {\n const records = defaultRecordsByRole.get(existing.roleId) ?? []\n records.push(existing)\n defaultRecordsByRole.set(existing.roleId, records)\n }\n }\n\n for (const roleId of input.roleIds) {\n let record = recordByRole.get(roleId) ?? null\n if (!record) {\n record = em.create(RolePerspective, {\n roleId,\n tableId,\n tenantId,\n organizationId,\n name: input.name,\n settingsJson: input.settings,\n isDefault: Boolean(input.setDefault),\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n recordByRole.set(roleId, record)\n } else {\n enforceCommandOptimisticLock({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: record.id,\n current: record.updatedAt ?? null,\n ...resolveRoleRecordLockInput(\n options.expectedUpdatedAtByPerspectiveId,\n options.expectedUpdatedAtByRoleId,\n record,\n options.request ?? null,\n ),\n })\n record.settingsJson = input.settings\n record.updatedAt = now\n if (input.setDefault === true) record.isDefault = true\n if (input.setDefault === false) record.isDefault = false\n }\n\n if (input.setDefault === true) {\n for (const defaultRecord of defaultRecordsByRole.get(roleId) ?? []) {\n if (defaultRecord.id === record.id) continue\n enforceCommandOptimisticLock({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: defaultRecord.id,\n current: defaultRecord.updatedAt ?? null,\n ...resolveRoleRecordLockInput(\n options.expectedUpdatedAtByPerspectiveId,\n options.expectedUpdatedAtByRoleId,\n defaultRecord,\n options.request ?? null,\n ),\n })\n }\n await em.nativeUpdate(\n RolePerspective,\n {\n roleId,\n tableId,\n tenantId,\n organizationId,\n id: { $ne: record.id } as any,\n isDefault: true,\n deletedAt: null,\n },\n { isDefault: false, updatedAt: now },\n )\n record.isDefault = true\n }\n\n touchedRoleIds.add(roleId)\n resultRecords.push(record)\n }\n\n if (input.roleIds.length) {\n await em.flush()\n }\n\n if (cache?.deleteByTags && touchedRoleIds.size > 0) {\n const tags = Array.from(touchedRoleIds).map((roleId) => roleTag(roleId, tableId, tenantId))\n await cache.deleteByTags(tags)\n }\n\n return resultRecords.map(toResolvedRolePerspective)\n}\n\nexport async function clearRolePerspectives(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: {\n tableId: string\n tenantId?: string | null\n organizationId?: string | null\n roleIds: string[]\n expectedUpdatedAtByRoleId?: ExpectedUpdatedAtById\n expectedUpdatedAtByPerspectiveId?: ExpectedUpdatedAtById\n request?: Request | Headers | null\n },\n): Promise<number> {\n const { tableId, roleIds } = options\n const tenantId = options.tenantId ?? null\n const organizationId = options.organizationId ?? null\n if (!roleIds.length) return 0\n\n const existingRecords = await em.find(RolePerspective, {\n roleId: { $in: roleIds as any },\n tableId,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n const recordsByRole = new Map<string, RolePerspective[]>()\n for (const record of existingRecords) {\n const records = recordsByRole.get(record.roleId) ?? []\n records.push(record)\n recordsByRole.set(record.roleId, records)\n }\n\n for (const roleId of roleIds) {\n const records = recordsByRole.get(roleId) ?? []\n const lockInput = resolveRoleLockInput(options.expectedUpdatedAtByRoleId, roleId, options.request ?? null)\n if (!records.length) {\n const expected = firstExpectedUpdatedAt(options.expectedUpdatedAtByPerspectiveId)\n enforceRecordGoneIsConflict({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: roleId,\n expected: expected ?? lockInput.expected,\n request: expected ? null : lockInput.request,\n })\n continue\n }\n for (const record of records) {\n if (\n options.expectedUpdatedAtByPerspectiveId\n && !Object.prototype.hasOwnProperty.call(options.expectedUpdatedAtByPerspectiveId, record.id)\n ) {\n throwMissingRoleRecordVersionConflict(record)\n }\n enforceCommandOptimisticLock({\n resourceKind: ROLE_PERSPECTIVE_RESOURCE_KIND,\n resourceId: record.id,\n current: record.updatedAt ?? null,\n ...resolveRoleRecordLockInput(\n options.expectedUpdatedAtByPerspectiveId,\n options.expectedUpdatedAtByRoleId,\n record,\n options.request ?? null,\n ),\n })\n }\n }\n\n const affected = await em.nativeUpdate(\n RolePerspective,\n {\n roleId: { $in: roleIds as any },\n tableId,\n tenantId,\n organizationId,\n deletedAt: null,\n },\n { deletedAt: new Date(), isDefault: false },\n )\n\n if (cache?.deleteByTags) {\n const tags = roleIds.map((roleId) => roleTag(roleId, tableId, tenantId))\n await cache.deleteByTags(tags)\n }\n\n return affected\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,uBAAuB;AA6C7C,MAAM,4BAA4B;AAClC,MAAM,iCAAiC;AAEvC,SAAS,qBACP,2BACA,QACA,SACkF;AAClF,MAAI,6BAA6B,OAAO,UAAU,eAAe,KAAK,2BAA2B,MAAM,GAAG;AACxG,WAAO,EAAE,UAAU,0BAA0B,MAAM,KAAK,MAAM,SAAS,KAAK;AAAA,EAC9E;AACA,SAAO,EAAE,UAAU,QAAW,SAAS,WAAW,KAAK;AACzD;AAEA,SAAS,2BACP,kCACA,2BACA,QACA,SACkF;AAClF,MAAI,oCAAoC,OAAO,UAAU,eAAe,KAAK,kCAAkC,OAAO,EAAE,GAAG;AACzH,WAAO,EAAE,UAAU,iCAAiC,OAAO,EAAE,KAAK,MAAM,SAAS,KAAK;AAAA,EACxF;AACA,SAAO,qBAAqB,2BAA2B,OAAO,QAAQ,OAAO;AAC/E;AAEA,SAAS,uBAAuB,uBAAuF;AACrH,MAAI,CAAC,sBAAuB,QAAO;AACnC,aAAW,SAAS,OAAO,OAAO,qBAAqB,GAAG;AACxD,QAAI,iBAAiB,KAAM,QAAO;AAClC,QAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,EAAG,QAAO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YAAY,OAAO;AAAA,QACnB,SAAS,OAAO,aAAa;AAAA,QAC7B,GAAG;AAAA,UACD,QAAQ;AAAA,UACR,QAAQ;AAAA,UACR;AAAA,UACA,QAAQ,WAAW;AAAA,QACrB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,GAAG;AAAA,IACxB;AAAA,IACA;AAAA,MACE,QAAQ,EAAE,KAAK,QAAe;AAAA,MAC9B;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,IACb;AAAA,IACA,EAAE,WAAW,oBAAI,KAAK,GAAG,WAAW,MAAM;AAAA,EAC5C;AAEA,MAAI,OAAO,cAAc;AACvB,UAAM,OAAO,QAAQ,IAAI,CAAC,WAAW,QAAQ,QAAQ,SAAS,QAAQ,CAAC;AACvE,UAAM,MAAM,aAAa,IAAI;AAAA,EAC/B;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import { registerCommand } from "@open-mercato/shared/lib/commands";
|
|
2
2
|
import { parseAvailabilityRuleWindow } from "@open-mercato/core/modules/planner/lib/availabilitySchedule";
|
|
3
|
-
import { PlannerAvailabilityRule } from "../data/entities.js";
|
|
3
|
+
import { PlannerAvailabilityRule, PlannerAvailabilityRuleSet } from "../data/entities.js";
|
|
4
4
|
import {
|
|
5
5
|
plannerAvailabilityWeeklyReplaceSchema
|
|
6
6
|
} from "../data/validators.js";
|
|
7
7
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
8
|
+
import {
|
|
9
|
+
enforceCommandOptimisticLock,
|
|
10
|
+
enforceRecordGoneIsConflict
|
|
11
|
+
} from "@open-mercato/shared/lib/crud/optimistic-lock-command";
|
|
8
12
|
import { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from "./shared.js";
|
|
9
13
|
const AVAILABILITY_RULE_RESOURCE_KIND = "planner.availability.rule";
|
|
14
|
+
const AVAILABILITY_RULE_SET_RESOURCE_KIND = "planner.availability.rule.set";
|
|
10
15
|
const DAY_CODES = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
|
|
11
16
|
function parseTimeInput(value) {
|
|
12
17
|
const [hours, minutes] = value.split(":").map((part) => Number(part));
|
|
@@ -121,6 +126,29 @@ const replaceWeeklyAvailabilityCommand = {
|
|
|
121
126
|
const em = ctx.container.resolve("em").fork();
|
|
122
127
|
const now = /* @__PURE__ */ new Date();
|
|
123
128
|
await em.transactional(async (trx) => {
|
|
129
|
+
let ruleSet = null;
|
|
130
|
+
if (parsed.subjectType === "ruleset") {
|
|
131
|
+
ruleSet = await trx.findOne(PlannerAvailabilityRuleSet, {
|
|
132
|
+
id: parsed.subjectId,
|
|
133
|
+
tenantId: parsed.tenantId,
|
|
134
|
+
organizationId: parsed.organizationId,
|
|
135
|
+
deletedAt: null
|
|
136
|
+
});
|
|
137
|
+
if (ruleSet) {
|
|
138
|
+
enforceCommandOptimisticLock({
|
|
139
|
+
resourceKind: AVAILABILITY_RULE_SET_RESOURCE_KIND,
|
|
140
|
+
resourceId: ruleSet.id,
|
|
141
|
+
current: ruleSet.updatedAt,
|
|
142
|
+
request: ctx.request ?? null
|
|
143
|
+
});
|
|
144
|
+
} else {
|
|
145
|
+
enforceRecordGoneIsConflict({
|
|
146
|
+
resourceKind: AVAILABILITY_RULE_SET_RESOURCE_KIND,
|
|
147
|
+
resourceId: parsed.subjectId,
|
|
148
|
+
request: ctx.request ?? null
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
124
152
|
const existing = await trx.find(PlannerAvailabilityRule, {
|
|
125
153
|
tenantId: parsed.tenantId,
|
|
126
154
|
organizationId: parsed.organizationId,
|
|
@@ -159,6 +187,10 @@ const replaceWeeklyAvailabilityCommand = {
|
|
|
159
187
|
});
|
|
160
188
|
trx.persist(record);
|
|
161
189
|
});
|
|
190
|
+
if (ruleSet) {
|
|
191
|
+
ruleSet.updatedAt = now;
|
|
192
|
+
trx.persist(ruleSet);
|
|
193
|
+
}
|
|
162
194
|
await trx.flush();
|
|
163
195
|
});
|
|
164
196
|
return { ok: true };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/planner/commands/availability-weekly.ts"],
|
|
4
|
-
"sourcesContent": ["import type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { parseAvailabilityRuleWindow } from '@open-mercato/core/modules/planner/lib/availabilitySchedule'\nimport { PlannerAvailabilityRule } from '../data/entities'\nimport {\n plannerAvailabilityWeeklyReplaceSchema,\n type PlannerAvailabilityWeeklyReplaceInput,\n} from '../data/validators'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { PlannerAvailabilityKind, PlannerAvailabilitySubjectType } from '../data/entities'\nimport { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'\n\nconst AVAILABILITY_RULE_RESOURCE_KIND = 'planner.availability.rule'\n\nconst DAY_CODES = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']\n\ntype AvailabilityRuleSnapshot = {\n id: string\n tenantId: string\n organizationId: string\n subjectType: PlannerAvailabilitySubjectType\n subjectId: string\n timezone: string\n rrule: string\n exdates: string[]\n kind: PlannerAvailabilityKind\n note: string | null\n deletedAt: Date | null\n}\n\ntype WeeklyUndoPayload = {\n before: AvailabilityRuleSnapshot[]\n after: AvailabilityRuleSnapshot[]\n}\n\nfunction parseTimeInput(value: string): { hours: number; minutes: number } | null {\n const [hours, minutes] = value.split(':').map((part) => Number(part))\n if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null\n if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null\n return { hours, minutes }\n}\n\nfunction toDateForWeekday(weekday: number, time: string): Date | null {\n const parsed = parseTimeInput(time)\n if (!parsed) return null\n const now = new Date()\n const base = new Date(now.getFullYear(), now.getMonth(), now.getDate())\n const diff = (weekday - base.getDay() + 7) % 7\n const target = new Date(base.getTime() + diff * 24 * 60 * 60 * 1000)\n target.setHours(parsed.hours, parsed.minutes, 0, 0)\n return target\n}\n\nfunction formatDuration(minutes: number): string {\n const clamped = Math.max(1, minutes)\n const hours = Math.floor(clamped / 60)\n const mins = clamped % 60\n if (hours > 0 && mins > 0) return `PT${hours}H${mins}M`\n if (hours > 0) return `PT${hours}H`\n return `PT${mins}M`\n}\n\nfunction buildWeeklyRrule(start: Date, end: Date): string {\n const dtStart = start.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z'\n const durationMinutes = Math.max(1, Math.round((end.getTime() - start.getTime()) / 60000))\n const duration = formatDuration(durationMinutes)\n const dayCode = DAY_CODES[start.getDay()] ?? 'MO'\n return `DTSTART:${dtStart}\\nDURATION:${duration}\\nRRULE:FREQ=WEEKLY;BYDAY=${dayCode}`\n}\n\nfunction toAvailabilityRuleSnapshot(record: PlannerAvailabilityRule): AvailabilityRuleSnapshot {\n return {\n id: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n subjectType: record.subjectType,\n subjectId: record.subjectId,\n timezone: record.timezone,\n rrule: record.rrule,\n exdates: [...(record.exdates ?? [])],\n kind: record.kind,\n note: record.note ?? null,\n deletedAt: record.deletedAt ?? null,\n }\n}\n\nasync function loadWeeklySnapshots(\n em: EntityManager,\n params: {\n tenantId: string\n organizationId: string\n subjectType: PlannerAvailabilitySubjectType\n subjectId: string\n }\n): Promise<AvailabilityRuleSnapshot[]> {\n const existing = await em.find(PlannerAvailabilityRule, {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n subjectType: params.subjectType,\n subjectId: params.subjectId,\n deletedAt: null,\n })\n return existing\n .filter((rule) => {\n const repeat = parseAvailabilityRuleWindow(rule).repeat\n return repeat === 'weekly' || repeat === 'daily'\n })\n .map(toAvailabilityRuleSnapshot)\n}\n\nasync function restoreAvailabilityRuleFromSnapshot(em: EntityManager, snapshot: AvailabilityRuleSnapshot): Promise<void> {\n let record = await em.findOne(PlannerAvailabilityRule, { id: snapshot.id })\n if (!record) {\n record = em.create(PlannerAvailabilityRule, {\n id: snapshot.id,\n tenantId: snapshot.tenantId,\n organizationId: snapshot.organizationId,\n subjectType: snapshot.subjectType,\n subjectId: snapshot.subjectId,\n timezone: snapshot.timezone,\n rrule: snapshot.rrule,\n exdates: snapshot.exdates ?? [],\n kind: snapshot.kind ?? 'availability',\n note: snapshot.note ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n deletedAt: snapshot.deletedAt ?? null,\n })\n em.persist(record)\n } else {\n record.subjectType = snapshot.subjectType\n record.subjectId = snapshot.subjectId\n record.timezone = snapshot.timezone\n record.rrule = snapshot.rrule\n record.exdates = snapshot.exdates ?? []\n record.kind = snapshot.kind ?? 'availability'\n record.note = snapshot.note ?? null\n record.deletedAt = snapshot.deletedAt ?? null\n }\n}\n\nconst replaceWeeklyAvailabilityCommand: CommandHandler<PlannerAvailabilityWeeklyReplaceInput, { ok: true }> = {\n id: 'planner.availability.weekly.replace',\n async prepare(input, ctx) {\n const parsed = plannerAvailabilityWeeklyReplaceSchema.parse(input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager)\n const before = await loadWeeklySnapshots(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n })\n return { before }\n },\n async execute(input, ctx) {\n const parsed = plannerAvailabilityWeeklyReplaceSchema.parse(input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const now = new Date()\n\n await em.transactional(async (trx) => {\n const existing = await trx.find(PlannerAvailabilityRule, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n deletedAt: null,\n })\n\n const toDelete = existing.filter((rule) => {\n const repeat = parseAvailabilityRuleWindow(rule).repeat\n return repeat === 'weekly' || repeat === 'daily'\n })\n\n toDelete.forEach((rule) => {\n rule.deletedAt = now\n rule.updatedAt = now\n })\n\n if (toDelete.length) {\n trx.persist(toDelete)\n }\n\n parsed.windows.forEach((window) => {\n const start = toDateForWeekday(window.weekday, window.start)\n const end = toDateForWeekday(window.weekday, window.end)\n if (!start || !end || start >= end) return\n const rrule = buildWeeklyRrule(start, end)\n const record = trx.create(PlannerAvailabilityRule, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n timezone: parsed.timezone,\n rrule,\n exdates: [],\n kind: 'availability',\n note: null,\n createdAt: now,\n updatedAt: now,\n })\n trx.persist(record)\n })\n\n await trx.flush()\n })\n\n return { ok: true }\n },\n buildLog: async ({ input, snapshots, ctx }) => {\n const parsed = plannerAvailabilityWeeklyReplaceSchema.parse(input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const after = await loadWeeklySnapshots(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n })\n const before = (snapshots.before as AvailabilityRuleSnapshot[] | undefined) ?? []\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('planner.audit.availability.weekly.replace', 'Replace weekly availability'),\n resourceKind: AVAILABILITY_RULE_RESOURCE_KIND,\n resourceId: null,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: {\n before,\n after,\n } satisfies WeeklyUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<WeeklyUndoPayload>(logEntry)\n const before = payload?.before ?? []\n const after = payload?.after ?? []\n if (!before.length && !after.length) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n await em.transactional(async (trx) => {\n if (after.length) {\n const ids = after.map((rule) => rule.id)\n const records = await trx.find(PlannerAvailabilityRule, { id: { $in: ids } })\n records.forEach((record) => {\n record.deletedAt = new Date()\n })\n if (records.length) trx.persist(records)\n }\n\n for (const snapshot of before) {\n await restoreAvailabilityRuleFromSnapshot(trx, { ...snapshot, deletedAt: null })\n }\n\n await trx.flush()\n })\n },\n}\n\nregisterCommand(replaceWeeklyAvailabilityCommand)\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,uBAAuB;AAEhC,SAAS,mCAAmC;AAC5C,SAAS
|
|
4
|
+
"sourcesContent": ["import type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { parseAvailabilityRuleWindow } from '@open-mercato/core/modules/planner/lib/availabilitySchedule'\nimport { PlannerAvailabilityRule, PlannerAvailabilityRuleSet } from '../data/entities'\nimport {\n plannerAvailabilityWeeklyReplaceSchema,\n type PlannerAvailabilityWeeklyReplaceInput,\n} from '../data/validators'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { PlannerAvailabilityKind, PlannerAvailabilitySubjectType } from '../data/entities'\nimport {\n enforceCommandOptimisticLock,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'\n\nconst AVAILABILITY_RULE_RESOURCE_KIND = 'planner.availability.rule'\n\n// Canonical resource kind for the parent rule set, matching the tag the CRUD\n// factory derives for `planner.availability-rule-sets.*` commands. Weekly\n// replace mutates the rule set's child `availability_rules`, so the parent is\n// the optimistic-lock consistency boundary (document-aggregate pattern).\nconst AVAILABILITY_RULE_SET_RESOURCE_KIND = 'planner.availability.rule.set'\n\nconst DAY_CODES = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA']\n\ntype AvailabilityRuleSnapshot = {\n id: string\n tenantId: string\n organizationId: string\n subjectType: PlannerAvailabilitySubjectType\n subjectId: string\n timezone: string\n rrule: string\n exdates: string[]\n kind: PlannerAvailabilityKind\n note: string | null\n deletedAt: Date | null\n}\n\ntype WeeklyUndoPayload = {\n before: AvailabilityRuleSnapshot[]\n after: AvailabilityRuleSnapshot[]\n}\n\nfunction parseTimeInput(value: string): { hours: number; minutes: number } | null {\n const [hours, minutes] = value.split(':').map((part) => Number(part))\n if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null\n if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null\n return { hours, minutes }\n}\n\nfunction toDateForWeekday(weekday: number, time: string): Date | null {\n const parsed = parseTimeInput(time)\n if (!parsed) return null\n const now = new Date()\n const base = new Date(now.getFullYear(), now.getMonth(), now.getDate())\n const diff = (weekday - base.getDay() + 7) % 7\n const target = new Date(base.getTime() + diff * 24 * 60 * 60 * 1000)\n target.setHours(parsed.hours, parsed.minutes, 0, 0)\n return target\n}\n\nfunction formatDuration(minutes: number): string {\n const clamped = Math.max(1, minutes)\n const hours = Math.floor(clamped / 60)\n const mins = clamped % 60\n if (hours > 0 && mins > 0) return `PT${hours}H${mins}M`\n if (hours > 0) return `PT${hours}H`\n return `PT${mins}M`\n}\n\nfunction buildWeeklyRrule(start: Date, end: Date): string {\n const dtStart = start.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z'\n const durationMinutes = Math.max(1, Math.round((end.getTime() - start.getTime()) / 60000))\n const duration = formatDuration(durationMinutes)\n const dayCode = DAY_CODES[start.getDay()] ?? 'MO'\n return `DTSTART:${dtStart}\\nDURATION:${duration}\\nRRULE:FREQ=WEEKLY;BYDAY=${dayCode}`\n}\n\nfunction toAvailabilityRuleSnapshot(record: PlannerAvailabilityRule): AvailabilityRuleSnapshot {\n return {\n id: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n subjectType: record.subjectType,\n subjectId: record.subjectId,\n timezone: record.timezone,\n rrule: record.rrule,\n exdates: [...(record.exdates ?? [])],\n kind: record.kind,\n note: record.note ?? null,\n deletedAt: record.deletedAt ?? null,\n }\n}\n\nasync function loadWeeklySnapshots(\n em: EntityManager,\n params: {\n tenantId: string\n organizationId: string\n subjectType: PlannerAvailabilitySubjectType\n subjectId: string\n }\n): Promise<AvailabilityRuleSnapshot[]> {\n const existing = await em.find(PlannerAvailabilityRule, {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n subjectType: params.subjectType,\n subjectId: params.subjectId,\n deletedAt: null,\n })\n return existing\n .filter((rule) => {\n const repeat = parseAvailabilityRuleWindow(rule).repeat\n return repeat === 'weekly' || repeat === 'daily'\n })\n .map(toAvailabilityRuleSnapshot)\n}\n\nasync function restoreAvailabilityRuleFromSnapshot(em: EntityManager, snapshot: AvailabilityRuleSnapshot): Promise<void> {\n let record = await em.findOne(PlannerAvailabilityRule, { id: snapshot.id })\n if (!record) {\n record = em.create(PlannerAvailabilityRule, {\n id: snapshot.id,\n tenantId: snapshot.tenantId,\n organizationId: snapshot.organizationId,\n subjectType: snapshot.subjectType,\n subjectId: snapshot.subjectId,\n timezone: snapshot.timezone,\n rrule: snapshot.rrule,\n exdates: snapshot.exdates ?? [],\n kind: snapshot.kind ?? 'availability',\n note: snapshot.note ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n deletedAt: snapshot.deletedAt ?? null,\n })\n em.persist(record)\n } else {\n record.subjectType = snapshot.subjectType\n record.subjectId = snapshot.subjectId\n record.timezone = snapshot.timezone\n record.rrule = snapshot.rrule\n record.exdates = snapshot.exdates ?? []\n record.kind = snapshot.kind ?? 'availability'\n record.note = snapshot.note ?? null\n record.deletedAt = snapshot.deletedAt ?? null\n }\n}\n\nconst replaceWeeklyAvailabilityCommand: CommandHandler<PlannerAvailabilityWeeklyReplaceInput, { ok: true }> = {\n id: 'planner.availability.weekly.replace',\n async prepare(input, ctx) {\n const parsed = plannerAvailabilityWeeklyReplaceSchema.parse(input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager)\n const before = await loadWeeklySnapshots(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n })\n return { before }\n },\n async execute(input, ctx) {\n const parsed = plannerAvailabilityWeeklyReplaceSchema.parse(input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const now = new Date()\n\n await em.transactional(async (trx) => {\n // The weekly rules of a rule set are a sub-resource of that rule set: the\n // parent is the optimistic-lock consistency boundary. Guard the parent's\n // version (so a stale weekly save loses to a concurrent rule-set\n // change/delete) and bump its `updated_at` after the replace (so a\n // concurrent rule-set delete/update with a stale token conflicts). See #2927.\n let ruleSet: PlannerAvailabilityRuleSet | null = null\n if (parsed.subjectType === 'ruleset') {\n ruleSet = await trx.findOne(PlannerAvailabilityRuleSet, {\n id: parsed.subjectId,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n deletedAt: null,\n })\n if (ruleSet) {\n enforceCommandOptimisticLock({\n resourceKind: AVAILABILITY_RULE_SET_RESOURCE_KIND,\n resourceId: ruleSet.id,\n current: ruleSet.updatedAt,\n request: ctx.request ?? null,\n })\n } else {\n // The rule set was deleted concurrently. When the client opted into\n // optimistic locking, surface the unified conflict instead of\n // silently writing orphan rules; otherwise preserve legacy behavior.\n enforceRecordGoneIsConflict({\n resourceKind: AVAILABILITY_RULE_SET_RESOURCE_KIND,\n resourceId: parsed.subjectId,\n request: ctx.request ?? null,\n })\n }\n }\n\n const existing = await trx.find(PlannerAvailabilityRule, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n deletedAt: null,\n })\n\n const toDelete = existing.filter((rule) => {\n const repeat = parseAvailabilityRuleWindow(rule).repeat\n return repeat === 'weekly' || repeat === 'daily'\n })\n\n toDelete.forEach((rule) => {\n rule.deletedAt = now\n rule.updatedAt = now\n })\n\n if (toDelete.length) {\n trx.persist(toDelete)\n }\n\n parsed.windows.forEach((window) => {\n const start = toDateForWeekday(window.weekday, window.start)\n const end = toDateForWeekday(window.weekday, window.end)\n if (!start || !end || start >= end) return\n const rrule = buildWeeklyRrule(start, end)\n const record = trx.create(PlannerAvailabilityRule, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n timezone: parsed.timezone,\n rrule,\n exdates: [],\n kind: 'availability',\n note: null,\n createdAt: now,\n updatedAt: now,\n })\n trx.persist(record)\n })\n\n if (ruleSet) {\n ruleSet.updatedAt = now\n trx.persist(ruleSet)\n }\n\n await trx.flush()\n })\n\n return { ok: true }\n },\n buildLog: async ({ input, snapshots, ctx }) => {\n const parsed = plannerAvailabilityWeeklyReplaceSchema.parse(input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const after = await loadWeeklySnapshots(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n subjectType: parsed.subjectType,\n subjectId: parsed.subjectId,\n })\n const before = (snapshots.before as AvailabilityRuleSnapshot[] | undefined) ?? []\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('planner.audit.availability.weekly.replace', 'Replace weekly availability'),\n resourceKind: AVAILABILITY_RULE_RESOURCE_KIND,\n resourceId: null,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: {\n undo: {\n before,\n after,\n } satisfies WeeklyUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<WeeklyUndoPayload>(logEntry)\n const before = payload?.before ?? []\n const after = payload?.after ?? []\n if (!before.length && !after.length) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n await em.transactional(async (trx) => {\n if (after.length) {\n const ids = after.map((rule) => rule.id)\n const records = await trx.find(PlannerAvailabilityRule, { id: { $in: ids } })\n records.forEach((record) => {\n record.deletedAt = new Date()\n })\n if (records.length) trx.persist(records)\n }\n\n for (const snapshot of before) {\n await restoreAvailabilityRuleFromSnapshot(trx, { ...snapshot, deletedAt: null })\n }\n\n await trx.flush()\n })\n },\n}\n\nregisterCommand(replaceWeeklyAvailabilityCommand)\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,uBAAuB;AAEhC,SAAS,mCAAmC;AAC5C,SAAS,yBAAyB,kCAAkC;AACpE;AAAA,EACE;AAAA,OAEK;AACP,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB,mBAAmB,0BAA0B;AAE/E,MAAM,kCAAkC;AAMxC,MAAM,sCAAsC;AAE5C,MAAM,YAAY,CAAC,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,IAAI;AAqB3D,SAAS,eAAe,OAA0D;AAChF,QAAM,CAAC,OAAO,OAAO,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,SAAS,OAAO,IAAI,CAAC;AACpE,MAAI,CAAC,OAAO,SAAS,KAAK,KAAK,CAAC,OAAO,SAAS,OAAO,EAAG,QAAO;AACjE,MAAI,QAAQ,KAAK,QAAQ,MAAM,UAAU,KAAK,UAAU,GAAI,QAAO;AACnE,SAAO,EAAE,OAAO,QAAQ;AAC1B;AAEA,SAAS,iBAAiB,SAAiB,MAA2B;AACpE,QAAM,SAAS,eAAe,IAAI;AAClC,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,OAAO,IAAI,KAAK,IAAI,YAAY,GAAG,IAAI,SAAS,GAAG,IAAI,QAAQ,CAAC;AACtE,QAAM,QAAQ,UAAU,KAAK,OAAO,IAAI,KAAK;AAC7C,QAAM,SAAS,IAAI,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,KAAK,GAAI;AACnE,SAAO,SAAS,OAAO,OAAO,OAA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? effectiveRulesetId ?? "" : subjectId;
|
|
720
720
|
if (!subjectIdForRules) return;
|
|
721
721
|
if (weeklyHasErrors) return;
|
|
722
|
+
const parentRuleSet = subjectForRules === "ruleset" ? ruleSets.find((entry) => entry.id === subjectIdForRules) ?? null : null;
|
|
722
723
|
const shouldSkipRefresh = Boolean(options?.skipRefresh);
|
|
723
724
|
setIsWeeklyAutoSaving(options?.silentSuccess === true);
|
|
724
725
|
try {
|
|
725
726
|
const windows = buildWeeklyPayload(normalizeWeeklyWindows(weeklyWindowsRef.current));
|
|
726
727
|
await runMutation({
|
|
727
|
-
operation: () => apiCallOrThrow("/api/planner/availability-weekly", {
|
|
728
|
+
operation: () => withOptimisticLockForRuleSet(parentRuleSet, () => apiCallOrThrow("/api/planner/availability-weekly", {
|
|
728
729
|
method: "POST",
|
|
729
730
|
headers: { "Content-Type": "application/json" },
|
|
730
731
|
body: JSON.stringify({
|
|
@@ -733,7 +734,7 @@ function AvailabilityRulesEditor({
|
|
|
733
734
|
timezone,
|
|
734
735
|
windows
|
|
735
736
|
})
|
|
736
|
-
}, { errorMessage: listLabels.saveWeeklyError }),
|
|
737
|
+
}, { errorMessage: listLabels.saveWeeklyError })),
|
|
737
738
|
context: mutationContext,
|
|
738
739
|
mutationPayload: { action: "save-weekly", subjectType: subjectForRules, subjectId: subjectIdForRules }
|
|
739
740
|
});
|
|
@@ -746,7 +747,13 @@ function AvailabilityRulesEditor({
|
|
|
746
747
|
await refreshAvailability();
|
|
747
748
|
await refreshRuleSetRules();
|
|
748
749
|
}
|
|
750
|
+
if (parentRuleSet) {
|
|
751
|
+
await refreshRuleSets();
|
|
752
|
+
}
|
|
749
753
|
} catch (error2) {
|
|
754
|
+
if (surfaceRecordConflict(error2, t)) {
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
750
757
|
const message = error2 instanceof Error ? error2.message : listLabels.saveWeeklyError;
|
|
751
758
|
flash(message, "error");
|
|
752
759
|
} finally {
|
|
@@ -757,9 +764,12 @@ function AvailabilityRulesEditor({
|
|
|
757
764
|
listLabels.saveWeeklySuccess,
|
|
758
765
|
refreshAvailability,
|
|
759
766
|
refreshRuleSetRules,
|
|
767
|
+
refreshRuleSets,
|
|
768
|
+
ruleSets,
|
|
760
769
|
effectiveRulesetId,
|
|
761
770
|
subjectId,
|
|
762
771
|
subjectType,
|
|
772
|
+
t,
|
|
763
773
|
timezone,
|
|
764
774
|
usingRuleSet,
|
|
765
775
|
weeklyHasErrors,
|
|
@@ -1000,6 +1010,7 @@ function AvailabilityRulesEditor({
|
|
|
1000
1010
|
refreshRuleSets,
|
|
1001
1011
|
onSuccess: () => flash(listLabels.ruleSetDeleteSuccess, "success"),
|
|
1002
1012
|
onError: (error2) => {
|
|
1013
|
+
if (surfaceRecordConflict(error2, t)) return;
|
|
1003
1014
|
console.error("planner.availability-rule-sets.delete", error2);
|
|
1004
1015
|
const normalized = normalizeCrudServerError(error2);
|
|
1005
1016
|
flash(normalized.message ?? listLabels.ruleSetDeleteError, "error");
|
|
@@ -1017,6 +1028,7 @@ function AvailabilityRulesEditor({
|
|
|
1017
1028
|
refreshRuleSets,
|
|
1018
1029
|
ruleSets,
|
|
1019
1030
|
rulesetId,
|
|
1031
|
+
t,
|
|
1020
1032
|
mutationContext,
|
|
1021
1033
|
runMutation
|
|
1022
1034
|
]);
|