@open-mercato/core 0.9.0 → 0.9.1-develop.7462.1.94c09f158f
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/generated/entities/customer_dictionary_entry/index.js +2 -0
- package/dist/generated/entities/customer_dictionary_entry/index.js.map +2 -2
- package/dist/generated/entities/customer_interaction/index.js +2 -0
- package/dist/generated/entities/customer_interaction/index.js.map +2 -2
- package/dist/generated/entity-fields-registry.js +2 -0
- package/dist/generated/entity-fields-registry.js.map +2 -2
- package/dist/modules/attachments/api/route.js +29 -3
- package/dist/modules/attachments/api/route.js.map +2 -2
- package/dist/modules/attachments/lib/ocrLimits.js +49 -0
- package/dist/modules/attachments/lib/ocrLimits.js.map +7 -0
- package/dist/modules/attachments/lib/ocrQueue.js +76 -2
- package/dist/modules/attachments/lib/ocrQueue.js.map +2 -2
- package/dist/modules/attachments/lib/ocrService.js +4 -0
- package/dist/modules/attachments/lib/ocrService.js.map +2 -2
- package/dist/modules/attachments/lib/pdfProcessing.js +14 -2
- package/dist/modules/attachments/lib/pdfProcessing.js.map +2 -2
- package/dist/modules/attachments/lib/scoped-upload-service.js +4 -2
- package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
- package/dist/modules/attachments/lib/textExtraction.js +13 -1
- package/dist/modules/attachments/lib/textExtraction.js.map +2 -2
- package/dist/modules/catalog/commands/categories.js +1 -1
- package/dist/modules/catalog/commands/categories.js.map +2 -2
- package/dist/modules/catalog/commands/productDeleteChildren.js +389 -0
- package/dist/modules/catalog/commands/productDeleteChildren.js.map +7 -0
- package/dist/modules/catalog/commands/products.js +52 -17
- package/dist/modules/catalog/commands/products.js.map +2 -2
- package/dist/modules/catalog/search.js +3 -1
- package/dist/modules/catalog/search.js.map +2 -2
- package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js +2 -1
- package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js.map +2 -2
- package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js +4 -6
- package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js.map +2 -2
- package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js +4 -6
- package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js.map +2 -2
- package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js +47 -11
- package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js.map +3 -3
- package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +10 -7
- package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +2 -2
- package/dist/modules/communication_channels/commands/deliver-outbound-message.js +5 -1
- package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +2 -2
- package/dist/modules/communication_channels/lib/inbound-message-origin.js +1 -1
- package/dist/modules/communication_channels/lib/inbound-message-origin.js.map +2 -2
- package/dist/modules/communication_channels/lib/oauth-result.js +12 -0
- package/dist/modules/communication_channels/lib/oauth-result.js.map +7 -0
- package/dist/modules/communication_channels/lib/oauth-state.js +4 -1
- package/dist/modules/communication_channels/lib/oauth-state.js.map +2 -2
- package/dist/modules/communication_channels/lib/use-connect-channel.js +10 -0
- package/dist/modules/communication_channels/lib/use-connect-channel.js.map +2 -2
- package/dist/modules/customers/api/activity-types/route.js +151 -0
- package/dist/modules/customers/api/activity-types/route.js.map +7 -0
- package/dist/modules/customers/api/deals/[id]/people/route.js +58 -5
- package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
- package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +13 -5
- package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
- package/dist/modules/customers/api/dictionaries/[kind]/route.js +20 -5
- package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
- package/dist/modules/customers/api/interactions/route.js +3 -0
- package/dist/modules/customers/api/interactions/route.js.map +2 -2
- package/dist/modules/customers/api/interactions/tasks/route.js +1 -0
- package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
- package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js +18 -0
- package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js.map +2 -2
- package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js +0 -23
- package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js.map +2 -2
- package/dist/modules/customers/backend/customers/deals/[id]/page.js +15 -17
- package/dist/modules/customers/backend/customers/deals/[id]/page.js.map +2 -2
- package/dist/modules/customers/calendar-event-types.js +548 -0
- package/dist/modules/customers/calendar-event-types.js.map +7 -0
- package/dist/modules/customers/commands/dictionaries.js +70 -10
- package/dist/modules/customers/commands/dictionaries.js.map +2 -2
- package/dist/modules/customers/commands/interactions.js +187 -22
- package/dist/modules/customers/commands/interactions.js.map +3 -3
- package/dist/modules/customers/components/ActivityTypeEditor.js +288 -0
- package/dist/modules/customers/components/ActivityTypeEditor.js.map +7 -0
- package/dist/modules/customers/components/DictionarySettings.js +3 -1
- package/dist/modules/customers/components/DictionarySettings.js.map +2 -2
- package/dist/modules/customers/components/calendar/CalendarEventEditor.js +391 -297
- package/dist/modules/customers/components/calendar/CalendarEventEditor.js.map +3 -3
- package/dist/modules/customers/components/calendar/CalendarSettingsModal.js +9 -74
- package/dist/modules/customers/components/calendar/CalendarSettingsModal.js.map +2 -2
- package/dist/modules/customers/components/calendar/TimeGrid.js +20 -16
- package/dist/modules/customers/components/calendar/TimeGrid.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/EventTypePanel.js +218 -0
- package/dist/modules/customers/components/calendar/editor/EventTypePanel.js.map +7 -0
- package/dist/modules/customers/components/calendar/editor/LocationField.js +7 -3
- package/dist/modules/customers/components/calendar/editor/LocationField.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/PeopleField.js +5 -2
- package/dist/modules/customers/components/calendar/editor/PeopleField.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/PriorityField.js +3 -1
- package/dist/modules/customers/components/calendar/editor/PriorityField.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/RepeatField.js +9 -1
- package/dist/modules/customers/components/calendar/editor/RepeatField.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/ResourcesField.js +4 -1
- package/dist/modules/customers/components/calendar/editor/ResourcesField.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/ScheduleSection.js +15 -7
- package/dist/modules/customers/components/calendar/editor/ScheduleSection.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/SegmentGroup.js +3 -1
- package/dist/modules/customers/components/calendar/editor/SegmentGroup.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/hooks.js +28 -13
- package/dist/modules/customers/components/calendar/editor/hooks.js.map +3 -3
- package/dist/modules/customers/components/calendar/editor/inputs.js +14 -6
- package/dist/modules/customers/components/calendar/editor/inputs.js.map +2 -2
- package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js +54 -0
- package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js.map +7 -0
- package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js +82 -0
- package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js.map +7 -0
- package/dist/modules/customers/components/calendar/types.js +1 -0
- package/dist/modules/customers/components/calendar/types.js.map +2 -2
- package/dist/modules/customers/components/detail/CompanyPeopleSection.js +78 -343
- package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
- package/dist/modules/customers/components/detail/CreatePersonDialog.js +12 -11
- package/dist/modules/customers/components/detail/CreatePersonDialog.js.map +2 -2
- package/dist/modules/customers/components/detail/DealForm.js +7 -3
- package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
- package/dist/modules/customers/components/detail/DealPeopleSection.js +206 -0
- package/dist/modules/customers/components/detail/DealPeopleSection.js.map +7 -0
- package/dist/modules/customers/components/detail/LinkedPeopleSection.js +342 -0
- package/dist/modules/customers/components/detail/LinkedPeopleSection.js.map +7 -0
- package/dist/modules/customers/components/detail/PersonCard.js +5 -2
- package/dist/modules/customers/components/detail/PersonCard.js.map +2 -2
- package/dist/modules/customers/components/linking/adapters/personAdapter.js +3 -0
- package/dist/modules/customers/components/linking/adapters/personAdapter.js.map +2 -2
- package/dist/modules/customers/data/entities.js +6 -0
- package/dist/modules/customers/data/entities.js.map +2 -2
- package/dist/modules/customers/data/validators.js +39 -10
- package/dist/modules/customers/data/validators.js.map +2 -2
- package/dist/modules/customers/di.js +20 -1
- package/dist/modules/customers/di.js.map +2 -2
- package/dist/modules/customers/extension-points.js +13 -0
- package/dist/modules/customers/extension-points.js.map +2 -2
- package/dist/modules/customers/lib/calendar/conflicts.js +59 -16
- package/dist/modules/customers/lib/calendar/conflicts.js.map +2 -2
- package/dist/modules/customers/lib/calendar/editorPayload.js +34 -16
- package/dist/modules/customers/lib/calendar/editorPayload.js.map +2 -2
- package/dist/modules/customers/lib/calendar/eventTypeResolver.js +197 -0
- package/dist/modules/customers/lib/calendar/eventTypeResolver.js.map +7 -0
- package/dist/modules/customers/lib/calendar/interactionApplicability.js +67 -0
- package/dist/modules/customers/lib/calendar/interactionApplicability.js.map +7 -0
- package/dist/modules/customers/lib/calendar/mapItem.js +5 -2
- package/dist/modules/customers/lib/calendar/mapItem.js.map +2 -2
- package/dist/modules/customers/lib/calendar/recurrence.js +62 -1
- package/dist/modules/customers/lib/calendar/recurrence.js.map +2 -2
- package/dist/modules/customers/lib/calendar/timezone.js +111 -0
- package/dist/modules/customers/lib/calendar/timezone.js.map +7 -0
- package/dist/modules/customers/lib/interactionReadModel.js +1 -0
- package/dist/modules/customers/lib/interactionReadModel.js.map +2 -2
- package/dist/modules/customers/lib/todoCompatibility.js +1 -0
- package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
- package/dist/modules/customers/migrations/Migration20260928175058_customers.js +17 -0
- package/dist/modules/customers/migrations/Migration20260928175058_customers.js.map +7 -0
- package/dist/modules/customers/migrations/Migration20260930110235_customers.js +17 -0
- package/dist/modules/customers/migrations/Migration20260930110235_customers.js.map +7 -0
- package/dist/modules/dictionaries/components/DictionaryTable.js +60 -51
- package/dist/modules/dictionaries/components/DictionaryTable.js.map +2 -2
- package/dist/modules/messages/subscribers/message-notification.js +13 -1
- package/dist/modules/messages/subscribers/message-notification.js.map +2 -2
- package/dist/modules/payment_gateways/api/webhook/[provider]/route.js +201 -53
- package/dist/modules/payment_gateways/api/webhook/[provider]/route.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +37 -11
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
- package/dist/modules/planner/lib/availabilityMerge.js +101 -38
- package/dist/modules/planner/lib/availabilityMerge.js.map +3 -3
- package/dist/modules/planner/services/plannerAvailabilityService.js.map +2 -2
- package/dist/modules/sales/components/documents/LineItemDialog.js +159 -81
- package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
- package/dist/modules/sales/components/documents/lineItemUtils.js +7 -0
- package/dist/modules/sales/components/documents/lineItemUtils.js.map +2 -2
- package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js +12 -7
- package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js.map +2 -2
- package/dist/modules/sync_excel/lib/adapters/customers.js +28 -25
- package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
- package/generated/entities/customer_dictionary_entry/index.ts +1 -0
- package/generated/entities/customer_interaction/index.ts +1 -0
- package/generated/entity-fields-registry.ts +2 -0
- package/package.json +9 -8
- package/src/modules/attachments/api/route.ts +36 -3
- package/src/modules/attachments/lib/ocrLimits.ts +62 -0
- package/src/modules/attachments/lib/ocrQueue.ts +95 -2
- package/src/modules/attachments/lib/ocrService.ts +4 -0
- package/src/modules/attachments/lib/pdfProcessing.ts +14 -2
- package/src/modules/attachments/lib/scoped-upload-service.ts +4 -2
- package/src/modules/attachments/lib/textExtraction.ts +14 -1
- package/src/modules/auth/i18n/de.json +3 -0
- package/src/modules/auth/i18n/en.json +3 -0
- package/src/modules/auth/i18n/es.json +3 -0
- package/src/modules/auth/i18n/ko.json +3 -0
- package/src/modules/auth/i18n/pl.json +3 -0
- package/src/modules/catalog/commands/categories.ts +1 -1
- package/src/modules/catalog/commands/productDeleteChildren.ts +557 -0
- package/src/modules/catalog/commands/products.ts +58 -17
- package/src/modules/catalog/search.ts +5 -1
- package/src/modules/communication_channels/api/get/oauth/[provider]/callback/route.ts +2 -1
- package/src/modules/communication_channels/api/post/channels/connect/credentials/route.ts +4 -6
- package/src/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.ts +4 -6
- package/src/modules/communication_channels/api/post/oauth/[provider]/initiate/route.ts +46 -10
- package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +12 -9
- package/src/modules/communication_channels/commands/deliver-outbound-message.ts +6 -1
- package/src/modules/communication_channels/i18n/de.json +4 -1
- package/src/modules/communication_channels/i18n/en.json +4 -1
- package/src/modules/communication_channels/i18n/es.json +4 -1
- package/src/modules/communication_channels/i18n/ko.json +4 -1
- package/src/modules/communication_channels/i18n/pl.json +4 -1
- package/src/modules/communication_channels/lib/inbound-message-origin.ts +2 -6
- package/src/modules/communication_channels/lib/oauth-result.ts +13 -0
- package/src/modules/communication_channels/lib/oauth-state.ts +4 -1
- package/src/modules/communication_channels/lib/use-connect-channel.ts +10 -0
- package/src/modules/customers/api/activity-types/route.ts +154 -0
- package/src/modules/customers/api/deals/[id]/people/route.ts +82 -3
- package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +9 -1
- package/src/modules/customers/api/dictionaries/[kind]/route.ts +18 -2
- package/src/modules/customers/api/interactions/route.ts +4 -0
- package/src/modules/customers/api/interactions/tasks/route.ts +1 -0
- package/src/modules/customers/backend/config/customers/pipeline-stages/page.meta.ts +20 -0
- package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.ts +0 -29
- package/src/modules/customers/backend/customers/deals/[id]/page.tsx +15 -17
- package/src/modules/customers/calendar-event-types.ts +674 -0
- package/src/modules/customers/commands/dictionaries.ts +84 -8
- package/src/modules/customers/commands/interactions.ts +244 -21
- package/src/modules/customers/components/ActivityTypeEditor.tsx +239 -0
- package/src/modules/customers/components/DictionarySettings.tsx +5 -3
- package/src/modules/customers/components/calendar/CalendarEventEditor.tsx +347 -218
- package/src/modules/customers/components/calendar/CalendarSettingsModal.tsx +18 -96
- package/src/modules/customers/components/calendar/TimeGrid.tsx +20 -18
- package/src/modules/customers/components/calendar/editor/EventTypePanel.tsx +230 -0
- package/src/modules/customers/components/calendar/editor/LocationField.tsx +7 -1
- package/src/modules/customers/components/calendar/editor/PeopleField.tsx +4 -0
- package/src/modules/customers/components/calendar/editor/PriorityField.tsx +3 -0
- package/src/modules/customers/components/calendar/editor/RepeatField.tsx +10 -0
- package/src/modules/customers/components/calendar/editor/ResourcesField.tsx +4 -0
- package/src/modules/customers/components/calendar/editor/ScheduleSection.tsx +16 -4
- package/src/modules/customers/components/calendar/editor/SegmentGroup.tsx +3 -0
- package/src/modules/customers/components/calendar/editor/hooks.ts +29 -13
- package/src/modules/customers/components/calendar/editor/inputs.tsx +17 -5
- package/src/modules/customers/components/calendar/editor/useCalendarCustomFields.ts +49 -0
- package/src/modules/customers/components/calendar/editor/useEventTypeCatalog.ts +100 -0
- package/src/modules/customers/components/calendar/types.ts +1 -0
- package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +94 -388
- package/src/modules/customers/components/detail/CreatePersonDialog.tsx +39 -19
- package/src/modules/customers/components/detail/DealForm.tsx +7 -3
- package/src/modules/customers/components/detail/DealPeopleSection.tsx +256 -0
- package/src/modules/customers/components/detail/LinkedPeopleSection.tsx +474 -0
- package/src/modules/customers/components/detail/PersonCard.tsx +12 -4
- package/src/modules/customers/components/detail/types.ts +1 -0
- package/src/modules/customers/components/linking/adapters/personAdapter.tsx +4 -0
- package/src/modules/customers/data/entities.ts +8 -1
- package/src/modules/customers/data/validators.ts +42 -7
- package/src/modules/customers/di.ts +21 -0
- package/src/modules/customers/extension-points.ts +13 -0
- package/src/modules/customers/i18n/de.json +104 -8
- package/src/modules/customers/i18n/en.json +104 -8
- package/src/modules/customers/i18n/es.json +104 -8
- package/src/modules/customers/i18n/ko.json +104 -8
- package/src/modules/customers/i18n/pl.json +104 -8
- package/src/modules/customers/lib/calendar/conflicts.ts +106 -27
- package/src/modules/customers/lib/calendar/editorPayload.ts +39 -19
- package/src/modules/customers/lib/calendar/eventTypeResolver.ts +258 -0
- package/src/modules/customers/lib/calendar/interactionApplicability.ts +99 -0
- package/src/modules/customers/lib/calendar/mapItem.ts +6 -2
- package/src/modules/customers/lib/calendar/recurrence.ts +65 -1
- package/src/modules/customers/lib/calendar/timezone.ts +117 -0
- package/src/modules/customers/lib/interactionReadModel.ts +1 -0
- package/src/modules/customers/lib/todoCompatibility.ts +2 -0
- package/src/modules/customers/migrations/.snapshot-open-mercato.json +34 -0
- package/src/modules/customers/migrations/Migration20260928175058_customers.ts +15 -0
- package/src/modules/customers/migrations/Migration20260930110235_customers.ts +15 -0
- package/src/modules/dictionaries/components/DictionaryTable.tsx +63 -56
- package/src/modules/messages/subscribers/message-notification.ts +13 -3
- package/src/modules/payment_gateways/api/webhook/[provider]/route.ts +243 -62
- package/src/modules/payment_gateways/lib/gateway-service.ts +39 -12
- package/src/modules/planner/lib/availabilityMerge.ts +106 -41
- package/src/modules/planner/services/plannerAvailabilityService.ts +4 -0
- package/src/modules/sales/components/documents/LineItemDialog.tsx +194 -111
- package/src/modules/sales/components/documents/lineItemUtils.ts +18 -0
- package/src/modules/staff/backend/staff/time-tracking/projects/[id]/page.tsx +25 -13
- package/src/modules/sync_excel/lib/adapters/customers.ts +33 -27
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../../src/modules/communication_channels/api/post/oauth/%5Bprovider%5D/initiate/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { toAbsoluteUrl } from '@open-mercato/shared/lib/url'\nimport { getChannelAdapter } from '../../../../../lib/adapter-registry-singleton'\nimport { resolveOAuthClientCredentials } from '../../../../../lib/oauth-client-config'\nimport {\n COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME,\n COMMUNICATION_CHANNELS_OAUTH_STATE_TTL_MS,\n createOAuthState,\n DEFAULT_OAUTH_RETURN_URL,\n isSafeOAuthReturnUrl,\n normalizeOAuthReturnUrl,\n OAuthStateError,\n} from '../../../../../lib/oauth-state'\n\nexport const metadata = {\n path: '/communication_channels/oauth/[provider]/initiate',\n POST: {\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\nconst initiateBodySchema = z.object({\n channelType: z.literal('email').optional(),\n /** Where to send the user after the callback succeeds. Defaults to the profile page. */\n returnUrl: z.string().min(1).max(2048).refine(isSafeOAuthReturnUrl, {\n message: 'returnUrl must be a same-origin path',\n }).optional(),\n /** Optional pre-filled email \u2014 Google `login_hint`. */\n loginHint: z.string().email().optional(),\n})\n\ntype RouteContext = {\n params: Promise<{ provider: string }> | { provider: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string },\n ) => Promise<Record<string, unknown> | null>\n}\n\n/**\n * Default profile redirect \u2014 matches the per-user channels page registered by\n * slice 3d (the `/backend/profile/communication-channels` route).\n */\nfunction defaultRedirectUri(req: Request, providerKey: string): string {\n // Derive the origin from the configured app URL / forwarded headers rather\n // than the raw request origin, so the redirect_uri matches the value the\n // provider has registered even when the app sits behind a reverse proxy.\n return toAbsoluteUrl(req, `/api/communication_channels/oauth/${providerKey}/callback`)\n}\n\nexport async function POST(req: Request, context: RouteContext): Promise<Response> {\n const { provider } = await context.params\n if (!/^[a-z0-9_-]+$/i.test(provider)) {\n return NextResponse.json({ error: 'Invalid provider' }, { status: 400 })\n }\n\n const adapter = getChannelAdapter(provider)\n if (!adapter) {\n return NextResponse.json(\n { error: `No ChannelAdapter for provider: ${provider}` },\n { status: 404 },\n )\n }\n if (typeof adapter.buildOAuthAuthorizeUrl !== 'function') {\n return NextResponse.json(\n { error: `Provider '${provider}' does not support OAuth (no buildOAuthAuthorizeUrl)` },\n { status: 400 },\n )\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n let body: z.infer<typeof initiateBodySchema>\n try {\n const json = await readJsonSafe(req, {})\n body = initiateBodySchema.parse(json ?? {})\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Invalid request body' },\n { status: 422 },\n )\n }\n\n const container = await createRequestContainer()\n const credentialsService = (() => {\n try {\n return container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n return null\n }\n })()\n // OAuth client credentials are tenant-level \u2014 the admin configures them under\n // the `channel_<provider>` integration in the Integrations UI (stored at\n // userId = null). A missing row means the provider has not been set up yet;\n // we surface that as an actionable error instead of handing an empty object to\n // the adapter (which would throw a cryptic Zod \"expected string\" message).\n const credentials = await resolveOAuthClientCredentials(credentialsService, provider, {\n tenantId: auth.tenantId as string,\n organizationId: (auth as { orgId?: string | null }).orgId ?? null,\n })\n if (!credentials) {\n return NextResponse.json(\n {\n error:\n `${provider} is not configured for this workspace yet. An administrator must add the OAuth Client ID and Secret under Integrations before mailboxes can be connected.`,\n code: 'oauth_client_not_configured',\n },\n { status: 409 },\n )\n }\n\n const redirectUri = defaultRedirectUri(req, provider)\n
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { toAbsoluteUrl } from '@open-mercato/shared/lib/url'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { getChannelAdapter } from '../../../../../lib/adapter-registry-singleton'\nimport { resolveOAuthClientCredentials } from '../../../../../lib/oauth-client-config'\nimport {\n COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME,\n COMMUNICATION_CHANNELS_OAUTH_STATE_TTL_MS,\n createOAuthState,\n DEFAULT_OAUTH_RETURN_URL,\n isSafeOAuthReturnUrl,\n normalizeOAuthReturnUrl,\n OAuthStateError,\n} from '../../../../../lib/oauth-state'\n\nconst logger = createLogger('communication_channels').child({ component: 'oauth-initiate' })\n\nexport const metadata = {\n path: '/communication_channels/oauth/[provider]/initiate',\n POST: {\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\nconst initiateBodySchema = z.object({\n channelType: z.literal('email').optional(),\n /** Where to send the user after the callback succeeds. Defaults to the profile page. */\n returnUrl: z.string().min(1).max(2048).refine(isSafeOAuthReturnUrl, {\n message: 'returnUrl must be a same-origin path',\n }).optional(),\n /** Optional pre-filled email \u2014 Google `login_hint`. */\n loginHint: z.string().email().optional(),\n})\n\ntype RouteContext = {\n params: Promise<{ provider: string }> | { provider: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string },\n ) => Promise<Record<string, unknown> | null>\n}\n\n/**\n * Default profile redirect \u2014 matches the per-user channels page registered by\n * slice 3d (the `/backend/profile/communication-channels` route).\n */\nfunction defaultRedirectUri(req: Request, providerKey: string): string {\n // Derive the origin from the configured app URL / forwarded headers rather\n // than the raw request origin, so the redirect_uri matches the value the\n // provider has registered even when the app sits behind a reverse proxy.\n return toAbsoluteUrl(req, `/api/communication_channels/oauth/${providerKey}/callback`)\n}\n\nfunction oauthStateErrorResponse(err: unknown): Response | null {\n if (err instanceof OAuthStateError) {\n if (err.code === 'missing_secret') {\n logger.error('OAuth state secret is not configured', { err })\n getTelemetryRuntime()?.reportError(err, {\n module: 'communication_channels',\n code: 'communication_channels.missing_secret',\n })\n return NextResponse.json({ error: 'OAuth is not available', code: err.code }, { status: 500 })\n }\n return NextResponse.json({ error: err.message, code: err.code }, { status: 500 })\n }\n return null\n}\n\nexport async function POST(req: Request, context: RouteContext): Promise<Response> {\n const { provider } = await context.params\n if (!/^[a-z0-9_-]+$/i.test(provider)) {\n return NextResponse.json({ error: 'Invalid provider' }, { status: 400 })\n }\n\n const adapter = getChannelAdapter(provider)\n if (!adapter) {\n return NextResponse.json(\n { error: `No ChannelAdapter for provider: ${provider}` },\n { status: 404 },\n )\n }\n if (typeof adapter.buildOAuthAuthorizeUrl !== 'function') {\n return NextResponse.json(\n { error: `Provider '${provider}' does not support OAuth (no buildOAuthAuthorizeUrl)` },\n { status: 400 },\n )\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n let body: z.infer<typeof initiateBodySchema>\n try {\n const json = await readJsonSafe(req, {})\n body = initiateBodySchema.parse(json ?? {})\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Invalid request body' },\n { status: 422 },\n )\n }\n\n const container = await createRequestContainer()\n const credentialsService = (() => {\n try {\n return container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n return null\n }\n })()\n // OAuth client credentials are tenant-level \u2014 the admin configures them under\n // the `channel_<provider>` integration in the Integrations UI (stored at\n // userId = null). A missing row means the provider has not been set up yet;\n // we surface that as an actionable error instead of handing an empty object to\n // the adapter (which would throw a cryptic Zod \"expected string\" message).\n const credentials = await resolveOAuthClientCredentials(credentialsService, provider, {\n tenantId: auth.tenantId as string,\n organizationId: (auth as { orgId?: string | null }).orgId ?? null,\n })\n if (!credentials) {\n return NextResponse.json(\n {\n error:\n `${provider} is not configured for this workspace yet. An administrator must add the OAuth Client ID and Secret under Integrations before mailboxes can be connected.`,\n code: 'oauth_client_not_configured',\n },\n { status: 409 },\n )\n }\n\n const redirectUri = defaultRedirectUri(req, provider)\n let stateEnvelope: ReturnType<typeof createOAuthState>\n try {\n stateEnvelope = createOAuthState({\n userId: auth.sub as string,\n tenantId: auth.tenantId as string,\n organizationId: (auth as { orgId?: string | null }).orgId ?? null,\n providerKey: provider,\n returnUrl: normalizeOAuthReturnUrl(body.returnUrl, DEFAULT_OAUTH_RETURN_URL),\n })\n } catch (err) {\n const response = oauthStateErrorResponse(err)\n if (response) return response\n throw err\n }\n\n let result\n try {\n result = await adapter.buildOAuthAuthorizeUrl({\n state: stateEnvelope.stateParam,\n nonce: stateEnvelope.payload.nonce,\n redirectUri,\n credentials,\n scope: {\n tenantId: auth.tenantId as string,\n organizationId:\n (auth as { orgId?: string | null }).orgId ?? (auth.tenantId as string),\n },\n loginHint: body.loginHint,\n })\n } catch (err) {\n if (err instanceof OAuthStateError) {\n return NextResponse.json({ error: err.message, code: err.code }, { status: 500 })\n }\n const message = err instanceof Error ? err.message : 'Failed to build OAuth authorize URL'\n return NextResponse.json({ error: message }, { status: 502 })\n }\n\n // If the adapter packed extras (PKCE verifier, scopes), bake them into the\n // state cookie now so the callback handler can pass them to exchangeOAuthCode.\n let finalCookie: string\n if (result.extra) {\n try {\n finalCookie = (await import('../../../../../lib/oauth-state')).encryptOAuthState({\n ...stateEnvelope.payload,\n extra: { ...(stateEnvelope.payload.extra ?? {}), ...result.extra },\n })\n } catch (err) {\n const response = oauthStateErrorResponse(err)\n if (response) return response\n throw err\n }\n } else {\n finalCookie = stateEnvelope.cookie\n }\n\n const response = NextResponse.json({ authorizeUrl: result.authorizeUrl })\n response.cookies.set({\n name: COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME,\n value: finalCookie,\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge: Math.floor(COMMUNICATION_CHANNELS_OAUTH_STATE_TTL_MS / 1000),\n })\n return response\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n POST: {\n summary: 'Start a per-user channel OAuth flow',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 200, description: 'Authorize URL + state cookie set' },\n { status: 400, description: 'Invalid provider or unsupported (no OAuth)' },\n { status: 401, description: 'Unauthorized' },\n { status: 422, description: 'Invalid request body' },\n { status: 500, description: 'OAuth state secret missing or state encryption failed' },\n { status: 502, description: 'Adapter failed to build authorize URL' },\n ],\n },\n },\n}\nexport default POST\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,yBAAyB;AAClC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,wBAAwB,EAAE,MAAM,EAAE,WAAW,iBAAiB,CAAC;AAEpF,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,MAAM;AAAA,IACJ,aAAa;AAAA,IACb,iBAAiB,CAAC,6CAA6C;AAAA,EACjE;AACF;AAEA,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,aAAa,EAAE,QAAQ,OAAO,EAAE,SAA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AQ,KAAK,MAAM,4CAA4C,GAAI;AAAA,EACrE,CAAC;AACD,SAAO;AACT;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,uBAAuB;AAAA,EAC9B,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,MAAM,CAAC,uBAAuB;AAAA,MAC9B,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,mCAAmC;AAAA,QAC/D,EAAE,QAAQ,KAAK,aAAa,6CAA6C;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,eAAe;AAAA,QAC3C,EAAE,QAAQ,KAAK,aAAa,uBAAuB;AAAA,QACnD,EAAE,QAAQ,KAAK,aAAa,wDAAwD;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,wCAAwC;AAAA,MACtE;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;",
|
|
6
|
+
"names": ["response"]
|
|
7
7
|
}
|
|
@@ -3,6 +3,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
|
|
|
3
3
|
import * as React from "react";
|
|
4
4
|
import { extensionPoints } from "@open-mercato/core/modules/communication_channels/extension-points";
|
|
5
5
|
import { getImportHistoryLimits } from "@open-mercato/core/modules/communication_channels/lib/import-history-limits";
|
|
6
|
+
import { OAUTH_RESULT_QUERY_PARAM, stripOAuthResultParams } from "@open-mercato/core/modules/communication_channels/lib/oauth-result";
|
|
6
7
|
import { useRouter, useSearchParams } from "next/navigation";
|
|
7
8
|
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
|
|
8
9
|
import { DataTable } from "@open-mercato/ui/backend/DataTable";
|
|
@@ -37,7 +38,7 @@ function ProfileCommunicationChannelsPage() {
|
|
|
37
38
|
const t = useT();
|
|
38
39
|
const router = useRouter();
|
|
39
40
|
const searchParams = useSearchParams();
|
|
40
|
-
const flashType = searchParams?.get(
|
|
41
|
+
const flashType = searchParams?.get(OAUTH_RESULT_QUERY_PARAM);
|
|
41
42
|
const flashCode = searchParams?.get("code");
|
|
42
43
|
const flashProvider = searchParams?.get("provider");
|
|
43
44
|
const [rows, setRows] = React.useState([]);
|
|
@@ -53,9 +54,10 @@ function ProfileCommunicationChannelsPage() {
|
|
|
53
54
|
const { confirm, ConfirmDialogElement } = useConfirmDialog();
|
|
54
55
|
React.useEffect(() => {
|
|
55
56
|
if (flashType === "connected") {
|
|
57
|
+
const providerLabel = flashProvider ? t(`communication_channels.channel.providers.${flashProvider}`, "") : "";
|
|
56
58
|
flash(
|
|
57
|
-
|
|
58
|
-
provider:
|
|
59
|
+
providerLabel ? t("communication_channels.profile.flash.connectedWithProvider", "Channel connected ({provider}).", {
|
|
60
|
+
provider: providerLabel
|
|
59
61
|
}) : t("communication_channels.profile.flash.connected", "Channel connected."),
|
|
60
62
|
"success"
|
|
61
63
|
);
|
|
@@ -73,13 +75,14 @@ function ProfileCommunicationChannelsPage() {
|
|
|
73
75
|
) : flashCode === "state_store_unavailable" ? t(
|
|
74
76
|
"communication_channels.profile.flash.stateStoreUnavailable",
|
|
75
77
|
"A server error prevented completing the connection. Please try again in a moment."
|
|
76
|
-
) :
|
|
77
|
-
code: flashCode
|
|
78
|
-
}) : t("communication_channels.profile.flash.error", "Failed to connect channel."),
|
|
78
|
+
) : t("communication_channels.profile.flash.error", "Failed to connect channel."),
|
|
79
79
|
"error"
|
|
80
80
|
);
|
|
81
|
+
} else {
|
|
82
|
+
return;
|
|
81
83
|
}
|
|
82
|
-
|
|
84
|
+
router.replace(stripOAuthResultParams(window.location.href), { scroll: false });
|
|
85
|
+
}, [flashType, flashCode, flashProvider, router, t]);
|
|
83
86
|
React.useEffect(() => {
|
|
84
87
|
let cancelled = false;
|
|
85
88
|
async function load() {
|
package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/communication_channels/backend/profile/communication-channels/page.tsx"],
|
|
4
|
-
"sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { extensionPoints } from '@open-mercato/core/modules/communication_channels/extension-points'\nimport { getImportHistoryLimits } from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport type { LegacyColumnDef as ColumnDef } from '@tanstack/react-table/legacy'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { DataTable } from '@open-mercato/ui/backend/DataTable'\nimport { Tag } from '@open-mercato/ui/primitives/tag'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { KbdShortcut } from '@open-mercato/ui/primitives/kbd'\nimport { RowActions, type RowActionItem } from '@open-mercato/ui/backend/RowActions'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { ConnectChannelMenu } from './ConnectChannelMenu'\n\ntype ChannelRow = {\n id: string\n providerKey: string\n channelType: string\n displayName: string\n externalIdentifier: string | null\n isPrimary: boolean\n /** `shared` = a team mailbox: teammates can read the CRM email it ingests. */\n visibility: 'private' | 'shared'\n /** Version token for the share toggle's optimistic-lock header. */\n updatedAt: string | null\n isActive: boolean\n status: 'connected' | 'requires_reauth' | 'error' | 'disconnected'\n lastError: string | null\n pollIntervalSeconds: number | null\n lastPolledAt: string | null\n /** Spec C \u2014 push delivery state (null when provider doesn't support push). */\n pushStatus: 'active' | 'inactive' | 'failed' | null\n lastPushError: { code: string | null; message: string | null; at: string | null } | null\n /**\n * `true` when the adapter declares real-time push, so the hub's poll worker\n * skips this channel entirely \u2014 inbound arrives over the provider connection.\n */\n supportsRealtimePush: boolean\n /** `true` when the adapter implements `registerPush` (Gmail-style subscriptions). */\n supportsPushRegistration: boolean\n createdAt: string | null\n}\n\nconst PROFILE_CHANNELS_MUTATION_CONTEXT_ID = 'communication-channels-profile'\nconst IMPORT_HISTORY_MUTATION_CONTEXT_ID = 'communication-channels-import-history'\nconst DISCONNECT_MUTATION_CONTEXT_ID = 'communication-channels-disconnect'\n\ntype ChannelMutationContext = {\n formId: string\n resourceKind: string\n resourceId: string\n retryLastMutation: () => Promise<boolean>\n}\n\nexport default function ProfileCommunicationChannelsPage() {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const flashType = searchParams?.get('flash')\n const flashCode = searchParams?.get('code')\n const flashProvider = searchParams?.get('provider')\n\n const [rows, setRows] = React.useState<ChannelRow[]>([])\n const [isLoading, setIsLoading] = React.useState(true)\n const [errorMessage, setErrorMessage] = React.useState<string | null>(null)\n const [reloadKey, setReloadKey] = React.useState(0)\n const [importChannel, setImportChannel] = React.useState<ChannelRow | null>(null)\n const [disconnectChannel, setDisconnectChannel] = React.useState<ChannelRow | null>(null)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n // Sharing a mailbox is privacy-consequential, so the widening direction is\n // confirmed. Escape cancels and Cmd/Ctrl+Enter submits (ConfirmDialog owns both).\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n\n React.useEffect(() => {\n if (flashType === 'connected') {\n flash(\n flashProvider\n ? t('communication_channels.profile.flash.connectedWithProvider', 'Channel connected ({provider}).', {\n provider: flashProvider,\n })\n : t('communication_channels.profile.flash.connected', 'Channel connected.'),\n 'success',\n )\n } else if (flashType === 'error') {\n flash(\n flashCode === 'oauth_client_not_configured'\n ? t(\n 'communication_channels.profile.connect.notConfigured',\n 'This provider is not configured yet. Ask an administrator to add the OAuth Client ID and Secret under Integrations before connecting a mailbox.',\n )\n : flashCode === 'mailbox_already_connected'\n ? t(\n 'communication_channels.profile.connect.mailboxAlreadyConnected',\n 'This mailbox is already connected through another provider. Disconnect it first to reconnect it with a different one.',\n )\n : flashCode === 'replay'\n ? t(\n 'communication_channels.profile.flash.replayedState',\n 'This connection link was already used \u2014 please start the connection again.',\n )\n : flashCode === 'state_store_unavailable'\n ? t(\n 'communication_channels.profile.flash.stateStoreUnavailable',\n 'A server error prevented completing the connection. Please try again in a moment.',\n )\n : flashCode\n ? t('communication_channels.profile.flash.errorWithCode', 'Failed to connect channel \u2014 {code}.', {\n code: flashCode,\n })\n : t('communication_channels.profile.flash.error', 'Failed to connect channel.'),\n 'error',\n )\n }\n }, [flashType, flashCode, flashProvider, t])\n\n React.useEffect(() => {\n let cancelled = false\n async function load() {\n setIsLoading(true)\n setErrorMessage(null)\n const response = await apiCall<{ items?: ChannelRow[] }>(\n '/api/communication_channels/me/channels',\n ).catch((err: unknown) => ({\n ok: false,\n result: { error: err instanceof Error ? err.message : 'Failed to load channels' },\n }))\n if (cancelled) return\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n setErrorMessage(\n body?.error ?? t('communication_channels.errors.loadList', 'Failed to load channels'),\n )\n setRows([])\n } else {\n const data = (response.result ?? {}) as { items?: ChannelRow[] }\n setRows(Array.isArray(data.items) ? data.items : [])\n }\n setIsLoading(false)\n }\n void load()\n return () => {\n cancelled = true\n }\n }, [reloadKey, t])\n\n const reauthRows = rows.filter((r) => r.status === 'requires_reauth')\n\n const reloadChannels = React.useCallback(() => setReloadKey((k) => k + 1), [])\n\n const onSetVisibility = React.useCallback(\n async (channel: ChannelRow, nextShared: boolean) => {\n // Only the widening direction needs a confirmation; making a mailbox\n // private again is the safe direction and stays one click.\n if (nextShared) {\n const confirmed = await confirm({\n title: t(\n 'communication_channels.profile.share.confirm.title',\n 'Share this mailbox with your team?',\n ),\n text: t(\n 'communication_channels.profile.share.confirm.text',\n 'Colleagues will be able to read the CRM email this mailbox handles, including messages already received. You stay the only person who can manage the connection, and you can stop sharing at any time.',\n ),\n confirmText: t('communication_channels.profile.share.confirm.cta', 'Share with team'),\n })\n if (!confirmed) return\n }\n\n const nextVisibility = nextShared ? 'shared' : 'private'\n let response\n try {\n response = await runMutation({\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(channel.updatedAt),\n () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/visibility`,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ visibility: nextVisibility }),\n },\n ),\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { visibility: nextVisibility },\n })\n } catch (err) {\n if (surfaceRecordConflict(err, t)) return\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n if (!response.ok) {\n if (surfaceRecordConflict(\n { status: response.status, body: response.result },\n t,\n { onRefresh: () => setReloadKey((k) => k + 1) },\n )) return\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n flash(\n nextShared\n ? t('communication_channels.profile.share.sharedSuccess', 'Mailbox shared with your team.')\n : t('communication_channels.profile.share.privateSuccess', 'Mailbox is private again.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [runMutation, retryLastMutation, confirm, t],\n )\n\n const onSetPrimary = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/set-primary`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { isPrimary: true },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'),\n 'error',\n )\n return\n }\n flash(\n t('communication_channels.profile.actions.setPrimarySuccess', 'Marked as primary.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onRegisterPush = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ pushStatus?: string; error?: { code: string; message: string } }>(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/push/register`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'push-register' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.push.button.reregister', 'Re-register push'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(body?.error ?? t('communication_channels.push.flash.registerFailed', 'Failed to register push'), 'error')\n return\n }\n const result = (response.result ?? {}) as { pushStatus?: string }\n if (result.pushStatus === 'active') {\n flash(t('communication_channels.push.status.active', 'Push active'), 'success')\n } else {\n flash(\n t(\n 'communication_channels.push.status.failed',\n 'Push registration returned a non-active status \u2014 falling back to polling.',\n ),\n 'error',\n )\n }\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onPollNow = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/poll-now`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'poll-now' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.pollNowSuccess',\n 'Poll triggered \u2014 new messages will appear on linked Person timelines in a few seconds.',\n ),\n 'success',\n )\n // Give the worker a moment to fetch + ingest, then refetch our channel list\n // so `lastPolledAt` updates in the UI.\n setTimeout(() => setReloadKey((k) => k + 1), 1500)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const columns = React.useMemo<ColumnDef<ChannelRow>[]>(\n () => [\n {\n header: t('communication_channels.columns.displayName', 'Channel'),\n accessorKey: 'displayName',\n },\n {\n header: t('communication_channels.columns.provider', 'Provider'),\n accessorKey: 'providerKey',\n cell: ({ row }) => (\n <Tag variant=\"info\">\n {t(\n `communication_channels.channel.providers.${row.original.providerKey}`,\n row.original.providerKey,\n )}\n </Tag>\n ),\n },\n {\n header: t('communication_channels.columns.identifier', 'Email / username'),\n accessorKey: 'externalIdentifier',\n cell: ({ row }) => row.original.externalIdentifier ?? '\u2014',\n meta: { truncate: true, maxWidth: 240 },\n },\n {\n header: t('communication_channels.profile.columns.primary', 'Primary'),\n accessorKey: 'isPrimary',\n // Status only \u2014 \"Set as primary\" lives in the row actions menu.\n cell: ({ row }) =>\n row.original.isPrimary ? (\n <Tag variant=\"success\" dot>\n {t('communication_channels.profile.primary', 'Primary')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ),\n },\n {\n header: t('communication_channels.profile.columns.sharing', 'Team access'),\n accessorKey: 'visibility',\n // Status only \u2014 the share/unshare flip lives in the row actions menu.\n //\n // Only email ingestion writes customer_interactions, so on an SMS or push\n // channel a share would flip the flag and flash success while changing\n // nothing anyone can observe. The menu applies the same email-only rule.\n cell: ({ row }) =>\n row.original.channelType !== 'email' ? (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ) : row.original.visibility === 'shared' ? (\n <Tag variant=\"info\" dot>\n {t('communication_channels.profile.share.shared', 'Shared')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.profile.share.private', 'Only you')}\n </span>\n ),\n },\n {\n header: t('communication_channels.columns.status', 'Status'),\n accessorKey: 'status',\n cell: ({ row }) => statusTag(row.original.status, t),\n },\n {\n id: 'pushStatus',\n // Its own key: sharing `push.status.active` made the header render\n // \"Push active\" over a column whose rows say \"Polling only\" (#4980).\n header: t('communication_channels.profile.columns.push', 'Push'),\n cell: ({ row }) => {\n const ps = row.original.pushStatus\n const errorTitle = row.original.lastPushError?.message ?? undefined\n // Derived from the adapter's declared capabilities, never from the\n // provider name: `supportsPushRegistration` means push subscriptions\n // can be (re-)registered from here, `supportsRealtimePush` means the\n // hub's poll worker skips the channel because the provider connection\n // delivers inbound itself (#4980).\n if (!row.original.supportsPushRegistration) {\n if (!row.original.supportsRealtimePush) {\n return (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.pushDrivenFailed', 'Push connection failed')}\n </Tag>\n )\n }\n // The \"why is there no Poll now action?\" explanation used to live on\n // the disabled Sync button's aria-label. That button is gone, so the\n // reason moves here rather than being lost.\n return (\n <Tag\n variant=\"success\"\n dot\n title={t(\n 'communication_channels.profile.actions.pollNowPushDriven',\n 'This channel is push-driven \u2014 inbound messages arrive over the provider connection, so polling does not apply.',\n )}\n >\n {t('communication_channels.push.status.pushDriven', 'Push-driven')}\n </Tag>\n )\n }\n if (ps === 'active') {\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.push.status.active', 'Push active')}\n </Tag>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.failed', 'Push failed \u2014 using polling')}\n </Tag>\n )\n }\n // null or 'inactive' \u2014 the provider can register push but has not yet.\n // Only a hub-polled channel falls back to polling meanwhile; for a\n // push-driven one nothing is delivering inbound at all, so claiming\n // \"Polling only\" would repeat the defect this issue is about (#4980).\n return (\n <span className=\"text-xs text-muted-foreground\">\n {row.original.supportsRealtimePush\n ? t('communication_channels.push.status.notRegistered', 'Push not registered')\n : t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n },\n },\n {\n header: t('communication_channels.profile.columns.lastPolled', 'Last synced'),\n accessorKey: 'lastPolledAt',\n cell: ({ row }) =>\n row.original.lastPolledAt\n ? new Date(row.original.lastPolledAt).toLocaleString()\n : '\u2014',\n },\n ],\n [t],\n )\n\n /**\n * Every per-row action, in one menu. The table previously carried five action\n * columns, which pushed the row past the viewport and clipped the trailing\n * buttons.\n *\n * Passed as DataTable's `rowActions` rather than as a hand-rolled column so the\n * table can merge row actions injected by other modules into this same menu\n * (`extensionTableId` below) instead of rendering a second one, and so the\n * actions cell keeps the table's own header, alignment and sticky behaviour.\n *\n * `RowActionItem` has no disabled state, so an unavailable action is OMITTED\n * rather than greyed out. The reason stays visible in the row: the Status and\n * Push columns already say why a channel cannot be polled or needs reconnecting.\n */\n const rowActions = React.useCallback(\n (channel: ChannelRow) => {\n const items: RowActionItem[] = []\n\n if (!channel.isPrimary) {\n items.push({\n id: 'set-primary',\n label: t('communication_channels.profile.actions.setPrimary', 'Set as primary'),\n onSelect: () => { void onSetPrimary(channel.id) },\n })\n }\n\n // Email only, for the reason the Team access column documents: on a\n // non-email channel the flip would change nothing anyone can observe.\n if (channel.channelType === 'email') {\n items.push(\n channel.visibility === 'shared'\n ? {\n id: 'make-private',\n label: t('communication_channels.profile.share.makePrivate', 'Make private'),\n onSelect: () => { void onSetVisibility(channel, false) },\n }\n : {\n id: 'share-with-team',\n label: t('communication_channels.profile.share.shareCta', 'Share with team'),\n onSelect: () => { void onSetVisibility(channel, true) },\n },\n )\n }\n\n // Offered only when the adapter can register push AND it is not already\n // active \u2014 re-registering a healthy subscription is a no-op.\n if (channel.supportsPushRegistration && channel.pushStatus !== 'active') {\n items.push({\n id: 'register-push',\n label: t('communication_channels.push.button.reregister', 'Re-register push'),\n onSelect: () => { void onRegisterPush(channel.id) },\n })\n }\n\n // Same eligibility the History column enforced.\n if (channel.isActive && channel.status === 'connected' && channel.channelType === 'email') {\n items.push({\n id: 'import-history',\n label: t('communication_channels.profile.actions.importHistory', 'Import history'),\n onSelect: () => setImportChannel(channel),\n })\n }\n\n // Same eligibility the Sync column enforced: allowed from 'connected'\n // AND 'error' (so a stuck channel can be recovered without a\n // reconnect), never for a push-driven channel the worker skips (#4980).\n const pollable =\n channel.isActive &&\n !channel.supportsRealtimePush &&\n (channel.status === 'connected' || channel.status === 'error')\n if (pollable) {\n items.push({\n id: 'poll-now',\n label:\n channel.status === 'error'\n ? t('communication_channels.profile.actions.retryPoll', 'Retry')\n : t('communication_channels.profile.actions.pollNow', 'Poll now'),\n onSelect: () => { void onPollNow(channel.id) },\n })\n }\n\n items.push({\n id: 'disconnect',\n label: t('communication_channels.profile.actions.disconnect', 'Disconnect'),\n destructive: true,\n onSelect: () => setDisconnectChannel(channel),\n })\n\n return <RowActions items={items} />\n },\n [onSetPrimary, onSetVisibility, onPollNow, onRegisterPush, t],\n )\n\n return (\n <Page>\n <PageBody>\n <header className=\"mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4\">\n <div className=\"min-w-0\">\n <h1 className=\"text-2xl font-semibold\">\n {t('communication_channels.profile.title', 'My communication channels')}\n </h1>\n <p className=\"text-sm text-muted-foreground\">\n {t(\n 'communication_channels.profile.subtitle',\n 'Connect your communication channels so outbound messages come from your own account and inbound messages land in your unified inbox.',\n )}\n </p>\n </div>\n {/* Provider connect entry points injected by each channel-* package\n (channel-gmail, channel-imap) via UMES. They stack inside one\n dropdown so the header does not widen per installed provider. */}\n <ConnectChannelMenu onConnected={reloadChannels} />\n </header>\n\n {reauthRows.length > 0 ? (\n <Alert status=\"warning\" className=\"mb-4\">\n <AlertDescription>\n {t(\n 'communication_channels.profile.alerts.requiresReauth',\n '{count} channel(s) need reconnection. Click \"Reconnect\" on the affected channel below.',\n { count: reauthRows.length },\n )}\n </AlertDescription>\n </Alert>\n ) : null}\n\n <DataTable<ChannelRow>\n title={t('communication_channels.profile.tableTitle', 'Your channels')}\n titleHeadingLevel={2}\n extensionTableId={extensionPoints.hosts.profileChannelsTable.tableId}\n columns={columns}\n rowActions={rowActions}\n // Pinned because this table is wider than a laptop viewport: at 1280px\n // the row runs out well before the actions cell, and since Primary,\n // Team access and Push are status-only there is no other control in\n // view. Unpinned, reaching \u22EF meant scrolling to the far end, which\n // scrolls the Channel column away \u2014 so you could no longer see which\n // channel the open menu belonged to (#6717).\n stickyActionsColumn\n data={rows}\n isLoading={isLoading}\n error={errorMessage}\n emptyState={t(\n 'communication_channels.profile.empty',\n 'You have no connected channels yet. Add one using the menu at the top of this page.',\n )}\n />\n <ImportHistoryDialog\n channel={importChannel}\n onClose={() => setImportChannel(null)}\n onQueued={() => {\n setImportChannel(null)\n router.refresh()\n }}\n />\n <DisconnectChannelDialog\n channel={disconnectChannel}\n onClose={() => setDisconnectChannel(null)}\n onDisconnected={() => {\n setDisconnectChannel(null)\n setReloadKey((k) => k + 1)\n }}\n />\n {ConfirmDialogElement}\n </PageBody>\n </Page>\n )\n}\n\ntype ImportHistoryDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onQueued: () => void\n}\n\nfunction ImportHistoryDialog({ channel, onClose, onQueued }: ImportHistoryDialogProps): React.JSX.Element {\n const t = useT()\n const importLimits = React.useMemo(() => getImportHistoryLimits(channel?.providerKey), [channel?.providerKey])\n const [sinceDays, setSinceDays] = React.useState('30')\n const [contactEmails, setContactEmails] = React.useState('')\n const [maxMessages, setMaxMessages] = React.useState('500')\n const [fieldErrors, setFieldErrors] = React.useState<Record<string, string>>({})\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) {\n setSinceDays('30')\n setContactEmails('')\n setMaxMessages('500')\n setFieldErrors({})\n setSubmitting(false)\n }\n }, [channel?.id])\n\n const handleSubmit = React.useCallback(async () => {\n if (!channel || submitting) return\n const sinceNum = Number.parseInt(sinceDays, 10)\n const maxNum = Number.parseInt(maxMessages, 10)\n const errors: Record<string, string> = {}\n if (!Number.isFinite(sinceNum) || sinceNum < 1 || sinceNum > importLimits.maxSinceDays) {\n errors.sinceDays = t(\n 'communication_channels.profile.importHistory.errors.sinceDays',\n 'Choose a number between 1 and {max} days.',\n { max: importLimits.maxSinceDays },\n )\n }\n if (!Number.isFinite(maxNum) || maxNum < 1 || maxNum > importLimits.maxMessages) {\n errors.maxMessages = t(\n 'communication_channels.profile.importHistory.errors.maxMessages',\n 'Choose a number between 1 and {max} messages.',\n { max: importLimits.maxMessages },\n )\n }\n const parsedEmails = contactEmails\n .split(/[\\s,;]+/)\n .map((s) => s.trim())\n .filter(Boolean)\n if (parsedEmails.length > 0 && parsedEmails.some((s) => !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s))) {\n errors.contactEmails = t(\n 'communication_channels.profile.importHistory.errors.contactEmails',\n 'One or more entries is not a valid email address.',\n )\n }\n if (Object.keys(errors).length > 0) {\n setFieldErrors(errors)\n return\n }\n setFieldErrors({})\n setSubmitting(true)\n const mutationPayload = {\n sinceDays: sinceNum,\n maxMessages: maxNum,\n ...(parsedEmails.length > 0 ? { contactEmails: parsedEmails } : {}),\n }\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ progressJobId?: string }>(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/import-history`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(mutationPayload),\n },\n ),\n context: {\n formId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload,\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.importHistory.flash.error', 'Failed to queue history import.'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string; fieldErrors?: Record<string, string> } | undefined\n if (body?.fieldErrors && Object.keys(body.fieldErrors).length > 0) {\n setFieldErrors(body.fieldErrors)\n return\n }\n flash(\n body?.error ??\n t(\n 'communication_channels.profile.importHistory.flash.error',\n 'Failed to queue history import.',\n ),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.importHistory.flash.success',\n 'History import queued \u2014 track progress in the top bar.',\n ),\n 'success',\n )\n onQueued()\n }, [channel, sinceDays, maxMessages, contactEmails, submitting, t, onQueued, retryLastMutation, runMutation, importLimits])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleSubmit()\n }\n },\n [handleSubmit],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.importHistory.title', 'Import channel history')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.importHistory.description',\n 'Pull older messages this channel never observed at connect-time. Filters narrow the search server-side.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-since\">\n {t('communication_channels.profile.importHistory.fields.sinceDays', 'Look back (days)')}\n </Label>\n <Input\n id=\"import-history-since\"\n type=\"number\"\n min={1}\n max={importLimits.maxSinceDays}\n value={sinceDays}\n onChange={(e) => setSinceDays(e.target.value)}\n aria-invalid={Boolean(fieldErrors.sinceDays)}\n />\n {fieldErrors.sinceDays ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.sinceDays}</p>\n ) : null}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-emails\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmails',\n 'Filter by sender (optional)',\n )}\n </Label>\n <Textarea\n id=\"import-history-emails\"\n rows={3}\n value={contactEmails}\n onChange={(e) => setContactEmails(e.target.value)}\n placeholder={t(\n 'communication_channels.profile.importHistory.fields.contactEmailsPlaceholder',\n 'alice@example.com, bob@example.com',\n )}\n aria-invalid={Boolean(fieldErrors.contactEmails)}\n />\n {fieldErrors.contactEmails ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.contactEmails}</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmailsHint',\n 'Leave empty to scan all senders in the window.',\n )}\n </p>\n )}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-max\">\n {t('communication_channels.profile.importHistory.fields.maxMessages', 'Maximum messages')}\n </Label>\n <Input\n id=\"import-history-max\"\n type=\"number\"\n min={1}\n max={importLimits.maxMessages}\n value={maxMessages}\n onChange={(e) => setMaxMessages(e.target.value)}\n aria-invalid={Boolean(fieldErrors.maxMessages)}\n />\n {fieldErrors.maxMessages ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.maxMessages}</p>\n ) : null}\n </div>\n\n {fieldErrors.channelId ? (\n <Alert status=\"warning\">\n <AlertDescription>{fieldErrors.channelId}</AlertDescription>\n </Alert>\n ) : null}\n </div>\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.importHistory.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" onClick={() => void handleSubmit()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.importHistory.submitting', 'Queueing\u2026')\n : t('communication_channels.profile.importHistory.submit', 'Start import')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\ntype DisconnectChannelDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onDisconnected: () => void\n}\n\nfunction DisconnectChannelDialog({\n channel,\n onClose,\n onDisconnected,\n}: DisconnectChannelDialogProps): React.JSX.Element {\n const t = useT()\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: DISCONNECT_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) setSubmitting(false)\n }, [channel?.id])\n\n const handleConfirm = React.useCallback(async () => {\n if (!channel || submitting) return\n setSubmitting(true)\n let response\n try {\n response = await runMutation({\n // optimistic-lock-exempt: self-service connect/disconnect of the\n // signed-in operator's OWN communication channel (an integration link),\n // not a shared multi-editor record. Disconnect is a terminal action\n // keyed by channel id; there is no concurrent-edit lost-update window to\n // guard, and the row carries no client-surfaced `updatedAt` round-trip.\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}`,\n { method: 'DELETE' },\n ),\n context: {\n formId: DISCONNECT_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { action: 'disconnect' },\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ??\n t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.disconnectSuccess',\n 'Channel disconnected. You can reconnect it anytime.',\n ),\n 'success',\n )\n onDisconnected()\n }, [channel, submitting, runMutation, retryLastMutation, t, onDisconnected])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleConfirm()\n }\n },\n [handleConfirm],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.disconnect.title', 'Disconnect channel')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.disconnect.description',\n 'This removes the connection and stops syncing. Emails already imported stay on your timelines. You can reconnect anytime.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n {channel ? (\n <p className=\"text-sm font-medium\">{channel.externalIdentifier ?? channel.displayName}</p>\n ) : null}\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.disconnect.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" variant=\"destructive-solid\" onClick={() => void handleConfirm()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.disconnect.submitting', 'Disconnecting\u2026')\n : t('communication_channels.profile.disconnect.confirm', 'Disconnect')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction statusTag(\n status: ChannelRow['status'],\n t: (key: string, fallback?: string) => string,\n): React.ReactNode {\n switch (status) {\n case 'connected':\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.status.connected', 'Connected')}\n </Tag>\n )\n case 'requires_reauth':\n return (\n <Tag variant=\"warning\" dot>\n {t('communication_channels.status.requiresReauth', 'Needs reconnection')}\n </Tag>\n )\n case 'error':\n return (\n <Tag variant=\"error\" dot>\n {t('communication_channels.status.error', 'Error')}\n </Tag>\n )\n case 'disconnected':\n return <Tag variant=\"neutral\">{t('communication_channels.status.disconnected', 'Disconnected')}</Tag>\n default:\n return <Tag variant=\"neutral\">{status}</Tag>\n }\n}\n"],
|
|
5
|
-
"mappings": ";AA8XU,cAyOA,YAzOA;AA5XV,YAAY,WAAW;AACvB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AAEvC,SAAS,WAAW,uBAAuB;AAC3C,SAAS,MAAM,gBAAgB;AAC/B,SAAS,iBAAiB;AAC1B,SAAS,WAAW;AACpB,SAAS,cAAc;AACvB,SAAS,OAAO,wBAAwB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa;AACtB,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,kBAAsC;AAC/C,SAAS,SAAS,mCAAmC;AACrD,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,0BAA0B;AA+BnC,MAAM,uCAAuC;AAC7C,MAAM,qCAAqC;AAC3C,MAAM,iCAAiC;AASxB,SAAR,mCAAoD;AACzD,QAAM,IAAI,KAAK;AACf,QAAM,SAAS,UAAU;AACzB,QAAM,eAAe,gBAAgB;AACrC,QAAM,YAAY,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,GAAG,GACrC;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,SAAS,UAAU,YACjE,YAAE,oDAAoD,QAAQ,GACjE;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,qBAAoB,SAAS,MAAM,KAAK,cAAc,GAAG,UAAU,YAC9F,uBACG,EAAE,wDAAwD,qBAAgB,IAC1E,EAAE,qDAAqD,YAAY,GACzE;AAAA,OACF;AAAA,KACF,GACF;AAEJ;AAEA,SAAS,UACP,QACA,GACiB;AACjB,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,WAAU,KAAG,MACvB,YAAE,2CAA2C,WAAW,GAC3D;AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,WAAU,KAAG,MACvB,YAAE,gDAAgD,oBAAoB,GACzE;AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,SAAQ,KAAG,MACrB,YAAE,uCAAuC,OAAO,GACnD;AAAA,IAEJ,KAAK;AACH,aAAO,oBAAC,OAAI,SAAQ,WAAW,YAAE,8CAA8C,cAAc,GAAE;AAAA,IACjG;AACE,aAAO,oBAAC,OAAI,SAAQ,WAAW,kBAAO;AAAA,EAC1C;AACF;",
|
|
4
|
+
"sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { extensionPoints } from '@open-mercato/core/modules/communication_channels/extension-points'\nimport { getImportHistoryLimits } from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport { OAUTH_RESULT_QUERY_PARAM, stripOAuthResultParams } from '@open-mercato/core/modules/communication_channels/lib/oauth-result'\nimport type { LegacyColumnDef as ColumnDef } from '@tanstack/react-table/legacy'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { DataTable } from '@open-mercato/ui/backend/DataTable'\nimport { Tag } from '@open-mercato/ui/primitives/tag'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { KbdShortcut } from '@open-mercato/ui/primitives/kbd'\nimport { RowActions, type RowActionItem } from '@open-mercato/ui/backend/RowActions'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { ConnectChannelMenu } from './ConnectChannelMenu'\n\ntype ChannelRow = {\n id: string\n providerKey: string\n channelType: string\n displayName: string\n externalIdentifier: string | null\n isPrimary: boolean\n /** `shared` = a team mailbox: teammates can read the CRM email it ingests. */\n visibility: 'private' | 'shared'\n /** Version token for the share toggle's optimistic-lock header. */\n updatedAt: string | null\n isActive: boolean\n status: 'connected' | 'requires_reauth' | 'error' | 'disconnected'\n lastError: string | null\n pollIntervalSeconds: number | null\n lastPolledAt: string | null\n /** Spec C \u2014 push delivery state (null when provider doesn't support push). */\n pushStatus: 'active' | 'inactive' | 'failed' | null\n lastPushError: { code: string | null; message: string | null; at: string | null } | null\n /**\n * `true` when the adapter declares real-time push, so the hub's poll worker\n * skips this channel entirely \u2014 inbound arrives over the provider connection.\n */\n supportsRealtimePush: boolean\n /** `true` when the adapter implements `registerPush` (Gmail-style subscriptions). */\n supportsPushRegistration: boolean\n createdAt: string | null\n}\n\nconst PROFILE_CHANNELS_MUTATION_CONTEXT_ID = 'communication-channels-profile'\nconst IMPORT_HISTORY_MUTATION_CONTEXT_ID = 'communication-channels-import-history'\nconst DISCONNECT_MUTATION_CONTEXT_ID = 'communication-channels-disconnect'\n\ntype ChannelMutationContext = {\n formId: string\n resourceKind: string\n resourceId: string\n retryLastMutation: () => Promise<boolean>\n}\n\nexport default function ProfileCommunicationChannelsPage() {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const flashType = searchParams?.get(OAUTH_RESULT_QUERY_PARAM)\n const flashCode = searchParams?.get('code')\n const flashProvider = searchParams?.get('provider')\n\n const [rows, setRows] = React.useState<ChannelRow[]>([])\n const [isLoading, setIsLoading] = React.useState(true)\n const [errorMessage, setErrorMessage] = React.useState<string | null>(null)\n const [reloadKey, setReloadKey] = React.useState(0)\n const [importChannel, setImportChannel] = React.useState<ChannelRow | null>(null)\n const [disconnectChannel, setDisconnectChannel] = React.useState<ChannelRow | null>(null)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n // Sharing a mailbox is privacy-consequential, so the widening direction is\n // confirmed. Escape cancels and Cmd/Ctrl+Enter submits (ConfirmDialog owns both).\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n\n React.useEffect(() => {\n if (flashType === 'connected') {\n const providerLabel = flashProvider\n ? t(`communication_channels.channel.providers.${flashProvider}`, '')\n : ''\n flash(\n providerLabel\n ? t('communication_channels.profile.flash.connectedWithProvider', 'Channel connected ({provider}).', {\n provider: providerLabel,\n })\n : t('communication_channels.profile.flash.connected', 'Channel connected.'),\n 'success',\n )\n } else if (flashType === 'error') {\n flash(\n flashCode === 'oauth_client_not_configured'\n ? t(\n 'communication_channels.profile.connect.notConfigured',\n 'This provider is not configured yet. Ask an administrator to add the OAuth Client ID and Secret under Integrations before connecting a mailbox.',\n )\n : flashCode === 'mailbox_already_connected'\n ? t(\n 'communication_channels.profile.connect.mailboxAlreadyConnected',\n 'This mailbox is already connected through another provider. Disconnect it first to reconnect it with a different one.',\n )\n : flashCode === 'replay'\n ? t(\n 'communication_channels.profile.flash.replayedState',\n 'This connection link was already used \u2014 please start the connection again.',\n )\n : flashCode === 'state_store_unavailable'\n ? t(\n 'communication_channels.profile.flash.stateStoreUnavailable',\n 'A server error prevented completing the connection. Please try again in a moment.',\n )\n : t('communication_channels.profile.flash.error', 'Failed to connect channel.'),\n 'error',\n )\n } else {\n return\n }\n router.replace(stripOAuthResultParams(window.location.href), { scroll: false })\n }, [flashType, flashCode, flashProvider, router, t])\n\n React.useEffect(() => {\n let cancelled = false\n async function load() {\n setIsLoading(true)\n setErrorMessage(null)\n const response = await apiCall<{ items?: ChannelRow[] }>(\n '/api/communication_channels/me/channels',\n ).catch((err: unknown) => ({\n ok: false,\n result: { error: err instanceof Error ? err.message : 'Failed to load channels' },\n }))\n if (cancelled) return\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n setErrorMessage(\n body?.error ?? t('communication_channels.errors.loadList', 'Failed to load channels'),\n )\n setRows([])\n } else {\n const data = (response.result ?? {}) as { items?: ChannelRow[] }\n setRows(Array.isArray(data.items) ? data.items : [])\n }\n setIsLoading(false)\n }\n void load()\n return () => {\n cancelled = true\n }\n }, [reloadKey, t])\n\n const reauthRows = rows.filter((r) => r.status === 'requires_reauth')\n\n const reloadChannels = React.useCallback(() => setReloadKey((k) => k + 1), [])\n\n const onSetVisibility = React.useCallback(\n async (channel: ChannelRow, nextShared: boolean) => {\n // Only the widening direction needs a confirmation; making a mailbox\n // private again is the safe direction and stays one click.\n if (nextShared) {\n const confirmed = await confirm({\n title: t(\n 'communication_channels.profile.share.confirm.title',\n 'Share this mailbox with your team?',\n ),\n text: t(\n 'communication_channels.profile.share.confirm.text',\n 'Colleagues will be able to read the CRM email this mailbox handles, including messages already received. You stay the only person who can manage the connection, and you can stop sharing at any time.',\n ),\n confirmText: t('communication_channels.profile.share.confirm.cta', 'Share with team'),\n })\n if (!confirmed) return\n }\n\n const nextVisibility = nextShared ? 'shared' : 'private'\n let response\n try {\n response = await runMutation({\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(channel.updatedAt),\n () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/visibility`,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ visibility: nextVisibility }),\n },\n ),\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { visibility: nextVisibility },\n })\n } catch (err) {\n if (surfaceRecordConflict(err, t)) return\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n if (!response.ok) {\n if (surfaceRecordConflict(\n { status: response.status, body: response.result },\n t,\n { onRefresh: () => setReloadKey((k) => k + 1) },\n )) return\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n flash(\n nextShared\n ? t('communication_channels.profile.share.sharedSuccess', 'Mailbox shared with your team.')\n : t('communication_channels.profile.share.privateSuccess', 'Mailbox is private again.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [runMutation, retryLastMutation, confirm, t],\n )\n\n const onSetPrimary = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/set-primary`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { isPrimary: true },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'),\n 'error',\n )\n return\n }\n flash(\n t('communication_channels.profile.actions.setPrimarySuccess', 'Marked as primary.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onRegisterPush = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ pushStatus?: string; error?: { code: string; message: string } }>(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/push/register`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'push-register' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.push.button.reregister', 'Re-register push'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(body?.error ?? t('communication_channels.push.flash.registerFailed', 'Failed to register push'), 'error')\n return\n }\n const result = (response.result ?? {}) as { pushStatus?: string }\n if (result.pushStatus === 'active') {\n flash(t('communication_channels.push.status.active', 'Push active'), 'success')\n } else {\n flash(\n t(\n 'communication_channels.push.status.failed',\n 'Push registration returned a non-active status \u2014 falling back to polling.',\n ),\n 'error',\n )\n }\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onPollNow = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/poll-now`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'poll-now' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.pollNowSuccess',\n 'Poll triggered \u2014 new messages will appear on linked Person timelines in a few seconds.',\n ),\n 'success',\n )\n // Give the worker a moment to fetch + ingest, then refetch our channel list\n // so `lastPolledAt` updates in the UI.\n setTimeout(() => setReloadKey((k) => k + 1), 1500)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const columns = React.useMemo<ColumnDef<ChannelRow>[]>(\n () => [\n {\n header: t('communication_channels.columns.displayName', 'Channel'),\n accessorKey: 'displayName',\n },\n {\n header: t('communication_channels.columns.provider', 'Provider'),\n accessorKey: 'providerKey',\n cell: ({ row }) => (\n <Tag variant=\"info\">\n {t(\n `communication_channels.channel.providers.${row.original.providerKey}`,\n row.original.providerKey,\n )}\n </Tag>\n ),\n },\n {\n header: t('communication_channels.columns.identifier', 'Email / username'),\n accessorKey: 'externalIdentifier',\n cell: ({ row }) => row.original.externalIdentifier ?? '\u2014',\n meta: { truncate: true, maxWidth: 240 },\n },\n {\n header: t('communication_channels.profile.columns.primary', 'Primary'),\n accessorKey: 'isPrimary',\n // Status only \u2014 \"Set as primary\" lives in the row actions menu.\n cell: ({ row }) =>\n row.original.isPrimary ? (\n <Tag variant=\"success\" dot>\n {t('communication_channels.profile.primary', 'Primary')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ),\n },\n {\n header: t('communication_channels.profile.columns.sharing', 'Team access'),\n accessorKey: 'visibility',\n // Status only \u2014 the share/unshare flip lives in the row actions menu.\n //\n // Only email ingestion writes customer_interactions, so on an SMS or push\n // channel a share would flip the flag and flash success while changing\n // nothing anyone can observe. The menu applies the same email-only rule.\n cell: ({ row }) =>\n row.original.channelType !== 'email' ? (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ) : row.original.visibility === 'shared' ? (\n <Tag variant=\"info\" dot>\n {t('communication_channels.profile.share.shared', 'Shared')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.profile.share.private', 'Only you')}\n </span>\n ),\n },\n {\n header: t('communication_channels.columns.status', 'Status'),\n accessorKey: 'status',\n cell: ({ row }) => statusTag(row.original.status, t),\n },\n {\n id: 'pushStatus',\n // Its own key: sharing `push.status.active` made the header render\n // \"Push active\" over a column whose rows say \"Polling only\" (#4980).\n header: t('communication_channels.profile.columns.push', 'Push'),\n cell: ({ row }) => {\n const ps = row.original.pushStatus\n const errorTitle = row.original.lastPushError?.message ?? undefined\n // Derived from the adapter's declared capabilities, never from the\n // provider name: `supportsPushRegistration` means push subscriptions\n // can be (re-)registered from here, `supportsRealtimePush` means the\n // hub's poll worker skips the channel because the provider connection\n // delivers inbound itself (#4980).\n if (!row.original.supportsPushRegistration) {\n if (!row.original.supportsRealtimePush) {\n return (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.pushDrivenFailed', 'Push connection failed')}\n </Tag>\n )\n }\n // The \"why is there no Poll now action?\" explanation used to live on\n // the disabled Sync button's aria-label. That button is gone, so the\n // reason moves here rather than being lost.\n return (\n <Tag\n variant=\"success\"\n dot\n title={t(\n 'communication_channels.profile.actions.pollNowPushDriven',\n 'This channel is push-driven \u2014 inbound messages arrive over the provider connection, so polling does not apply.',\n )}\n >\n {t('communication_channels.push.status.pushDriven', 'Push-driven')}\n </Tag>\n )\n }\n if (ps === 'active') {\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.push.status.active', 'Push active')}\n </Tag>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.failed', 'Push failed \u2014 using polling')}\n </Tag>\n )\n }\n // null or 'inactive' \u2014 the provider can register push but has not yet.\n // Only a hub-polled channel falls back to polling meanwhile; for a\n // push-driven one nothing is delivering inbound at all, so claiming\n // \"Polling only\" would repeat the defect this issue is about (#4980).\n return (\n <span className=\"text-xs text-muted-foreground\">\n {row.original.supportsRealtimePush\n ? t('communication_channels.push.status.notRegistered', 'Push not registered')\n : t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n },\n },\n {\n header: t('communication_channels.profile.columns.lastPolled', 'Last synced'),\n accessorKey: 'lastPolledAt',\n cell: ({ row }) =>\n row.original.lastPolledAt\n ? new Date(row.original.lastPolledAt).toLocaleString()\n : '\u2014',\n },\n ],\n [t],\n )\n\n /**\n * Every per-row action, in one menu. The table previously carried five action\n * columns, which pushed the row past the viewport and clipped the trailing\n * buttons.\n *\n * Passed as DataTable's `rowActions` rather than as a hand-rolled column so the\n * table can merge row actions injected by other modules into this same menu\n * (`extensionTableId` below) instead of rendering a second one, and so the\n * actions cell keeps the table's own header, alignment and sticky behaviour.\n *\n * `RowActionItem` has no disabled state, so an unavailable action is OMITTED\n * rather than greyed out. The reason stays visible in the row: the Status and\n * Push columns already say why a channel cannot be polled or needs reconnecting.\n */\n const rowActions = React.useCallback(\n (channel: ChannelRow) => {\n const items: RowActionItem[] = []\n\n if (!channel.isPrimary) {\n items.push({\n id: 'set-primary',\n label: t('communication_channels.profile.actions.setPrimary', 'Set as primary'),\n onSelect: () => { void onSetPrimary(channel.id) },\n })\n }\n\n // Email only, for the reason the Team access column documents: on a\n // non-email channel the flip would change nothing anyone can observe.\n if (channel.channelType === 'email') {\n items.push(\n channel.visibility === 'shared'\n ? {\n id: 'make-private',\n label: t('communication_channels.profile.share.makePrivate', 'Make private'),\n onSelect: () => { void onSetVisibility(channel, false) },\n }\n : {\n id: 'share-with-team',\n label: t('communication_channels.profile.share.shareCta', 'Share with team'),\n onSelect: () => { void onSetVisibility(channel, true) },\n },\n )\n }\n\n // Offered only when the adapter can register push AND it is not already\n // active \u2014 re-registering a healthy subscription is a no-op.\n if (channel.supportsPushRegistration && channel.pushStatus !== 'active') {\n items.push({\n id: 'register-push',\n label: t('communication_channels.push.button.reregister', 'Re-register push'),\n onSelect: () => { void onRegisterPush(channel.id) },\n })\n }\n\n // Same eligibility the History column enforced.\n if (channel.isActive && channel.status === 'connected' && channel.channelType === 'email') {\n items.push({\n id: 'import-history',\n label: t('communication_channels.profile.actions.importHistory', 'Import history'),\n onSelect: () => setImportChannel(channel),\n })\n }\n\n // Same eligibility the Sync column enforced: allowed from 'connected'\n // AND 'error' (so a stuck channel can be recovered without a\n // reconnect), never for a push-driven channel the worker skips (#4980).\n const pollable =\n channel.isActive &&\n !channel.supportsRealtimePush &&\n (channel.status === 'connected' || channel.status === 'error')\n if (pollable) {\n items.push({\n id: 'poll-now',\n label:\n channel.status === 'error'\n ? t('communication_channels.profile.actions.retryPoll', 'Retry')\n : t('communication_channels.profile.actions.pollNow', 'Poll now'),\n onSelect: () => { void onPollNow(channel.id) },\n })\n }\n\n items.push({\n id: 'disconnect',\n label: t('communication_channels.profile.actions.disconnect', 'Disconnect'),\n destructive: true,\n onSelect: () => setDisconnectChannel(channel),\n })\n\n return <RowActions items={items} />\n },\n [onSetPrimary, onSetVisibility, onPollNow, onRegisterPush, t],\n )\n\n return (\n <Page>\n <PageBody>\n <header className=\"mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4\">\n <div className=\"min-w-0\">\n <h1 className=\"text-2xl font-semibold\">\n {t('communication_channels.profile.title', 'My communication channels')}\n </h1>\n <p className=\"text-sm text-muted-foreground\">\n {t(\n 'communication_channels.profile.subtitle',\n 'Connect your communication channels so outbound messages come from your own account and inbound messages land in your unified inbox.',\n )}\n </p>\n </div>\n {/* Provider connect entry points injected by each channel-* package\n (channel-gmail, channel-imap) via UMES. They stack inside one\n dropdown so the header does not widen per installed provider. */}\n <ConnectChannelMenu onConnected={reloadChannels} />\n </header>\n\n {reauthRows.length > 0 ? (\n <Alert status=\"warning\" className=\"mb-4\">\n <AlertDescription>\n {t(\n 'communication_channels.profile.alerts.requiresReauth',\n '{count} channel(s) need reconnection. Click \"Reconnect\" on the affected channel below.',\n { count: reauthRows.length },\n )}\n </AlertDescription>\n </Alert>\n ) : null}\n\n <DataTable<ChannelRow>\n title={t('communication_channels.profile.tableTitle', 'Your channels')}\n titleHeadingLevel={2}\n extensionTableId={extensionPoints.hosts.profileChannelsTable.tableId}\n columns={columns}\n rowActions={rowActions}\n // Pinned because this table is wider than a laptop viewport: at 1280px\n // the row runs out well before the actions cell, and since Primary,\n // Team access and Push are status-only there is no other control in\n // view. Unpinned, reaching \u22EF meant scrolling to the far end, which\n // scrolls the Channel column away \u2014 so you could no longer see which\n // channel the open menu belonged to (#6717).\n stickyActionsColumn\n data={rows}\n isLoading={isLoading}\n error={errorMessage}\n emptyState={t(\n 'communication_channels.profile.empty',\n 'You have no connected channels yet. Add one using the menu at the top of this page.',\n )}\n />\n <ImportHistoryDialog\n channel={importChannel}\n onClose={() => setImportChannel(null)}\n onQueued={() => {\n setImportChannel(null)\n router.refresh()\n }}\n />\n <DisconnectChannelDialog\n channel={disconnectChannel}\n onClose={() => setDisconnectChannel(null)}\n onDisconnected={() => {\n setDisconnectChannel(null)\n setReloadKey((k) => k + 1)\n }}\n />\n {ConfirmDialogElement}\n </PageBody>\n </Page>\n )\n}\n\ntype ImportHistoryDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onQueued: () => void\n}\n\nfunction ImportHistoryDialog({ channel, onClose, onQueued }: ImportHistoryDialogProps): React.JSX.Element {\n const t = useT()\n const importLimits = React.useMemo(() => getImportHistoryLimits(channel?.providerKey), [channel?.providerKey])\n const [sinceDays, setSinceDays] = React.useState('30')\n const [contactEmails, setContactEmails] = React.useState('')\n const [maxMessages, setMaxMessages] = React.useState('500')\n const [fieldErrors, setFieldErrors] = React.useState<Record<string, string>>({})\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) {\n setSinceDays('30')\n setContactEmails('')\n setMaxMessages('500')\n setFieldErrors({})\n setSubmitting(false)\n }\n }, [channel?.id])\n\n const handleSubmit = React.useCallback(async () => {\n if (!channel || submitting) return\n const sinceNum = Number.parseInt(sinceDays, 10)\n const maxNum = Number.parseInt(maxMessages, 10)\n const errors: Record<string, string> = {}\n if (!Number.isFinite(sinceNum) || sinceNum < 1 || sinceNum > importLimits.maxSinceDays) {\n errors.sinceDays = t(\n 'communication_channels.profile.importHistory.errors.sinceDays',\n 'Choose a number between 1 and {max} days.',\n { max: importLimits.maxSinceDays },\n )\n }\n if (!Number.isFinite(maxNum) || maxNum < 1 || maxNum > importLimits.maxMessages) {\n errors.maxMessages = t(\n 'communication_channels.profile.importHistory.errors.maxMessages',\n 'Choose a number between 1 and {max} messages.',\n { max: importLimits.maxMessages },\n )\n }\n const parsedEmails = contactEmails\n .split(/[\\s,;]+/)\n .map((s) => s.trim())\n .filter(Boolean)\n if (parsedEmails.length > 0 && parsedEmails.some((s) => !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s))) {\n errors.contactEmails = t(\n 'communication_channels.profile.importHistory.errors.contactEmails',\n 'One or more entries is not a valid email address.',\n )\n }\n if (Object.keys(errors).length > 0) {\n setFieldErrors(errors)\n return\n }\n setFieldErrors({})\n setSubmitting(true)\n const mutationPayload = {\n sinceDays: sinceNum,\n maxMessages: maxNum,\n ...(parsedEmails.length > 0 ? { contactEmails: parsedEmails } : {}),\n }\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ progressJobId?: string }>(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/import-history`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(mutationPayload),\n },\n ),\n context: {\n formId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload,\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.importHistory.flash.error', 'Failed to queue history import.'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string; fieldErrors?: Record<string, string> } | undefined\n if (body?.fieldErrors && Object.keys(body.fieldErrors).length > 0) {\n setFieldErrors(body.fieldErrors)\n return\n }\n flash(\n body?.error ??\n t(\n 'communication_channels.profile.importHistory.flash.error',\n 'Failed to queue history import.',\n ),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.importHistory.flash.success',\n 'History import queued \u2014 track progress in the top bar.',\n ),\n 'success',\n )\n onQueued()\n }, [channel, sinceDays, maxMessages, contactEmails, submitting, t, onQueued, retryLastMutation, runMutation, importLimits])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleSubmit()\n }\n },\n [handleSubmit],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.importHistory.title', 'Import channel history')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.importHistory.description',\n 'Pull older messages this channel never observed at connect-time. Filters narrow the search server-side.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-since\">\n {t('communication_channels.profile.importHistory.fields.sinceDays', 'Look back (days)')}\n </Label>\n <Input\n id=\"import-history-since\"\n type=\"number\"\n min={1}\n max={importLimits.maxSinceDays}\n value={sinceDays}\n onChange={(e) => setSinceDays(e.target.value)}\n aria-invalid={Boolean(fieldErrors.sinceDays)}\n />\n {fieldErrors.sinceDays ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.sinceDays}</p>\n ) : null}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-emails\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmails',\n 'Filter by sender (optional)',\n )}\n </Label>\n <Textarea\n id=\"import-history-emails\"\n rows={3}\n value={contactEmails}\n onChange={(e) => setContactEmails(e.target.value)}\n placeholder={t(\n 'communication_channels.profile.importHistory.fields.contactEmailsPlaceholder',\n 'alice@example.com, bob@example.com',\n )}\n aria-invalid={Boolean(fieldErrors.contactEmails)}\n />\n {fieldErrors.contactEmails ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.contactEmails}</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmailsHint',\n 'Leave empty to scan all senders in the window.',\n )}\n </p>\n )}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-max\">\n {t('communication_channels.profile.importHistory.fields.maxMessages', 'Maximum messages')}\n </Label>\n <Input\n id=\"import-history-max\"\n type=\"number\"\n min={1}\n max={importLimits.maxMessages}\n value={maxMessages}\n onChange={(e) => setMaxMessages(e.target.value)}\n aria-invalid={Boolean(fieldErrors.maxMessages)}\n />\n {fieldErrors.maxMessages ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.maxMessages}</p>\n ) : null}\n </div>\n\n {fieldErrors.channelId ? (\n <Alert status=\"warning\">\n <AlertDescription>{fieldErrors.channelId}</AlertDescription>\n </Alert>\n ) : null}\n </div>\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.importHistory.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" onClick={() => void handleSubmit()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.importHistory.submitting', 'Queueing\u2026')\n : t('communication_channels.profile.importHistory.submit', 'Start import')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\ntype DisconnectChannelDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onDisconnected: () => void\n}\n\nfunction DisconnectChannelDialog({\n channel,\n onClose,\n onDisconnected,\n}: DisconnectChannelDialogProps): React.JSX.Element {\n const t = useT()\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: DISCONNECT_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) setSubmitting(false)\n }, [channel?.id])\n\n const handleConfirm = React.useCallback(async () => {\n if (!channel || submitting) return\n setSubmitting(true)\n let response\n try {\n response = await runMutation({\n // optimistic-lock-exempt: self-service connect/disconnect of the\n // signed-in operator's OWN communication channel (an integration link),\n // not a shared multi-editor record. Disconnect is a terminal action\n // keyed by channel id; there is no concurrent-edit lost-update window to\n // guard, and the row carries no client-surfaced `updatedAt` round-trip.\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}`,\n { method: 'DELETE' },\n ),\n context: {\n formId: DISCONNECT_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { action: 'disconnect' },\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ??\n t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.disconnectSuccess',\n 'Channel disconnected. You can reconnect it anytime.',\n ),\n 'success',\n )\n onDisconnected()\n }, [channel, submitting, runMutation, retryLastMutation, t, onDisconnected])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleConfirm()\n }\n },\n [handleConfirm],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.disconnect.title', 'Disconnect channel')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.disconnect.description',\n 'This removes the connection and stops syncing. Emails already imported stay on your timelines. You can reconnect anytime.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n {channel ? (\n <p className=\"text-sm font-medium\">{channel.externalIdentifier ?? channel.displayName}</p>\n ) : null}\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.disconnect.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" variant=\"destructive-solid\" onClick={() => void handleConfirm()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.disconnect.submitting', 'Disconnecting\u2026')\n : t('communication_channels.profile.disconnect.confirm', 'Disconnect')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction statusTag(\n status: ChannelRow['status'],\n t: (key: string, fallback?: string) => string,\n): React.ReactNode {\n switch (status) {\n case 'connected':\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.status.connected', 'Connected')}\n </Tag>\n )\n case 'requires_reauth':\n return (\n <Tag variant=\"warning\" dot>\n {t('communication_channels.status.requiresReauth', 'Needs reconnection')}\n </Tag>\n )\n case 'error':\n return (\n <Tag variant=\"error\" dot>\n {t('communication_channels.status.error', 'Error')}\n </Tag>\n )\n case 'disconnected':\n return <Tag variant=\"neutral\">{t('communication_channels.status.disconnected', 'Disconnected')}</Tag>\n default:\n return <Tag variant=\"neutral\">{status}</Tag>\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAiYU,cAyOA,YAzOA;AA/XV,YAAY,WAAW;AACvB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,0BAA0B,8BAA8B;AAEjE,SAAS,WAAW,uBAAuB;AAC3C,SAAS,MAAM,gBAAgB;AAC/B,SAAS,iBAAiB;AAC1B,SAAS,WAAW;AACpB,SAAS,cAAc;AACvB,SAAS,OAAO,wBAAwB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa;AACtB,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,kBAAsC;AAC/C,SAAS,SAAS,mCAAmC;AACrD,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,0BAA0B;AA+BnC,MAAM,uCAAuC;AAC7C,MAAM,qCAAqC;AAC3C,MAAM,iCAAiC;AASxB,SAAR,mCAAoD;AACzD,QAAM,IAAI,KAAK;AACf,QAAM,SAAS,UAAU;AACzB,QAAM,eAAe,gBAAgB;AACrC,QAAM,YAAY,cAAc,IAAI,wBAAwB;AAC5D,QAAM,YAAY,cAAc,IAAI,MAAM;AAC1C,QAAM,gBAAgB,cAAc,IAAI,UAAU;AAElD,QAAM,CAAC,MAAM,OAAO,IAAI,MAAM,SAAuB,CAAC,CAAC;AACvD,QAAM,CAAC,WAAW,YAAY,IAAI,MAAM,SAAS,IAAI;AACrD,QAAM,CAAC,cAAc,eAAe,IAAI,MAAM,SAAwB,IAAI;AA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,SAAS,MAAM,KAAK,cAAc,GAAG,UAAU,YAC9F,uBACG,EAAE,wDAAwD,qBAAgB,IAC1E,EAAE,qDAAqD,YAAY,GACzE;AAAA,OACF;AAAA,KACF,GACF;AAEJ;AAEA,SAAS,UACP,QACA,GACiB;AACjB,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,WAAU,KAAG,MACvB,YAAE,2CAA2C,WAAW,GAC3D;AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,WAAU,KAAG,MACvB,YAAE,gDAAgD,oBAAoB,GACzE;AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,SAAQ,KAAG,MACrB,YAAE,uCAAuC,OAAO,GACnD;AAAA,IAEJ,KAAK;AACH,aAAO,oBAAC,OAAI,SAAQ,WAAW,YAAE,8CAA8C,cAAc,GAAE;AAAA,IACjG;AACE,aAAO,oBAAC,OAAI,SAAQ,WAAW,kBAAO;AAAA,EAC1C;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -36,6 +36,10 @@ const deliverInputSchema = z.object({
|
|
|
36
36
|
forceCredentialRefresh: z.boolean().optional()
|
|
37
37
|
});
|
|
38
38
|
const COMMUNICATION_CHANNELS_DELIVER_OUTBOUND_COMMAND_ID = "communication_channels.message.deliver_outbound";
|
|
39
|
+
function omitRawMessage(metadata) {
|
|
40
|
+
if (!metadata) return {};
|
|
41
|
+
return Object.fromEntries(Object.entries(metadata).filter(([key]) => key !== "rawMessage"));
|
|
42
|
+
}
|
|
39
43
|
const deliverOutboundMessageCommand = {
|
|
40
44
|
id: COMMUNICATION_CHANNELS_DELIVER_OUTBOUND_COMMAND_ID,
|
|
41
45
|
async execute(rawInput, ctx) {
|
|
@@ -311,7 +315,7 @@ const deliverOutboundMessageCommand = {
|
|
|
311
315
|
link.externalMessageId = externalMessageRowId;
|
|
312
316
|
link.channelMetadata = {
|
|
313
317
|
...link.channelMetadata ?? {},
|
|
314
|
-
...converted.metadata
|
|
318
|
+
...omitRawMessage(converted.metadata),
|
|
315
319
|
externalMessageId: sendResult.externalMessageId,
|
|
316
320
|
// Always persist the RFC2822 Message-ID so inbound reply matching (JWZ
|
|
317
321
|
// strategy in lib/thread-matcher) and sent-folder dedup can resolve this
|