@open-mercato/core 0.6.6 → 0.6.7-develop.6553.1.2ec7246e04
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 +2 -2
- package/dist/generated/entities/gateway_session_initialization/index.js +23 -0
- package/dist/generated/entities/gateway_session_initialization/index.js.map +7 -0
- package/dist/generated/entities.ids.generated.js +1 -0
- package/dist/generated/entities.ids.generated.js.map +2 -2
- package/dist/generated/entity-fields-registry.js +12 -0
- package/dist/generated/entity-fields-registry.js.map +2 -2
- package/dist/modules/api_keys/api/keys/route.js +30 -13
- package/dist/modules/api_keys/api/keys/route.js.map +2 -2
- package/dist/modules/api_keys/cli.js +2 -1
- package/dist/modules/api_keys/cli.js.map +2 -2
- package/dist/modules/attachments/api/file/[id]/route.js +9 -7
- package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
- package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +9 -7
- package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
- package/dist/modules/attachments/api/route.js +21 -17
- package/dist/modules/attachments/api/route.js.map +2 -2
- package/dist/modules/attachments/components/AttachmentContentPreview.js +6 -35
- package/dist/modules/attachments/components/AttachmentContentPreview.js.map +2 -2
- package/dist/modules/attachments/lib/reconcileOrganization.js +110 -0
- package/dist/modules/attachments/lib/reconcileOrganization.js.map +7 -0
- package/dist/modules/attachments/lib/requestScope.js +10 -0
- package/dist/modules/attachments/lib/requestScope.js.map +7 -0
- package/dist/modules/audit_logs/backend/audit-logs/page.js +14 -24
- package/dist/modules/audit_logs/backend/audit-logs/page.js.map +2 -2
- package/dist/modules/auth/api/autologin.js +85 -0
- package/dist/modules/auth/api/autologin.js.map +7 -0
- package/dist/modules/auth/api/users/route.js +6 -2
- package/dist/modules/auth/api/users/route.js.map +2 -2
- package/dist/modules/auth/cli.js +3 -2
- package/dist/modules/auth/cli.js.map +2 -2
- package/dist/modules/auth/lib/autologin.js +19 -0
- package/dist/modules/auth/lib/autologin.js.map +7 -0
- package/dist/modules/configs/lib/upgrade-actions.js +22 -0
- package/dist/modules/configs/lib/upgrade-actions.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/roles/[id]/acl.js +1 -0
- package/dist/modules/customer_accounts/api/admin/roles/[id]/acl.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/roles/[id].js +17 -3
- package/dist/modules/customer_accounts/api/admin/roles/[id].js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/users/[id]/roles.js +6 -1
- package/dist/modules/customer_accounts/api/portal/users/[id]/roles.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/users-invite.js +6 -1
- package/dist/modules/customer_accounts/api/portal/users-invite.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerInvitationService.js +1 -0
- package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerRbacService.js +6 -1
- package/dist/modules/customer_accounts/services/customerRbacService.js.map +2 -2
- package/dist/modules/customer_accounts/widgets/injection-table.js +0 -2
- package/dist/modules/customer_accounts/widgets/injection-table.js.map +2 -2
- package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js +7 -1
- package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js.map +2 -2
- package/dist/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.js +2 -2
- package/dist/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.js.map +2 -2
- package/dist/modules/customers/components/detail/CompanyDetailTabs.js +37 -43
- package/dist/modules/customers/components/detail/CompanyDetailTabs.js.map +2 -2
- package/dist/modules/customers/components/detail/DealDetailTabs.js +23 -35
- package/dist/modules/customers/components/detail/DealDetailTabs.js.map +2 -2
- package/dist/modules/customers/components/detail/DetailTabsLayout.js +6 -21
- package/dist/modules/customers/components/detail/DetailTabsLayout.js.map +2 -2
- package/dist/modules/customers/components/detail/MobilePersonDetail.js +26 -32
- package/dist/modules/customers/components/detail/MobilePersonDetail.js.map +2 -2
- package/dist/modules/customers/components/detail/PersonDetailTabs.js +29 -39
- package/dist/modules/customers/components/detail/PersonDetailTabs.js.map +2 -2
- package/dist/modules/customers/components/detail/useDealsAccess.js +16 -0
- package/dist/modules/customers/components/detail/useDealsAccess.js.map +7 -0
- package/dist/modules/dashboards/api/roles/widgets/route.js +22 -3
- package/dist/modules/dashboards/api/roles/widgets/route.js.map +2 -2
- package/dist/modules/dashboards/api/users/widgets/route.js +22 -3
- package/dist/modules/dashboards/api/users/widgets/route.js.map +2 -2
- package/dist/modules/dashboards/cli.js +4 -3
- package/dist/modules/dashboards/cli.js.map +2 -2
- package/dist/modules/dashboards/lib/widgetAssignmentScope.js +9 -1
- package/dist/modules/dashboards/lib/widgetAssignmentScope.js.map +2 -2
- package/dist/modules/dictionaries/commands/entries.js +7 -14
- package/dist/modules/dictionaries/commands/entries.js.map +2 -2
- package/dist/modules/dictionaries/commands/entry-operations.js +7 -16
- package/dist/modules/dictionaries/commands/entry-operations.js.map +2 -2
- package/dist/modules/dictionaries/commands/factory.js +9 -3
- package/dist/modules/dictionaries/commands/factory.js.map +2 -2
- package/dist/modules/dictionaries/fields/dictionary.js +56 -41
- package/dist/modules/dictionaries/fields/dictionary.js.map +2 -2
- package/dist/modules/directory/utils/organizationScope.js +10 -3
- package/dist/modules/directory/utils/organizationScope.js.map +2 -2
- package/dist/modules/entities/api/records.js +5 -4
- package/dist/modules/entities/api/records.js.map +2 -2
- package/dist/modules/entities/backend/entities/system/[entityId]/page.meta.js +1 -0
- package/dist/modules/entities/backend/entities/system/[entityId]/page.meta.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js +49 -49
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/page.meta.js +1 -0
- package/dist/modules/entities/backend/entities/user/[entityId]/page.meta.js.map +2 -2
- package/dist/modules/entities/cli.js +2 -1
- package/dist/modules/entities/cli.js.map +2 -2
- package/dist/modules/feature_toggles/api/check/boolean/route.js +0 -14
- package/dist/modules/feature_toggles/api/check/boolean/route.js.map +2 -2
- package/dist/modules/feature_toggles/defaults.json +8 -0
- package/dist/modules/integrations/backend/integrations/[id]/page.js +9 -80
- package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
- package/dist/modules/payment_gateways/data/entities.js +45 -0
- package/dist/modules/payment_gateways/data/entities.js.map +2 -2
- package/dist/modules/payment_gateways/lib/gateway-service.js +173 -38
- package/dist/modules/payment_gateways/lib/gateway-service.js.map +3 -3
- package/dist/modules/payment_gateways/lib/session-idempotency.js +104 -0
- package/dist/modules/payment_gateways/lib/session-idempotency.js.map +7 -0
- package/dist/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.js +11 -0
- package/dist/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.js.map +7 -0
- package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js +16 -14
- package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js.map +2 -2
- package/dist/modules/planner/components/AvailabilityRulesEditor.js +18 -30
- package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
- package/dist/modules/query_index/api/status.js +2 -8
- package/dist/modules/query_index/api/status.js.map +2 -2
- package/dist/modules/resources/backend/resources/resources/[id]/page.js +24 -24
- package/dist/modules/resources/backend/resources/resources/[id]/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/create/page.js +6 -0
- package/dist/modules/sales/backend/sales/channels/create/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/create/page.meta.js +2 -0
- package/dist/modules/sales/backend/sales/channels/create/page.meta.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/offers/page.js +6 -0
- package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/offers/page.meta.js +2 -0
- package/dist/modules/sales/backend/sales/channels/offers/page.meta.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/page.js +6 -0
- package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
- package/dist/modules/sales/backend/sales/channels/page.meta.js +2 -0
- package/dist/modules/sales/backend/sales/channels/page.meta.js.map +2 -2
- package/dist/modules/sales/backend/sales/documents/[id]/page.js +6 -4
- package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
- package/dist/modules/sales/commands/documents.js +44 -0
- package/dist/modules/sales/commands/documents.js.map +2 -2
- package/dist/modules/sales/commands/returns.js +2 -27
- package/dist/modules/sales/commands/returns.js.map +2 -2
- package/dist/modules/sales/components/SalesChannelsDisabledNotice.js +15 -0
- package/dist/modules/sales/components/SalesChannelsDisabledNotice.js.map +7 -0
- package/dist/modules/sales/components/documents/AddressesSection.js +6 -2
- package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
- package/dist/modules/sales/components/documents/ItemsSection.js +1 -0
- package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
- package/dist/modules/sales/components/documents/LineItemDialog.js +9 -0
- package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
- package/dist/modules/sales/components/documents/SalesDocumentForm.js +51 -3
- package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
- package/dist/modules/sales/components/documents/SalesDocumentsTable.js +10 -8
- package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
- package/dist/modules/sales/components/documents/ShipmentDialog.js +59 -38
- package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
- package/dist/modules/sales/components/useSalesChannelsEnabled.js +44 -0
- package/dist/modules/sales/components/useSalesChannelsEnabled.js.map +7 -0
- package/dist/modules/sales/lib/calculations.js +6 -0
- package/dist/modules/sales/lib/calculations.js.map +2 -2
- package/dist/modules/sales/lib/salesChannelsToggle.js +18 -0
- package/dist/modules/sales/lib/salesChannelsToggle.js.map +7 -0
- package/dist/modules/sales/lib/salesChannelsToggleId.js +5 -0
- package/dist/modules/sales/lib/salesChannelsToggleId.js.map +7 -0
- package/dist/modules/sales/lib/shipments/snapshots.js +27 -1
- package/dist/modules/sales/lib/shipments/snapshots.js.map +2 -2
- package/dist/modules/staff/backend/staff/team-members/[id]/page.js +22 -25
- package/dist/modules/staff/backend/staff/team-members/[id]/page.js.map +2 -2
- package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js +12 -14
- package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js.map +2 -2
- package/dist/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.js +10 -29
- package/dist/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.js.map +2 -2
- package/dist/modules/sync_excel/lib/adapters/customers.js +19 -20
- package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
- package/dist/modules/sync_excel/lib/parser.js +185 -0
- package/dist/modules/sync_excel/lib/parser.js.map +2 -2
- package/dist/modules/sync_excel/lib/upload-storage.js +20 -1
- package/dist/modules/sync_excel/lib/upload-storage.js.map +2 -2
- package/generated/entities/gateway_session_initialization/index.ts +10 -0
- package/generated/entities.ids.generated.ts +1 -0
- package/generated/entity-fields-registry.ts +12 -0
- package/package.json +9 -8
- package/src/modules/api_keys/api/keys/route.ts +36 -13
- package/src/modules/api_keys/cli.ts +2 -3
- package/src/modules/attachments/api/file/[id]/route.ts +11 -7
- package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +11 -7
- package/src/modules/attachments/api/route.ts +26 -21
- package/src/modules/attachments/components/AttachmentContentPreview.tsx +9 -44
- package/src/modules/attachments/lib/reconcileOrganization.ts +188 -0
- package/src/modules/attachments/lib/requestScope.ts +27 -0
- package/src/modules/audit_logs/backend/audit-logs/page.tsx +12 -22
- package/src/modules/auth/api/autologin.ts +100 -0
- package/src/modules/auth/api/users/route.ts +11 -2
- package/src/modules/auth/cli.ts +3 -2
- package/src/modules/auth/lib/autologin.ts +36 -0
- package/src/modules/configs/i18n/de.json +5 -1
- package/src/modules/configs/i18n/en.json +5 -1
- package/src/modules/configs/i18n/es.json +5 -1
- package/src/modules/configs/i18n/pl.json +5 -1
- package/src/modules/configs/lib/upgrade-actions.ts +24 -0
- package/src/modules/customer_accounts/AGENTS.md +8 -6
- package/src/modules/customer_accounts/api/admin/roles/[id]/acl.ts +1 -0
- package/src/modules/customer_accounts/api/admin/roles/[id].ts +17 -3
- package/src/modules/customer_accounts/api/portal/users/[id]/roles.ts +6 -1
- package/src/modules/customer_accounts/api/portal/users-invite.ts +6 -1
- package/src/modules/customer_accounts/services/customerInvitationService.ts +1 -0
- package/src/modules/customer_accounts/services/customerRbacService.ts +9 -2
- package/src/modules/customer_accounts/widgets/injection-table.ts +0 -2
- package/src/modules/customers/backend/customers/companies-v2/[id]/page.tsx +11 -1
- package/src/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.tsx +6 -2
- package/src/modules/customers/components/detail/CompanyDetailTabs.tsx +39 -55
- package/src/modules/customers/components/detail/DealDetailTabs.tsx +24 -49
- package/src/modules/customers/components/detail/DetailTabsLayout.tsx +13 -24
- package/src/modules/customers/components/detail/MobilePersonDetail.tsx +25 -31
- package/src/modules/customers/components/detail/PersonDetailTabs.tsx +29 -50
- package/src/modules/customers/components/detail/useDealsAccess.ts +19 -0
- package/src/modules/dashboards/api/roles/widgets/route.ts +22 -3
- package/src/modules/dashboards/api/users/widgets/route.ts +22 -3
- package/src/modules/dashboards/cli.ts +4 -9
- package/src/modules/dashboards/lib/widgetAssignmentScope.ts +18 -0
- package/src/modules/dictionaries/commands/entries.ts +7 -16
- package/src/modules/dictionaries/commands/entry-operations.ts +8 -18
- package/src/modules/dictionaries/commands/factory.ts +8 -2
- package/src/modules/dictionaries/fields/dictionary.tsx +55 -32
- package/src/modules/dictionaries/i18n/de.json +2 -0
- package/src/modules/dictionaries/i18n/en.json +2 -0
- package/src/modules/dictionaries/i18n/es.json +2 -0
- package/src/modules/dictionaries/i18n/pl.json +2 -0
- package/src/modules/directory/utils/organizationScope.ts +36 -2
- package/src/modules/entities/api/records.ts +5 -7
- package/src/modules/entities/backend/entities/system/[entityId]/page.meta.ts +1 -0
- package/src/modules/entities/backend/entities/user/[entityId]/page.meta.ts +1 -0
- package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +51 -49
- package/src/modules/entities/cli.ts +2 -1
- package/src/modules/entities/i18n/de.json +34 -0
- package/src/modules/entities/i18n/en.json +34 -0
- package/src/modules/entities/i18n/es.json +34 -0
- package/src/modules/entities/i18n/pl.json +34 -0
- package/src/modules/feature_toggles/api/check/boolean/route.ts +0 -15
- package/src/modules/feature_toggles/defaults.json +8 -0
- package/src/modules/integrations/backend/integrations/[id]/page.tsx +16 -59
- package/src/modules/payment_gateways/data/entities.ts +39 -0
- package/src/modules/payment_gateways/lib/gateway-service.ts +211 -40
- package/src/modules/payment_gateways/lib/session-idempotency.ts +142 -0
- package/src/modules/payment_gateways/migrations/.snapshot-open-mercato.json +236 -0
- package/src/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.ts +10 -0
- package/src/modules/planner/backend/planner/availability-rulesets/[id]/page.tsx +14 -20
- package/src/modules/planner/components/AvailabilityRulesEditor.tsx +16 -34
- package/src/modules/query_index/api/status.ts +2 -8
- package/src/modules/resources/backend/resources/resources/[id]/page.tsx +27 -37
- package/src/modules/sales/backend/sales/channels/create/page.meta.ts +3 -0
- package/src/modules/sales/backend/sales/channels/create/page.tsx +7 -0
- package/src/modules/sales/backend/sales/channels/offers/page.meta.ts +3 -0
- package/src/modules/sales/backend/sales/channels/offers/page.tsx +7 -0
- package/src/modules/sales/backend/sales/channels/page.meta.ts +4 -0
- package/src/modules/sales/backend/sales/channels/page.tsx +7 -0
- package/src/modules/sales/backend/sales/documents/[id]/page.tsx +7 -5
- package/src/modules/sales/commands/documents.ts +65 -0
- package/src/modules/sales/commands/returns.ts +2 -32
- package/src/modules/sales/components/SalesChannelsDisabledNotice.tsx +21 -0
- package/src/modules/sales/components/documents/AddressesSection.tsx +6 -2
- package/src/modules/sales/components/documents/ItemsSection.tsx +5 -0
- package/src/modules/sales/components/documents/LineItemDialog.tsx +10 -0
- package/src/modules/sales/components/documents/SalesDocumentForm.tsx +53 -3
- package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +10 -8
- package/src/modules/sales/components/documents/ShipmentDialog.tsx +65 -40
- package/src/modules/sales/components/useSalesChannelsEnabled.ts +59 -0
- package/src/modules/sales/i18n/de.json +5 -0
- package/src/modules/sales/i18n/en.json +5 -0
- package/src/modules/sales/i18n/es.json +5 -0
- package/src/modules/sales/i18n/pl.json +5 -0
- package/src/modules/sales/lib/calculations.ts +15 -0
- package/src/modules/sales/lib/salesChannelsToggle.ts +26 -0
- package/src/modules/sales/lib/salesChannelsToggleId.ts +1 -0
- package/src/modules/sales/lib/shipments/snapshots.ts +30 -0
- package/src/modules/staff/backend/staff/team-members/[id]/page.tsx +25 -34
- package/src/modules/staff/backend/staff/teams/[id]/edit/page.tsx +11 -17
- package/src/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.tsx +11 -28
- package/src/modules/sync_excel/lib/adapters/customers.ts +20 -22
- package/src/modules/sync_excel/lib/parser.ts +245 -0
- package/src/modules/sync_excel/lib/upload-storage.ts +23 -1
|
@@ -315,10 +315,7 @@ async function GET(req) {
|
|
|
315
315
|
errorQuery = errorQuery.where("tenant_id", "is", null);
|
|
316
316
|
}
|
|
317
317
|
if (Array.isArray(organizationScopeIds) && organizationScopeIds.length) {
|
|
318
|
-
errorQuery = errorQuery.where(
|
|
319
|
-
eb("organization_id", "is", null),
|
|
320
|
-
eb("organization_id", "in", organizationScopeIds)
|
|
321
|
-
]));
|
|
318
|
+
errorQuery = errorQuery.where("organization_id", "in", organizationScopeIds);
|
|
322
319
|
} else {
|
|
323
320
|
errorQuery = errorQuery.where("organization_id", "is", null);
|
|
324
321
|
}
|
|
@@ -349,10 +346,7 @@ async function GET(req) {
|
|
|
349
346
|
logsQuery = logsQuery.where("tenant_id", "is", null);
|
|
350
347
|
}
|
|
351
348
|
if (Array.isArray(organizationScopeIds) && organizationScopeIds.length) {
|
|
352
|
-
logsQuery = logsQuery.where(
|
|
353
|
-
eb("organization_id", "is", null),
|
|
354
|
-
eb("organization_id", "in", organizationScopeIds)
|
|
355
|
-
]));
|
|
349
|
+
logsQuery = logsQuery.where("organization_id", "in", organizationScopeIds);
|
|
356
350
|
} else {
|
|
357
351
|
logsQuery = logsQuery.where("organization_id", "is", null);
|
|
358
352
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/query_index/api/status.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { sql } from 'kysely'\nimport { readCoverageSnapshots, refreshCoverageSnapshot, type CoverageSnapshot } from '../lib/coverage'\nimport { mapWithConcurrency } from '@open-mercato/shared/lib/query/bounded-decrypt'\nimport type { FullTextSearchStrategy } from '@open-mercato/search/strategies'\nimport type { SearchModuleConfig } from '@open-mercato/shared/modules/search'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { queryIndexTag, queryIndexErrorSchema, queryIndexStatusResponseSchema } from './openapi'\nimport { flattenSystemEntityIds } from '@open-mercato/shared/lib/entities/system-entities'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['query_index.status.view'] },\n}\n\nconst STATUS_REFRESH_COOLDOWN_MS = 60_000\n\nfunction getCoverageSnapshotRefreshedAt(snapshot: Pick<CoverageSnapshot, 'refreshed_at'> | null | undefined): number | null {\n const value = snapshot?.refreshed_at\n if (value instanceof Date) {\n const time = value.getTime()\n return Number.isFinite(time) ? time : null\n }\n if (typeof value === 'string') {\n const time = new Date(value).getTime()\n return Number.isFinite(time) ? time : null\n }\n return null\n}\n\nfunction hasFreshCoverageSnapshots(\n snapshots: Map<string, CoverageSnapshot>,\n entityIds: string[],\n now: number,\n): boolean {\n for (const entityId of entityIds) {\n const refreshedAt = getCoverageSnapshotRefreshedAt(snapshots.get(entityId))\n if (refreshedAt === null || now - refreshedAt >= STATUS_REFRESH_COOLDOWN_MS) return false\n }\n return entityIds.length > 0\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const db = (em as any).getKysely()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n\n const organizationId = scope.selectedId ?? auth.orgId ?? null\n const tenantId = typeof scope.tenantId === 'string' && scope.tenantId.trim().length > 0\n ? scope.tenantId.trim()\n : (typeof auth.tenantId === 'string' && auth.tenantId.trim().length > 0 ? auth.tenantId.trim() : null)\n if (!tenantId) {\n return NextResponse.json({ error: 'Tenant context is required' }, { status: 400 })\n }\n\n const organizationFilter =\n scope.filterIds === null\n ? null\n : Array.isArray(scope.filterIds) && scope.filterIds.length > 0\n ? scope.filterIds\n : organizationId\n ? [organizationId]\n : []\n\n if (Array.isArray(organizationFilter) && organizationFilter.length === 0) {\n return NextResponse.json({ error: 'Organization access denied' }, { status: 403 })\n }\n\n const organizationScopeIds = organizationFilter === null\n ? null\n : Array.from(\n new Set(\n organizationFilter.filter(\n (value): value is string => typeof value === 'string' && value.length > 0,\n ),\n ),\n )\n\n if (Array.isArray(organizationScopeIds) && organizationScopeIds.length === 0) {\n return NextResponse.json({ error: 'Organization access denied' }, { status: 403 })\n }\n\n const url = new URL(req.url)\n const forceRefresh = url.searchParams.has('refresh') && url.searchParams.get('refresh') !== '0'\n\n const generatedIds = flattenSystemEntityIds(getEntityIds() as Record<string, Record<string, string>>)\n const generated = generatedIds.map((entityId) => ({ entityId, label: entityId }))\n\n const byId = new Map<string, { entityId: string; label: string }>()\n for (const g of generated) byId.set(g.entityId, g)\n\n let entityIds = generatedIds.slice()\n\n // Resolve search module configs to determine vector-enabled entities\n // Entities with buildSource defined are vector-search enabled\n let searchModuleConfigs: SearchModuleConfig[] = []\n try {\n searchModuleConfigs = container.resolve('searchModuleConfigs') as SearchModuleConfig[]\n } catch {\n // Search module configs not available\n }\n\n const vectorEnabledEntities = new Set<string>()\n const fulltextEnabledEntities = new Set<string>()\n for (const moduleConfig of searchModuleConfigs) {\n for (const entity of moduleConfig.entities ?? []) {\n if (entity.enabled !== false) {\n // Vector: entities with buildSource defined\n if (typeof entity.buildSource === 'function') {\n vectorEnabledEntities.add(entity.entityId)\n }\n // Fulltext: entities with fieldPolicy defined\n if (entity.fieldPolicy && typeof entity.fieldPolicy === 'object') {\n fulltextEnabledEntities.add(entity.entityId)\n }\n }\n }\n }\n\n // Resolve fulltext strategy for entity counts\n let fulltextStrategy: FullTextSearchStrategy | null = null\n try {\n const searchStrategies = container.resolve('searchStrategies') as unknown[]\n fulltextStrategy = (searchStrategies?.find(\n (s: unknown) => (s as { id?: string })?.id === 'fulltext',\n ) as FullTextSearchStrategy) ?? null\n } catch {\n fulltextStrategy = null\n }\n\n // Fetch fulltext entity counts\n let fulltextEntityCounts: Record<string, number> | null = null\n if (fulltextStrategy) {\n try {\n fulltextEntityCounts = await fulltextStrategy.getEntityCounts(tenantId)\n } catch {\n fulltextEntityCounts = null\n }\n }\n\n // Limit to entities that have active custom field definitions in current scope\n try {\n let cfQuery = db\n .selectFrom('custom_field_defs' as any)\n .select(['entity_id' as any])\n .distinct()\n .where('is_active' as any, '=', true)\n if (tenantId != null) {\n cfQuery = cfQuery.where((eb: any) => eb.or([\n eb('tenant_id' as any, '=', tenantId),\n eb('tenant_id' as any, 'is', null),\n ]))\n } else {\n cfQuery = cfQuery.where('tenant_id' as any, 'is', null as any)\n }\n if (Array.isArray(organizationScopeIds)) {\n cfQuery = cfQuery.where((eb: any) => eb.or([\n eb('organization_id' as any, 'in', organizationScopeIds),\n eb('organization_id' as any, 'is', null),\n ]))\n }\n const cfRows = await cfQuery.execute() as Array<{ entity_id: string }>\n const enabled = new Set<string>((cfRows || []).map((r) => String(r.entity_id)))\n entityIds = entityIds.filter((id) => enabled.has(id))\n } catch {}\n\n const HEARTBEAT_STALE_MS = 60_000\n const COVERAGE_STALE_MS = 60_000\n const COVERAGE_REFRESH_CONCURRENCY = 8\n\n async function fetchJobSummary(entityType: string, tenantIdParam: string | null, organizationIdParam: string | null) {\n try {\n let jobQuery = db\n .selectFrom('entity_index_jobs' as any)\n .selectAll()\n .where('entity_type' as any, '=', entityType)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantIdParam ?? null}`)\n if (organizationIdParam != null) {\n jobQuery = jobQuery.where((eb: any) => eb.or([\n eb('organization_id' as any, '=', organizationIdParam),\n eb('organization_id' as any, 'is', null),\n ]))\n } else {\n jobQuery = jobQuery.where(sql<boolean>`organization_id is not distinct from ${null}`)\n }\n const rows = await jobQuery\n .orderBy('started_at' as any, 'desc')\n .execute() as Array<Record<string, any>>\n\n if (!rows.length) {\n return { status: 'idle' as const, partitions: [] as any[] }\n }\n\n const preferOrg =\n organizationIdParam != null && rows.some((row: any) => row.organization_id === organizationIdParam)\n const pickPreferred = <T extends { startedTs: number; tenantMatch: boolean; orgMatch: boolean }>(\n existing: T | null,\n candidate: T,\n ): T => {\n if (!existing) return candidate\n if (preferOrg) {\n if (candidate.orgMatch && !existing.orgMatch) return candidate\n if (!candidate.orgMatch && existing.orgMatch) return existing\n }\n if (candidate.tenantMatch && !existing.tenantMatch) return candidate\n if (!candidate.tenantMatch && existing.tenantMatch) return existing\n return candidate.startedTs > existing.startedTs ? candidate : existing\n }\n\n const partitionRows = new Map<string, { row: any; startedTs: number; tenantMatch: boolean; orgMatch: boolean }>()\n let scopeRow: { row: any; startedTs: number; tenantMatch: boolean; orgMatch: boolean } | null = null\n for (const row of rows) {\n const key = String(row.partition_index ?? '__null__')\n const startedTs = row.started_at ? new Date(row.started_at).getTime() : 0\n const tenantMatch = tenantIdParam != null ? row.tenant_id === tenantIdParam : true\n const orgMatch = organizationIdParam != null ? row.organization_id === organizationIdParam : row.organization_id == null\n const candidate = { row, startedTs, tenantMatch, orgMatch }\n if (row.partition_index == null) {\n scopeRow = pickPreferred(scopeRow, candidate)\n continue\n }\n const existing = partitionRows.get(key)\n partitionRows.set(key, pickPreferred(existing ?? null, candidate))\n }\n\n const partitions = Array.from(partitionRows.values())\n .filter((entry) => !preferOrg || entry.orgMatch)\n .map(({ row }) => {\n const heartbeatDate = row.heartbeat_at ? new Date(row.heartbeat_at) : null\n const startedDate = row.started_at ? new Date(row.started_at) : null\n const finishedDate = row.finished_at ? new Date(row.finished_at) : null\n const stalled =\n !finishedDate && (!heartbeatDate || Date.now() - heartbeatDate.getTime() > HEARTBEAT_STALE_MS)\n const state = finishedDate\n ? 'completed'\n : stalled\n ? 'stalled'\n : (row.status as string) || 'reindexing'\n return {\n partitionIndex: row.partition_index ?? null,\n partitionCount: row.partition_count ?? null,\n status: state,\n startedAt: startedDate ? startedDate.toISOString() : null,\n finishedAt: finishedDate ? finishedDate.toISOString() : null,\n heartbeatAt: heartbeatDate ? heartbeatDate.toISOString() : null,\n processedCount: row.processed_count ?? null,\n totalCount: row.total_count ?? null,\n }\n })\n .sort((a, b) => (a.partitionIndex ?? 0) - (b.partitionIndex ?? 0))\n const activePartitions = partitions.filter((p) => !p.finishedAt)\n const runningPartitions = activePartitions.filter(\n (p) => p.status === 'reindexing' || p.status === 'purging',\n )\n const stalledPartitions = activePartitions.filter((p) => p.status === 'stalled')\n let status: 'idle' | 'reindexing' | 'purging' | 'stalled' = 'idle'\n if (activePartitions.length) {\n if (runningPartitions.length) {\n status = runningPartitions.some((p) => p.status === 'purging') ? 'purging' : 'reindexing'\n } else if (stalledPartitions.length) {\n status = 'stalled'\n }\n }\n\n const startedAt = activePartitions[0]?.startedAt ?? partitions[0]?.startedAt ?? null\n const finishedAt = status === 'idle' ? (partitions.find((p) => p.finishedAt)?.finishedAt ?? null) : null\n const heartbeatAt = activePartitions[0]?.heartbeatAt ?? partitions[0]?.heartbeatAt ?? null\n const jobTotalCount = partitions.reduce((sum, p) => sum + (p.totalCount ?? 0), 0)\n const processedSum = partitions.reduce((sum, p) => sum + (p.processedCount ?? 0), 0)\n const processedCount = jobTotalCount ? Math.min(jobTotalCount, processedSum) : processedSum || null\n const scopeCandidate = !preferOrg || !scopeRow || scopeRow.orgMatch ? scopeRow : null\n\n return {\n status,\n startedAt,\n finishedAt,\n heartbeatAt,\n processedCount: jobTotalCount ? processedCount : scopeCandidate?.row?.processed_count ?? null,\n totalCount: jobTotalCount ? jobTotalCount : scopeCandidate?.row?.total_count ?? null,\n partitions,\n scope: scopeCandidate\n ? {\n status: (() => {\n const heartbeatDate = scopeCandidate!.row.heartbeat_at ? new Date(scopeCandidate!.row.heartbeat_at) : null\n const finishedDate = scopeCandidate!.row.finished_at ? new Date(scopeCandidate!.row.finished_at) : null\n if (finishedDate) return 'completed'\n if (\n !heartbeatDate ||\n Date.now() - heartbeatDate.getTime() > HEARTBEAT_STALE_MS\n ) {\n return 'stalled'\n }\n return (scopeCandidate!.row.status as string) || 'reindexing'\n })(),\n processedCount: scopeCandidate.row.processed_count ?? null,\n totalCount: scopeCandidate.row.total_count ?? null,\n }\n : null,\n }\n } catch {\n return { status: 'idle' as const, partitions: [] as any[] }\n }\n }\n\n const normalizeCount = (value: unknown): number | null => {\n if (value == null) return null\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n\n const coverageScope = {\n tenantId: tenantId ?? null,\n organizationId,\n withDeleted: false,\n } as const\n const entitiesNeedingRefresh = new Set<string>()\n\n // Read every entity's coverage snapshot in a single batched query. This endpoint is\n // polled by the status table every few seconds, so the poll path must stay read-cheap:\n // stale snapshots are refreshed asynchronously via the query_index.coverage.refresh\n // event emitted below, never inline per entity.\n const snapshotByEntity = await readCoverageSnapshots(db, { entityTypes: entityIds, ...coverageScope })\n\n // An explicit refresh action (?refresh) may block, but only when the durable\n // coverage snapshots are stale. Recent persisted snapshots survive workers/restarts,\n // so repeated refresh requests use them instead of hammering base-table counts.\n if (forceRefresh && entityIds.length > 0 && !hasFreshCoverageSnapshots(snapshotByEntity, entityIds, Date.now())) {\n await mapWithConcurrency(entityIds, COVERAGE_REFRESH_CONCURRENCY, (entityId) =>\n refreshCoverageSnapshot(em, { entityType: entityId, ...coverageScope }).catch(() => undefined),\n )\n const refreshed = await readCoverageSnapshots(db, { entityTypes: entityIds, ...coverageScope })\n for (const [entityId, snapshot] of refreshed) snapshotByEntity.set(entityId, snapshot)\n }\n\n const coverageSnapshots = entityIds.map((entityId) => snapshotByEntity.get(entityId) ?? null)\n\n const jobs = await Promise.all(entityIds.map((eid) => fetchJobSummary(eid, tenantId, organizationId)))\n\n const items: any[] = []\n for (let idx = 0; idx < entityIds.length; idx += 1) {\n const eid = entityIds[idx]\n let coverage = coverageSnapshots[idx]\n\n const refreshedAt = coverage?.refreshed_at instanceof Date ? coverage.refreshed_at : coverage?.refreshed_at ? new Date(coverage.refreshed_at) : null\n const isStale = !coverage || !refreshedAt || (Date.now() - refreshedAt.getTime() > COVERAGE_STALE_MS)\n if (isStale) entitiesNeedingRefresh.add(eid)\n\n const job = jobs[idx]\n const label = (byId.get(eid)?.label) || eid\n const baseCountNumber = normalizeCount(coverage?.baseCount)\n const indexCountNumber = normalizeCount(coverage?.indexedCount)\n const vectorEnabled = vectorEnabledEntities.has(eid)\n const vectorCountNumber = vectorEnabled ? normalizeCount((coverage as any)?.vectorIndexedCount ?? (coverage as any)?.vector_indexed_count) : null\n const fulltextEnabled = fulltextEnabledEntities.has(eid)\n const fulltextCountNumber = fulltextEnabled ? (fulltextEntityCounts?.[eid] ?? 0) : null\n const ok = (() => {\n if (baseCountNumber == null || indexCountNumber == null) return false\n if (baseCountNumber !== indexCountNumber) return false\n if (!vectorEnabled) return true\n return vectorCountNumber != null && vectorCountNumber === baseCountNumber\n })()\n items.push({\n entityId: eid,\n label,\n baseCount: baseCountNumber,\n indexCount: indexCountNumber,\n vectorCount: vectorEnabled ? vectorCountNumber : null,\n vectorEnabled,\n fulltextCount: fulltextCountNumber,\n fulltextEnabled,\n ok,\n job,\n refreshedAt: refreshedAt ?? null,\n })\n }\n\n if (!forceRefresh) {\n try {\n const eventBus = container.resolve('eventBus')\n if (entitiesNeedingRefresh.size > 0) {\n await Promise.all(\n Array.from(entitiesNeedingRefresh).map((entityId) =>\n eventBus\n .emitEvent('query_index.coverage.refresh', {\n entityType: entityId,\n tenantId: tenantId ?? null,\n organizationId,\n delayMs: 0,\n })\n .catch(() => undefined)\n )\n )\n }\n } catch {}\n }\n\n let errorQuery = db\n .selectFrom('indexer_error_logs' as any)\n .selectAll()\n if (tenantId != null) {\n errorQuery = errorQuery.where((eb: any) => eb.or([\n eb('tenant_id' as any, '=', tenantId),\n eb('tenant_id' as any, 'is', null),\n ]))\n } else {\n errorQuery = errorQuery.where('tenant_id' as any, 'is', null as any)\n }\n if (Array.isArray(organizationScopeIds) && organizationScopeIds.length) {\n errorQuery = errorQuery.where((eb: any) => eb.or([\n eb('organization_id' as any, 'is', null),\n eb('organization_id' as any, 'in', organizationScopeIds),\n ]))\n } else {\n errorQuery = errorQuery.where('organization_id' as any, 'is', null as any)\n }\n const errorRows = await errorQuery\n .orderBy('occurred_at' as any, 'desc')\n .limit(100)\n .execute() as Array<Record<string, any>>\n\n const errors = errorRows.map((row: any) => {\n const occurredAt = row.occurred_at instanceof Date ? row.occurred_at : row.occurred_at ? new Date(row.occurred_at) : null\n return {\n id: String(row.id),\n source: String(row.source ?? ''),\n handler: String(row.handler ?? ''),\n entityType: row.entity_type ?? null,\n recordId: row.record_id ?? null,\n tenantId: row.tenant_id ?? null,\n organizationId: row.organization_id ?? null,\n message: String(row.message ?? ''),\n stack: row.stack ?? null,\n payload: row.payload ?? null,\n occurredAt: occurredAt ? occurredAt.toISOString() : new Date().toISOString(),\n }\n })\n\n let logsQuery = db\n .selectFrom('indexer_status_logs' as any)\n .selectAll()\n if (tenantId != null) {\n logsQuery = logsQuery.where((eb: any) => eb.or([\n eb('tenant_id' as any, '=', tenantId),\n eb('tenant_id' as any, 'is', null),\n ]))\n } else {\n logsQuery = logsQuery.where('tenant_id' as any, 'is', null as any)\n }\n if (Array.isArray(organizationScopeIds) && organizationScopeIds.length) {\n logsQuery = logsQuery.where((eb: any) => eb.or([\n eb('organization_id' as any, 'is', null),\n eb('organization_id' as any, 'in', organizationScopeIds),\n ]))\n } else {\n logsQuery = logsQuery.where('organization_id' as any, 'is', null as any)\n }\n const logRows = await logsQuery\n .orderBy('occurred_at' as any, 'desc')\n .limit(100)\n .execute() as Array<Record<string, any>>\n\n const logs = logRows.map((row: any) => {\n const occurredAt = row.occurred_at instanceof Date ? row.occurred_at : row.occurred_at ? new Date(row.occurred_at) : null\n const level = row.level === 'warn' ? 'warn' : 'info'\n return {\n id: String(row.id),\n source: String(row.source ?? ''),\n handler: String(row.handler ?? ''),\n level,\n entityType: row.entity_type ?? null,\n recordId: row.record_id ?? null,\n tenantId: row.tenant_id ?? null,\n organizationId: row.organization_id ?? null,\n message: String(row.message ?? ''),\n details: row.details ?? null,\n occurredAt: occurredAt ? occurredAt.toISOString() : new Date().toISOString(),\n }\n })\n\n const response = NextResponse.json({ items, errors, logs })\n const partial = items.find((item) => {\n // Coverage not computed yet (no snapshot) \u2014 pending an async refresh, not a partial\n // index. Do not raise the partial-index warning while counts are still unknown.\n if (item.baseCount == null && item.indexCount == null) return false\n if (item.baseCount == null || item.indexCount == null) return true\n return item.baseCount !== item.indexCount\n })\n if (partial) {\n response.headers.set(\n 'x-om-partial-index',\n JSON.stringify({\n type: 'partial_index',\n entity: partial.entityId,\n entityLabel: partial.label ?? partial.entityId,\n baseCount: partial.baseCount,\n indexedCount: partial.indexCount,\n scope: organizationId,\n })\n )\n }\n return response\n}\n\nconst queryIndexStatusDoc: OpenApiMethodDoc = {\n summary: 'Inspect query index coverage',\n description: 'Returns entity counts comparing base tables with the query index along with the latest job status.',\n tags: [queryIndexTag],\n responses: [\n { status: 200, description: 'Current query index status.', schema: queryIndexStatusResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Tenant or organization context required', schema: queryIndexErrorSchema },\n { status: 401, description: 'Authentication required', schema: queryIndexErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: queryIndexTag,\n summary: 'Query index status',\n methods: {\n GET: queryIndexStatusDoc,\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAE7B,SAAS,WAAW;AACpB,SAAS,uBAAuB,+BAAsD;AACtF,SAAS,0BAA0B;AAInC,SAAS,eAAe,uBAAuB,sCAAsC;AACrF,SAAS,8BAA8B;AACvC,SAAS,0CAA0C;AAE5C,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,yBAAyB,EAAE;AACzE;AAEA,MAAM,6BAA6B;AAEnC,SAAS,+BAA+B,UAAoF;AAC1H,QAAM,QAAQ,UAAU;AACxB,MAAI,iBAAiB,MAAM;AACzB,UAAM,OAAO,MAAM,QAAQ;AAC3B,WAAO,OAAO,SAAS,IAAI,IAAI,OAAO;AAAA,EACxC;AACA,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,OAAO,IAAI,KAAK,KAAK,EAAE,QAAQ;AACrC,WAAO,OAAO,SAAS,IAAI,IAAI,OAAO;AAAA,EACxC;AACA,SAAO;AACT;AAEA,SAAS,0BACP,WACA,WACA,KACS;AACT,aAAW,YAAY,WAAW;AAChC,UAAM,cAAc,+BAA+B,UAAU,IAAI,QAAQ,CAAC;AAC1E,QAAI,gBAAgB,QAAQ,MAAM,eAAe,2BAA4B,QAAO;AAAA,EACtF;AACA,SAAO,UAAU,SAAS;AAC5B;AAEA,eAAsB,IAAI,KAAc;AACtC,QAAM,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/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { sql } from 'kysely'\nimport { readCoverageSnapshots, refreshCoverageSnapshot, type CoverageSnapshot } from '../lib/coverage'\nimport { mapWithConcurrency } from '@open-mercato/shared/lib/query/bounded-decrypt'\nimport type { FullTextSearchStrategy } from '@open-mercato/search/strategies'\nimport type { SearchModuleConfig } from '@open-mercato/shared/modules/search'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { queryIndexTag, queryIndexErrorSchema, queryIndexStatusResponseSchema } from './openapi'\nimport { flattenSystemEntityIds } from '@open-mercato/shared/lib/entities/system-entities'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['query_index.status.view'] },\n}\n\nconst STATUS_REFRESH_COOLDOWN_MS = 60_000\n\nfunction getCoverageSnapshotRefreshedAt(snapshot: Pick<CoverageSnapshot, 'refreshed_at'> | null | undefined): number | null {\n const value = snapshot?.refreshed_at\n if (value instanceof Date) {\n const time = value.getTime()\n return Number.isFinite(time) ? time : null\n }\n if (typeof value === 'string') {\n const time = new Date(value).getTime()\n return Number.isFinite(time) ? time : null\n }\n return null\n}\n\nfunction hasFreshCoverageSnapshots(\n snapshots: Map<string, CoverageSnapshot>,\n entityIds: string[],\n now: number,\n): boolean {\n for (const entityId of entityIds) {\n const refreshedAt = getCoverageSnapshotRefreshedAt(snapshots.get(entityId))\n if (refreshedAt === null || now - refreshedAt >= STATUS_REFRESH_COOLDOWN_MS) return false\n }\n return entityIds.length > 0\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const db = (em as any).getKysely()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n\n const organizationId = scope.selectedId ?? auth.orgId ?? null\n const tenantId = typeof scope.tenantId === 'string' && scope.tenantId.trim().length > 0\n ? scope.tenantId.trim()\n : (typeof auth.tenantId === 'string' && auth.tenantId.trim().length > 0 ? auth.tenantId.trim() : null)\n if (!tenantId) {\n return NextResponse.json({ error: 'Tenant context is required' }, { status: 400 })\n }\n\n const organizationFilter =\n scope.filterIds === null\n ? null\n : Array.isArray(scope.filterIds) && scope.filterIds.length > 0\n ? scope.filterIds\n : organizationId\n ? [organizationId]\n : []\n\n if (Array.isArray(organizationFilter) && organizationFilter.length === 0) {\n return NextResponse.json({ error: 'Organization access denied' }, { status: 403 })\n }\n\n const organizationScopeIds = organizationFilter === null\n ? null\n : Array.from(\n new Set(\n organizationFilter.filter(\n (value): value is string => typeof value === 'string' && value.length > 0,\n ),\n ),\n )\n\n if (Array.isArray(organizationScopeIds) && organizationScopeIds.length === 0) {\n return NextResponse.json({ error: 'Organization access denied' }, { status: 403 })\n }\n\n const url = new URL(req.url)\n const forceRefresh = url.searchParams.has('refresh') && url.searchParams.get('refresh') !== '0'\n\n const generatedIds = flattenSystemEntityIds(getEntityIds() as Record<string, Record<string, string>>)\n const generated = generatedIds.map((entityId) => ({ entityId, label: entityId }))\n\n const byId = new Map<string, { entityId: string; label: string }>()\n for (const g of generated) byId.set(g.entityId, g)\n\n let entityIds = generatedIds.slice()\n\n // Resolve search module configs to determine vector-enabled entities\n // Entities with buildSource defined are vector-search enabled\n let searchModuleConfigs: SearchModuleConfig[] = []\n try {\n searchModuleConfigs = container.resolve('searchModuleConfigs') as SearchModuleConfig[]\n } catch {\n // Search module configs not available\n }\n\n const vectorEnabledEntities = new Set<string>()\n const fulltextEnabledEntities = new Set<string>()\n for (const moduleConfig of searchModuleConfigs) {\n for (const entity of moduleConfig.entities ?? []) {\n if (entity.enabled !== false) {\n // Vector: entities with buildSource defined\n if (typeof entity.buildSource === 'function') {\n vectorEnabledEntities.add(entity.entityId)\n }\n // Fulltext: entities with fieldPolicy defined\n if (entity.fieldPolicy && typeof entity.fieldPolicy === 'object') {\n fulltextEnabledEntities.add(entity.entityId)\n }\n }\n }\n }\n\n // Resolve fulltext strategy for entity counts\n let fulltextStrategy: FullTextSearchStrategy | null = null\n try {\n const searchStrategies = container.resolve('searchStrategies') as unknown[]\n fulltextStrategy = (searchStrategies?.find(\n (s: unknown) => (s as { id?: string })?.id === 'fulltext',\n ) as FullTextSearchStrategy) ?? null\n } catch {\n fulltextStrategy = null\n }\n\n // Fetch fulltext entity counts\n let fulltextEntityCounts: Record<string, number> | null = null\n if (fulltextStrategy) {\n try {\n fulltextEntityCounts = await fulltextStrategy.getEntityCounts(tenantId)\n } catch {\n fulltextEntityCounts = null\n }\n }\n\n // Limit to entities that have active custom field definitions in current scope\n try {\n let cfQuery = db\n .selectFrom('custom_field_defs' as any)\n .select(['entity_id' as any])\n .distinct()\n .where('is_active' as any, '=', true)\n if (tenantId != null) {\n cfQuery = cfQuery.where((eb: any) => eb.or([\n eb('tenant_id' as any, '=', tenantId),\n eb('tenant_id' as any, 'is', null),\n ]))\n } else {\n cfQuery = cfQuery.where('tenant_id' as any, 'is', null as any)\n }\n if (Array.isArray(organizationScopeIds)) {\n cfQuery = cfQuery.where((eb: any) => eb.or([\n eb('organization_id' as any, 'in', organizationScopeIds),\n eb('organization_id' as any, 'is', null),\n ]))\n }\n const cfRows = await cfQuery.execute() as Array<{ entity_id: string }>\n const enabled = new Set<string>((cfRows || []).map((r) => String(r.entity_id)))\n entityIds = entityIds.filter((id) => enabled.has(id))\n } catch {}\n\n const HEARTBEAT_STALE_MS = 60_000\n const COVERAGE_STALE_MS = 60_000\n const COVERAGE_REFRESH_CONCURRENCY = 8\n\n async function fetchJobSummary(entityType: string, tenantIdParam: string | null, organizationIdParam: string | null) {\n try {\n let jobQuery = db\n .selectFrom('entity_index_jobs' as any)\n .selectAll()\n .where('entity_type' as any, '=', entityType)\n .where(sql<boolean>`tenant_id is not distinct from ${tenantIdParam ?? null}`)\n if (organizationIdParam != null) {\n jobQuery = jobQuery.where((eb: any) => eb.or([\n eb('organization_id' as any, '=', organizationIdParam),\n eb('organization_id' as any, 'is', null),\n ]))\n } else {\n jobQuery = jobQuery.where(sql<boolean>`organization_id is not distinct from ${null}`)\n }\n const rows = await jobQuery\n .orderBy('started_at' as any, 'desc')\n .execute() as Array<Record<string, any>>\n\n if (!rows.length) {\n return { status: 'idle' as const, partitions: [] as any[] }\n }\n\n const preferOrg =\n organizationIdParam != null && rows.some((row: any) => row.organization_id === organizationIdParam)\n const pickPreferred = <T extends { startedTs: number; tenantMatch: boolean; orgMatch: boolean }>(\n existing: T | null,\n candidate: T,\n ): T => {\n if (!existing) return candidate\n if (preferOrg) {\n if (candidate.orgMatch && !existing.orgMatch) return candidate\n if (!candidate.orgMatch && existing.orgMatch) return existing\n }\n if (candidate.tenantMatch && !existing.tenantMatch) return candidate\n if (!candidate.tenantMatch && existing.tenantMatch) return existing\n return candidate.startedTs > existing.startedTs ? candidate : existing\n }\n\n const partitionRows = new Map<string, { row: any; startedTs: number; tenantMatch: boolean; orgMatch: boolean }>()\n let scopeRow: { row: any; startedTs: number; tenantMatch: boolean; orgMatch: boolean } | null = null\n for (const row of rows) {\n const key = String(row.partition_index ?? '__null__')\n const startedTs = row.started_at ? new Date(row.started_at).getTime() : 0\n const tenantMatch = tenantIdParam != null ? row.tenant_id === tenantIdParam : true\n const orgMatch = organizationIdParam != null ? row.organization_id === organizationIdParam : row.organization_id == null\n const candidate = { row, startedTs, tenantMatch, orgMatch }\n if (row.partition_index == null) {\n scopeRow = pickPreferred(scopeRow, candidate)\n continue\n }\n const existing = partitionRows.get(key)\n partitionRows.set(key, pickPreferred(existing ?? null, candidate))\n }\n\n const partitions = Array.from(partitionRows.values())\n .filter((entry) => !preferOrg || entry.orgMatch)\n .map(({ row }) => {\n const heartbeatDate = row.heartbeat_at ? new Date(row.heartbeat_at) : null\n const startedDate = row.started_at ? new Date(row.started_at) : null\n const finishedDate = row.finished_at ? new Date(row.finished_at) : null\n const stalled =\n !finishedDate && (!heartbeatDate || Date.now() - heartbeatDate.getTime() > HEARTBEAT_STALE_MS)\n const state = finishedDate\n ? 'completed'\n : stalled\n ? 'stalled'\n : (row.status as string) || 'reindexing'\n return {\n partitionIndex: row.partition_index ?? null,\n partitionCount: row.partition_count ?? null,\n status: state,\n startedAt: startedDate ? startedDate.toISOString() : null,\n finishedAt: finishedDate ? finishedDate.toISOString() : null,\n heartbeatAt: heartbeatDate ? heartbeatDate.toISOString() : null,\n processedCount: row.processed_count ?? null,\n totalCount: row.total_count ?? null,\n }\n })\n .sort((a, b) => (a.partitionIndex ?? 0) - (b.partitionIndex ?? 0))\n const activePartitions = partitions.filter((p) => !p.finishedAt)\n const runningPartitions = activePartitions.filter(\n (p) => p.status === 'reindexing' || p.status === 'purging',\n )\n const stalledPartitions = activePartitions.filter((p) => p.status === 'stalled')\n let status: 'idle' | 'reindexing' | 'purging' | 'stalled' = 'idle'\n if (activePartitions.length) {\n if (runningPartitions.length) {\n status = runningPartitions.some((p) => p.status === 'purging') ? 'purging' : 'reindexing'\n } else if (stalledPartitions.length) {\n status = 'stalled'\n }\n }\n\n const startedAt = activePartitions[0]?.startedAt ?? partitions[0]?.startedAt ?? null\n const finishedAt = status === 'idle' ? (partitions.find((p) => p.finishedAt)?.finishedAt ?? null) : null\n const heartbeatAt = activePartitions[0]?.heartbeatAt ?? partitions[0]?.heartbeatAt ?? null\n const jobTotalCount = partitions.reduce((sum, p) => sum + (p.totalCount ?? 0), 0)\n const processedSum = partitions.reduce((sum, p) => sum + (p.processedCount ?? 0), 0)\n const processedCount = jobTotalCount ? Math.min(jobTotalCount, processedSum) : processedSum || null\n const scopeCandidate = !preferOrg || !scopeRow || scopeRow.orgMatch ? scopeRow : null\n\n return {\n status,\n startedAt,\n finishedAt,\n heartbeatAt,\n processedCount: jobTotalCount ? processedCount : scopeCandidate?.row?.processed_count ?? null,\n totalCount: jobTotalCount ? jobTotalCount : scopeCandidate?.row?.total_count ?? null,\n partitions,\n scope: scopeCandidate\n ? {\n status: (() => {\n const heartbeatDate = scopeCandidate!.row.heartbeat_at ? new Date(scopeCandidate!.row.heartbeat_at) : null\n const finishedDate = scopeCandidate!.row.finished_at ? new Date(scopeCandidate!.row.finished_at) : null\n if (finishedDate) return 'completed'\n if (\n !heartbeatDate ||\n Date.now() - heartbeatDate.getTime() > HEARTBEAT_STALE_MS\n ) {\n return 'stalled'\n }\n return (scopeCandidate!.row.status as string) || 'reindexing'\n })(),\n processedCount: scopeCandidate.row.processed_count ?? null,\n totalCount: scopeCandidate.row.total_count ?? null,\n }\n : null,\n }\n } catch {\n return { status: 'idle' as const, partitions: [] as any[] }\n }\n }\n\n const normalizeCount = (value: unknown): number | null => {\n if (value == null) return null\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n\n const coverageScope = {\n tenantId: tenantId ?? null,\n organizationId,\n withDeleted: false,\n } as const\n const entitiesNeedingRefresh = new Set<string>()\n\n // Read every entity's coverage snapshot in a single batched query. This endpoint is\n // polled by the status table every few seconds, so the poll path must stay read-cheap:\n // stale snapshots are refreshed asynchronously via the query_index.coverage.refresh\n // event emitted below, never inline per entity.\n const snapshotByEntity = await readCoverageSnapshots(db, { entityTypes: entityIds, ...coverageScope })\n\n // An explicit refresh action (?refresh) may block, but only when the durable\n // coverage snapshots are stale. Recent persisted snapshots survive workers/restarts,\n // so repeated refresh requests use them instead of hammering base-table counts.\n if (forceRefresh && entityIds.length > 0 && !hasFreshCoverageSnapshots(snapshotByEntity, entityIds, Date.now())) {\n await mapWithConcurrency(entityIds, COVERAGE_REFRESH_CONCURRENCY, (entityId) =>\n refreshCoverageSnapshot(em, { entityType: entityId, ...coverageScope }).catch(() => undefined),\n )\n const refreshed = await readCoverageSnapshots(db, { entityTypes: entityIds, ...coverageScope })\n for (const [entityId, snapshot] of refreshed) snapshotByEntity.set(entityId, snapshot)\n }\n\n const coverageSnapshots = entityIds.map((entityId) => snapshotByEntity.get(entityId) ?? null)\n\n const jobs = await Promise.all(entityIds.map((eid) => fetchJobSummary(eid, tenantId, organizationId)))\n\n const items: any[] = []\n for (let idx = 0; idx < entityIds.length; idx += 1) {\n const eid = entityIds[idx]\n let coverage = coverageSnapshots[idx]\n\n const refreshedAt = coverage?.refreshed_at instanceof Date ? coverage.refreshed_at : coverage?.refreshed_at ? new Date(coverage.refreshed_at) : null\n const isStale = !coverage || !refreshedAt || (Date.now() - refreshedAt.getTime() > COVERAGE_STALE_MS)\n if (isStale) entitiesNeedingRefresh.add(eid)\n\n const job = jobs[idx]\n const label = (byId.get(eid)?.label) || eid\n const baseCountNumber = normalizeCount(coverage?.baseCount)\n const indexCountNumber = normalizeCount(coverage?.indexedCount)\n const vectorEnabled = vectorEnabledEntities.has(eid)\n const vectorCountNumber = vectorEnabled ? normalizeCount((coverage as any)?.vectorIndexedCount ?? (coverage as any)?.vector_indexed_count) : null\n const fulltextEnabled = fulltextEnabledEntities.has(eid)\n const fulltextCountNumber = fulltextEnabled ? (fulltextEntityCounts?.[eid] ?? 0) : null\n const ok = (() => {\n if (baseCountNumber == null || indexCountNumber == null) return false\n if (baseCountNumber !== indexCountNumber) return false\n if (!vectorEnabled) return true\n return vectorCountNumber != null && vectorCountNumber === baseCountNumber\n })()\n items.push({\n entityId: eid,\n label,\n baseCount: baseCountNumber,\n indexCount: indexCountNumber,\n vectorCount: vectorEnabled ? vectorCountNumber : null,\n vectorEnabled,\n fulltextCount: fulltextCountNumber,\n fulltextEnabled,\n ok,\n job,\n refreshedAt: refreshedAt ?? null,\n })\n }\n\n if (!forceRefresh) {\n try {\n const eventBus = container.resolve('eventBus')\n if (entitiesNeedingRefresh.size > 0) {\n await Promise.all(\n Array.from(entitiesNeedingRefresh).map((entityId) =>\n eventBus\n .emitEvent('query_index.coverage.refresh', {\n entityType: entityId,\n tenantId: tenantId ?? null,\n organizationId,\n delayMs: 0,\n })\n .catch(() => undefined)\n )\n )\n }\n } catch {}\n }\n\n let errorQuery = db\n .selectFrom('indexer_error_logs' as any)\n .selectAll()\n if (tenantId != null) {\n errorQuery = errorQuery.where((eb: any) => eb.or([\n eb('tenant_id' as any, '=', tenantId),\n eb('tenant_id' as any, 'is', null),\n ]))\n } else {\n errorQuery = errorQuery.where('tenant_id' as any, 'is', null as any)\n }\n if (Array.isArray(organizationScopeIds) && organizationScopeIds.length) {\n errorQuery = errorQuery.where('organization_id' as any, 'in', organizationScopeIds)\n } else {\n errorQuery = errorQuery.where('organization_id' as any, 'is', null as any)\n }\n const errorRows = await errorQuery\n .orderBy('occurred_at' as any, 'desc')\n .limit(100)\n .execute() as Array<Record<string, any>>\n\n const errors = errorRows.map((row: any) => {\n const occurredAt = row.occurred_at instanceof Date ? row.occurred_at : row.occurred_at ? new Date(row.occurred_at) : null\n return {\n id: String(row.id),\n source: String(row.source ?? ''),\n handler: String(row.handler ?? ''),\n entityType: row.entity_type ?? null,\n recordId: row.record_id ?? null,\n tenantId: row.tenant_id ?? null,\n organizationId: row.organization_id ?? null,\n message: String(row.message ?? ''),\n stack: row.stack ?? null,\n payload: row.payload ?? null,\n occurredAt: occurredAt ? occurredAt.toISOString() : new Date().toISOString(),\n }\n })\n\n let logsQuery = db\n .selectFrom('indexer_status_logs' as any)\n .selectAll()\n if (tenantId != null) {\n logsQuery = logsQuery.where((eb: any) => eb.or([\n eb('tenant_id' as any, '=', tenantId),\n eb('tenant_id' as any, 'is', null),\n ]))\n } else {\n logsQuery = logsQuery.where('tenant_id' as any, 'is', null as any)\n }\n if (Array.isArray(organizationScopeIds) && organizationScopeIds.length) {\n logsQuery = logsQuery.where('organization_id' as any, 'in', organizationScopeIds)\n } else {\n logsQuery = logsQuery.where('organization_id' as any, 'is', null as any)\n }\n const logRows = await logsQuery\n .orderBy('occurred_at' as any, 'desc')\n .limit(100)\n .execute() as Array<Record<string, any>>\n\n const logs = logRows.map((row: any) => {\n const occurredAt = row.occurred_at instanceof Date ? row.occurred_at : row.occurred_at ? new Date(row.occurred_at) : null\n const level = row.level === 'warn' ? 'warn' : 'info'\n return {\n id: String(row.id),\n source: String(row.source ?? ''),\n handler: String(row.handler ?? ''),\n level,\n entityType: row.entity_type ?? null,\n recordId: row.record_id ?? null,\n tenantId: row.tenant_id ?? null,\n organizationId: row.organization_id ?? null,\n message: String(row.message ?? ''),\n details: row.details ?? null,\n occurredAt: occurredAt ? occurredAt.toISOString() : new Date().toISOString(),\n }\n })\n\n const response = NextResponse.json({ items, errors, logs })\n const partial = items.find((item) => {\n // Coverage not computed yet (no snapshot) \u2014 pending an async refresh, not a partial\n // index. Do not raise the partial-index warning while counts are still unknown.\n if (item.baseCount == null && item.indexCount == null) return false\n if (item.baseCount == null || item.indexCount == null) return true\n return item.baseCount !== item.indexCount\n })\n if (partial) {\n response.headers.set(\n 'x-om-partial-index',\n JSON.stringify({\n type: 'partial_index',\n entity: partial.entityId,\n entityLabel: partial.label ?? partial.entityId,\n baseCount: partial.baseCount,\n indexedCount: partial.indexCount,\n scope: organizationId,\n })\n )\n }\n return response\n}\n\nconst queryIndexStatusDoc: OpenApiMethodDoc = {\n summary: 'Inspect query index coverage',\n description: 'Returns entity counts comparing base tables with the query index along with the latest job status.',\n tags: [queryIndexTag],\n responses: [\n { status: 200, description: 'Current query index status.', schema: queryIndexStatusResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Tenant or organization context required', schema: queryIndexErrorSchema },\n { status: 401, description: 'Authentication required', schema: queryIndexErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: queryIndexTag,\n summary: 'Query index status',\n methods: {\n GET: queryIndexStatusDoc,\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAE7B,SAAS,WAAW;AACpB,SAAS,uBAAuB,+BAAsD;AACtF,SAA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,IACH;AAAA,EACF;AACA,SAAO;AACT;AAEA,MAAM,sBAAwC;AAAA,EAC5C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,aAAa;AAAA,EACpB,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,+BAA+B,QAAQ,+BAA+B;AAAA,EACpG;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,2CAA2C,QAAQ,sBAAsB;AAAA,IACrG,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,EACvF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,EACP;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -5,6 +5,7 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
|
|
5
5
|
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
|
|
6
6
|
import { FormHeader } from "@open-mercato/ui/backend/forms";
|
|
7
7
|
import { Button } from "@open-mercato/ui/primitives/button";
|
|
8
|
+
import { Tabs, TabsList, TabsTrigger } from "@open-mercato/ui/primitives/tabs";
|
|
8
9
|
import { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
|
|
9
10
|
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
|
|
10
11
|
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
|
|
@@ -517,35 +518,34 @@ function ResourcesResourceDetailPage({ params }) {
|
|
|
517
518
|
subtitle: t("resources.resources.detail.subtitle", "Resource profile and activity")
|
|
518
519
|
}
|
|
519
520
|
),
|
|
520
|
-
/* @__PURE__ */ jsx(
|
|
521
|
-
|
|
521
|
+
/* @__PURE__ */ jsx(
|
|
522
|
+
Tabs,
|
|
522
523
|
{
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
"
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
524
|
+
value: activeTab,
|
|
525
|
+
onValueChange: (value) => setActiveTab(value),
|
|
526
|
+
variant: "underline",
|
|
527
|
+
children: /* @__PURE__ */ jsx(
|
|
528
|
+
TabsList,
|
|
529
|
+
{
|
|
530
|
+
className: "w-full flex-wrap",
|
|
531
|
+
"aria-label": t("resources.resources.tabs.label", "Resource sections"),
|
|
532
|
+
children: tabs.map((tab) => /* @__PURE__ */ jsx(TabsTrigger, { value: tab.id, children: tab.label }, tab.id))
|
|
533
|
+
}
|
|
534
|
+
)
|
|
535
|
+
}
|
|
536
|
+
),
|
|
534
537
|
activeTab === "details" ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
535
538
|
/* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
|
|
536
539
|
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
|
|
537
|
-
/* @__PURE__ */ jsx(
|
|
538
|
-
|
|
540
|
+
/* @__PURE__ */ jsx(
|
|
541
|
+
Tabs,
|
|
539
542
|
{
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
},
|
|
547
|
-
tab.id
|
|
548
|
-
)) }),
|
|
543
|
+
value: activeDetailTab,
|
|
544
|
+
onValueChange: (value) => setActiveDetailTab(value),
|
|
545
|
+
variant: "underline",
|
|
546
|
+
children: /* @__PURE__ */ jsx(TabsList, { className: "h-auto flex-wrap border-b-0", children: detailTabs.map((tab) => /* @__PURE__ */ jsx(TabsTrigger, { value: tab.id, children: tab.label }, tab.id)) })
|
|
547
|
+
}
|
|
548
|
+
),
|
|
549
549
|
sectionAction ? /* @__PURE__ */ jsxs(
|
|
550
550
|
Button,
|
|
551
551
|
{
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/resources/backend/resources/resources/%5Bid%5D/page.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { usePathname, useRouter, useSearchParams } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { FormHeader } from '@open-mercato/ui/backend/forms'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { collectCustomFieldValues } from '@open-mercato/ui/backend/utils/customFieldValues'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { updateCrud, deleteCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { ActivitiesSection, NotesSection, RecordNotFoundState, type SectionAction, type TagOption } from '@open-mercato/ui/backend/detail'\nimport { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from '@open-mercato/ui/backend/injection/recordContext'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { VersionHistoryAction } from '@open-mercato/ui/backend/version-history'\nimport { SendObjectMessageDialog } from '@open-mercato/ui/backend/messages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { extractCustomFieldEntries } from '@open-mercato/shared/lib/crud/custom-fields-client'\nimport { createTranslatorWithFallback } from '@open-mercato/shared/lib/i18n/translate'\nimport { buildResourceScheduleItems } from '@open-mercato/core/modules/resources/lib/resourceSchedule'\nimport { RESOURCES_RESOURCE_FIELDSET_DEFAULT } from '@open-mercato/core/modules/resources/lib/resourceCustomFields'\nimport type { AvailabilityScheduleItemBuilder } from '@open-mercato/core/modules/planner/components/AvailabilityRulesEditor'\nimport { AvailabilityRulesEditor } from '@open-mercato/core/modules/planner/components/AvailabilityRulesEditor'\nimport { ResourcesResourceForm, useResourcesResourceFormConfig } from '@open-mercato/core/modules/resources/components/ResourceCrudForm'\nimport { renderDictionaryColor, renderDictionaryIcon, ICON_SUGGESTIONS } from '@open-mercato/core/modules/dictionaries/components/dictionaryAppearance'\nimport { createResourceNotesAdapter } from '@open-mercato/core/modules/resources/components/detail/notesAdapter'\nimport { createResourceActivitiesAdapter } from '@open-mercato/core/modules/resources/components/detail/activitiesAdapter'\nimport {\n createResourceDictionaryEntry,\n loadResourceDictionary,\n type DictionaryEntryOption,\n} from '@open-mercato/core/modules/resources/components/detail/dictionaries'\nimport type { DictionarySelectLabels } from '@open-mercato/core/modules/dictionaries/components/DictionaryEntrySelect'\n\ntype ResourceRecord = {\n id: string\n name: string\n description?: string | null\n resourceTypeId: string | null\n capacity: number | null\n capacityUnitValue: string | null\n capacityUnitName: string | null\n capacityUnitColor: string | null\n capacityUnitIcon: string | null\n tags?: TagOption[] | null\n isActive: boolean\n appearanceIcon?: string | null\n appearanceColor?: string | null\n resource_type_id?: string | null\n capacity_unit_value?: string | null\n capacity_unit_name?: string | null\n capacity_unit_color?: string | null\n capacity_unit_icon?: string | null\n appearance_icon?: string | null\n appearance_color?: string | null\n is_active?: boolean\n availabilityRuleSetId?: string | null\n availability_rule_set_id?: string | null\n} & Record<string, unknown>\n\ntype ResourceResponse = {\n items: ResourceRecord[]\n}\n\ntype ResourceDetailMutationContext = {\n formId: string\n resourceKind: string\n resourceId?: string\n data: Record<string, unknown> | null\n retryLastMutation: () => Promise<boolean>\n}\n\nfunction normalizeResourceRecord(record: ResourceRecord): ResourceRecord {\n return {\n ...record,\n resourceTypeId: record.resourceTypeId ?? record.resource_type_id ?? null,\n description: record.description ?? null,\n capacityUnitValue: record.capacityUnitValue ?? record.capacity_unit_value ?? null,\n capacityUnitName: record.capacityUnitName ?? record.capacity_unit_name ?? null,\n capacityUnitColor: record.capacityUnitColor ?? record.capacity_unit_color ?? null,\n capacityUnitIcon: record.capacityUnitIcon ?? record.capacity_unit_icon ?? null,\n appearanceIcon: record.appearanceIcon ?? record.appearance_icon ?? null,\n appearanceColor: record.appearanceColor ?? record.appearance_color ?? null,\n isActive: record.isActive ?? record.is_active ?? true,\n }\n}\n\nexport default function ResourcesResourceDetailPage({ params }: { params?: { id?: string } }) {\n const resourceId = params?.id\n const t = useT()\n const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t])\n const router = useRouter()\n const pathname = usePathname()\n const searchParams = useSearchParams()\n const [initialValues, setInitialValues] = React.useState<Record<string, unknown> | null>(null)\n const [isNotFound, setIsNotFound] = React.useState(false)\n // Capture the record (incl. its optimistic-lock `updatedAt`) exactly ONCE per\n // resource. The load effect's deps include identity-unstable values (`t`,\n // `resolveFieldsetCode`), so without this guard a re-render would re-fetch and\n // overwrite `initialValues.updatedAt` with a newer server value mid-edit \u2014\n // silently defeating optimistic locking (a concurrent change would no longer be\n // detected) and making the conflict flaky.\n const loadedResourceIdRef = React.useRef<string | null>(null)\n const [tags, setTags] = React.useState<TagOption[]>([])\n const [activeTab, setActiveTab] = React.useState<'details' | 'availability'>('details')\n const [activeDetailTab, setActiveDetailTab] = React.useState<'notes' | 'activities'>('notes')\n const [sectionAction, setSectionAction] = React.useState<SectionAction | null>(null)\n const [availabilityRuleSetId, setAvailabilityRuleSetId] = React.useState<string | null>(null)\n const [selectedCapacityUnit, setSelectedCapacityUnit] = React.useState<{\n value: string\n label: string\n color?: string | null\n icon?: string | null\n } | null>(null)\n const [activityDictionaryId, setActivityDictionaryId] = React.useState<string | null>(null)\n const [activityTypeEntries, setActivityTypeEntries] = React.useState<DictionaryEntryOption[]>([])\n const flashShownRef = React.useRef(false)\n\n const availabilityMode = 'availability'\n const mutationContextId = React.useMemo(\n () => (resourceId ? `resources.resource:${resourceId}` : 'resources.resource:pending'),\n [resourceId],\n )\n const { runMutation, retryLastMutation } = useGuardedMutation<ResourceDetailMutationContext>({\n contextId: mutationContextId,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n const mutationContext = React.useMemo<ResourceDetailMutationContext>(\n () => ({\n formId: mutationContextId,\n resourceKind: 'resources.resource',\n resourceId,\n data: initialValues,\n retryLastMutation,\n }),\n [initialValues, mutationContextId, resourceId, retryLastMutation],\n )\n const runMutationWithContext = React.useCallback(\n async <T,>(operation: () => Promise<T>, mutationPayload?: Record<string, unknown>): Promise<T> => (\n runMutation({\n operation,\n mutationPayload,\n context: mutationContext,\n })\n ),\n [mutationContext, runMutation],\n )\n const notesAdapter = React.useMemo(\n () => createResourceNotesAdapter(detailTranslator, { runMutation: runMutationWithContext }),\n [detailTranslator, runMutationWithContext],\n )\n const activitiesAdapter = React.useMemo(\n () => createResourceActivitiesAdapter(detailTranslator, { runMutation: runMutationWithContext }),\n [detailTranslator, runMutationWithContext],\n )\n\n const activityTypeLabels = React.useMemo<DictionarySelectLabels>(() => ({\n placeholder: t('resources.resources.detail.activities.dictionary.placeholder', 'Select an activity type'),\n addLabel: t('resources.resources.detail.activities.dictionary.add', 'Add type'),\n addPrompt: t('resources.resources.detail.activities.dictionary.prompt', 'Name the type'),\n dialogTitle: t('resources.resources.detail.activities.dictionary.dialogTitle', 'Add activity type'),\n valueLabel: t('resources.resources.detail.activities.dictionary.valueLabel', 'Name'),\n valuePlaceholder: t('resources.resources.detail.activities.dictionary.valuePlaceholder', 'Name'),\n labelLabel: t('resources.resources.detail.activities.dictionary.labelLabel', 'Label'),\n labelPlaceholder: t('resources.resources.detail.activities.dictionary.labelPlaceholder', 'Display name shown in UI'),\n emptyError: t('resources.resources.detail.activities.dictionary.emptyError', 'Please enter a name'),\n cancelLabel: t('resources.resources.detail.activities.dictionary.cancel', 'Cancel'),\n saveLabel: t('resources.resources.detail.activities.dictionary.save', 'Save'),\n saveShortcutHint: t('resources.resources.detail.activities.dictionary.saveShortcut', '\u2318/Ctrl + Enter'),\n errorLoad: t('resources.resources.detail.activities.dictionary.errorLoad', 'Failed to load options'),\n errorSave: t('resources.resources.detail.activities.dictionary.errorSave', 'Failed to save option'),\n loadingLabel: t('resources.resources.detail.activities.dictionary.loading', 'Loading\u2026'),\n manageTitle: t('resources.resources.detail.activities.dictionary.manage', 'Manage dictionary'),\n }), [t])\n\n const loadActivityOptions = React.useCallback(async () => {\n const { dictionary, entries } = await loadResourceDictionary('activityTypes')\n setActivityDictionaryId(dictionary?.id ?? null)\n setActivityTypeEntries(entries)\n return entries\n }, [])\n\n const createActivityOption = React.useCallback(\n async (input: { value: string; label?: string; color?: string | null; icon?: string | null }) => {\n const entry = await createResourceDictionaryEntry('activityTypes', input)\n if (!entry) {\n throw new Error(t('resources.resources.detail.activities.dictionary.errorSave', 'Failed to save option'))\n }\n return entry\n },\n [t],\n )\n\n React.useEffect(() => {\n loadActivityOptions().catch(() => {})\n }, [loadActivityOptions])\n\n const activityTypeMap = React.useMemo(\n () => new Map(activityTypeEntries.map((entry) => [entry.value, entry])),\n [activityTypeEntries],\n )\n\n const resolveActivityPresentation = React.useCallback(\n (activity: { activityType: string; appearanceIcon?: string | null; appearanceColor?: string | null }) => {\n const entry = activityTypeMap.get(activity.activityType)\n return {\n label: entry?.label ?? activity.activityType,\n icon: entry?.icon ?? activity.appearanceIcon ?? null,\n color: entry?.color ?? activity.appearanceColor ?? null,\n }\n },\n [activityTypeMap],\n )\n\n const manageActivityHref = React.useMemo(() => {\n if (!activityDictionaryId) return '/backend/config/dictionaries'\n return `/backend/config/dictionaries?dictionaryId=${encodeURIComponent(activityDictionaryId)}`\n }, [activityDictionaryId])\n\n const appearanceLabels = React.useMemo(() => ({\n colorLabel: t('resources.resources.detail.activities.appearance.colorLabel', 'Color'),\n colorHelp: t('resources.resources.detail.activities.appearance.colorHelp', 'Pick a highlight color for this entry.'),\n colorClearLabel: t('resources.resources.detail.activities.appearance.colorClear', 'Remove color'),\n iconLabel: t('resources.resources.detail.activities.appearance.iconLabel', 'Icon or emoji'),\n iconPlaceholder: t('resources.resources.detail.activities.appearance.iconPlaceholder', 'Type an emoji or pick one of the suggestions.'),\n iconPickerTriggerLabel: t('resources.resources.detail.activities.appearance.iconBrowse', 'Browse icons and emojis'),\n iconSearchPlaceholder: t('resources.resources.detail.activities.appearance.iconSearchPlaceholder', 'Search icons or emojis\u2026'),\n iconSearchEmptyLabel: t('resources.resources.detail.activities.appearance.iconSearchEmpty', 'No icons match your search.'),\n iconSuggestionsLabel: t('resources.resources.detail.activities.appearance.iconSuggestions', 'Suggestions'),\n iconClearLabel: t('resources.resources.detail.activities.appearance.iconClear', 'Remove icon'),\n previewEmptyLabel: t('resources.resources.detail.activities.appearance.previewEmpty', 'No appearance selected'),\n }), [t])\n\n const renderCustomFields = React.useCallback((activity: { id?: string; customFields?: Array<{ key: string; label?: string | null; value: unknown }> }) => {\n const entries = Array.isArray(activity.customFields) ? activity.customFields : []\n if (!entries.length) return null\n const emptyLabel = t('resources.resources.detail.activities.customFields.empty', 'Not provided')\n return (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {entries.map((entry, index) => {\n const label = entry.label ?? entry.key\n const value = entry.value\n const hasValue = !(value == null || value === '' || (Array.isArray(value) && value.length === 0))\n const content = hasValue\n ? Array.isArray(value)\n ? value.map((item) => String(item)).join(', ')\n : String(value)\n : emptyLabel\n return (\n <div\n key={`activity-${activity.id ?? 'row'}-custom-${index}`}\n className=\"rounded-md border border-border/70 bg-muted/30 px-3 py-2\"\n >\n <div className=\"text-xs font-medium text-muted-foreground\">{label}</div>\n <div className=\"mt-1 text-sm text-foreground\">{content}</div>\n </div>\n )\n })}\n </div>\n )\n }, [t])\n\n React.useEffect(() => {\n if (!searchParams) return\n const tabParam = searchParams.get('tab')\n if (tabParam === 'availability') {\n setActiveTab('availability')\n }\n const created = searchParams.get('created') === '1'\n if (created && !flashShownRef.current) {\n flashShownRef.current = true\n flash(t('resources.resources.flash.createdAvailability', 'Saved. You can now set availability.'), 'success')\n const nextParams = new URLSearchParams(searchParams.toString())\n nextParams.delete('created')\n const nextQuery = nextParams.toString()\n const nextPath = resourceId\n ? `/backend/resources/resources/${encodeURIComponent(resourceId)}${nextQuery ? `?${nextQuery}` : ''}`\n : `/backend/resources/resources${nextQuery ? `?${nextQuery}` : ''}`\n router.replace(nextPath)\n }\n }, [resourceId, router, searchParams, t])\n\n const buildScheduleItems = React.useCallback<AvailabilityScheduleItemBuilder>(\n ({ availabilityRules, translate }) => buildResourceScheduleItems({\n availabilityRules,\n isAvailableByDefault: false,\n translate,\n }),\n [],\n )\n\n const tagLabels = React.useMemo(\n () => ({\n loading: t('resources.resources.tags.loading', 'Loading tags...'),\n placeholder: t('resources.resources.tags.placeholder', 'Type to add tags'),\n empty: t('resources.resources.tags.placeholder', 'No tags yet. Add labels to keep resources organized.'),\n loadError: t('resources.resources.tags.loadError', 'Failed to load tags.'),\n createError: t('resources.resources.tags.createError', 'Failed to create tag.'),\n updateError: t('resources.resources.tags.updateError', 'Failed to update tags.'),\n labelRequired: t('resources.resources.tags.labelRequired', 'Tag name is required.'),\n saveShortcut: t('resources.resources.tags.saveShortcut', 'Save Cmd+Enter / Ctrl+Enter'),\n cancelShortcut: t('resources.resources.tags.cancelShortcut', 'Cancel (Esc)'),\n edit: t('ui.forms.actions.edit', 'Edit'),\n cancel: t('ui.forms.actions.cancel', 'Cancel'),\n success: t('resources.resources.tags.success', 'Tags updated.'),\n }),\n [t],\n )\n\n const handleSubmit = React.useCallback(async (values: Record<string, unknown>) => {\n if (!resourceId) return\n const appearance = values.appearance && typeof values.appearance === 'object'\n ? values.appearance as { icon?: string | null; color?: string | null }\n : {}\n const { appearance: _appearance, ...rest } = values\n const customFieldsetCode = typeof values.customFieldsetCode === 'string' && values.customFieldsetCode.trim().length\n ? values.customFieldsetCode.trim()\n : RESOURCES_RESOURCE_FIELDSET_DEFAULT\n const payload: Record<string, unknown> = {\n ...rest,\n id: resourceId,\n resourceTypeId: values.resourceTypeId || null,\n capacity: values.capacity ? Number(values.capacity) : null,\n capacityUnitValue: values.capacityUnitValue ? String(values.capacityUnitValue) : null,\n appearanceIcon: appearance.icon ?? null,\n appearanceColor: appearance.color ?? null,\n isActive: values.isActive ?? true,\n customFieldsetCode,\n ...collectCustomFieldValues(values),\n }\n if (!payload.name || String(payload.name).trim().length === 0) {\n throw createCrudFormError(t('resources.resources.form.errors.nameRequired', 'Name is required.'))\n }\n await updateCrud('resources/resources', payload, {\n errorMessage: t('resources.resources.form.errors.update', 'Failed to update resource.'),\n })\n flash(t('resources.resources.form.flash.updated', 'Resource updated.'), 'success')\n }, [resourceId, t])\n\n const tabs = React.useMemo(() => ([\n { id: 'details', label: t('resources.resources.tabs.details', 'Details') },\n { id: 'availability', label: t('resources.resources.tabs.availability', 'Availability') },\n ]), [t])\n const detailTabs = React.useMemo(() => ([\n { id: 'notes' as const, label: t('resources.resources.detail.tabs.notes', 'Notes') },\n { id: 'activities' as const, label: t('resources.resources.detail.tabs.activities', 'Activities') },\n ]), [t])\n\n const loadTagOptions = React.useCallback(\n async (query?: string): Promise<TagOption[]> => {\n const params = new URLSearchParams({ pageSize: '100' })\n if (query) params.set('search', query)\n const payload = await readApiResultOrThrow<Record<string, unknown>>(\n `/api/resources/tags?${params.toString()}`,\n undefined,\n { errorMessage: t('resources.resources.tags.loadError', 'Failed to load tags.') },\n )\n const items = Array.isArray(payload?.items) ? payload.items : []\n return items\n .map((item: unknown): TagOption | null => {\n if (!item || typeof item !== 'object') return null\n const raw = item as { id?: unknown; tagId?: unknown; label?: unknown; slug?: unknown; color?: unknown }\n const rawId =\n typeof raw.id === 'string'\n ? raw.id\n : typeof raw.tagId === 'string'\n ? raw.tagId\n : null\n if (!rawId) return null\n const labelValue =\n (typeof raw.label === 'string' && raw.label.trim().length && raw.label.trim()) ||\n (typeof raw.slug === 'string' && raw.slug.trim().length && raw.slug.trim()) ||\n rawId\n const color = typeof raw.color === 'string' && raw.color.trim().length ? raw.color.trim() : null\n return { id: rawId, label: labelValue, color }\n })\n .filter((entry): entry is TagOption => entry !== null)\n },\n [t],\n )\n\n const createTag = React.useCallback(\n async (label: string): Promise<TagOption> => {\n const trimmed = label.trim()\n if (!trimmed.length) {\n throw new Error(t('resources.resources.tags.labelRequired', 'Tag name is required.'))\n }\n const requestBody = { label: trimmed }\n const response = await runMutationWithContext(\n () => apiCallOrThrow<Record<string, unknown>>(\n '/api/resources/tags',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(requestBody),\n },\n { errorMessage: t('resources.resources.tags.createError', 'Failed to create tag.') },\n ),\n { operation: 'createTag', label: trimmed },\n )\n const payload = response.result ?? {}\n const id =\n typeof payload?.id === 'string'\n ? payload.id\n : typeof (payload as any)?.tagId === 'string'\n ? (payload as any).tagId\n : ''\n if (!id) throw new Error(t('resources.resources.tags.createError', 'Failed to create tag.'))\n const color = typeof (payload as any)?.color === 'string' && (payload as any).color.trim().length\n ? (payload as any).color.trim()\n : null\n return { id, label: trimmed, color }\n },\n [runMutationWithContext, t],\n )\n\n const assignTag = React.useCallback(async (tagId: string) => {\n if (!resourceId) return\n const requestBody = { tagId, resourceId }\n await runMutationWithContext(\n () => apiCallOrThrow(\n '/api/resources/resources/tags/assign',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(requestBody),\n },\n { errorMessage: t('resources.resources.tags.updateError', 'Failed to update tags.') },\n ),\n { operation: 'assignTag', resourceId, tagId },\n )\n }, [resourceId, runMutationWithContext, t])\n\n const unassignTag = React.useCallback(async (tagId: string) => {\n if (!resourceId) return\n const requestBody = { tagId, resourceId }\n await runMutationWithContext(\n () => apiCallOrThrow(\n '/api/resources/resources/tags/unassign',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(requestBody),\n },\n { errorMessage: t('resources.resources.tags.updateError', 'Failed to update tags.') },\n ),\n { operation: 'unassignTag', resourceId, tagId },\n )\n }, [resourceId, runMutationWithContext, t])\n\n const handleTagsSave = React.useCallback(\n async ({ next, added, removed }: { next: TagOption[]; added: TagOption[]; removed: TagOption[] }) => {\n if (!resourceId) return\n await Promise.all([\n ...added.map((tag) => assignTag(tag.id)),\n ...removed.map((tag) => unassignTag(tag.id)),\n ])\n setTags(next)\n flash(t('resources.resources.tags.success', 'Tags updated.'), 'success')\n },\n [assignTag, resourceId, t, unassignTag],\n )\n\n const tagsSection = React.useMemo(\n () => ({\n title: t('resources.resources.tags.title', 'Tags'),\n tags,\n onChange: setTags,\n loadOptions: loadTagOptions,\n createTag,\n onSave: handleTagsSave,\n labels: tagLabels,\n }),\n [createTag, handleTagsSave, loadTagOptions, t, tagLabels, tags],\n )\n\n const formConfig = useResourcesResourceFormConfig({\n tagsSection,\n selectedResourceTypeId:\n typeof initialValues?.resourceTypeId === 'string' ? initialValues.resourceTypeId : null,\n selectedCapacityUnit:\n typeof initialValues?.capacityUnitValue === 'string' && initialValues.capacityUnitValue.length > 0\n ? selectedCapacityUnit\n : null,\n })\n const { resourceTypesLoaded, resolveFieldsetCode } = formConfig\n\n React.useEffect(() => {\n if (!resourceId || !resourceTypesLoaded) return\n // Load once per resource \u2014 never re-fetch (and thereby refresh the captured\n // optimistic-lock token) on subsequent re-renders. See loadedResourceIdRef.\n if (loadedResourceIdRef.current === resourceId) return\n setIsNotFound(false)\n let cancelled = false\n async function loadResource() {\n try {\n const params = new URLSearchParams()\n params.set('page', '1')\n params.set('pageSize', '1')\n if (resourceId) params.set('ids', resourceId)\n const record = await readApiResultOrThrow<ResourceResponse>(`/api/resources/resources?${params.toString()}`)\n const resourceRaw = Array.isArray(record?.items) ? record.items[0] : null\n const resource = resourceRaw ? normalizeResourceRecord(resourceRaw) : null\n if (!resource) {\n if (!cancelled) setIsNotFound(true)\n return\n }\n if (!cancelled) {\n loadedResourceIdRef.current = resourceId ?? null\n const customValues = extractCustomFieldEntries(resource)\n setTags(Array.isArray(resource.tags) ? resource.tags : [])\n setAvailabilityRuleSetId(\n typeof resource.availabilityRuleSetId === 'string'\n ? resource.availabilityRuleSetId\n : typeof resource.availability_rule_set_id === 'string'\n ? resource.availability_rule_set_id\n : null,\n )\n setSelectedCapacityUnit(\n typeof resource.capacityUnitValue === 'string' && resource.capacityUnitValue.length > 0\n ? {\n value: resource.capacityUnitValue,\n label:\n typeof resource.capacityUnitName === 'string' && resource.capacityUnitName.length > 0\n ? resource.capacityUnitName\n : resource.capacityUnitValue,\n color: typeof resource.capacityUnitColor === 'string' ? resource.capacityUnitColor : null,\n icon: typeof resource.capacityUnitIcon === 'string' ? resource.capacityUnitIcon : null,\n }\n : null,\n )\n setInitialValues({\n id: resource.id,\n name: resource.name,\n description: resource.description ?? '',\n resourceTypeId: resource.resourceTypeId || '',\n capacity: resource.capacity ?? '',\n capacityUnitValue: resource.capacityUnitValue ?? '',\n appearance: { icon: resource.appearanceIcon ?? null, color: resource.appearanceColor ?? null },\n isActive: resource.isActive ?? true,\n updatedAt:\n typeof resource.updatedAt === 'string'\n ? resource.updatedAt\n : typeof resource.updated_at === 'string'\n ? resource.updated_at\n : null,\n customFieldsetCode: resource.resourceTypeId\n ? resolveFieldsetCode(resource.resourceTypeId)\n : RESOURCES_RESOURCE_FIELDSET_DEFAULT,\n ...customValues,\n })\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : t('resources.resources.form.errors.load', 'Failed to load resource.')\n flash(message, 'error')\n }\n }\n loadResource()\n return () => { cancelled = true }\n }, [resourceId, resourceTypesLoaded, resolveFieldsetCode, t])\n\n const handleDelete = React.useCallback(async () => {\n if (!resourceId) return\n const resourceOptimisticLockHeader = buildOptimisticLockHeader(\n typeof initialValues?.updatedAt === 'string' ? initialValues.updatedAt : null,\n )\n const deleteResource = () => deleteCrud('resources/resources', resourceId, {\n errorMessage: t('resources.resources.form.errors.delete', 'Failed to delete resource.'),\n })\n await runMutationWithContext(\n () => Object.keys(resourceOptimisticLockHeader).length > 0\n ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, deleteResource)\n : deleteResource(),\n { operation: 'deleteResource', id: resourceId, updatedAt: initialValues?.updatedAt ?? null },\n )\n flash(t('resources.resources.form.flash.deleted', 'Resource deleted.'), 'success')\n router.push('/backend/resources/resources')\n }, [initialValues?.updatedAt, resourceId, router, runMutationWithContext, t])\n\n const handleRulesetChange = React.useCallback(async (nextId: string | null) => {\n if (!resourceId) return\n const updateSchedule = () => updateCrud('resources/resources', { id: resourceId, availabilityRuleSetId: nextId }, {\n errorMessage: t('resources.resources.availability.ruleset.updateError', 'Failed to update schedule.'),\n })\n const resourceOptimisticLockHeader = buildOptimisticLockHeader(\n typeof initialValues?.updatedAt === 'string' ? initialValues.updatedAt : null,\n )\n await runMutationWithContext(\n () => Object.keys(resourceOptimisticLockHeader).length > 0\n ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, updateSchedule)\n : updateSchedule(),\n { operation: 'updateAvailabilityRuleSet', id: resourceId, availabilityRuleSetId: nextId },\n )\n setAvailabilityRuleSetId(nextId)\n flash(t('resources.resources.availability.ruleset.updateSuccess', 'Schedule updated.'), 'success')\n }, [initialValues?.updatedAt, resourceId, runMutationWithContext, t])\n\n const resourceTitle =\n typeof initialValues?.name === 'string' && initialValues.name.trim().length > 0\n ? initialValues.name.trim()\n : t('resources.resources.detail.untitled', 'Unnamed resource')\n\n // Publish page-load record context to the AppShell-owned `backend:record:current`\n // mount so the enterprise record_locks widget resolves `resources.resource` + id\n // explicitly. The resourceKind mirrors the VersionHistoryAction config / ResourceCrudForm\n // `versionHistory` so the held lock matches the save-time conflict surface for the resource.\n useSetCurrentRecordInjectionContext(\n buildRecordInjectionContext({\n resourceKind: 'resources.resource',\n resourceId: resourceId || null,\n updatedAt: typeof initialValues?.updatedAt === 'string' ? initialValues.updatedAt : null,\n data: initialValues,\n path: pathname,\n }),\n )\n\n if (isNotFound) {\n return (\n <Page>\n <PageBody>\n <RecordNotFoundState\n label={t('resources.resources.form.errors.notFound', 'Resource not found.')}\n backHref=\"/backend/resources/resources\"\n backLabel={t('resources.resources.detail.back', 'Back to resources')}\n />\n </PageBody>\n </Page>\n )\n }\n\n return (\n <Page>\n <PageBody>\n <div className=\"space-y-6\">\n <FormHeader\n mode=\"detail\"\n backHref=\"/backend/resources/resources\"\n backLabel={t('resources.resources.detail.back', 'Back to resources')}\n utilityActions={(\n <>\n {resourceId ? (\n <SendObjectMessageDialog\n object={{\n entityModule: 'resources',\n entityType: 'resource',\n entityId: resourceId,\n previewData: {\n title: resourceTitle,\n },\n }}\n viewHref={`/backend/resources/resources/${resourceId}`}\n />\n ) : null}\n <VersionHistoryAction\n config={resourceId ? { resourceKind: 'resources.resource', resourceId, includeRelated: true } : null}\n t={t}\n />\n </>\n )}\n title={resourceTitle}\n subtitle={t('resources.resources.detail.subtitle', 'Resource profile and activity')}\n />\n\n <div className=\"border-b\">\n <nav className=\"flex flex-wrap items-center gap-5 text-sm\" aria-label={t('resources.resources.tabs.label', 'Resource sections')}>\n {tabs.map((tab) => (\n <Button\n key={tab.id}\n type=\"button\"\n role=\"tab\"\n aria-selected={activeTab === tab.id}\n variant=\"ghost\"\n size=\"sm\"\n className={`relative -mb-px h-auto rounded-none border-b-2 px-0 py-2 font-medium ${\n activeTab === tab.id\n ? 'border-accent-indigo text-foreground'\n : 'border-transparent text-muted-foreground hover:text-foreground'\n }`}\n onClick={() => setActiveTab(tab.id as 'details' | 'availability')}\n >\n {tab.label}\n </Button>\n ))}\n </nav>\n </div>\n\n {activeTab === 'details' ? (\n <>\n <div className=\"rounded-lg border bg-card p-4\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex gap-2\">\n {detailTabs.map((tab) => (\n <Button\n key={tab.id}\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className={`relative -mb-px h-auto rounded-none border-b-2 px-0 py-1 font-medium ${\n activeDetailTab === tab.id\n ? 'border-accent-indigo text-foreground'\n : 'border-transparent text-muted-foreground hover:text-foreground'\n }`}\n onClick={() => setActiveDetailTab(tab.id)}\n >\n {tab.label}\n </Button>\n ))}\n </div>\n {sectionAction ? (\n <Button\n type=\"button\"\n size=\"sm\"\n disabled={sectionAction.disabled}\n onClick={() => sectionAction.onClick()}\n >\n {sectionAction.icon ?? null}\n {sectionAction.label}\n </Button>\n ) : null}\n </div>\n {activeDetailTab === 'notes' ? (\n <NotesSection\n entityId={resourceId ?? null}\n emptyLabel={t('resources.resources.detail.notes.empty', 'No notes yet.')}\n viewerUserId={null}\n viewerName={null}\n viewerEmail={null}\n addActionLabel={t('resources.resources.detail.notes.add', 'Add note')}\n emptyState={{\n title: t('resources.resources.detail.notes.emptyTitle', 'Keep everyone in the loop'),\n actionLabel: t('resources.resources.detail.notes.emptyAction', 'Add a note'),\n }}\n onActionChange={setSectionAction}\n translator={detailTranslator}\n labelPrefix=\"resources.resources.detail.notes\"\n inlineLabelPrefix=\"resources.resources.detail.inline\"\n dataAdapter={notesAdapter}\n renderIcon={renderDictionaryIcon}\n renderColor={renderDictionaryColor}\n iconSuggestions={ICON_SUGGESTIONS}\n />\n ) : null}\n {activeDetailTab === 'activities' ? (\n <ActivitiesSection\n entityId={resourceId ?? null}\n addActionLabel={t('resources.resources.detail.activities.add', 'Log activity')}\n emptyState={{\n title: t('resources.resources.detail.activities.emptyTitle', 'No activities yet'),\n actionLabel: t('resources.resources.detail.activities.emptyAction', 'Add an activity'),\n }}\n onActionChange={setSectionAction}\n dataAdapter={activitiesAdapter}\n activityTypeLabels={activityTypeLabels}\n loadActivityOptions={loadActivityOptions}\n createActivityOption={createActivityOption}\n resolveActivityPresentation={resolveActivityPresentation}\n renderCustomFields={renderCustomFields}\n labelPrefix=\"resources.resources.detail.activities\"\n renderIcon={renderDictionaryIcon}\n renderColor={renderDictionaryColor}\n appearanceLabels={appearanceLabels}\n manageHref={manageActivityHref}\n customFieldEntityIds={['resources:resources_resource_activity']}\n />\n ) : null}\n </div>\n\n <div className=\"rounded-lg border bg-card p-4\">\n <h2 className=\"mb-4 text-sm font-semibold uppercase text-muted-foreground\">\n {t('resources.resources.detail.formTitle', 'Resource settings')}\n </h2>\n <ResourcesResourceForm\n embedded\n title={t('resources.resources.form.editTitle', 'Edit resource')}\n backHref=\"/backend/resources/resources\"\n cancelHref=\"/backend/resources/resources\"\n successRedirect=\"/backend/resources/resources\"\n formConfig={formConfig}\n initialValues={initialValues ?? undefined}\n optimisticLockUpdatedAt={\n typeof initialValues?.updatedAt === 'string'\n ? initialValues.updatedAt\n : null\n }\n onSubmit={handleSubmit}\n onDelete={handleDelete}\n isLoading={!initialValues}\n loadingMessage={t('resources.resources.form.loading', 'Loading resource...')}\n />\n </div>\n </>\n ) : (\n <AvailabilityRulesEditor\n subjectType=\"resource\"\n subjectId={resourceId ?? ''}\n labelPrefix=\"resources.resources\"\n mode={availabilityMode}\n rulesetId={availabilityRuleSetId}\n onRulesetChange={handleRulesetChange}\n buildScheduleItems={buildScheduleItems}\n />\n )}\n </div>\n </PageBody>\n </Page>\n )\n}\n"],
|
|
5
|
-
"mappings": ";AA2PY,SAsYE,UAlYA,KAJF;AAzPZ,YAAY,WAAW;AACvB,SAAS,aAAa,WAAW,uBAAuB;AACxD,SAAS,MAAM,gBAAgB;AAC/B,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB,SAAS,gBAAgB,sBAAsB,mCAAmC;AAClF,SAAS,iCAAiC;AAC1C,SAAS,gCAAgC;AACzC,SAAS,2BAA2B;AACpC,SAAS,YAAY,kBAAkB;AACvC,SAAS,aAAa;AACtB,SAAS,mBAAmB,cAAc,2BAA+D;AACzG,SAAS,6BAA6B,2CAA2C;AACjF,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,YAAY;AACrB,SAAS,iCAAiC;AAC1C,SAAS,oCAAoC;AAC7C,SAAS,kCAAkC;AAC3C,SAAS,2CAA2C;AAEpD,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,sCAAsC;AACtE,SAAS,uBAAuB,sBAAsB,wBAAwB;AAC9E,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;AAChD;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAyCP,SAAS,wBAAwB,QAAwC;A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UAAU;AAAA,YACV,WAAW,CAAC;AAAA,YACZ,gBAAgB,EAAE,oCAAoC,qBAAqB;AAAA;AAAA,QAC7E;AAAA,SACF;AAAA,OACF,IAEA;AAAA,MAAC;AAAA;AAAA,QACC,aAAY;AAAA,QACZ,WAAW,cAAc;AAAA,QACzB,aAAY;AAAA,QACZ,MAAM;AAAA,QACN,WAAW;AAAA,QACX,iBAAiB;AAAA,QACjB;AAAA;AAAA,IACF;AAAA,KAEJ,GACF,GACF;AAEJ;",
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { usePathname, useRouter, useSearchParams } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { FormHeader } from '@open-mercato/ui/backend/forms'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Tabs, TabsList, TabsTrigger } from '@open-mercato/ui/primitives/tabs'\nimport { apiCallOrThrow, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { collectCustomFieldValues } from '@open-mercato/ui/backend/utils/customFieldValues'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { updateCrud, deleteCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { ActivitiesSection, NotesSection, RecordNotFoundState, type SectionAction, type TagOption } from '@open-mercato/ui/backend/detail'\nimport { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from '@open-mercato/ui/backend/injection/recordContext'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { VersionHistoryAction } from '@open-mercato/ui/backend/version-history'\nimport { SendObjectMessageDialog } from '@open-mercato/ui/backend/messages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { extractCustomFieldEntries } from '@open-mercato/shared/lib/crud/custom-fields-client'\nimport { createTranslatorWithFallback } from '@open-mercato/shared/lib/i18n/translate'\nimport { buildResourceScheduleItems } from '@open-mercato/core/modules/resources/lib/resourceSchedule'\nimport { RESOURCES_RESOURCE_FIELDSET_DEFAULT } from '@open-mercato/core/modules/resources/lib/resourceCustomFields'\nimport type { AvailabilityScheduleItemBuilder } from '@open-mercato/core/modules/planner/components/AvailabilityRulesEditor'\nimport { AvailabilityRulesEditor } from '@open-mercato/core/modules/planner/components/AvailabilityRulesEditor'\nimport { ResourcesResourceForm, useResourcesResourceFormConfig } from '@open-mercato/core/modules/resources/components/ResourceCrudForm'\nimport { renderDictionaryColor, renderDictionaryIcon, ICON_SUGGESTIONS } from '@open-mercato/core/modules/dictionaries/components/dictionaryAppearance'\nimport { createResourceNotesAdapter } from '@open-mercato/core/modules/resources/components/detail/notesAdapter'\nimport { createResourceActivitiesAdapter } from '@open-mercato/core/modules/resources/components/detail/activitiesAdapter'\nimport {\n createResourceDictionaryEntry,\n loadResourceDictionary,\n type DictionaryEntryOption,\n} from '@open-mercato/core/modules/resources/components/detail/dictionaries'\nimport type { DictionarySelectLabels } from '@open-mercato/core/modules/dictionaries/components/DictionaryEntrySelect'\n\ntype ResourceRecord = {\n id: string\n name: string\n description?: string | null\n resourceTypeId: string | null\n capacity: number | null\n capacityUnitValue: string | null\n capacityUnitName: string | null\n capacityUnitColor: string | null\n capacityUnitIcon: string | null\n tags?: TagOption[] | null\n isActive: boolean\n appearanceIcon?: string | null\n appearanceColor?: string | null\n resource_type_id?: string | null\n capacity_unit_value?: string | null\n capacity_unit_name?: string | null\n capacity_unit_color?: string | null\n capacity_unit_icon?: string | null\n appearance_icon?: string | null\n appearance_color?: string | null\n is_active?: boolean\n availabilityRuleSetId?: string | null\n availability_rule_set_id?: string | null\n} & Record<string, unknown>\n\ntype ResourceResponse = {\n items: ResourceRecord[]\n}\n\ntype ResourceDetailMutationContext = {\n formId: string\n resourceKind: string\n resourceId?: string\n data: Record<string, unknown> | null\n retryLastMutation: () => Promise<boolean>\n}\n\nfunction normalizeResourceRecord(record: ResourceRecord): ResourceRecord {\n return {\n ...record,\n resourceTypeId: record.resourceTypeId ?? record.resource_type_id ?? null,\n description: record.description ?? null,\n capacityUnitValue: record.capacityUnitValue ?? record.capacity_unit_value ?? null,\n capacityUnitName: record.capacityUnitName ?? record.capacity_unit_name ?? null,\n capacityUnitColor: record.capacityUnitColor ?? record.capacity_unit_color ?? null,\n capacityUnitIcon: record.capacityUnitIcon ?? record.capacity_unit_icon ?? null,\n appearanceIcon: record.appearanceIcon ?? record.appearance_icon ?? null,\n appearanceColor: record.appearanceColor ?? record.appearance_color ?? null,\n isActive: record.isActive ?? record.is_active ?? true,\n }\n}\n\nexport default function ResourcesResourceDetailPage({ params }: { params?: { id?: string } }) {\n const resourceId = params?.id\n const t = useT()\n const detailTranslator = React.useMemo(() => createTranslatorWithFallback(t), [t])\n const router = useRouter()\n const pathname = usePathname()\n const searchParams = useSearchParams()\n const [initialValues, setInitialValues] = React.useState<Record<string, unknown> | null>(null)\n const [isNotFound, setIsNotFound] = React.useState(false)\n // Capture the record (incl. its optimistic-lock `updatedAt`) exactly ONCE per\n // resource. The load effect's deps include identity-unstable values (`t`,\n // `resolveFieldsetCode`), so without this guard a re-render would re-fetch and\n // overwrite `initialValues.updatedAt` with a newer server value mid-edit \u2014\n // silently defeating optimistic locking (a concurrent change would no longer be\n // detected) and making the conflict flaky.\n const loadedResourceIdRef = React.useRef<string | null>(null)\n const [tags, setTags] = React.useState<TagOption[]>([])\n const [activeTab, setActiveTab] = React.useState<'details' | 'availability'>('details')\n const [activeDetailTab, setActiveDetailTab] = React.useState<'notes' | 'activities'>('notes')\n const [sectionAction, setSectionAction] = React.useState<SectionAction | null>(null)\n const [availabilityRuleSetId, setAvailabilityRuleSetId] = React.useState<string | null>(null)\n const [selectedCapacityUnit, setSelectedCapacityUnit] = React.useState<{\n value: string\n label: string\n color?: string | null\n icon?: string | null\n } | null>(null)\n const [activityDictionaryId, setActivityDictionaryId] = React.useState<string | null>(null)\n const [activityTypeEntries, setActivityTypeEntries] = React.useState<DictionaryEntryOption[]>([])\n const flashShownRef = React.useRef(false)\n\n const availabilityMode = 'availability'\n const mutationContextId = React.useMemo(\n () => (resourceId ? `resources.resource:${resourceId}` : 'resources.resource:pending'),\n [resourceId],\n )\n const { runMutation, retryLastMutation } = useGuardedMutation<ResourceDetailMutationContext>({\n contextId: mutationContextId,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n const mutationContext = React.useMemo<ResourceDetailMutationContext>(\n () => ({\n formId: mutationContextId,\n resourceKind: 'resources.resource',\n resourceId,\n data: initialValues,\n retryLastMutation,\n }),\n [initialValues, mutationContextId, resourceId, retryLastMutation],\n )\n const runMutationWithContext = React.useCallback(\n async <T,>(operation: () => Promise<T>, mutationPayload?: Record<string, unknown>): Promise<T> => (\n runMutation({\n operation,\n mutationPayload,\n context: mutationContext,\n })\n ),\n [mutationContext, runMutation],\n )\n const notesAdapter = React.useMemo(\n () => createResourceNotesAdapter(detailTranslator, { runMutation: runMutationWithContext }),\n [detailTranslator, runMutationWithContext],\n )\n const activitiesAdapter = React.useMemo(\n () => createResourceActivitiesAdapter(detailTranslator, { runMutation: runMutationWithContext }),\n [detailTranslator, runMutationWithContext],\n )\n\n const activityTypeLabels = React.useMemo<DictionarySelectLabels>(() => ({\n placeholder: t('resources.resources.detail.activities.dictionary.placeholder', 'Select an activity type'),\n addLabel: t('resources.resources.detail.activities.dictionary.add', 'Add type'),\n addPrompt: t('resources.resources.detail.activities.dictionary.prompt', 'Name the type'),\n dialogTitle: t('resources.resources.detail.activities.dictionary.dialogTitle', 'Add activity type'),\n valueLabel: t('resources.resources.detail.activities.dictionary.valueLabel', 'Name'),\n valuePlaceholder: t('resources.resources.detail.activities.dictionary.valuePlaceholder', 'Name'),\n labelLabel: t('resources.resources.detail.activities.dictionary.labelLabel', 'Label'),\n labelPlaceholder: t('resources.resources.detail.activities.dictionary.labelPlaceholder', 'Display name shown in UI'),\n emptyError: t('resources.resources.detail.activities.dictionary.emptyError', 'Please enter a name'),\n cancelLabel: t('resources.resources.detail.activities.dictionary.cancel', 'Cancel'),\n saveLabel: t('resources.resources.detail.activities.dictionary.save', 'Save'),\n saveShortcutHint: t('resources.resources.detail.activities.dictionary.saveShortcut', '\u2318/Ctrl + Enter'),\n errorLoad: t('resources.resources.detail.activities.dictionary.errorLoad', 'Failed to load options'),\n errorSave: t('resources.resources.detail.activities.dictionary.errorSave', 'Failed to save option'),\n loadingLabel: t('resources.resources.detail.activities.dictionary.loading', 'Loading\u2026'),\n manageTitle: t('resources.resources.detail.activities.dictionary.manage', 'Manage dictionary'),\n }), [t])\n\n const loadActivityOptions = React.useCallback(async () => {\n const { dictionary, entries } = await loadResourceDictionary('activityTypes')\n setActivityDictionaryId(dictionary?.id ?? null)\n setActivityTypeEntries(entries)\n return entries\n }, [])\n\n const createActivityOption = React.useCallback(\n async (input: { value: string; label?: string; color?: string | null; icon?: string | null }) => {\n const entry = await createResourceDictionaryEntry('activityTypes', input)\n if (!entry) {\n throw new Error(t('resources.resources.detail.activities.dictionary.errorSave', 'Failed to save option'))\n }\n return entry\n },\n [t],\n )\n\n React.useEffect(() => {\n loadActivityOptions().catch(() => {})\n }, [loadActivityOptions])\n\n const activityTypeMap = React.useMemo(\n () => new Map(activityTypeEntries.map((entry) => [entry.value, entry])),\n [activityTypeEntries],\n )\n\n const resolveActivityPresentation = React.useCallback(\n (activity: { activityType: string; appearanceIcon?: string | null; appearanceColor?: string | null }) => {\n const entry = activityTypeMap.get(activity.activityType)\n return {\n label: entry?.label ?? activity.activityType,\n icon: entry?.icon ?? activity.appearanceIcon ?? null,\n color: entry?.color ?? activity.appearanceColor ?? null,\n }\n },\n [activityTypeMap],\n )\n\n const manageActivityHref = React.useMemo(() => {\n if (!activityDictionaryId) return '/backend/config/dictionaries'\n return `/backend/config/dictionaries?dictionaryId=${encodeURIComponent(activityDictionaryId)}`\n }, [activityDictionaryId])\n\n const appearanceLabels = React.useMemo(() => ({\n colorLabel: t('resources.resources.detail.activities.appearance.colorLabel', 'Color'),\n colorHelp: t('resources.resources.detail.activities.appearance.colorHelp', 'Pick a highlight color for this entry.'),\n colorClearLabel: t('resources.resources.detail.activities.appearance.colorClear', 'Remove color'),\n iconLabel: t('resources.resources.detail.activities.appearance.iconLabel', 'Icon or emoji'),\n iconPlaceholder: t('resources.resources.detail.activities.appearance.iconPlaceholder', 'Type an emoji or pick one of the suggestions.'),\n iconPickerTriggerLabel: t('resources.resources.detail.activities.appearance.iconBrowse', 'Browse icons and emojis'),\n iconSearchPlaceholder: t('resources.resources.detail.activities.appearance.iconSearchPlaceholder', 'Search icons or emojis\u2026'),\n iconSearchEmptyLabel: t('resources.resources.detail.activities.appearance.iconSearchEmpty', 'No icons match your search.'),\n iconSuggestionsLabel: t('resources.resources.detail.activities.appearance.iconSuggestions', 'Suggestions'),\n iconClearLabel: t('resources.resources.detail.activities.appearance.iconClear', 'Remove icon'),\n previewEmptyLabel: t('resources.resources.detail.activities.appearance.previewEmpty', 'No appearance selected'),\n }), [t])\n\n const renderCustomFields = React.useCallback((activity: { id?: string; customFields?: Array<{ key: string; label?: string | null; value: unknown }> }) => {\n const entries = Array.isArray(activity.customFields) ? activity.customFields : []\n if (!entries.length) return null\n const emptyLabel = t('resources.resources.detail.activities.customFields.empty', 'Not provided')\n return (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {entries.map((entry, index) => {\n const label = entry.label ?? entry.key\n const value = entry.value\n const hasValue = !(value == null || value === '' || (Array.isArray(value) && value.length === 0))\n const content = hasValue\n ? Array.isArray(value)\n ? value.map((item) => String(item)).join(', ')\n : String(value)\n : emptyLabel\n return (\n <div\n key={`activity-${activity.id ?? 'row'}-custom-${index}`}\n className=\"rounded-md border border-border/70 bg-muted/30 px-3 py-2\"\n >\n <div className=\"text-xs font-medium text-muted-foreground\">{label}</div>\n <div className=\"mt-1 text-sm text-foreground\">{content}</div>\n </div>\n )\n })}\n </div>\n )\n }, [t])\n\n React.useEffect(() => {\n if (!searchParams) return\n const tabParam = searchParams.get('tab')\n if (tabParam === 'availability') {\n setActiveTab('availability')\n }\n const created = searchParams.get('created') === '1'\n if (created && !flashShownRef.current) {\n flashShownRef.current = true\n flash(t('resources.resources.flash.createdAvailability', 'Saved. You can now set availability.'), 'success')\n const nextParams = new URLSearchParams(searchParams.toString())\n nextParams.delete('created')\n const nextQuery = nextParams.toString()\n const nextPath = resourceId\n ? `/backend/resources/resources/${encodeURIComponent(resourceId)}${nextQuery ? `?${nextQuery}` : ''}`\n : `/backend/resources/resources${nextQuery ? `?${nextQuery}` : ''}`\n router.replace(nextPath)\n }\n }, [resourceId, router, searchParams, t])\n\n const buildScheduleItems = React.useCallback<AvailabilityScheduleItemBuilder>(\n ({ availabilityRules, translate }) => buildResourceScheduleItems({\n availabilityRules,\n isAvailableByDefault: false,\n translate,\n }),\n [],\n )\n\n const tagLabels = React.useMemo(\n () => ({\n loading: t('resources.resources.tags.loading', 'Loading tags...'),\n placeholder: t('resources.resources.tags.placeholder', 'Type to add tags'),\n empty: t('resources.resources.tags.placeholder', 'No tags yet. Add labels to keep resources organized.'),\n loadError: t('resources.resources.tags.loadError', 'Failed to load tags.'),\n createError: t('resources.resources.tags.createError', 'Failed to create tag.'),\n updateError: t('resources.resources.tags.updateError', 'Failed to update tags.'),\n labelRequired: t('resources.resources.tags.labelRequired', 'Tag name is required.'),\n saveShortcut: t('resources.resources.tags.saveShortcut', 'Save Cmd+Enter / Ctrl+Enter'),\n cancelShortcut: t('resources.resources.tags.cancelShortcut', 'Cancel (Esc)'),\n edit: t('ui.forms.actions.edit', 'Edit'),\n cancel: t('ui.forms.actions.cancel', 'Cancel'),\n success: t('resources.resources.tags.success', 'Tags updated.'),\n }),\n [t],\n )\n\n const handleSubmit = React.useCallback(async (values: Record<string, unknown>) => {\n if (!resourceId) return\n const appearance = values.appearance && typeof values.appearance === 'object'\n ? values.appearance as { icon?: string | null; color?: string | null }\n : {}\n const { appearance: _appearance, ...rest } = values\n const customFieldsetCode = typeof values.customFieldsetCode === 'string' && values.customFieldsetCode.trim().length\n ? values.customFieldsetCode.trim()\n : RESOURCES_RESOURCE_FIELDSET_DEFAULT\n const payload: Record<string, unknown> = {\n ...rest,\n id: resourceId,\n resourceTypeId: values.resourceTypeId || null,\n capacity: values.capacity ? Number(values.capacity) : null,\n capacityUnitValue: values.capacityUnitValue ? String(values.capacityUnitValue) : null,\n appearanceIcon: appearance.icon ?? null,\n appearanceColor: appearance.color ?? null,\n isActive: values.isActive ?? true,\n customFieldsetCode,\n ...collectCustomFieldValues(values),\n }\n if (!payload.name || String(payload.name).trim().length === 0) {\n throw createCrudFormError(t('resources.resources.form.errors.nameRequired', 'Name is required.'))\n }\n await updateCrud('resources/resources', payload, {\n errorMessage: t('resources.resources.form.errors.update', 'Failed to update resource.'),\n })\n flash(t('resources.resources.form.flash.updated', 'Resource updated.'), 'success')\n }, [resourceId, t])\n\n const tabs = React.useMemo(() => ([\n { id: 'details', label: t('resources.resources.tabs.details', 'Details') },\n { id: 'availability', label: t('resources.resources.tabs.availability', 'Availability') },\n ]), [t])\n const detailTabs = React.useMemo(() => ([\n { id: 'notes' as const, label: t('resources.resources.detail.tabs.notes', 'Notes') },\n { id: 'activities' as const, label: t('resources.resources.detail.tabs.activities', 'Activities') },\n ]), [t])\n\n const loadTagOptions = React.useCallback(\n async (query?: string): Promise<TagOption[]> => {\n const params = new URLSearchParams({ pageSize: '100' })\n if (query) params.set('search', query)\n const payload = await readApiResultOrThrow<Record<string, unknown>>(\n `/api/resources/tags?${params.toString()}`,\n undefined,\n { errorMessage: t('resources.resources.tags.loadError', 'Failed to load tags.') },\n )\n const items = Array.isArray(payload?.items) ? payload.items : []\n return items\n .map((item: unknown): TagOption | null => {\n if (!item || typeof item !== 'object') return null\n const raw = item as { id?: unknown; tagId?: unknown; label?: unknown; slug?: unknown; color?: unknown }\n const rawId =\n typeof raw.id === 'string'\n ? raw.id\n : typeof raw.tagId === 'string'\n ? raw.tagId\n : null\n if (!rawId) return null\n const labelValue =\n (typeof raw.label === 'string' && raw.label.trim().length && raw.label.trim()) ||\n (typeof raw.slug === 'string' && raw.slug.trim().length && raw.slug.trim()) ||\n rawId\n const color = typeof raw.color === 'string' && raw.color.trim().length ? raw.color.trim() : null\n return { id: rawId, label: labelValue, color }\n })\n .filter((entry): entry is TagOption => entry !== null)\n },\n [t],\n )\n\n const createTag = React.useCallback(\n async (label: string): Promise<TagOption> => {\n const trimmed = label.trim()\n if (!trimmed.length) {\n throw new Error(t('resources.resources.tags.labelRequired', 'Tag name is required.'))\n }\n const requestBody = { label: trimmed }\n const response = await runMutationWithContext(\n () => apiCallOrThrow<Record<string, unknown>>(\n '/api/resources/tags',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(requestBody),\n },\n { errorMessage: t('resources.resources.tags.createError', 'Failed to create tag.') },\n ),\n { operation: 'createTag', label: trimmed },\n )\n const payload = response.result ?? {}\n const id =\n typeof payload?.id === 'string'\n ? payload.id\n : typeof (payload as any)?.tagId === 'string'\n ? (payload as any).tagId\n : ''\n if (!id) throw new Error(t('resources.resources.tags.createError', 'Failed to create tag.'))\n const color = typeof (payload as any)?.color === 'string' && (payload as any).color.trim().length\n ? (payload as any).color.trim()\n : null\n return { id, label: trimmed, color }\n },\n [runMutationWithContext, t],\n )\n\n const assignTag = React.useCallback(async (tagId: string) => {\n if (!resourceId) return\n const requestBody = { tagId, resourceId }\n await runMutationWithContext(\n () => apiCallOrThrow(\n '/api/resources/resources/tags/assign',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(requestBody),\n },\n { errorMessage: t('resources.resources.tags.updateError', 'Failed to update tags.') },\n ),\n { operation: 'assignTag', resourceId, tagId },\n )\n }, [resourceId, runMutationWithContext, t])\n\n const unassignTag = React.useCallback(async (tagId: string) => {\n if (!resourceId) return\n const requestBody = { tagId, resourceId }\n await runMutationWithContext(\n () => apiCallOrThrow(\n '/api/resources/resources/tags/unassign',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(requestBody),\n },\n { errorMessage: t('resources.resources.tags.updateError', 'Failed to update tags.') },\n ),\n { operation: 'unassignTag', resourceId, tagId },\n )\n }, [resourceId, runMutationWithContext, t])\n\n const handleTagsSave = React.useCallback(\n async ({ next, added, removed }: { next: TagOption[]; added: TagOption[]; removed: TagOption[] }) => {\n if (!resourceId) return\n await Promise.all([\n ...added.map((tag) => assignTag(tag.id)),\n ...removed.map((tag) => unassignTag(tag.id)),\n ])\n setTags(next)\n flash(t('resources.resources.tags.success', 'Tags updated.'), 'success')\n },\n [assignTag, resourceId, t, unassignTag],\n )\n\n const tagsSection = React.useMemo(\n () => ({\n title: t('resources.resources.tags.title', 'Tags'),\n tags,\n onChange: setTags,\n loadOptions: loadTagOptions,\n createTag,\n onSave: handleTagsSave,\n labels: tagLabels,\n }),\n [createTag, handleTagsSave, loadTagOptions, t, tagLabels, tags],\n )\n\n const formConfig = useResourcesResourceFormConfig({\n tagsSection,\n selectedResourceTypeId:\n typeof initialValues?.resourceTypeId === 'string' ? initialValues.resourceTypeId : null,\n selectedCapacityUnit:\n typeof initialValues?.capacityUnitValue === 'string' && initialValues.capacityUnitValue.length > 0\n ? selectedCapacityUnit\n : null,\n })\n const { resourceTypesLoaded, resolveFieldsetCode } = formConfig\n\n React.useEffect(() => {\n if (!resourceId || !resourceTypesLoaded) return\n // Load once per resource \u2014 never re-fetch (and thereby refresh the captured\n // optimistic-lock token) on subsequent re-renders. See loadedResourceIdRef.\n if (loadedResourceIdRef.current === resourceId) return\n setIsNotFound(false)\n let cancelled = false\n async function loadResource() {\n try {\n const params = new URLSearchParams()\n params.set('page', '1')\n params.set('pageSize', '1')\n if (resourceId) params.set('ids', resourceId)\n const record = await readApiResultOrThrow<ResourceResponse>(`/api/resources/resources?${params.toString()}`)\n const resourceRaw = Array.isArray(record?.items) ? record.items[0] : null\n const resource = resourceRaw ? normalizeResourceRecord(resourceRaw) : null\n if (!resource) {\n if (!cancelled) setIsNotFound(true)\n return\n }\n if (!cancelled) {\n loadedResourceIdRef.current = resourceId ?? null\n const customValues = extractCustomFieldEntries(resource)\n setTags(Array.isArray(resource.tags) ? resource.tags : [])\n setAvailabilityRuleSetId(\n typeof resource.availabilityRuleSetId === 'string'\n ? resource.availabilityRuleSetId\n : typeof resource.availability_rule_set_id === 'string'\n ? resource.availability_rule_set_id\n : null,\n )\n setSelectedCapacityUnit(\n typeof resource.capacityUnitValue === 'string' && resource.capacityUnitValue.length > 0\n ? {\n value: resource.capacityUnitValue,\n label:\n typeof resource.capacityUnitName === 'string' && resource.capacityUnitName.length > 0\n ? resource.capacityUnitName\n : resource.capacityUnitValue,\n color: typeof resource.capacityUnitColor === 'string' ? resource.capacityUnitColor : null,\n icon: typeof resource.capacityUnitIcon === 'string' ? resource.capacityUnitIcon : null,\n }\n : null,\n )\n setInitialValues({\n id: resource.id,\n name: resource.name,\n description: resource.description ?? '',\n resourceTypeId: resource.resourceTypeId || '',\n capacity: resource.capacity ?? '',\n capacityUnitValue: resource.capacityUnitValue ?? '',\n appearance: { icon: resource.appearanceIcon ?? null, color: resource.appearanceColor ?? null },\n isActive: resource.isActive ?? true,\n updatedAt:\n typeof resource.updatedAt === 'string'\n ? resource.updatedAt\n : typeof resource.updated_at === 'string'\n ? resource.updated_at\n : null,\n customFieldsetCode: resource.resourceTypeId\n ? resolveFieldsetCode(resource.resourceTypeId)\n : RESOURCES_RESOURCE_FIELDSET_DEFAULT,\n ...customValues,\n })\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : t('resources.resources.form.errors.load', 'Failed to load resource.')\n flash(message, 'error')\n }\n }\n loadResource()\n return () => { cancelled = true }\n }, [resourceId, resourceTypesLoaded, resolveFieldsetCode, t])\n\n const handleDelete = React.useCallback(async () => {\n if (!resourceId) return\n const resourceOptimisticLockHeader = buildOptimisticLockHeader(\n typeof initialValues?.updatedAt === 'string' ? initialValues.updatedAt : null,\n )\n const deleteResource = () => deleteCrud('resources/resources', resourceId, {\n errorMessage: t('resources.resources.form.errors.delete', 'Failed to delete resource.'),\n })\n await runMutationWithContext(\n () => Object.keys(resourceOptimisticLockHeader).length > 0\n ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, deleteResource)\n : deleteResource(),\n { operation: 'deleteResource', id: resourceId, updatedAt: initialValues?.updatedAt ?? null },\n )\n flash(t('resources.resources.form.flash.deleted', 'Resource deleted.'), 'success')\n router.push('/backend/resources/resources')\n }, [initialValues?.updatedAt, resourceId, router, runMutationWithContext, t])\n\n const handleRulesetChange = React.useCallback(async (nextId: string | null) => {\n if (!resourceId) return\n const updateSchedule = () => updateCrud('resources/resources', { id: resourceId, availabilityRuleSetId: nextId }, {\n errorMessage: t('resources.resources.availability.ruleset.updateError', 'Failed to update schedule.'),\n })\n const resourceOptimisticLockHeader = buildOptimisticLockHeader(\n typeof initialValues?.updatedAt === 'string' ? initialValues.updatedAt : null,\n )\n await runMutationWithContext(\n () => Object.keys(resourceOptimisticLockHeader).length > 0\n ? withScopedApiRequestHeaders(resourceOptimisticLockHeader, updateSchedule)\n : updateSchedule(),\n { operation: 'updateAvailabilityRuleSet', id: resourceId, availabilityRuleSetId: nextId },\n )\n setAvailabilityRuleSetId(nextId)\n flash(t('resources.resources.availability.ruleset.updateSuccess', 'Schedule updated.'), 'success')\n }, [initialValues?.updatedAt, resourceId, runMutationWithContext, t])\n\n const resourceTitle =\n typeof initialValues?.name === 'string' && initialValues.name.trim().length > 0\n ? initialValues.name.trim()\n : t('resources.resources.detail.untitled', 'Unnamed resource')\n\n // Publish page-load record context to the AppShell-owned `backend:record:current`\n // mount so the enterprise record_locks widget resolves `resources.resource` + id\n // explicitly. The resourceKind mirrors the VersionHistoryAction config / ResourceCrudForm\n // `versionHistory` so the held lock matches the save-time conflict surface for the resource.\n useSetCurrentRecordInjectionContext(\n buildRecordInjectionContext({\n resourceKind: 'resources.resource',\n resourceId: resourceId || null,\n updatedAt: typeof initialValues?.updatedAt === 'string' ? initialValues.updatedAt : null,\n data: initialValues,\n path: pathname,\n }),\n )\n\n if (isNotFound) {\n return (\n <Page>\n <PageBody>\n <RecordNotFoundState\n label={t('resources.resources.form.errors.notFound', 'Resource not found.')}\n backHref=\"/backend/resources/resources\"\n backLabel={t('resources.resources.detail.back', 'Back to resources')}\n />\n </PageBody>\n </Page>\n )\n }\n\n return (\n <Page>\n <PageBody>\n <div className=\"space-y-6\">\n <FormHeader\n mode=\"detail\"\n backHref=\"/backend/resources/resources\"\n backLabel={t('resources.resources.detail.back', 'Back to resources')}\n utilityActions={(\n <>\n {resourceId ? (\n <SendObjectMessageDialog\n object={{\n entityModule: 'resources',\n entityType: 'resource',\n entityId: resourceId,\n previewData: {\n title: resourceTitle,\n },\n }}\n viewHref={`/backend/resources/resources/${resourceId}`}\n />\n ) : null}\n <VersionHistoryAction\n config={resourceId ? { resourceKind: 'resources.resource', resourceId, includeRelated: true } : null}\n t={t}\n />\n </>\n )}\n title={resourceTitle}\n subtitle={t('resources.resources.detail.subtitle', 'Resource profile and activity')}\n />\n\n <Tabs\n value={activeTab}\n onValueChange={(value) => setActiveTab(value as 'details' | 'availability')}\n variant=\"underline\"\n >\n <TabsList\n className=\"w-full flex-wrap\"\n aria-label={t('resources.resources.tabs.label', 'Resource sections')}\n >\n {tabs.map((tab) => (\n <TabsTrigger key={tab.id} value={tab.id}>\n {tab.label}\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n\n {activeTab === 'details' ? (\n <>\n <div className=\"rounded-lg border bg-card p-4\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <Tabs\n value={activeDetailTab}\n onValueChange={(value) => setActiveDetailTab(value as 'notes' | 'activities')}\n variant=\"underline\"\n >\n <TabsList className=\"h-auto flex-wrap border-b-0\">\n {detailTabs.map((tab) => (\n <TabsTrigger key={tab.id} value={tab.id}>\n {tab.label}\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n {sectionAction ? (\n <Button\n type=\"button\"\n size=\"sm\"\n disabled={sectionAction.disabled}\n onClick={() => sectionAction.onClick()}\n >\n {sectionAction.icon ?? null}\n {sectionAction.label}\n </Button>\n ) : null}\n </div>\n {activeDetailTab === 'notes' ? (\n <NotesSection\n entityId={resourceId ?? null}\n emptyLabel={t('resources.resources.detail.notes.empty', 'No notes yet.')}\n viewerUserId={null}\n viewerName={null}\n viewerEmail={null}\n addActionLabel={t('resources.resources.detail.notes.add', 'Add note')}\n emptyState={{\n title: t('resources.resources.detail.notes.emptyTitle', 'Keep everyone in the loop'),\n actionLabel: t('resources.resources.detail.notes.emptyAction', 'Add a note'),\n }}\n onActionChange={setSectionAction}\n translator={detailTranslator}\n labelPrefix=\"resources.resources.detail.notes\"\n inlineLabelPrefix=\"resources.resources.detail.inline\"\n dataAdapter={notesAdapter}\n renderIcon={renderDictionaryIcon}\n renderColor={renderDictionaryColor}\n iconSuggestions={ICON_SUGGESTIONS}\n />\n ) : null}\n {activeDetailTab === 'activities' ? (\n <ActivitiesSection\n entityId={resourceId ?? null}\n addActionLabel={t('resources.resources.detail.activities.add', 'Log activity')}\n emptyState={{\n title: t('resources.resources.detail.activities.emptyTitle', 'No activities yet'),\n actionLabel: t('resources.resources.detail.activities.emptyAction', 'Add an activity'),\n }}\n onActionChange={setSectionAction}\n dataAdapter={activitiesAdapter}\n activityTypeLabels={activityTypeLabels}\n loadActivityOptions={loadActivityOptions}\n createActivityOption={createActivityOption}\n resolveActivityPresentation={resolveActivityPresentation}\n renderCustomFields={renderCustomFields}\n labelPrefix=\"resources.resources.detail.activities\"\n renderIcon={renderDictionaryIcon}\n renderColor={renderDictionaryColor}\n appearanceLabels={appearanceLabels}\n manageHref={manageActivityHref}\n customFieldEntityIds={['resources:resources_resource_activity']}\n />\n ) : null}\n </div>\n\n <div className=\"rounded-lg border bg-card p-4\">\n <h2 className=\"mb-4 text-sm font-semibold uppercase text-muted-foreground\">\n {t('resources.resources.detail.formTitle', 'Resource settings')}\n </h2>\n <ResourcesResourceForm\n embedded\n title={t('resources.resources.form.editTitle', 'Edit resource')}\n backHref=\"/backend/resources/resources\"\n cancelHref=\"/backend/resources/resources\"\n successRedirect=\"/backend/resources/resources\"\n formConfig={formConfig}\n initialValues={initialValues ?? undefined}\n optimisticLockUpdatedAt={\n typeof initialValues?.updatedAt === 'string'\n ? initialValues.updatedAt\n : null\n }\n onSubmit={handleSubmit}\n onDelete={handleDelete}\n isLoading={!initialValues}\n loadingMessage={t('resources.resources.form.loading', 'Loading resource...')}\n />\n </div>\n </>\n ) : (\n <AvailabilityRulesEditor\n subjectType=\"resource\"\n subjectId={resourceId ?? ''}\n labelPrefix=\"resources.resources\"\n mode={availabilityMode}\n rulesetId={availabilityRuleSetId}\n onRulesetChange={handleRulesetChange}\n buildScheduleItems={buildScheduleItems}\n />\n )}\n </div>\n </PageBody>\n </Page>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AA4PY,SAsYE,UAlYA,KAJF;AA1PZ,YAAY,WAAW;AACvB,SAAS,aAAa,WAAW,uBAAuB;AACxD,SAAS,MAAM,gBAAgB;AAC/B,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB,SAAS,MAAM,UAAU,mBAAmB;AAC5C,SAAS,gBAAgB,sBAAsB,mCAAmC;AAClF,SAAS,iCAAiC;AAC1C,SAAS,gCAAgC;AACzC,SAAS,2BAA2B;AACpC,SAAS,YAAY,kBAAkB;AACvC,SAAS,aAAa;AACtB,SAAS,mBAAmB,cAAc,2BAA+D;AACzG,SAAS,6BAA6B,2CAA2C;AACjF,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,YAAY;AACrB,SAAS,iCAAiC;AAC1C,SAAS,oCAAoC;AAC7C,SAAS,kCAAkC;AAC3C,SAAS,2CAA2C;AAEpD,SAAS,+BAA+B;AACxC,SAAS,uBAAuB,sCAAsC;AACtE,SAAS,uBAAuB,sBAAsB,wBAAwB;AAC9E,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;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AAE,oCAAoC,qBAAqB;AAAA;AAAA,QAC7E;AAAA,SACF;AAAA,OACF,IAEA;AAAA,MAAC;AAAA;AAAA,QACC,aAAY;AAAA,QACZ,WAAW,cAAc;AAAA,QACzB,aAAY;AAAA,QACZ,MAAM;AAAA,QACN,WAAW;AAAA,QACX,iBAAiB;AAAA,QACjB;AAAA;AAAA,IACF;AAAA,KAEJ,GACF,GACF;AAEJ;",
|
|
6
6
|
"names": ["params"]
|
|
7
7
|
}
|
|
@@ -8,11 +8,17 @@ import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customF
|
|
|
8
8
|
import { flash } from "@open-mercato/ui/backend/FlashMessages";
|
|
9
9
|
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
10
10
|
import { useChannelFields, buildChannelPayload } from "@open-mercato/core/modules/sales/components/channels/channelFormFields";
|
|
11
|
+
import { useSalesChannelsEnabled } from "@open-mercato/core/modules/sales/components/useSalesChannelsEnabled";
|
|
12
|
+
import { SalesChannelsDisabledNotice } from "@open-mercato/core/modules/sales/components/SalesChannelsDisabledNotice";
|
|
11
13
|
import { E } from "../../../../../../generated/entities.ids.generated.js";
|
|
12
14
|
function CreateChannelPage() {
|
|
13
15
|
const t = useT();
|
|
14
16
|
const { fields, groups } = useChannelFields();
|
|
17
|
+
const { enabled: channelsEnabled, isLoading: channelsEnabledLoading } = useSalesChannelsEnabled();
|
|
15
18
|
const router = useRouter();
|
|
19
|
+
if (!channelsEnabled && !channelsEnabledLoading) {
|
|
20
|
+
return /* @__PURE__ */ jsx(SalesChannelsDisabledNotice, {});
|
|
21
|
+
}
|
|
16
22
|
return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
|
|
17
23
|
CrudForm,
|
|
18
24
|
{
|