@open-mercato/core 0.6.7-develop.6828.1.ab1620a63e → 0.6.7-develop.6842.1.8cd8a8883c

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 (181) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/fields/attachment.js +1 -1
  3. package/dist/modules/attachments/fields/attachment.js.map +2 -2
  4. package/dist/modules/auth/components/UserConsentsPanel.js +9 -9
  5. package/dist/modules/auth/components/UserConsentsPanel.js.map +2 -2
  6. package/dist/modules/auth/frontend/reset.js +2 -2
  7. package/dist/modules/auth/frontend/reset.js.map +2 -2
  8. package/dist/modules/business_rules/components/ActionRow.js +1 -1
  9. package/dist/modules/business_rules/components/ActionRow.js.map +1 -1
  10. package/dist/modules/business_rules/components/ConditionRow.js +8 -4
  11. package/dist/modules/business_rules/components/ConditionRow.js.map +2 -2
  12. package/dist/modules/catalog/backend/catalog/products/[id]/page.js +4 -4
  13. package/dist/modules/catalog/backend/catalog/products/[id]/page.js.map +2 -2
  14. package/dist/modules/catalog/backend/catalog/products/create/page.js +5 -5
  15. package/dist/modules/catalog/backend/catalog/products/create/page.js.map +2 -2
  16. package/dist/modules/catalog/components/PriceKindSettings.js +3 -3
  17. package/dist/modules/catalog/components/PriceKindSettings.js.map +2 -2
  18. package/dist/modules/catalog/components/products/ProductCategorizeSection.js +3 -3
  19. package/dist/modules/catalog/components/products/ProductCategorizeSection.js.map +2 -2
  20. package/dist/modules/catalog/components/products/ProductMediaManager.js +1 -1
  21. package/dist/modules/catalog/components/products/ProductMediaManager.js.map +2 -2
  22. package/dist/modules/catalog/components/products/VariantBuilder.js +5 -5
  23. package/dist/modules/catalog/components/products/VariantBuilder.js.map +2 -2
  24. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +1 -1
  25. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +2 -2
  26. package/dist/modules/customers/components/detail/ActivitiesDayStrip.js +2 -3
  27. package/dist/modules/customers/components/detail/ActivitiesDayStrip.js.map +2 -2
  28. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js +1 -1
  29. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js.map +1 -1
  30. package/dist/modules/dashboards/api/widgets/data/schema.js +26 -17
  31. package/dist/modules/dashboards/api/widgets/data/schema.js.map +2 -2
  32. package/dist/modules/dashboards/lib/aggregations.js +20 -6
  33. package/dist/modules/dashboards/lib/aggregations.js.map +2 -2
  34. package/dist/modules/design_system/gallery/entries/detail.js +8 -8
  35. package/dist/modules/design_system/gallery/entries/detail.js.map +1 -1
  36. package/dist/modules/design_system/gallery/entries/overlays.js +2 -2
  37. package/dist/modules/design_system/gallery/entries/overlays.js.map +2 -2
  38. package/dist/modules/design_system/gallery/entries/scaffolding.js +8 -8
  39. package/dist/modules/design_system/gallery/entries/scaffolding.js.map +1 -1
  40. package/dist/modules/dictionaries/components/DictionaryEntrySelect.js +1 -1
  41. package/dist/modules/dictionaries/components/DictionaryEntrySelect.js.map +2 -2
  42. package/dist/modules/inbox_ops/backend/inbox-ops/log/page.js +6 -6
  43. package/dist/modules/inbox_ops/backend/inbox-ops/log/page.js.map +2 -2
  44. package/dist/modules/inbox_ops/components/proposals/EditActionDialog.js +3 -3
  45. package/dist/modules/inbox_ops/components/proposals/EditActionDialog.js.map +2 -2
  46. package/dist/modules/messages/components/message-detail/panels/dialogs.js +1 -1
  47. package/dist/modules/messages/components/message-detail/panels/dialogs.js.map +1 -1
  48. package/dist/modules/planner/components/AvailabilityRulesEditor.js +4 -4
  49. package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
  50. package/dist/modules/shipping_carriers/lib/shipment-wizard/components/PackageEditor.js +1 -1
  51. package/dist/modules/shipping_carriers/lib/shipment-wizard/components/PackageEditor.js.map +1 -1
  52. package/dist/modules/wms/components/backend/ReleaseReservationDialog.js +1 -1
  53. package/dist/modules/wms/components/backend/ReleaseReservationDialog.js.map +1 -1
  54. package/dist/modules/workflows/backend/definitions/page.js +1 -1
  55. package/dist/modules/workflows/backend/definitions/page.js.map +2 -2
  56. package/dist/modules/workflows/backend/definitions/visual-editor/page.js +1 -1
  57. package/dist/modules/workflows/backend/definitions/visual-editor/page.js.map +2 -2
  58. package/dist/modules/workflows/backend/instances/page.js +8 -8
  59. package/dist/modules/workflows/backend/instances/page.js.map +2 -2
  60. package/dist/modules/workflows/backend/tasks/page.js +6 -6
  61. package/dist/modules/workflows/backend/tasks/page.js.map +2 -2
  62. package/dist/modules/workflows/components/ActivitiesEditor.js +2 -2
  63. package/dist/modules/workflows/components/ActivitiesEditor.js.map +2 -2
  64. package/dist/modules/workflows/components/BusinessRulesSelector.js +1 -1
  65. package/dist/modules/workflows/components/BusinessRulesSelector.js.map +2 -2
  66. package/dist/modules/workflows/components/DefinitionTriggersEditor.js +2 -2
  67. package/dist/modules/workflows/components/DefinitionTriggersEditor.js.map +2 -2
  68. package/dist/modules/workflows/components/EdgeEditDialogCrudForm.js +1 -2
  69. package/dist/modules/workflows/components/EdgeEditDialogCrudForm.js.map +2 -2
  70. package/dist/modules/workflows/components/NodeEditDialogCrudForm.js +1 -2
  71. package/dist/modules/workflows/components/NodeEditDialogCrudForm.js.map +2 -2
  72. package/dist/modules/workflows/components/StepsEditor.js +2 -2
  73. package/dist/modules/workflows/components/StepsEditor.js.map +2 -2
  74. package/dist/modules/workflows/components/TransitionsEditor.js +3 -3
  75. package/dist/modules/workflows/components/TransitionsEditor.js.map +2 -2
  76. package/dist/modules/workflows/components/WorkflowLegend.js +1 -1
  77. package/dist/modules/workflows/components/WorkflowLegend.js.map +2 -2
  78. package/dist/modules/workflows/components/WorkflowSelector.js +1 -1
  79. package/dist/modules/workflows/components/WorkflowSelector.js.map +2 -2
  80. package/dist/modules/workflows/components/fields/BusinessRuleConditionsEditor.js +1 -1
  81. package/dist/modules/workflows/components/fields/BusinessRuleConditionsEditor.js.map +2 -2
  82. package/dist/modules/workflows/components/fields/FormFieldArrayEditor.js +1 -1
  83. package/dist/modules/workflows/components/fields/FormFieldArrayEditor.js.map +2 -2
  84. package/dist/modules/workflows/components/fields/MappingArrayEditor.js +1 -1
  85. package/dist/modules/workflows/components/fields/MappingArrayEditor.js.map +2 -2
  86. package/dist/modules/workflows/components/fields/StartPreConditionsEditor.js +1 -1
  87. package/dist/modules/workflows/components/fields/StartPreConditionsEditor.js.map +2 -2
  88. package/dist/modules/workflows/components/fields/WorkflowSelectorField.js +4 -4
  89. package/dist/modules/workflows/components/fields/WorkflowSelectorField.js.map +2 -2
  90. package/package.json +8 -8
  91. package/src/modules/api_keys/i18n/ko.json +42 -0
  92. package/src/modules/attachments/fields/attachment.tsx +1 -1
  93. package/src/modules/attachments/i18n/ko.json +172 -0
  94. package/src/modules/audit_logs/i18n/ko.json +66 -0
  95. package/src/modules/auth/components/UserConsentsPanel.tsx +9 -9
  96. package/src/modules/auth/frontend/reset.tsx +2 -2
  97. package/src/modules/auth/i18n/ko.json +255 -0
  98. package/src/modules/business_rules/components/ActionRow.tsx +1 -1
  99. package/src/modules/business_rules/components/ConditionRow.tsx +9 -6
  100. package/src/modules/business_rules/i18n/ko.json +396 -0
  101. package/src/modules/catalog/backend/catalog/products/[id]/page.tsx +4 -4
  102. package/src/modules/catalog/backend/catalog/products/create/page.tsx +5 -5
  103. package/src/modules/catalog/components/PriceKindSettings.tsx +3 -3
  104. package/src/modules/catalog/components/products/ProductCategorizeSection.tsx +3 -3
  105. package/src/modules/catalog/components/products/ProductMediaManager.tsx +1 -1
  106. package/src/modules/catalog/components/products/VariantBuilder.tsx +5 -5
  107. package/src/modules/catalog/i18n/ko.json +723 -0
  108. package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +1 -1
  109. package/src/modules/communication_channels/i18n/ko.json +138 -0
  110. package/src/modules/configs/i18n/ko.json +197 -0
  111. package/src/modules/currencies/i18n/de.json +1 -0
  112. package/src/modules/currencies/i18n/en.json +1 -0
  113. package/src/modules/currencies/i18n/es.json +1 -0
  114. package/src/modules/currencies/i18n/ko.json +160 -0
  115. package/src/modules/currencies/i18n/pl.json +1 -0
  116. package/src/modules/customer_accounts/i18n/ko.json +354 -0
  117. package/src/modules/customers/components/detail/ActivitiesDayStrip.tsx +2 -3
  118. package/src/modules/customers/components/detail/ConfirmDealLostDialog.tsx +1 -1
  119. package/src/modules/customers/i18n/de.json +10 -0
  120. package/src/modules/customers/i18n/en.json +10 -0
  121. package/src/modules/customers/i18n/es.json +10 -0
  122. package/src/modules/customers/i18n/ko.json +2855 -0
  123. package/src/modules/customers/i18n/pl.json +10 -0
  124. package/src/modules/dashboards/api/widgets/data/schema.ts +48 -19
  125. package/src/modules/dashboards/i18n/ko.json +118 -0
  126. package/src/modules/dashboards/lib/aggregations.ts +42 -6
  127. package/src/modules/data_sync/i18n/ko.json +125 -0
  128. package/src/modules/design_system/gallery/entries/detail.tsx +8 -8
  129. package/src/modules/design_system/gallery/entries/overlays.tsx +2 -2
  130. package/src/modules/design_system/gallery/entries/scaffolding.tsx +8 -8
  131. package/src/modules/design_system/i18n/de.json +12 -0
  132. package/src/modules/design_system/i18n/en.json +12 -0
  133. package/src/modules/design_system/i18n/es.json +12 -0
  134. package/src/modules/design_system/i18n/ko.json +58 -0
  135. package/src/modules/design_system/i18n/pl.json +12 -0
  136. package/src/modules/dictionaries/components/DictionaryEntrySelect.tsx +1 -1
  137. package/src/modules/dictionaries/i18n/ko.json +130 -0
  138. package/src/modules/directory/i18n/ko.json +105 -0
  139. package/src/modules/entities/i18n/ko.json +260 -0
  140. package/src/modules/feature_toggles/i18n/ko.json +96 -0
  141. package/src/modules/inbox_ops/backend/inbox-ops/log/page.tsx +6 -6
  142. package/src/modules/inbox_ops/components/proposals/EditActionDialog.tsx +3 -3
  143. package/src/modules/inbox_ops/i18n/ko.json +196 -0
  144. package/src/modules/integrations/i18n/ko.json +129 -0
  145. package/src/modules/messages/components/message-detail/panels/dialogs.tsx +1 -1
  146. package/src/modules/messages/i18n/ko.json +263 -0
  147. package/src/modules/notifications/i18n/ko.json +55 -0
  148. package/src/modules/payment_gateways/i18n/ko.json +87 -0
  149. package/src/modules/planner/components/AvailabilityRulesEditor.tsx +4 -4
  150. package/src/modules/planner/i18n/ko.json +565 -0
  151. package/src/modules/portal/i18n/ko.json +143 -0
  152. package/src/modules/progress/i18n/ko.json +20 -0
  153. package/src/modules/query_index/i18n/ko.json +69 -0
  154. package/src/modules/resources/i18n/ko.json +770 -0
  155. package/src/modules/sales/i18n/ko.json +1442 -0
  156. package/src/modules/shipping_carriers/i18n/ko.json +85 -0
  157. package/src/modules/shipping_carriers/lib/shipment-wizard/components/PackageEditor.tsx +1 -1
  158. package/src/modules/staff/i18n/ko.json +1162 -0
  159. package/src/modules/sync_excel/i18n/ko.json +107 -0
  160. package/src/modules/translations/i18n/ko.json +45 -0
  161. package/src/modules/wms/components/backend/ReleaseReservationDialog.tsx +1 -1
  162. package/src/modules/wms/i18n/ko.json +1053 -0
  163. package/src/modules/workflows/backend/definitions/page.tsx +1 -1
  164. package/src/modules/workflows/backend/definitions/visual-editor/page.tsx +1 -1
  165. package/src/modules/workflows/backend/instances/page.tsx +8 -8
  166. package/src/modules/workflows/backend/tasks/page.tsx +6 -6
  167. package/src/modules/workflows/components/ActivitiesEditor.tsx +2 -2
  168. package/src/modules/workflows/components/BusinessRulesSelector.tsx +1 -1
  169. package/src/modules/workflows/components/DefinitionTriggersEditor.tsx +2 -2
  170. package/src/modules/workflows/components/EdgeEditDialogCrudForm.tsx +1 -2
  171. package/src/modules/workflows/components/NodeEditDialogCrudForm.tsx +1 -2
  172. package/src/modules/workflows/components/StepsEditor.tsx +2 -2
  173. package/src/modules/workflows/components/TransitionsEditor.tsx +3 -3
  174. package/src/modules/workflows/components/WorkflowLegend.tsx +1 -1
  175. package/src/modules/workflows/components/WorkflowSelector.tsx +1 -1
  176. package/src/modules/workflows/components/fields/BusinessRuleConditionsEditor.tsx +1 -1
  177. package/src/modules/workflows/components/fields/FormFieldArrayEditor.tsx +1 -1
  178. package/src/modules/workflows/components/fields/MappingArrayEditor.tsx +1 -1
  179. package/src/modules/workflows/components/fields/StartPreConditionsEditor.tsx +1 -1
  180. package/src/modules/workflows/components/fields/WorkflowSelectorField.tsx +4 -4
  181. package/src/modules/workflows/i18n/ko.json +1203 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/components/detail/ActivitiesDayStrip.tsx"],
4
- "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { ChevronLeft, ChevronRight } from 'lucide-react'\nimport { toZonedTime } from 'date-fns-tz'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport type { InteractionSummary } from './types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\ninterface ActivitiesDayStripProps {\n entityId: string\n selectedDate: Date\n onSelectDate: (date: Date) => void\n refreshKey?: number\n /**\n * Optional pre-fetched events. When provided, the day strip skips its own fetch\n * and uses the supplied list, ensuring its busyness count agrees with the\n * activity list rendered alongside it (issue #1809 \u2014 E1 status filter alignment).\n */\n events?: InteractionSummary[]\n}\n\nconst USER_TIMEZONE = (() => {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'\n } catch {\n return 'UTC'\n }\n})()\n\n// Project a UTC ISO timestamp to the user's local timezone before comparing\n// \"same day\" (issue #1809 \u2014 E3). The browser's `new Date(iso)` treats the\n// instant correctly, but `getDate()/getMonth()/getFullYear()` reflect the\n// user's local day, so for activities scheduled at e.g. 23:30 local on a UTC\n// boundary the day-strip and list now agree.\nfunction toLocalZonedDate(value: string | Date): Date {\n return toZonedTime(value, USER_TIMEZONE)\n}\n\nconst VISIBLE_DAYS = 5\nconst BUSYNESS_SLOTS = 10\nconst SLOT_START_HOUR = 7\nconst SLOT_END_HOUR = 22\n\nconst DAY_LABEL_KEYS: Array<[number, string, string]> = [\n [0, 'customers.calendar.day.sun', 'SUN'],\n [1, 'customers.calendar.day.mon', 'MON'],\n [2, 'customers.calendar.day.tue', 'TUE'],\n [3, 'customers.calendar.day.wed', 'WED'],\n [4, 'customers.calendar.day.thu', 'THU'],\n [5, 'customers.calendar.day.fri', 'FRI'],\n [6, 'customers.calendar.day.sat', 'SAT'],\n]\n\nconst MONTH_KEYS: Array<[number, string, string]> = [\n [0, 'customers.calendar.month.january', 'January'],\n [1, 'customers.calendar.month.february', 'February'],\n [2, 'customers.calendar.month.march', 'March'],\n [3, 'customers.calendar.month.april', 'April'],\n [4, 'customers.calendar.month.may', 'May'],\n [5, 'customers.calendar.month.june', 'June'],\n [6, 'customers.calendar.month.july', 'July'],\n [7, 'customers.calendar.month.august', 'August'],\n [8, 'customers.calendar.month.september', 'September'],\n [9, 'customers.calendar.month.october', 'October'],\n [10, 'customers.calendar.month.november', 'November'],\n [11, 'customers.calendar.month.december', 'December'],\n]\n\nfunction startOfDay(date: Date): Date {\n const next = new Date(date)\n next.setHours(0, 0, 0, 0)\n return next\n}\n\nfunction endOfDay(date: Date): Date {\n const next = new Date(date)\n next.setHours(23, 59, 59, 999)\n return next\n}\n\nfunction isSameDay(a: Date, b: Date): boolean {\n return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()\n}\n\nfunction isWeekend(date: Date): boolean {\n const day = date.getDay()\n return day === 0 || day === 6\n}\n\nfunction addDays(date: Date, delta: number): Date {\n const next = new Date(date)\n next.setDate(date.getDate() + delta)\n return next\n}\n\nfunction buildVisibleDays(anchor: Date): Date[] {\n const start = startOfDay(anchor)\n return Array.from({ length: VISIBLE_DAYS }, (_, index) => addDays(start, index))\n}\n\n// Anchor the visible window so that the given focal date lands at the center slot\n// (position 2 out of 5). Matches Figma 784:809 where the selected day is centered.\nfunction anchorCenteredOn(focalDate: Date): Date {\n return startOfDay(addDays(focalDate, -Math.floor(VISIBLE_DAYS / 2)))\n}\n\ntype SlotState = 'empty' | 'partial' | 'full' | 'conflict'\n\ntype DayBusyness = {\n totalMinutes: number\n eventCount: number\n slots: SlotState[]\n}\n\nfunction emptyBusyness(): DayBusyness {\n return {\n totalMinutes: 0,\n eventCount: 0,\n slots: Array<SlotState>(BUSYNESS_SLOTS).fill('empty'),\n }\n}\n\nfunction computeDayBusyness(events: InteractionSummary[], day: Date): DayBusyness {\n if (events.length === 0) return emptyBusyness()\n const dayStart = startOfDay(day).getTime()\n const slotMs = ((SLOT_END_HOUR - SLOT_START_HOUR) * 60 * 60 * 1000) / BUSYNESS_SLOTS\n const slotMinutes = slotMs / 60000\n const slotCounts: number[] = Array(BUSYNESS_SLOTS).fill(0)\n const slotMinutesUsed: number[] = Array(BUSYNESS_SLOTS).fill(0)\n let totalMinutes = 0\n let eventCount = 0\n\n for (const event of events) {\n const startIso = event.scheduledAt ?? event.occurredAt ?? event.createdAt\n if (!startIso) continue\n const start = new Date(startIso)\n if (Number.isNaN(start.getTime())) continue\n // Compare in the user's local timezone so an activity at 23:30 local time\n // doesn't bleed into the next UTC day's chip (issue #1809 \u2014 E3).\n const localStart = toLocalZonedDate(startIso)\n if (!isSameDay(localStart, day)) continue\n eventCount += 1\n const durationMinutes = typeof event.duration === 'number' && event.duration > 0 ? event.duration : 30\n totalMinutes += durationMinutes\n const eventStartMs = start.getTime()\n const eventEndMs = eventStartMs + durationMinutes * 60000\n const slotsStartMs = dayStart + SLOT_START_HOUR * 60 * 60 * 1000\n for (let slot = 0; slot < BUSYNESS_SLOTS; slot += 1) {\n const slotStart = slotsStartMs + slot * slotMs\n const slotEnd = slotStart + slotMs\n const overlapStart = Math.max(slotStart, eventStartMs)\n const overlapEnd = Math.min(slotEnd, eventEndMs)\n const overlapMinutes = Math.max(0, (overlapEnd - overlapStart) / 60000)\n if (overlapMinutes <= 0) continue\n slotCounts[slot] += 1\n slotMinutesUsed[slot] += overlapMinutes\n }\n }\n\n const slots: SlotState[] = slotCounts.map((count, index) => {\n if (count === 0) return 'empty'\n if (count > 1) return 'conflict'\n const used = slotMinutesUsed[index]\n if (used >= slotMinutes * 0.5) return 'full'\n return 'partial'\n })\n\n return { totalMinutes, eventCount, slots }\n}\n\nfunction formatBusyLabel(busy: DayBusyness, t: TranslateFn): string {\n if (busy.eventCount === 0) return ''\n // Match Figma 784:809 label format: \"Xm\" when under an hour, \"Xh\" otherwise.\n // Mixed \"Xh Ym\" overflows the 101px card and is not part of the visual spec.\n const durationLabel = busy.totalMinutes < 60\n ? t('customers.activities.calendar.minutesShort', '{minutes}m', { minutes: Math.max(Math.round(busy.totalMinutes), 1) })\n : t('customers.activities.calendar.hoursShort', '{hours}h', { hours: Math.floor(busy.totalMinutes / 60) })\n return t('customers.activities.calendar.eventsSummary', '{count} {countLabel} \u00B7 {duration}', {\n count: busy.eventCount,\n countLabel: busy.eventCount === 1\n ? t('customers.activities.calendar.eventSingular', 'event')\n : t('customers.activities.calendar.eventPlural', 'events'),\n duration: durationLabel,\n })\n}\n\nfunction formatMonthLabel(date: Date, t: TranslateFn): string {\n const monthEntry = MONTH_KEYS.find(([index]) => index === date.getMonth())\n const monthName = monthEntry ? t(monthEntry[1], monthEntry[2]) : ''\n return t('customers.activities.calendar.monthYear', '{month} {year}', { month: monthName, year: date.getFullYear() })\n}\n\nfunction formatDayLabel(date: Date, t: TranslateFn): string {\n const entry = DAY_LABEL_KEYS.find(([index]) => index === date.getDay())\n return entry ? t(entry[1], entry[2]) : ''\n}\n\nexport function ActivitiesDayStrip({ entityId, selectedDate, onSelectDate, refreshKey = 0, events: providedEvents }: ActivitiesDayStripProps) {\n const t = useT()\n const [anchor, setAnchor] = React.useState<Date>(() => anchorCenteredOn(selectedDate))\n const [fetchedEvents, setFetchedEvents] = React.useState<InteractionSummary[]>([])\n // When the parent supplies `events` (preferred path \u2014 keeps day strip and\n // the list in lockstep, fixes #1809 E1), skip the local fetch entirely.\n const useProvidedEvents = providedEvents !== undefined\n const events = useProvidedEvents ? providedEvents : fetchedEvents\n\n React.useEffect(() => {\n setAnchor((current) => {\n const days = buildVisibleDays(current)\n const visible = days.some((day) => isSameDay(day, selectedDate))\n if (visible) return current\n return anchorCenteredOn(selectedDate)\n })\n }, [selectedDate])\n\n const visibleDays = React.useMemo(() => buildVisibleDays(anchor), [anchor])\n const headerLabel = React.useMemo(() => formatMonthLabel(visibleDays[0], t), [visibleDays, t])\n\n React.useEffect(() => {\n if (useProvidedEvents) return\n if (!entityId || visibleDays.length === 0) return\n const controller = new AbortController()\n const fromIso = startOfDay(visibleDays[0]).toISOString()\n const toIso = endOfDay(visibleDays[visibleDays.length - 1]).toISOString()\n const params = new URLSearchParams({\n entityId,\n from: fromIso,\n to: toIso,\n limit: '100',\n sortField: 'scheduledAt',\n sortDir: 'asc',\n excludeInteractionType: 'task',\n })\n void (async () => {\n try {\n const payload = await readApiResultOrThrow<{ items?: InteractionSummary[] }>(\n `/api/customers/interactions?${params.toString()}`,\n { signal: controller.signal },\n )\n setFetchedEvents(Array.isArray(payload?.items) ? payload.items : [])\n } catch (err) {\n if ((err as { name?: string } | null)?.name !== 'AbortError') {\n logger.warn('failed to load interactions', { component: 'ActivitiesDayStrip', err })\n }\n setFetchedEvents([])\n }\n })()\n return () => controller.abort()\n }, [entityId, visibleDays, refreshKey, useProvidedEvents])\n\n const todayDate = React.useMemo(() => startOfDay(new Date()), [])\n\n const handlePrev = React.useCallback(() => {\n setAnchor((current) => addDays(current, -VISIBLE_DAYS))\n }, [])\n const handleNext = React.useCallback(() => {\n setAnchor((current) => addDays(current, VISIBLE_DAYS))\n }, [])\n const handleHeaderPrev = React.useCallback(() => {\n setAnchor((current) => {\n const next = new Date(current)\n next.setMonth(current.getMonth() - 1)\n return startOfDay(next)\n })\n }, [])\n const handleHeaderNext = React.useCallback(() => {\n setAnchor((current) => {\n const next = new Date(current)\n next.setMonth(current.getMonth() + 1)\n return startOfDay(next)\n })\n }, [])\n\n return (\n <div className=\"flex flex-col gap-2.5 rounded-md px-3.5 py-3 w-full\">\n <div className=\"flex items-center justify-center gap-1.5 rounded-md bg-muted px-1.5 py-1.5\">\n <button\n type=\"button\"\n onClick={handleHeaderPrev}\n aria-label={t('customers.activities.calendar.prevMonth', 'Previous month')}\n className=\"flex size-6 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronLeft className=\"size-4 text-foreground\" />\n </button>\n <span className=\"flex-1 text-center text-sm font-medium leading-5 text-foreground\">{headerLabel}</span>\n <button\n type=\"button\"\n onClick={handleHeaderNext}\n aria-label={t('customers.activities.calendar.nextMonth', 'Next month')}\n className=\"flex size-6 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronRight className=\"size-4 text-foreground\" />\n </button>\n </div>\n <div className=\"flex w-full items-center gap-2\">\n <button\n type=\"button\"\n onClick={handlePrev}\n aria-label={t('customers.activities.calendar.prevWindow', 'Previous days')}\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronLeft className=\"size-4 text-foreground\" />\n </button>\n <div className=\"flex flex-1 items-stretch justify-center gap-1\">\n {visibleDays.map((day) => {\n const busy = computeDayBusyness(events, day)\n const isSelected = isSameDay(day, selectedDate)\n const isToday = isSameDay(day, todayDate)\n const weekend = isWeekend(day)\n const busyLabel = busy.eventCount > 0\n ? formatBusyLabel(busy, t)\n : weekend\n ? t('customers.activities.calendar.weekend', 'Weekend')\n : ''\n return (\n <DayCard\n key={day.toISOString()}\n day={day}\n isActive={isSelected}\n isToday={isToday}\n busyness={busy}\n label={busyLabel}\n dayName={formatDayLabel(day, t)}\n onSelect={() => onSelectDate(day)}\n />\n )\n })}\n </div>\n <button\n type=\"button\"\n onClick={handleNext}\n aria-label={t('customers.activities.calendar.nextWindow', 'Next days')}\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronRight className=\"size-4 text-foreground\" />\n </button>\n </div>\n </div>\n )\n}\n\ninterface DayCardProps {\n day: Date\n isActive: boolean\n isToday: boolean\n busyness: DayBusyness\n label: string\n dayName: string\n onSelect: () => void\n}\n\nfunction DayCard({ day, isActive, isToday, busyness, label, dayName, onSelect }: DayCardProps) {\n const dayNumber = String(day.getDate()).padStart(2, '0')\n return (\n <button\n type=\"button\"\n onClick={onSelect}\n aria-pressed={isActive}\n aria-label={`${dayName} ${dayNumber}`}\n className={cn(\n 'flex h-[104px] w-[101px] flex-col items-center gap-[6px] overflow-hidden rounded-[10px] border p-[12px] transition-colors',\n isActive\n ? 'border-transparent bg-foreground'\n : 'border-border bg-card hover:border-foreground/40',\n )}\n >\n <span className=\"text-[11px] font-medium leading-none tracking-[0.44px] text-muted-foreground\">\n {dayName}\n </span>\n <div className=\"flex items-center gap-[5px]\">\n <span\n className={cn(\n 'text-2xl font-semibold leading-7',\n isActive ? 'text-background' : 'text-foreground',\n )}\n >\n {dayNumber}\n </span>\n {isToday ? (\n <span\n className=\"inline-block size-1.5 rounded-full bg-status-info-icon\"\n aria-hidden\n />\n ) : null}\n </div>\n <div className=\"flex h-4 w-[82px] items-end gap-[1.5px]\">\n {busyness.slots.map((state, index) => (\n <BusySlot key={index} state={state} active={isActive} />\n ))}\n </div>\n <span className=\"text-[11px] leading-[14px] font-normal whitespace-nowrap text-muted-foreground\">\n {label}\n </span>\n </button>\n )\n}\n\nfunction BusySlot({ state, active }: { state: SlotState; active: boolean }) {\n const heightClass = state === 'empty'\n ? 'h-0.5'\n : state === 'partial'\n ? 'h-2'\n : 'h-3.5'\n let bgClass: string\n if (state === 'conflict') {\n bgClass = 'bg-status-error-icon'\n } else if (active) {\n if (state === 'empty') bgClass = 'bg-background/30'\n else if (state === 'partial') bgClass = 'bg-background/60'\n else bgClass = 'bg-background'\n } else {\n if (state === 'empty') bgClass = 'bg-border'\n else if (state === 'partial') bgClass = 'bg-muted-foreground'\n else bgClass = 'bg-foreground'\n }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;",
4
+ "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { ChevronLeft, ChevronRight } from 'lucide-react'\nimport { toZonedTime } from 'date-fns-tz'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport type { InteractionSummary } from './types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\ninterface ActivitiesDayStripProps {\n entityId: string\n selectedDate: Date\n onSelectDate: (date: Date) => void\n refreshKey?: number\n /**\n * Optional pre-fetched events. When provided, the day strip skips its own fetch\n * and uses the supplied list, ensuring its busyness count agrees with the\n * activity list rendered alongside it (issue #1809 \u2014 E1 status filter alignment).\n */\n events?: InteractionSummary[]\n}\n\nconst USER_TIMEZONE = (() => {\n try {\n return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'\n } catch {\n return 'UTC'\n }\n})()\n\n// Project a UTC ISO timestamp to the user's local timezone before comparing\n// \"same day\" (issue #1809 \u2014 E3). The browser's `new Date(iso)` treats the\n// instant correctly, but `getDate()/getMonth()/getFullYear()` reflect the\n// user's local day, so for activities scheduled at e.g. 23:30 local on a UTC\n// boundary the day-strip and list now agree.\nfunction toLocalZonedDate(value: string | Date): Date {\n return toZonedTime(value, USER_TIMEZONE)\n}\n\nconst VISIBLE_DAYS = 5\nconst BUSYNESS_SLOTS = 10\nconst SLOT_START_HOUR = 7\nconst SLOT_END_HOUR = 22\n\nconst DAY_LABEL_KEYS: Array<[number, string, string]> = [\n [0, 'customers.calendar.day.sun', 'SUN'],\n [1, 'customers.calendar.day.mon', 'MON'],\n [2, 'customers.calendar.day.tue', 'TUE'],\n [3, 'customers.calendar.day.wed', 'WED'],\n [4, 'customers.calendar.day.thu', 'THU'],\n [5, 'customers.calendar.day.fri', 'FRI'],\n [6, 'customers.calendar.day.sat', 'SAT'],\n]\n\nconst MONTH_KEYS: Array<[number, string, string]> = [\n [0, 'customers.calendar.month.january', 'January'],\n [1, 'customers.calendar.month.february', 'February'],\n [2, 'customers.calendar.month.march', 'March'],\n [3, 'customers.calendar.month.april', 'April'],\n [4, 'customers.calendar.month.may', 'May'],\n [5, 'customers.calendar.month.june', 'June'],\n [6, 'customers.calendar.month.july', 'July'],\n [7, 'customers.calendar.month.august', 'August'],\n [8, 'customers.calendar.month.september', 'September'],\n [9, 'customers.calendar.month.october', 'October'],\n [10, 'customers.calendar.month.november', 'November'],\n [11, 'customers.calendar.month.december', 'December'],\n]\n\nfunction startOfDay(date: Date): Date {\n const next = new Date(date)\n next.setHours(0, 0, 0, 0)\n return next\n}\n\nfunction endOfDay(date: Date): Date {\n const next = new Date(date)\n next.setHours(23, 59, 59, 999)\n return next\n}\n\nfunction isSameDay(a: Date, b: Date): boolean {\n return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()\n}\n\nfunction isWeekend(date: Date): boolean {\n const day = date.getDay()\n return day === 0 || day === 6\n}\n\nfunction addDays(date: Date, delta: number): Date {\n const next = new Date(date)\n next.setDate(date.getDate() + delta)\n return next\n}\n\nfunction buildVisibleDays(anchor: Date): Date[] {\n const start = startOfDay(anchor)\n return Array.from({ length: VISIBLE_DAYS }, (_, index) => addDays(start, index))\n}\n\n// Anchor the visible window so that the given focal date lands at the center slot\n// (position 2 out of 5). Matches Figma 784:809 where the selected day is centered.\nfunction anchorCenteredOn(focalDate: Date): Date {\n return startOfDay(addDays(focalDate, -Math.floor(VISIBLE_DAYS / 2)))\n}\n\ntype SlotState = 'empty' | 'partial' | 'full' | 'conflict'\n\ntype DayBusyness = {\n totalMinutes: number\n eventCount: number\n slots: SlotState[]\n}\n\nfunction emptyBusyness(): DayBusyness {\n return {\n totalMinutes: 0,\n eventCount: 0,\n slots: Array<SlotState>(BUSYNESS_SLOTS).fill('empty'),\n }\n}\n\nfunction computeDayBusyness(events: InteractionSummary[], day: Date): DayBusyness {\n if (events.length === 0) return emptyBusyness()\n const dayStart = startOfDay(day).getTime()\n const slotMs = ((SLOT_END_HOUR - SLOT_START_HOUR) * 60 * 60 * 1000) / BUSYNESS_SLOTS\n const slotMinutes = slotMs / 60000\n const slotCounts: number[] = Array(BUSYNESS_SLOTS).fill(0)\n const slotMinutesUsed: number[] = Array(BUSYNESS_SLOTS).fill(0)\n let totalMinutes = 0\n let eventCount = 0\n\n for (const event of events) {\n const startIso = event.scheduledAt ?? event.occurredAt ?? event.createdAt\n if (!startIso) continue\n const start = new Date(startIso)\n if (Number.isNaN(start.getTime())) continue\n // Compare in the user's local timezone so an activity at 23:30 local time\n // doesn't bleed into the next UTC day's chip (issue #1809 \u2014 E3).\n const localStart = toLocalZonedDate(startIso)\n if (!isSameDay(localStart, day)) continue\n eventCount += 1\n const durationMinutes = typeof event.duration === 'number' && event.duration > 0 ? event.duration : 30\n totalMinutes += durationMinutes\n const eventStartMs = start.getTime()\n const eventEndMs = eventStartMs + durationMinutes * 60000\n const slotsStartMs = dayStart + SLOT_START_HOUR * 60 * 60 * 1000\n for (let slot = 0; slot < BUSYNESS_SLOTS; slot += 1) {\n const slotStart = slotsStartMs + slot * slotMs\n const slotEnd = slotStart + slotMs\n const overlapStart = Math.max(slotStart, eventStartMs)\n const overlapEnd = Math.min(slotEnd, eventEndMs)\n const overlapMinutes = Math.max(0, (overlapEnd - overlapStart) / 60000)\n if (overlapMinutes <= 0) continue\n slotCounts[slot] += 1\n slotMinutesUsed[slot] += overlapMinutes\n }\n }\n\n const slots: SlotState[] = slotCounts.map((count, index) => {\n if (count === 0) return 'empty'\n if (count > 1) return 'conflict'\n const used = slotMinutesUsed[index]\n if (used >= slotMinutes * 0.5) return 'full'\n return 'partial'\n })\n\n return { totalMinutes, eventCount, slots }\n}\n\nfunction formatBusyLabel(busy: DayBusyness, t: TranslateFn): string {\n if (busy.eventCount === 0) return ''\n // Match Figma 784:809 label format: \"Xm\" when under an hour, \"Xh\" otherwise.\n // Mixed \"Xh Ym\" overflows the 101px card and is not part of the visual spec.\n const durationLabel = busy.totalMinutes < 60\n ? t('customers.activities.calendar.minutesShort', '{minutes}m', { minutes: Math.max(Math.round(busy.totalMinutes), 1) })\n : t('customers.activities.calendar.hoursShort', '{hours}h', { hours: Math.floor(busy.totalMinutes / 60) })\n return t('customers.activities.calendar.eventsSummary', '{count} {countLabel} \u00B7 {duration}', {\n count: busy.eventCount,\n countLabel: busy.eventCount === 1\n ? t('customers.activities.calendar.eventSingular', 'event')\n : t('customers.activities.calendar.eventPlural', 'events'),\n duration: durationLabel,\n })\n}\n\nfunction formatMonthLabel(date: Date, t: TranslateFn): string {\n const monthEntry = MONTH_KEYS.find(([index]) => index === date.getMonth())\n const monthName = monthEntry ? t(monthEntry[1], monthEntry[2]) : ''\n return t('customers.activities.calendar.monthYear', '{month} {year}', { month: monthName, year: date.getFullYear() })\n}\n\nfunction formatDayLabel(date: Date, t: TranslateFn): string {\n const entry = DAY_LABEL_KEYS.find(([index]) => index === date.getDay())\n return entry ? t(entry[1], entry[2]) : ''\n}\n\nexport function ActivitiesDayStrip({ entityId, selectedDate, onSelectDate, refreshKey = 0, events: providedEvents }: ActivitiesDayStripProps) {\n const t = useT()\n const [anchor, setAnchor] = React.useState<Date>(() => anchorCenteredOn(selectedDate))\n const [fetchedEvents, setFetchedEvents] = React.useState<InteractionSummary[]>([])\n // When the parent supplies `events` (preferred path \u2014 keeps day strip and\n // the list in lockstep, fixes #1809 E1), skip the local fetch entirely.\n const useProvidedEvents = providedEvents !== undefined\n const events = useProvidedEvents ? providedEvents : fetchedEvents\n\n React.useEffect(() => {\n setAnchor((current) => {\n const days = buildVisibleDays(current)\n const visible = days.some((day) => isSameDay(day, selectedDate))\n if (visible) return current\n return anchorCenteredOn(selectedDate)\n })\n }, [selectedDate])\n\n const visibleDays = React.useMemo(() => buildVisibleDays(anchor), [anchor])\n const headerLabel = React.useMemo(() => formatMonthLabel(visibleDays[0], t), [visibleDays, t])\n\n React.useEffect(() => {\n if (useProvidedEvents) return\n if (!entityId || visibleDays.length === 0) return\n const controller = new AbortController()\n const fromIso = startOfDay(visibleDays[0]).toISOString()\n const toIso = endOfDay(visibleDays[visibleDays.length - 1]).toISOString()\n const params = new URLSearchParams({\n entityId,\n from: fromIso,\n to: toIso,\n limit: '100',\n sortField: 'scheduledAt',\n sortDir: 'asc',\n excludeInteractionType: 'task',\n })\n void (async () => {\n try {\n const payload = await readApiResultOrThrow<{ items?: InteractionSummary[] }>(\n `/api/customers/interactions?${params.toString()}`,\n { signal: controller.signal },\n )\n setFetchedEvents(Array.isArray(payload?.items) ? payload.items : [])\n } catch (err) {\n if ((err as { name?: string } | null)?.name === 'AbortError') return\n logger.warn('failed to load interactions', { component: 'ActivitiesDayStrip', err })\n setFetchedEvents([])\n }\n })()\n return () => controller.abort()\n }, [entityId, visibleDays, refreshKey, useProvidedEvents])\n\n const todayDate = React.useMemo(() => startOfDay(new Date()), [])\n\n const handlePrev = React.useCallback(() => {\n setAnchor((current) => addDays(current, -VISIBLE_DAYS))\n }, [])\n const handleNext = React.useCallback(() => {\n setAnchor((current) => addDays(current, VISIBLE_DAYS))\n }, [])\n const handleHeaderPrev = React.useCallback(() => {\n setAnchor((current) => {\n const next = new Date(current)\n next.setMonth(current.getMonth() - 1)\n return startOfDay(next)\n })\n }, [])\n const handleHeaderNext = React.useCallback(() => {\n setAnchor((current) => {\n const next = new Date(current)\n next.setMonth(current.getMonth() + 1)\n return startOfDay(next)\n })\n }, [])\n\n return (\n <div className=\"flex flex-col gap-2.5 rounded-md px-3.5 py-3 w-full\">\n <div className=\"flex items-center justify-center gap-1.5 rounded-md bg-muted px-1.5 py-1.5\">\n <button\n type=\"button\"\n onClick={handleHeaderPrev}\n aria-label={t('customers.activities.calendar.prevMonth', 'Previous month')}\n className=\"flex size-6 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronLeft className=\"size-4 text-foreground\" />\n </button>\n <span className=\"flex-1 text-center text-sm font-medium leading-5 text-foreground\">{headerLabel}</span>\n <button\n type=\"button\"\n onClick={handleHeaderNext}\n aria-label={t('customers.activities.calendar.nextMonth', 'Next month')}\n className=\"flex size-6 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronRight className=\"size-4 text-foreground\" />\n </button>\n </div>\n <div className=\"flex w-full items-center gap-2\">\n <button\n type=\"button\"\n onClick={handlePrev}\n aria-label={t('customers.activities.calendar.prevWindow', 'Previous days')}\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronLeft className=\"size-4 text-foreground\" />\n </button>\n <div className=\"flex flex-1 items-stretch justify-center gap-1\">\n {visibleDays.map((day) => {\n const busy = computeDayBusyness(events, day)\n const isSelected = isSameDay(day, selectedDate)\n const isToday = isSameDay(day, todayDate)\n const weekend = isWeekend(day)\n const busyLabel = busy.eventCount > 0\n ? formatBusyLabel(busy, t)\n : weekend\n ? t('customers.activities.calendar.weekend', 'Weekend')\n : ''\n return (\n <DayCard\n key={day.toISOString()}\n day={day}\n isActive={isSelected}\n isToday={isToday}\n busyness={busy}\n label={busyLabel}\n dayName={formatDayLabel(day, t)}\n onSelect={() => onSelectDate(day)}\n />\n )\n })}\n </div>\n <button\n type=\"button\"\n onClick={handleNext}\n aria-label={t('customers.activities.calendar.nextWindow', 'Next days')}\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md border border-border bg-card shadow-xs hover:bg-accent/40\"\n >\n <ChevronRight className=\"size-4 text-foreground\" />\n </button>\n </div>\n </div>\n )\n}\n\ninterface DayCardProps {\n day: Date\n isActive: boolean\n isToday: boolean\n busyness: DayBusyness\n label: string\n dayName: string\n onSelect: () => void\n}\n\nfunction DayCard({ day, isActive, isToday, busyness, label, dayName, onSelect }: DayCardProps) {\n const dayNumber = String(day.getDate()).padStart(2, '0')\n return (\n <button\n type=\"button\"\n onClick={onSelect}\n aria-pressed={isActive}\n aria-label={`${dayName} ${dayNumber}`}\n className={cn(\n 'flex h-[104px] w-[101px] flex-col items-center gap-[6px] overflow-hidden rounded-[10px] border p-[12px] transition-colors',\n isActive\n ? 'border-transparent bg-foreground'\n : 'border-border bg-card hover:border-foreground/40',\n )}\n >\n <span className=\"text-[11px] font-medium leading-none tracking-[0.44px] text-muted-foreground\">\n {dayName}\n </span>\n <div className=\"flex items-center gap-[5px]\">\n <span\n className={cn(\n 'text-2xl font-semibold leading-7',\n isActive ? 'text-background' : 'text-foreground',\n )}\n >\n {dayNumber}\n </span>\n {isToday ? (\n <span\n className=\"inline-block size-1.5 rounded-full bg-status-info-icon\"\n aria-hidden\n />\n ) : null}\n </div>\n <div className=\"flex h-4 w-[82px] items-end gap-[1.5px]\">\n {busyness.slots.map((state, index) => (\n <BusySlot key={index} state={state} active={isActive} />\n ))}\n </div>\n <span className=\"text-[11px] leading-[14px] font-normal whitespace-nowrap text-muted-foreground\">\n {label}\n </span>\n </button>\n )\n}\n\nfunction BusySlot({ state, active }: { state: SlotState; active: boolean }) {\n const heightClass = state === 'empty'\n ? 'h-0.5'\n : state === 'partial'\n ? 'h-2'\n : 'h-3.5'\n let bgClass: string\n if (state === 'conflict') {\n bgClass = 'bg-status-error-icon'\n } else if (active) {\n if (state === 'empty') bgClass = 'bg-background/30'\n else if (state === 'partial') bgClass = 'bg-background/60'\n else bgClass = 'bg-background'\n } else {\n if (state === 'empty') bgClass = 'bg-border'\n else if (state === 'partial') bgClass = 'bg-muted-foreground'\n else bgClass = 'bg-foreground'\n }\n return <div className={cn('w-[7px] shrink-0 rounded-[1.5px]', heightClass, bgClass)} aria-hidden />\n}\n\nexport default ActivitiesDayStrip\n"],
5
+ "mappings": ";AAwRM,SAOI,KAPJ;AAtRN,YAAY,WAAW;AACvB,SAAS,aAAa,oBAAoB;AAC1C,SAAS,mBAAmB;AAC5B,SAAS,UAAU;AACnB,SAAS,YAAY;AAErB,SAAS,4BAA4B;AAErC,SAAS,oB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,MAEA;AAAA,4BAAC,UAAK,WAAU,gFACb,mBACH;AAAA,QACA,qBAAC,SAAI,WAAU,+BACb;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,WAAW;AAAA,gBACT;AAAA,gBACA,WAAW,oBAAoB;AAAA,cACjC;AAAA,cAEC;AAAA;AAAA,UACH;AAAA,UACC,UACC;AAAA,YAAC;AAAA;AAAA,cACC,WAAU;AAAA,cACV,eAAW;AAAA;AAAA,UACb,IACE;AAAA,WACN;AAAA,QACA,oBAAC,SAAI,WAAU,2CACZ,mBAAS,MAAM,IAAI,CAAC,OAAO,UAC1B,oBAAC,YAAqB,OAAc,QAAQ,YAA7B,KAAuC,CACvD,GACH;AAAA,QACA,oBAAC,UAAK,WAAU,kFACb,iBACH;AAAA;AAAA;AAAA,EACF;AAEJ;AAEA,SAAS,SAAS,EAAE,OAAO,OAAO,GAA0C;AAC1E,QAAM,cAAc,UAAU,UAC1B,UACA,UAAU,YACR,QACA;AACN,MAAI;AACJ,MAAI,UAAU,YAAY;AACxB,cAAU;AAAA,EACZ,WAAW,QAAQ;AACjB,QAAI,UAAU,QAAS,WAAU;AAAA,aACxB,UAAU,UAAW,WAAU;AAAA,QACnC,WAAU;AAAA,EACjB,OAAO;AACL,QAAI,UAAU,QAAS,WAAU;AAAA,aACxB,UAAU,UAAW,WAAU;AAAA,QACnC,WAAU;AAAA,EACjB;AACA,SAAO,oBAAC,SAAI,WAAW,GAAG,oCAAoC,aAAa,OAAO,GAAG,eAAW,MAAC;AACnG;AAEA,IAAO,6BAAQ;",
6
6
  "names": []
7
7
  }
@@ -187,7 +187,7 @@ function ConfirmDealLostDialog({
187
187
  Button,
188
188
  {
189
189
  type: "button",
190
- variant: "destructive",
190
+ variant: "destructive-solid",
191
191
  disabled: confirmDisabled,
192
192
  onClick: () => {
193
193
  void handleConfirm();
@@ -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'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\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 logger.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"],
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'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\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 logger.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-solid\"\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
5
  "mappings": ";AAyIgB,cAMA,YANA;AAvIhB,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;AACpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAkBhC,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,sBAAsB,uBAAuB,IAAI,MAA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16,31 @@ const dateRangePresetSchema = z.enum([
16
16
  "last_30_days",
17
17
  "last_90_days"
18
18
  ]);
19
+ const comparisonFilterOperators = ["eq", "neq", "gt", "gte", "lt", "lte"];
20
+ const setFilterOperators = ["in", "not_in"];
21
+ const nullFilterOperators = ["is_null", "is_not_null"];
22
+ const scalarFilterOperators = [...comparisonFilterOperators, ...nullFilterOperators];
23
+ const scalarFilterOperatorSchema = z.enum(scalarFilterOperators);
24
+ const setFilterOperatorSchema = z.enum(setFilterOperators);
19
25
  const filterOperatorSchema = z.enum([
20
- "eq",
21
- "neq",
22
- "gt",
23
- "gte",
24
- "lt",
25
- "lte",
26
- "in",
27
- "not_in",
28
- "is_null",
29
- "is_not_null"
26
+ ...comparisonFilterOperators,
27
+ ...setFilterOperators,
28
+ ...nullFilterOperators
29
+ ]);
30
+ const MAX_SET_FILTER_VALUES = 200;
31
+ const setFilterMemberSchema = z.union([z.string(), z.number(), z.boolean()]);
32
+ const setFilterValueSchema = z.array(setFilterMemberSchema).max(MAX_SET_FILTER_VALUES);
33
+ const widgetDataFilterSchema = z.discriminatedUnion("operator", [
34
+ z.object({
35
+ field: z.string().min(1),
36
+ operator: setFilterOperatorSchema,
37
+ value: setFilterValueSchema
38
+ }),
39
+ z.object({
40
+ field: z.string().min(1),
41
+ operator: scalarFilterOperatorSchema,
42
+ value: z.unknown().optional()
43
+ })
30
44
  ]);
31
45
  const widgetDataRequestSchema = z.object({
32
46
  entityType: z.string().min(1),
@@ -40,13 +54,7 @@ const widgetDataRequestSchema = z.object({
40
54
  limit: z.number().int().min(1).max(100).optional(),
41
55
  resolveLabels: z.boolean().optional()
42
56
  }).optional(),
43
- filters: z.array(
44
- z.object({
45
- field: z.string().min(1),
46
- operator: filterOperatorSchema,
47
- value: z.unknown().optional()
48
- })
49
- ).optional(),
57
+ filters: z.array(widgetDataFilterSchema).optional(),
50
58
  dateRange: z.object({
51
59
  field: z.string().min(1),
52
60
  preset: dateRangePresetSchema
@@ -75,6 +83,7 @@ const widgetDataResponseSchema = z.object({
75
83
  })
76
84
  });
77
85
  export {
86
+ MAX_SET_FILTER_VALUES,
78
87
  aggregateFunctionSchema,
79
88
  dateGranularitySchema,
80
89
  dateRangePresetSchema,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/dashboards/api/widgets/data/schema.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\n\nexport const aggregateFunctionSchema = z.enum(['count', 'sum', 'avg', 'min', 'max'])\nexport const dateGranularitySchema = z.enum(['day', 'week', 'month', 'quarter', 'year'])\nexport const dateRangePresetSchema = z.enum([\n 'today',\n 'yesterday',\n 'this_week',\n 'last_week',\n 'this_month',\n 'last_month',\n 'this_quarter',\n 'last_quarter',\n 'this_year',\n 'last_year',\n 'last_7_days',\n 'last_30_days',\n 'last_90_days',\n])\n\nexport const filterOperatorSchema = z.enum([\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'in',\n 'not_in',\n 'is_null',\n 'is_not_null',\n])\n\nexport const widgetDataRequestSchema = z.object({\n entityType: z.string().min(1),\n metric: z.object({\n field: z.string().min(1),\n aggregate: aggregateFunctionSchema,\n }),\n groupBy: z\n .object({\n field: z.string().min(1),\n granularity: dateGranularitySchema.optional(),\n limit: z.number().int().min(1).max(100).optional(),\n resolveLabels: z.boolean().optional(),\n })\n .optional(),\n filters: z\n .array(\n z.object({\n field: z.string().min(1),\n operator: filterOperatorSchema,\n value: z.unknown().optional(),\n }),\n )\n .optional(),\n dateRange: z\n .object({\n field: z.string().min(1),\n preset: dateRangePresetSchema,\n })\n .optional(),\n comparison: z\n .object({\n type: z.enum(['previous_period', 'previous_year']),\n })\n .optional(),\n})\n\nexport const widgetDataItemSchema = z.object({\n groupKey: z.unknown(),\n groupLabel: z.string().optional(),\n value: z.number().nullable(),\n})\n\nexport const widgetDataResponseSchema = z.object({\n value: z.number().nullable(),\n data: z.array(widgetDataItemSchema),\n comparison: z\n .object({\n value: z.number().nullable(),\n change: z.number(),\n direction: z.enum(['up', 'down', 'unchanged']),\n })\n .optional(),\n metadata: z.object({\n fetchedAt: z.string(),\n recordCount: z.number(),\n currency: z.string().nullable().optional(),\n }),\n})\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAEX,MAAM,0BAA0B,EAAE,KAAK,CAAC,SAAS,OAAO,OAAO,OAAO,KAAK,CAAC;AAC5E,MAAM,wBAAwB,EAAE,KAAK,CAAC,OAAO,QAAQ,SAAS,WAAW,MAAM,CAAC;AAChF,MAAM,wBAAwB,EAAE,KAAK;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,MAAM,uBAAuB,EAAE,KAAK;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,MAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,YAAY,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC5B,QAAQ,EAAE,OAAO;AAAA,IACf,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACvB,WAAW;AAAA,EACb,CAAC;AAAA,EACD,SAAS,EACN,OAAO;AAAA,IACN,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACvB,aAAa,sBAAsB,SAAS;AAAA,IAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AAAA,IACjD,eAAe,EAAE,QAAQ,EAAE,SAAS;AAAA,EACtC,CAAC,EACA,SAAS;AAAA,EACZ,SAAS,EACN;AAAA,IACC,EAAE,OAAO;AAAA,MACP,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,MACvB,UAAU;AAAA,MACV,OAAO,EAAE,QAAQ,EAAE,SAAS;AAAA,IAC9B,CAAC;AAAA,EACH,EACC,SAAS;AAAA,EACZ,WAAW,EACR,OAAO;AAAA,IACN,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,IACvB,QAAQ;AAAA,EACV,CAAC,EACA,SAAS;AAAA,EACZ,YAAY,EACT,OAAO;AAAA,IACN,MAAM,EAAE,KAAK,CAAC,mBAAmB,eAAe,CAAC;AAAA,EACnD,CAAC,EACA,SAAS;AACd,CAAC;AAEM,MAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,UAAU,EAAE,QAAQ;AAAA,EACpB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,OAAO,EAAE,OAAO,EAAE,SAAS;AAC7B,CAAC;AAEM,MAAM,2BAA2B,EAAE,OAAO;AAAA,EAC/C,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,EAC3B,MAAM,EAAE,MAAM,oBAAoB;AAAA,EAClC,YAAY,EACT,OAAO;AAAA,IACN,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,IAC3B,QAAQ,EAAE,OAAO;AAAA,IACjB,WAAW,EAAE,KAAK,CAAC,MAAM,QAAQ,WAAW,CAAC;AAAA,EAC/C,CAAC,EACA,SAAS;AAAA,EACZ,UAAU,EAAE,OAAO;AAAA,IACjB,WAAW,EAAE,OAAO;AAAA,IACpB,aAAa,EAAE,OAAO;AAAA,IACtB,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC3C,CAAC;AACH,CAAC;",
4
+ "sourcesContent": ["import { z } from 'zod'\n\nexport const aggregateFunctionSchema = z.enum(['count', 'sum', 'avg', 'min', 'max'])\nexport const dateGranularitySchema = z.enum(['day', 'week', 'month', 'quarter', 'year'])\nexport const dateRangePresetSchema = z.enum([\n 'today',\n 'yesterday',\n 'this_week',\n 'last_week',\n 'this_month',\n 'last_month',\n 'this_quarter',\n 'last_quarter',\n 'this_year',\n 'last_year',\n 'last_7_days',\n 'last_30_days',\n 'last_90_days',\n])\n\nconst comparisonFilterOperators = ['eq', 'neq', 'gt', 'gte', 'lt', 'lte'] as const\nconst setFilterOperators = ['in', 'not_in'] as const\nconst nullFilterOperators = ['is_null', 'is_not_null'] as const\nconst scalarFilterOperators = [...comparisonFilterOperators, ...nullFilterOperators] as const\n\nconst scalarFilterOperatorSchema = z.enum(scalarFilterOperators)\nconst setFilterOperatorSchema = z.enum(setFilterOperators)\n\nexport const filterOperatorSchema = z.enum([\n ...comparisonFilterOperators,\n ...setFilterOperators,\n ...nullFilterOperators,\n])\n\n/**\n * Upper bound on how many members an `in` / `not_in` widget-data filter may carry (#4852).\n *\n * Every member becomes one placeholder plus one bound parameter in the aggregation's WHERE\n * clause, so the cost of a set filter is proportional to its length. The bound lives here\n * rather than in the SQL builder because `buildWhereClause` can only truncate the list \u2014\n * silently returning an answer to a different question than the caller asked \u2014 or throw from\n * deep inside query construction; validating here yields a 400 that names the offending\n * filter and is published in the route's OpenAPI schema.\n *\n * 200 is deliberately generous for a dashboard filter: the widest grouping a widget can render\n * is capped at 100 buckets (`groupBy.limit`), and a batch carries at most 50 requests, so even\n * a fully saturated batch stays an order of magnitude below PostgreSQL's per-statement limit\n * of 65535 bound parameters. Raising it later is a one-line change to this constant.\n */\nexport const MAX_SET_FILTER_VALUES = 200\n\n// `IN` / `NOT IN` compare against literals; a null member never matches either way, which is\n// what the dedicated `is_null` / `is_not_null` operators are for.\nconst setFilterMemberSchema = z.union([z.string(), z.number(), z.boolean()])\n\nconst setFilterValueSchema = z.array(setFilterMemberSchema).max(MAX_SET_FILTER_VALUES)\n\nconst widgetDataFilterSchema = z.discriminatedUnion('operator', [\n z.object({\n field: z.string().min(1),\n operator: setFilterOperatorSchema,\n value: setFilterValueSchema,\n }),\n z.object({\n field: z.string().min(1),\n operator: scalarFilterOperatorSchema,\n value: z.unknown().optional(),\n }),\n])\n\nexport const widgetDataRequestSchema = z.object({\n entityType: z.string().min(1),\n metric: z.object({\n field: z.string().min(1),\n aggregate: aggregateFunctionSchema,\n }),\n groupBy: z\n .object({\n field: z.string().min(1),\n granularity: dateGranularitySchema.optional(),\n limit: z.number().int().min(1).max(100).optional(),\n resolveLabels: z.boolean().optional(),\n })\n .optional(),\n filters: z.array(widgetDataFilterSchema).optional(),\n dateRange: z\n .object({\n field: z.string().min(1),\n preset: dateRangePresetSchema,\n })\n .optional(),\n comparison: z\n .object({\n type: z.enum(['previous_period', 'previous_year']),\n })\n .optional(),\n})\n\nexport const widgetDataItemSchema = z.object({\n groupKey: z.unknown(),\n groupLabel: z.string().optional(),\n value: z.number().nullable(),\n})\n\nexport const widgetDataResponseSchema = z.object({\n value: z.number().nullable(),\n data: z.array(widgetDataItemSchema),\n comparison: z\n .object({\n value: z.number().nullable(),\n change: z.number(),\n direction: z.enum(['up', 'down', 'unchanged']),\n })\n .optional(),\n metadata: z.object({\n fetchedAt: z.string(),\n recordCount: z.number(),\n currency: z.string().nullable().optional(),\n }),\n})\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAEX,MAAM,0BAA0B,EAAE,KAAK,CAAC,SAAS,OAAO,OAAO,OAAO,KAAK,CAAC;AAC5E,MAAM,wBAAwB,EAAE,KAAK,CAAC,OAAO,QAAQ,SAAS,WAAW,MAAM,CAAC;AAChF,MAAM,wBAAwB,EAAE,KAAK;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,MAAM,4BAA4B,CAAC,MAAM,OAAO,MAAM,OAAO,MAAM,KAAK;AACxE,MAAM,qBAAqB,CAAC,MAAM,QAAQ;AAC1C,MAAM,sBAAsB,CAAC,WAAW,aAAa;AACrD,MAAM,wBAAwB,CAAC,GAAG,2BAA2B,GAAG,mBAAmB;AAEnF,MAAM,6BAA6B,EAAE,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AAO,EAAE,IAAI,CAAC;AAAA,IACvB,QAAQ;AAAA,EACV,CAAC,EACA,SAAS;AAAA,EACZ,YAAY,EACT,OAAO;AAAA,IACN,MAAM,EAAE,KAAK,CAAC,mBAAmB,eAAe,CAAC;AAAA,EACnD,CAAC,EACA,SAAS;AACd,CAAC;AAEM,MAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,UAAU,EAAE,QAAQ;AAAA,EACpB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,OAAO,EAAE,OAAO,EAAE,SAAS;AAC7B,CAAC;AAEM,MAAM,2BAA2B,EAAE,OAAO;AAAA,EAC/C,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,EAC3B,MAAM,EAAE,MAAM,oBAAoB;AAAA,EAClC,YAAY,EACT,OAAO;AAAA,IACN,OAAO,EAAE,OAAO,EAAE,SAAS;AAAA,IAC3B,QAAQ,EAAE,OAAO;AAAA,IACjB,WAAW,EAAE,KAAK,CAAC,MAAM,QAAQ,WAAW,CAAC;AAAA,EAC/C,CAAC,EACA,SAAS;AAAA,EACZ,UAAU,EAAE,OAAO;AAAA,IACjB,WAAW,EAAE,OAAO;AAAA,IACpB,aAAa,EAAE,OAAO;AAAA,IACtB,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EAC3C,CAAC;AACH,CAAC;",
6
6
  "names": []
7
7
  }
@@ -69,6 +69,15 @@ function resolveGroupExpression(registry, entityType, groupBy) {
69
69
  }
70
70
  return { expression: groupMapping.dbColumn, dbColumn: groupMapping.dbColumn, jsonPath: null };
71
71
  }
72
+ function normalizeSetFilterValues(value) {
73
+ const values = Array.isArray(value) ? value : value === void 0 ? [] : [value];
74
+ if (values.some((member) => member === null || member === void 0)) {
75
+ throw new Error(
76
+ "[internal] Set filter members must not be null or undefined \u2014 use the is_null / is_not_null operators to filter on nullness"
77
+ );
78
+ }
79
+ return values;
80
+ }
72
81
  function buildWhereClause(options) {
73
82
  const { registry } = options;
74
83
  const params = [];
@@ -119,13 +128,18 @@ function buildWhereClause(options) {
119
128
  params.push(filter.value);
120
129
  break;
121
130
  case "in":
122
- whereClauses.push(`${filterMapping.dbColumn} = ANY(?)`);
123
- params.push(filter.value);
124
- break;
125
- case "not_in":
126
- whereClauses.push(`${filterMapping.dbColumn} != ALL(?)`);
127
- params.push(filter.value);
131
+ case "not_in": {
132
+ const values = normalizeSetFilterValues(filter.value);
133
+ if (values.length === 0) {
134
+ whereClauses.push(filter.operator === "in" ? "FALSE" : "TRUE");
135
+ break;
136
+ }
137
+ const keyword = filter.operator === "in" ? "IN" : "NOT IN";
138
+ const placeholders = values.map(() => "?").join(", ");
139
+ whereClauses.push(`${filterMapping.dbColumn} ${keyword} (${placeholders})`);
140
+ params.push(...values);
128
141
  break;
142
+ }
129
143
  case "is_null":
130
144
  whereClauses.push(`${filterMapping.dbColumn} IS NULL`);
131
145
  break;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/dashboards/lib/aggregations.ts"],
4
- "sourcesContent": ["import type { AnalyticsRegistry } from '../services/analyticsRegistry'\nimport type { AnalyticsEntityTypeConfig, AnalyticsFieldMapping } from '@open-mercato/shared/modules/analytics'\n\nexport type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max'\nexport type DateGranularity = 'day' | 'week' | 'month' | 'quarter' | 'year'\n\nconst VALID_GRANULARITIES: readonly DateGranularity[] = ['day', 'week', 'month', 'quarter', 'year']\nconst VALID_AGGREGATES: readonly AggregateFunction[] = ['count', 'sum', 'avg', 'min', 'max']\nconst SAFE_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\nexport function isValidGranularity(value: unknown): value is DateGranularity {\n return typeof value === 'string' && VALID_GRANULARITIES.includes(value as DateGranularity)\n}\n\nexport function isValidAggregate(value: unknown): value is AggregateFunction {\n return typeof value === 'string' && VALID_AGGREGATES.includes(value as AggregateFunction)\n}\n\nfunction isSafeIdentifier(value: string): boolean {\n return SAFE_IDENTIFIER_PATTERN.test(value)\n}\n\n// Re-export types from shared module for convenience\nexport type EntityTypeConfig = AnalyticsEntityTypeConfig\nexport type FieldMapping = AnalyticsFieldMapping\n\nexport function buildAggregateExpression(aggregate: AggregateFunction, column: string): string {\n switch (aggregate) {\n case 'count':\n return column === 'id' ? 'COUNT(*)' : `COUNT(${column})`\n case 'sum':\n return `COALESCE(SUM(${column}::numeric), 0)`\n case 'avg':\n return `COALESCE(AVG(${column}::numeric), 0)`\n case 'min':\n return `MIN(${column}::numeric)`\n case 'max':\n return `MAX(${column}::numeric)`\n default:\n return `COUNT(*)`\n }\n}\n\nexport function buildDateTruncExpression(column: string, granularity: DateGranularity): string {\n if (!isValidGranularity(granularity)) {\n throw new Error(`Invalid granularity: ${granularity}`)\n }\n return `DATE_TRUNC('${granularity}', ${column})`\n}\n\nexport function buildJsonbFieldExpression(column: string, path: string): string {\n const parts = path.split('.')\n for (const part of parts) {\n if (!isSafeIdentifier(part)) {\n throw new Error(`Invalid JSONB path part: ${part}`)\n }\n }\n if (parts.length === 1) {\n return `${column}->>'${parts[0]}'`\n }\n const intermediate = parts.slice(0, -1).map((p) => `'${p}'`).join('->')\n const lastPart = parts[parts.length - 1]\n return `${column}->${intermediate}->>'${lastPart}'`\n}\n\nexport type AggregationQuery = {\n sql: string\n params: unknown[]\n}\n\nexport type BuildAggregationQueryOptions = {\n entityType: string\n metric: {\n field: string\n aggregate: AggregateFunction\n }\n groupBy?: {\n field: string\n granularity?: DateGranularity\n limit?: number\n }\n dateRange?: {\n field: string\n start: Date\n end: Date\n }\n filters?: Array<{\n field: string\n operator: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'not_in' | 'is_null' | 'is_not_null'\n value?: unknown\n }>\n scope: {\n tenantId: string\n organizationIds?: string[]\n }\n /** Analytics registry for resolving entity and field configurations */\n registry: AnalyticsRegistry\n}\n\nexport type ResolvedGroupExpression = {\n expression: string\n /** Column the group expression reads from \u2014 the encryption map is keyed by this. */\n dbColumn: string\n /** JSONB path below `dbColumn`, when the groupBy field used path notation. */\n jsonPath: string | null\n}\n\n/**\n * Resolves the SQL expression a groupBy field maps to, together with the underlying column so\n * callers can decide whether the source is encrypted at rest before grouping over it (#4622).\n */\nexport function resolveGroupExpression(\n registry: AnalyticsRegistry,\n entityType: string,\n groupBy: { field: string; granularity?: DateGranularity },\n): ResolvedGroupExpression | null {\n const groupMapping = registry.getFieldMapping(entityType, groupBy.field)\n\n // Handle JSONB path notation (e.g., shippingAddressSnapshot.region)\n if (!groupMapping && groupBy.field.includes('.')) {\n const [baseField, ...pathParts] = groupBy.field.split('.')\n const baseMapping = registry.getFieldMapping(entityType, baseField)\n if (baseMapping?.type !== 'jsonb') return null\n const jsonPath = pathParts.join('.')\n return {\n expression: buildJsonbFieldExpression(baseMapping.dbColumn, jsonPath),\n dbColumn: baseMapping.dbColumn,\n jsonPath,\n }\n }\n\n if (!groupMapping) return null\n\n if (groupMapping.type === 'timestamp' && groupBy.granularity) {\n return {\n expression: buildDateTruncExpression(groupMapping.dbColumn, groupBy.granularity),\n dbColumn: groupMapping.dbColumn,\n jsonPath: null,\n }\n }\n\n return { expression: groupMapping.dbColumn, dbColumn: groupMapping.dbColumn, jsonPath: null }\n}\n\nfunction buildWhereClause(\n options: Pick<BuildAggregationQueryOptions, 'entityType' | 'dateRange' | 'filters' | 'scope' | 'registry'>,\n): { clause: string; params: unknown[] } {\n const { registry } = options\n const params: unknown[] = []\n const whereClauses: string[] = []\n\n whereClauses.push(`tenant_id = ?`)\n params.push(options.scope.tenantId)\n\n if (options.scope.organizationIds && options.scope.organizationIds.length > 0) {\n whereClauses.push(`organization_id = ANY(?::uuid[])`)\n params.push(`{${options.scope.organizationIds.join(',')}}`)\n }\n\n whereClauses.push(`deleted_at IS NULL`)\n\n if (options.dateRange) {\n const dateMapping = registry.getFieldMapping(options.entityType, options.dateRange.field)\n if (dateMapping) {\n whereClauses.push(`${dateMapping.dbColumn} >= ?`)\n params.push(options.dateRange.start)\n whereClauses.push(`${dateMapping.dbColumn} <= ?`)\n params.push(options.dateRange.end)\n }\n }\n\n if (options.filters) {\n for (const filter of options.filters) {\n const filterMapping = registry.getFieldMapping(options.entityType, filter.field)\n if (!filterMapping) continue\n\n switch (filter.operator) {\n case 'eq':\n whereClauses.push(`${filterMapping.dbColumn} = ?`)\n params.push(filter.value)\n break\n case 'neq':\n whereClauses.push(`${filterMapping.dbColumn} != ?`)\n params.push(filter.value)\n break\n case 'gt':\n whereClauses.push(`${filterMapping.dbColumn} > ?`)\n params.push(filter.value)\n break\n case 'gte':\n whereClauses.push(`${filterMapping.dbColumn} >= ?`)\n params.push(filter.value)\n break\n case 'lt':\n whereClauses.push(`${filterMapping.dbColumn} < ?`)\n params.push(filter.value)\n break\n case 'lte':\n whereClauses.push(`${filterMapping.dbColumn} <= ?`)\n params.push(filter.value)\n break\n case 'in':\n whereClauses.push(`${filterMapping.dbColumn} = ANY(?)`)\n params.push(filter.value)\n break\n case 'not_in':\n whereClauses.push(`${filterMapping.dbColumn} != ALL(?)`)\n params.push(filter.value)\n break\n case 'is_null':\n whereClauses.push(`${filterMapping.dbColumn} IS NULL`)\n break\n case 'is_not_null':\n whereClauses.push(`${filterMapping.dbColumn} IS NOT NULL`)\n break\n }\n }\n }\n\n return { clause: whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '', params }\n}\n\nfunction resolveTableName(config: EntityTypeConfig): string {\n return config.schema ? `\"${config.schema}\".\"${config.tableName}\"` : `\"${config.tableName}\"`\n}\n\nexport type BuildDistinctCurrencyQueryOptions = Pick<\n BuildAggregationQueryOptions,\n 'entityType' | 'dateRange' | 'filters' | 'scope' | 'registry'\n>\n\n/**\n * Builds the query that reads the distinct per-row currencies of the rows an aggregation\n * would sum, over exactly the same tenant/organization scope, date range and filters.\n * Returns `null` when the entity declares no `currencyField`, which means its amounts are\n * not per-row denominated and there is nothing to verify (#4676).\n */\nexport function buildDistinctCurrencyQuery(\n options: BuildDistinctCurrencyQueryOptions,\n): AggregationQuery | null {\n const { registry } = options\n const config = registry.getEntityTypeConfig(options.entityType)\n if (!config?.currencyField) return null\n\n const currencyMapping = registry.getFieldMapping(options.entityType, config.currencyField)\n if (!currencyMapping || !isSafeIdentifier(currencyMapping.dbColumn)) return null\n\n const where = buildWhereClause(options)\n const normalizedCurrencyExpression = `UPPER(NULLIF(BTRIM(${currencyMapping.dbColumn}), ''))`\n const sql = [\n `SELECT DISTINCT ${normalizedCurrencyExpression} AS code`,\n `FROM ${resolveTableName(config)}`,\n where.clause,\n 'LIMIT 2',\n ]\n .filter(Boolean)\n .join(' ')\n\n return { sql, params: where.params }\n}\n\nexport function buildAggregationQuery(options: BuildAggregationQueryOptions): AggregationQuery | null {\n const { registry } = options\n const config = registry.getEntityTypeConfig(options.entityType)\n if (!config) return null\n\n const metricMapping = registry.getFieldMapping(options.entityType, options.metric.field)\n if (!metricMapping) return null\n\n const tableName = resolveTableName(config)\n const aggregateExpr = buildAggregateExpression(options.metric.aggregate, metricMapping.dbColumn)\n\n let selectClause = `SELECT ${aggregateExpr} AS value`\n let groupByClause = ''\n let orderByClause = ''\n let limitClause = ''\n\n if (options.groupBy) {\n const resolved = resolveGroupExpression(registry, options.entityType, options.groupBy)\n\n if (resolved) {\n selectClause = `SELECT ${resolved.expression} AS group_key, ${aggregateExpr} AS value`\n groupByClause = `GROUP BY ${resolved.expression}`\n // NULLS LAST is stated explicitly (PostgreSQL defaults DESC to NULLS FIRST) so a group limit\n // keeps the highest-value buckets instead of the empty ones, and so the application-side\n // encrypted path can mirror the same ordering (#4622).\n orderByClause = `ORDER BY value DESC NULLS LAST`\n\n if (options.groupBy.limit && options.groupBy.limit > 0) {\n limitClause = `LIMIT ${Math.min(options.groupBy.limit, 100)}`\n }\n }\n }\n\n const where = buildWhereClause(options)\n\n const sql = [selectClause, `FROM ${tableName}`, where.clause, groupByClause, orderByClause, limitClause]\n .filter(Boolean)\n .join(' ')\n\n return { sql, params: where.params }\n}\n\nexport type BuildGroupSourceRowsQueryOptions = Omit<BuildAggregationQueryOptions, 'groupBy'> & {\n /** Column holding the (encrypted) group source, resolved via `resolveGroupExpression`. */\n groupColumn: string\n /** Hard cap on scanned rows; callers fetch `rowLimit + 1` to detect overflow. */\n rowLimit: number\n}\n\n/**\n * Builds a per-row query for group sources that cannot be grouped in SQL because the column is\n * encrypted at rest. Returns the raw group source alongside the metric value so the caller can\n * decrypt, then aggregate in application code (#4622).\n */\nexport function buildGroupSourceRowsQuery(options: BuildGroupSourceRowsQueryOptions): AggregationQuery | null {\n const { registry } = options\n const config = registry.getEntityTypeConfig(options.entityType)\n if (!config) return null\n\n const metricMapping = registry.getFieldMapping(options.entityType, options.metric.field)\n if (!metricMapping) return null\n\n if (!isSafeIdentifier(options.groupColumn)) {\n throw new Error(`Invalid group column: ${options.groupColumn}`)\n }\n\n const where = buildWhereClause(options)\n const sql = [\n `SELECT ${options.groupColumn} AS group_source, ${metricMapping.dbColumn} AS metric_value`,\n `FROM ${resolveTableName(config)}`,\n where.clause,\n `LIMIT ${Math.max(1, Math.floor(options.rowLimit)) + 1}`,\n ]\n .filter(Boolean)\n .join(' ')\n\n return { sql, params: where.params }\n}\n"],
5
- "mappings": "AAMA,MAAM,sBAAkD,CAAC,OAAO,QAAQ,SAAS,WAAW,MAAM;AAClG,MAAM,mBAAiD,CAAC,SAAS,OAAO,OAAO,OAAO,KAAK;AAC3F,MAAM,0BAA0B;AAEzB,SAAS,mBAAmB,OAA0C;AAC3E,SAAO,OAAO,UAAU,YAAY,oBAAoB,SAAS,KAAwB;AAC3F;AAEO,SAAS,iBAAiB,OAA4C;AAC3E,SAAO,OAAO,UAAU,YAAY,iBAAiB,SAAS,KAA0B;AAC1F;AAEA,SAAS,iBAAiB,OAAwB;AAChD,SAAO,wBAAwB,KAAK,KAAK;AAC3C;AAMO,SAAS,yBAAyB,WAA8B,QAAwB;AAC7F,UAAQ,WAAW;AAAA,IACjB,KAAK;AACH,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GAAG,CAAC;AAAA,MAC7D;AAAA,IACF;AAAA,EACF;AAEA,QAAM,QAAQ,iBAAiB,OAAO;AAEtC,QAAM,MAAM,CAAC,cAAc,QAAQ,SAAS,IAAI,MAAM,QAAQ,eAAe,eAAe,WAAW,EACpG,OAAO,OAAO,EACd,KAAK,GAAG;AAEX,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;AAcO,SAAS,0BAA0B,SAAoE;AAC5G,QAAM,EAAE,SAAS,IAAI;AACrB,QAAM,SAAS,SAAS,oBAAoB,QAAQ,UAAU;AAC9D,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,gBAAgB,SAAS,gBAAgB,QAAQ,YAAY,QAAQ,OAAO,KAAK;AACvF,MAAI,CAAC,cAAe,QAAO;AAE3B,MAAI,CAAC,iBAAiB,QAAQ,WAAW,GAAG;AAC1C,UAAM,IAAI,MAAM,yBAAyB,QAAQ,WAAW,EAAE;AAAA,EAChE;AAEA,QAAM,QAAQ,iBAAiB,OAAO;AACtC,QAAM,MAAM;AAAA,IACV,UAAU,QAAQ,WAAW,qBAAqB,cAAc,QAAQ;AAAA,IACxE,QAAQ,iBAAiB,MAAM,CAAC;AAAA,IAChC,MAAM;AAAA,IACN,SAAS,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,QAAQ,CAAC,IAAI,CAAC;AAAA,EACxD,EACG,OAAO,OAAO,EACd,KAAK,GAAG;AAEX,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;",
4
+ "sourcesContent": ["import type { AnalyticsRegistry } from '../services/analyticsRegistry'\nimport type { AnalyticsEntityTypeConfig, AnalyticsFieldMapping } from '@open-mercato/shared/modules/analytics'\n\nexport type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max'\nexport type DateGranularity = 'day' | 'week' | 'month' | 'quarter' | 'year'\n\nconst VALID_GRANULARITIES: readonly DateGranularity[] = ['day', 'week', 'month', 'quarter', 'year']\nconst VALID_AGGREGATES: readonly AggregateFunction[] = ['count', 'sum', 'avg', 'min', 'max']\nconst SAFE_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/\n\nexport function isValidGranularity(value: unknown): value is DateGranularity {\n return typeof value === 'string' && VALID_GRANULARITIES.includes(value as DateGranularity)\n}\n\nexport function isValidAggregate(value: unknown): value is AggregateFunction {\n return typeof value === 'string' && VALID_AGGREGATES.includes(value as AggregateFunction)\n}\n\nfunction isSafeIdentifier(value: string): boolean {\n return SAFE_IDENTIFIER_PATTERN.test(value)\n}\n\n// Re-export types from shared module for convenience\nexport type EntityTypeConfig = AnalyticsEntityTypeConfig\nexport type FieldMapping = AnalyticsFieldMapping\n\nexport function buildAggregateExpression(aggregate: AggregateFunction, column: string): string {\n switch (aggregate) {\n case 'count':\n return column === 'id' ? 'COUNT(*)' : `COUNT(${column})`\n case 'sum':\n return `COALESCE(SUM(${column}::numeric), 0)`\n case 'avg':\n return `COALESCE(AVG(${column}::numeric), 0)`\n case 'min':\n return `MIN(${column}::numeric)`\n case 'max':\n return `MAX(${column}::numeric)`\n default:\n return `COUNT(*)`\n }\n}\n\nexport function buildDateTruncExpression(column: string, granularity: DateGranularity): string {\n if (!isValidGranularity(granularity)) {\n throw new Error(`Invalid granularity: ${granularity}`)\n }\n return `DATE_TRUNC('${granularity}', ${column})`\n}\n\nexport function buildJsonbFieldExpression(column: string, path: string): string {\n const parts = path.split('.')\n for (const part of parts) {\n if (!isSafeIdentifier(part)) {\n throw new Error(`Invalid JSONB path part: ${part}`)\n }\n }\n if (parts.length === 1) {\n return `${column}->>'${parts[0]}'`\n }\n const intermediate = parts.slice(0, -1).map((p) => `'${p}'`).join('->')\n const lastPart = parts[parts.length - 1]\n return `${column}->${intermediate}->>'${lastPart}'`\n}\n\nexport type AggregationQuery = {\n sql: string\n params: unknown[]\n}\n\nexport type BuildAggregationQueryOptions = {\n entityType: string\n metric: {\n field: string\n aggregate: AggregateFunction\n }\n groupBy?: {\n field: string\n granularity?: DateGranularity\n limit?: number\n }\n dateRange?: {\n field: string\n start: Date\n end: Date\n }\n filters?: Array<{\n field: string\n operator: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'not_in' | 'is_null' | 'is_not_null'\n value?: unknown\n }>\n scope: {\n tenantId: string\n organizationIds?: string[]\n }\n /** Analytics registry for resolving entity and field configurations */\n registry: AnalyticsRegistry\n}\n\nexport type ResolvedGroupExpression = {\n expression: string\n /** Column the group expression reads from \u2014 the encryption map is keyed by this. */\n dbColumn: string\n /** JSONB path below `dbColumn`, when the groupBy field used path notation. */\n jsonPath: string | null\n}\n\n/**\n * Resolves the SQL expression a groupBy field maps to, together with the underlying column so\n * callers can decide whether the source is encrypted at rest before grouping over it (#4622).\n */\nexport function resolveGroupExpression(\n registry: AnalyticsRegistry,\n entityType: string,\n groupBy: { field: string; granularity?: DateGranularity },\n): ResolvedGroupExpression | null {\n const groupMapping = registry.getFieldMapping(entityType, groupBy.field)\n\n // Handle JSONB path notation (e.g., shippingAddressSnapshot.region)\n if (!groupMapping && groupBy.field.includes('.')) {\n const [baseField, ...pathParts] = groupBy.field.split('.')\n const baseMapping = registry.getFieldMapping(entityType, baseField)\n if (baseMapping?.type !== 'jsonb') return null\n const jsonPath = pathParts.join('.')\n return {\n expression: buildJsonbFieldExpression(baseMapping.dbColumn, jsonPath),\n dbColumn: baseMapping.dbColumn,\n jsonPath,\n }\n }\n\n if (!groupMapping) return null\n\n if (groupMapping.type === 'timestamp' && groupBy.granularity) {\n return {\n expression: buildDateTruncExpression(groupMapping.dbColumn, groupBy.granularity),\n dbColumn: groupMapping.dbColumn,\n jsonPath: null,\n }\n }\n\n return { expression: groupMapping.dbColumn, dbColumn: groupMapping.dbColumn, jsonPath: null }\n}\n\n/**\n * Normalizes the value of a set filter (`in` / `not_in`) into the list of members it selects.\n *\n * The list is rendered as one placeholder per member rather than as a single array parameter:\n * MikroORM does not bind parameters at the driver level \u2014 `AbstractSqlConnection.execute` calls\n * `platform.formatQuery`, which interpolates each value through `BasePostgreSqlPlatform.escape`,\n * and that renders a JavaScript array as a bare comma-separated list. The previous\n * `= ANY(?)` / `!= ALL(?)` form therefore produced `= ANY('a', 'b')`, which PostgreSQL rejects\n * for every shape of value (#4669).\n *\n * A missing value yields an empty set rather than a dropped filter, so an `in` filter the caller\n * failed to populate selects nothing instead of silently widening the result.\n *\n * A null or undefined *member* is refused instead of rendered. `column IN (NULL)` matches no row\n * and `column NOT IN ('a', NULL)` is NULL for every row, so such a member would return an empty\n * aggregation with no error \u2014 a silent zero on a reporting surface, which is worse than a loud\n * failure. Requests are already rejected at the API boundary by `widgetDataFilterSchema` in\n * `api/widgets/data/schema.ts`; this throw keeps in-process callers, whose filter values are\n * typed as `unknown`, from reaching the same silent path. Nullness is queried with the dedicated\n * `is_null` / `is_not_null` operators.\n */\nfunction normalizeSetFilterValues(value: unknown): unknown[] {\n const values = Array.isArray(value) ? value : value === undefined ? [] : [value]\n if (values.some((member) => member === null || member === undefined)) {\n throw new Error(\n '[internal] Set filter members must not be null or undefined \u2014 use the is_null / is_not_null operators to filter on nullness',\n )\n }\n return values\n}\n\nfunction buildWhereClause(\n options: Pick<BuildAggregationQueryOptions, 'entityType' | 'dateRange' | 'filters' | 'scope' | 'registry'>,\n): { clause: string; params: unknown[] } {\n const { registry } = options\n const params: unknown[] = []\n const whereClauses: string[] = []\n\n whereClauses.push(`tenant_id = ?`)\n params.push(options.scope.tenantId)\n\n if (options.scope.organizationIds && options.scope.organizationIds.length > 0) {\n whereClauses.push(`organization_id = ANY(?::uuid[])`)\n params.push(`{${options.scope.organizationIds.join(',')}}`)\n }\n\n whereClauses.push(`deleted_at IS NULL`)\n\n if (options.dateRange) {\n const dateMapping = registry.getFieldMapping(options.entityType, options.dateRange.field)\n if (dateMapping) {\n whereClauses.push(`${dateMapping.dbColumn} >= ?`)\n params.push(options.dateRange.start)\n whereClauses.push(`${dateMapping.dbColumn} <= ?`)\n params.push(options.dateRange.end)\n }\n }\n\n if (options.filters) {\n for (const filter of options.filters) {\n const filterMapping = registry.getFieldMapping(options.entityType, filter.field)\n if (!filterMapping) continue\n\n switch (filter.operator) {\n case 'eq':\n whereClauses.push(`${filterMapping.dbColumn} = ?`)\n params.push(filter.value)\n break\n case 'neq':\n whereClauses.push(`${filterMapping.dbColumn} != ?`)\n params.push(filter.value)\n break\n case 'gt':\n whereClauses.push(`${filterMapping.dbColumn} > ?`)\n params.push(filter.value)\n break\n case 'gte':\n whereClauses.push(`${filterMapping.dbColumn} >= ?`)\n params.push(filter.value)\n break\n case 'lt':\n whereClauses.push(`${filterMapping.dbColumn} < ?`)\n params.push(filter.value)\n break\n case 'lte':\n whereClauses.push(`${filterMapping.dbColumn} <= ?`)\n params.push(filter.value)\n break\n case 'in':\n case 'not_in': {\n const values = normalizeSetFilterValues(filter.value)\n if (values.length === 0) {\n whereClauses.push(filter.operator === 'in' ? 'FALSE' : 'TRUE')\n break\n }\n const keyword = filter.operator === 'in' ? 'IN' : 'NOT IN'\n const placeholders = values.map(() => '?').join(', ')\n whereClauses.push(`${filterMapping.dbColumn} ${keyword} (${placeholders})`)\n params.push(...values)\n break\n }\n case 'is_null':\n whereClauses.push(`${filterMapping.dbColumn} IS NULL`)\n break\n case 'is_not_null':\n whereClauses.push(`${filterMapping.dbColumn} IS NOT NULL`)\n break\n }\n }\n }\n\n return { clause: whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '', params }\n}\n\nfunction resolveTableName(config: EntityTypeConfig): string {\n return config.schema ? `\"${config.schema}\".\"${config.tableName}\"` : `\"${config.tableName}\"`\n}\n\nexport type BuildDistinctCurrencyQueryOptions = Pick<\n BuildAggregationQueryOptions,\n 'entityType' | 'dateRange' | 'filters' | 'scope' | 'registry'\n>\n\n/**\n * Builds the query that reads the distinct per-row currencies of the rows an aggregation\n * would sum, over exactly the same tenant/organization scope, date range and filters.\n * Returns `null` when the entity declares no `currencyField`, which means its amounts are\n * not per-row denominated and there is nothing to verify (#4676).\n */\nexport function buildDistinctCurrencyQuery(\n options: BuildDistinctCurrencyQueryOptions,\n): AggregationQuery | null {\n const { registry } = options\n const config = registry.getEntityTypeConfig(options.entityType)\n if (!config?.currencyField) return null\n\n const currencyMapping = registry.getFieldMapping(options.entityType, config.currencyField)\n if (!currencyMapping || !isSafeIdentifier(currencyMapping.dbColumn)) return null\n\n const where = buildWhereClause(options)\n const normalizedCurrencyExpression = `UPPER(NULLIF(BTRIM(${currencyMapping.dbColumn}), ''))`\n const sql = [\n `SELECT DISTINCT ${normalizedCurrencyExpression} AS code`,\n `FROM ${resolveTableName(config)}`,\n where.clause,\n 'LIMIT 2',\n ]\n .filter(Boolean)\n .join(' ')\n\n return { sql, params: where.params }\n}\n\nexport function buildAggregationQuery(options: BuildAggregationQueryOptions): AggregationQuery | null {\n const { registry } = options\n const config = registry.getEntityTypeConfig(options.entityType)\n if (!config) return null\n\n const metricMapping = registry.getFieldMapping(options.entityType, options.metric.field)\n if (!metricMapping) return null\n\n const tableName = resolveTableName(config)\n const aggregateExpr = buildAggregateExpression(options.metric.aggregate, metricMapping.dbColumn)\n\n let selectClause = `SELECT ${aggregateExpr} AS value`\n let groupByClause = ''\n let orderByClause = ''\n let limitClause = ''\n\n if (options.groupBy) {\n const resolved = resolveGroupExpression(registry, options.entityType, options.groupBy)\n\n if (resolved) {\n selectClause = `SELECT ${resolved.expression} AS group_key, ${aggregateExpr} AS value`\n groupByClause = `GROUP BY ${resolved.expression}`\n // NULLS LAST is stated explicitly (PostgreSQL defaults DESC to NULLS FIRST) so a group limit\n // keeps the highest-value buckets instead of the empty ones, and so the application-side\n // encrypted path can mirror the same ordering (#4622).\n orderByClause = `ORDER BY value DESC NULLS LAST`\n\n if (options.groupBy.limit && options.groupBy.limit > 0) {\n limitClause = `LIMIT ${Math.min(options.groupBy.limit, 100)}`\n }\n }\n }\n\n const where = buildWhereClause(options)\n\n const sql = [selectClause, `FROM ${tableName}`, where.clause, groupByClause, orderByClause, limitClause]\n .filter(Boolean)\n .join(' ')\n\n return { sql, params: where.params }\n}\n\nexport type BuildGroupSourceRowsQueryOptions = Omit<BuildAggregationQueryOptions, 'groupBy'> & {\n /** Column holding the (encrypted) group source, resolved via `resolveGroupExpression`. */\n groupColumn: string\n /** Hard cap on scanned rows; callers fetch `rowLimit + 1` to detect overflow. */\n rowLimit: number\n}\n\n/**\n * Builds a per-row query for group sources that cannot be grouped in SQL because the column is\n * encrypted at rest. Returns the raw group source alongside the metric value so the caller can\n * decrypt, then aggregate in application code (#4622).\n */\nexport function buildGroupSourceRowsQuery(options: BuildGroupSourceRowsQueryOptions): AggregationQuery | null {\n const { registry } = options\n const config = registry.getEntityTypeConfig(options.entityType)\n if (!config) return null\n\n const metricMapping = registry.getFieldMapping(options.entityType, options.metric.field)\n if (!metricMapping) return null\n\n if (!isSafeIdentifier(options.groupColumn)) {\n throw new Error(`Invalid group column: ${options.groupColumn}`)\n }\n\n const where = buildWhereClause(options)\n const sql = [\n `SELECT ${options.groupColumn} AS group_source, ${metricMapping.dbColumn} AS metric_value`,\n `FROM ${resolveTableName(config)}`,\n where.clause,\n `LIMIT ${Math.max(1, Math.floor(options.rowLimit)) + 1}`,\n ]\n .filter(Boolean)\n .join(' ')\n\n return { sql, params: where.params }\n}\n"],
5
+ "mappings": "AAMA,MAAM,sBAAkD,CAAC,OAAO,QAAQ,SAAS,WAAW,MAAM;AAClG,MAAM,mBAAiD,CAAC,SAAS,OAAO,OAAO,OAAO,KAAK;AAC3F,MAAM,0BAA0B;AAEzB,SAAS,mBAAmB,OAA0C;AAC3E,SAAO,OAAO,UAAU,YAAY,oBAAoB,SAAS,KAAwB;AAC3F;AAEO,SAAS,iBAAiB,OAA4C;AAC3E,SAAO,OAAO,UAAU,YAAY,iBAAiB,SAAS,KAA0B;AAC1F;AAEA,SAAS,iBAAiB,OAAwB;AAChD,SAAO,wBAAwB,KAAK,KAAK;AAC3C;AAMO,SAAS,yBAAyB,WAA8B,QAAwB;AAC7F,UAAQ,WAAW;AAAA,IACjB,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AAS,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,QAAQ,CAAC,IAAI,CAAC;AAAA,EACxD,EACG,OAAO,OAAO,EACd,KAAK,GAAG;AAEX,SAAO,EAAE,KAAK,QAAQ,MAAM,OAAO;AACrC;",
6
6
  "names": []
7
7
  }
@@ -260,11 +260,11 @@ const notesAdapter: NotesDataAdapter = {
260
260
  entityId={personId}
261
261
  viewerUserId={viewer.id}
262
262
  viewerName={viewer.name}
263
- emptyLabel={t('customers.people.detail.notes.empty')}
264
- addActionLabel={t('customers.people.detail.notes.add')}
263
+ emptyLabel={t('design_system.gallery.samples.notes.empty')}
264
+ addActionLabel={t('design_system.gallery.samples.notes.add')}
265
265
  emptyState={{
266
- title: t('customers.people.detail.notes.emptyTitle'),
267
- actionLabel: t('customers.people.detail.notes.add'),
266
+ title: t('design_system.gallery.samples.notes.emptyTitle'),
267
+ actionLabel: t('design_system.gallery.samples.notes.add'),
268
268
  }}
269
269
  translator={t}
270
270
  dataAdapter={notesAdapter}
@@ -302,10 +302,10 @@ const addressesAdapter: AddressDataAdapter = {
302
302
 
303
303
  <AddressesSection
304
304
  entityId={personId}
305
- emptyLabel={t('customers.people.detail.addresses.empty')}
305
+ emptyLabel={t('design_system.gallery.samples.addresses.empty')}
306
306
  addActionLabel={t('customers.people.detail.addresses.add')}
307
307
  emptyState={{
308
- title: t('customers.people.detail.addresses.emptyTitle'),
308
+ title: t('design_system.gallery.samples.addresses.emptyTitle'),
309
309
  actionLabel: t('customers.people.detail.addresses.add'),
310
310
  }}
311
311
  translator={t}
@@ -338,8 +338,8 @@ const attachmentsSectionEntry = {
338
338
  <AttachmentsSection
339
339
  entityId="customers:person"
340
340
  recordId={person?.id ?? null}
341
- title={t('customers.people.detail.attachments.title')}
342
- description={t('customers.people.detail.attachments.description')}
341
+ title={t('design_system.gallery.samples.attachments.title')}
342
+ description={t('design_system.gallery.samples.attachments.description')}
343
343
  />`
344
344
  }
345
345
  ]
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/design_system/gallery/entries/detail.tsx"],
4
- "sourcesContent": ["import * as React from 'react'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport {\n AddressesSection,\n AttachmentsSection,\n DetailFieldsSection,\n ErrorMessage,\n LoadingMessage,\n NotesSection,\n type AddressDataAdapter,\n type DetailFieldConfig,\n type NotesSectionProps,\n} from '@open-mercato/ui/backend/detail'\nimport type { GalleryEntry } from '../types'\n\n// Component titles and variant names are proper nouns from the codebase and\n// are deliberately not translated. `code` MUST contain the entry's importPath\n// (enforced by the registry-integrity test) and is always reviewed alongside\n// its sibling `render`.\n\n// Data-backed sections (Notes/Addresses) take adapter objects \u2014 the demos pass\n// inline in-memory adapters, so previews never touch an API. AttachmentsSection\n// fetches through `apiCall` internally and cannot take an adapter; it is shown\n// in its `recordId={null}` state, where fetching is disabled by design.\n\nconst saveNoop = async () => {}\n\nconst fieldGrid: DetailFieldConfig[] = [\n {\n key: 'first-name',\n kind: 'text',\n label: 'First name',\n value: 'Anna',\n emptyLabel: 'Add first name',\n onSave: saveNoop,\n },\n {\n key: 'phone',\n kind: 'text',\n label: 'Phone',\n value: null,\n emptyLabel: 'Add phone',\n onSave: saveNoop,\n },\n {\n key: 'status',\n kind: 'select',\n label: 'Status',\n value: 'active',\n emptyLabel: 'Set status',\n options: [\n { value: 'active', label: 'Active' },\n { value: 'inactive', label: 'Inactive' },\n ],\n onSave: saveNoop,\n },\n {\n key: 'notes',\n kind: 'multiline',\n label: 'Notes',\n value: 'Prefers email contact.',\n emptyLabel: 'Add notes',\n onSave: saveNoop,\n gridClassName: 'sm:col-span-2 md:col-span-3',\n },\n]\n\nconst fieldGridWithCustom: DetailFieldConfig[] = [\n {\n key: 'email',\n kind: 'text',\n label: 'Email',\n value: 'anna@example.com',\n emptyLabel: 'Add email',\n onSave: saveNoop,\n },\n {\n key: 'owner',\n kind: 'custom',\n label: 'Owner',\n emptyLabel: 'Unassigned',\n render: () => (\n <div className=\"space-y-1\">\n <div className=\"text-xs text-muted-foreground\">Owner</div>\n <Badge variant=\"muted\">Unassigned</Badge>\n </div>\n ),\n },\n]\n\n// Sections resolve their labels through an app translator in real pages; the\n// gallery translator just surfaces each key's fallback (or last segment).\nconst galleryTranslator = (key: string, fallback?: string) =>\n fallback ?? key.split('.').pop() ?? key\n\nconst notesAdapter: NotesSectionProps['dataAdapter'] = {\n list: async () => [\n {\n id: 'note-1',\n body: 'Asked for a revised quote \u2014 follow up on Friday.',\n createdAt: '2026-07-15T09:30:00.000Z',\n authorName: 'Anna Nowak',\n },\n {\n id: 'note-2',\n body: 'Prefers email contact over phone.',\n createdAt: '2026-07-10T14:05:00.000Z',\n authorName: 'Jan Kowalski',\n },\n ],\n create: async () => {},\n update: async () => {},\n delete: async () => {},\n}\n\nconst addressesAdapter: AddressDataAdapter = {\n list: async () => [\n {\n id: 'address-1',\n name: 'Headquarters',\n addressLine1: 'Prosta 51',\n city: 'Warszawa',\n postalCode: '00-838',\n country: 'PL',\n isPrimary: true,\n },\n {\n id: 'address-2',\n name: 'Warehouse',\n addressLine1: 'Magazynowa 7',\n city: 'Pruszk\u00F3w',\n postalCode: '05-800',\n country: 'PL',\n },\n ],\n create: async () => {},\n update: async () => {},\n delete: async () => {},\n}\n\nconst detailFieldsSectionEntry: GalleryEntry = {\n id: 'detail-fields-section',\n title: 'DetailFieldsSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'field-grid',\n title: 'Inline-editable field grid',\n render: () => (\n <div className=\"w-full\">\n <DetailFieldsSection fields={fieldGrid} />\n </div>\n ),\n code: `import { DetailFieldsSection, type DetailFieldConfig } from '@open-mercato/ui/backend/detail'\n\nconst fields: DetailFieldConfig[] = [\n { key: 'first-name', kind: 'text', label: 'First name', value: person.firstName, emptyLabel: 'Add first name', onSave: saveFirstName },\n { key: 'phone', kind: 'text', label: 'Phone', value: person.phone, emptyLabel: 'Add phone', onSave: savePhone },\n {\n key: 'status', kind: 'select', label: 'Status', value: person.status, emptyLabel: 'Set status',\n options: [{ value: 'active', label: 'Active' }, { value: 'inactive', label: 'Inactive' }],\n onSave: saveStatus,\n },\n {\n key: 'notes', kind: 'multiline', label: 'Notes', value: person.notes, emptyLabel: 'Add notes',\n onSave: saveNotes, gridClassName: 'sm:col-span-2 md:col-span-3',\n },\n]\n\n<DetailFieldsSection fields={fields} />`,\n },\n {\n id: 'custom-field',\n title: 'With a custom field cell',\n render: () => (\n <div className=\"w-full\">\n <DetailFieldsSection fields={fieldGridWithCustom} />\n </div>\n ),\n code: `import { DetailFieldsSection, type DetailFieldConfig } from '@open-mercato/ui/backend/detail'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\n\nconst fields: DetailFieldConfig[] = [\n { key: 'email', kind: 'text', label: 'Email', value: person.email, emptyLabel: 'Add email', onSave: saveEmail },\n {\n key: 'owner', kind: 'custom', label: 'Owner', emptyLabel: 'Unassigned',\n render: () => (\n <div className=\"space-y-1\">\n <div className=\"text-xs text-muted-foreground\">Owner</div>\n <Badge variant=\"muted\">Unassigned</Badge>\n </div>\n ),\n },\n]\n\n<DetailFieldsSection fields={fields} />`,\n },\n ],\n}\n\nconst loadingMessageEntry: GalleryEntry = {\n id: 'loading-message',\n title: 'LoadingMessage',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'default',\n title: 'default',\n render: () => (\n <div className=\"w-full max-w-md\">\n <LoadingMessage label=\"Loading customer\u2026\" />\n </div>\n ),\n code: `import { LoadingMessage } from '@open-mercato/ui/backend/detail'\n\nif (isLoading) return <LoadingMessage label={t('customers.people.detail.loading')} />`,\n },\n ],\n}\n\nconst errorMessageEntry: GalleryEntry = {\n id: 'error-message',\n title: 'ErrorMessage',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'basic',\n title: 'Label only',\n render: () => (\n <div className=\"w-full max-w-md\">\n <ErrorMessage label=\"Failed to load customer.\" />\n </div>\n ),\n code: `import { ErrorMessage } from '@open-mercato/ui/backend/detail'\n\nif (error) return <ErrorMessage label={error} />`,\n },\n {\n id: 'with-description-action',\n title: 'With description and action',\n render: () => (\n <div className=\"w-full max-w-md\">\n <ErrorMessage\n label=\"Failed to load attachments.\"\n description=\"The storage service did not respond in time.\"\n action={\n <Button variant=\"outline\" size=\"sm\">\n Retry\n </Button>\n }\n />\n </div>\n ),\n code: `import { ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { Button } from '@open-mercato/ui/primitives/button'\n\n<ErrorMessage\n label=\"Failed to load attachments.\"\n description=\"The storage service did not respond in time.\"\n action={<Button variant=\"outline\" size=\"sm\" onClick={retry}>Retry</Button>}\n/>`,\n },\n ],\n}\n\nconst notesSectionEntry: GalleryEntry = {\n id: 'notes-section',\n title: 'NotesSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'mock-adapter',\n title: 'Timeline (inline mock adapter \u2014 no API)',\n render: () => (\n <div className=\"w-full max-w-2xl\">\n <NotesSection\n entityId=\"person-1\"\n viewerUserId=\"user-1\"\n viewerName=\"Anna Nowak\"\n emptyLabel=\"No notes yet\"\n addActionLabel=\"Add note\"\n emptyState={{\n title: 'No notes yet',\n actionLabel: 'Add note',\n description: 'Notes added here are visible to the whole team.',\n }}\n translator={galleryTranslator}\n dataAdapter={notesAdapter}\n />\n </div>\n ),\n code: `import { NotesSection, type NotesDataAdapter } from '@open-mercato/ui/backend/detail'\n\n// Implement the adapter against your module's API (apiCall) \u2014 never fork the section.\nconst notesAdapter: NotesDataAdapter = {\n list: async ({ entityId }) => fetchNotes(entityId),\n create: async ({ entityId, body }) => createNote(entityId, body),\n update: async ({ id, patch }) => updateNote(id, patch),\n delete: async ({ id }) => deleteNote(id),\n}\n\n<NotesSection\n entityId={personId}\n viewerUserId={viewer.id}\n viewerName={viewer.name}\n emptyLabel={t('customers.people.detail.notes.empty')}\n addActionLabel={t('customers.people.detail.notes.add')}\n emptyState={{\n title: t('customers.people.detail.notes.emptyTitle'),\n actionLabel: t('customers.people.detail.notes.add'),\n }}\n translator={t}\n dataAdapter={notesAdapter}\n/>`,\n },\n ],\n}\n\nconst addressesSectionEntry: GalleryEntry = {\n id: 'addresses-section',\n title: 'AddressesSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'mock-adapter',\n title: 'Address tiles (inline mock adapter \u2014 no API)',\n render: () => (\n <div className=\"w-full max-w-2xl\">\n <AddressesSection\n entityId=\"person-1\"\n emptyLabel=\"No addresses yet\"\n addActionLabel=\"Add address\"\n emptyState={{ title: 'No addresses yet', actionLabel: 'Add address' }}\n translator={galleryTranslator}\n dataAdapter={addressesAdapter}\n />\n </div>\n ),\n code: `import { AddressesSection, type AddressDataAdapter } from '@open-mercato/ui/backend/detail'\n\nconst addressesAdapter: AddressDataAdapter = {\n list: async ({ entityId }) => fetchAddresses(entityId),\n create: async ({ entityId, payload }) => createAddress(entityId, payload),\n update: async ({ id, payload }) => updateAddress(id, payload),\n delete: async ({ id }) => deleteAddress(id),\n}\n\n<AddressesSection\n entityId={personId}\n emptyLabel={t('customers.people.detail.addresses.empty')}\n addActionLabel={t('customers.people.detail.addresses.add')}\n emptyState={{\n title: t('customers.people.detail.addresses.emptyTitle'),\n actionLabel: t('customers.people.detail.addresses.add'),\n }}\n translator={t}\n dataAdapter={addressesAdapter}\n/>`,\n },\n ],\n}\n\nconst attachmentsSectionEntry: GalleryEntry = {\n id: 'attachments-section',\n title: 'AttachmentsSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'unsaved-record',\n title: 'Unsaved record (recordId null \u2014 API fetch disabled)',\n render: () => (\n <div className=\"w-full max-w-2xl\">\n <AttachmentsSection\n entityId=\"customers:person\"\n recordId={null}\n title=\"Attachments\"\n description=\"Files linked to this record.\"\n />\n </div>\n ),\n code: `import { AttachmentsSection } from '@open-mercato/ui/backend/detail'\n\n// Fetches /api/attachments internally once recordId is set;\n// with recordId={null} it renders the save-first placeholder.\n<AttachmentsSection\n entityId=\"customers:person\"\n recordId={person?.id ?? null}\n title={t('customers.people.detail.attachments.title')}\n description={t('customers.people.detail.attachments.description')}\n/>`,\n },\n ],\n}\n\nexport const entries: GalleryEntry[] = [\n detailFieldsSectionEntry,\n loadingMessageEntry,\n errorMessageEntry,\n notesSectionEntry,\n addressesSectionEntry,\n attachmentsSectionEntry,\n]\n"],
4
+ "sourcesContent": ["import * as React from 'react'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport {\n AddressesSection,\n AttachmentsSection,\n DetailFieldsSection,\n ErrorMessage,\n LoadingMessage,\n NotesSection,\n type AddressDataAdapter,\n type DetailFieldConfig,\n type NotesSectionProps,\n} from '@open-mercato/ui/backend/detail'\nimport type { GalleryEntry } from '../types'\n\n// Component titles and variant names are proper nouns from the codebase and\n// are deliberately not translated. `code` MUST contain the entry's importPath\n// (enforced by the registry-integrity test) and is always reviewed alongside\n// its sibling `render`.\n\n// Data-backed sections (Notes/Addresses) take adapter objects \u2014 the demos pass\n// inline in-memory adapters, so previews never touch an API. AttachmentsSection\n// fetches through `apiCall` internally and cannot take an adapter; it is shown\n// in its `recordId={null}` state, where fetching is disabled by design.\n\nconst saveNoop = async () => {}\n\nconst fieldGrid: DetailFieldConfig[] = [\n {\n key: 'first-name',\n kind: 'text',\n label: 'First name',\n value: 'Anna',\n emptyLabel: 'Add first name',\n onSave: saveNoop,\n },\n {\n key: 'phone',\n kind: 'text',\n label: 'Phone',\n value: null,\n emptyLabel: 'Add phone',\n onSave: saveNoop,\n },\n {\n key: 'status',\n kind: 'select',\n label: 'Status',\n value: 'active',\n emptyLabel: 'Set status',\n options: [\n { value: 'active', label: 'Active' },\n { value: 'inactive', label: 'Inactive' },\n ],\n onSave: saveNoop,\n },\n {\n key: 'notes',\n kind: 'multiline',\n label: 'Notes',\n value: 'Prefers email contact.',\n emptyLabel: 'Add notes',\n onSave: saveNoop,\n gridClassName: 'sm:col-span-2 md:col-span-3',\n },\n]\n\nconst fieldGridWithCustom: DetailFieldConfig[] = [\n {\n key: 'email',\n kind: 'text',\n label: 'Email',\n value: 'anna@example.com',\n emptyLabel: 'Add email',\n onSave: saveNoop,\n },\n {\n key: 'owner',\n kind: 'custom',\n label: 'Owner',\n emptyLabel: 'Unassigned',\n render: () => (\n <div className=\"space-y-1\">\n <div className=\"text-xs text-muted-foreground\">Owner</div>\n <Badge variant=\"muted\">Unassigned</Badge>\n </div>\n ),\n },\n]\n\n// Sections resolve their labels through an app translator in real pages; the\n// gallery translator just surfaces each key's fallback (or last segment).\nconst galleryTranslator = (key: string, fallback?: string) =>\n fallback ?? key.split('.').pop() ?? key\n\nconst notesAdapter: NotesSectionProps['dataAdapter'] = {\n list: async () => [\n {\n id: 'note-1',\n body: 'Asked for a revised quote \u2014 follow up on Friday.',\n createdAt: '2026-07-15T09:30:00.000Z',\n authorName: 'Anna Nowak',\n },\n {\n id: 'note-2',\n body: 'Prefers email contact over phone.',\n createdAt: '2026-07-10T14:05:00.000Z',\n authorName: 'Jan Kowalski',\n },\n ],\n create: async () => {},\n update: async () => {},\n delete: async () => {},\n}\n\nconst addressesAdapter: AddressDataAdapter = {\n list: async () => [\n {\n id: 'address-1',\n name: 'Headquarters',\n addressLine1: 'Prosta 51',\n city: 'Warszawa',\n postalCode: '00-838',\n country: 'PL',\n isPrimary: true,\n },\n {\n id: 'address-2',\n name: 'Warehouse',\n addressLine1: 'Magazynowa 7',\n city: 'Pruszk\u00F3w',\n postalCode: '05-800',\n country: 'PL',\n },\n ],\n create: async () => {},\n update: async () => {},\n delete: async () => {},\n}\n\nconst detailFieldsSectionEntry: GalleryEntry = {\n id: 'detail-fields-section',\n title: 'DetailFieldsSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'field-grid',\n title: 'Inline-editable field grid',\n render: () => (\n <div className=\"w-full\">\n <DetailFieldsSection fields={fieldGrid} />\n </div>\n ),\n code: `import { DetailFieldsSection, type DetailFieldConfig } from '@open-mercato/ui/backend/detail'\n\nconst fields: DetailFieldConfig[] = [\n { key: 'first-name', kind: 'text', label: 'First name', value: person.firstName, emptyLabel: 'Add first name', onSave: saveFirstName },\n { key: 'phone', kind: 'text', label: 'Phone', value: person.phone, emptyLabel: 'Add phone', onSave: savePhone },\n {\n key: 'status', kind: 'select', label: 'Status', value: person.status, emptyLabel: 'Set status',\n options: [{ value: 'active', label: 'Active' }, { value: 'inactive', label: 'Inactive' }],\n onSave: saveStatus,\n },\n {\n key: 'notes', kind: 'multiline', label: 'Notes', value: person.notes, emptyLabel: 'Add notes',\n onSave: saveNotes, gridClassName: 'sm:col-span-2 md:col-span-3',\n },\n]\n\n<DetailFieldsSection fields={fields} />`,\n },\n {\n id: 'custom-field',\n title: 'With a custom field cell',\n render: () => (\n <div className=\"w-full\">\n <DetailFieldsSection fields={fieldGridWithCustom} />\n </div>\n ),\n code: `import { DetailFieldsSection, type DetailFieldConfig } from '@open-mercato/ui/backend/detail'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\n\nconst fields: DetailFieldConfig[] = [\n { key: 'email', kind: 'text', label: 'Email', value: person.email, emptyLabel: 'Add email', onSave: saveEmail },\n {\n key: 'owner', kind: 'custom', label: 'Owner', emptyLabel: 'Unassigned',\n render: () => (\n <div className=\"space-y-1\">\n <div className=\"text-xs text-muted-foreground\">Owner</div>\n <Badge variant=\"muted\">Unassigned</Badge>\n </div>\n ),\n },\n]\n\n<DetailFieldsSection fields={fields} />`,\n },\n ],\n}\n\nconst loadingMessageEntry: GalleryEntry = {\n id: 'loading-message',\n title: 'LoadingMessage',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'default',\n title: 'default',\n render: () => (\n <div className=\"w-full max-w-md\">\n <LoadingMessage label=\"Loading customer\u2026\" />\n </div>\n ),\n code: `import { LoadingMessage } from '@open-mercato/ui/backend/detail'\n\nif (isLoading) return <LoadingMessage label={t('customers.people.detail.loading')} />`,\n },\n ],\n}\n\nconst errorMessageEntry: GalleryEntry = {\n id: 'error-message',\n title: 'ErrorMessage',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'basic',\n title: 'Label only',\n render: () => (\n <div className=\"w-full max-w-md\">\n <ErrorMessage label=\"Failed to load customer.\" />\n </div>\n ),\n code: `import { ErrorMessage } from '@open-mercato/ui/backend/detail'\n\nif (error) return <ErrorMessage label={error} />`,\n },\n {\n id: 'with-description-action',\n title: 'With description and action',\n render: () => (\n <div className=\"w-full max-w-md\">\n <ErrorMessage\n label=\"Failed to load attachments.\"\n description=\"The storage service did not respond in time.\"\n action={\n <Button variant=\"outline\" size=\"sm\">\n Retry\n </Button>\n }\n />\n </div>\n ),\n code: `import { ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { Button } from '@open-mercato/ui/primitives/button'\n\n<ErrorMessage\n label=\"Failed to load attachments.\"\n description=\"The storage service did not respond in time.\"\n action={<Button variant=\"outline\" size=\"sm\" onClick={retry}>Retry</Button>}\n/>`,\n },\n ],\n}\n\nconst notesSectionEntry: GalleryEntry = {\n id: 'notes-section',\n title: 'NotesSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'mock-adapter',\n title: 'Timeline (inline mock adapter \u2014 no API)',\n render: () => (\n <div className=\"w-full max-w-2xl\">\n <NotesSection\n entityId=\"person-1\"\n viewerUserId=\"user-1\"\n viewerName=\"Anna Nowak\"\n emptyLabel=\"No notes yet\"\n addActionLabel=\"Add note\"\n emptyState={{\n title: 'No notes yet',\n actionLabel: 'Add note',\n description: 'Notes added here are visible to the whole team.',\n }}\n translator={galleryTranslator}\n dataAdapter={notesAdapter}\n />\n </div>\n ),\n code: `import { NotesSection, type NotesDataAdapter } from '@open-mercato/ui/backend/detail'\n\n// Implement the adapter against your module's API (apiCall) \u2014 never fork the section.\nconst notesAdapter: NotesDataAdapter = {\n list: async ({ entityId }) => fetchNotes(entityId),\n create: async ({ entityId, body }) => createNote(entityId, body),\n update: async ({ id, patch }) => updateNote(id, patch),\n delete: async ({ id }) => deleteNote(id),\n}\n\n<NotesSection\n entityId={personId}\n viewerUserId={viewer.id}\n viewerName={viewer.name}\n emptyLabel={t('design_system.gallery.samples.notes.empty')}\n addActionLabel={t('design_system.gallery.samples.notes.add')}\n emptyState={{\n title: t('design_system.gallery.samples.notes.emptyTitle'),\n actionLabel: t('design_system.gallery.samples.notes.add'),\n }}\n translator={t}\n dataAdapter={notesAdapter}\n/>`,\n },\n ],\n}\n\nconst addressesSectionEntry: GalleryEntry = {\n id: 'addresses-section',\n title: 'AddressesSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'mock-adapter',\n title: 'Address tiles (inline mock adapter \u2014 no API)',\n render: () => (\n <div className=\"w-full max-w-2xl\">\n <AddressesSection\n entityId=\"person-1\"\n emptyLabel=\"No addresses yet\"\n addActionLabel=\"Add address\"\n emptyState={{ title: 'No addresses yet', actionLabel: 'Add address' }}\n translator={galleryTranslator}\n dataAdapter={addressesAdapter}\n />\n </div>\n ),\n code: `import { AddressesSection, type AddressDataAdapter } from '@open-mercato/ui/backend/detail'\n\nconst addressesAdapter: AddressDataAdapter = {\n list: async ({ entityId }) => fetchAddresses(entityId),\n create: async ({ entityId, payload }) => createAddress(entityId, payload),\n update: async ({ id, payload }) => updateAddress(id, payload),\n delete: async ({ id }) => deleteAddress(id),\n}\n\n<AddressesSection\n entityId={personId}\n emptyLabel={t('design_system.gallery.samples.addresses.empty')}\n addActionLabel={t('customers.people.detail.addresses.add')}\n emptyState={{\n title: t('design_system.gallery.samples.addresses.emptyTitle'),\n actionLabel: t('customers.people.detail.addresses.add'),\n }}\n translator={t}\n dataAdapter={addressesAdapter}\n/>`,\n },\n ],\n}\n\nconst attachmentsSectionEntry: GalleryEntry = {\n id: 'attachments-section',\n title: 'AttachmentsSection',\n importPath: '@open-mercato/ui/backend/detail',\n variants: [\n {\n id: 'unsaved-record',\n title: 'Unsaved record (recordId null \u2014 API fetch disabled)',\n render: () => (\n <div className=\"w-full max-w-2xl\">\n <AttachmentsSection\n entityId=\"customers:person\"\n recordId={null}\n title=\"Attachments\"\n description=\"Files linked to this record.\"\n />\n </div>\n ),\n code: `import { AttachmentsSection } from '@open-mercato/ui/backend/detail'\n\n// Fetches /api/attachments internally once recordId is set;\n// with recordId={null} it renders the save-first placeholder.\n<AttachmentsSection\n entityId=\"customers:person\"\n recordId={person?.id ?? null}\n title={t('design_system.gallery.samples.attachments.title')}\n description={t('design_system.gallery.samples.attachments.description')}\n/>`,\n },\n ],\n}\n\nexport const entries: GalleryEntry[] = [\n detailFieldsSectionEntry,\n loadingMessageEntry,\n errorMessageEntry,\n notesSectionEntry,\n addressesSectionEntry,\n attachmentsSectionEntry,\n]\n"],
5
5
  "mappings": "AAmFM,SACE,KADF;AAlFN,SAAS,aAAa;AACtB,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAaP,MAAM,WAAW,YAAY;AAAC;AAE9B,MAAM,YAAiC;AAAA,EACrC;AAAA,IACE,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,SAAS;AAAA,MACP,EAAE,OAAO,UAAU,OAAO,SAAS;AAAA,MACnC,EAAE,OAAO,YAAY,OAAO,WAAW;AAAA,IACzC;AAAA,IACA,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,OAAO;AAAA,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