@open-mercato/core 0.6.7-develop.6862.1.c11a64ce0a → 0.6.7-develop.6869.1.d1ce9999ea

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 (110) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/backend/config/attachments/page.js +1 -1
  3. package/dist/modules/attachments/backend/config/attachments/page.js.map +2 -2
  4. package/dist/modules/audit_logs/components/AuditLogsActions.js +1 -1
  5. package/dist/modules/audit_logs/components/AuditLogsActions.js.map +2 -2
  6. package/dist/modules/auth/frontend/login.js +2 -2
  7. package/dist/modules/auth/frontend/login.js.map +2 -2
  8. package/dist/modules/catalog/widgets/injection/product-bulk-delete/widget.js +10 -5
  9. package/dist/modules/catalog/widgets/injection/product-bulk-delete/widget.js.map +2 -2
  10. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +4 -4
  11. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +2 -2
  12. package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Diagnostics.js +2 -2
  13. package/dist/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Diagnostics.js.map +2 -2
  14. package/dist/modules/customers/api/utils.js +9 -6
  15. package/dist/modules/customers/api/utils.js.map +2 -2
  16. package/dist/modules/customers/backend/customers/deals/pipeline/page.js +1 -1
  17. package/dist/modules/customers/backend/customers/deals/pipeline/page.js.map +2 -2
  18. package/dist/modules/customers/components/calendar/CalendarEventEditor.js +1 -1
  19. package/dist/modules/customers/components/calendar/CalendarEventEditor.js.map +2 -2
  20. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js +1 -1
  21. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js.map +2 -2
  22. package/dist/modules/customers/components/detail/MiniWeekCalendar.js +7 -52
  23. package/dist/modules/customers/components/detail/MiniWeekCalendar.js.map +2 -2
  24. package/dist/modules/customers/components/detail/ScheduleActivityDialog.js +1 -1
  25. package/dist/modules/customers/components/detail/ScheduleActivityDialog.js.map +2 -2
  26. package/dist/modules/customers/components/detail/legacyActivities.js +69 -0
  27. package/dist/modules/customers/components/detail/legacyActivities.js.map +7 -0
  28. package/dist/modules/customers/utils/phoneDuplicates.js +1 -2
  29. package/dist/modules/customers/utils/phoneDuplicates.js.map +2 -2
  30. package/dist/modules/data_sync/backend/data-sync/page.js +3 -3
  31. package/dist/modules/data_sync/backend/data-sync/page.js.map +2 -2
  32. package/dist/modules/data_sync/components/IntegrationScheduleTab.js +5 -5
  33. package/dist/modules/data_sync/components/IntegrationScheduleTab.js.map +2 -2
  34. package/dist/modules/entities/api/records.js +8 -4
  35. package/dist/modules/entities/api/records.js.map +2 -2
  36. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +1 -1
  37. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  38. package/dist/modules/feature_toggles/components/FeatureToggleOverrideCard.js +1 -1
  39. package/dist/modules/feature_toggles/components/FeatureToggleOverrideCard.js.map +2 -2
  40. package/dist/modules/portal/frontend/[orgSlug]/portal/invite/page.js +1 -1
  41. package/dist/modules/portal/frontend/[orgSlug]/portal/invite/page.js.map +2 -2
  42. package/dist/modules/portal/frontend/[orgSlug]/portal/login/page.js +1 -1
  43. package/dist/modules/portal/frontend/[orgSlug]/portal/login/page.js.map +2 -2
  44. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +1 -1
  45. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
  46. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +1 -1
  47. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
  48. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js +1 -1
  49. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js.map +2 -2
  50. package/dist/modules/sales/components/documents/ItemsSection.js +11 -1
  51. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  52. package/dist/modules/sync_excel/widgets/injection/upload-config/widget.client.js +1 -1
  53. package/dist/modules/sync_excel/widgets/injection/upload-config/widget.client.js.map +2 -2
  54. package/dist/modules/workflows/backend/definitions/[id]/page.js +2 -2
  55. package/dist/modules/workflows/backend/definitions/[id]/page.js.map +2 -2
  56. package/dist/modules/workflows/backend/definitions/create/page.js +1 -1
  57. package/dist/modules/workflows/backend/definitions/create/page.js.map +2 -2
  58. package/dist/modules/workflows/backend/definitions/visual-editor/page.js +3 -3
  59. package/dist/modules/workflows/backend/definitions/visual-editor/page.js.map +2 -2
  60. package/dist/modules/workflows/components/DefinitionTriggersEditor.js +1 -1
  61. package/dist/modules/workflows/components/DefinitionTriggersEditor.js.map +2 -2
  62. package/dist/modules/workflows/components/NodeEditDialog.js +3 -3
  63. package/dist/modules/workflows/components/NodeEditDialog.js.map +2 -2
  64. package/dist/modules/workflows/components/NodeEditDialogCrudForm.js +3 -3
  65. package/dist/modules/workflows/components/NodeEditDialogCrudForm.js.map +2 -2
  66. package/dist/modules/workflows/components/WorkflowGraphImpl.js +1 -1
  67. package/dist/modules/workflows/components/WorkflowGraphImpl.js.map +2 -2
  68. package/dist/modules/workflows/components/fields/FormFieldArrayEditor.js +1 -1
  69. package/dist/modules/workflows/components/fields/FormFieldArrayEditor.js.map +2 -2
  70. package/package.json +7 -7
  71. package/src/modules/attachments/backend/config/attachments/page.tsx +1 -1
  72. package/src/modules/audit_logs/components/AuditLogsActions.tsx +1 -1
  73. package/src/modules/auth/frontend/login.tsx +2 -2
  74. package/src/modules/catalog/widgets/injection/product-bulk-delete/widget.ts +15 -5
  75. package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +4 -4
  76. package/src/modules/communication_channels/i18n/de.json +2 -2
  77. package/src/modules/communication_channels/i18n/en.json +2 -2
  78. package/src/modules/communication_channels/i18n/es.json +2 -2
  79. package/src/modules/communication_channels/i18n/ko.json +2 -2
  80. package/src/modules/communication_channels/i18n/pl.json +2 -2
  81. package/src/modules/customer_accounts/backend/customer_accounts/settings/domain/components/Diagnostics.tsx +2 -2
  82. package/src/modules/customers/api/utils.ts +13 -6
  83. package/src/modules/customers/backend/customers/deals/pipeline/page.tsx +1 -1
  84. package/src/modules/customers/components/calendar/CalendarEventEditor.tsx +1 -1
  85. package/src/modules/customers/components/detail/ConfirmDealLostDialog.tsx +1 -1
  86. package/src/modules/customers/components/detail/MiniWeekCalendar.tsx +8 -57
  87. package/src/modules/customers/components/detail/ScheduleActivityDialog.tsx +1 -1
  88. package/src/modules/customers/components/detail/legacyActivities.ts +79 -0
  89. package/src/modules/customers/utils/phoneDuplicates.ts +6 -3
  90. package/src/modules/data_sync/backend/data-sync/page.tsx +3 -3
  91. package/src/modules/data_sync/components/IntegrationScheduleTab.tsx +5 -5
  92. package/src/modules/entities/api/records.ts +12 -4
  93. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +1 -1
  94. package/src/modules/feature_toggles/components/FeatureToggleOverrideCard.tsx +1 -1
  95. package/src/modules/portal/frontend/[orgSlug]/portal/invite/page.tsx +1 -1
  96. package/src/modules/portal/frontend/[orgSlug]/portal/login/page.tsx +1 -1
  97. package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +1 -1
  98. package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +1 -1
  99. package/src/modules/portal/frontend/[orgSlug]/portal/verify/page.tsx +1 -1
  100. package/src/modules/sales/components/documents/ItemsSection.tsx +13 -0
  101. package/src/modules/sales/components/documents/lineItemTypes.ts +1 -0
  102. package/src/modules/sync_excel/widgets/injection/upload-config/widget.client.tsx +1 -1
  103. package/src/modules/workflows/backend/definitions/[id]/page.tsx +2 -2
  104. package/src/modules/workflows/backend/definitions/create/page.tsx +1 -1
  105. package/src/modules/workflows/backend/definitions/visual-editor/page.tsx +3 -3
  106. package/src/modules/workflows/components/DefinitionTriggersEditor.tsx +1 -1
  107. package/src/modules/workflows/components/NodeEditDialog.tsx +3 -3
  108. package/src/modules/workflows/components/NodeEditDialogCrudForm.tsx +3 -3
  109. package/src/modules/workflows/components/WorkflowGraphImpl.tsx +1 -1
  110. package/src/modules/workflows/components/fields/FormFieldArrayEditor.tsx +1 -1
@@ -125,7 +125,7 @@ function EditorBody({
125
125
  // people/resources and the task fields pair up below; title, description
126
126
  // and the type switcher span both columns.
127
127
  /* @__PURE__ */ jsxs("div", { className: "grid w-full grid-cols-1 items-start gap-4 lg:grid-cols-2 lg:gap-x-6", children: [
128
- conflict ? /* @__PURE__ */ jsxs(Alert, { variant: "warning", className: "rounded-lg lg:col-span-2", children: [
128
+ conflict ? /* @__PURE__ */ jsxs(Alert, { status: "warning", className: "rounded-lg lg:col-span-2", children: [
129
129
  /* @__PURE__ */ jsx(AlertTitle, { children: t("customers.calendar.editor.conflictTitle", "Calendar conflict") }),
130
130
  /* @__PURE__ */ jsx(AlertDescription, { children: conflict })
131
131
  ] }) : null,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/components/calendar/CalendarEventEditor.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Calendar, X } from 'lucide-react'\nimport { VisuallyHidden } from '@radix-ui/react-visually-hidden'\nimport { useLocale, useT } from '@open-mercato/shared/lib/i18n/context'\nimport { apiCallOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { extractOptimisticLockConflict } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { CrudForm, type CrudFormGroup, type CrudFormGroupComponentProps } from '@open-mercato/ui/backend/CrudForm'\nimport { collectCustomFieldValues } from '@open-mercato/ui/backend/utils/customFieldValues'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Dialog, DialogContent, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { useDialogKeyHandler } from '@open-mercato/ui/hooks/useDialogKeyHandler'\nimport { E } from '#generated/entities.ids.generated'\nimport {\n buildEditorTypeOptions,\n buildInteractionPayload,\n computeDurationMinutes,\n createDefaultFormState,\n defaultRepeatDaysForDateInput,\n editorKindOfInteractionType,\n KIND_CONFIG,\n parseItemToFormState,\n resolveSavedOwnerUserId,\n type EditorFormState,\n type EditorKind,\n type EditorPriority,\n} from '../../lib/calendar/editorPayload'\nimport type { ConflictScope } from '../../lib/calendar/preferences'\nimport { renderDictionaryIcon } from '@open-mercato/core/modules/dictionaries/components/dictionaryAppearance'\nimport { normalizeCustomFieldSubmitValue } from '../detail/customFieldUtils'\nimport type { CalendarItem } from './types'\nimport { EDITOR_SCROLL_EVENT, Field } from './editor/inputs'\nimport { SegmentGroup } from './editor/SegmentGroup'\nimport { PriorityField } from './editor/PriorityField'\nimport { RelatedToField } from './editor/RelatedToField'\nimport { RepeatField } from './editor/RepeatField'\nimport { PeopleField } from './editor/PeopleField'\nimport { ResourcesField } from './editor/ResourcesField'\nimport { ScheduleSection } from './editor/ScheduleSection'\nimport { LocationField } from './editor/LocationField'\nimport { useConflictProbe, useEditorLabelResolution } from './editor/hooks'\n\nexport interface CalendarEventEditorProps {\n open: boolean\n mode: 'create' | 'edit'\n item?: CalendarItem | null\n defaultDate?: Date\n defaultRange?: { start: Date; end: Date } | null\n typeLabels: Record<string, string>\n typeIcons?: Record<string, string | null>\n conflictScope?: ConflictScope\n currentUserId?: string | null\n resourcesEnabled?: boolean\n staffEnabled?: boolean\n onOpenChange(open: boolean): void\n onSaved(): void\n}\n\nconst FORM_ID = 'customers-calendar-event-editor'\nconst INTERACTION_ENTITY_IDS = [E.customers.customer_interaction]\n\nconst PEOPLE_FIELD_TEXT = {\n attendees: { labelKey: 'customers.calendar.editor.attendees', label: 'Attendees', placeholderKey: 'customers.calendar.editor.addPeoplePlaceholder', placeholder: 'Add staff or customer\u2026' },\n participants: { labelKey: 'customers.calendar.editor.participants', label: 'Participants', placeholderKey: 'customers.calendar.editor.addPeoplePlaceholder', placeholder: 'Add staff or customer\u2026' },\n to: { labelKey: 'customers.calendar.editor.to', label: 'To', placeholderKey: 'customers.calendar.editor.addRecipientPlaceholder', placeholder: 'Add recipient\u2026' },\n} as const\n\n// CrudForm values carry the flattened EditorFormState keys (seeded via\n// initialValues) plus cf_* custom-field keys managed by CrudForm itself.\nfunction formStateOfValues(values: Record<string, unknown>): EditorFormState {\n return values as unknown as EditorFormState\n}\n\nfunction customFieldInitialValues(item: CalendarItem): Record<string, unknown> {\n const customValues = (item.raw as Record<string, unknown>).customValues\n if (!customValues || typeof customValues !== 'object' || Array.isArray(customValues)) return {}\n return Object.fromEntries(\n Object.entries(customValues as Record<string, unknown>).map(([key, value]) => [`cf_${key}`, value]),\n )\n}\n\ntype EditorBodyProps = {\n ctx: CrudFormGroupComponentProps\n open: boolean\n isEdit: boolean\n item?: CalendarItem | null\n typeLabels: Record<string, string>\n typeIcons: Record<string, string | null>\n conflictScope: ConflictScope\n currentUserId: string | null\n resourcesEnabled: boolean\n staffEnabled: boolean\n}\n\nfunction EditorBody({\n ctx,\n open,\n isEdit,\n item,\n typeLabels,\n typeIcons,\n conflictScope,\n currentUserId,\n resourcesEnabled,\n staffEnabled,\n}: EditorBodyProps) {\n const t = useT()\n const locale = useLocale()\n const { setValue, errors } = ctx\n const form = formStateOfValues(ctx.values)\n const config = KIND_CONFIG[form.kind]\n\n const update = React.useCallback(\n (patch: Partial<EditorFormState>) => {\n for (const [key, value] of Object.entries(patch)) setValue(key, value)\n },\n [setValue],\n )\n\n useEditorLabelResolution(open, form, update)\n // Probe against the owner the interaction will actually be SAVED with so the\n // editor warning matches the grid's post-save conflict rings: tasks own via\n // their assignee, other kinds stay ownerless on create / keep the existing\n // owner on edit (conflicts then come from shared participants).\n const draftOwnerUserId = resolveSavedOwnerUserId(config, form, isEdit, item?.ownerUserId ?? null)\n // Self-exclude by the underlying interaction id (raw.id): findEditorConflictItems\n // drops candidates by raw.id, and every expanded occurrence of a recurring series\n // shares it \u2014 so the edited record never conflicts with itself.\n const conflict = useConflictProbe(open, form, config, isEdit && item ? item.raw.id : null, draftOwnerUserId, conflictScope, currentUserId)\n\n const kindLabels = React.useMemo(\n () => ({\n meeting: t('customers.calendar.editor.types.meeting', 'meeting'),\n call: t('customers.calendar.editor.types.call', 'call'),\n email: t('customers.calendar.editor.types.email', 'email'),\n note: t('customers.calendar.editor.types.note', 'note'),\n event: t('customers.calendar.editor.types.event', 'event'),\n task: t('customers.calendar.editor.types.task', 'task'),\n }),\n [t],\n ) satisfies Record<EditorKind, string>\n\n const selectedType = form.category ?? form.kind\n const typeOptions = React.useMemo(\n () => buildEditorTypeOptions({ typeLabels, typeIcons, selectedValue: selectedType, kindLabels }),\n [typeLabels, typeIcons, selectedType, kindLabels],\n )\n const typeSwitcherOptions = React.useMemo(\n () =>\n typeOptions.map((option) => ({\n value: option.value,\n label: option.label,\n icon: renderDictionaryIcon(option.icon, 'h-4 w-4'),\n })),\n [typeOptions],\n )\n\n // Candidates for the Call \"insert phone from contact\" button: the linked\n // person (companies have no phone) + customer attendees. Their userId is the\n // person id, so the picker can resolve primary_phone from the people API.\n const phoneContactIds = React.useMemo(() => {\n const ids: string[] = []\n if (form.relatedTo && form.relatedTo.kind !== 'company') ids.push(form.relatedTo.id)\n for (const participant of form.participants) {\n if (participant.isCustomer) ids.push(participant.userId)\n }\n return Array.from(new Set(ids))\n }, [form.relatedTo, form.participants])\n\n const titleLabel = form.kind === 'email'\n ? t('customers.calendar.editor.titleLabel.email', 'Subject')\n : form.kind === 'note'\n ? t('customers.calendar.editor.titleLabel.note', 'Note')\n : t('customers.calendar.editor.titleLabel.generic', 'Title')\n\n return (\n // Single column on phones (full-screen sheet). On lg+ the dialog widens and\n // the fields group into two thematic columns: WHEN (schedule + repeat) on\n // the left, CONTEXT (related record, category, location) on the right;\n // people/resources and the task fields pair up below; title, description\n // and the type switcher span both columns.\n <div className=\"grid w-full grid-cols-1 items-start gap-4 lg:grid-cols-2 lg:gap-x-6\">\n {conflict ? (\n <Alert variant=\"warning\" className=\"rounded-lg lg:col-span-2\">\n <AlertTitle>{t('customers.calendar.editor.conflictTitle', 'Calendar conflict')}</AlertTitle>\n <AlertDescription>{conflict}</AlertDescription>\n </Alert>\n ) : null}\n <div className=\"w-full lg:col-span-2\">\n <SegmentGroup<string>\n ariaLabel={t('customers.calendar.editor.typeSwitcher', 'Event type')}\n value={selectedType}\n onChange={(type) => update({ kind: editorKindOfInteractionType(type), category: type })}\n options={typeSwitcherOptions}\n />\n </div>\n <Field label={titleLabel} error={errors.title} className=\"lg:col-span-2\">\n <Input\n type=\"text\"\n value={form.title}\n onChange={(event) => update({ title: event.target.value })}\n placeholder={t('customers.calendar.editor.titlePlaceholder', 'Add a title\u2026')}\n aria-label={titleLabel}\n autoFocus\n size=\"lg\"\n />\n </Field>\n <div className=\"flex w-full flex-col gap-4\">\n <ScheduleSection\n dateLabel={config.dateLabel}\n hasAllDay={config.hasAllDay}\n hasEnd={config.hasEnd}\n allDay={form.allDay}\n date={form.date}\n startTime={form.startTime}\n endDate={form.endDate}\n endTime={form.endTime}\n locale={locale}\n endsError={errors.ends}\n onAllDayChange={(allDay) => update({ allDay })}\n onDateChange={(date) => {\n const untouchedDefault =\n JSON.stringify(form.repeatDays) === JSON.stringify(defaultRepeatDaysForDateInput(form.date))\n update(\n untouchedDefault\n ? { date, repeatDays: defaultRepeatDaysForDateInput(date) }\n : { date },\n )\n }}\n onStartTimeChange={(startTime) => update({ startTime })}\n onEndDateChange={(endDate) => update({ endDate })}\n onEndTimeChange={(endTime) => update({ endTime })}\n />\n {config.hasRepeat ? (\n <RepeatField\n freq={form.repeatFreq}\n days={form.repeatDays}\n endType={form.repeatEndType}\n count={form.repeatCount}\n untilDate={form.repeatUntilDate}\n locale={locale}\n onFreqChange={(repeatFreq) =>\n update(\n repeatFreq === 'weekly'\n ? { repeatFreq, repeatDays: defaultRepeatDaysForDateInput(form.date) }\n : { repeatFreq },\n )}\n onToggleDay={(index) =>\n update({ repeatDays: form.repeatDays.map((active, dayIndex) => (dayIndex === index ? !active : active)) })}\n onEndTypeChange={(repeatEndType) => update({ repeatEndType })}\n onCountChange={(repeatCount) => update({ repeatCount })}\n onUntilDateChange={(repeatUntilDate) => update({ repeatUntilDate })}\n />\n ) : null}\n {config.people && config.people !== 'assignee' ? (\n <Field label={t(PEOPLE_FIELD_TEXT[config.people].labelKey, PEOPLE_FIELD_TEXT[config.people].label)}>\n <PeopleField\n mode=\"multi\"\n includeCustomers\n includeStaff={staffEnabled}\n placeholder={t(PEOPLE_FIELD_TEXT[config.people].placeholderKey, PEOPLE_FIELD_TEXT[config.people].placeholder)}\n ariaLabel={t(PEOPLE_FIELD_TEXT[config.people].labelKey, PEOPLE_FIELD_TEXT[config.people].label)}\n value={form.participants}\n onChange={(participants) => update({ participants })}\n />\n </Field>\n ) : null}\n {config.people === 'assignee' && staffEnabled ? (\n <Field label={t('customers.calendar.editor.assignee', 'Assignee')} error={errors.assignee}>\n <PeopleField\n mode=\"single\"\n includeCustomers={false}\n includeStaff\n placeholder={t('customers.calendar.editor.assigneePlaceholder', 'Assign to a team member\u2026')}\n ariaLabel={t('customers.calendar.editor.assignee', 'Assignee')}\n value={form.assigneeUserId\n ? [{ userId: form.assigneeUserId, name: form.assigneeName ?? form.assigneeUserId, isCustomer: false }]\n : []}\n onChange={(entries) => {\n const next = entries[entries.length - 1] ?? null\n update({ assigneeUserId: next?.userId ?? null, assigneeName: next?.name ?? null })\n }}\n />\n </Field>\n ) : null}\n </div>\n <div className=\"flex w-full flex-col gap-4\">\n <Field label={t('customers.calendar.editor.relatedTo', 'Related to')} error={errors.relatedTo}>\n <RelatedToField\n label={t('customers.calendar.editor.relatedTo', 'Related to')}\n value={form.relatedTo}\n deal={form.dealId && form.dealLabel ? { id: form.dealId, label: form.dealLabel } : null}\n onChange={(relatedTo) => update({ relatedTo })}\n onDealChange={(deal) => update({ dealId: deal?.id ?? null, dealLabel: deal?.label ?? null })}\n error={errors.relatedTo}\n />\n </Field>\n {config.location ? (\n <LocationField\n variant={config.location}\n value={form.location}\n onChange={(location) => update({ location })}\n phoneContactIds={phoneContactIds}\n />\n ) : null}\n {resourcesEnabled ? (\n <Field label={t('customers.calendar.editor.resources', 'Resources')}>\n <ResourcesField\n placeholder={t('customers.calendar.editor.resourcesPlaceholder', 'Add a resource\u2026')}\n ariaLabel={t('customers.calendar.editor.resources', 'Resources')}\n value={form.resources}\n onChange={(resources) => update({ resources })}\n />\n </Field>\n ) : null}\n {config.hasPriority ? (\n <Field label={t('customers.calendar.editor.priority.label', 'Priority')}>\n <PriorityField\n value={form.priority}\n ariaLabel={t('customers.calendar.editor.priority.label', 'Priority')}\n labels={{\n low: t('customers.calendar.editor.priority.low', 'Low'),\n medium: t('customers.calendar.editor.priority.medium', 'Medium'),\n high: t('customers.calendar.editor.priority.high', 'High'),\n }}\n onChange={(priority) => update({ priority })}\n />\n </Field>\n ) : null}\n </div>\n <Field label={t('customers.calendar.editor.description', 'Description')} className=\"lg:col-span-2\">\n <Textarea\n value={form.description}\n onChange={(event) => update({ description: event.target.value })}\n placeholder={t('customers.calendar.editor.descriptionPlaceholder', 'Add details\u2026')}\n aria-label={t('customers.calendar.editor.description', 'Description')}\n className=\"h-20 resize-none\"\n />\n </Field>\n </div>\n )\n}\n\nexport function CalendarEventEditor({\n open,\n mode,\n item,\n defaultDate,\n defaultRange,\n typeLabels,\n typeIcons,\n conflictScope,\n currentUserId,\n resourcesEnabled,\n staffEnabled,\n onOpenChange,\n onSaved,\n}: CalendarEventEditorProps) {\n const t = useT()\n const [saving, setSaving] = React.useState(false)\n const isEdit = mode === 'edit' && Boolean(item?.id)\n\n // CrudForm reads initialValues once, so every dialog open gets a fresh form\n // instance keyed by the open sequence + edited record.\n const [openSeq, setOpenSeq] = React.useState(0)\n const wasOpenRef = React.useRef(false)\n React.useEffect(() => {\n if (open && !wasOpenRef.current) setOpenSeq((seq) => seq + 1)\n wasOpenRef.current = open\n }, [open])\n const formKey = `${mode}:${item?.id ?? 'new'}:${openSeq}`\n\n const initialValues = React.useMemo<Record<string, unknown>>(() => {\n if (isEdit && item) {\n return {\n ...parseItemToFormState(item),\n ...customFieldInitialValues(item),\n id: item.id,\n updatedAt: item.updatedAt ?? undefined,\n }\n }\n return { ...createDefaultFormState(defaultDate ?? null, undefined, defaultRange ?? null) }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- openSeq re-seeds defaults per dialog open\n }, [isEdit, item, defaultDate, defaultRange, openSeq])\n\n const handleSubmit = React.useCallback(\n async (values: Record<string, unknown>) => {\n const form = formStateOfValues(values)\n const config = KIND_CONFIG[form.kind]\n const fieldErrors: Record<string, string> = {}\n if (!form.title.trim()) {\n fieldErrors.title = t('customers.calendar.editor.validation.titleRequired', 'Title is required')\n }\n if (!form.relatedTo) {\n fieldErrors.relatedTo = t('customers.calendar.editor.validation.relatedToRequired', 'Select a person or company to link this event')\n }\n if (config.hasEnd && !form.allDay && computeDurationMinutes(form) === null) {\n fieldErrors.ends = t('customers.calendar.editor.validation.endsBeforeStarts', 'End must be after start')\n }\n // A task must be assigned to a team member \u2014 surface the requirement inline\n // instead of letting the save fail with no visible reason (#3747 feedback).\n if (config.people === 'assignee' && staffEnabled !== false && !form.assigneeUserId) {\n fieldErrors.assignee = t('customers.calendar.editor.validation.assigneeRequired', 'Assign this task to a team member')\n }\n if (Object.keys(fieldErrors).length > 0) {\n throw createCrudFormError(Object.values(fieldErrors)[0], fieldErrors)\n }\n setSaving(true)\n try {\n const payload = buildInteractionPayload(form, {\n mode,\n id: item?.id,\n resourcesEnabled: resourcesEnabled === true,\n staffEnabled: staffEnabled !== false,\n })\n const custom = collectCustomFieldValues(values, {\n transform: (value) => normalizeCustomFieldSubmitValue(value),\n })\n for (const [key, value] of Object.entries(custom)) payload[`cf_${key}`] = value\n // CrudForm supplies the optimistic-lock header (auto-derived from\n // initialValues.updatedAt) via scoped request headers around onSubmit.\n await apiCallOrThrow('/api/customers/interactions', {\n method: isEdit ? 'PUT' : 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n })\n flash(t('customers.calendar.editor.saved', 'Event saved'), 'success')\n onOpenChange(false)\n requestAnimationFrame(() => { onSaved() })\n } catch (err) {\n // Surface an optimistic-lock 409 as the persistent conflict bar and\n // close \u2014 the bar renders at page level, behind the dialog overlay.\n if (extractOptimisticLockConflict(err)) {\n surfaceRecordConflict(err, t)\n onOpenChange(false)\n return\n }\n throw err\n } finally {\n setSaving(false)\n }\n },\n [isEdit, item?.id, mode, onOpenChange, onSaved, resourcesEnabled, staffEnabled, t],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => [\n {\n id: 'details',\n bare: true,\n component: (ctx) => (\n <EditorBody\n ctx={ctx}\n open={open}\n isEdit={isEdit}\n item={item}\n typeLabels={typeLabels}\n typeIcons={typeIcons ?? {}}\n conflictScope={conflictScope ?? 'all'}\n currentUserId={currentUserId ?? null}\n resourcesEnabled={resourcesEnabled === true}\n staffEnabled={staffEnabled !== false}\n />\n ),\n },\n { id: 'customFields', kind: 'customFields' },\n ],\n [open, isEdit, item, typeLabels, typeIcons, conflictScope, currentUserId, resourcesEnabled, staffEnabled],\n )\n\n const handleKeyDown = useDialogKeyHandler({\n onConfirm: () => {\n const formElement = document.getElementById(FORM_ID)\n if (formElement instanceof HTMLFormElement) formElement.requestSubmit()\n },\n disabled: saving,\n })\n\n const dialogTitle = isEdit ? t('customers.calendar.editor.title.edit', 'Edit event') : t('customers.calendar.editor.title.create', 'New event')\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n onKeyDown={handleKeyDown}\n // Only dismiss on a genuine click OUTSIDE the whole editor. Radix\n // relays a click inside the dialog (but outside an open DS\n // DatePicker/Select popover) up to the dialog as an \"interact\n // outside\" event when it dismisses that popover \u2014 without this guard\n // it would tear down the entire editor. Keep it open when the target\n // is inside the dialog body or inside any portalled popover.\n onInteractOutside={(event) => {\n const target = event.detail.originalEvent.target as HTMLElement | null\n if (target?.closest('[data-dialog-content]') || target?.closest('[data-radix-popper-content-wrapper]')) {\n event.preventDefault()\n }\n }}\n aria-describedby={undefined}\n dismissible={false}\n className=\"flex h-dvh max-h-dvh w-screen max-w-none flex-col gap-0 overflow-hidden rounded-none border-0 bg-background p-0 shadow-xl sm:h-auto sm:max-h-[calc(100dvh-4rem)] sm:w-full sm:max-w-lg sm:rounded-2xl sm:border-0 lg:max-w-3xl\"\n >\n <VisuallyHidden>\n <DialogTitle>{dialogTitle}</DialogTitle>\n </VisuallyHidden>\n <div className=\"flex shrink-0 items-center gap-3 border-b border-border bg-background py-4 pl-5 pr-4\">\n <Calendar aria-hidden className=\"size-6 shrink-0 text-foreground\" strokeWidth={1.75} />\n <p className=\"min-w-0 flex-1 text-sm font-medium leading-5 text-foreground\">{dialogTitle}</p>\n <IconButton\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => onOpenChange(false)}\n aria-label={t('customers.calendar.editor.close', 'Close')}\n className=\"shrink-0 text-muted-foreground\"\n >\n <X aria-hidden className=\"size-5\" />\n </IconButton>\n </div>\n <div\n className=\"flex-1 overflow-y-auto\"\n onScroll={() => {\n // Tell the DS date/time fields to close their (controlled) popover\n // so a portalled popover doesn't float over the form or drift away\n // from its field while scrolling (#3747 feedback). Radix ignores\n // synthetic dismiss events, so the fields drive their own `open`.\n document.dispatchEvent(new CustomEvent(EDITOR_SCROLL_EVENT))\n }}\n >\n <div className=\"px-4 py-4 sm:px-6 sm:py-5\">\n <CrudForm<Record<string, unknown>>\n key={formKey}\n formId={FORM_ID}\n embedded\n hideFooterActions\n customFieldsManageMode=\"page\"\n fields={[]}\n groups={groups}\n initialValues={initialValues}\n entityIds={INTERACTION_ENTITY_IDS}\n onSubmit={handleSubmit}\n />\n </div>\n </div>\n <div className=\"flex shrink-0 items-center justify-end gap-3 border-t border-border bg-background px-5 py-4\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => onOpenChange(false)}\n >\n {t('customers.calendar.editor.cancel', 'Cancel')}\n </Button>\n <Button\n type=\"submit\"\n form={FORM_ID}\n disabled={saving}\n >\n {saving ? t('customers.calendar.editor.saving', 'Saving\u2026') : t('customers.calendar.editor.save', 'Save event')}\n </Button>\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n"],
5
- "mappings": ";AA+LQ,SACE,KADF;AA7LR,YAAY,WAAW;AACvB,SAAS,UAAU,SAAS;AAC5B,SAAS,sBAAsB;AAC/B,SAAS,WAAW,YAAY;AAChC,SAAS,sBAAsB;AAC/B,SAAS,qCAAqC;AAC9C,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,aAAa;AACtB,SAAS,gBAAsE;AAC/E,SAAS,gCAAgC;AACzC,SAAS,OAAO,kBAAkB,kBAAkB;AACpD,SAAS,cAAc;AACvB,SAAS,QAAQ,eAAe,mBAAmB;AACnD,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,2BAA2B;AACpC,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAEP,SAAS,4BAA4B;AACrC,SAAS,uCAAuC;AAEhD,SAAS,qBAAqB,aAAa;AAC3C,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB;AAC/B,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,sBAAsB;AAC/B,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB,gCAAgC;AAkB3D,MAAM,UAAU;AAChB,MAAM,yBAAyB,CAAC,EAAE,UAAU,oBAA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C,YAAS,eAAW,MAAC,WAAU,mCAAkC,aAAa,MAAM;AAAA,UACrF,oBAAC,OAAE,WAAU,gEAAgE,uBAAY;AAAA,UACzF;AAAA,YAAC;AAAA;AAAA,cACC,SAAQ;AAAA,cACR,MAAK;AAAA,cACL,SAAS,MAAM,aAAa,KAAK;AAAA,cACjC,cAAY,EAAE,mCAAmC,OAAO;AAAA,cACxD,WAAU;AAAA,cAEV,8BAAC,KAAE,eAAW,MAAC,WAAU,UAAS;AAAA;AAAA,UACpC;AAAA,WACF;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,WAAU;AAAA,YACV,UAAU,MAAM;AAKd,uBAAS,cAAc,IAAI,YAAY,mBAAmB,CAAC;AAAA,YAC7D;AAAA,YAEA,8BAAC,SAAI,WAAU,6BACb;AAAA,cAAC;AAAA;AAAA,gBAEC,QAAQ;AAAA,gBACR,UAAQ;AAAA,gBACR,mBAAiB;AAAA,gBACjB,wBAAuB;AAAA,gBACvB,QAAQ,CAAC;AAAA,gBACT;AAAA,gBACA;AAAA,gBACA,WAAW;AAAA,gBACX,UAAU;AAAA;AAAA,cATL;AAAA,YAUP,GACF;AAAA;AAAA,QACF;AAAA,QACA,qBAAC,SAAI,WAAU,+FACb;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,SAAQ;AAAA,cACR,SAAS,MAAM,aAAa,KAAK;AAAA,cAEhC,YAAE,oCAAoC,QAAQ;AAAA;AAAA,UACjD;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,MAAM;AAAA,cACN,UAAU;AAAA,cAET,mBAAS,EAAE,oCAAoC,cAAS,IAAI,EAAE,kCAAkC,YAAY;AAAA;AAAA,UAC/G;AAAA,WACF;AAAA;AAAA;AAAA,EACF,GACF;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Calendar, X } from 'lucide-react'\nimport { VisuallyHidden } from '@radix-ui/react-visually-hidden'\nimport { useLocale, useT } from '@open-mercato/shared/lib/i18n/context'\nimport { apiCallOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { extractOptimisticLockConflict } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { CrudForm, type CrudFormGroup, type CrudFormGroupComponentProps } from '@open-mercato/ui/backend/CrudForm'\nimport { collectCustomFieldValues } from '@open-mercato/ui/backend/utils/customFieldValues'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Dialog, DialogContent, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { useDialogKeyHandler } from '@open-mercato/ui/hooks/useDialogKeyHandler'\nimport { E } from '#generated/entities.ids.generated'\nimport {\n buildEditorTypeOptions,\n buildInteractionPayload,\n computeDurationMinutes,\n createDefaultFormState,\n defaultRepeatDaysForDateInput,\n editorKindOfInteractionType,\n KIND_CONFIG,\n parseItemToFormState,\n resolveSavedOwnerUserId,\n type EditorFormState,\n type EditorKind,\n type EditorPriority,\n} from '../../lib/calendar/editorPayload'\nimport type { ConflictScope } from '../../lib/calendar/preferences'\nimport { renderDictionaryIcon } from '@open-mercato/core/modules/dictionaries/components/dictionaryAppearance'\nimport { normalizeCustomFieldSubmitValue } from '../detail/customFieldUtils'\nimport type { CalendarItem } from './types'\nimport { EDITOR_SCROLL_EVENT, Field } from './editor/inputs'\nimport { SegmentGroup } from './editor/SegmentGroup'\nimport { PriorityField } from './editor/PriorityField'\nimport { RelatedToField } from './editor/RelatedToField'\nimport { RepeatField } from './editor/RepeatField'\nimport { PeopleField } from './editor/PeopleField'\nimport { ResourcesField } from './editor/ResourcesField'\nimport { ScheduleSection } from './editor/ScheduleSection'\nimport { LocationField } from './editor/LocationField'\nimport { useConflictProbe, useEditorLabelResolution } from './editor/hooks'\n\nexport interface CalendarEventEditorProps {\n open: boolean\n mode: 'create' | 'edit'\n item?: CalendarItem | null\n defaultDate?: Date\n defaultRange?: { start: Date; end: Date } | null\n typeLabels: Record<string, string>\n typeIcons?: Record<string, string | null>\n conflictScope?: ConflictScope\n currentUserId?: string | null\n resourcesEnabled?: boolean\n staffEnabled?: boolean\n onOpenChange(open: boolean): void\n onSaved(): void\n}\n\nconst FORM_ID = 'customers-calendar-event-editor'\nconst INTERACTION_ENTITY_IDS = [E.customers.customer_interaction]\n\nconst PEOPLE_FIELD_TEXT = {\n attendees: { labelKey: 'customers.calendar.editor.attendees', label: 'Attendees', placeholderKey: 'customers.calendar.editor.addPeoplePlaceholder', placeholder: 'Add staff or customer\u2026' },\n participants: { labelKey: 'customers.calendar.editor.participants', label: 'Participants', placeholderKey: 'customers.calendar.editor.addPeoplePlaceholder', placeholder: 'Add staff or customer\u2026' },\n to: { labelKey: 'customers.calendar.editor.to', label: 'To', placeholderKey: 'customers.calendar.editor.addRecipientPlaceholder', placeholder: 'Add recipient\u2026' },\n} as const\n\n// CrudForm values carry the flattened EditorFormState keys (seeded via\n// initialValues) plus cf_* custom-field keys managed by CrudForm itself.\nfunction formStateOfValues(values: Record<string, unknown>): EditorFormState {\n return values as unknown as EditorFormState\n}\n\nfunction customFieldInitialValues(item: CalendarItem): Record<string, unknown> {\n const customValues = (item.raw as Record<string, unknown>).customValues\n if (!customValues || typeof customValues !== 'object' || Array.isArray(customValues)) return {}\n return Object.fromEntries(\n Object.entries(customValues as Record<string, unknown>).map(([key, value]) => [`cf_${key}`, value]),\n )\n}\n\ntype EditorBodyProps = {\n ctx: CrudFormGroupComponentProps\n open: boolean\n isEdit: boolean\n item?: CalendarItem | null\n typeLabels: Record<string, string>\n typeIcons: Record<string, string | null>\n conflictScope: ConflictScope\n currentUserId: string | null\n resourcesEnabled: boolean\n staffEnabled: boolean\n}\n\nfunction EditorBody({\n ctx,\n open,\n isEdit,\n item,\n typeLabels,\n typeIcons,\n conflictScope,\n currentUserId,\n resourcesEnabled,\n staffEnabled,\n}: EditorBodyProps) {\n const t = useT()\n const locale = useLocale()\n const { setValue, errors } = ctx\n const form = formStateOfValues(ctx.values)\n const config = KIND_CONFIG[form.kind]\n\n const update = React.useCallback(\n (patch: Partial<EditorFormState>) => {\n for (const [key, value] of Object.entries(patch)) setValue(key, value)\n },\n [setValue],\n )\n\n useEditorLabelResolution(open, form, update)\n // Probe against the owner the interaction will actually be SAVED with so the\n // editor warning matches the grid's post-save conflict rings: tasks own via\n // their assignee, other kinds stay ownerless on create / keep the existing\n // owner on edit (conflicts then come from shared participants).\n const draftOwnerUserId = resolveSavedOwnerUserId(config, form, isEdit, item?.ownerUserId ?? null)\n // Self-exclude by the underlying interaction id (raw.id): findEditorConflictItems\n // drops candidates by raw.id, and every expanded occurrence of a recurring series\n // shares it \u2014 so the edited record never conflicts with itself.\n const conflict = useConflictProbe(open, form, config, isEdit && item ? item.raw.id : null, draftOwnerUserId, conflictScope, currentUserId)\n\n const kindLabels = React.useMemo(\n () => ({\n meeting: t('customers.calendar.editor.types.meeting', 'meeting'),\n call: t('customers.calendar.editor.types.call', 'call'),\n email: t('customers.calendar.editor.types.email', 'email'),\n note: t('customers.calendar.editor.types.note', 'note'),\n event: t('customers.calendar.editor.types.event', 'event'),\n task: t('customers.calendar.editor.types.task', 'task'),\n }),\n [t],\n ) satisfies Record<EditorKind, string>\n\n const selectedType = form.category ?? form.kind\n const typeOptions = React.useMemo(\n () => buildEditorTypeOptions({ typeLabels, typeIcons, selectedValue: selectedType, kindLabels }),\n [typeLabels, typeIcons, selectedType, kindLabels],\n )\n const typeSwitcherOptions = React.useMemo(\n () =>\n typeOptions.map((option) => ({\n value: option.value,\n label: option.label,\n icon: renderDictionaryIcon(option.icon, 'h-4 w-4'),\n })),\n [typeOptions],\n )\n\n // Candidates for the Call \"insert phone from contact\" button: the linked\n // person (companies have no phone) + customer attendees. Their userId is the\n // person id, so the picker can resolve primary_phone from the people API.\n const phoneContactIds = React.useMemo(() => {\n const ids: string[] = []\n if (form.relatedTo && form.relatedTo.kind !== 'company') ids.push(form.relatedTo.id)\n for (const participant of form.participants) {\n if (participant.isCustomer) ids.push(participant.userId)\n }\n return Array.from(new Set(ids))\n }, [form.relatedTo, form.participants])\n\n const titleLabel = form.kind === 'email'\n ? t('customers.calendar.editor.titleLabel.email', 'Subject')\n : form.kind === 'note'\n ? t('customers.calendar.editor.titleLabel.note', 'Note')\n : t('customers.calendar.editor.titleLabel.generic', 'Title')\n\n return (\n // Single column on phones (full-screen sheet). On lg+ the dialog widens and\n // the fields group into two thematic columns: WHEN (schedule + repeat) on\n // the left, CONTEXT (related record, category, location) on the right;\n // people/resources and the task fields pair up below; title, description\n // and the type switcher span both columns.\n <div className=\"grid w-full grid-cols-1 items-start gap-4 lg:grid-cols-2 lg:gap-x-6\">\n {conflict ? (\n <Alert status=\"warning\" className=\"rounded-lg lg:col-span-2\">\n <AlertTitle>{t('customers.calendar.editor.conflictTitle', 'Calendar conflict')}</AlertTitle>\n <AlertDescription>{conflict}</AlertDescription>\n </Alert>\n ) : null}\n <div className=\"w-full lg:col-span-2\">\n <SegmentGroup<string>\n ariaLabel={t('customers.calendar.editor.typeSwitcher', 'Event type')}\n value={selectedType}\n onChange={(type) => update({ kind: editorKindOfInteractionType(type), category: type })}\n options={typeSwitcherOptions}\n />\n </div>\n <Field label={titleLabel} error={errors.title} className=\"lg:col-span-2\">\n <Input\n type=\"text\"\n value={form.title}\n onChange={(event) => update({ title: event.target.value })}\n placeholder={t('customers.calendar.editor.titlePlaceholder', 'Add a title\u2026')}\n aria-label={titleLabel}\n autoFocus\n size=\"lg\"\n />\n </Field>\n <div className=\"flex w-full flex-col gap-4\">\n <ScheduleSection\n dateLabel={config.dateLabel}\n hasAllDay={config.hasAllDay}\n hasEnd={config.hasEnd}\n allDay={form.allDay}\n date={form.date}\n startTime={form.startTime}\n endDate={form.endDate}\n endTime={form.endTime}\n locale={locale}\n endsError={errors.ends}\n onAllDayChange={(allDay) => update({ allDay })}\n onDateChange={(date) => {\n const untouchedDefault =\n JSON.stringify(form.repeatDays) === JSON.stringify(defaultRepeatDaysForDateInput(form.date))\n update(\n untouchedDefault\n ? { date, repeatDays: defaultRepeatDaysForDateInput(date) }\n : { date },\n )\n }}\n onStartTimeChange={(startTime) => update({ startTime })}\n onEndDateChange={(endDate) => update({ endDate })}\n onEndTimeChange={(endTime) => update({ endTime })}\n />\n {config.hasRepeat ? (\n <RepeatField\n freq={form.repeatFreq}\n days={form.repeatDays}\n endType={form.repeatEndType}\n count={form.repeatCount}\n untilDate={form.repeatUntilDate}\n locale={locale}\n onFreqChange={(repeatFreq) =>\n update(\n repeatFreq === 'weekly'\n ? { repeatFreq, repeatDays: defaultRepeatDaysForDateInput(form.date) }\n : { repeatFreq },\n )}\n onToggleDay={(index) =>\n update({ repeatDays: form.repeatDays.map((active, dayIndex) => (dayIndex === index ? !active : active)) })}\n onEndTypeChange={(repeatEndType) => update({ repeatEndType })}\n onCountChange={(repeatCount) => update({ repeatCount })}\n onUntilDateChange={(repeatUntilDate) => update({ repeatUntilDate })}\n />\n ) : null}\n {config.people && config.people !== 'assignee' ? (\n <Field label={t(PEOPLE_FIELD_TEXT[config.people].labelKey, PEOPLE_FIELD_TEXT[config.people].label)}>\n <PeopleField\n mode=\"multi\"\n includeCustomers\n includeStaff={staffEnabled}\n placeholder={t(PEOPLE_FIELD_TEXT[config.people].placeholderKey, PEOPLE_FIELD_TEXT[config.people].placeholder)}\n ariaLabel={t(PEOPLE_FIELD_TEXT[config.people].labelKey, PEOPLE_FIELD_TEXT[config.people].label)}\n value={form.participants}\n onChange={(participants) => update({ participants })}\n />\n </Field>\n ) : null}\n {config.people === 'assignee' && staffEnabled ? (\n <Field label={t('customers.calendar.editor.assignee', 'Assignee')} error={errors.assignee}>\n <PeopleField\n mode=\"single\"\n includeCustomers={false}\n includeStaff\n placeholder={t('customers.calendar.editor.assigneePlaceholder', 'Assign to a team member\u2026')}\n ariaLabel={t('customers.calendar.editor.assignee', 'Assignee')}\n value={form.assigneeUserId\n ? [{ userId: form.assigneeUserId, name: form.assigneeName ?? form.assigneeUserId, isCustomer: false }]\n : []}\n onChange={(entries) => {\n const next = entries[entries.length - 1] ?? null\n update({ assigneeUserId: next?.userId ?? null, assigneeName: next?.name ?? null })\n }}\n />\n </Field>\n ) : null}\n </div>\n <div className=\"flex w-full flex-col gap-4\">\n <Field label={t('customers.calendar.editor.relatedTo', 'Related to')} error={errors.relatedTo}>\n <RelatedToField\n label={t('customers.calendar.editor.relatedTo', 'Related to')}\n value={form.relatedTo}\n deal={form.dealId && form.dealLabel ? { id: form.dealId, label: form.dealLabel } : null}\n onChange={(relatedTo) => update({ relatedTo })}\n onDealChange={(deal) => update({ dealId: deal?.id ?? null, dealLabel: deal?.label ?? null })}\n error={errors.relatedTo}\n />\n </Field>\n {config.location ? (\n <LocationField\n variant={config.location}\n value={form.location}\n onChange={(location) => update({ location })}\n phoneContactIds={phoneContactIds}\n />\n ) : null}\n {resourcesEnabled ? (\n <Field label={t('customers.calendar.editor.resources', 'Resources')}>\n <ResourcesField\n placeholder={t('customers.calendar.editor.resourcesPlaceholder', 'Add a resource\u2026')}\n ariaLabel={t('customers.calendar.editor.resources', 'Resources')}\n value={form.resources}\n onChange={(resources) => update({ resources })}\n />\n </Field>\n ) : null}\n {config.hasPriority ? (\n <Field label={t('customers.calendar.editor.priority.label', 'Priority')}>\n <PriorityField\n value={form.priority}\n ariaLabel={t('customers.calendar.editor.priority.label', 'Priority')}\n labels={{\n low: t('customers.calendar.editor.priority.low', 'Low'),\n medium: t('customers.calendar.editor.priority.medium', 'Medium'),\n high: t('customers.calendar.editor.priority.high', 'High'),\n }}\n onChange={(priority) => update({ priority })}\n />\n </Field>\n ) : null}\n </div>\n <Field label={t('customers.calendar.editor.description', 'Description')} className=\"lg:col-span-2\">\n <Textarea\n value={form.description}\n onChange={(event) => update({ description: event.target.value })}\n placeholder={t('customers.calendar.editor.descriptionPlaceholder', 'Add details\u2026')}\n aria-label={t('customers.calendar.editor.description', 'Description')}\n className=\"h-20 resize-none\"\n />\n </Field>\n </div>\n )\n}\n\nexport function CalendarEventEditor({\n open,\n mode,\n item,\n defaultDate,\n defaultRange,\n typeLabels,\n typeIcons,\n conflictScope,\n currentUserId,\n resourcesEnabled,\n staffEnabled,\n onOpenChange,\n onSaved,\n}: CalendarEventEditorProps) {\n const t = useT()\n const [saving, setSaving] = React.useState(false)\n const isEdit = mode === 'edit' && Boolean(item?.id)\n\n // CrudForm reads initialValues once, so every dialog open gets a fresh form\n // instance keyed by the open sequence + edited record.\n const [openSeq, setOpenSeq] = React.useState(0)\n const wasOpenRef = React.useRef(false)\n React.useEffect(() => {\n if (open && !wasOpenRef.current) setOpenSeq((seq) => seq + 1)\n wasOpenRef.current = open\n }, [open])\n const formKey = `${mode}:${item?.id ?? 'new'}:${openSeq}`\n\n const initialValues = React.useMemo<Record<string, unknown>>(() => {\n if (isEdit && item) {\n return {\n ...parseItemToFormState(item),\n ...customFieldInitialValues(item),\n id: item.id,\n updatedAt: item.updatedAt ?? undefined,\n }\n }\n return { ...createDefaultFormState(defaultDate ?? null, undefined, defaultRange ?? null) }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- openSeq re-seeds defaults per dialog open\n }, [isEdit, item, defaultDate, defaultRange, openSeq])\n\n const handleSubmit = React.useCallback(\n async (values: Record<string, unknown>) => {\n const form = formStateOfValues(values)\n const config = KIND_CONFIG[form.kind]\n const fieldErrors: Record<string, string> = {}\n if (!form.title.trim()) {\n fieldErrors.title = t('customers.calendar.editor.validation.titleRequired', 'Title is required')\n }\n if (!form.relatedTo) {\n fieldErrors.relatedTo = t('customers.calendar.editor.validation.relatedToRequired', 'Select a person or company to link this event')\n }\n if (config.hasEnd && !form.allDay && computeDurationMinutes(form) === null) {\n fieldErrors.ends = t('customers.calendar.editor.validation.endsBeforeStarts', 'End must be after start')\n }\n // A task must be assigned to a team member \u2014 surface the requirement inline\n // instead of letting the save fail with no visible reason (#3747 feedback).\n if (config.people === 'assignee' && staffEnabled !== false && !form.assigneeUserId) {\n fieldErrors.assignee = t('customers.calendar.editor.validation.assigneeRequired', 'Assign this task to a team member')\n }\n if (Object.keys(fieldErrors).length > 0) {\n throw createCrudFormError(Object.values(fieldErrors)[0], fieldErrors)\n }\n setSaving(true)\n try {\n const payload = buildInteractionPayload(form, {\n mode,\n id: item?.id,\n resourcesEnabled: resourcesEnabled === true,\n staffEnabled: staffEnabled !== false,\n })\n const custom = collectCustomFieldValues(values, {\n transform: (value) => normalizeCustomFieldSubmitValue(value),\n })\n for (const [key, value] of Object.entries(custom)) payload[`cf_${key}`] = value\n // CrudForm supplies the optimistic-lock header (auto-derived from\n // initialValues.updatedAt) via scoped request headers around onSubmit.\n await apiCallOrThrow('/api/customers/interactions', {\n method: isEdit ? 'PUT' : 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n })\n flash(t('customers.calendar.editor.saved', 'Event saved'), 'success')\n onOpenChange(false)\n requestAnimationFrame(() => { onSaved() })\n } catch (err) {\n // Surface an optimistic-lock 409 as the persistent conflict bar and\n // close \u2014 the bar renders at page level, behind the dialog overlay.\n if (extractOptimisticLockConflict(err)) {\n surfaceRecordConflict(err, t)\n onOpenChange(false)\n return\n }\n throw err\n } finally {\n setSaving(false)\n }\n },\n [isEdit, item?.id, mode, onOpenChange, onSaved, resourcesEnabled, staffEnabled, t],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => [\n {\n id: 'details',\n bare: true,\n component: (ctx) => (\n <EditorBody\n ctx={ctx}\n open={open}\n isEdit={isEdit}\n item={item}\n typeLabels={typeLabels}\n typeIcons={typeIcons ?? {}}\n conflictScope={conflictScope ?? 'all'}\n currentUserId={currentUserId ?? null}\n resourcesEnabled={resourcesEnabled === true}\n staffEnabled={staffEnabled !== false}\n />\n ),\n },\n { id: 'customFields', kind: 'customFields' },\n ],\n [open, isEdit, item, typeLabels, typeIcons, conflictScope, currentUserId, resourcesEnabled, staffEnabled],\n )\n\n const handleKeyDown = useDialogKeyHandler({\n onConfirm: () => {\n const formElement = document.getElementById(FORM_ID)\n if (formElement instanceof HTMLFormElement) formElement.requestSubmit()\n },\n disabled: saving,\n })\n\n const dialogTitle = isEdit ? t('customers.calendar.editor.title.edit', 'Edit event') : t('customers.calendar.editor.title.create', 'New event')\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n onKeyDown={handleKeyDown}\n // Only dismiss on a genuine click OUTSIDE the whole editor. Radix\n // relays a click inside the dialog (but outside an open DS\n // DatePicker/Select popover) up to the dialog as an \"interact\n // outside\" event when it dismisses that popover \u2014 without this guard\n // it would tear down the entire editor. Keep it open when the target\n // is inside the dialog body or inside any portalled popover.\n onInteractOutside={(event) => {\n const target = event.detail.originalEvent.target as HTMLElement | null\n if (target?.closest('[data-dialog-content]') || target?.closest('[data-radix-popper-content-wrapper]')) {\n event.preventDefault()\n }\n }}\n aria-describedby={undefined}\n dismissible={false}\n className=\"flex h-dvh max-h-dvh w-screen max-w-none flex-col gap-0 overflow-hidden rounded-none border-0 bg-background p-0 shadow-xl sm:h-auto sm:max-h-[calc(100dvh-4rem)] sm:w-full sm:max-w-lg sm:rounded-2xl sm:border-0 lg:max-w-3xl\"\n >\n <VisuallyHidden>\n <DialogTitle>{dialogTitle}</DialogTitle>\n </VisuallyHidden>\n <div className=\"flex shrink-0 items-center gap-3 border-b border-border bg-background py-4 pl-5 pr-4\">\n <Calendar aria-hidden className=\"size-6 shrink-0 text-foreground\" strokeWidth={1.75} />\n <p className=\"min-w-0 flex-1 text-sm font-medium leading-5 text-foreground\">{dialogTitle}</p>\n <IconButton\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => onOpenChange(false)}\n aria-label={t('customers.calendar.editor.close', 'Close')}\n className=\"shrink-0 text-muted-foreground\"\n >\n <X aria-hidden className=\"size-5\" />\n </IconButton>\n </div>\n <div\n className=\"flex-1 overflow-y-auto\"\n onScroll={() => {\n // Tell the DS date/time fields to close their (controlled) popover\n // so a portalled popover doesn't float over the form or drift away\n // from its field while scrolling (#3747 feedback). Radix ignores\n // synthetic dismiss events, so the fields drive their own `open`.\n document.dispatchEvent(new CustomEvent(EDITOR_SCROLL_EVENT))\n }}\n >\n <div className=\"px-4 py-4 sm:px-6 sm:py-5\">\n <CrudForm<Record<string, unknown>>\n key={formKey}\n formId={FORM_ID}\n embedded\n hideFooterActions\n customFieldsManageMode=\"page\"\n fields={[]}\n groups={groups}\n initialValues={initialValues}\n entityIds={INTERACTION_ENTITY_IDS}\n onSubmit={handleSubmit}\n />\n </div>\n </div>\n <div className=\"flex shrink-0 items-center justify-end gap-3 border-t border-border bg-background px-5 py-4\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => onOpenChange(false)}\n >\n {t('customers.calendar.editor.cancel', 'Cancel')}\n </Button>\n <Button\n type=\"submit\"\n form={FORM_ID}\n disabled={saving}\n >\n {saving ? t('customers.calendar.editor.saving', 'Saving\u2026') : t('customers.calendar.editor.save', 'Save event')}\n </Button>\n </div>\n </DialogContent>\n </Dialog>\n )\n}\n"],
5
+ "mappings": ";AA+LQ,SACE,KADF;AA7LR,YAAY,WAAW;AACvB,SAAS,UAAU,SAAS;AAC5B,SAAS,sBAAsB;AAC/B,SAAS,WAAW,YAAY;AAChC,SAAS,sBAAsB;AAC/B,SAAS,qCAAqC;AAC9C,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,aAAa;AACtB,SAAS,gBAAsE;AAC/E,SAAS,gCAAgC;AACzC,SAAS,OAAO,kBAAkB,kBAAkB;AACpD,SAAS,cAAc;AACvB,SAAS,QAAQ,eAAe,mBAAmB;AACnD,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,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AI,WAAU,+FACb;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,SAAQ;AAAA,cACR,SAAS,MAAM,aAAa,KAAK;AAAA,cAEhC,YAAE,oCAAoC,QAAQ;AAAA;AAAA,UACjD;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,MAAM;AAAA,cACN,UAAU;AAAA,cAET,mBAAS,EAAE,oCAAoC,cAAS,IAAI,EAAE,kCAAkC,YAAY;AAAA;AAAA,UAC/G;AAAA,WACF;AAAA;AAAA;AAAA,EACF,GACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -113,7 +113,7 @@ function ConfirmDealLostDialog({
113
113
  ] })
114
114
  ] }) }),
115
115
  /* @__PURE__ */ jsxs("div", { className: "space-y-6 px-7 py-6", children: [
116
- /* @__PURE__ */ jsxs(Alert, { variant: "warning", className: "rounded-md", children: [
116
+ /* @__PURE__ */ jsxs(Alert, { status: "warning", className: "rounded-md", children: [
117
117
  /* @__PURE__ */ jsx(AlertTitle, { children: t("customers.deals.detail.lost.warningTitle", "This action closes the deal") }),
118
118
  /* @__PURE__ */ jsx(AlertDescription, { children: t("customers.deals.detail.lost.warning", "This action sets the stage to 'Lost' and cannot be undone without 'sales.reopen' permission") })
119
119
  ] }),
@@ -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-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
- "mappings": ";AAyIgB,cAMA,YANA;AAvIhB,YAAY,WAAW;AACvB,SAAS,eAAe,OAAO,mBAAmB;AAClD,SAAS,YAA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AI,WAAU,aACb;AAAA,4BAAC,WAAM,WAAU,yCACd,YAAE,0CAA0C,uBAAuB,GACtE;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,OAAO;AAAA,YACP,UAAU,CAAC,UAAU,aAAa,MAAM,OAAO,KAAK;AAAA,YACpD,aAAa,EAAE,gDAAgD,sCAAsC;AAAA,YACrG,MAAM;AAAA,YACN,WAAU;AAAA;AAAA,QACZ;AAAA,SACF;AAAA,OACF;AAAA,IAEA,qBAAC,gBAAa,WAAU,sDACtB;AAAA,0BAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,SAC9C,YAAE,sCAAsC,QAAQ,GACnD;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,SAAQ;AAAA,UACR,UAAU;AAAA,UACV,SAAS,MAAM;AAAE,iBAAK,cAAc;AAAA,UAAE;AAAA,UAErC,YAAE,uCAAuC,cAAc;AAAA;AAAA,MAC1D;AAAA,OACF;AAAA,KACF,GACF,GACF;AAEJ;",
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 status=\"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
+ "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;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Z;AAAA,SACF;AAAA,OACF;AAAA,IAEA,qBAAC,gBAAa,WAAU,sDACtB;AAAA,0BAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,SAC9C,YAAE,sCAAsC,QAAQ,GACnD;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,SAAQ;AAAA,UACR,UAAU;AAAA,UACV,SAAS,MAAM;AAAE,iBAAK,cAAc;AAAA,UAAE;AAAA,UAErC,YAAE,uCAAuC,cAAc;AAAA;AAAA,MAC1D;AAAA,OACF;AAAA,KACF,GACF,GACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -7,6 +7,7 @@ import { useT } from "@open-mercato/shared/lib/i18n/context";
7
7
  import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
8
8
  import { Button } from "@open-mercato/ui/primitives/button";
9
9
  import { IconButton } from "@open-mercato/ui/primitives/icon-button";
10
+ import { loadLegacyActivitiesInRange } from "./legacyActivities.js";
10
11
  function getWeekDays(baseDate) {
11
12
  const day = baseDate.getDay();
12
13
  const monday = new Date(baseDate);
@@ -104,57 +105,6 @@ function MiniWeekCalendar({ entityId, useCanonicalInteractions = true, refreshRe
104
105
  } while (cursor);
105
106
  return items.filter(isWithinRange);
106
107
  }
107
- async function loadLegacyActivities() {
108
- const items = [];
109
- let page = 1;
110
- let totalPages = 1;
111
- do {
112
- const payload = await readApiResultOrThrow(
113
- `/api/customers/activities?entityId=${encodeURIComponent(entityId)}&page=${page}&pageSize=100&sortField=occurredAt&sortDir=desc`,
114
- { signal: controller.signal }
115
- );
116
- const pageItems = Array.isArray(payload?.items) ? payload.items : [];
117
- const mappedItems = pageItems.map((activity) => ({
118
- id: activity.id,
119
- interactionType: activity.activityType,
120
- title: activity.subject ?? null,
121
- body: activity.body ?? null,
122
- status: "done",
123
- scheduledAt: null,
124
- occurredAt: activity.occurredAt ?? null,
125
- priority: null,
126
- authorUserId: activity.authorUserId ?? null,
127
- ownerUserId: null,
128
- appearanceIcon: activity.appearanceIcon ?? null,
129
- appearanceColor: activity.appearanceColor ?? null,
130
- source: "legacy-activity",
131
- entityId: activity.entityId ?? null,
132
- dealId: activity.dealId ?? null,
133
- organizationId: null,
134
- tenantId: null,
135
- authorName: activity.authorName ?? null,
136
- authorEmail: activity.authorEmail ?? null,
137
- dealTitle: activity.dealTitle ?? null,
138
- customValues: null,
139
- createdAt: activity.createdAt,
140
- updatedAt: activity.createdAt
141
- }));
142
- items.push(...mappedItems.filter(isWithinRange));
143
- totalPages = typeof payload?.totalPages === "number" ? payload.totalPages : totalPages;
144
- if (!pageItems.length) break;
145
- const oldestPageTimestamp = pageItems.reduce((oldest, activity) => {
146
- const rawDate = activity.occurredAt ?? activity.createdAt;
147
- const timestamp = rawDate ? new Date(rawDate).getTime() : Number.NaN;
148
- if (!Number.isFinite(timestamp)) return oldest;
149
- return Math.min(oldest, timestamp);
150
- }, Number.POSITIVE_INFINITY);
151
- if (Number.isFinite(oldestPageTimestamp) && oldestPageTimestamp < rangeStart.getTime()) {
152
- break;
153
- }
154
- page += 1;
155
- } while (page <= totalPages);
156
- return items;
157
- }
158
108
  void (async () => {
159
109
  try {
160
110
  const canonicalItems = await loadCanonicalInteractions();
@@ -162,7 +112,12 @@ function MiniWeekCalendar({ entityId, useCanonicalInteractions = true, refreshRe
162
112
  setEvents(canonicalItems);
163
113
  return;
164
114
  }
165
- const legacyItems = await loadLegacyActivities();
115
+ const legacyItems = await loadLegacyActivitiesInRange({
116
+ entityId,
117
+ rangeStart,
118
+ isWithinRange,
119
+ signal: controller.signal
120
+ });
166
121
  const seen = /* @__PURE__ */ new Set();
167
122
  const merged = [];
168
123
  for (const item of [...canonicalItems, ...legacyItems]) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/components/detail/MiniWeekCalendar.tsx"],
4
- "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { Calendar, ChevronLeft, ChevronRight } from 'lucide-react'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport type { InteractionSummary, ActivitySummary } from './types'\n\ninterface MiniWeekCalendarProps {\n entityId: string\n useCanonicalInteractions?: boolean\n refreshRef?: React.RefObject<(() => void) | null>\n}\n\nfunction getWeekDays(baseDate: Date): Date[] {\n const day = baseDate.getDay()\n const monday = new Date(baseDate)\n monday.setDate(baseDate.getDate() - ((day === 0 ? 7 : day) - 1))\n monday.setHours(0, 0, 0, 0)\n const days: Date[] = []\n for (let i = 0; i < 7; i++) {\n const d = new Date(monday)\n d.setDate(monday.getDate() + i)\n days.push(d)\n }\n return days\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 getDayLabels(t: ReturnType<typeof useT>): string[] {\n return [\n t('customers.calendar.day.mon', 'MON'),\n t('customers.calendar.day.tue', 'TUE'),\n t('customers.calendar.day.wed', 'WED'),\n t('customers.calendar.day.thu', 'THU'),\n t('customers.calendar.day.fri', 'FRI'),\n t('customers.calendar.day.sat', 'SAT'),\n t('customers.calendar.day.sun', 'SUN'),\n ]\n}\n\nconst INTERACTION_TYPE_COLORS: Record<string, string> = {\n call: 'bg-chart-orange',\n email: 'bg-chart-blue',\n meeting: 'bg-chart-emerald',\n task: 'bg-chart-violet',\n note: 'bg-muted-foreground',\n}\n\nconst INTERACTION_TYPE_FALLBACK_COLOR = 'bg-chart-orange'\n\nfunction dotColorForType(type: string, isToday: boolean): string {\n if (isToday) return 'bg-background'\n return INTERACTION_TYPE_COLORS[type] ?? INTERACTION_TYPE_FALLBACK_COLOR\n}\n\nexport function MiniWeekCalendar({ entityId, useCanonicalInteractions = true, refreshRef }: MiniWeekCalendarProps) {\n const t = useT()\n const today = React.useMemo(() => new Date(), [])\n const [weekOffset, setWeekOffset] = React.useState(0)\n const [events, setEvents] = React.useState<InteractionSummary[]>([])\n\n const baseDate = React.useMemo(() => {\n const d = new Date(today)\n d.setDate(d.getDate() + weekOffset * 7)\n return d\n }, [today, weekOffset])\n\n const weekDays = React.useMemo(() => getWeekDays(baseDate), [baseDate])\n const weekStart = weekDays[0]\n const weekEnd = weekDays[6]\n\n const monthLabel = React.useMemo(() => {\n const month = baseDate.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })\n return weekOffset === 0\n ? t('customers.calendar.thisWeek', 'This week') + ' \u2014 ' + month\n : month\n }, [baseDate, t, weekOffset])\n\n const [refreshKey, setRefreshKey] = React.useState(0)\n const refresh = React.useCallback(() => setRefreshKey((k) => k + 1), [])\n\n React.useEffect(() => {\n if (refreshRef) (refreshRef as React.MutableRefObject<(() => void) | null>).current = refresh\n }, [refresh, refreshRef])\n\n React.useEffect(() => {\n if (!entityId) return\n const controller = new AbortController()\n const rangeStart = new Date(weekStart)\n rangeStart.setHours(0, 0, 0, 0)\n const rangeEnd = new Date(weekEnd)\n rangeEnd.setDate(rangeEnd.getDate() + 2)\n rangeEnd.setHours(23, 59, 59, 999)\n\n function isWithinRange(item: InteractionSummary): boolean {\n const rawDate = item.scheduledAt ?? item.occurredAt ?? item.createdAt\n if (!rawDate) return false\n const eventDate = new Date(rawDate)\n if (Number.isNaN(eventDate.getTime())) return false\n return eventDate >= rangeStart && eventDate <= rangeEnd\n }\n\n async function loadCanonicalInteractions(): Promise<InteractionSummary[]> {\n const items: InteractionSummary[] = []\n let cursor: string | undefined\n do {\n const params = new URLSearchParams({\n entityId,\n sortField: 'occurredAt',\n sortDir: 'desc',\n limit: '100',\n excludeInteractionType: 'task',\n from: rangeStart.toISOString(),\n to: rangeEnd.toISOString(),\n })\n if (cursor) params.set('cursor', cursor)\n const payload = await readApiResultOrThrow<{\n items?: InteractionSummary[]\n nextCursor?: string\n }>(`/api/customers/interactions?${params.toString()}`, { signal: controller.signal })\n const pageItems = Array.isArray(payload?.items) ? payload.items : []\n items.push(...pageItems)\n cursor = typeof payload?.nextCursor === 'string' ? payload.nextCursor : undefined\n } while (cursor)\n return items.filter(isWithinRange)\n }\n\n async function loadLegacyActivities(): Promise<InteractionSummary[]> {\n const items: InteractionSummary[] = []\n let page = 1\n let totalPages = 1\n do {\n const payload = await readApiResultOrThrow<{\n items?: ActivitySummary[]\n totalPages?: number\n }>(\n `/api/customers/activities?entityId=${encodeURIComponent(entityId)}&page=${page}&pageSize=100&sortField=occurredAt&sortDir=desc`,\n { signal: controller.signal },\n )\n const pageItems = Array.isArray(payload?.items) ? payload.items : []\n const mappedItems: InteractionSummary[] = pageItems.map((activity) => ({\n id: activity.id,\n interactionType: activity.activityType,\n title: activity.subject ?? null,\n body: activity.body ?? null,\n status: 'done',\n scheduledAt: null,\n occurredAt: activity.occurredAt ?? null,\n priority: null,\n authorUserId: activity.authorUserId ?? null,\n ownerUserId: null,\n appearanceIcon: activity.appearanceIcon ?? null,\n appearanceColor: activity.appearanceColor ?? null,\n source: 'legacy-activity',\n entityId: activity.entityId ?? null,\n dealId: activity.dealId ?? null,\n organizationId: null,\n tenantId: null,\n authorName: activity.authorName ?? null,\n authorEmail: activity.authorEmail ?? null,\n dealTitle: activity.dealTitle ?? null,\n customValues: null,\n createdAt: activity.createdAt,\n updatedAt: activity.createdAt,\n }))\n items.push(...mappedItems.filter(isWithinRange))\n totalPages = typeof payload?.totalPages === 'number' ? payload.totalPages : totalPages\n if (!pageItems.length) break\n const oldestPageTimestamp = pageItems.reduce<number>((oldest, activity) => {\n const rawDate = activity.occurredAt ?? activity.createdAt\n const timestamp = rawDate ? new Date(rawDate).getTime() : Number.NaN\n if (!Number.isFinite(timestamp)) return oldest\n return Math.min(oldest, timestamp)\n }, Number.POSITIVE_INFINITY)\n if (Number.isFinite(oldestPageTimestamp) && oldestPageTimestamp < rangeStart.getTime()) {\n break\n }\n page += 1\n } while (page <= totalPages)\n return items\n }\n\n void (async () => {\n try {\n const canonicalItems = await loadCanonicalInteractions()\n if (useCanonicalInteractions) {\n setEvents(canonicalItems)\n return\n }\n const legacyItems = await loadLegacyActivities()\n const seen = new Set<string>()\n const merged: InteractionSummary[] = []\n for (const item of [...canonicalItems, ...legacyItems]) {\n if (seen.has(item.id)) continue\n seen.add(item.id)\n merged.push(item)\n }\n setEvents(merged.filter(isWithinRange))\n } catch {\n setEvents([])\n }\n })()\n return () => controller.abort()\n }, [entityId, weekStart, weekEnd, useCanonicalInteractions, refreshKey])\n\n const eventsByDay = React.useMemo(() => {\n const map = new Map<string, InteractionSummary[]>()\n for (const event of events) {\n const dateStr = event.scheduledAt ?? event.occurredAt ?? event.createdAt\n if (!dateStr) continue\n const key = new Date(dateStr).toDateString()\n const list = map.get(key) ?? []\n list.push(event)\n map.set(key, list)\n }\n return map\n }, [events])\n\n // Selected day for summary (defaults to today)\n const [selectedDay, setSelectedDay] = React.useState<Date | null>(null)\n const activeDay = selectedDay ?? today\n\n // Collect events for the active day + tomorrow for the summary list\n const summaryEvents = React.useMemo(() => {\n const result: Array<{ event: InteractionSummary; dayLabel: string; isToday: boolean }> = []\n for (let offset = 0; offset <= 2 && result.length < 3; offset++) {\n const d = new Date(activeDay)\n d.setDate(d.getDate() + offset)\n const dayEvents = eventsByDay.get(d.toDateString()) ?? []\n const isActiveDay = offset === 0\n const label = isActiveDay\n ? ''\n : offset === 1\n ? t('customers.calendar.tomorrow', 'Tomorrow') + ' '\n : d.toLocaleDateString(undefined, { weekday: 'short' }) + ' '\n for (const ev of dayEvents) {\n if (result.length >= 3) break\n result.push({ event: ev, dayLabel: label, isToday: isActiveDay })\n }\n }\n return result\n }, [eventsByDay, activeDay, t])\n\n const dayLabels = getDayLabels(t)\n\n return (\n <div className=\"rounded-lg border border-border/60 p-4\">\n {/* Header */}\n <div className=\"mb-3 flex items-center justify-between\">\n <div className=\"flex items-center gap-2 text-sm font-medium\">\n <Calendar className=\"size-4 text-muted-foreground\" />\n {monthLabel}\n </div>\n <div className=\"flex items-center gap-1\">\n <IconButton type=\"button\" variant=\"ghost\" size=\"xs\" onClick={() => setWeekOffset((w) => w - 1)} aria-label={t('customers.calendar.previousWeek', 'Previous week')}>\n <ChevronLeft className=\"size-3.5\" />\n </IconButton>\n <IconButton type=\"button\" variant=\"ghost\" size=\"xs\" onClick={() => setWeekOffset((w) => w + 1)} aria-label={t('customers.calendar.nextWeek', 'Next week')}>\n <ChevronRight className=\"size-3.5\" />\n </IconButton>\n </div>\n </div>\n\n {/* Day headers */}\n <div className=\"grid grid-cols-7 mb-1\">\n {dayLabels.map((label) => (\n <div key={label} className=\"text-center text-xs font-medium text-muted-foreground\">\n {label}\n </div>\n ))}\n </div>\n\n {/* Day cells \u2014 bordered grid like Figma */}\n <div className=\"grid grid-cols-7 border rounded-lg overflow-hidden\">\n {weekDays.map((day) => {\n const isToday = isSameDay(day, today)\n const isSelected = selectedDay ? isSameDay(day, selectedDay) : isToday\n const dayEvents = eventsByDay.get(day.toDateString()) ?? []\n const hasEvents = dayEvents.length > 0\n return (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n key={day.toISOString()}\n onClick={() => setSelectedDay(isSameDay(day, selectedDay ?? today) ? null : day)}\n className={cn(\n 'h-auto flex flex-col items-center border-r last:border-r-0 py-3 text-sm transition-colors cursor-pointer rounded-none',\n isSelected ? 'bg-foreground text-background font-bold' : 'hover:bg-accent/50',\n )}\n >\n <span className=\"text-base\">{day.getDate()}</span>\n {hasEvents && (\n <div className=\"mt-1 flex gap-0.5\">\n {dayEvents.slice(0, 3).map((ev, i) => (\n <span\n key={i}\n className={cn(\n 'size-1 rounded-full',\n dotColorForType(ev.interactionType, isSelected),\n )}\n />\n ))}\n </div>\n )}\n </Button>\n )\n })}\n </div>\n\n {/* Day summary \u2014 events for selected/active day + upcoming */}\n {summaryEvents.length > 0 && (\n <div className=\"mt-3 space-y-1.5 border-t pt-3\">\n {summaryEvents.map(({ event, dayLabel, isToday: isActiveDay }) => {\n const dateStr = event.scheduledAt ?? event.occurredAt ?? event.createdAt\n const time = dateStr ? new Date(dateStr).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : ''\n return (\n <div key={event.id} className=\"flex items-center gap-2 text-xs\">\n <span className={cn('size-1.5 rounded-full shrink-0', INTERACTION_TYPE_COLORS[event.interactionType] ?? (isActiveDay ? INTERACTION_TYPE_FALLBACK_COLOR : 'bg-muted-foreground'))} />\n <span className=\"font-semibold text-muted-foreground shrink-0\">\n {dayLabel}{time}\n </span>\n <span className=\"truncate\">{event.title ?? event.body ?? event.interactionType}</span>\n </div>\n )\n })}\n </div>\n )}\n </div>\n )\n}\n"],
5
- "mappings": ";AAgQQ,SACE,KADF;AA9PR,YAAY,WAAW;AACvB,SAAS,UAAU,aAAa,oBAAoB;AACpD,SAAS,UAAU;AACnB,SAAS,YAAY;AACrB,SAAS,4BAA4B;AACrC,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAS3B,SAAS,YAAY,UAAwB;AAC3C,QAAM,MAAM,SAAS,OAAO;AAC5B,QAAM,SAAS,IAAI,KAAK,QAAQ;AAChC,SAAO,QAAQ,SAAS,QAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO,EAAE;AAC/D,SAAO,SAAS,GAAG,GAAG,GAAG,CAAC;AAC1B,QAAM,OAAe,CAAC;AACtB,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,UAAM,IAAI,IAAI,KAAK,MAAM;AACzB,MAAE,QAAQ,OAAO,QAAQ,IAAI,CAAC;AAC9B,SAAK,KAAK,CAAC;AAAA,EACb;AACA,SAAO;AACT;AAEA,SAAS,UAAU,GAAS,GAAkB;AAC5C,SAAO,EAAE,YAAY,MAAM,EAAE,YAAY,KAAK,EAAE,SAAS,MAAM,EAAE,SAAS,KAAK,EAAE,QAAQ,MAAM,EAAE,QAAQ;AAC3G;AAEA,SAAS,aAAa,GAAsC;AAC1D,SAA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cAAc,SAAS,KACtB,oBAAC,SAAI,WAAU,kCACZ,wBAAc,IAAI,CAAC,EAAE,OAAO,UAAU,SAAS,YAAY,MAAM;AAChE,YAAM,UAAU,MAAM,eAAe,MAAM,cAAc,MAAM;AAC/D,YAAM,OAAO,UAAU,IAAI,KAAK,OAAO,EAAE,mBAAmB,QAAW,EAAE,MAAM,WAAW,QAAQ,UAAU,CAAC,IAAI;AACjH,aACE,qBAAC,SAAmB,WAAU,mCAC5B;AAAA,4BAAC,UAAK,WAAW,GAAG,kCAAkC,wBAAwB,MAAM,eAAe,MAAM,cAAc,kCAAkC,sBAAsB,GAAG;AAAA,QAClL,qBAAC,UAAK,WAAU,gDACb;AAAA;AAAA,UAAU;AAAA,WACb;AAAA,QACA,oBAAC,UAAK,WAAU,YAAY,gBAAM,SAAS,MAAM,QAAQ,MAAM,iBAAgB;AAAA,WALvE,MAAM,EAMhB;AAAA,IAEJ,CAAC,GACH;AAAA,KAEJ;AAEJ;",
4
+ "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { Calendar, ChevronLeft, ChevronRight } from 'lucide-react'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport type { InteractionSummary } from './types'\nimport { loadLegacyActivitiesInRange } from './legacyActivities'\n\ninterface MiniWeekCalendarProps {\n entityId: string\n useCanonicalInteractions?: boolean\n refreshRef?: React.RefObject<(() => void) | null>\n}\n\nfunction getWeekDays(baseDate: Date): Date[] {\n const day = baseDate.getDay()\n const monday = new Date(baseDate)\n monday.setDate(baseDate.getDate() - ((day === 0 ? 7 : day) - 1))\n monday.setHours(0, 0, 0, 0)\n const days: Date[] = []\n for (let i = 0; i < 7; i++) {\n const d = new Date(monday)\n d.setDate(monday.getDate() + i)\n days.push(d)\n }\n return days\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 getDayLabels(t: ReturnType<typeof useT>): string[] {\n return [\n t('customers.calendar.day.mon', 'MON'),\n t('customers.calendar.day.tue', 'TUE'),\n t('customers.calendar.day.wed', 'WED'),\n t('customers.calendar.day.thu', 'THU'),\n t('customers.calendar.day.fri', 'FRI'),\n t('customers.calendar.day.sat', 'SAT'),\n t('customers.calendar.day.sun', 'SUN'),\n ]\n}\n\nconst INTERACTION_TYPE_COLORS: Record<string, string> = {\n call: 'bg-chart-orange',\n email: 'bg-chart-blue',\n meeting: 'bg-chart-emerald',\n task: 'bg-chart-violet',\n note: 'bg-muted-foreground',\n}\n\nconst INTERACTION_TYPE_FALLBACK_COLOR = 'bg-chart-orange'\n\nfunction dotColorForType(type: string, isToday: boolean): string {\n if (isToday) return 'bg-background'\n return INTERACTION_TYPE_COLORS[type] ?? INTERACTION_TYPE_FALLBACK_COLOR\n}\n\nexport function MiniWeekCalendar({ entityId, useCanonicalInteractions = true, refreshRef }: MiniWeekCalendarProps) {\n const t = useT()\n const today = React.useMemo(() => new Date(), [])\n const [weekOffset, setWeekOffset] = React.useState(0)\n const [events, setEvents] = React.useState<InteractionSummary[]>([])\n\n const baseDate = React.useMemo(() => {\n const d = new Date(today)\n d.setDate(d.getDate() + weekOffset * 7)\n return d\n }, [today, weekOffset])\n\n const weekDays = React.useMemo(() => getWeekDays(baseDate), [baseDate])\n const weekStart = weekDays[0]\n const weekEnd = weekDays[6]\n\n const monthLabel = React.useMemo(() => {\n const month = baseDate.toLocaleDateString(undefined, { month: 'long', year: 'numeric' })\n return weekOffset === 0\n ? t('customers.calendar.thisWeek', 'This week') + ' \u2014 ' + month\n : month\n }, [baseDate, t, weekOffset])\n\n const [refreshKey, setRefreshKey] = React.useState(0)\n const refresh = React.useCallback(() => setRefreshKey((k) => k + 1), [])\n\n React.useEffect(() => {\n if (refreshRef) (refreshRef as React.MutableRefObject<(() => void) | null>).current = refresh\n }, [refresh, refreshRef])\n\n React.useEffect(() => {\n if (!entityId) return\n const controller = new AbortController()\n const rangeStart = new Date(weekStart)\n rangeStart.setHours(0, 0, 0, 0)\n const rangeEnd = new Date(weekEnd)\n rangeEnd.setDate(rangeEnd.getDate() + 2)\n rangeEnd.setHours(23, 59, 59, 999)\n\n function isWithinRange(item: InteractionSummary): boolean {\n const rawDate = item.scheduledAt ?? item.occurredAt ?? item.createdAt\n if (!rawDate) return false\n const eventDate = new Date(rawDate)\n if (Number.isNaN(eventDate.getTime())) return false\n return eventDate >= rangeStart && eventDate <= rangeEnd\n }\n\n async function loadCanonicalInteractions(): Promise<InteractionSummary[]> {\n const items: InteractionSummary[] = []\n let cursor: string | undefined\n do {\n const params = new URLSearchParams({\n entityId,\n sortField: 'occurredAt',\n sortDir: 'desc',\n limit: '100',\n excludeInteractionType: 'task',\n from: rangeStart.toISOString(),\n to: rangeEnd.toISOString(),\n })\n if (cursor) params.set('cursor', cursor)\n const payload = await readApiResultOrThrow<{\n items?: InteractionSummary[]\n nextCursor?: string\n }>(`/api/customers/interactions?${params.toString()}`, { signal: controller.signal })\n const pageItems = Array.isArray(payload?.items) ? payload.items : []\n items.push(...pageItems)\n cursor = typeof payload?.nextCursor === 'string' ? payload.nextCursor : undefined\n } while (cursor)\n return items.filter(isWithinRange)\n }\n\n void (async () => {\n try {\n const canonicalItems = await loadCanonicalInteractions()\n if (useCanonicalInteractions) {\n setEvents(canonicalItems)\n return\n }\n const legacyItems = await loadLegacyActivitiesInRange({\n entityId,\n rangeStart,\n isWithinRange,\n signal: controller.signal,\n })\n const seen = new Set<string>()\n const merged: InteractionSummary[] = []\n for (const item of [...canonicalItems, ...legacyItems]) {\n if (seen.has(item.id)) continue\n seen.add(item.id)\n merged.push(item)\n }\n setEvents(merged.filter(isWithinRange))\n } catch {\n setEvents([])\n }\n })()\n return () => controller.abort()\n }, [entityId, weekStart, weekEnd, useCanonicalInteractions, refreshKey])\n\n const eventsByDay = React.useMemo(() => {\n const map = new Map<string, InteractionSummary[]>()\n for (const event of events) {\n const dateStr = event.scheduledAt ?? event.occurredAt ?? event.createdAt\n if (!dateStr) continue\n const key = new Date(dateStr).toDateString()\n const list = map.get(key) ?? []\n list.push(event)\n map.set(key, list)\n }\n return map\n }, [events])\n\n // Selected day for summary (defaults to today)\n const [selectedDay, setSelectedDay] = React.useState<Date | null>(null)\n const activeDay = selectedDay ?? today\n\n // Collect events for the active day + tomorrow for the summary list\n const summaryEvents = React.useMemo(() => {\n const result: Array<{ event: InteractionSummary; dayLabel: string; isToday: boolean }> = []\n for (let offset = 0; offset <= 2 && result.length < 3; offset++) {\n const d = new Date(activeDay)\n d.setDate(d.getDate() + offset)\n const dayEvents = eventsByDay.get(d.toDateString()) ?? []\n const isActiveDay = offset === 0\n const label = isActiveDay\n ? ''\n : offset === 1\n ? t('customers.calendar.tomorrow', 'Tomorrow') + ' '\n : d.toLocaleDateString(undefined, { weekday: 'short' }) + ' '\n for (const ev of dayEvents) {\n if (result.length >= 3) break\n result.push({ event: ev, dayLabel: label, isToday: isActiveDay })\n }\n }\n return result\n }, [eventsByDay, activeDay, t])\n\n const dayLabels = getDayLabels(t)\n\n return (\n <div className=\"rounded-lg border border-border/60 p-4\">\n {/* Header */}\n <div className=\"mb-3 flex items-center justify-between\">\n <div className=\"flex items-center gap-2 text-sm font-medium\">\n <Calendar className=\"size-4 text-muted-foreground\" />\n {monthLabel}\n </div>\n <div className=\"flex items-center gap-1\">\n <IconButton type=\"button\" variant=\"ghost\" size=\"xs\" onClick={() => setWeekOffset((w) => w - 1)} aria-label={t('customers.calendar.previousWeek', 'Previous week')}>\n <ChevronLeft className=\"size-3.5\" />\n </IconButton>\n <IconButton type=\"button\" variant=\"ghost\" size=\"xs\" onClick={() => setWeekOffset((w) => w + 1)} aria-label={t('customers.calendar.nextWeek', 'Next week')}>\n <ChevronRight className=\"size-3.5\" />\n </IconButton>\n </div>\n </div>\n\n {/* Day headers */}\n <div className=\"grid grid-cols-7 mb-1\">\n {dayLabels.map((label) => (\n <div key={label} className=\"text-center text-xs font-medium text-muted-foreground\">\n {label}\n </div>\n ))}\n </div>\n\n {/* Day cells \u2014 bordered grid like Figma */}\n <div className=\"grid grid-cols-7 border rounded-lg overflow-hidden\">\n {weekDays.map((day) => {\n const isToday = isSameDay(day, today)\n const isSelected = selectedDay ? isSameDay(day, selectedDay) : isToday\n const dayEvents = eventsByDay.get(day.toDateString()) ?? []\n const hasEvents = dayEvents.length > 0\n return (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n key={day.toISOString()}\n onClick={() => setSelectedDay(isSameDay(day, selectedDay ?? today) ? null : day)}\n className={cn(\n 'h-auto flex flex-col items-center border-r last:border-r-0 py-3 text-sm transition-colors cursor-pointer rounded-none',\n isSelected ? 'bg-foreground text-background font-bold' : 'hover:bg-accent/50',\n )}\n >\n <span className=\"text-base\">{day.getDate()}</span>\n {hasEvents && (\n <div className=\"mt-1 flex gap-0.5\">\n {dayEvents.slice(0, 3).map((ev, i) => (\n <span\n key={i}\n className={cn(\n 'size-1 rounded-full',\n dotColorForType(ev.interactionType, isSelected),\n )}\n />\n ))}\n </div>\n )}\n </Button>\n )\n })}\n </div>\n\n {/* Day summary \u2014 events for selected/active day + upcoming */}\n {summaryEvents.length > 0 && (\n <div className=\"mt-3 space-y-1.5 border-t pt-3\">\n {summaryEvents.map(({ event, dayLabel, isToday: isActiveDay }) => {\n const dateStr = event.scheduledAt ?? event.occurredAt ?? event.createdAt\n const time = dateStr ? new Date(dateStr).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : ''\n return (\n <div key={event.id} className=\"flex items-center gap-2 text-xs\">\n <span className={cn('size-1.5 rounded-full shrink-0', INTERACTION_TYPE_COLORS[event.interactionType] ?? (isActiveDay ? INTERACTION_TYPE_FALLBACK_COLOR : 'bg-muted-foreground'))} />\n <span className=\"font-semibold text-muted-foreground shrink-0\">\n {dayLabel}{time}\n </span>\n <span className=\"truncate\">{event.title ?? event.body ?? event.interactionType}</span>\n </div>\n )\n })}\n </div>\n )}\n </div>\n )\n}\n"],
5
+ "mappings": ";AA+MQ,SACE,KADF;AA7MR,YAAY,WAAW;AACvB,SAAS,UAAU,aAAa,oBAAoB;AACpD,SAAS,UAAU;AACnB,SAAS,YAAY;AACrB,SAAS,4BAA4B;AACrC,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAE3B,SAAS,mCAAmC;AAQ5C,SAAS,YAAY,UAAwB;AAC3C,QAAM,MAAM,SAAS,OAAO;AAC5B,QAAM,SAAS,IAAI,KAAK,QAAQ;AAChC,SAAO,QAAQ,SAAS,QAAQ,MAAM,QAAQ,IAAI,IAAI,OAAO,EAAE;AAC/D,SAAO,SAAS,GAAG,GAAG,GAAG,CAAC;AAC1B,QAAM,OAAe,CAAC;AACtB,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AAC1B,UAAM,IAAI,IAAI,KAAK,MAAM;AACzB,MAAE,QAAQ,OAAO,QAAQ,IAAI,CAAC;AAC9B,SAAK,KAAK,CAAC;AAAA,EACb;AACA,SAAO;AACT;AAEA,SAAS,UAAU,GAAS,GAAkB;AAC5C,SAAO,EAAE,YAAY,MAAM,EAAE,YAAY,KAAK,EAAE,SAAS,MAAM,EAAE,SAAS,KAAK,EAAE,QAAQ,MAAM,EAAE,QAAQ;AAC3G;AAEA,SAAS,aAAa,GAAsC;AAC1D,SAAO;AAAA,IACL,EAAE,8BAA8B,KAAK;AAAA,IACrC,EAAE,8BAA8B,KAAK;AAAA,IACrC,EAAE,8BAA8B,KAAK;AAAA,IACrC,EAAE,8BAA8B,KAAK;AAAA,IACrC,EAAE,8BAA8B,KAAK;AAAA,IACrC,EAAE,8BAA8B,KAAK;AAAA,IACrC,EAAE,8BAA8B,KAAK;AAAA,EACvC;AACF;AAEA,MAAM,0BAAkD;AAAA,EACtD,MAAM;AAAA,EACN,OAAO;AAAA,EACP,SAA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AAM,QAAQ,MAAM,iBAAgB;AAAA,WALvE,MAAM,EAMhB;AAAA,IAEJ,CAAC,GACH;AAAA,KAEJ;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -443,7 +443,7 @@ function ScheduleActivityDialog({
443
443
  }, className: "flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background", "aria-label": t("customers.schedule.cancel", "Cancel"), children: /* @__PURE__ */ jsx(X, { className: "size-4 text-muted-foreground" }) })
444
444
  ] }),
445
445
  /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 bg-background p-6", children: [
446
- state.conflict && /* @__PURE__ */ jsxs(Alert, { variant: "warning", className: "rounded-lg", children: [
446
+ state.conflict && /* @__PURE__ */ jsxs(Alert, { status: "warning", className: "rounded-lg", children: [
447
447
  /* @__PURE__ */ jsx(AlertTitle, { children: t("customers.schedule.conflict.title", "Calendar conflict") }),
448
448
  /* @__PURE__ */ jsx(AlertDescription, { children: state.conflict })
449
449
  ] }),