@open-mercato/core 0.6.2-develop.3467.1.2a1818709d → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/helpers/integration/queue-runner.js +15 -3
- package/dist/helpers/integration/queue-runner.js.map +2 -2
- package/dist/helpers/integration/queue.js +1 -1
- package/dist/helpers/integration/queue.js.map +2 -2
- package/dist/helpers/integration/salesUi.js +24 -1
- package/dist/helpers/integration/salesUi.js.map +2 -2
- package/dist/modules/auth/api/roles/acl/route.js +37 -1
- package/dist/modules/auth/api/roles/acl/route.js.map +2 -2
- package/dist/modules/auth/api/roles/route.js +36 -2
- package/dist/modules/auth/api/roles/route.js.map +2 -2
- package/dist/modules/auth/api/users/acl/route.js +36 -1
- package/dist/modules/auth/api/users/acl/route.js.map +2 -2
- package/dist/modules/auth/api/users/route.js +101 -13
- package/dist/modules/auth/api/users/route.js.map +2 -2
- package/dist/modules/auth/backend/roles/[id]/edit/page.js +32 -14
- package/dist/modules/auth/backend/roles/[id]/edit/page.js.map +2 -2
- package/dist/modules/auth/backend/users/[id]/edit/page.js +1 -1
- package/dist/modules/auth/backend/users/[id]/edit/page.js.map +2 -2
- package/dist/modules/auth/backend/users/create/page.js +1 -1
- package/dist/modules/auth/backend/users/create/page.js.map +2 -2
- package/dist/modules/auth/backend/users/roleOptions.js +1 -1
- package/dist/modules/auth/backend/users/roleOptions.js.map +2 -2
- package/dist/modules/auth/commands/roles.js +8 -0
- package/dist/modules/auth/commands/roles.js.map +2 -2
- package/dist/modules/auth/commands/users.js +3 -0
- package/dist/modules/auth/commands/users.js.map +2 -2
- package/dist/modules/auth/components/AclEditor.js +53 -26
- package/dist/modules/auth/components/AclEditor.js.map +2 -2
- package/dist/modules/auth/lib/grantChecks.js +97 -2
- package/dist/modules/auth/lib/grantChecks.js.map +2 -2
- package/dist/modules/business_rules/lib/expression-evaluator.js +9 -7
- package/dist/modules/business_rules/lib/expression-evaluator.js.map +2 -2
- package/dist/modules/customers/ai-agents.js +10 -1
- package/dist/modules/customers/ai-agents.js.map +2 -2
- package/dist/modules/customers/ai-tools/settings-pack.js +55 -1
- package/dist/modules/customers/ai-tools/settings-pack.js.map +2 -2
- package/dist/modules/customers/components/detail/schedule/useScheduleFormState.js +13 -5
- package/dist/modules/customers/components/detail/schedule/useScheduleFormState.js.map +2 -2
- package/dist/modules/customers/lib/personCompanyLinkTable.js +4 -30
- package/dist/modules/customers/lib/personCompanyLinkTable.js.map +2 -2
- package/dist/modules/customers/migrations/Migration20260521175027.js +12 -0
- package/dist/modules/customers/migrations/Migration20260521175027.js.map +7 -0
- package/dist/modules/dashboards/components/WidgetVisibilityEditor.js +41 -12
- package/dist/modules/dashboards/components/WidgetVisibilityEditor.js.map +2 -2
- package/dist/modules/data_sync/api/options.js +2 -0
- package/dist/modules/data_sync/api/options.js.map +2 -2
- package/dist/modules/data_sync/api/run.js +77 -58
- package/dist/modules/data_sync/api/run.js.map +2 -2
- package/dist/modules/data_sync/backend/data-sync/page.js +3 -2
- package/dist/modules/data_sync/backend/data-sync/page.js.map +2 -2
- package/dist/modules/data_sync/components/IntegrationScheduleTab.js +8 -3
- package/dist/modules/data_sync/components/IntegrationScheduleTab.js.map +2 -2
- package/dist/modules/integrations/backend/integrations/[id]/page.js +15 -13
- package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
- package/dist/modules/integrations/data/validators.js +9 -6
- package/dist/modules/integrations/data/validators.js.map +2 -2
- package/dist/modules/messages/api/route.js +2 -2
- package/dist/modules/messages/api/route.js.map +2 -2
- package/dist/modules/messages/commands/messages.js +42 -2
- package/dist/modules/messages/commands/messages.js.map +2 -2
- package/dist/modules/messages/components/MessagesInboxPageClient.js +66 -87
- package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
- package/dist/modules/messages/components/inboxFilters.js +133 -0
- package/dist/modules/messages/components/inboxFilters.js.map +7 -0
- package/dist/modules/messages/data/validators.js +8 -6
- package/dist/modules/messages/data/validators.js.map +2 -2
- package/dist/modules/progress/api/jobs/route.js +26 -16
- package/dist/modules/progress/api/jobs/route.js.map +2 -2
- package/dist/modules/query_index/di.js +8 -6
- package/dist/modules/query_index/di.js.map +2 -2
- package/dist/modules/query_index/lib/indexer.js +12 -10
- package/dist/modules/query_index/lib/indexer.js.map +2 -2
- package/dist/modules/query_index/subscribers/upsert_one.js +7 -1
- package/dist/modules/query_index/subscribers/upsert_one.js.map +2 -2
- package/dist/modules/sales/api/order-adjustments/route.js.map +2 -2
- package/dist/modules/sales/api/quote-adjustments/route.js.map +2 -2
- package/dist/modules/sales/commands/documents.js +104 -0
- package/dist/modules/sales/commands/documents.js.map +2 -2
- package/dist/modules/sales/data/validators.js +20 -1
- package/dist/modules/sales/data/validators.js.map +2 -2
- package/dist/modules/sales/lib/makeSalesLineRoute.js.map +2 -2
- package/dist/modules/sync_excel/api/import/route.js +126 -116
- package/dist/modules/sync_excel/api/import/route.js.map +2 -2
- package/dist/modules/sync_excel/lib/adapters/customers.js +1 -0
- package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
- package/dist/modules/translations/components/TranslationManager.js +9 -4
- package/dist/modules/translations/components/TranslationManager.js.map +2 -2
- package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
- package/dist/modules/workflows/lib/event-trigger-service.js +23 -11
- package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
- package/jest.config.cjs +4 -1
- package/package.json +15 -16
- package/src/helpers/integration/queue-runner.ts +21 -2
- package/src/helpers/integration/queue.ts +1 -1
- package/src/helpers/integration/salesUi.ts +26 -1
- package/src/modules/auth/api/roles/acl/route.ts +39 -1
- package/src/modules/auth/api/roles/route.ts +38 -2
- package/src/modules/auth/api/users/acl/route.ts +41 -1
- package/src/modules/auth/api/users/route.ts +105 -12
- package/src/modules/auth/backend/roles/[id]/edit/page.tsx +35 -13
- package/src/modules/auth/backend/users/[id]/edit/page.tsx +1 -1
- package/src/modules/auth/backend/users/create/page.tsx +1 -1
- package/src/modules/auth/backend/users/roleOptions.ts +2 -1
- package/src/modules/auth/commands/roles.ts +8 -0
- package/src/modules/auth/commands/users.ts +3 -0
- package/src/modules/auth/components/AclEditor.tsx +50 -24
- package/src/modules/auth/lib/grantChecks.ts +116 -2
- package/src/modules/business_rules/lib/expression-evaluator.ts +9 -13
- package/src/modules/customers/ai-agents.ts +10 -1
- package/src/modules/customers/ai-tools/settings-pack.ts +62 -1
- package/src/modules/customers/components/detail/schedule/useScheduleFormState.ts +18 -7
- package/src/modules/customers/lib/personCompanyLinkTable.ts +33 -41
- package/src/modules/customers/migrations/Migration20260521175027.ts +39 -0
- package/src/modules/dashboards/components/WidgetVisibilityEditor.tsx +38 -12
- package/src/modules/data_sync/api/options.ts +2 -0
- package/src/modules/data_sync/api/run.ts +80 -61
- package/src/modules/data_sync/backend/data-sync/page.tsx +10 -0
- package/src/modules/data_sync/components/IntegrationScheduleTab.tsx +17 -3
- package/src/modules/data_sync/i18n/de.json +3 -0
- package/src/modules/data_sync/i18n/en.json +3 -0
- package/src/modules/data_sync/i18n/es.json +3 -0
- package/src/modules/data_sync/i18n/pl.json +3 -0
- package/src/modules/data_sync/lib/adapter.ts +9 -0
- package/src/modules/integrations/backend/integrations/[id]/page.tsx +15 -13
- package/src/modules/integrations/data/validators.ts +5 -4
- package/src/modules/messages/api/route.ts +2 -2
- package/src/modules/messages/commands/messages.ts +54 -2
- package/src/modules/messages/components/MessagesInboxPageClient.tsx +75 -90
- package/src/modules/messages/components/inboxFilters.ts +162 -0
- package/src/modules/messages/data/validators.ts +7 -5
- package/src/modules/messages/i18n/de.json +5 -4
- package/src/modules/messages/i18n/en.json +5 -4
- package/src/modules/messages/i18n/es.json +5 -4
- package/src/modules/messages/i18n/pl.json +5 -4
- package/src/modules/progress/api/jobs/route.ts +30 -20
- package/src/modules/query_index/di.ts +9 -7
- package/src/modules/query_index/lib/indexer.ts +13 -11
- package/src/modules/query_index/subscribers/upsert_one.ts +9 -1
- package/src/modules/sales/api/order-adjustments/route.ts +2 -1
- package/src/modules/sales/api/quote-adjustments/route.ts +2 -1
- package/src/modules/sales/commands/documents.ts +116 -0
- package/src/modules/sales/data/validators.ts +38 -0
- package/src/modules/sales/i18n/de.json +2 -0
- package/src/modules/sales/i18n/en.json +2 -0
- package/src/modules/sales/i18n/es.json +2 -0
- package/src/modules/sales/i18n/pl.json +2 -0
- package/src/modules/sales/lib/makeSalesLineRoute.ts +2 -1
- package/src/modules/staff/i18n/de.json +1 -0
- package/src/modules/staff/i18n/en.json +1 -0
- package/src/modules/staff/i18n/es.json +1 -0
- package/src/modules/staff/i18n/pl.json +1 -0
- package/src/modules/sync_excel/api/import/route.ts +141 -131
- package/src/modules/sync_excel/lib/adapters/customers.ts +1 -0
- package/src/modules/translations/components/TranslationManager.tsx +9 -4
- package/src/modules/workflows/lib/activity-executor.ts +4 -3
- package/src/modules/workflows/lib/event-trigger-service.ts +24 -11
- package/tsconfig.json +1 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customers/ai-tools/settings-pack.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `customers.get_settings` (Phase 1 WS-C, Step 3.9).\n *\n * Aggregates the four settings surfaces the spec calls out: pipelines,\n * pipeline stages, dictionaries, and address-format settings. All reads are\n * tenant + organization scoped through the existing encryption helpers.\n */\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerDictionaryEntry,\n CustomerPipeline,\n CustomerPipelineStage,\n CustomerSettings,\n} from '../data/entities'\nimport { assertTenantScope, type CustomersAiToolDefinition, type CustomersToolContext } from './types'\n\nfunction resolveEm(ctx: CustomersToolContext): EntityManager {\n return ctx.container.resolve<EntityManager>('em')\n}\n\nfunction buildScope(ctx: CustomersToolContext, tenantId: string) {\n return { tenantId, organizationId: ctx.organizationId }\n}\n\nconst getSettingsInput = z.object({}).passthrough()\n\nconst getSettingsTool: CustomersAiToolDefinition = {\n name: 'customers.get_settings',\n displayName: 'Get customers module settings',\n description:\n 'Return the customers module settings for the caller scope: pipelines, pipeline stages, dictionaries (grouped by kind), and address format.',\n inputSchema: getSettingsInput,\n requiredFeatures: ['customers.settings.manage'],\n tags: ['read', 'customers'],\n handler: async (_rawInput, ctx) => {\n const { tenantId } = assertTenantScope(ctx)\n const em = resolveEm(ctx)\n const where: Record<string, unknown> = { tenantId }\n if (ctx.organizationId) where.organizationId = ctx.organizationId\n const [pipelines, stages, dictionaryEntries, settings] = await Promise.all([\n findWithDecryption<CustomerPipeline>(\n em,\n CustomerPipeline,\n where as any,\n { orderBy: { createdAt: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n findWithDecryption<CustomerPipelineStage>(\n em,\n CustomerPipelineStage,\n where as any,\n { orderBy: { pipelineId: 'asc', order: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n findWithDecryption<CustomerDictionaryEntry>(\n em,\n CustomerDictionaryEntry,\n where as any,\n { orderBy: { kind: 'asc', label: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n ctx.organizationId\n ? findOneWithDecryption<CustomerSettings>(\n em,\n CustomerSettings,\n { tenantId, organizationId: ctx.organizationId } as any,\n undefined,\n buildScope(ctx, tenantId),\n )\n : null,\n ])\n const pipelineRows = pipelines.filter((row) => row.tenantId === tenantId)\n const stageRows = stages.filter((row) => row.tenantId === tenantId)\n const dictionaryRows = dictionaryEntries.filter((row) => row.tenantId === tenantId)\n const dictionaries: Record<string, Array<{\n id: string\n value: string\n label: string\n normalizedValue: string\n color: string | null\n icon: string | null\n }>> = {}\n for (const row of dictionaryRows) {\n const bucket = dictionaries[row.kind] ?? (dictionaries[row.kind] = [])\n bucket.push({\n id: row.id,\n value: row.value,\n label: row.label,\n normalizedValue: row.normalizedValue,\n color: row.color ?? null,\n icon: row.icon ?? null,\n })\n }\n return {\n pipelines: pipelineRows.map((row) => ({\n id: row.id,\n name: row.name,\n isDefault: !!row.isDefault,\n organizationId: row.organizationId ?? null,\n tenantId: row.tenantId ?? null,\n createdAt: row.createdAt ? new Date(row.createdAt).toISOString() : null,\n })),\n pipelineStages: stageRows.map((row) => ({\n id: row.id,\n pipelineId: row.pipelineId,\n label: row.label,\n order: row.order,\n organizationId: row.organizationId ?? null,\n tenantId: row.tenantId ?? null,\n })),\n dictionaries,\n addressFormat: settings?.addressFormat ?? 'line_first',\n }\n },\n}\n\nexport const settingsAiTools: CustomersAiToolDefinition[] = [getSettingsTool]\n\nexport default settingsAiTools\n"],
|
|
5
|
-
"mappings": "AAQA,SAAS,SAAS;AAClB,SAAS,uBAAuB,0BAA0B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAoF;AAE7F,SAAS,UAAU,KAA0C;AAC3D,SAAO,IAAI,UAAU,QAAuB,IAAI;AAClD;AAEA,SAAS,WAAW,KAA2B,UAAkB;AAC/D,SAAO,EAAE,UAAU,gBAAgB,IAAI,eAAe;AACxD;AAEA,MAAM,mBAAmB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAElD,MAAM,kBAA6C;AAAA,EACjD,MAAM;AAAA,EACN,aAAa;AAAA,EACb,aACE;AAAA,EACF,aAAa;AAAA,EACb,kBAAkB,CAAC,2BAA2B;AAAA,EAC9C,MAAM,CAAC,QAAQ,WAAW;AAAA,EAC1B,SAAS,OAAO,WAAW,QAAQ;AACjC,UAAM,EAAE,SAAS,IAAI,kBAAkB,GAAG;AAC1C,UAAM,KAAK,UAAU,GAAG;AACxB,UAAM,QAAiC,EAAE,SAAS;AAClD,QAAI,IAAI,eAAgB,OAAM,iBAAiB,IAAI;AACnD,UAAM,CAAC,WAAW,QAAQ,mBAAmB,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAAA,MACzE;AAAA,QACE;AAAA,QACA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IAAI,kBAAkB;AAAA,QACtC,UAAU,IAAI,YAAY;AAAA,QAC1B,WAAW,IAAI,YAAY,IAAI,KAAK,IAAI,SAAS,EAAE,YAAY,IAAI;AAAA,MACrE,EAAE;AAAA,MACF,gBAAgB,UAAU,IAAI,CAAC,SAAS;AAAA,QACtC,IAAI,IAAI;AAAA,QACR,YAAY,IAAI;AAAA,QAChB,OAAO,IAAI;AAAA,QACX,OAAO,IAAI;AAAA,QACX,gBAAgB,IAAI,kBAAkB;AAAA,QACtC,UAAU,IAAI,YAAY;AAAA,MAC5B,EAAE;AAAA,MACF;AAAA,MACA,eAAe,UAAU,iBAAiB;AAAA,IAC5C;AAAA,EACF;AACF;AAEO,MAAM,kBAA+C,CAAC,
|
|
4
|
+
"sourcesContent": ["/**\n * `customers.get_settings` (Phase 1 WS-C, Step 3.9).\n *\n * Aggregates the four settings surfaces the spec calls out: pipelines,\n * pipeline stages, dictionaries, and address-format settings. All reads are\n * tenant + organization scoped through the existing encryption helpers.\n */\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerDictionaryEntry,\n CustomerPipeline,\n CustomerPipelineStage,\n CustomerSettings,\n} from '../data/entities'\nimport { assertTenantScope, type CustomersAiToolDefinition, type CustomersToolContext } from './types'\n\nfunction resolveEm(ctx: CustomersToolContext): EntityManager {\n return ctx.container.resolve<EntityManager>('em')\n}\n\nfunction buildScope(ctx: CustomersToolContext, tenantId: string) {\n return { tenantId, organizationId: ctx.organizationId }\n}\n\nconst getSettingsInput = z.object({}).passthrough()\n\nconst listPipelineStagesInput = z.object({\n pipelineId: z.string().uuid().optional().describe('Optional pipeline id to restrict returned stages.'),\n}).passthrough()\n\nconst getSettingsTool: CustomersAiToolDefinition = {\n name: 'customers.get_settings',\n displayName: 'Get customers module settings',\n description:\n 'Return the customers module settings for the caller scope: pipelines, pipeline stages, dictionaries (grouped by kind), and address format.',\n inputSchema: getSettingsInput,\n requiredFeatures: ['customers.settings.manage'],\n tags: ['read', 'customers'],\n handler: async (_rawInput, ctx) => {\n const { tenantId } = assertTenantScope(ctx)\n const em = resolveEm(ctx)\n const where: Record<string, unknown> = { tenantId }\n if (ctx.organizationId) where.organizationId = ctx.organizationId\n const [pipelines, stages, dictionaryEntries, settings] = await Promise.all([\n findWithDecryption<CustomerPipeline>(\n em,\n CustomerPipeline,\n where as any,\n { orderBy: { createdAt: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n findWithDecryption<CustomerPipelineStage>(\n em,\n CustomerPipelineStage,\n where as any,\n { orderBy: { pipelineId: 'asc', order: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n findWithDecryption<CustomerDictionaryEntry>(\n em,\n CustomerDictionaryEntry,\n where as any,\n { orderBy: { kind: 'asc', label: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n ctx.organizationId\n ? findOneWithDecryption<CustomerSettings>(\n em,\n CustomerSettings,\n { tenantId, organizationId: ctx.organizationId } as any,\n undefined,\n buildScope(ctx, tenantId),\n )\n : null,\n ])\n const pipelineRows = pipelines.filter((row) => row.tenantId === tenantId)\n const stageRows = stages.filter((row) => row.tenantId === tenantId)\n const dictionaryRows = dictionaryEntries.filter((row) => row.tenantId === tenantId)\n const dictionaries: Record<string, Array<{\n id: string\n value: string\n label: string\n normalizedValue: string\n color: string | null\n icon: string | null\n }>> = {}\n for (const row of dictionaryRows) {\n const bucket = dictionaries[row.kind] ?? (dictionaries[row.kind] = [])\n bucket.push({\n id: row.id,\n value: row.value,\n label: row.label,\n normalizedValue: row.normalizedValue,\n color: row.color ?? null,\n icon: row.icon ?? null,\n })\n }\n return {\n pipelines: pipelineRows.map((row) => ({\n id: row.id,\n name: row.name,\n isDefault: !!row.isDefault,\n organizationId: row.organizationId ?? null,\n tenantId: row.tenantId ?? null,\n createdAt: row.createdAt ? new Date(row.createdAt).toISOString() : null,\n })),\n pipelineStages: stageRows.map((row) => ({\n id: row.id,\n pipelineId: row.pipelineId,\n label: row.label,\n order: row.order,\n organizationId: row.organizationId ?? null,\n tenantId: row.tenantId ?? null,\n })),\n dictionaries,\n addressFormat: settings?.addressFormat ?? 'line_first',\n }\n },\n}\n\nconst listPipelineStagesTool: CustomersAiToolDefinition = {\n name: 'customers.list_pipeline_stages',\n displayName: 'List customer pipeline stages',\n description:\n 'Return customer deal pipelines and their pipeline stages, including stage ids. Use this before moving a deal to a named pipeline stage.',\n inputSchema: listPipelineStagesInput,\n requiredFeatures: ['customers.pipelines.view'],\n tags: ['read', 'customers', 'pipelines'],\n isMutation: false,\n handler: async (rawInput, ctx) => {\n const { tenantId } = assertTenantScope(ctx)\n const input = listPipelineStagesInput.parse(rawInput)\n const em = resolveEm(ctx)\n const where: Record<string, unknown> = { tenantId }\n if (ctx.organizationId) where.organizationId = ctx.organizationId\n const stageWhere: Record<string, unknown> = { ...where }\n if (input.pipelineId) stageWhere.pipelineId = input.pipelineId\n const [pipelines, stages] = await Promise.all([\n findWithDecryption<CustomerPipeline>(\n em,\n CustomerPipeline,\n where as any,\n { orderBy: { createdAt: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n findWithDecryption<CustomerPipelineStage>(\n em,\n CustomerPipelineStage,\n stageWhere as any,\n { orderBy: { pipelineId: 'asc', order: 'asc' } as any } as any,\n buildScope(ctx, tenantId),\n ),\n ])\n return {\n pipelines: pipelines\n .filter((row) => row.tenantId === tenantId)\n .map((row) => ({\n id: row.id,\n name: row.name,\n isDefault: !!row.isDefault,\n organizationId: row.organizationId ?? null,\n tenantId: row.tenantId ?? null,\n })),\n pipelineStages: stages\n .filter((row) => row.tenantId === tenantId)\n .map((row) => ({\n id: row.id,\n pipelineId: row.pipelineId,\n label: row.label,\n order: row.order,\n organizationId: row.organizationId ?? null,\n tenantId: row.tenantId ?? null,\n })),\n }\n },\n}\n\nexport const settingsAiTools: CustomersAiToolDefinition[] = [getSettingsTool, listPipelineStages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A,QACtC,UAAU,IAAI,YAAY;AAAA,MAC5B,EAAE;AAAA,MACJ,gBAAgB,OACb,OAAO,CAAC,QAAQ,IAAI,aAAa,QAAQ,EACzC,IAAI,CAAC,SAAS;AAAA,QACb,IAAI,IAAI;AAAA,QACR,YAAY,IAAI;AAAA,QAChB,OAAO,IAAI;AAAA,QACX,OAAO,IAAI;AAAA,QACX,gBAAgB,IAAI,kBAAkB;AAAA,QACtC,UAAU,IAAI,YAAY;AAAA,MAC5B,EAAE;AAAA,IACN;AAAA,EACF;AACF;AAEO,MAAM,kBAA+C,CAAC,iBAAiB,sBAAsB;AAEpG,IAAO,wBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
|
-
import { format } from "date-fns";
|
|
3
2
|
const PARTICIPANT_COLORS = [
|
|
4
3
|
"bg-chart-emerald",
|
|
5
4
|
"bg-chart-blue",
|
|
@@ -14,10 +13,19 @@ const DEFAULT_REMINDER_MINUTES = {
|
|
|
14
13
|
task: 1440,
|
|
15
14
|
email: 15
|
|
16
15
|
};
|
|
16
|
+
function padDatePart(value) {
|
|
17
|
+
return String(value).padStart(2, "0");
|
|
18
|
+
}
|
|
19
|
+
function formatLocalDateInput(date) {
|
|
20
|
+
return `${date.getFullYear()}-${padDatePart(date.getMonth() + 1)}-${padDatePart(date.getDate())}`;
|
|
21
|
+
}
|
|
22
|
+
function formatLocalTimeInput(date) {
|
|
23
|
+
return `${padDatePart(date.getHours())}:${padDatePart(date.getMinutes())}`;
|
|
24
|
+
}
|
|
17
25
|
function useScheduleFormState({ open, editData }) {
|
|
18
26
|
const [activityType, setActivityType] = React.useState("meeting");
|
|
19
27
|
const [title, setTitle] = React.useState("");
|
|
20
|
-
const [date, setDate] = React.useState(() =>
|
|
28
|
+
const [date, setDate] = React.useState(() => formatLocalDateInput(/* @__PURE__ */ new Date()));
|
|
21
29
|
const [startTime, setStartTime] = React.useState("10:00");
|
|
22
30
|
const [duration, setDuration] = React.useState(30);
|
|
23
31
|
const [allDay, setAllDay] = React.useState(false);
|
|
@@ -47,8 +55,8 @@ function useScheduleFormState({ open, editData }) {
|
|
|
47
55
|
const seedDateValid = !Number.isNaN(seedDate.getTime());
|
|
48
56
|
const fallbackNow = /* @__PURE__ */ new Date();
|
|
49
57
|
const dateForForm = seedDateValid ? seedDate : fallbackNow;
|
|
50
|
-
setDate(
|
|
51
|
-
setStartTime(
|
|
58
|
+
setDate(formatLocalDateInput(dateForForm));
|
|
59
|
+
setStartTime(formatLocalTimeInput(dateForForm));
|
|
52
60
|
setDuration(editData.durationMinutes ?? 30);
|
|
53
61
|
setAllDay(editData.allDay ?? false);
|
|
54
62
|
setDescription(editData.body ?? "");
|
|
@@ -101,7 +109,7 @@ function useScheduleFormState({ open, editData }) {
|
|
|
101
109
|
} else {
|
|
102
110
|
setActivityType("meeting");
|
|
103
111
|
setTitle("");
|
|
104
|
-
setDate(
|
|
112
|
+
setDate(formatLocalDateInput(/* @__PURE__ */ new Date()));
|
|
105
113
|
setStartTime("10:00");
|
|
106
114
|
setDuration(30);
|
|
107
115
|
setAllDay(false);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/customers/components/detail/schedule/useScheduleFormState.ts"],
|
|
4
|
-
"sourcesContent": ["import * as React from 'react'\nimport { format } from 'date-fns'\nimport type { ActivityType } from './fieldConfig'\n\nexport type RsvpStatus = 'pending' | 'accepted' | 'declined' | 'tentative'\n\nexport type Participant = {\n userId: string\n name: string\n email?: string\n color?: string\n status?: RsvpStatus\n}\n\nexport type LinkedEntity = {\n id: string\n type: 'company' | 'deal' | 'offer'\n label: string\n}\n\nexport type ScheduleActivityEditData = {\n id: string\n interactionType?: string\n title?: string | null\n body?: string | null\n scheduledAt?: string | null\n /**\n * Historical timestamp for completed activities (status `done`). Required for\n * the edit prefill to restore the original date/time instead of falling back\n * to \"today\" (#1807).\n */\n occurredAt?: string | null\n durationMinutes?: number | null\n location?: string | null\n allDay?: boolean | null\n recurrenceRule?: string | null\n recurrenceEnd?: string | null\n participants?: Array<{ userId: string; name?: string; email?: string; status?: string }> | null\n reminderMinutes?: number | null\n visibility?: string | null\n linkedEntities?: Array<{ id: string; type: string; label: string }> | null\n guestPermissions?: { canInviteOthers?: boolean; canModify?: boolean; canSeeList?: boolean } | null\n}\n\nexport const PARTICIPANT_COLORS = [\n 'bg-chart-emerald',\n 'bg-chart-blue',\n 'bg-chart-orange',\n 'bg-chart-violet',\n 'bg-chart-pink',\n 'bg-chart-teal',\n]\n\n// Per-Figma defaults for the Reminder dropdown when the user picks an activity\n// type. Meeting/email keep the standard 15 min; tasks default to 1 day (1440 min)\n// because they're plan-ahead artefacts; calls default to 5 min as a stand-in for\n// the Figma \"After call ends\" treatment (which would need a non-numeric sentinel\n// in the API contract \u2014 tracked as a follow-up).\nconst DEFAULT_REMINDER_MINUTES: Record<ActivityType, number> = {\n meeting: 15,\n call: 5,\n task: 1440,\n email: 15,\n}\n\ninterface UseScheduleFormStateParams {\n open: boolean\n editData: ScheduleActivityEditData | null | undefined\n}\n\nexport function useScheduleFormState({ open, editData }: UseScheduleFormStateParams) {\n const [activityType, setActivityType] = React.useState<ActivityType>('meeting')\n const [title, setTitle] = React.useState('')\n const [date, setDate] = React.useState(() => format(new Date(), 'yyyy-MM-dd'))\n const [startTime, setStartTime] = React.useState('10:00')\n const [duration, setDuration] = React.useState(30)\n const [allDay, setAllDay] = React.useState(false)\n const [description, setDescription] = React.useState('')\n const [markdownEnabled, setMarkdownEnabled] = React.useState(true)\n const [location, setLocation] = React.useState('')\n const [reminderMinutes, setReminderMinutes] = React.useState(15)\n const [visibility, setVisibility] = React.useState('team')\n const [participants, setParticipants] = React.useState<Participant[]>([])\n const [linkedEntities, setLinkedEntities] = React.useState<LinkedEntity[]>([])\n const [recurrenceEnabled, setRecurrenceEnabled] = React.useState(false)\n const [recurrenceDays, setRecurrenceDays] = React.useState<boolean[]>([true, false, true, false, false, false, false])\n const [recurrenceEndType, setRecurrenceEndType] = React.useState<'never' | 'count' | 'date'>('never')\n const [recurrenceCount, setRecurrenceCount] = React.useState(8)\n const [recurrenceEndDate, setRecurrenceEndDate] = React.useState('')\n const [conflict, setConflict] = React.useState<string | null>(null)\n const [saving, setSaving] = React.useState(false)\n const [guestPermissions, setGuestPermissions] = React.useState({ canInviteOthers: true, canModify: false, canSeeList: true })\n\n React.useEffect(() => {\n if (open) {\n if (editData) {\n // Edit mode: populate from existing interaction\n const resolvedType = (editData.interactionType as ActivityType) ?? 'meeting'\n setActivityType(resolvedType)\n setTitle(editData.title ?? '')\n // For historical activities the canonical timestamp is `occurredAt`; for\n // planned/future ones it's `scheduledAt`. Without this fallback editing a\n // past activity prefilled to \"today\" instead of its actual moment (#1807).\n // Use `date-fns` `format(...)` so the seed values are in the user's local\n // timezone (matches the cluster-E local-day convention).\n const sourceTimestamp = editData.occurredAt ?? editData.scheduledAt ?? null\n const seedDate = sourceTimestamp ? new Date(sourceTimestamp) : new Date()\n const seedDateValid = !Number.isNaN(seedDate.getTime())\n const fallbackNow = new Date()\n const dateForForm = seedDateValid ? seedDate : fallbackNow\n setDate(format(dateForForm, 'yyyy-MM-dd'))\n setStartTime(format(dateForForm, 'HH:mm'))\n setDuration(editData.durationMinutes ?? 30)\n setAllDay(editData.allDay ?? false)\n setDescription(editData.body ?? '')\n setLocation(editData.location ?? '')\n // Use per-type default when the editData omits an explicit reminder\n // (the menu-driven \"New X\" flow opens the dialog with `reminderMinutes: null`).\n setReminderMinutes(editData.reminderMinutes ?? DEFAULT_REMINDER_MINUTES[resolvedType])\n setVisibility(editData.visibility ?? 'team')\n setParticipants(\n Array.isArray(editData.participants)\n ? editData.participants.map((p, i) => ({\n userId: p.userId,\n name: p.name ?? p.userId,\n email: p.email,\n color: PARTICIPANT_COLORS[i % PARTICIPANT_COLORS.length],\n status: (p.status ?? 'pending') as RsvpStatus,\n }))\n : [],\n )\n setLinkedEntities(\n Array.isArray(editData.linkedEntities)\n ? editData.linkedEntities.map((e) => ({ id: e.id, type: e.type as LinkedEntity['type'], label: e.label }))\n : [],\n )\n if (editData.recurrenceRule) {\n setRecurrenceEnabled(true)\n // Parse RRULE to set days and end type\n const rule = editData.recurrenceRule\n const byDayMatch = rule.match(/BYDAY=([A-Z,]+)/)\n if (byDayMatch) {\n const dayNames = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']\n const activeDays = byDayMatch[1].split(',')\n setRecurrenceDays(dayNames.map((d) => activeDays.includes(d)))\n }\n const countMatch = rule.match(/COUNT=(\\d+)/)\n const untilMatch = rule.match(/UNTIL=(\\d{8})/)\n if (countMatch) {\n setRecurrenceEndType('count')\n setRecurrenceCount(Number(countMatch[1]))\n } else if (untilMatch) {\n setRecurrenceEndType('date')\n const raw = untilMatch[1]\n setRecurrenceEndDate(`${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`)\n } else {\n setRecurrenceEndType('never')\n }\n } else {\n setRecurrenceEnabled(false)\n }\n if (editData.guestPermissions) {\n setGuestPermissions({\n canInviteOthers: editData.guestPermissions.canInviteOthers ?? true,\n canModify: editData.guestPermissions.canModify ?? false,\n canSeeList: editData.guestPermissions.canSeeList ?? true,\n })\n }\n } else {\n // Create mode: reset all fields\n setActivityType('meeting')\n setTitle('')\n setDate(format(new Date(), 'yyyy-MM-dd'))\n setStartTime('10:00')\n setDuration(30)\n setAllDay(false)\n setDescription('')\n setLocation('')\n setReminderMinutes(DEFAULT_REMINDER_MINUTES.meeting)\n setVisibility('team')\n setParticipants([])\n setLinkedEntities([])\n setRecurrenceEnabled(false)\n }\n setConflict(null)\n }\n return () => {\n // Safety net: restore body scroll if Radix Dialog fails to clean up\n document.body.style.removeProperty('overflow')\n document.body.style.removeProperty('pointer-events')\n }\n }, [open, editData])\n\n // Update the Reminder default when the activity type changes in create mode.\n // Skipped in edit mode (the persisted value wins), and gated by `open` to\n // avoid flipping the default in a closed-but-mounted dialog.\n const lastReminderTypeRef = React.useRef<ActivityType>('meeting')\n React.useEffect(() => {\n if (!open || editData) {\n lastReminderTypeRef.current = activityType\n return\n }\n if (lastReminderTypeRef.current === activityType) return\n lastReminderTypeRef.current = activityType\n setReminderMinutes(DEFAULT_REMINDER_MINUTES[activityType])\n }, [activityType, editData, open])\n\n const removeParticipant = React.useCallback((userId: string) => {\n setParticipants((prev) => prev.filter((p) => p.userId !== userId))\n }, [])\n\n const toggleRecurrenceDay = React.useCallback((index: number) => {\n setRecurrenceDays((prev) => {\n const next = [...prev]\n next[index] = !next[index]\n return next\n })\n }, [])\n\n return {\n activityType,\n setActivityType,\n title,\n setTitle,\n date,\n setDate,\n startTime,\n setStartTime,\n duration,\n setDuration,\n allDay,\n setAllDay,\n description,\n setDescription,\n markdownEnabled,\n setMarkdownEnabled,\n location,\n setLocation,\n reminderMinutes,\n setReminderMinutes,\n visibility,\n setVisibility,\n participants,\n setParticipants,\n linkedEntities,\n setLinkedEntities,\n recurrenceEnabled,\n setRecurrenceEnabled,\n recurrenceDays,\n setRecurrenceDays,\n recurrenceEndType,\n setRecurrenceEndType,\n recurrenceCount,\n setRecurrenceCount,\n recurrenceEndDate,\n setRecurrenceEndDate,\n conflict,\n setConflict,\n saving,\n setSaving,\n guestPermissions,\n setGuestPermissions,\n removeParticipant,\n toggleRecurrenceDay,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,WAAW;
|
|
4
|
+
"sourcesContent": ["import * as React from 'react'\nimport type { ActivityType } from './fieldConfig'\n\nexport type RsvpStatus = 'pending' | 'accepted' | 'declined' | 'tentative'\n\nexport type Participant = {\n userId: string\n name: string\n email?: string\n color?: string\n status?: RsvpStatus\n}\n\nexport type LinkedEntity = {\n id: string\n type: 'company' | 'deal' | 'offer'\n label: string\n}\n\nexport type ScheduleActivityEditData = {\n id: string\n interactionType?: string\n title?: string | null\n body?: string | null\n scheduledAt?: string | null\n /**\n * Historical timestamp for completed activities (status `done`). Required for\n * the edit prefill to restore the original date/time instead of falling back\n * to \"today\" (#1807).\n */\n occurredAt?: string | null\n durationMinutes?: number | null\n location?: string | null\n allDay?: boolean | null\n recurrenceRule?: string | null\n recurrenceEnd?: string | null\n participants?: Array<{ userId: string; name?: string; email?: string; status?: string }> | null\n reminderMinutes?: number | null\n visibility?: string | null\n linkedEntities?: Array<{ id: string; type: string; label: string }> | null\n guestPermissions?: { canInviteOthers?: boolean; canModify?: boolean; canSeeList?: boolean } | null\n}\n\nexport const PARTICIPANT_COLORS = [\n 'bg-chart-emerald',\n 'bg-chart-blue',\n 'bg-chart-orange',\n 'bg-chart-violet',\n 'bg-chart-pink',\n 'bg-chart-teal',\n]\n\n// Per-Figma defaults for the Reminder dropdown when the user picks an activity\n// type. Meeting/email keep the standard 15 min; tasks default to 1 day (1440 min)\n// because they're plan-ahead artefacts; calls default to 5 min as a stand-in for\n// the Figma \"After call ends\" treatment (which would need a non-numeric sentinel\n// in the API contract \u2014 tracked as a follow-up).\nconst DEFAULT_REMINDER_MINUTES: Record<ActivityType, number> = {\n meeting: 15,\n call: 5,\n task: 1440,\n email: 15,\n}\n\nfunction padDatePart(value: number): string {\n return String(value).padStart(2, '0')\n}\n\nfunction formatLocalDateInput(date: Date): string {\n return `${date.getFullYear()}-${padDatePart(date.getMonth() + 1)}-${padDatePart(date.getDate())}`\n}\n\nfunction formatLocalTimeInput(date: Date): string {\n return `${padDatePart(date.getHours())}:${padDatePart(date.getMinutes())}`\n}\n\ninterface UseScheduleFormStateParams {\n open: boolean\n editData: ScheduleActivityEditData | null | undefined\n}\n\nexport function useScheduleFormState({ open, editData }: UseScheduleFormStateParams) {\n const [activityType, setActivityType] = React.useState<ActivityType>('meeting')\n const [title, setTitle] = React.useState('')\n const [date, setDate] = React.useState(() => formatLocalDateInput(new Date()))\n const [startTime, setStartTime] = React.useState('10:00')\n const [duration, setDuration] = React.useState(30)\n const [allDay, setAllDay] = React.useState(false)\n const [description, setDescription] = React.useState('')\n const [markdownEnabled, setMarkdownEnabled] = React.useState(true)\n const [location, setLocation] = React.useState('')\n const [reminderMinutes, setReminderMinutes] = React.useState(15)\n const [visibility, setVisibility] = React.useState('team')\n const [participants, setParticipants] = React.useState<Participant[]>([])\n const [linkedEntities, setLinkedEntities] = React.useState<LinkedEntity[]>([])\n const [recurrenceEnabled, setRecurrenceEnabled] = React.useState(false)\n const [recurrenceDays, setRecurrenceDays] = React.useState<boolean[]>([true, false, true, false, false, false, false])\n const [recurrenceEndType, setRecurrenceEndType] = React.useState<'never' | 'count' | 'date'>('never')\n const [recurrenceCount, setRecurrenceCount] = React.useState(8)\n const [recurrenceEndDate, setRecurrenceEndDate] = React.useState('')\n const [conflict, setConflict] = React.useState<string | null>(null)\n const [saving, setSaving] = React.useState(false)\n const [guestPermissions, setGuestPermissions] = React.useState({ canInviteOthers: true, canModify: false, canSeeList: true })\n\n React.useEffect(() => {\n if (open) {\n if (editData) {\n // Edit mode: populate from existing interaction\n const resolvedType = (editData.interactionType as ActivityType) ?? 'meeting'\n setActivityType(resolvedType)\n setTitle(editData.title ?? '')\n // For historical activities the canonical timestamp is `occurredAt`; for\n // planned/future ones it's `scheduledAt`. Without this fallback editing a\n // past activity prefilled to \"today\" instead of its actual moment (#1807).\n // Keep seed values in the user's local timezone, matching the cluster-E\n // local-day convention.\n const sourceTimestamp = editData.occurredAt ?? editData.scheduledAt ?? null\n const seedDate = sourceTimestamp ? new Date(sourceTimestamp) : new Date()\n const seedDateValid = !Number.isNaN(seedDate.getTime())\n const fallbackNow = new Date()\n const dateForForm = seedDateValid ? seedDate : fallbackNow\n setDate(formatLocalDateInput(dateForForm))\n setStartTime(formatLocalTimeInput(dateForForm))\n setDuration(editData.durationMinutes ?? 30)\n setAllDay(editData.allDay ?? false)\n setDescription(editData.body ?? '')\n setLocation(editData.location ?? '')\n // Use per-type default when the editData omits an explicit reminder\n // (the menu-driven \"New X\" flow opens the dialog with `reminderMinutes: null`).\n setReminderMinutes(editData.reminderMinutes ?? DEFAULT_REMINDER_MINUTES[resolvedType])\n setVisibility(editData.visibility ?? 'team')\n setParticipants(\n Array.isArray(editData.participants)\n ? editData.participants.map((p, i) => ({\n userId: p.userId,\n name: p.name ?? p.userId,\n email: p.email,\n color: PARTICIPANT_COLORS[i % PARTICIPANT_COLORS.length],\n status: (p.status ?? 'pending') as RsvpStatus,\n }))\n : [],\n )\n setLinkedEntities(\n Array.isArray(editData.linkedEntities)\n ? editData.linkedEntities.map((e) => ({ id: e.id, type: e.type as LinkedEntity['type'], label: e.label }))\n : [],\n )\n if (editData.recurrenceRule) {\n setRecurrenceEnabled(true)\n // Parse RRULE to set days and end type\n const rule = editData.recurrenceRule\n const byDayMatch = rule.match(/BYDAY=([A-Z,]+)/)\n if (byDayMatch) {\n const dayNames = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']\n const activeDays = byDayMatch[1].split(',')\n setRecurrenceDays(dayNames.map((d) => activeDays.includes(d)))\n }\n const countMatch = rule.match(/COUNT=(\\d+)/)\n const untilMatch = rule.match(/UNTIL=(\\d{8})/)\n if (countMatch) {\n setRecurrenceEndType('count')\n setRecurrenceCount(Number(countMatch[1]))\n } else if (untilMatch) {\n setRecurrenceEndType('date')\n const raw = untilMatch[1]\n setRecurrenceEndDate(`${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`)\n } else {\n setRecurrenceEndType('never')\n }\n } else {\n setRecurrenceEnabled(false)\n }\n if (editData.guestPermissions) {\n setGuestPermissions({\n canInviteOthers: editData.guestPermissions.canInviteOthers ?? true,\n canModify: editData.guestPermissions.canModify ?? false,\n canSeeList: editData.guestPermissions.canSeeList ?? true,\n })\n }\n } else {\n // Create mode: reset all fields\n setActivityType('meeting')\n setTitle('')\n setDate(formatLocalDateInput(new Date()))\n setStartTime('10:00')\n setDuration(30)\n setAllDay(false)\n setDescription('')\n setLocation('')\n setReminderMinutes(DEFAULT_REMINDER_MINUTES.meeting)\n setVisibility('team')\n setParticipants([])\n setLinkedEntities([])\n setRecurrenceEnabled(false)\n }\n setConflict(null)\n }\n return () => {\n // Safety net: restore body scroll if Radix Dialog fails to clean up\n document.body.style.removeProperty('overflow')\n document.body.style.removeProperty('pointer-events')\n }\n }, [open, editData])\n\n // Update the Reminder default when the activity type changes in create mode.\n // Skipped in edit mode (the persisted value wins), and gated by `open` to\n // avoid flipping the default in a closed-but-mounted dialog.\n const lastReminderTypeRef = React.useRef<ActivityType>('meeting')\n React.useEffect(() => {\n if (!open || editData) {\n lastReminderTypeRef.current = activityType\n return\n }\n if (lastReminderTypeRef.current === activityType) return\n lastReminderTypeRef.current = activityType\n setReminderMinutes(DEFAULT_REMINDER_MINUTES[activityType])\n }, [activityType, editData, open])\n\n const removeParticipant = React.useCallback((userId: string) => {\n setParticipants((prev) => prev.filter((p) => p.userId !== userId))\n }, [])\n\n const toggleRecurrenceDay = React.useCallback((index: number) => {\n setRecurrenceDays((prev) => {\n const next = [...prev]\n next[index] = !next[index]\n return next\n })\n }, [])\n\n return {\n activityType,\n setActivityType,\n title,\n setTitle,\n date,\n setDate,\n startTime,\n setStartTime,\n duration,\n setDuration,\n allDay,\n setAllDay,\n description,\n setDescription,\n markdownEnabled,\n setMarkdownEnabled,\n location,\n setLocation,\n reminderMinutes,\n setReminderMinutes,\n visibility,\n setVisibility,\n participants,\n setParticipants,\n linkedEntities,\n setLinkedEntities,\n recurrenceEnabled,\n setRecurrenceEnabled,\n recurrenceDays,\n setRecurrenceDays,\n recurrenceEndType,\n setRecurrenceEndType,\n recurrenceCount,\n setRecurrenceCount,\n recurrenceEndDate,\n setRecurrenceEndDate,\n conflict,\n setConflict,\n saving,\n setSaving,\n guestPermissions,\n setGuestPermissions,\n removeParticipant,\n toggleRecurrenceDay,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,WAAW;AA2ChB,MAAM,qBAAqB;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;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AAC,SAAS;AAC1B,YAAM,OAAO,CAAC,GAAG,IAAI;AACrB,WAAK,KAAK,IAAI,CAAC,KAAK,KAAK;AACzB,aAAO;AAAA,IACT,CAAC;AAAA,EACH,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,35 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
const PERSON_COMPANY_LINKS_DELETED_AT_COLUMN = "deleted_at";
|
|
4
|
-
let supportsDeletedAtColumnPromise = null;
|
|
5
|
-
let warnedAboutMissingDeletedAtColumn = false;
|
|
6
|
-
async function customerPersonCompanyLinksSupportDeletedAt(em) {
|
|
7
|
-
if (typeof em.getKysely !== "function") {
|
|
8
|
-
return true;
|
|
9
|
-
}
|
|
10
|
-
if (!supportsDeletedAtColumnPromise) {
|
|
11
|
-
const db = em.getKysely();
|
|
12
|
-
const probe = db.selectFrom("information_schema.columns").select(["column_name"]).where(sql`table_schema = current_schema()`).where("table_name", "=", PERSON_COMPANY_LINKS_TABLE).where("column_name", "=", PERSON_COMPANY_LINKS_DELETED_AT_COLUMN).executeTakeFirst().then((row) => !!row).catch(() => false);
|
|
13
|
-
supportsDeletedAtColumnPromise = probe;
|
|
14
|
-
return probe;
|
|
15
|
-
}
|
|
16
|
-
return supportsDeletedAtColumnPromise;
|
|
1
|
+
async function customerPersonCompanyLinksSupportDeletedAt(_em) {
|
|
2
|
+
return true;
|
|
17
3
|
}
|
|
18
|
-
function warnMissingCustomerPersonCompanyLinksDeletedAt(
|
|
19
|
-
if (warnedAboutMissingDeletedAtColumn) {
|
|
20
|
-
return;
|
|
21
|
-
}
|
|
22
|
-
warnedAboutMissingDeletedAtColumn = true;
|
|
23
|
-
console.warn(
|
|
24
|
-
`[${source}] missing ${PERSON_COMPANY_LINKS_TABLE}.${PERSON_COMPANY_LINKS_DELETED_AT_COLUMN}; continuing without link soft-delete filtering. Run yarn db:migrate.`
|
|
25
|
-
);
|
|
4
|
+
function warnMissingCustomerPersonCompanyLinksDeletedAt(_source) {
|
|
26
5
|
}
|
|
27
|
-
async function withActiveCustomerPersonCompanyLinkFilter(
|
|
28
|
-
const supportsDeletedAt = await customerPersonCompanyLinksSupportDeletedAt(em);
|
|
29
|
-
if (!supportsDeletedAt) {
|
|
30
|
-
warnMissingCustomerPersonCompanyLinksDeletedAt(source);
|
|
31
|
-
return { ...where };
|
|
32
|
-
}
|
|
6
|
+
async function withActiveCustomerPersonCompanyLinkFilter(_em, where, _source) {
|
|
33
7
|
return { ...where, deletedAt: null };
|
|
34
8
|
}
|
|
35
9
|
function filterActivePersonCompanyLinks(links) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customers/lib/personCompanyLinkTable.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\n\n// The previous implementation probed `information_schema.columns` on every\n// first call via `em.getKysely()` to decide whether to add a `deletedAt: null`\n// filter. When that probe ran inside an already-active MikroORM transaction it\n// shared the transaction's connection \u2014 and any failure (including transient\n// connection-pool state, an aborted TX from a sibling query, or pg returning\n// 25P02) propagated back into the host transaction, poisoning every following\n// query with `current transaction is aborted, commands ignored until end of\n// transaction block`. That is what produced the standalone-CI failure burst\n// (loadPersonCompanyLinks \u2192 25P02 \u2192 customers.people.create \u2192 500) and the\n// sync_excel worker `failedCount: 1` regression.\n//\n// The `deleted_at` column on `customer_person_company_links` has been part of\n// the committed module snapshot since `Migration20260415095203` (April 2026)\n// and is referenced by `Migration20260417140000` (partial unique index uses\n// `where deleted_at is null`). Any environment running these migrations\n// already has the column. So the probe is no longer load-bearing \u2014 it only\n// adds risk. We now unconditionally include `deletedAt: null` in the filter.\n// If a downstream DB is genuinely un-migrated, the underlying `em.find` will\n// surface the authentic `column \"deleted_at\" of relation\n// \"customer_person_company_links\" does not exist` (pg 42703) pointing the\n// operator at the real fix (`yarn db:migrate`).\n//\n// `customerPersonCompanyLinksSupportDeletedAt` and\n// `warnMissingCustomerPersonCompanyLinksDeletedAt` are kept as exported\n// no-op-equivalents so external callers (and the published @open-mercato/core\n// API surface) don't break.\n\nexport async function customerPersonCompanyLinksSupportDeletedAt(_em: EntityManager): Promise<boolean> {\n return true\n}\n\nexport function warnMissingCustomerPersonCompanyLinksDeletedAt(_source: string): void {\n // No-op: column is guaranteed present by Migration20260415095203 and the\n // module snapshot. Kept for backward-compatible exports.\n}\n\nexport async function withActiveCustomerPersonCompanyLinkFilter<T extends Record<string, unknown>>(\n _em: EntityManager,\n where: T,\n _source: string,\n): Promise<T & { deletedAt?: null }> {\n return { ...where, deletedAt: null }\n}\n\n/**\n * Drop soft-deleted link rows from a result set as a defense-in-depth fallback.\n * MikroORM has historically dropped `deletedAt: null` from the WHERE clause for\n * nullable date columns under certain configurations, so callers SHOULD apply this\n * after `findWithDecryption(...)` until the upstream query filter is verified to\n * fully cover all callers.\n */\nexport function filterActivePersonCompanyLinks<T extends { deletedAt?: Date | string | null | undefined }>(\n links: T[] | null | undefined,\n): T[] {\n if (!Array.isArray(links)) return []\n return links.filter((entry) => entry?.deletedAt == null)\n}\n"],
|
|
5
|
+
"mappings": "AA6BA,eAAsB,2CAA2C,KAAsC;AACrG,SAAO;AACT;AAEO,SAAS,+CAA+C,SAAuB;AAGtF;AAEA,eAAsB,0CACpB,KACA,OACA,SACmC;AACnC,SAAO,EAAE,GAAG,OAAO,WAAW,KAAK;AACrC;AASO,SAAS,+BACd,OACK;AACL,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACnC,SAAO,MAAM,OAAO,CAAC,UAAU,OAAO,aAAa,IAAI;AACzD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Migration } from "@mikro-orm/migrations";
|
|
2
|
+
class Migration20260521175027 extends Migration {
|
|
3
|
+
async up() {
|
|
4
|
+
this.addSql(`alter table "customer_person_company_links" add column if not exists "deleted_at" timestamptz null;`);
|
|
5
|
+
}
|
|
6
|
+
async down() {
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export {
|
|
10
|
+
Migration20260521175027
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=Migration20260521175027.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/customers/migrations/Migration20260521175027.ts"],
|
|
4
|
+
"sourcesContent": ["import { Migration } from '@mikro-orm/migrations';\n\n/**\n * Idempotent backstop for `customer_person_company_links.deleted_at`.\n *\n * The column was originally added by `Migration20260415095203` and is\n * referenced by `Migration20260417140000`'s partial unique index\n * (`where \"deleted_at\" is null`). It is part of the committed\n * `migrations/.snapshot-open-mercato.json`.\n *\n * However, the runtime defensive probe that lived in\n * `packages/core/src/modules/customers/lib/personCompanyLinkTable.ts`\n * historically existed because an aborted-transaction state on a\n * shared connection could (very rarely) make `loadPersonCompanyLinks`\n * fail in a way that *looked* like the column was missing \u2014 and the\n * cached fallback then silently dropped the `deletedAt: null` filter.\n * That probe is removed in the same change as this migration (no\n * Kysely query is ever issued from inside an active MikroORM TX);\n * this migration is the matching belt-and-suspenders guarantee that\n * the column is physically present so the unconditional `deletedAt:\n * null` filter cannot 42703.\n *\n * Postgres-native `add column if not exists` is used so this re-applies\n * cleanly on already-migrated databases without raising.\n */\nexport class Migration20260521175027 extends Migration {\n\n override async up(): Promise<void> {\n this.addSql(`alter table \"customer_person_company_links\" add column if not exists \"deleted_at\" timestamptz null;`);\n }\n\n override async down(): Promise<void> {\n // No-op on the way down: dropping the column would break\n // `Migration20260417140000`'s partial unique index, which is the\n // authoritative owner of the column going forward. The original\n // `Migration20260415095203` down still drops it for full rollback.\n }\n\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAyBnB,MAAM,gCAAgC,UAAU;AAAA,EAErD,MAAe,KAAoB;AACjC,SAAK,OAAO,qGAAqG;AAAA,EACnH;AAAA,EAEA,MAAe,OAAsB;AAAA,EAKrC;AAEF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -38,7 +38,7 @@ const WidgetVisibilityEditor = React.forwardRef(function WidgetVisibilityEditor2
|
|
|
38
38
|
(widget) => resolveWidgetText(t, widget.id, "description", widget.description || ""),
|
|
39
39
|
[t]
|
|
40
40
|
);
|
|
41
|
-
const { kind, targetId, tenantId, organizationId } = props;
|
|
41
|
+
const { kind, targetId, tenantId, organizationId, preserveOnTenantChange = false } = props;
|
|
42
42
|
const [catalog, setCatalog] = React.useState([]);
|
|
43
43
|
const [loading, setLoading] = React.useState(true);
|
|
44
44
|
const [saving, setSaving] = React.useState(false);
|
|
@@ -74,10 +74,19 @@ const WidgetVisibilityEditor = React.forwardRef(function WidgetVisibilityEditor2
|
|
|
74
74
|
}).filter((item) => item !== null);
|
|
75
75
|
setCatalog(mapped);
|
|
76
76
|
}, []);
|
|
77
|
-
const
|
|
77
|
+
const tenantIdRef = React.useRef(tenantId);
|
|
78
|
+
React.useEffect(() => {
|
|
79
|
+
tenantIdRef.current = tenantId;
|
|
80
|
+
}, [tenantId]);
|
|
81
|
+
const organizationIdRef = React.useRef(organizationId);
|
|
82
|
+
React.useEffect(() => {
|
|
83
|
+
organizationIdRef.current = organizationId;
|
|
84
|
+
}, [organizationId]);
|
|
85
|
+
const hasMountedRef = React.useRef(false);
|
|
86
|
+
const loadRoleData = React.useCallback(async (forTenantId, forOrganizationId) => {
|
|
78
87
|
const params = new URLSearchParams({ roleId: targetId });
|
|
79
|
-
if (
|
|
80
|
-
if (
|
|
88
|
+
if (forTenantId) params.set("tenantId", forTenantId);
|
|
89
|
+
if (forOrganizationId) params.set("organizationId", forOrganizationId);
|
|
81
90
|
const data = await readApiResultOrThrow(
|
|
82
91
|
`/api/dashboards/roles/widgets?${params.toString()}`,
|
|
83
92
|
void 0,
|
|
@@ -89,11 +98,11 @@ const WidgetVisibilityEditor = React.forwardRef(function WidgetVisibilityEditor2
|
|
|
89
98
|
setMode("override");
|
|
90
99
|
setOriginalMode("override");
|
|
91
100
|
setEffective(ids);
|
|
92
|
-
}, [
|
|
93
|
-
const loadUserData = React.useCallback(async () => {
|
|
101
|
+
}, [targetId]);
|
|
102
|
+
const loadUserData = React.useCallback(async (forTenantId, forOrganizationId) => {
|
|
94
103
|
const params = new URLSearchParams({ userId: targetId });
|
|
95
|
-
if (
|
|
96
|
-
if (
|
|
104
|
+
if (forTenantId) params.set("tenantId", forTenantId);
|
|
105
|
+
if (forOrganizationId) params.set("organizationId", forOrganizationId);
|
|
97
106
|
const data = await readApiResultOrThrow(
|
|
98
107
|
`/api/dashboards/users/widgets?${params.toString()}`,
|
|
99
108
|
void 0,
|
|
@@ -105,7 +114,7 @@ const WidgetVisibilityEditor = React.forwardRef(function WidgetVisibilityEditor2
|
|
|
105
114
|
setMode(data.mode || "inherit");
|
|
106
115
|
setOriginalMode(data.mode || "inherit");
|
|
107
116
|
setEffective(Array.isArray(data.effectiveWidgetIds) ? data.effectiveWidgetIds : []);
|
|
108
|
-
}, [
|
|
117
|
+
}, [targetId]);
|
|
109
118
|
React.useEffect(() => {
|
|
110
119
|
let cancelled = false;
|
|
111
120
|
async function load() {
|
|
@@ -113,15 +122,18 @@ const WidgetVisibilityEditor = React.forwardRef(function WidgetVisibilityEditor2
|
|
|
113
122
|
setError(null);
|
|
114
123
|
try {
|
|
115
124
|
await loadCatalog();
|
|
116
|
-
if (kind === "role") await loadRoleData();
|
|
117
|
-
else await loadUserData();
|
|
125
|
+
if (kind === "role") await loadRoleData(tenantIdRef.current, organizationIdRef.current);
|
|
126
|
+
else await loadUserData(tenantIdRef.current, organizationIdRef.current);
|
|
118
127
|
} catch (err) {
|
|
119
128
|
console.error("Failed to load widget visibility data", err);
|
|
120
129
|
if (!cancelled) {
|
|
121
130
|
setError(tRef.current("dashboards.widgets.error.load", "Unable to load widget configuration."));
|
|
122
131
|
}
|
|
123
132
|
} finally {
|
|
124
|
-
if (!cancelled)
|
|
133
|
+
if (!cancelled) {
|
|
134
|
+
setLoading(false);
|
|
135
|
+
hasMountedRef.current = true;
|
|
136
|
+
}
|
|
125
137
|
}
|
|
126
138
|
}
|
|
127
139
|
load();
|
|
@@ -129,6 +141,23 @@ const WidgetVisibilityEditor = React.forwardRef(function WidgetVisibilityEditor2
|
|
|
129
141
|
cancelled = true;
|
|
130
142
|
};
|
|
131
143
|
}, [kind, loadCatalog, loadRoleData, loadUserData]);
|
|
144
|
+
React.useEffect(() => {
|
|
145
|
+
if (!hasMountedRef.current) return;
|
|
146
|
+
if (preserveOnTenantChange) return;
|
|
147
|
+
let cancelled = false;
|
|
148
|
+
async function refetch() {
|
|
149
|
+
try {
|
|
150
|
+
if (kind === "role") await loadRoleData(tenantId, organizationId);
|
|
151
|
+
else await loadUserData(tenantId, organizationId);
|
|
152
|
+
} catch (err) {
|
|
153
|
+
console.error("Failed to reload widget visibility data", err);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
refetch();
|
|
157
|
+
return () => {
|
|
158
|
+
cancelled = true;
|
|
159
|
+
};
|
|
160
|
+
}, [tenantId, organizationId, kind, loadRoleData, loadUserData, preserveOnTenantChange]);
|
|
132
161
|
const toggle = React.useCallback((id) => {
|
|
133
162
|
setSelected((prev) => prev.includes(id) ? prev.filter((value) => value !== id) : [...prev, id]);
|
|
134
163
|
}, []);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/dashboards/components/WidgetVisibilityEditor.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { RadioGroup } from '@open-mercato/ui/primitives/radio'\nimport { RadioField } from '@open-mercato/ui/primitives/radio-field'\nimport { apiCallOrThrow, readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\n\ntype WidgetCatalogItem = {\n id: string\n title: string\n description: string | null\n}\n\ntype RoleResponse = {\n widgetIds: string[]\n hasCustom: boolean\n scope: { tenantId: string | null; organizationId: string | null }\n}\n\ntype UserResponse = {\n mode: 'inherit' | 'override'\n widgetIds: string[]\n hasCustom: boolean\n effectiveWidgetIds: string[]\n scope: { tenantId: string | null; organizationId: string | null }\n}\n\ntype BaseProps = {\n tenantId?: string | null\n organizationId?: string | null\n}\n\ntype RoleProps = BaseProps & {\n kind: 'role'\n targetId: string\n}\n\ntype UserProps = BaseProps & {\n kind: 'user'\n targetId: string\n}\n\ntype WidgetVisibilityEditorProps = RoleProps | UserProps\n\nexport type WidgetVisibilityEditorHandle = {\n save: () => Promise<void>\n}\n\nconst EMPTY: string[] = []\n\nfunction resolveWidgetText(\n t: (key: string, fallback: string) => string,\n id: string,\n field: 'title' | 'description',\n fallback: string,\n): string {\n const key1 = `${id}.${field}`\n const result1 = t(key1, '')\n if (result1 && result1 !== key1) return result1\n\n const key2 = `dashboard.widgets.${id}.${field}`\n const result2 = t(key2, '')\n if (result2 && result2 !== key2) return result2\n\n const dotIndex = id.lastIndexOf('.')\n if (dotIndex > 0) {\n const prefix = id.slice(0, dotIndex)\n const lastPart = id.slice(dotIndex + 1)\n const key3 = `${prefix}.widgets.${lastPart}.${field}`\n const result3 = t(key3, '')\n if (result3 && result3 !== key3) return result3\n }\n\n return fallback\n}\n\nexport const WidgetVisibilityEditor = React.forwardRef<WidgetVisibilityEditorHandle, WidgetVisibilityEditorProps>(function WidgetVisibilityEditor(props, ref) {\n const t = useT()\n const tRef = React.useRef(t)\n tRef.current = t\n\n const resolveTitle = React.useCallback(\n (widget: WidgetCatalogItem) => resolveWidgetText(t, widget.id, 'title', widget.title),\n [t],\n )\n\n const resolveDescription = React.useCallback(\n (widget: WidgetCatalogItem) => resolveWidgetText(t, widget.id, 'description', widget.description || ''),\n [t],\n )\n const { kind, targetId, tenantId, organizationId } = props\n const [catalog, setCatalog] = React.useState<WidgetCatalogItem[]>([])\n const [loading, setLoading] = React.useState(true)\n const [saving, setSaving] = React.useState(false)\n const [error, setError] = React.useState<string | null>(null)\n\n const [selected, setSelected] = React.useState<string[]>(EMPTY)\n const [original, setOriginal] = React.useState<string[]>(EMPTY)\n const [mode, setMode] = React.useState<'inherit' | 'override'>('inherit')\n const [originalMode, setOriginalMode] = React.useState<'inherit' | 'override'>('inherit')\n const [effective, setEffective] = React.useState<string[]>(EMPTY)\n\n const dirty = React.useMemo(() => {\n if (kind === 'user') {\n if (mode !== originalMode) return true\n if (mode === 'override') return selected.join('|') !== original.join('|')\n return false\n }\n return selected.join('|') !== original.join('|')\n }, [kind, mode, original, originalMode, selected])\n\n const loadCatalog = React.useCallback(async () => {\n const data = await readApiResultOrThrow<{ items?: unknown[] }>(\n '/api/dashboards/widgets/catalog',\n undefined,\n { errorMessage: tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.') },\n )\n const items = Array.isArray(data?.items) ? data.items : []\n const mapped = items\n .map((item: unknown): WidgetCatalogItem | null => {\n if (!item || typeof item !== 'object') return null\n const entry = item as Record<string, unknown>\n const id = typeof entry.id === 'string' ? entry.id : null\n if (!id || !id.length) return null\n const title =\n typeof entry.title === 'string' && entry.title.length ? entry.title : id\n const description =\n typeof entry.description === 'string' && entry.description.length ? entry.description : null\n return { id, title, description }\n })\n .filter((item: WidgetCatalogItem | null): item is WidgetCatalogItem => item !== null)\n setCatalog(mapped)\n }, [])\n\n const loadRoleData = React.useCallback(async () => {\n const params = new URLSearchParams({ roleId: targetId })\n if (tenantId) params.set('tenantId', tenantId)\n if (organizationId) params.set('organizationId', organizationId)\n const data = await readApiResultOrThrow<RoleResponse>(\n `/api/dashboards/roles/widgets?${params.toString()}`,\n undefined,\n { errorMessage: tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.') },\n )\n const ids = Array.isArray(data.widgetIds) ? data.widgetIds : []\n setSelected(ids)\n setOriginal(ids)\n setMode('override')\n setOriginalMode('override')\n setEffective(ids)\n }, [organizationId, targetId, tenantId])\n\n const loadUserData = React.useCallback(async () => {\n const params = new URLSearchParams({ userId: targetId })\n if (tenantId) params.set('tenantId', tenantId)\n if (organizationId) params.set('organizationId', organizationId)\n const data = await readApiResultOrThrow<UserResponse>(\n `/api/dashboards/users/widgets?${params.toString()}`,\n undefined,\n { errorMessage: tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.') },\n )\n const ids = Array.isArray(data.widgetIds) ? data.widgetIds : []\n setSelected(ids)\n setOriginal(ids)\n setMode(data.mode || 'inherit')\n setOriginalMode(data.mode || 'inherit')\n setEffective(Array.isArray(data.effectiveWidgetIds) ? data.effectiveWidgetIds : [])\n }, [organizationId, targetId, tenantId])\n\n React.useEffect(() => {\n let cancelled = false\n async function load() {\n setLoading(true)\n setError(null)\n try {\n await loadCatalog()\n if (kind === 'role') await loadRoleData()\n else await loadUserData()\n } catch (err) {\n console.error('Failed to load widget visibility data', err)\n if (!cancelled) {\n setError(tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.'))\n }\n } finally {\n if (!cancelled) setLoading(false)\n }\n }\n load()\n return () => { cancelled = true }\n }, [kind, loadCatalog, loadRoleData, loadUserData])\n\n const toggle = React.useCallback((id: string) => {\n setSelected((prev) => (prev.includes(id) ? prev.filter((value) => value !== id) : [...prev, id]))\n }, [])\n\n const resetSelections = React.useCallback(() => {\n setSelected(original)\n setMode(originalMode)\n }, [original, originalMode])\n\n const save = React.useCallback(async () => {\n if (loading) return\n if (error && catalog.length === 0) return\n if (!dirty) return\n setSaving(true)\n setError(null)\n try {\n const saveError = t('dashboards.widgets.error.save', 'Unable to save dashboard widget preferences.')\n if (kind === 'role') {\n const payload = {\n roleId: targetId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n widgetIds: selected,\n }\n await apiCallOrThrow('/api/dashboards/roles/widgets', {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n }, { errorMessage: saveError })\n setOriginal(selected)\n setOriginalMode('override')\n setEffective(selected)\n } else {\n const payload = {\n userId: targetId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n mode,\n widgetIds: selected,\n }\n await apiCallOrThrow('/api/dashboards/users/widgets', {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n }, { errorMessage: saveError })\n setOriginal(selected)\n if (mode === 'inherit') {\n const refreshed = await readApiResultOrThrow<UserResponse>(\n `/api/dashboards/users/widgets?userId=${encodeURIComponent(targetId)}`,\n undefined,\n { errorMessage: saveError },\n )\n setEffective(Array.isArray(refreshed.effectiveWidgetIds) ? refreshed.effectiveWidgetIds : [])\n } else {\n setEffective(selected)\n }\n setOriginal(selected)\n setOriginalMode(mode)\n }\n try { flash(t('dashboards.widgets.flash.saved', 'Dashboard widgets updated'), 'success') } catch {}\n } catch (err) {\n console.error('Failed to save widget visibility', err)\n setError(t('dashboards.widgets.error.save', 'Unable to save dashboard widget preferences.'))\n } finally {\n setSaving(false)\n }\n }, [catalog.length, dirty, error, kind, loading, mode, organizationId, selected, t, targetId, tenantId])\n\n React.useImperativeHandle(ref, () => ({ save }), [save])\n\n if (loading) {\n return (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Spinner size=\"sm\" /> {t('dashboards.widgets.loading', 'Loading widget options\u2026')}\n </div>\n )\n }\n\n if (error && catalog.length === 0) {\n return <div className=\"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive\">{error}</div>\n }\n\n return (\n <div className=\"space-y-4\">\n {error && (\n <div className=\"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive\">{error}</div>\n )}\n\n {kind === 'user' && (\n <RadioGroup\n className=\"flex flex-row items-center gap-3 rounded-md border bg-muted/30 px-3 py-2\"\n name=\"widgetOverride\"\n value={mode}\n onValueChange={(next) => setMode(next as 'inherit' | 'override')}\n >\n <RadioField\n value=\"inherit\"\n label={t('dashboards.widgets.mode.inherit', 'Inherit from roles')}\n />\n <RadioField\n value=\"override\"\n label={t('dashboards.widgets.mode.override', 'Override for this user')}\n />\n </RadioGroup>\n )}\n\n {kind === 'user' && mode === 'inherit' && (\n <div className=\"rounded-md border border-muted bg-muted/30 px-3 py-2 text-xs text-muted-foreground\">\n {t('dashboards.widgets.mode.hint', 'This user currently inherits widgets from their assigned roles. Switch to override to customize.')}\n </div>\n )}\n\n {(kind === 'role' || mode === 'override') && (\n <div className=\"space-y-3\">\n {catalog.map((widget) => (\n <label key={widget.id} className=\"flex items-start gap-3 rounded-md border px-3 py-2 hover:border-primary/40\">\n <input\n type=\"checkbox\"\n className=\"mt-1 size-4\"\n checked={selected.includes(widget.id)}\n onChange={() => toggle(widget.id)}\n />\n <div>\n <div className=\"text-sm font-medium leading-none\">{resolveTitle(widget)}</div>\n {widget.description ? <div className=\"mt-1 text-xs text-muted-foreground\">{resolveDescription(widget)}</div> : null}\n </div>\n </label>\n ))}\n </div>\n )}\n\n {kind === 'user' && effective.length > 0 && (\n <div className=\"rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground\">\n {t('dashboards.widgets.effective', 'Effective widgets:')} {effective.map((id) => { const meta = catalog.find((m) => m.id === id); return meta ? resolveTitle(meta) : id }).join(', ')}\n </div>\n )}\n\n <div className=\"flex items-center gap-2\">\n <Button type=\"button\" onClick={save} disabled={saving || !dirty}>\n {saving ? t('dashboards.widgets.saving', 'Saving\u2026') : t('dashboards.widgets.save', 'Save widgets')}\n </Button>\n <Button type=\"button\" variant=\"ghost\" onClick={resetSelections} disabled={!dirty}>\n {t('dashboards.widgets.reset', 'Reset')}\n </Button>\n </div>\n </div>\n )\n})\n\nWidgetVisibilityEditor.displayName = 'WidgetVisibilityEditor'\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { RadioGroup } from '@open-mercato/ui/primitives/radio'\nimport { RadioField } from '@open-mercato/ui/primitives/radio-field'\nimport { apiCallOrThrow, readApiResultOrThrow } from '@open-mercato/ui/backend/utils/apiCall'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\n\ntype WidgetCatalogItem = {\n id: string\n title: string\n description: string | null\n}\n\ntype RoleResponse = {\n widgetIds: string[]\n hasCustom: boolean\n scope: { tenantId: string | null; organizationId: string | null }\n}\n\ntype UserResponse = {\n mode: 'inherit' | 'override'\n widgetIds: string[]\n hasCustom: boolean\n effectiveWidgetIds: string[]\n scope: { tenantId: string | null; organizationId: string | null }\n}\n\ntype BaseProps = {\n tenantId?: string | null\n organizationId?: string | null\n preserveOnTenantChange?: boolean\n}\n\ntype RoleProps = BaseProps & {\n kind: 'role'\n targetId: string\n}\n\ntype UserProps = BaseProps & {\n kind: 'user'\n targetId: string\n}\n\ntype WidgetVisibilityEditorProps = RoleProps | UserProps\n\nexport type WidgetVisibilityEditorHandle = {\n save: () => Promise<void>\n}\n\nconst EMPTY: string[] = []\n\nfunction resolveWidgetText(\n t: (key: string, fallback: string) => string,\n id: string,\n field: 'title' | 'description',\n fallback: string,\n): string {\n const key1 = `${id}.${field}`\n const result1 = t(key1, '')\n if (result1 && result1 !== key1) return result1\n\n const key2 = `dashboard.widgets.${id}.${field}`\n const result2 = t(key2, '')\n if (result2 && result2 !== key2) return result2\n\n const dotIndex = id.lastIndexOf('.')\n if (dotIndex > 0) {\n const prefix = id.slice(0, dotIndex)\n const lastPart = id.slice(dotIndex + 1)\n const key3 = `${prefix}.widgets.${lastPart}.${field}`\n const result3 = t(key3, '')\n if (result3 && result3 !== key3) return result3\n }\n\n return fallback\n}\n\nexport const WidgetVisibilityEditor = React.forwardRef<WidgetVisibilityEditorHandle, WidgetVisibilityEditorProps>(function WidgetVisibilityEditor(props, ref) {\n const t = useT()\n const tRef = React.useRef(t)\n tRef.current = t\n\n const resolveTitle = React.useCallback(\n (widget: WidgetCatalogItem) => resolveWidgetText(t, widget.id, 'title', widget.title),\n [t],\n )\n\n const resolveDescription = React.useCallback(\n (widget: WidgetCatalogItem) => resolveWidgetText(t, widget.id, 'description', widget.description || ''),\n [t],\n )\n const { kind, targetId, tenantId, organizationId, preserveOnTenantChange = false } = props\n const [catalog, setCatalog] = React.useState<WidgetCatalogItem[]>([])\n const [loading, setLoading] = React.useState(true)\n const [saving, setSaving] = React.useState(false)\n const [error, setError] = React.useState<string | null>(null)\n\n const [selected, setSelected] = React.useState<string[]>(EMPTY)\n const [original, setOriginal] = React.useState<string[]>(EMPTY)\n const [mode, setMode] = React.useState<'inherit' | 'override'>('inherit')\n const [originalMode, setOriginalMode] = React.useState<'inherit' | 'override'>('inherit')\n const [effective, setEffective] = React.useState<string[]>(EMPTY)\n\n const dirty = React.useMemo(() => {\n if (kind === 'user') {\n if (mode !== originalMode) return true\n if (mode === 'override') return selected.join('|') !== original.join('|')\n return false\n }\n return selected.join('|') !== original.join('|')\n }, [kind, mode, original, originalMode, selected])\n\n const loadCatalog = React.useCallback(async () => {\n const data = await readApiResultOrThrow<{ items?: unknown[] }>(\n '/api/dashboards/widgets/catalog',\n undefined,\n { errorMessage: tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.') },\n )\n const items = Array.isArray(data?.items) ? data.items : []\n const mapped = items\n .map((item: unknown): WidgetCatalogItem | null => {\n if (!item || typeof item !== 'object') return null\n const entry = item as Record<string, unknown>\n const id = typeof entry.id === 'string' ? entry.id : null\n if (!id || !id.length) return null\n const title =\n typeof entry.title === 'string' && entry.title.length ? entry.title : id\n const description =\n typeof entry.description === 'string' && entry.description.length ? entry.description : null\n return { id, title, description }\n })\n .filter((item: WidgetCatalogItem | null): item is WidgetCatalogItem => item !== null)\n setCatalog(mapped)\n }, [])\n\n const tenantIdRef = React.useRef(tenantId)\n React.useEffect(() => { tenantIdRef.current = tenantId }, [tenantId])\n const organizationIdRef = React.useRef(organizationId)\n React.useEffect(() => { organizationIdRef.current = organizationId }, [organizationId])\n const hasMountedRef = React.useRef(false)\n\n const loadRoleData = React.useCallback(async (forTenantId: string | null | undefined, forOrganizationId: string | null | undefined) => {\n const params = new URLSearchParams({ roleId: targetId })\n if (forTenantId) params.set('tenantId', forTenantId)\n if (forOrganizationId) params.set('organizationId', forOrganizationId)\n const data = await readApiResultOrThrow<RoleResponse>(\n `/api/dashboards/roles/widgets?${params.toString()}`,\n undefined,\n { errorMessage: tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.') },\n )\n const ids = Array.isArray(data.widgetIds) ? data.widgetIds : []\n setSelected(ids)\n setOriginal(ids)\n setMode('override')\n setOriginalMode('override')\n setEffective(ids)\n }, [targetId])\n\n const loadUserData = React.useCallback(async (forTenantId: string | null | undefined, forOrganizationId: string | null | undefined) => {\n const params = new URLSearchParams({ userId: targetId })\n if (forTenantId) params.set('tenantId', forTenantId)\n if (forOrganizationId) params.set('organizationId', forOrganizationId)\n const data = await readApiResultOrThrow<UserResponse>(\n `/api/dashboards/users/widgets?${params.toString()}`,\n undefined,\n { errorMessage: tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.') },\n )\n const ids = Array.isArray(data.widgetIds) ? data.widgetIds : []\n setSelected(ids)\n setOriginal(ids)\n setMode(data.mode || 'inherit')\n setOriginalMode(data.mode || 'inherit')\n setEffective(Array.isArray(data.effectiveWidgetIds) ? data.effectiveWidgetIds : [])\n }, [targetId])\n\n React.useEffect(() => {\n let cancelled = false\n async function load() {\n setLoading(true)\n setError(null)\n try {\n await loadCatalog()\n if (kind === 'role') await loadRoleData(tenantIdRef.current, organizationIdRef.current)\n else await loadUserData(tenantIdRef.current, organizationIdRef.current)\n } catch (err) {\n console.error('Failed to load widget visibility data', err)\n if (!cancelled) {\n setError(tRef.current('dashboards.widgets.error.load', 'Unable to load widget configuration.'))\n }\n } finally {\n if (!cancelled) {\n setLoading(false)\n hasMountedRef.current = true\n }\n }\n }\n load()\n return () => { cancelled = true }\n }, [kind, loadCatalog, loadRoleData, loadUserData])\n\n React.useEffect(() => {\n if (!hasMountedRef.current) return\n if (preserveOnTenantChange) return\n let cancelled = false\n async function refetch() {\n try {\n if (kind === 'role') await loadRoleData(tenantId, organizationId)\n else await loadUserData(tenantId, organizationId)\n } catch (err) {\n console.error('Failed to reload widget visibility data', err)\n }\n }\n refetch()\n return () => { cancelled = true }\n }, [tenantId, organizationId, kind, loadRoleData, loadUserData, preserveOnTenantChange])\n\n const toggle = React.useCallback((id: string) => {\n setSelected((prev) => (prev.includes(id) ? prev.filter((value) => value !== id) : [...prev, id]))\n }, [])\n\n const resetSelections = React.useCallback(() => {\n setSelected(original)\n setMode(originalMode)\n }, [original, originalMode])\n\n const save = React.useCallback(async () => {\n if (loading) return\n if (error && catalog.length === 0) return\n if (!dirty) return\n setSaving(true)\n setError(null)\n try {\n const saveError = t('dashboards.widgets.error.save', 'Unable to save dashboard widget preferences.')\n if (kind === 'role') {\n const payload = {\n roleId: targetId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n widgetIds: selected,\n }\n await apiCallOrThrow('/api/dashboards/roles/widgets', {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n }, { errorMessage: saveError })\n setOriginal(selected)\n setOriginalMode('override')\n setEffective(selected)\n } else {\n const payload = {\n userId: targetId,\n tenantId: tenantId ?? null,\n organizationId: organizationId ?? null,\n mode,\n widgetIds: selected,\n }\n await apiCallOrThrow('/api/dashboards/users/widgets', {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n }, { errorMessage: saveError })\n setOriginal(selected)\n if (mode === 'inherit') {\n const refreshed = await readApiResultOrThrow<UserResponse>(\n `/api/dashboards/users/widgets?userId=${encodeURIComponent(targetId)}`,\n undefined,\n { errorMessage: saveError },\n )\n setEffective(Array.isArray(refreshed.effectiveWidgetIds) ? refreshed.effectiveWidgetIds : [])\n } else {\n setEffective(selected)\n }\n setOriginal(selected)\n setOriginalMode(mode)\n }\n try { flash(t('dashboards.widgets.flash.saved', 'Dashboard widgets updated'), 'success') } catch {}\n } catch (err) {\n console.error('Failed to save widget visibility', err)\n setError(t('dashboards.widgets.error.save', 'Unable to save dashboard widget preferences.'))\n } finally {\n setSaving(false)\n }\n }, [catalog.length, dirty, error, kind, loading, mode, organizationId, selected, t, targetId, tenantId])\n\n React.useImperativeHandle(ref, () => ({ save }), [save])\n\n if (loading) {\n return (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Spinner size=\"sm\" /> {t('dashboards.widgets.loading', 'Loading widget options\u2026')}\n </div>\n )\n }\n\n if (error && catalog.length === 0) {\n return <div className=\"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive\">{error}</div>\n }\n\n return (\n <div className=\"space-y-4\">\n {error && (\n <div className=\"rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive\">{error}</div>\n )}\n\n {kind === 'user' && (\n <RadioGroup\n className=\"flex flex-row items-center gap-3 rounded-md border bg-muted/30 px-3 py-2\"\n name=\"widgetOverride\"\n value={mode}\n onValueChange={(next) => setMode(next as 'inherit' | 'override')}\n >\n <RadioField\n value=\"inherit\"\n label={t('dashboards.widgets.mode.inherit', 'Inherit from roles')}\n />\n <RadioField\n value=\"override\"\n label={t('dashboards.widgets.mode.override', 'Override for this user')}\n />\n </RadioGroup>\n )}\n\n {kind === 'user' && mode === 'inherit' && (\n <div className=\"rounded-md border border-muted bg-muted/30 px-3 py-2 text-xs text-muted-foreground\">\n {t('dashboards.widgets.mode.hint', 'This user currently inherits widgets from their assigned roles. Switch to override to customize.')}\n </div>\n )}\n\n {(kind === 'role' || mode === 'override') && (\n <div className=\"space-y-3\">\n {catalog.map((widget) => (\n <label key={widget.id} className=\"flex items-start gap-3 rounded-md border px-3 py-2 hover:border-primary/40\">\n <input\n type=\"checkbox\"\n className=\"mt-1 size-4\"\n checked={selected.includes(widget.id)}\n onChange={() => toggle(widget.id)}\n />\n <div>\n <div className=\"text-sm font-medium leading-none\">{resolveTitle(widget)}</div>\n {widget.description ? <div className=\"mt-1 text-xs text-muted-foreground\">{resolveDescription(widget)}</div> : null}\n </div>\n </label>\n ))}\n </div>\n )}\n\n {kind === 'user' && effective.length > 0 && (\n <div className=\"rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground\">\n {t('dashboards.widgets.effective', 'Effective widgets:')} {effective.map((id) => { const meta = catalog.find((m) => m.id === id); return meta ? resolveTitle(meta) : id }).join(', ')}\n </div>\n )}\n\n <div className=\"flex items-center gap-2\">\n <Button type=\"button\" onClick={save} disabled={saving || !dirty}>\n {saving ? t('dashboards.widgets.saving', 'Saving\u2026') : t('dashboards.widgets.save', 'Save widgets')}\n </Button>\n <Button type=\"button\" variant=\"ghost\" onClick={resetSelections} disabled={!dirty}>\n {t('dashboards.widgets.reset', 'Reset')}\n </Button>\n </div>\n </div>\n )\n})\n\nWidgetVis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AU,yEACZ;AAAA,QAAE,gCAAgC,oBAAoB;AAAA,MAAE;AAAA,MAAE,UAAU,IAAI,CAAC,OAAO;AAAE,cAAM,OAAO,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE;AAAG,eAAO,OAAO,aAAa,IAAI,IAAI;AAAA,MAAG,CAAC,EAAE,KAAK,IAAI;AAAA,OACtL;AAAA,IAGF,qBAAC,SAAI,WAAU,2BACb;AAAA,0BAAC,UAAO,MAAK,UAAS,SAAS,MAAM,UAAU,UAAU,CAAC,OACvD,mBAAS,EAAE,6BAA6B,cAAS,IAAI,EAAE,2BAA2B,cAAc,GACnG;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,SAAQ,SAAS,iBAAiB,UAAU,CAAC,OACxE,YAAE,4BAA4B,OAAO,GACxC;AAAA,OACF;AAAA,KACF;AAEJ,CAAC;AAED,uBAAuB,cAAc;",
|
|
6
6
|
"names": ["WidgetVisibilityEditor"]
|
|
7
7
|
}
|
|
@@ -33,6 +33,8 @@ async function GET(req) {
|
|
|
33
33
|
description: integration.description ?? null,
|
|
34
34
|
providerKey: integration.providerKey ?? null,
|
|
35
35
|
direction: adapter.direction,
|
|
36
|
+
runMode: adapter.runMode ?? "generic",
|
|
37
|
+
canStartRun: adapter.runMode !== "provider",
|
|
36
38
|
supportedEntities: adapter.supportedEntities,
|
|
37
39
|
hasCredentials: Boolean(credentials),
|
|
38
40
|
isEnabled: state.isEnabled,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/data_sync/api/options.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAllIntegrations } from '@open-mercato/shared/modules/integrations/types'\nimport type { CredentialsService } from '../../integrations/lib/credentials-service'\nimport type { IntegrationStateService } from '../../integrations/lib/state-service'\nimport { getDataSyncAdapter } from '../lib/adapter-registry'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['data_sync.view'] },\n}\n\nexport const openApi = {\n tags: ['DataSync'],\n summary: 'List data sync integration options',\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n const items = await Promise.all(\n getAllIntegrations()\n .filter((integration) => integration.hub === 'data_sync' && integration.providerKey)\n .map(async (integration) => {\n const adapter = getDataSyncAdapter(integration.providerKey as string)\n if (!adapter) return null\n\n const [credentials, state] = await Promise.all([\n credentialsService.resolve(integration.id, scope),\n stateService.resolveState(integration.id, scope),\n ])\n\n return {\n integrationId: integration.id,\n title: integration.title,\n description: integration.description ?? null,\n providerKey: integration.providerKey ?? null,\n direction: adapter.direction,\n supportedEntities: adapter.supportedEntities,\n hasCredentials: Boolean(credentials),\n isEnabled: state.isEnabled,\n settingsPath: `/backend/integrations/${encodeURIComponent(integration.id)}`,\n }\n }),\n )\n\n return NextResponse.json({\n items: items.filter((item): item is NonNullable<typeof item> => Boolean(item)),\n })\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AAGnC,SAAS,0BAA0B;AAE5B,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,gBAAgB,EAAE;AAChE;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,UAAU;AAAA,EACjB,SAAS;AACX;AAEA,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,YAAY,CAAC,KAAK,OAAO;AAClC,WAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,qBAAqB,UAAU,QAAQ,+BAA+B;AAC5E,QAAM,eAAe,UAAU,QAAQ,yBAAyB;AAChE,QAAM,QAAQ,EAAE,gBAAgB,KAAK,OAAiB,UAAU,KAAK,SAAS;AAE9E,QAAM,QAAQ,MAAM,QAAQ;AAAA,IAC1B,mBAAmB,EAChB,OAAO,CAAC,gBAAgB,YAAY,QAAQ,eAAe,YAAY,WAAW,EAClF,IAAI,OAAO,gBAAgB;AAC1B,YAAM,UAAU,mBAAmB,YAAY,WAAqB;AACpE,UAAI,CAAC,QAAS,QAAO;AAErB,YAAM,CAAC,aAAa,KAAK,IAAI,MAAM,QAAQ,IAAI;AAAA,QAC7C,mBAAmB,QAAQ,YAAY,IAAI,KAAK;AAAA,QAChD,aAAa,aAAa,YAAY,IAAI,KAAK;AAAA,MACjD,CAAC;AAED,aAAO;AAAA,QACL,eAAe,YAAY;AAAA,QAC3B,OAAO,YAAY;AAAA,QACnB,aAAa,YAAY,eAAe;AAAA,QACxC,aAAa,YAAY,eAAe;AAAA,QACxC,WAAW,QAAQ;AAAA,QACnB,mBAAmB,QAAQ;AAAA,QAC3B,gBAAgB,QAAQ,WAAW;AAAA,QACnC,WAAW,MAAM;AAAA,QACjB,cAAc,yBAAyB,mBAAmB,YAAY,EAAE,CAAC;AAAA,MAC3E;AAAA,IACF,CAAC;AAAA,EACL;AAEA,SAAO,aAAa,KAAK;AAAA,IACvB,OAAO,MAAM,OAAO,CAAC,SAA2C,QAAQ,IAAI,CAAC;AAAA,EAC/E,CAAC;AACH;",
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAllIntegrations } from '@open-mercato/shared/modules/integrations/types'\nimport type { CredentialsService } from '../../integrations/lib/credentials-service'\nimport type { IntegrationStateService } from '../../integrations/lib/state-service'\nimport { getDataSyncAdapter } from '../lib/adapter-registry'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['data_sync.view'] },\n}\n\nexport const openApi = {\n tags: ['DataSync'],\n summary: 'List data sync integration options',\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId || !auth.orgId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsService\n const stateService = container.resolve('integrationStateService') as IntegrationStateService\n const scope = { organizationId: auth.orgId as string, tenantId: auth.tenantId }\n\n const items = await Promise.all(\n getAllIntegrations()\n .filter((integration) => integration.hub === 'data_sync' && integration.providerKey)\n .map(async (integration) => {\n const adapter = getDataSyncAdapter(integration.providerKey as string)\n if (!adapter) return null\n\n const [credentials, state] = await Promise.all([\n credentialsService.resolve(integration.id, scope),\n stateService.resolveState(integration.id, scope),\n ])\n\n return {\n integrationId: integration.id,\n title: integration.title,\n description: integration.description ?? null,\n providerKey: integration.providerKey ?? null,\n direction: adapter.direction,\n runMode: adapter.runMode ?? 'generic',\n canStartRun: adapter.runMode !== 'provider',\n supportedEntities: adapter.supportedEntities,\n hasCredentials: Boolean(credentials),\n isEnabled: state.isEnabled,\n settingsPath: `/backend/integrations/${encodeURIComponent(integration.id)}`,\n }\n }),\n )\n\n return NextResponse.json({\n items: items.filter((item): item is NonNullable<typeof item> => Boolean(item)),\n })\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AAGnC,SAAS,0BAA0B;AAE5B,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MA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