@open-mercato/core 0.6.6-develop.6401.1.8c07df34a7 → 0.6.6-develop.6403.1.b57089b6fe

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.js +9 -12
  2. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.js.map +2 -2
  3. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js +49 -10
  4. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js.map +2 -2
  5. package/dist/modules/planner/api/availability-weekly.js +11 -1
  6. package/dist/modules/planner/api/availability-weekly.js.map +2 -2
  7. package/dist/modules/planner/commands/availability-weekly.js +34 -3
  8. package/dist/modules/planner/commands/availability-weekly.js.map +2 -2
  9. package/dist/modules/planner/components/AvailabilityRulesEditor.js +14 -6
  10. package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
  11. package/dist/modules/sales/cli.js +38 -1
  12. package/dist/modules/sales/cli.js.map +2 -2
  13. package/dist/modules/sales/lib/dictionaries.js +70 -0
  14. package/dist/modules/sales/lib/dictionaries.js.map +2 -2
  15. package/package.json +7 -7
  16. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.ts +9 -13
  17. package/src/modules/customers/components/detail/ConfirmDealLostDialog.tsx +58 -8
  18. package/src/modules/customers/i18n/de.json +4 -0
  19. package/src/modules/customers/i18n/en.json +4 -0
  20. package/src/modules/customers/i18n/es.json +4 -0
  21. package/src/modules/customers/i18n/pl.json +4 -0
  22. package/src/modules/planner/api/availability-weekly.ts +10 -0
  23. package/src/modules/planner/commands/availability-weekly.ts +46 -8
  24. package/src/modules/planner/components/AvailabilityRulesEditor.tsx +15 -6
  25. package/src/modules/sales/cli.ts +39 -1
  26. package/src/modules/sales/lib/dictionaries.ts +90 -0
@@ -57,24 +57,21 @@ function useDealClosure({
57
57
  async (input) => {
58
58
  if (!currentDealId) return;
59
59
  if (!await confirmDiscardIfDirty()) return;
60
+ const lossPayload = {
61
+ id: currentDealId,
62
+ closureOutcome: "lost",
63
+ status: "loose",
64
+ lossReasonId: input.lossReasonId,
65
+ ...input.lossNotes ? { lossNotes: input.lossNotes } : {}
66
+ };
60
67
  try {
61
68
  await runMutationWithContext(
62
69
  () => withScopedApiRequestHeaders(
63
70
  buildOptimisticLockHeader(dealUpdatedAt),
64
- () => updateCrud("customers/deals", {
65
- id: currentDealId,
66
- closureOutcome: "lost",
67
- status: "loose",
68
- lossReasonId: input.lossReasonId,
69
- lossNotes: input.lossNotes ?? null
70
- })
71
+ () => updateCrud("customers/deals", lossPayload)
71
72
  ),
72
73
  {
73
- id: currentDealId,
74
- closureOutcome: "lost",
75
- status: "loose",
76
- lossReasonId: input.lossReasonId,
77
- lossNotes: input.lossNotes ?? null,
74
+ ...lossPayload,
78
75
  operation: "closeLost"
79
76
  }
80
77
  );
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../../src/modules/customers/backend/customers/deals/%5Bid%5D/hooks/useDealClosure.ts"],
4
- "sourcesContent": ["import * as React from 'react'\nimport { updateCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { DealStatsPayload, GuardedMutationRunner } from './types'\n\ntype UseDealClosureOptions = {\n currentDealId: string | null\n dealUpdatedAt: string | null\n runMutationWithContext: GuardedMutationRunner\n confirmDiscardIfDirty: () => Promise<boolean>\n onClosed: () => Promise<void>\n}\n\ntype UseDealClosureResult = {\n lostDialogOpen: boolean\n wonPopupOpen: boolean\n lostPopupOpen: boolean\n wonStats: DealStatsPayload | null\n lostStats: DealStatsPayload | null\n openLostDialog: () => void\n closeLostDialog: () => void\n closeWonPopup: () => void\n closeLostPopup: () => void\n handleWon: () => Promise<void>\n handleLostConfirm: (input: { lossReasonId: string; lossNotes?: string }) => Promise<void>\n}\n\nexport function useDealClosure({\n currentDealId,\n dealUpdatedAt,\n runMutationWithContext,\n confirmDiscardIfDirty,\n onClosed,\n}: UseDealClosureOptions): UseDealClosureResult {\n const t = useT()\n const [lostDialogOpen, setLostDialogOpen] = React.useState(false)\n const [wonPopupOpen, setWonPopupOpen] = React.useState(false)\n const [lostPopupOpen, setLostPopupOpen] = React.useState(false)\n const [wonStats, setWonStats] = React.useState<DealStatsPayload | null>(null)\n const [lostStats, setLostStats] = React.useState<DealStatsPayload | null>(null)\n\n const fetchDealStats = React.useCallback(async (): Promise<DealStatsPayload | null> => {\n if (!currentDealId) return null\n try {\n return await readApiResultOrThrow<DealStatsPayload>(\n `/api/customers/deals/${encodeURIComponent(currentDealId)}/stats`,\n )\n } catch (statsError) {\n console.error('customers.deals.detail.stats failed', statsError)\n return null\n }\n }, [currentDealId])\n\n const handleWon = React.useCallback(async () => {\n if (!currentDealId) return\n if (!(await confirmDiscardIfDirty())) return\n try {\n await runMutationWithContext(\n () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(dealUpdatedAt),\n () => updateCrud('customers/deals', { id: currentDealId, closureOutcome: 'won', status: 'win' }),\n ),\n { id: currentDealId, closureOutcome: 'won', status: 'win', operation: 'closeWon' },\n )\n } catch (err) {\n if (!surfaceRecordConflict(err, t, { onRefresh: () => { void onClosed() } })) {\n flash(t('customers.deals.detail.closeWonError', 'Failed to mark deal as won.'), 'error')\n }\n return\n }\n const stats = await fetchDealStats()\n setWonStats(stats)\n setWonPopupOpen(true)\n await onClosed()\n }, [confirmDiscardIfDirty, currentDealId, dealUpdatedAt, fetchDealStats, onClosed, runMutationWithContext, t])\n\n const handleLostConfirm = React.useCallback(\n async (input: { lossReasonId: string; lossNotes?: string }) => {\n if (!currentDealId) return\n if (!(await confirmDiscardIfDirty())) return\n try {\n await runMutationWithContext(\n () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(dealUpdatedAt),\n () =>\n updateCrud('customers/deals', {\n id: currentDealId,\n closureOutcome: 'lost',\n status: 'loose',\n lossReasonId: input.lossReasonId,\n lossNotes: input.lossNotes ?? null,\n }),\n ),\n {\n id: currentDealId,\n closureOutcome: 'lost',\n status: 'loose',\n lossReasonId: input.lossReasonId,\n lossNotes: input.lossNotes ?? null,\n operation: 'closeLost',\n },\n )\n } catch (err) {\n if (!surfaceRecordConflict(err, t, { onRefresh: () => { void onClosed() } })) {\n flash(t('customers.deals.detail.closeLostError', 'Failed to mark deal as lost.'), 'error')\n }\n return\n }\n setLostDialogOpen(false)\n const stats = await fetchDealStats()\n setLostStats(stats)\n setLostPopupOpen(true)\n await onClosed()\n },\n [confirmDiscardIfDirty, currentDealId, dealUpdatedAt, fetchDealStats, onClosed, runMutationWithContext, t],\n )\n\n const openLostDialog = React.useCallback(() => setLostDialogOpen(true), [])\n const closeLostDialog = React.useCallback(() => setLostDialogOpen(false), [])\n const closeWonPopup = React.useCallback(() => setWonPopupOpen(false), [])\n const closeLostPopup = React.useCallback(() => setLostPopupOpen(false), [])\n\n return {\n lostDialogOpen,\n wonPopupOpen,\n lostPopupOpen,\n wonStats,\n lostStats,\n openLostDialog,\n closeLostDialog,\n closeWonPopup,\n closeLostPopup,\n handleWon,\n handleLostConfirm,\n }\n}\n"],
5
- "mappings": "AAAA,YAAY,WAAW;AACvB,SAAS,kBAAkB;AAC3B,SAAS,sBAAsB,mCAAmC;AAClE,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,aAAa;AACtB,SAAS,YAAY;AAyBd,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgD;AAC9C,QAAM,IAAI,KAAK;AACf,QAAM,CAAC,gBAAgB,iB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AAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import * as React from 'react'\nimport { updateCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { DealStatsPayload, GuardedMutationRunner } from './types'\n\ntype UseDealClosureOptions = {\n currentDealId: string | null\n dealUpdatedAt: string | null\n runMutationWithContext: GuardedMutationRunner\n confirmDiscardIfDirty: () => Promise<boolean>\n onClosed: () => Promise<void>\n}\n\ntype UseDealClosureResult = {\n lostDialogOpen: boolean\n wonPopupOpen: boolean\n lostPopupOpen: boolean\n wonStats: DealStatsPayload | null\n lostStats: DealStatsPayload | null\n openLostDialog: () => void\n closeLostDialog: () => void\n closeWonPopup: () => void\n closeLostPopup: () => void\n handleWon: () => Promise<void>\n handleLostConfirm: (input: { lossReasonId: string; lossNotes?: string }) => Promise<void>\n}\n\nexport function useDealClosure({\n currentDealId,\n dealUpdatedAt,\n runMutationWithContext,\n confirmDiscardIfDirty,\n onClosed,\n}: UseDealClosureOptions): UseDealClosureResult {\n const t = useT()\n const [lostDialogOpen, setLostDialogOpen] = React.useState(false)\n const [wonPopupOpen, setWonPopupOpen] = React.useState(false)\n const [lostPopupOpen, setLostPopupOpen] = React.useState(false)\n const [wonStats, setWonStats] = React.useState<DealStatsPayload | null>(null)\n const [lostStats, setLostStats] = React.useState<DealStatsPayload | null>(null)\n\n const fetchDealStats = React.useCallback(async (): Promise<DealStatsPayload | null> => {\n if (!currentDealId) return null\n try {\n return await readApiResultOrThrow<DealStatsPayload>(\n `/api/customers/deals/${encodeURIComponent(currentDealId)}/stats`,\n )\n } catch (statsError) {\n console.error('customers.deals.detail.stats failed', statsError)\n return null\n }\n }, [currentDealId])\n\n const handleWon = React.useCallback(async () => {\n if (!currentDealId) return\n if (!(await confirmDiscardIfDirty())) return\n try {\n await runMutationWithContext(\n () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(dealUpdatedAt),\n () => updateCrud('customers/deals', { id: currentDealId, closureOutcome: 'won', status: 'win' }),\n ),\n { id: currentDealId, closureOutcome: 'won', status: 'win', operation: 'closeWon' },\n )\n } catch (err) {\n if (!surfaceRecordConflict(err, t, { onRefresh: () => { void onClosed() } })) {\n flash(t('customers.deals.detail.closeWonError', 'Failed to mark deal as won.'), 'error')\n }\n return\n }\n const stats = await fetchDealStats()\n setWonStats(stats)\n setWonPopupOpen(true)\n await onClosed()\n }, [confirmDiscardIfDirty, currentDealId, dealUpdatedAt, fetchDealStats, onClosed, runMutationWithContext, t])\n\n const handleLostConfirm = React.useCallback(\n async (input: { lossReasonId: string; lossNotes?: string }) => {\n if (!currentDealId) return\n if (!(await confirmDiscardIfDirty())) return\n const lossPayload = {\n id: currentDealId,\n closureOutcome: 'lost' as const,\n status: 'loose',\n lossReasonId: input.lossReasonId,\n ...(input.lossNotes ? { lossNotes: input.lossNotes } : {}),\n }\n try {\n await runMutationWithContext(\n () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(dealUpdatedAt),\n () => updateCrud('customers/deals', lossPayload),\n ),\n {\n ...lossPayload,\n operation: 'closeLost',\n },\n )\n } catch (err) {\n if (!surfaceRecordConflict(err, t, { onRefresh: () => { void onClosed() } })) {\n flash(t('customers.deals.detail.closeLostError', 'Failed to mark deal as lost.'), 'error')\n }\n return\n }\n setLostDialogOpen(false)\n const stats = await fetchDealStats()\n setLostStats(stats)\n setLostPopupOpen(true)\n await onClosed()\n },\n [confirmDiscardIfDirty, currentDealId, dealUpdatedAt, fetchDealStats, onClosed, runMutationWithContext, t],\n )\n\n const openLostDialog = React.useCallback(() => setLostDialogOpen(true), [])\n const closeLostDialog = React.useCallback(() => setLostDialogOpen(false), [])\n const closeWonPopup = React.useCallback(() => setWonPopupOpen(false), [])\n const closeLostPopup = React.useCallback(() => setLostPopupOpen(false), [])\n\n return {\n lostDialogOpen,\n wonPopupOpen,\n lostPopupOpen,\n wonStats,\n lostStats,\n openLostDialog,\n closeLostDialog,\n closeWonPopup,\n closeLostPopup,\n handleWon,\n handleLostConfirm,\n }\n}\n"],
5
+ "mappings": "AAAA,YAAY,WAAW;AACvB,SAAS,kBAAkB;AAC3B,SAAS,sBAAsB,mCAAmC;AAClE,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,aAAa;AACtB,SAAS,YAAY;AAyBd,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgD;AAC9C,QAAM,IAAI,KAAK;AACf,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,MAAM,SAAS,KAAK;AAChE,QAAM,CAAC,cAAc,eAAe,IAAI,MAAM,SAAS,KAAK;AAC5D,QAAM,CAAC,eAAe,gBAAgB,IAAI,MAAM,SAAS,KAAK;AAC9D,QAAM,CAAC,UAAU,WAAW,IAAI,MAAM,SAAkC,IAAI;AAC5E,QAAM,CAAC,WAAW,YAAY,IAAI,MAAM,SAAkC,IAAI;AAE9E,QAAM,iBAAiB,MAAM,YAAY,YAA8C;AACrF,QAAI,CAAC,cAAe,QAAO;AAC3B,QAAI;AACF,aAAO,MAAM;AAAA,QACX,wBAAwB,mBAAmB,aAAa,CAAC;AAAA,MAC3D;AAAA,IACF,SAAS,YAAY;AACnB,cAAQ,MAAM,uCAAuC,UAAU;AAC/D,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,aAAa,CAAC;AAElB,QAAM,YAAY,MAAM,YAAY,YAAY;AAC9C,QAAI,CAAC,cAAe;AACpB,QAAI,C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E,CAAC,GAAG;AAC5E,gBAAM,EAAE,yCAAyC,8BAA8B,GAAG,OAAO;AAAA,QAC3F;AACA;AAAA,MACF;AACA,wBAAkB,KAAK;AACvB,YAAM,QAAQ,MAAM,eAAe;AACnC,mBAAa,KAAK;AAClB,uBAAiB,IAAI;AACrB,YAAM,SAAS;AAAA,IACjB;AAAA,IACA,CAAC,uBAAuB,eAAe,eAAe,gBAAgB,UAAU,wBAAwB,CAAC;AAAA,EAC3G;AAEA,QAAM,iBAAiB,MAAM,YAAY,MAAM,kBAAkB,IAAI,GAAG,CAAC,CAAC;AAC1E,QAAM,kBAAkB,MAAM,YAAY,MAAM,kBAAkB,KAAK,GAAG,CAAC,CAAC;AAC5E,QAAM,gBAAgB,MAAM,YAAY,MAAM,gBAAgB,KAAK,GAAG,CAAC,CAAC;AACxE,QAAM,iBAAiB,MAAM,YAAY,MAAM,iBAAiB,KAAK,GAAG,CAAC,CAAC;AAE1E,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -23,15 +23,24 @@ function ConfirmDealLostDialog({
23
23
  const [lossReasons, setLossReasons] = React.useState([]);
24
24
  const [reasonListOpen, setReasonListOpen] = React.useState(false);
25
25
  const [error, setError] = React.useState("");
26
+ const [dictionaryLoadFailed, setDictionaryLoadFailed] = React.useState(false);
27
+ const [isLoadingReasons, setIsLoadingReasons] = React.useState(false);
26
28
  const [isConfirming, setIsConfirming] = React.useState(false);
27
29
  React.useEffect(() => {
28
30
  if (!open) return;
29
31
  let cancelled = false;
32
+ setIsLoadingReasons(true);
33
+ setDictionaryLoadFailed(false);
30
34
  loadDictionaryEntriesByKey("sales.deal_loss_reason").then((items) => {
31
35
  if (!cancelled) setLossReasons(items);
32
36
  }).catch((loadError) => {
33
37
  console.error("customers.deals.detail.lossReasons failed", loadError);
34
- if (!cancelled) setLossReasons([]);
38
+ if (!cancelled) {
39
+ setLossReasons([]);
40
+ setDictionaryLoadFailed(true);
41
+ }
42
+ }).finally(() => {
43
+ if (!cancelled) setIsLoadingReasons(false);
35
44
  });
36
45
  return () => {
37
46
  cancelled = true;
@@ -43,12 +52,31 @@ function ConfirmDealLostDialog({
43
52
  setLossNotes("");
44
53
  setReasonListOpen(false);
45
54
  setError("");
55
+ setDictionaryLoadFailed(false);
56
+ setIsConfirming(false);
46
57
  }, [open]);
47
58
  const selectedLossReason = React.useMemo(
48
59
  () => lossReasons.find((reason) => reason.id === lossReasonId) ?? null,
49
60
  [lossReasonId, lossReasons]
50
61
  );
62
+ const hasLossReasons = lossReasons.length > 0;
63
+ const reasonUnavailable = !isLoadingReasons && !hasLossReasons;
64
+ const unavailableReasonText = dictionaryLoadFailed ? t("customers.deals.detail.lost.reasonLoadError", "Loss reasons could not be loaded.") : t("customers.deals.detail.lost.reasonUnavailable", "No loss reasons are configured.");
65
+ const reasonHelpText = React.useMemo(() => {
66
+ if (selectedLossReason?.description) return selectedLossReason.description;
67
+ if (isLoadingReasons) {
68
+ return t("customers.deals.detail.lost.reasonLoading", "Loading loss reasons...");
69
+ }
70
+ if (reasonUnavailable) {
71
+ return unavailableReasonText;
72
+ }
73
+ return t("customers.deals.detail.lost.reasonHelp", "Choose the closest reason from the dictionary.");
74
+ }, [isLoadingReasons, reasonUnavailable, selectedLossReason?.description, t, unavailableReasonText]);
51
75
  const handleConfirm = React.useCallback(async () => {
76
+ if (isLoadingReasons || reasonUnavailable) {
77
+ setError(unavailableReasonText);
78
+ return;
79
+ }
52
80
  if (!lossReasonId) {
53
81
  setError(t("customers.deals.detail.lost.reasonRequired", "Please select a loss reason"));
54
82
  return;
@@ -62,10 +90,11 @@ function ConfirmDealLostDialog({
62
90
  } finally {
63
91
  setIsConfirming(false);
64
92
  }
65
- }, [lossNotes, lossReasonId, onConfirm, t]);
93
+ }, [isLoadingReasons, lossNotes, lossReasonId, onConfirm, reasonUnavailable, t, unavailableReasonText]);
94
+ const confirmDisabled = isConfirming || isLoadingReasons || reasonUnavailable || !lossReasonId;
66
95
  const handleKeyDown = useDialogKeyHandler({
67
96
  onConfirm: () => void handleConfirm(),
68
- disabled: isConfirming
97
+ disabled: confirmDisabled
69
98
  });
70
99
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange: (nextOpen) => {
71
100
  if (!nextOpen) onClose();
@@ -101,14 +130,14 @@ function ConfirmDealLostDialog({
101
130
  className: "h-auto flex w-full items-center justify-between rounded-md border-2 border-foreground bg-background px-4 py-3 text-left",
102
131
  children: [
103
132
  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
104
- /* @__PURE__ */ jsx("div", { className: "truncate text-base font-semibold text-foreground", children: selectedLossReason?.label ?? t("customers.deals.detail.lost.reasonPlaceholder", "Select loss reason") }),
105
- /* @__PURE__ */ jsx("div", { className: "truncate text-sm text-muted-foreground", children: selectedLossReason?.description ?? t("customers.deals.detail.lost.reasonHelp", "Choose the closest reason from the dictionary.") })
133
+ /* @__PURE__ */ jsx("div", { className: "truncate text-base font-semibold text-foreground", children: selectedLossReason?.label ?? (isLoadingReasons ? t("customers.deals.detail.lost.reasonLoadingShort", "Loading...") : t("customers.deals.detail.lost.reasonPlaceholder", "Select loss reason")) }),
134
+ /* @__PURE__ */ jsx("div", { className: "truncate text-sm text-muted-foreground", children: reasonHelpText })
106
135
  ] }),
107
136
  /* @__PURE__ */ jsx(ChevronDown, { className: "ml-3 size-4 shrink-0 text-muted-foreground" })
108
137
  ]
109
138
  }
110
139
  ),
111
- reasonListOpen ? /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-md border border-border/80 bg-background", children: lossReasons.map((reason, index) => {
140
+ reasonListOpen ? /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-md border border-border/80 bg-background", children: hasLossReasons ? lossReasons.map((reason, index) => {
112
141
  const isSelected = reason.id === lossReasonId;
113
142
  return /* @__PURE__ */ jsxs(
114
143
  Button,
@@ -131,8 +160,9 @@ function ConfirmDealLostDialog({
131
160
  },
132
161
  reason.id
133
162
  );
134
- }) }) : null
163
+ }) : /* @__PURE__ */ jsx("div", { className: "px-4 py-3 text-sm text-muted-foreground", children: unavailableReasonText }) }) : null
135
164
  ] }),
165
+ reasonUnavailable ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: unavailableReasonText }) : null,
136
166
  error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error }) : null
137
167
  ] }),
138
168
  /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
@@ -151,9 +181,18 @@ function ConfirmDealLostDialog({
151
181
  ] }),
152
182
  /* @__PURE__ */ jsxs(DialogFooter, { className: "border-t border-border/70 px-7 py-4 sm:justify-end", children: [
153
183
  /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: onClose, children: t("customers.deals.detail.lost.cancel", "Cancel") }),
154
- /* @__PURE__ */ jsx(Button, { type: "button", variant: "destructive", onClick: () => {
155
- void handleConfirm();
156
- }, children: t("customers.deals.detail.lost.confirm", "Mark as Lost") })
184
+ /* @__PURE__ */ jsx(
185
+ Button,
186
+ {
187
+ type: "button",
188
+ variant: "destructive",
189
+ disabled: confirmDisabled,
190
+ onClick: () => {
191
+ void handleConfirm();
192
+ },
193
+ children: t("customers.deals.detail.lost.confirm", "Mark as Lost")
194
+ }
195
+ )
157
196
  ] })
158
197
  ] }) }) });
159
198
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/components/detail/ConfirmDealLostDialog.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { AlertTriangle, Check, ChevronDown } from 'lucide-react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { loadDictionaryEntriesByKey } from '@open-mercato/core/modules/dictionaries/lib/clientEntries'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { useDialogKeyHandler } from '@open-mercato/ui/hooks/useDialogKeyHandler'\n\ntype LossReasonOption = {\n id: string\n value: string\n label: string\n description?: string | null\n}\n\ntype ConfirmDealLostDialogProps = {\n open: boolean\n dealTitle: string\n dealValue?: string | null\n companyName?: string | null\n onClose: () => void\n onConfirm: (input: { lossReasonId: string; lossNotes?: string }) => void | Promise<void>\n}\n\nexport function ConfirmDealLostDialog({\n open,\n dealTitle,\n dealValue,\n companyName,\n onClose,\n onConfirm,\n}: ConfirmDealLostDialogProps) {\n const t = useT()\n const [lossReasonId, setLossReasonId] = React.useState('')\n const [lossNotes, setLossNotes] = React.useState('')\n const [lossReasons, setLossReasons] = React.useState<LossReasonOption[]>([])\n const [reasonListOpen, setReasonListOpen] = React.useState(false)\n const [error, setError] = React.useState('')\n const [isConfirming, setIsConfirming] = React.useState(false)\n\n React.useEffect(() => {\n if (!open) return\n let cancelled = false\n loadDictionaryEntriesByKey('sales.deal_loss_reason')\n .then((items) => {\n if (!cancelled) setLossReasons(items)\n })\n .catch((loadError) => {\n console.error('customers.deals.detail.lossReasons failed', loadError)\n if (!cancelled) setLossReasons([])\n })\n return () => {\n cancelled = true\n }\n }, [open])\n\n React.useEffect(() => {\n if (!open) return\n setLossReasonId('')\n setLossNotes('')\n setReasonListOpen(false)\n setError('')\n }, [open])\n\n const selectedLossReason = React.useMemo(\n () => lossReasons.find((reason) => reason.id === lossReasonId) ?? null,\n [lossReasonId, lossReasons],\n )\n\n const handleConfirm = React.useCallback(async () => {\n if (!lossReasonId) {\n setError(t('customers.deals.detail.lost.reasonRequired', 'Please select a loss reason'))\n return\n }\n setIsConfirming(true)\n try {\n await onConfirm({\n lossReasonId,\n lossNotes: lossNotes.trim() || undefined,\n })\n } finally {\n setIsConfirming(false)\n }\n }, [lossNotes, lossReasonId, onConfirm, t])\n\n const handleKeyDown = useDialogKeyHandler({\n onConfirm: () => void handleConfirm(),\n disabled: isConfirming,\n })\n\n return (\n <Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onClose() }}>\n <DialogContent className=\"overflow-hidden p-0 sm:max-w-[560px]\" onKeyDown={handleKeyDown}>\n <div className=\"overflow-hidden rounded-lg bg-card\">\n <DialogHeader className=\"border-b border-border/70 px-7 py-5\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex size-10 shrink-0 items-center justify-center rounded-md bg-destructive/10 text-destructive\">\n <AlertTriangle className=\"size-5\" />\n </div>\n <div className=\"min-w-0\">\n <DialogTitle className=\"text-lg font-bold leading-none tracking-tight text-foreground\">\n {t('customers.deals.detail.lost.title', 'Mark deal as Lost?')}\n </DialogTitle>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {dealTitle}\n {dealValue ? ` \u00B7 ${dealValue}` : ''}\n {companyName ? ` \u00B7 ${companyName}` : ''}\n </p>\n </div>\n </div>\n </DialogHeader>\n\n <div className=\"space-y-6 px-7 py-6\">\n <Alert variant=\"warning\" className=\"rounded-md\">\n <AlertTitle>\n {t('customers.deals.detail.lost.warningTitle', 'This action closes the deal')}\n </AlertTitle>\n <AlertDescription>\n {t('customers.deals.detail.lost.warning', \"This action sets the stage to 'Lost' and cannot be undone without 'sales.reopen' permission\")}\n </AlertDescription>\n </Alert>\n\n <div className=\"space-y-2\">\n <label className=\"text-sm font-semibold text-foreground\">\n {t('customers.deals.detail.lost.reasonLabel', 'Loss reason')}\n <span className=\"ml-1 text-destructive\">*</span>\n </label>\n <div className=\"space-y-3\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setReasonListOpen((current) => !current)}\n className=\"h-auto flex w-full items-center justify-between rounded-md border-2 border-foreground bg-background px-4 py-3 text-left\"\n >\n <div className=\"min-w-0\">\n <div className=\"truncate text-base font-semibold text-foreground\">\n {selectedLossReason?.label ?? t('customers.deals.detail.lost.reasonPlaceholder', 'Select loss reason')}\n </div>\n <div className=\"truncate text-sm text-muted-foreground\">\n {selectedLossReason?.description ?? t('customers.deals.detail.lost.reasonHelp', 'Choose the closest reason from the dictionary.')}\n </div>\n </div>\n <ChevronDown className=\"ml-3 size-4 shrink-0 text-muted-foreground\" />\n </Button>\n\n {reasonListOpen ? (\n <div className=\"overflow-hidden rounded-md border border-border/80 bg-background\">\n {lossReasons.map((reason, index) => {\n const isSelected = reason.id === lossReasonId\n return (\n <Button\n key={reason.id}\n type=\"button\"\n variant=\"ghost\"\n onClick={() => {\n setLossReasonId(reason.id)\n setReasonListOpen(false)\n setError('')\n }}\n className={`h-auto flex w-full items-center justify-between rounded-none px-4 py-3 text-left ${\n index < lossReasons.length - 1 ? 'border-b border-border/60' : ''\n } ${isSelected ? 'bg-muted/60' : 'hover:bg-accent/50'}`}\n >\n <div className=\"min-w-0\">\n <div className=\"text-base font-semibold text-foreground\">{reason.label}</div>\n <div className=\"text-sm text-muted-foreground\">\n {reason.description ?? t('customers.deals.detail.lost.reasonFallbackDescription', 'No description available.')}\n </div>\n </div>\n {isSelected ? (\n <span className=\"ml-3 flex size-6 shrink-0 items-center justify-center rounded-full bg-foreground text-background\">\n <Check className=\"size-3.5\" />\n </span>\n ) : null}\n </Button>\n )\n })}\n </div>\n ) : null}\n </div>\n {error ? <p className=\"text-xs text-destructive\">{error}</p> : null}\n </div>\n\n <div className=\"space-y-2\">\n <label className=\"text-sm font-semibold text-foreground\">\n {t('customers.deals.detail.lost.notesLabel', 'Loss notes (optional)')}\n </label>\n <Textarea\n value={lossNotes}\n onChange={(event) => setLossNotes(event.target.value)}\n placeholder={t('customers.deals.detail.lost.notesPlaceholder', 'Additional context about the loss...')}\n rows={4}\n className=\"min-h-[88px] rounded-md border-border/80 px-4 py-3 shadow-none\"\n />\n </div>\n </div>\n\n <DialogFooter className=\"border-t border-border/70 px-7 py-4 sm:justify-end\">\n <Button type=\"button\" variant=\"outline\" onClick={onClose}>\n {t('customers.deals.detail.lost.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" variant=\"destructive\" onClick={() => { void handleConfirm() }}>\n {t('customers.deals.detail.lost.confirm', 'Mark as Lost')}\n </Button>\n </DialogFooter>\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n"],
5
- "mappings": ";AAqGgB,cAMA,YANA;AAnGhB,YAAY,WAAW;AACvB,SAAS,eAAe,OAAO,mBAAmB;AAClD,SAAS,YAAY;AACrB,SAAS,kCAAkC;AAC3C,SAAS,OAAO,kBAAkB,kBAAkB;AACpD,SAAS,cAAc;AACvB,SAAS,QAAQ,eAAe,cAAc,cAAc,mBAAmB;AAC/E,SAAS,gBAAgB;AACzB,SAAS,2BAA2B;AAkB7B,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAC7B,QAAM,IAAI,KAAK;AACf,QAAM,CAAC,cAAc,eAAe,IAAI,MAAM,SAAS,EAAE;AACzD,QAAM,CAAC,WAAW,YAAY,IAAI,MAAM,SAAS,EAAE;AACnD,QAAM,CAAC,aAAa,cAAc,IAAI,MAAM,SAA6B,CAAC,CAAC;AAC3E,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,MAAM,SAAS,KAAK;AAChE,QAAM,CAAC,OAAO,QAAQ,IAAI,MAAM,SAAS,EAAE;AAC3C,QAAM,CAAC,cAAc,eAAe,IAAI,MAAM,SAAS,KAAK;AAE5D,QAAM,UAAU,MAAM;AACpB,QAAI,CAAC,KAAM;AACX,QAAI,YAAY;AAChB,+BAA2B,wBAAwB,EAChD,KAAK,CAAC,UAAU;AACf,UAAI,CAAC,UAAW,gBAAe,KAAK;AAAA,IACtC,CAAC,EACA,MAAM,CAAC,cAAc;AACpB,cAAQ,MAAM,6CAA6C,SAAS;AACpE,UAAI,CAAC,UAAW,gBAAe,CAAC,CAAC;AAAA,IACnC,CAAC;AACH,WAAO,MAAM;AACX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AAgB,oBAAoB;AAAA,gBAErD;AAAA,uCAAC,SAAI,WAAU,WACb;AAAA,wCAAC,SAAI,WAAU,2CAA2C,iBAAO,OAAM;AAAA,oBACvE,oBAAC,SAAI,WAAU,iCACZ,iBAAO,eAAe,EAAE,yDAAyD,2BAA2B,GAC/G;AAAA,qBACF;AAAA,kBACC,aACC,oBAAC,UAAK,WAAU,oGACd,8BAAC,SAAM,WAAU,YAAW,GAC9B,IACE;AAAA;AAAA;AAAA,cAtBC,OAAO;AAAA,YAuBd;AAAA,UAEJ,CAAC,GACH,IACE;AAAA,WACN;AAAA,QACC,QAAQ,oBAAC,OAAE,WAAU,4BAA4B,iBAAM,IAAO;AAAA,SACjE;AAAA,MAEA,qBAAC,SAAI,WAAU,aACb;AAAA,4BAAC,WAAM,WAAU,yCACd,YAAE,0CAA0C,uBAAuB,GACtE;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,OAAO;AAAA,YACP,UAAU,CAAC,UAAU,aAAa,MAAM,OAAO,KAAK;AAAA,YACpD,aAAa,EAAE,gDAAgD,sCAAsC;AAAA,YACrG,MAAM;AAAA,YACN,WAAU;AAAA;AAAA,QACZ;AAAA,SACF;AAAA,OACF;AAAA,IAEA,qBAAC,gBAAa,WAAU,sDACtB;AAAA,0BAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,SAC9C,YAAE,sCAAsC,QAAQ,GACnD;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,eAAc,SAAS,MAAM;AAAE,aAAK,cAAc;AAAA,MAAE,GAC/E,YAAE,uCAAuC,cAAc,GAC1D;AAAA,OACF;AAAA,KACF,GACF,GACF;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { AlertTriangle, Check, ChevronDown } from 'lucide-react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { loadDictionaryEntriesByKey } from '@open-mercato/core/modules/dictionaries/lib/clientEntries'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { useDialogKeyHandler } from '@open-mercato/ui/hooks/useDialogKeyHandler'\n\ntype LossReasonOption = {\n id: string\n value: string\n label: string\n description?: string | null\n}\n\ntype ConfirmDealLostDialogProps = {\n open: boolean\n dealTitle: string\n dealValue?: string | null\n companyName?: string | null\n onClose: () => void\n onConfirm: (input: { lossReasonId: string; lossNotes?: string }) => void | Promise<void>\n}\n\nexport function ConfirmDealLostDialog({\n open,\n dealTitle,\n dealValue,\n companyName,\n onClose,\n onConfirm,\n}: ConfirmDealLostDialogProps) {\n const t = useT()\n const [lossReasonId, setLossReasonId] = React.useState('')\n const [lossNotes, setLossNotes] = React.useState('')\n const [lossReasons, setLossReasons] = React.useState<LossReasonOption[]>([])\n const [reasonListOpen, setReasonListOpen] = React.useState(false)\n const [error, setError] = React.useState('')\n const [dictionaryLoadFailed, setDictionaryLoadFailed] = React.useState(false)\n const [isLoadingReasons, setIsLoadingReasons] = React.useState(false)\n const [isConfirming, setIsConfirming] = React.useState(false)\n\n React.useEffect(() => {\n if (!open) return\n let cancelled = false\n setIsLoadingReasons(true)\n setDictionaryLoadFailed(false)\n loadDictionaryEntriesByKey('sales.deal_loss_reason')\n .then((items) => {\n if (!cancelled) setLossReasons(items)\n })\n .catch((loadError) => {\n console.error('customers.deals.detail.lossReasons failed', loadError)\n if (!cancelled) {\n setLossReasons([])\n setDictionaryLoadFailed(true)\n }\n })\n .finally(() => {\n if (!cancelled) setIsLoadingReasons(false)\n })\n return () => {\n cancelled = true\n }\n }, [open])\n\n React.useEffect(() => {\n if (!open) return\n setLossReasonId('')\n setLossNotes('')\n setReasonListOpen(false)\n setError('')\n setDictionaryLoadFailed(false)\n setIsConfirming(false)\n }, [open])\n\n const selectedLossReason = React.useMemo(\n () => lossReasons.find((reason) => reason.id === lossReasonId) ?? null,\n [lossReasonId, lossReasons],\n )\n const hasLossReasons = lossReasons.length > 0\n const reasonUnavailable = !isLoadingReasons && !hasLossReasons\n const unavailableReasonText = dictionaryLoadFailed\n ? t('customers.deals.detail.lost.reasonLoadError', 'Loss reasons could not be loaded.')\n : t('customers.deals.detail.lost.reasonUnavailable', 'No loss reasons are configured.')\n const reasonHelpText = React.useMemo(() => {\n if (selectedLossReason?.description) return selectedLossReason.description\n if (isLoadingReasons) {\n return t('customers.deals.detail.lost.reasonLoading', 'Loading loss reasons...')\n }\n if (reasonUnavailable) {\n return unavailableReasonText\n }\n return t('customers.deals.detail.lost.reasonHelp', 'Choose the closest reason from the dictionary.')\n }, [isLoadingReasons, reasonUnavailable, selectedLossReason?.description, t, unavailableReasonText])\n\n const handleConfirm = React.useCallback(async () => {\n if (isLoadingReasons || reasonUnavailable) {\n setError(unavailableReasonText)\n return\n }\n if (!lossReasonId) {\n setError(t('customers.deals.detail.lost.reasonRequired', 'Please select a loss reason'))\n return\n }\n setIsConfirming(true)\n try {\n await onConfirm({\n lossReasonId,\n lossNotes: lossNotes.trim() || undefined,\n })\n } finally {\n setIsConfirming(false)\n }\n }, [isLoadingReasons, lossNotes, lossReasonId, onConfirm, reasonUnavailable, t, unavailableReasonText])\n\n const confirmDisabled = isConfirming || isLoadingReasons || reasonUnavailable || !lossReasonId\n\n const handleKeyDown = useDialogKeyHandler({\n onConfirm: () => void handleConfirm(),\n disabled: confirmDisabled,\n })\n\n return (\n <Dialog open={open} onOpenChange={(nextOpen) => { if (!nextOpen) onClose() }}>\n <DialogContent className=\"overflow-hidden p-0 sm:max-w-[560px]\" onKeyDown={handleKeyDown}>\n <div className=\"overflow-hidden rounded-lg bg-card\">\n <DialogHeader className=\"border-b border-border/70 px-7 py-5\">\n <div className=\"flex items-start gap-4\">\n <div className=\"flex size-10 shrink-0 items-center justify-center rounded-md bg-destructive/10 text-destructive\">\n <AlertTriangle className=\"size-5\" />\n </div>\n <div className=\"min-w-0\">\n <DialogTitle className=\"text-lg font-bold leading-none tracking-tight text-foreground\">\n {t('customers.deals.detail.lost.title', 'Mark deal as Lost?')}\n </DialogTitle>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {dealTitle}\n {dealValue ? ` \u00B7 ${dealValue}` : ''}\n {companyName ? ` \u00B7 ${companyName}` : ''}\n </p>\n </div>\n </div>\n </DialogHeader>\n\n <div className=\"space-y-6 px-7 py-6\">\n <Alert variant=\"warning\" className=\"rounded-md\">\n <AlertTitle>\n {t('customers.deals.detail.lost.warningTitle', 'This action closes the deal')}\n </AlertTitle>\n <AlertDescription>\n {t('customers.deals.detail.lost.warning', \"This action sets the stage to 'Lost' and cannot be undone without 'sales.reopen' permission\")}\n </AlertDescription>\n </Alert>\n\n <div className=\"space-y-2\">\n <label className=\"text-sm font-semibold text-foreground\">\n {t('customers.deals.detail.lost.reasonLabel', 'Loss reason')}\n <span className=\"ml-1 text-destructive\">*</span>\n </label>\n <div className=\"space-y-3\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setReasonListOpen((current) => !current)}\n className=\"h-auto flex w-full items-center justify-between rounded-md border-2 border-foreground bg-background px-4 py-3 text-left\"\n >\n <div className=\"min-w-0\">\n <div className=\"truncate text-base font-semibold text-foreground\">\n {selectedLossReason?.label\n ?? (isLoadingReasons\n ? t('customers.deals.detail.lost.reasonLoadingShort', 'Loading...')\n : t('customers.deals.detail.lost.reasonPlaceholder', 'Select loss reason'))}\n </div>\n <div className=\"truncate text-sm text-muted-foreground\">\n {reasonHelpText}\n </div>\n </div>\n <ChevronDown className=\"ml-3 size-4 shrink-0 text-muted-foreground\" />\n </Button>\n\n {reasonListOpen ? (\n <div className=\"overflow-hidden rounded-md border border-border/80 bg-background\">\n {hasLossReasons ? lossReasons.map((reason, index) => {\n const isSelected = reason.id === lossReasonId\n return (\n <Button\n key={reason.id}\n type=\"button\"\n variant=\"ghost\"\n onClick={() => {\n setLossReasonId(reason.id)\n setReasonListOpen(false)\n setError('')\n }}\n className={`h-auto flex w-full items-center justify-between rounded-none px-4 py-3 text-left ${\n index < lossReasons.length - 1 ? 'border-b border-border/60' : ''\n } ${isSelected ? 'bg-muted/60' : 'hover:bg-accent/50'}`}\n >\n <div className=\"min-w-0\">\n <div className=\"text-base font-semibold text-foreground\">{reason.label}</div>\n <div className=\"text-sm text-muted-foreground\">\n {reason.description ?? t('customers.deals.detail.lost.reasonFallbackDescription', 'No description available.')}\n </div>\n </div>\n {isSelected ? (\n <span className=\"ml-3 flex size-6 shrink-0 items-center justify-center rounded-full bg-foreground text-background\">\n <Check className=\"size-3.5\" />\n </span>\n ) : null}\n </Button>\n )\n }) : (\n <div className=\"px-4 py-3 text-sm text-muted-foreground\">\n {unavailableReasonText}\n </div>\n )}\n </div>\n ) : null}\n </div>\n {reasonUnavailable ? (\n <p className=\"text-xs text-destructive\">\n {unavailableReasonText}\n </p>\n ) : null}\n {error ? <p className=\"text-xs text-destructive\">{error}</p> : null}\n </div>\n\n <div className=\"space-y-2\">\n <label className=\"text-sm font-semibold text-foreground\">\n {t('customers.deals.detail.lost.notesLabel', 'Loss notes (optional)')}\n </label>\n <Textarea\n value={lossNotes}\n onChange={(event) => setLossNotes(event.target.value)}\n placeholder={t('customers.deals.detail.lost.notesPlaceholder', 'Additional context about the loss...')}\n rows={4}\n className=\"min-h-[88px] rounded-md border-border/80 px-4 py-3 shadow-none\"\n />\n </div>\n </div>\n\n <DialogFooter className=\"border-t border-border/70 px-7 py-4 sm:justify-end\">\n <Button type=\"button\" variant=\"outline\" onClick={onClose}>\n {t('customers.deals.detail.lost.cancel', 'Cancel')}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n disabled={confirmDisabled}\n onClick={() => { void handleConfirm() }}\n >\n {t('customers.deals.detail.lost.confirm', 'Mark as Lost')}\n </Button>\n </DialogFooter>\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n"],
5
+ "mappings": ";AAsIgB,cAMA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,qBAAC,SAAI,WAAU,aACb;AAAA,4BAAC,WAAM,WAAU,yCACd,YAAE,0CAA0C,uBAAuB,GACtE;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,OAAO;AAAA,YACP,UAAU,CAAC,UAAU,aAAa,MAAM,OAAO,KAAK;AAAA,YACpD,aAAa,EAAE,gDAAgD,sCAAsC;AAAA,YACrG,MAAM;AAAA,YACN,WAAU;AAAA;AAAA,QACZ;AAAA,SACF;AAAA,OACF;AAAA,IAEA,qBAAC,gBAAa,WAAU,sDACtB;AAAA,0BAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,SAC9C,YAAE,sCAAsC,QAAQ,GACnD;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,SAAQ;AAAA,UACR,UAAU;AAAA,UACV,SAAS,MAAM;AAAE,iBAAK,cAAc;AAAA,UAAE;AAAA,UAErC,YAAE,uCAAuC,cAAc;AAAA;AAAA,MAC1D;AAAA,OACF;AAAA,KACF,GACF,GACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -109,7 +109,17 @@ const openApi = {
109
109
  { status: 200, description: "Weekly availability updated", schema: z.object({ ok: z.literal(true) }) },
110
110
  { status: 400, description: "Invalid payload", schema: z.object({ error: z.string() }) },
111
111
  { status: 401, description: "Unauthorized", schema: z.object({ error: z.string() }) },
112
- { status: 403, description: "Forbidden", schema: z.object({ error: z.string() }) }
112
+ { status: 403, description: "Forbidden", schema: z.object({ error: z.string() }) },
113
+ {
114
+ status: 409,
115
+ description: "Optimistic lock conflict",
116
+ schema: z.object({
117
+ error: z.string(),
118
+ code: z.literal("optimistic_lock_conflict"),
119
+ currentUpdatedAt: z.string(),
120
+ expectedUpdatedAt: z.string()
121
+ })
122
+ }
113
123
  ]
114
124
  }
115
125
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/planner/api/availability-weekly.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { parseScopedCommandInput } from '@open-mercato/shared/lib/api/scoped'\nimport { plannerAvailabilityWeeklyReplaceSchema } from '../data/validators'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { assertAvailabilityWriteAccess, resolveAvailabilityActorId } from './access'\n\nexport const metadata = {\n POST: { requireAuth: true },\n}\n\ntype RequestContext = {\n ctx: CommandRuntimeContext\n}\n\nasync function resolveRequestContext(req: Request): Promise<RequestContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('planner.availability.errors.unauthorized', 'Unauthorized') })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, {\n error: translate('planner.availability.errors.organizationRequired', 'Organization context is required'),\n })\n }\n\n const ctx: CommandRuntimeContext = {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n }\n\n return { ctx }\n}\n\nexport async function POST(req: Request) {\n try {\n const { ctx } = await resolveRequestContext(req)\n const { translate } = await resolveTranslations()\n const payload = await req.json().catch(() => ({}))\n const input = parseScopedCommandInput(plannerAvailabilityWeeklyReplaceSchema, payload, ctx, translate)\n await assertAvailabilityWriteAccess(ctx, { subjectType: input.subjectType, subjectId: input.subjectId }, translate)\n const guardInput = {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: resolveAvailabilityActorId(ctx.auth),\n resourceKind: 'planner.availability',\n resourceId: input.subjectId,\n operation: 'custom' as const,\n requestMethod: req.method,\n requestHeaders: req.headers,\n }\n const guardResult = await validateCrudMutationGuard(ctx.container, { ...guardInput, mutationPayload: input })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const { logEntry } = await commandBus.execute('planner.availability.weekly.replace', { input, ctx })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(ctx.container, { ...guardInput, metadata: guardResult.metadata ?? null })\n }\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'planner.availability',\n resourceId: logEntry.resourceId ?? null,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n console.error('planner.availability.weekly.replace failed', err)\n return NextResponse.json(\n { error: translate('planner.availability.errors.updateWeekly', 'Failed to save weekly availability.') },\n { status: 400 },\n )\n }\n}\n\nexport const openApi = {\n tag: 'Planner',\n summary: 'Replace weekly availability',\n methods: {\n POST: {\n summary: 'Replace weekly availability',\n description: 'Replaces weekly availability rules for the subject in a single request.',\n requestBody: {\n contentType: 'application/json',\n schema: plannerAvailabilityWeeklyReplaceSchema,\n },\n responses: [\n { status: 200, description: 'Weekly availability updated', schema: z.object({ ok: z.literal(true) }) },\n { status: 400, description: 'Invalid payload', schema: z.object({ error: z.string() }) },\n { status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },\n { status: 403, description: 'Forbidden', schema: z.object({ error: z.string() }) },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,+BAA+B;AACxC,SAAS,8CAA8C;AACvD,SAAS,kCAAkC;AAC3C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B,kCAAkC;AAEnE,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,KAAK;AAC5B;AAMA,eAAe,sBAAsB,KAAuC;AAC1E,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAEhD,MAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,UAAU,4CAA4C,cAAc,EAAE,CAAC;AAAA,EAC/G;AAEA,QAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,SAAS,IAAI,CAAC;AACxF,QAAM,iBAAiB,OAAO,cAAc,KAAK,SAAS;AAC1D,MAAI,CAAC,gBAAgB;AACnB,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,OAAO,UAAU,oDAAoD,kCAAkC;AAAA,IACzG,CAAC;AAAA,EACH;AAEA,QAAM,MAA6B;AAAA,IACjC;AAAA,IACA;AAAA,IACA,mBAAmB;AAAA,IACnB,wBAAwB;AAAA,IACxB,iBAAiB,OAAO,cAAc,KAAK,QAAQ,CAAC,KAA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O,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { parseScopedCommandInput } from '@open-mercato/shared/lib/api/scoped'\nimport { plannerAvailabilityWeeklyReplaceSchema } from '../data/validators'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport { assertAvailabilityWriteAccess, resolveAvailabilityActorId } from './access'\n\nexport const metadata = {\n POST: { requireAuth: true },\n}\n\ntype RequestContext = {\n ctx: CommandRuntimeContext\n}\n\nasync function resolveRequestContext(req: Request): Promise<RequestContext> {\n const container = await createRequestContainer()\n const auth = await getAuthFromRequest(req)\n const { translate } = await resolveTranslations()\n\n if (!auth || !auth.tenantId) {\n throw new CrudHttpError(401, { error: translate('planner.availability.errors.unauthorized', 'Unauthorized') })\n }\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const organizationId = scope?.selectedId ?? auth.orgId ?? null\n if (!organizationId) {\n throw new CrudHttpError(400, {\n error: translate('planner.availability.errors.organizationRequired', 'Organization context is required'),\n })\n }\n\n const ctx: CommandRuntimeContext = {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: organizationId,\n organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),\n request: req,\n }\n\n return { ctx }\n}\n\nexport async function POST(req: Request) {\n try {\n const { ctx } = await resolveRequestContext(req)\n const { translate } = await resolveTranslations()\n const payload = await req.json().catch(() => ({}))\n const input = parseScopedCommandInput(plannerAvailabilityWeeklyReplaceSchema, payload, ctx, translate)\n await assertAvailabilityWriteAccess(ctx, { subjectType: input.subjectType, subjectId: input.subjectId }, translate)\n const guardInput = {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n userId: resolveAvailabilityActorId(ctx.auth),\n resourceKind: 'planner.availability',\n resourceId: input.subjectId,\n operation: 'custom' as const,\n requestMethod: req.method,\n requestHeaders: req.headers,\n }\n const guardResult = await validateCrudMutationGuard(ctx.container, { ...guardInput, mutationPayload: input })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n const commandBus = ctx.container.resolve('commandBus') as CommandBus\n const { logEntry } = await commandBus.execute('planner.availability.weekly.replace', { input, ctx })\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(ctx.container, { ...guardInput, metadata: guardResult.metadata ?? null })\n }\n const response = NextResponse.json({ ok: true })\n if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'planner.availability',\n resourceId: logEntry.resourceId ?? null,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : undefined,\n })\n )\n }\n return response\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const { translate } = await resolveTranslations()\n console.error('planner.availability.weekly.replace failed', err)\n return NextResponse.json(\n { error: translate('planner.availability.errors.updateWeekly', 'Failed to save weekly availability.') },\n { status: 400 },\n )\n }\n}\n\nexport const openApi = {\n tag: 'Planner',\n summary: 'Replace weekly availability',\n methods: {\n POST: {\n summary: 'Replace weekly availability',\n description: 'Replaces weekly availability rules for the subject in a single request.',\n requestBody: {\n contentType: 'application/json',\n schema: plannerAvailabilityWeeklyReplaceSchema,\n },\n responses: [\n { status: 200, description: 'Weekly availability updated', schema: z.object({ ok: z.literal(true) }) },\n { status: 400, description: 'Invalid payload', schema: z.object({ error: z.string() }) },\n { status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },\n { status: 403, description: 'Forbidden', schema: z.object({ error: z.string() }) },\n {\n status: 409,\n description: 'Optimistic lock conflict',\n schema: z.object({\n error: z.string(),\n code: z.literal('optimistic_lock_conflict'),\n currentUpdatedAt: z.string(),\n expectedUpdatedAt: z.string(),\n }),\n },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AAEnD,SAAS,2BAA2B;AACpC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,+BAA+B;AACxC,SAAS,8CAA8C;AACvD,SAAS,kCAAkC;AAC3C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B,kCAAkC;AAEnE,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,KAAK;AAC5B;AAMA,eAAe,sBAAsB,KAAuC;AAC1E,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAEhD,MAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,UAAU,4CAA4C,cAAc,EAAE,CAAC;AAAA,EAC/G;AAEA,QAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,SAAS,IAAI,CAAC;AACxF,QAAM,iBAAiB,OAAO,cAAc,KAAK,SAAS;AAC1D,MAAI,CAAC,gBAAgB;AACnB,UAAM,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AAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACvF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACjF;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE,OAAO;AAAA,YAChB,MAAM,EAAE,QAAQ,0BAA0B;AAAA,YAC1C,kBAAkB,EAAE,OAAO;AAAA,YAC3B,mBAAmB,EAAE,OAAO;AAAA,UAC9B,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -5,12 +5,19 @@ import {
5
5
  plannerAvailabilityWeeklyReplaceSchema
6
6
  } from "../data/validators.js";
7
7
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
8
+ import { emitCrudSideEffects } from "@open-mercato/shared/lib/commands/helpers";
8
9
  import {
9
10
  enforceCommandOptimisticLock,
10
11
  enforceRecordGoneIsConflict
11
12
  } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
12
13
  import { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from "./shared.js";
14
+ import { plannerAvailabilityRuleSetCrudEvents } from "../lib/crud.js";
15
+ import { E } from "../../../generated/entities.ids.generated.js";
13
16
  const AVAILABILITY_RULE_RESOURCE_KIND = "planner.availability.rule";
17
+ const AVAILABILITY_RULE_SET_CACHE_RESOURCE_KIND = "planner.availability-rule-set";
18
+ const availabilityRuleSetCrudIndexer = {
19
+ entityType: E.planner.planner_availability_rule_set
20
+ };
14
21
  const AVAILABILITY_RULE_SET_RESOURCE_KIND = "planner.availability.rule.set";
15
22
  const DAY_CODES = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
16
23
  function parseTimeInput(value) {
@@ -61,6 +68,13 @@ function toAvailabilityRuleSnapshot(record) {
61
68
  deletedAt: record.deletedAt ?? null
62
69
  };
63
70
  }
71
+ function nextRuleSetUpdatedAt(current, fallback) {
72
+ const currentMs = current instanceof Date ? current.getTime() : Number.NaN;
73
+ if (Number.isFinite(currentMs) && fallback.getTime() <= currentMs) {
74
+ return new Date(currentMs + 1);
75
+ }
76
+ return fallback;
77
+ }
64
78
  async function loadWeeklySnapshots(em, params) {
65
79
  const existing = await em.find(PlannerAvailabilityRule, {
66
80
  tenantId: params.tenantId,
@@ -125,7 +139,7 @@ const replaceWeeklyAvailabilityCommand = {
125
139
  ensureOrganizationScope(ctx, parsed.organizationId);
126
140
  const em = ctx.container.resolve("em").fork();
127
141
  const now = /* @__PURE__ */ new Date();
128
- await em.transactional(async (trx) => {
142
+ const touchedRuleSet = await em.transactional(async (trx) => {
129
143
  let ruleSet = null;
130
144
  if (parsed.subjectType === "ruleset") {
131
145
  ruleSet = await trx.findOne(PlannerAvailabilityRuleSet, {
@@ -188,11 +202,27 @@ const replaceWeeklyAvailabilityCommand = {
188
202
  trx.persist(record);
189
203
  });
190
204
  if (ruleSet) {
191
- ruleSet.updatedAt = now;
205
+ ruleSet.updatedAt = nextRuleSetUpdatedAt(ruleSet.updatedAt, now);
192
206
  trx.persist(ruleSet);
193
207
  }
194
208
  await trx.flush();
209
+ return ruleSet;
195
210
  });
211
+ if (touchedRuleSet) {
212
+ const dataEngine = ctx.container.resolve("dataEngine");
213
+ await emitCrudSideEffects({
214
+ dataEngine,
215
+ action: "updated",
216
+ entity: touchedRuleSet,
217
+ identifiers: {
218
+ id: touchedRuleSet.id,
219
+ organizationId: touchedRuleSet.organizationId,
220
+ tenantId: touchedRuleSet.tenantId
221
+ },
222
+ events: plannerAvailabilityRuleSetCrudEvents,
223
+ indexer: availabilityRuleSetCrudIndexer
224
+ });
225
+ }
196
226
  return { ok: true };
197
227
  },
198
228
  buildLog: async ({ input, snapshots, ctx }) => {
@@ -219,7 +249,8 @@ const replaceWeeklyAvailabilityCommand = {
219
249
  before,
220
250
  after
221
251
  }
222
- }
252
+ },
253
+ context: parsed.subjectType === "ruleset" ? { cacheAliases: [AVAILABILITY_RULE_SET_CACHE_RESOURCE_KIND] } : null
223
254
  };
224
255
  },
225
256
  undo: async ({ logEntry, ctx }) => {
@@ -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, 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,OAAO,SAAS,GAAG,CAAC;AAClD,SAAO;AACT;AAEA,SAAS,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B;AAChD,WAAO;AAAA,MACL,aAAa,UAAU,6CAA6C,6BAA6B;AAAA,MACjG,cAAc;AAAA,MACd,YAAY;AAAA,MACZ,UAAU,OAAO;AAAA,MACjB,gBAAgB,OAAO;AAAA,MACvB,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,SAAS;AAAA,QACP,MAAM;AAAA,UACJ;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA,MAAM,OAAO,EAAE,UAAU,IAAI,MAAM;AACjC,UAAM,UAAU,mBAAsC,QAAQ;AAC9D,UAAM,SAAS,SAAS,UAAU,CAAC;AACnC,UAAM,QAAQ,SAAS,SAAS,CAAC;AACjC,QAAI,CAAC,OAAO,UAAU,CAAC,MAAM,OAAQ;AACrC,UAAM,KAAM,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAC/D,UAAM,GAAG,cAAc,OAAO,QAAQ;AACpC,UAAI,MAAM,QAAQ;AAChB,cAAM,MAAM,MAAM,IAAI,CAAC,SAAS,KAAK,EAAE;AACvC,cAAM,UAAU,MAAM,IAAI,KAAK,yBAAyB,EAAE,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;AAC5E,gBAAQ,QAAQ,CAAC,WAAW;AAC1B,iBAAO,YAAY,oBAAI,KAAK;AAAA,QAC9B,CAAC;AACD,YAAI,QAAQ,OAAQ,KAAI,QAAQ,OAAO;AAAA,MACzC;AAEA,iBAAW,YAAY,QAAQ;AAC7B,cAAM,oCAAoC,KAAK,EAAE,GAAG,UAAU,WAAW,KAAK,CAAC;AAAA,MACjF;AAEA,YAAM,IAAI,MAAM;AAAA,IAClB,CAAC;AAAA,EACH;AACF;AAEA,gBAAgB,gCAAgC;",
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 { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport {\n enforceCommandOptimisticLock,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { PlannerAvailabilityKind, PlannerAvailabilitySubjectType } from '../data/entities'\nimport { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'\nimport { plannerAvailabilityRuleSetCrudEvents } from '../lib/crud'\nimport { E } from '#generated/entities.ids.generated'\n\nconst AVAILABILITY_RULE_RESOURCE_KIND = 'planner.availability.rule'\nconst AVAILABILITY_RULE_SET_CACHE_RESOURCE_KIND = 'planner.availability-rule-set'\n\nconst availabilityRuleSetCrudIndexer: CrudIndexerConfig<PlannerAvailabilityRuleSet> = {\n entityType: E.planner.planner_availability_rule_set,\n}\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\nfunction nextRuleSetUpdatedAt(current: Date | null | undefined, fallback: Date): Date {\n const currentMs = current instanceof Date ? current.getTime() : Number.NaN\n if (Number.isFinite(currentMs) && fallback.getTime() <= currentMs) {\n return new Date(currentMs + 1)\n }\n return fallback\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 // 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 const touchedRuleSet = await em.transactional(async (trx): Promise<PlannerAvailabilityRuleSet | null> => {\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 = nextRuleSetUpdatedAt(ruleSet.updatedAt, now)\n trx.persist(ruleSet)\n }\n\n await trx.flush()\n return ruleSet\n })\n\n if (touchedRuleSet) {\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: 'updated',\n entity: touchedRuleSet,\n identifiers: {\n id: touchedRuleSet.id,\n organizationId: touchedRuleSet.organizationId,\n tenantId: touchedRuleSet.tenantId,\n },\n events: plannerAvailabilityRuleSetCrudEvents,\n indexer: availabilityRuleSetCrudIndexer,\n })\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 context: parsed.subjectType === 'ruleset'\n ? { cacheAliases: [AVAILABILITY_RULE_SET_CACHE_RESOURCE_KIND] }\n : null,\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;AACpC,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAIP,SAAS,yBAAyB,mBAAmB,0BAA0B;AAC/E,SAAS,4CAA4C;AACrD,SAAS,SAAS;AAElB,MAAM,kCAAkC;AACxC,MAAM,4CAA4C;AAElD,MAAM,iCAAgF;AAAA,EACpF,YAAY,EAAE,QAAQ;AACxB;AAMA,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,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;AAAA,MACd,YAAY;AAAA,MACZ,UAAU,OAAO;AAAA,MACjB,gBAAgB,OAAO;AAAA,MACvB,gBAAgB;AAAA,MAChB,eAAe;AAAA,MACf,SAAS;AAAA,QACP,MAAM;AAAA,UACJ;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,MACA,SAAS,OAAO,gBAAgB,YAC5B,EAAE,cAAc,CAAC,yCAAyC,EAAE,IAC5D;AAAA,IACN;AAAA,EACF;AAAA,EACA,MAAM,OAAO,EAAE,UAAU,IAAI,MAAM;AACjC,UAAM,UAAU,mBAAsC,QAAQ;AAC9D,UAAM,SAAS,SAAS,UAAU,CAAC;AACnC,UAAM,QAAQ,SAAS,SAAS,CAAC;AACjC,QAAI,CAAC,OAAO,UAAU,CAAC,MAAM,OAAQ;AACrC,UAAM,KAAM,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAC/D,UAAM,GAAG,cAAc,OAAO,QAAQ;AACpC,UAAI,MAAM,QAAQ;AAChB,cAAM,MAAM,MAAM,IAAI,CAAC,SAAS,KAAK,EAAE;AACvC,cAAM,UAAU,MAAM,IAAI,KAAK,yBAAyB,EAAE,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;AAC5E,gBAAQ,QAAQ,CAAC,WAAW;AAC1B,iBAAO,YAAY,oBAAI,KAAK;AAAA,QAC9B,CAAC;AACD,YAAI,QAAQ,OAAQ,KAAI,QAAQ,OAAO;AAAA,MACzC;AAEA,iBAAW,YAAY,QAAQ;AAC7B,cAAM,oCAAoC,KAAK,EAAE,GAAG,UAAU,WAAW,KAAK,CAAC;AAAA,MACjF;AAEA,YAAM,IAAI,MAAM;AAAA,IAClB,CAAC;AAAA,EACH;AACF;AAEA,gBAAgB,gCAAgC;",
6
6
  "names": []
7
7
  }
@@ -19,6 +19,7 @@ import { createCrud, deleteCrud, updateCrud } from "@open-mercato/ui/backend/uti
19
19
  import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
20
20
  import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
21
21
  import { flash } from "@open-mercato/ui/backend/FlashMessages";
22
+ import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
22
23
  import { Spinner } from "@open-mercato/ui/primitives/spinner";
23
24
  import { ComboboxInput, TimePicker } from "@open-mercato/ui/backend/inputs";
24
25
  import { DictionaryEntrySelect } from "@open-mercato/core/modules/dictionaries/components/DictionaryEntrySelect";
@@ -29,7 +30,6 @@ import {
29
30
  import { useT } from "@open-mercato/shared/lib/i18n/context";
30
31
  import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
31
32
  import { normalizeCrudServerError } from "@open-mercato/ui/backend/utils/serverErrors";
32
- import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
33
33
  import { parseAvailabilityRuleWindow } from "@open-mercato/core/modules/planner/lib/availabilitySchedule";
34
34
  import { deleteAvailabilityRuleSet } from "@open-mercato/core/modules/planner/lib/deleteAvailabilityRuleSet";
35
35
  import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
@@ -650,6 +650,11 @@ function AvailabilityRulesEditor({
650
650
  React.useEffect(() => {
651
651
  void refreshBookedEvents();
652
652
  }, [refreshBookedEvents]);
653
+ const refreshAfterRuleSetConflict = React.useCallback(() => {
654
+ void refreshRuleSets();
655
+ void refreshRuleSetRules();
656
+ void refreshAvailability();
657
+ }, [refreshAvailability, refreshRuleSetRules, refreshRuleSets]);
653
658
  const weeklyDraft = React.useMemo(() => buildWeeklyDraft(activeRules), [activeRules]);
654
659
  const [weeklyWindows, setWeeklyWindows] = React.useState(() => cloneWeeklyWindows(weeklyDraft));
655
660
  const weeklyWindowsRef = React.useRef(cloneWeeklyWindows(weeklyDraft));
@@ -746,14 +751,15 @@ function AvailabilityRulesEditor({
746
751
  if (!shouldSkipRefresh) {
747
752
  await refreshAvailability();
748
753
  await refreshRuleSetRules();
754
+ if (usingRuleSet) {
755
+ await refreshRuleSets();
756
+ }
749
757
  }
750
758
  if (parentRuleSet) {
751
759
  await refreshRuleSets();
752
760
  }
753
761
  } catch (error2) {
754
- if (surfaceRecordConflict(error2, t)) {
755
- return;
756
- }
762
+ if (surfaceRecordConflict(error2, t, { onRefresh: refreshAfterRuleSetConflict })) return;
757
763
  const message = error2 instanceof Error ? error2.message : listLabels.saveWeeklyError;
758
764
  flash(message, "error");
759
765
  } finally {
@@ -765,8 +771,9 @@ function AvailabilityRulesEditor({
765
771
  refreshAvailability,
766
772
  refreshRuleSetRules,
767
773
  refreshRuleSets,
768
- ruleSets,
774
+ refreshAfterRuleSetConflict,
769
775
  effectiveRulesetId,
776
+ ruleSets,
770
777
  subjectId,
771
778
  subjectType,
772
779
  t,
@@ -1010,7 +1017,7 @@ function AvailabilityRulesEditor({
1010
1017
  refreshRuleSets,
1011
1018
  onSuccess: () => flash(listLabels.ruleSetDeleteSuccess, "success"),
1012
1019
  onError: (error2) => {
1013
- if (surfaceRecordConflict(error2, t)) return;
1020
+ if (surfaceRecordConflict(error2, t, { onRefresh: refreshAfterRuleSetConflict })) return;
1014
1021
  console.error("planner.availability-rule-sets.delete", error2);
1015
1022
  const normalized = normalizeCrudServerError(error2);
1016
1023
  flash(normalized.message ?? listLabels.ruleSetDeleteError, "error");
@@ -1025,6 +1032,7 @@ function AvailabilityRulesEditor({
1025
1032
  listLabels.ruleSetDeleteSuccess,
1026
1033
  onRulesetChange,
1027
1034
  refreshAvailability,
1035
+ refreshAfterRuleSetConflict,
1028
1036
  refreshRuleSets,
1029
1037
  ruleSets,
1030
1038
  rulesetId,