@open-mercato/core 0.6.7-develop.6706.1.b3a4c759bb → 0.6.7-develop.6726.1.983ae8a07e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/auth/api/admin/nav.js +14 -4
- package/dist/modules/auth/api/admin/nav.js.map +2 -2
- package/dist/modules/auth/api/users/route.js +8 -19
- package/dist/modules/auth/api/users/route.js.map +2 -2
- package/dist/modules/auth/lib/backendChrome.js +31 -14
- package/dist/modules/auth/lib/backendChrome.js.map +2 -2
- package/dist/modules/customers/api/utils.js +12 -18
- package/dist/modules/customers/api/utils.js.map +2 -2
- package/dist/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.js +17 -3
- package/dist/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.js.map +2 -2
- package/dist/modules/customers/backend/customers/deals/pipeline/page.js +7 -1
- package/dist/modules/customers/backend/customers/deals/pipeline/page.js.map +2 -2
- package/dist/modules/customers/cli.js +11 -4
- package/dist/modules/customers/cli.js.map +2 -2
- package/dist/modules/customers/components/detail/ScheduleActivityDialog.js +4 -2
- package/dist/modules/customers/components/detail/ScheduleActivityDialog.js.map +2 -2
- package/dist/modules/customers/components/formConfig.js +14 -10
- package/dist/modules/customers/components/formConfig.js.map +2 -2
- package/dist/modules/dashboards/api/widgets/data/batch/route.js +4 -2
- package/dist/modules/dashboards/api/widgets/data/batch/route.js.map +2 -2
- package/dist/modules/dashboards/api/widgets/data/route.js +20 -2
- package/dist/modules/dashboards/api/widgets/data/route.js.map +2 -2
- package/dist/modules/dashboards/lib/aggregations.js +76 -40
- package/dist/modules/dashboards/lib/aggregations.js.map +2 -2
- package/dist/modules/dashboards/lib/exactDecimal.js +69 -0
- package/dist/modules/dashboards/lib/exactDecimal.js.map +7 -0
- package/dist/modules/dashboards/services/widgetDataService.js +228 -5
- package/dist/modules/dashboards/services/widgetDataService.js.map +2 -2
- package/dist/modules/feature_toggles/components/FeatureGuard.js +3 -2
- package/dist/modules/feature_toggles/components/FeatureGuard.js.map +2 -2
- package/dist/modules/feature_toggles/components/hooks/staleTime.js +5 -0
- package/dist/modules/feature_toggles/components/hooks/staleTime.js.map +7 -0
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagBoolean.js +5 -2
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagBoolean.js.map +2 -2
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagJson.js +5 -2
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagJson.js.map +2 -2
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagNumber.js +5 -2
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagNumber.js.map +2 -2
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagString.js +5 -2
- package/dist/modules/feature_toggles/components/hooks/useFeatureFlagString.js.map +2 -2
- package/dist/modules/inbox_ops/api/proposals/route.js +16 -1
- package/dist/modules/inbox_ops/api/proposals/route.js.map +2 -2
- package/dist/modules/inbox_ops/subscribers/search-reindex-proposal-created.js +32 -0
- package/dist/modules/inbox_ops/subscribers/search-reindex-proposal-created.js.map +7 -0
- package/dist/modules/integrations/widgets/injection/external-ids/widget.client.js +0 -5
- package/dist/modules/integrations/widgets/injection/external-ids/widget.client.js.map +2 -2
- package/dist/modules/integrations/widgets/injection/external-ids/widget.js +14 -0
- package/dist/modules/integrations/widgets/injection/external-ids/widget.js.map +7 -0
- package/dist/modules/messages/lib/searchLookup.js +8 -16
- package/dist/modules/messages/lib/searchLookup.js.map +2 -2
- package/dist/modules/query_index/api/openapi.js +13 -1
- package/dist/modules/query_index/api/openapi.js.map +2 -2
- package/dist/modules/query_index/api/status.js +165 -105
- package/dist/modules/query_index/api/status.js.map +2 -2
- package/dist/modules/query_index/components/QueryIndexesTable.js +128 -41
- package/dist/modules/query_index/components/QueryIndexesTable.js.map +2 -2
- package/dist/modules/query_index/lib/batch.js +11 -4
- package/dist/modules/query_index/lib/batch.js.map +2 -2
- package/dist/modules/query_index/lib/document.js +12 -5
- package/dist/modules/query_index/lib/document.js.map +2 -2
- package/dist/modules/query_index/lib/engine.js +36 -4
- package/dist/modules/query_index/lib/engine.js.map +2 -2
- package/dist/modules/query_index/lib/indexer.js +1 -1
- package/dist/modules/query_index/lib/indexer.js.map +2 -2
- package/dist/modules/query_index/lib/search-tokens.js +7 -4
- package/dist/modules/query_index/lib/search-tokens.js.map +2 -2
- package/dist/modules/sales/api/documents/factory.js +14 -3
- package/dist/modules/sales/api/documents/factory.js.map +2 -2
- package/dist/modules/sales/commands/documents.js +22 -1
- package/dist/modules/sales/commands/documents.js.map +2 -2
- package/dist/modules/sales/components/useSalesChannelsEnabled.js +2 -35
- package/dist/modules/sales/components/useSalesChannelsEnabled.js.map +2 -2
- package/dist/modules/sales/data/validators.js +25 -4
- package/dist/modules/sales/data/validators.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/api/admin/nav.ts +24 -4
- package/src/modules/auth/api/users/route.ts +8 -28
- package/src/modules/auth/lib/backendChrome.tsx +51 -13
- package/src/modules/customers/api/utils.ts +12 -31
- package/src/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.tsx +35 -3
- package/src/modules/customers/backend/customers/deals/pipeline/page.tsx +10 -1
- package/src/modules/customers/cli.ts +11 -4
- package/src/modules/customers/components/detail/ScheduleActivityDialog.tsx +4 -0
- package/src/modules/customers/components/formConfig.tsx +12 -8
- package/src/modules/dashboards/api/widgets/data/batch/route.ts +4 -0
- package/src/modules/dashboards/api/widgets/data/route.ts +21 -0
- package/src/modules/dashboards/lib/aggregations.ts +122 -43
- package/src/modules/dashboards/lib/exactDecimal.ts +96 -0
- package/src/modules/dashboards/services/widgetDataService.ts +342 -4
- package/src/modules/feature_toggles/components/FeatureGuard.tsx +9 -2
- package/src/modules/feature_toggles/components/hooks/staleTime.ts +5 -0
- package/src/modules/feature_toggles/components/hooks/useFeatureFlagBoolean.ts +13 -1
- package/src/modules/feature_toggles/components/hooks/useFeatureFlagJson.ts +12 -3
- package/src/modules/feature_toggles/components/hooks/useFeatureFlagNumber.ts +10 -1
- package/src/modules/feature_toggles/components/hooks/useFeatureFlagString.ts +10 -1
- package/src/modules/inbox_ops/api/proposals/route.ts +20 -1
- package/src/modules/inbox_ops/subscribers/search-reindex-proposal-created.ts +39 -0
- package/src/modules/integrations/widgets/injection/external-ids/widget.client.tsx +0 -5
- package/src/modules/integrations/widgets/injection/external-ids/widget.ts +13 -0
- package/src/modules/messages/lib/searchLookup.ts +11 -34
- package/src/modules/query_index/api/openapi.ts +12 -0
- package/src/modules/query_index/api/status.ts +238 -136
- package/src/modules/query_index/components/QueryIndexesTable.tsx +192 -46
- package/src/modules/query_index/i18n/de.json +5 -3
- package/src/modules/query_index/i18n/en.json +5 -3
- package/src/modules/query_index/i18n/es.json +5 -3
- package/src/modules/query_index/i18n/pl.json +5 -3
- package/src/modules/query_index/lib/batch.ts +11 -4
- package/src/modules/query_index/lib/document.ts +35 -4
- package/src/modules/query_index/lib/engine.ts +53 -5
- package/src/modules/query_index/lib/indexer.ts +1 -1
- package/src/modules/query_index/lib/search-tokens.ts +13 -4
- package/src/modules/sales/api/documents/factory.ts +28 -3
- package/src/modules/sales/commands/documents.ts +26 -2
- package/src/modules/sales/components/useSalesChannelsEnabled.ts +2 -48
- package/src/modules/sales/data/validators.ts +50 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/auth/lib/backendChrome.tsx"],
|
|
4
|
-
"sourcesContent": ["import * as React from 'react'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport type { BackendRouteManifestEntry } from '@open-mercato/shared/modules/registry'\nimport type {\n BackendChromePayload,\n BackendChromeNavGroup,\n BackendChromeNavItem,\n BackendChromeSectionGroup,\n BackendChromeSectionItem,\n} from '@open-mercato/shared/modules/navigation/backendChrome'\nimport {\n buildAdminNav,\n buildSettingsSections,\n computeSettingsPathPrefixes,\n convertToSectionNavGroups,\n type AdminNavItem,\n} from '@open-mercato/ui/backend/utils/nav'\nimport { resolveRegisteredLucideIconNode } from '@open-mercato/ui/backend/icons/lucideRegistry'\nimport { profilePathPrefixes, profileSections } from './profile-sections'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { filterGrantsByEnabledModules } from '@open-mercato/shared/security/enabledModulesRegistry'\nimport {\n getSelectedOrganizationFromRequest,\n resolveFeatureCheckContext,\n} from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { isAllOrganizationsSelection } from '@open-mercato/core/modules/directory/constants'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { CustomEntity } from '@open-mercato/core/modules/entities/data/entities'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n applySidebarPreference,\n loadFirstRoleSidebarPreference,\n loadSidebarPreference,\n} from '@open-mercato/core/modules/auth/services/sidebarPreferencesService'\nimport type { SidebarPreferencesSettings } from '@open-mercato/shared/modules/navigation/sidebarPreferences'\n\ntype TranslationFn = (key: string | undefined, fallback: string) => string\n\ntype RouteModule = {\n id: string\n backendRoutes?: BackendRouteManifestEntry[]\n}\n\nexport function groupBackendRoutesByModule(routes: BackendRouteManifestEntry[]): RouteModule[] {\n return Array.from(\n routes.reduce((grouped, route) => {\n const list = grouped.get(route.moduleId) ?? []\n list.push(route)\n grouped.set(route.moduleId, list)\n return grouped\n }, new Map<string, BackendRouteManifestEntry[]>()),\n ).map(([id, backendRoutes]) => ({ id, backendRoutes }))\n}\n\ntype SerializableSectionItem = {\n id: string\n label: string\n labelKey?: string\n href: string\n icon?: React.ReactNode\n order?: number\n children?: SerializableSectionItem[]\n}\n\ntype SerializableSectionGroup = {\n id: string\n label: string\n labelKey?: string\n order?: number\n items: SerializableSectionItem[]\n}\n\ntype ResolvedNavItem = Omit<BackendChromeNavItem, 'defaultTitle' | 'children'> & {\n defaultTitle: string\n children?: ResolvedNavItem[]\n}\n\ntype ResolveBackendChromePayloadArgs = {\n auth: Exclude<AuthContext, null>\n locale: string\n modules: RouteModule[]\n translate: TranslationFn\n request?: Request\n selectedOrganizationId?: string | null\n selectedTenantId?: string | null\n}\n\nconst settingsSectionOrder: Record<string, number> = {\n system: 1,\n auth: 2,\n 'customer-portal': 3,\n 'data-designer': 4,\n 'module-configs': 5,\n currencies: 6,\n directory: 7,\n 'feature-toggles': 8,\n}\n\ntype NavGroupWithWeight = Omit<BackendChromeNavGroup, 'id' | 'defaultName' | 'items'> & {\n id: string\n defaultName: string\n items: ResolvedNavItem[]\n weight: number\n}\n\nlet renderToStaticMarkupPromise: Promise<typeof import('react-dom/server')> | null = null\n\nasync function serializeIconMarkup(icon: React.ReactNode | undefined): Promise<string | undefined> {\n if (!icon) return undefined\n if (!renderToStaticMarkupPromise) {\n renderToStaticMarkupPromise = import('react-dom/server')\n }\n const { renderToStaticMarkup } = await renderToStaticMarkupPromise\n\n const normalizedIcon = typeof icon === 'string'\n ? resolveRegisteredLucideIconNode(icon, 'size-4')\n : icon\n\n if (!normalizedIcon) return undefined\n\n try {\n const markup = renderToStaticMarkup(<>{normalizedIcon}</>)\n return markup.trim().length > 0 ? markup : undefined\n } catch {\n // Some icon values may be client-only component references after dependency upgrades.\n // Avoid taking down the entire nav payload because one icon cannot be rendered server-side.\n return undefined\n }\n}\n\nasync function serializeNavItem(item: AdminNavItem): Promise<ResolvedNavItem> {\n return {\n id: item.href,\n href: item.href,\n title: item.title,\n defaultTitle: item.defaultTitle,\n enabled: item.enabled,\n hidden: item.hidden,\n pageContext: item.pageContext,\n iconName: typeof item.icon === 'string' ? item.icon : undefined,\n iconMarkup: await serializeIconMarkup(item.icon),\n children: item.children ? await Promise.all(item.children.map((child) => serializeNavItem(child))) : undefined,\n }\n}\n\nfunction normalizeGroupWeights(groups: NavGroupWithWeight[]): NavGroupWithWeight[] {\n const defaultGroupOrder = [\n 'customers.nav.group',\n 'catalog.nav.group',\n 'customers~sales.nav.group',\n 'wms.nav.group',\n 'resources.nav.group',\n 'staff.nav.group',\n 'entities.nav.group',\n 'directory.nav.group',\n 'attachments.nav.group',\n ]\n const groupOrderIndex = new Map(defaultGroupOrder.map((id, index) => [id, index]))\n groups.sort((a, b) => {\n const aIndex = groupOrderIndex.get(a.id)\n const bIndex = groupOrderIndex.get(b.id)\n if (aIndex !== undefined || bIndex !== undefined) {\n if (aIndex === undefined) return 1\n if (bIndex === undefined) return -1\n if (aIndex !== bIndex) return aIndex - bIndex\n }\n if (a.weight !== b.weight) return a.weight - b.weight\n return a.name.localeCompare(b.name)\n })\n const defaultGroupCount = defaultGroupOrder.length\n groups.forEach((group, index) => {\n const rank = groupOrderIndex.get(group.id)\n const fallbackWeight = typeof group.weight === 'number' ? group.weight : 10_000\n group.weight =\n (rank !== undefined ? rank : defaultGroupCount + index) * 1_000_000 +\n Math.min(Math.max(fallbackWeight, 0), 999_999)\n })\n return groups\n}\n\nasync function groupEntries(entries: AdminNavItem[]): Promise<NavGroupWithWeight[]> {\n const groupMap = new Map<string, NavGroupWithWeight>()\n for (const entry of entries) {\n const weight = entry.priority ?? entry.order ?? 10_000\n const serializedItem = await serializeNavItem(entry)\n const existing = groupMap.get(entry.groupId)\n if (existing) {\n existing.items.push(serializedItem)\n if (weight < existing.weight) existing.weight = weight\n continue\n }\n groupMap.set(entry.groupId, {\n id: entry.groupId,\n name: entry.group,\n defaultName: entry.groupDefaultName,\n items: [serializedItem],\n weight,\n })\n }\n return normalizeGroupWeights(Array.from(groupMap.values()))\n}\n\nfunction adoptSidebarDefaults(groups: NavGroupWithWeight[]): NavGroupWithWeight[] {\n const adoptItems = (items: ResolvedNavItem[]): ResolvedNavItem[] =>\n items.map((item) => ({\n ...item,\n defaultTitle: item.title,\n children: item.children ? adoptItems(item.children) : undefined,\n }))\n\n return groups.map((group) => ({\n ...group,\n defaultName: group.name,\n items: adoptItems(group.items),\n }))\n}\n\nasync function serializeSectionItem(item: {\n id: string\n label: string\n labelKey?: string\n href: string\n icon?: React.ReactNode\n order?: number\n children?: SerializableSectionItem[]\n}): Promise<BackendChromeSectionItem> {\n return {\n id: item.id,\n label: item.label,\n labelKey: item.labelKey,\n href: item.href,\n order: item.order,\n iconName: typeof item.icon === 'string' ? item.icon : undefined,\n iconMarkup: await serializeIconMarkup(item.icon),\n children: item.children ? await Promise.all(item.children.map((child) => serializeSectionItem(child))) : undefined,\n }\n}\n\nasync function serializeSectionGroups(groups: SerializableSectionGroup[]): Promise<BackendChromeSectionGroup[]> {\n return Promise.all(groups.map(async (group) => ({\n id: group.id,\n label: group.label,\n labelKey: group.labelKey,\n order: group.order,\n items: await Promise.all(group.items.map((item) => serializeSectionItem(item))),\n })))\n}\n\nasync function loadScopedContainer(): Promise<AwilixContainer> {\n return createRequestContainer()\n}\n\nexport async function resolveBackendChromePayload({\n auth,\n locale,\n modules,\n translate,\n request,\n selectedOrganizationId,\n selectedTenantId,\n}: ResolveBackendChromePayloadArgs): Promise<BackendChromePayload> {\n const container = await loadScopedContainer()\n const em = container.resolve('em') as EntityManager\n const rbac = container.resolve('rbacService') as {\n loadAcl: (userId: string, scope: { tenantId: string | null; organizationId: string | null }) => Promise<{\n isSuperAdmin: boolean\n features: string[]\n }>\n userHasAllFeatures: (userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }) => Promise<boolean>\n }\n\n let scopedOrganizationId: string | null = auth.orgId ?? null\n let scopedTenantId: string | null = auth.tenantId ?? null\n let allowNavigation = true\n\n try {\n const { organizationId, scope, allowedOrganizationIds } = await resolveFeatureCheckContext({\n container,\n auth,\n request,\n selectedId: selectedOrganizationId,\n tenantId: selectedTenantId,\n })\n scopedOrganizationId = organizationId\n scopedTenantId = scope.tenantId ?? auth.tenantId ?? null\n if (Array.isArray(allowedOrganizationIds) && allowedOrganizationIds.length === 0) {\n allowNavigation = false\n }\n } catch {\n scopedOrganizationId = auth.orgId ?? null\n scopedTenantId = auth.tenantId ?? null\n }\n\n const acl = allowNavigation\n ? await rbac.loadAcl(auth.sub, {\n tenantId: scopedTenantId,\n organizationId: scopedOrganizationId,\n })\n : { isSuperAdmin: false, features: [] }\n\n const rawGrantedFeatures = acl.isSuperAdmin ? ['*'] : acl.features\n const grantedFeatures = filterGrantsByEnabledModules(rawGrantedFeatures)\n const featureChecker = async (features: string[]): Promise<string[]> => {\n if (!allowNavigation || !features.length) return []\n const context = {\n tenantId: scopedTenantId ?? auth.tenantId ?? null,\n organizationId: scopedOrganizationId ?? null,\n }\n const hasAll = await rbac.userHasAllFeatures(auth.sub, features, context)\n if (hasAll) return features\n\n const granted: string[] = []\n for (const feature of features) {\n const hasFeature = await rbac.userHasAllFeatures(auth.sub, [feature], context)\n if (hasFeature) granted.push(feature)\n }\n return granted\n }\n\n let userEntities: Array<{ entityId: string; label: string; href: string }> = []\n if (allowNavigation) {\n try {\n const where: FilterQuery<CustomEntity> = {\n isActive: true,\n showInSidebar: true,\n }\n where.$and = [\n { $or: [{ organizationId: scopedOrganizationId ?? undefined }, { organizationId: null }] },\n { $or: [{ tenantId: scopedTenantId ?? undefined }, { tenantId: null }] },\n ]\n const entities = await em.find(CustomEntity, where, { orderBy: { label: 'asc' } })\n userEntities = entities.map((entity) => ({\n entityId: entity.entityId,\n label: entity.label,\n href: `/backend/entities/user/${encodeURIComponent(entity.entityId)}/records`,\n }))\n } catch {\n userEntities = []\n }\n }\n\n const ctxAuth = {\n roles: auth.roles || [],\n sub: auth.sub,\n tenantId: scopedTenantId,\n orgId: scopedOrganizationId,\n }\n const entries = allowNavigation\n ? await buildAdminNav(\n modules,\n { auth: ctxAuth },\n userEntities,\n translate,\n { checkFeatures: featureChecker },\n )\n : []\n\n let rolePreference: SidebarPreferencesSettings | null = null\n let userPreference: SidebarPreferencesSettings | null = null\n\n if (Array.isArray(auth.roles) && auth.roles.length > 0) {\n const roleRecords = scopedTenantId\n ? await em.find(Role, {\n name: { $in: auth.roles },\n tenantId: scopedTenantId,\n })\n : []\n const roleIds = Array.isArray(roleRecords) ? roleRecords.map((role) => role.id) : []\n if (roleIds.length > 0) {\n rolePreference = await loadFirstRoleSidebarPreference(em, {\n roleIds,\n tenantId: scopedTenantId,\n locale,\n })\n }\n }\n\n const effectiveUserId = auth.isApiKey ? auth.userId : auth.sub\n if (effectiveUserId) {\n userPreference = await loadSidebarPreference(em, {\n userId: effectiveUserId,\n tenantId: scopedTenantId,\n organizationId: scopedOrganizationId,\n locale,\n })\n }\n\n const baseGroups = await groupEntries(entries)\n const groupsWithRole = rolePreference\n ? applySidebarPreference<NavGroupWithWeight>(baseGroups, rolePreference)\n : baseGroups\n const baseForUser = adoptSidebarDefaults(groupsWithRole)\n const appliedGroups = userPreference\n ? applySidebarPreference<NavGroupWithWeight>(baseForUser, userPreference)\n : baseForUser\n\n const settingsSections = await serializeSectionGroups(\n convertToSectionNavGroups(\n buildSettingsSections(entries, settingsSectionOrder),\n translate,\n ),\n )\n\n const requestOrganizationId = request ? getSelectedOrganizationFromRequest(request) : null\n const fallbackOrganizationId = selectedOrganizationId ?? requestOrganizationId ?? auth.orgId ?? null\n const brandOrganizationId = scopedOrganizationId\n ?? (fallbackOrganizationId && !isAllOrganizationsSelection(fallbackOrganizationId) ? fallbackOrganizationId : null)\n\n let brand: BackendChromePayload['brand'] = null\n if (brandOrganizationId && scopedTenantId) {\n try {\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: brandOrganizationId, tenant: scopedTenantId, deletedAt: null },\n undefined,\n { tenantId: scopedTenantId, organizationId: brandOrganizationId },\n )\n if (organization?.logoUrl) {\n brand = {\n name: organization.name,\n logo: {\n src: organization.logoUrl,\n alt: `${organization.name} logo`,\n },\n }\n }\n } catch {\n brand = null\n }\n }\n\n return {\n groups: appliedGroups.map(({ weight: _weight, ...group }) => group),\n settingsSections,\n settingsPathPrefixes: computeSettingsPathPrefixes(buildSettingsSections(entries, settingsSectionOrder)),\n profileSections: await serializeSectionGroups(profileSections),\n profilePathPrefixes,\n grantedFeatures,\n roles: Array.isArray(auth.roles) ? auth.roles : [],\n brand,\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import * as React from 'react'\nimport type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport type { BackendRouteManifestEntry } from '@open-mercato/shared/modules/registry'\nimport type {\n BackendChromePayload,\n BackendChromeNavGroup,\n BackendChromeNavItem,\n BackendChromeSectionGroup,\n BackendChromeSectionItem,\n} from '@open-mercato/shared/modules/navigation/backendChrome'\nimport {\n buildAdminNav,\n buildSettingsSections,\n computeSettingsPathPrefixes,\n convertToSectionNavGroups,\n type AdminNavItem,\n} from '@open-mercato/ui/backend/utils/nav'\nimport { resolveRegisteredLucideIconNode } from '@open-mercato/ui/backend/icons/lucideRegistry'\nimport { profilePathPrefixes, profileSections } from './profile-sections'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { filterGrantsByEnabledModules } from '@open-mercato/shared/security/enabledModulesRegistry'\nimport { getNavGroupOrderOverride } from '@open-mercato/shared/modules/overrides'\nimport {\n getSelectedOrganizationFromRequest,\n resolveFeatureCheckContext,\n} from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { isAllOrganizationsSelection } from '@open-mercato/core/modules/directory/constants'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { CustomEntity } from '@open-mercato/core/modules/entities/data/entities'\nimport { Role } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n applySidebarPreference,\n loadFirstRoleSidebarPreference,\n loadSidebarPreference,\n} from '@open-mercato/core/modules/auth/services/sidebarPreferencesService'\nimport type { SidebarPreferencesSettings } from '@open-mercato/shared/modules/navigation/sidebarPreferences'\n\ntype TranslationFn = (key: string | undefined, fallback: string) => string\n\ntype RouteModule = {\n id: string\n backendRoutes?: BackendRouteManifestEntry[]\n}\n\nexport function groupBackendRoutesByModule(routes: BackendRouteManifestEntry[]): RouteModule[] {\n return Array.from(\n routes.reduce((grouped, route) => {\n const list = grouped.get(route.moduleId) ?? []\n list.push(route)\n grouped.set(route.moduleId, list)\n return grouped\n }, new Map<string, BackendRouteManifestEntry[]>()),\n ).map(([id, backendRoutes]) => ({ id, backendRoutes }))\n}\n\ntype SerializableSectionItem = {\n id: string\n label: string\n labelKey?: string\n href: string\n icon?: React.ReactNode\n order?: number\n children?: SerializableSectionItem[]\n}\n\ntype SerializableSectionGroup = {\n id: string\n label: string\n labelKey?: string\n order?: number\n items: SerializableSectionItem[]\n}\n\ntype ResolvedNavItem = Omit<BackendChromeNavItem, 'defaultTitle' | 'children'> & {\n defaultTitle: string\n children?: ResolvedNavItem[]\n}\n\ntype ResolveBackendChromePayloadArgs = {\n auth: Exclude<AuthContext, null>\n locale: string\n modules: RouteModule[]\n translate: TranslationFn\n request?: Request\n selectedOrganizationId?: string | null\n selectedTenantId?: string | null\n}\n\nconst settingsSectionOrder: Record<string, number> = {\n system: 1,\n auth: 2,\n 'customer-portal': 3,\n 'data-designer': 4,\n 'module-configs': 5,\n currencies: 6,\n directory: 7,\n 'feature-toggles': 8,\n}\n\ntype NavGroupWithWeight = Omit<BackendChromeNavGroup, 'id' | 'defaultName' | 'items'> & {\n id: string\n defaultName: string\n items: ResolvedNavItem[]\n weight: number\n}\n\nlet renderToStaticMarkupPromise: Promise<typeof import('react-dom/server')> | null = null\n\nasync function serializeIconMarkup(icon: React.ReactNode | undefined): Promise<string | undefined> {\n if (!icon) return undefined\n if (!renderToStaticMarkupPromise) {\n renderToStaticMarkupPromise = import('react-dom/server')\n }\n const { renderToStaticMarkup } = await renderToStaticMarkupPromise\n\n const normalizedIcon = typeof icon === 'string'\n ? resolveRegisteredLucideIconNode(icon, 'size-4')\n : icon\n\n if (!normalizedIcon) return undefined\n\n try {\n const markup = renderToStaticMarkup(<>{normalizedIcon}</>)\n return markup.trim().length > 0 ? markup : undefined\n } catch {\n // Some icon values may be client-only component references after dependency upgrades.\n // Avoid taking down the entire nav payload because one icon cannot be rendered server-side.\n return undefined\n }\n}\n\nasync function serializeNavItem(item: AdminNavItem): Promise<ResolvedNavItem> {\n return {\n id: item.href,\n href: item.href,\n title: item.title,\n defaultTitle: item.defaultTitle,\n enabled: item.enabled,\n hidden: item.hidden,\n pageContext: item.pageContext,\n iconName: typeof item.icon === 'string' ? item.icon : undefined,\n iconMarkup: await serializeIconMarkup(item.icon),\n children: item.children ? await Promise.all(item.children.map((child) => serializeNavItem(child))) : undefined,\n }\n}\n\nconst defaultGroupOrder = [\n 'customers.nav.group',\n 'catalog.nav.group',\n 'customers~sales.nav.group',\n 'wms.nav.group',\n 'resources.nav.group',\n 'staff.nav.group',\n 'entities.nav.group',\n 'directory.nav.group',\n 'attachments.nav.group',\n]\n\n/**\n * Group ids ranked ahead of everything else, most significant first.\n *\n * An app may prepend its own ids via `overrides.nav.groupOrder` in `modules.ts`; ids it does not name\n * keep the ordering they have today. With no override configured this returns `defaultGroupOrder`\n * itself, so ordering is unchanged for every existing install.\n */\nfunction resolveGroupOrder(): string[] {\n const override = getNavGroupOrderOverride()\n if (!override || override.length === 0) return defaultGroupOrder\n const overridden = new Set(override)\n return [...override, ...defaultGroupOrder.filter((id) => !overridden.has(id))]\n}\n\nfunction normalizeGroupWeights(groups: NavGroupWithWeight[]): NavGroupWithWeight[] {\n const groupOrder = resolveGroupOrder()\n const groupOrderIndex = new Map(groupOrder.map((id, index) => [id, index]))\n groups.sort((a, b) => {\n const aIndex = groupOrderIndex.get(a.id)\n const bIndex = groupOrderIndex.get(b.id)\n if (aIndex !== undefined || bIndex !== undefined) {\n if (aIndex === undefined) return 1\n if (bIndex === undefined) return -1\n if (aIndex !== bIndex) return aIndex - bIndex\n }\n if (a.weight !== b.weight) return a.weight - b.weight\n return a.name.localeCompare(b.name)\n })\n const defaultGroupCount = groupOrder.length\n groups.forEach((group, index) => {\n const rank = groupOrderIndex.get(group.id)\n const fallbackWeight = typeof group.weight === 'number' ? group.weight : 10_000\n group.weight =\n (rank !== undefined ? rank : defaultGroupCount + index) * 1_000_000 +\n Math.min(Math.max(fallbackWeight, 0), 999_999)\n })\n return groups\n}\n\nasync function groupEntries(entries: AdminNavItem[]): Promise<NavGroupWithWeight[]> {\n const groupMap = new Map<string, NavGroupWithWeight>()\n for (const entry of entries) {\n const weight = entry.priority ?? entry.order ?? 10_000\n const serializedItem = await serializeNavItem(entry)\n const existing = groupMap.get(entry.groupId)\n if (existing) {\n existing.items.push(serializedItem)\n if (weight < existing.weight) existing.weight = weight\n continue\n }\n groupMap.set(entry.groupId, {\n id: entry.groupId,\n name: entry.group,\n defaultName: entry.groupDefaultName,\n items: [serializedItem],\n weight,\n })\n }\n return normalizeGroupWeights(Array.from(groupMap.values()))\n}\n\nfunction adoptSidebarDefaults(groups: NavGroupWithWeight[]): NavGroupWithWeight[] {\n const adoptItems = (items: ResolvedNavItem[]): ResolvedNavItem[] =>\n items.map((item) => ({\n ...item,\n defaultTitle: item.title,\n children: item.children ? adoptItems(item.children) : undefined,\n }))\n\n return groups.map((group) => ({\n ...group,\n defaultName: group.name,\n items: adoptItems(group.items),\n }))\n}\n\nasync function serializeSectionItem(item: {\n id: string\n label: string\n labelKey?: string\n href: string\n icon?: React.ReactNode\n order?: number\n children?: SerializableSectionItem[]\n}): Promise<BackendChromeSectionItem> {\n return {\n id: item.id,\n label: item.label,\n labelKey: item.labelKey,\n href: item.href,\n order: item.order,\n iconName: typeof item.icon === 'string' ? item.icon : undefined,\n iconMarkup: await serializeIconMarkup(item.icon),\n children: item.children ? await Promise.all(item.children.map((child) => serializeSectionItem(child))) : undefined,\n }\n}\n\nasync function serializeSectionGroups(groups: SerializableSectionGroup[]): Promise<BackendChromeSectionGroup[]> {\n return Promise.all(groups.map(async (group) => ({\n id: group.id,\n label: group.label,\n labelKey: group.labelKey,\n order: group.order,\n items: await Promise.all(group.items.map((item) => serializeSectionItem(item))),\n })))\n}\n\nasync function loadScopedContainer(): Promise<AwilixContainer> {\n return createRequestContainer()\n}\n\nexport async function resolveBackendChromePayload({\n auth,\n locale,\n modules,\n translate,\n request,\n selectedOrganizationId,\n selectedTenantId,\n}: ResolveBackendChromePayloadArgs): Promise<BackendChromePayload> {\n const container = await loadScopedContainer()\n const em = container.resolve('em') as EntityManager\n const rbac = container.resolve('rbacService') as {\n loadAcl: (userId: string, scope: { tenantId: string | null; organizationId: string | null }) => Promise<{\n isSuperAdmin: boolean\n features: string[]\n }>\n userHasAllFeatures: (userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }) => Promise<boolean>\n }\n\n let scopedOrganizationId: string | null = auth.orgId ?? null\n let scopedTenantId: string | null = auth.tenantId ?? null\n // The organization the caller actually *selected*, as distinct from the one the scope resolver fell\n // back to. `resolveFeatureCheckContext` resolves `organizationId` to `auth.orgId` when no concrete\n // organization is selected \u2014 which is precisely what an all-organizations view produces \u2014 so the\n // resolved id cannot answer \"which organization am I viewing\".\n let concretelySelectedOrganizationId: string | null = null\n let allowNavigation = true\n\n try {\n const { organizationId, scope, allowedOrganizationIds } = await resolveFeatureCheckContext({\n container,\n auth,\n request,\n selectedId: selectedOrganizationId,\n tenantId: selectedTenantId,\n })\n scopedOrganizationId = organizationId\n scopedTenantId = scope.tenantId ?? auth.tenantId ?? null\n concretelySelectedOrganizationId = scope.selectedId ?? null\n if (Array.isArray(allowedOrganizationIds) && allowedOrganizationIds.length === 0) {\n allowNavigation = false\n }\n } catch {\n scopedOrganizationId = auth.orgId ?? null\n scopedTenantId = auth.tenantId ?? null\n concretelySelectedOrganizationId = null\n }\n\n const acl = allowNavigation\n ? await rbac.loadAcl(auth.sub, {\n tenantId: scopedTenantId,\n organizationId: scopedOrganizationId,\n })\n : { isSuperAdmin: false, features: [] }\n\n const rawGrantedFeatures = acl.isSuperAdmin ? ['*'] : acl.features\n const grantedFeatures = filterGrantsByEnabledModules(rawGrantedFeatures)\n const featureChecker = async (features: string[]): Promise<string[]> => {\n if (!allowNavigation || !features.length) return []\n const context = {\n tenantId: scopedTenantId ?? auth.tenantId ?? null,\n organizationId: scopedOrganizationId ?? null,\n }\n const hasAll = await rbac.userHasAllFeatures(auth.sub, features, context)\n if (hasAll) return features\n\n const granted: string[] = []\n for (const feature of features) {\n const hasFeature = await rbac.userHasAllFeatures(auth.sub, [feature], context)\n if (hasFeature) granted.push(feature)\n }\n return granted\n }\n\n let userEntities: Array<{ entityId: string; label: string; href: string }> = []\n if (allowNavigation) {\n try {\n const where: FilterQuery<CustomEntity> = {\n isActive: true,\n showInSidebar: true,\n }\n where.$and = [\n { $or: [{ organizationId: scopedOrganizationId ?? undefined }, { organizationId: null }] },\n { $or: [{ tenantId: scopedTenantId ?? undefined }, { tenantId: null }] },\n ]\n const entities = await em.find(CustomEntity, where, { orderBy: { label: 'asc' } })\n userEntities = entities.map((entity) => ({\n entityId: entity.entityId,\n label: entity.label,\n href: `/backend/entities/user/${encodeURIComponent(entity.entityId)}/records`,\n }))\n } catch {\n userEntities = []\n }\n }\n\n const ctxAuth = {\n roles: auth.roles || [],\n sub: auth.sub,\n tenantId: scopedTenantId,\n orgId: scopedOrganizationId,\n }\n const entries = allowNavigation\n ? await buildAdminNav(\n modules,\n { auth: ctxAuth },\n userEntities,\n translate,\n { checkFeatures: featureChecker },\n )\n : []\n\n let rolePreference: SidebarPreferencesSettings | null = null\n let userPreference: SidebarPreferencesSettings | null = null\n\n if (Array.isArray(auth.roles) && auth.roles.length > 0) {\n const roleRecords = scopedTenantId\n ? await em.find(Role, {\n name: { $in: auth.roles },\n tenantId: scopedTenantId,\n })\n : []\n const roleIds = Array.isArray(roleRecords) ? roleRecords.map((role) => role.id) : []\n if (roleIds.length > 0) {\n rolePreference = await loadFirstRoleSidebarPreference(em, {\n roleIds,\n tenantId: scopedTenantId,\n locale,\n })\n }\n }\n\n const effectiveUserId = auth.isApiKey ? auth.userId : auth.sub\n if (effectiveUserId) {\n userPreference = await loadSidebarPreference(em, {\n userId: effectiveUserId,\n tenantId: scopedTenantId,\n organizationId: scopedOrganizationId,\n locale,\n })\n }\n\n const baseGroups = await groupEntries(entries)\n const groupsWithRole = rolePreference\n ? applySidebarPreference<NavGroupWithWeight>(baseGroups, rolePreference)\n : baseGroups\n const baseForUser = adoptSidebarDefaults(groupsWithRole)\n const appliedGroups = userPreference\n ? applySidebarPreference<NavGroupWithWeight>(baseForUser, userPreference)\n : baseForUser\n\n const settingsSections = await serializeSectionGroups(\n convertToSectionNavGroups(\n buildSettingsSections(entries, settingsSectionOrder),\n translate,\n ),\n )\n\n const requestOrganizationId = request ? getSelectedOrganizationFromRequest(request) : null\n const fallbackOrganizationId = selectedOrganizationId ?? requestOrganizationId ?? auth.orgId ?? null\n const brandOrganizationId = scopedOrganizationId\n ?? (fallbackOrganizationId && !isAllOrganizationsSelection(fallbackOrganizationId) ? fallbackOrganizationId : null)\n\n let brand: BackendChromePayload['brand'] = null\n // Resolved here rather than left to callers. `brand` only populates when the organization has a\n // logo, so it is a branding channel, not a dependable \"which organization am I viewing\" source.\n // Without this field every downstream app has to fetch `/api/directory/organization-switcher` and\n // walk its tree for the selected id. The row is already loaded below, so the name costs nothing.\n let currentOrganization: BackendChromePayload['currentOrganization'] = null\n if (brandOrganizationId && scopedTenantId) {\n try {\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: brandOrganizationId, tenant: scopedTenantId, deletedAt: null },\n undefined,\n { tenantId: scopedTenantId, organizationId: brandOrganizationId },\n )\n // Only when a concrete organization was selected. Under an all-organizations view\n // `brandOrganizationId` still resolves (to the caller's own organization, which is what keeps\n // branding working), so gating on the loaded row alone would misreport the scope.\n if (organization && concretelySelectedOrganizationId === brandOrganizationId) {\n currentOrganization = { id: String(organization.id), name: organization.name }\n }\n if (organization?.logoUrl) {\n brand = {\n name: organization.name,\n logo: {\n src: organization.logoUrl,\n alt: `${organization.name} logo`,\n },\n }\n }\n } catch {\n // Fail soft, as before: a failed organization lookup must not take down the nav payload.\n brand = null\n currentOrganization = null\n }\n }\n\n return {\n groups: appliedGroups.map(({ weight: _weight, ...group }) => group),\n settingsSections,\n settingsPathPrefixes: computeSettingsPathPrefixes(buildSettingsSections(entries, settingsSectionOrder)),\n profileSections: await serializeSectionGroups(profileSections),\n profilePathPrefixes,\n grantedFeatures,\n roles: Array.isArray(auth.roles) ? auth.roles : [],\n brand,\n currentOrganization,\n }\n}\n"],
|
|
5
|
+
"mappings": "AA8HwC;AAjHxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,uCAAuC;AAChD,SAAS,qBAAqB,uBAAuB;AACrD,SAAS,8BAA8B;AACvC,SAAS,oCAAoC;AAC7C,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUA,SAAS,2BAA2B,QAAoD;AAC7F,SAAO,MAAM;AAAA,IACX,OAAO,OAAO,CAAC,SAAS,UAAU;AAChC,YAAM,OAAO,QAAQ,IAAI,MAAM,QAAQ,KAAK,CAAC;AAC7C,WAAK,KAAK,KAAK;AACf,cAAQ,IAAI,MAAM,UAAU,IAAI;AAChC,aAAO;AAAA,IACT,GAAG,oBAAI,IAAyC,CAAC;AAAA,EACnD,EAAE,IAAI,CAAC,CAAC,IAAI,aAAa,OAAO,EAAE,IAAI,cAAc,EAAE;AACxD;AAmCA,MAAM,uBAA+C;AAAA,EACnD,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,YAAY;AAAA,EACZ,W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A,EAAE,IAAI,qBAAqB,QAAQ,gBAAgB,WAAW,KAAK;AAAA,QACnE;AAAA,QACA,EAAE,UAAU,gBAAgB,gBAAgB,oBAAoB;AAAA,MAClE;AAIA,UAAI,gBAAgB,qCAAqC,qBAAqB;AAC5E,8BAAsB,EAAE,IAAI,OAAO,aAAa,EAAE,GAAG,MAAM,aAAa,KAAK;AAAA,MAC/E;AACA,UAAI,cAAc,SAAS;AACzB,gBAAQ;AAAA,UACN,MAAM,aAAa;AAAA,UACnB,MAAM;AAAA,YACJ,KAAK,aAAa;AAAA,YAClB,KAAK,GAAG,aAAa,IAAI;AAAA,UAC3B;AAAA,QACF;AAAA,MACF;AAAA,IACF,QAAQ;AAEN,cAAQ;AACR,4BAAsB;AAAA,IACxB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,QAAQ,cAAc,IAAI,CAAC,EAAE,QAAQ,SAAS,GAAG,MAAM,MAAM,KAAK;AAAA,IAClE;AAAA,IACA,sBAAsB,4BAA4B,sBAAsB,SAAS,oBAAoB,CAAC;AAAA,IACtG,iBAAiB,MAAM,uBAAuB,eAAe;AAAA,IAC7D;AAAA,IACA;AAAA,IACA,OAAO,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,QAAQ,CAAC;AAAA,IACjD;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { createScopedApiHelpers } from "@open-mercato/shared/lib/api/scoped";
|
|
2
2
|
import { sql } from "kysely";
|
|
3
|
-
import {
|
|
4
|
-
import { tokenizeText } from "@open-mercato/shared/lib/search/tokenize";
|
|
3
|
+
import { findEntityIdsBySearchTokensCompat } from "@open-mercato/shared/lib/search/tokenLookup";
|
|
5
4
|
import { SortDir } from "@open-mercato/shared/lib/query/types";
|
|
6
5
|
const { withScopedPayload, parseScopedCommandInput } = createScopedApiHelpers({
|
|
7
6
|
messages: {
|
|
@@ -65,23 +64,18 @@ async function findSearchTokenEntityIds({
|
|
|
65
64
|
fields,
|
|
66
65
|
query
|
|
67
66
|
}) {
|
|
68
|
-
const trimmed = query.trim();
|
|
69
|
-
if (!trimmed) return null;
|
|
70
|
-
const tokens = tokenizeText(trimmed, resolveSearchConfig());
|
|
71
|
-
if (!tokens.hashes.length) return [];
|
|
72
67
|
const em = ctx.container.resolve("em");
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
return rows.map((row) => typeof row.entity_id === "string" ? row.entity_id : null).filter((id) => typeof id === "string" && id.length > 0);
|
|
68
|
+
return findEntityIdsBySearchTokensCompat({
|
|
69
|
+
db: em.getKysely(),
|
|
70
|
+
entityType,
|
|
71
|
+
query,
|
|
72
|
+
fields,
|
|
73
|
+
scope: {
|
|
74
|
+
tenantId: ctx.auth?.tenantId !== void 0 ? ctx.auth?.tenantId ?? null : void 0,
|
|
75
|
+
organizationId: ctx.selectedOrganizationId ?? void 0,
|
|
76
|
+
organizationIds: ctx.organizationIds
|
|
77
|
+
}
|
|
78
|
+
});
|
|
85
79
|
}
|
|
86
80
|
async function mapScopedEntityIds({
|
|
87
81
|
ctx,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customers/api/utils.ts"],
|
|
4
|
-
"sourcesContent": ["import { createScopedApiHelpers } from '@open-mercato/shared/lib/api/scoped'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { sql } from 'kysely'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport type { QueryCustomFieldSource, QueryJoinEdge, QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { resolveSearchConfig } from '@open-mercato/shared/lib/search/config'\nimport { tokenizeText } from '@open-mercato/shared/lib/search/tokenize'\nimport { SortDir } from '@open-mercato/shared/lib/query/types'\n\nconst { withScopedPayload, parseScopedCommandInput } = createScopedApiHelpers({\n messages: {\n tenantRequired: { key: 'customers.errors.tenant_required', fallback: 'Tenant context is required' },\n organizationRequired: { key: 'customers.errors.organization_required', fallback: 'Organization context is required' },\n },\n})\n\nconst NO_MATCH_ID = '00000000-0000-0000-0000-000000000000'\n\ntype SearchTokenMatchInput = {\n ctx: CrudCtx\n entityType: string\n fields: string[]\n query: string\n}\n\ntype SearchTokenSource = {\n entityType: string\n fields: string[]\n mapToEntityIds?: {\n table: string\n sourceColumn?: string\n targetColumn: string\n tenantColumn?: string\n organizationColumn?: string\n }\n}\n\nasync function enrichSearchSourcesWithCustomFieldTokens(\n ctx: CrudCtx,\n sources: SearchTokenSource[],\n): Promise<SearchTokenSource[]> {\n const entityTypes = Array.from(\n new Set(\n sources\n .map((source) => source.entityType)\n .filter((value): value is string => typeof value === 'string' && value.length > 0),\n ),\n )\n if (!entityTypes.length) return sources\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>() as any\n let defsQuery = db\n .selectFrom('custom_field_defs')\n .select(['entity_id', 'key', 'kind'])\n .where('entity_id', 'in', entityTypes)\n .where('is_active', '=', true)\n\n const tenantScope = ctx.auth?.tenantId ?? null\n defsQuery = defsQuery.where((eb: any) => eb.or([\n eb('tenant_id', '=', tenantScope),\n eb('tenant_id', 'is', null),\n ]))\n\n if (ctx.selectedOrganizationId) {\n defsQuery = defsQuery.where((eb: any) => eb.or([\n eb('organization_id', '=', ctx.selectedOrganizationId),\n eb('organization_id', 'is', null),\n ]))\n } else if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length > 0) {\n defsQuery = defsQuery.where((eb: any) => eb.or([\n eb('organization_id', 'in', ctx.organizationIds),\n eb('organization_id', 'is', null),\n ]))\n }\n\n const customFieldKeysByEntity = new Map<string, Set<string>>()\n const rows = await defsQuery.execute()\n for (const row of rows as Array<{ entity_id?: unknown; key?: unknown; kind?: unknown }>) {\n if (row.kind === 'attachment') continue\n const entityType = typeof row.entity_id === 'string' ? row.entity_id : null\n const key = typeof row.key === 'string' ? row.key.trim() : ''\n if (!entityType || !key) continue\n const bucket = customFieldKeysByEntity.get(entityType) ?? new Set<string>()\n bucket.add(`cf:${key}`)\n customFieldKeysByEntity.set(entityType, bucket)\n }\n\n return sources.map((source) => {\n const customFieldKeys = customFieldKeysByEntity.get(source.entityType)\n return {\n ...source,\n fields: Array.from(new Set([\n 'search_text',\n ...source.fields,\n ...(customFieldKeys ? Array.from(customFieldKeys) : []),\n ])),\n }\n })\n}\n\nasync function findSearchTokenEntityIds({\n ctx,\n entityType,\n fields,\n query,\n}: SearchTokenMatchInput): Promise<string[] | null> {\n const trimmed = query.trim()\n if (!trimmed) return null\n\n const tokens = tokenizeText(trimmed, resolveSearchConfig())\n if (!tokens.hashes.length) return []\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>() as any\n let searchQuery = db\n .selectFrom('search_tokens')\n .select('entity_id')\n .where('entity_type', '=', entityType)\n .where('field', 'in', fields)\n .where('token_hash', 'in', tokens.hashes)\n .groupBy('entity_id')\n .having(sql<boolean>`count(distinct token_hash) >= ${tokens.hashes.length}`)\n\n if (ctx.auth?.tenantId !== undefined) {\n searchQuery = searchQuery.where(sql<boolean>`tenant_id is not distinct from ${ctx.auth?.tenantId ?? null}`)\n }\n if (ctx.selectedOrganizationId) {\n searchQuery = searchQuery.where('organization_id', '=', ctx.selectedOrganizationId)\n } else if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length > 0) {\n searchQuery = searchQuery.where('organization_id', 'in', ctx.organizationIds)\n }\n\n const rows = await searchQuery.execute() as Array<{ entity_id?: unknown }>\n return rows\n .map((row) => (typeof row.entity_id === 'string' ? row.entity_id : null))\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n}\n\nasync function mapScopedEntityIds({\n ctx,\n ids,\n config,\n}: {\n ctx: CrudCtx\n ids: string[]\n config: NonNullable<SearchTokenSource['mapToEntityIds']>\n}): Promise<string[]> {\n if (!ids.length) return []\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>() as any\n const sourceColumn = config.sourceColumn ?? 'id'\n const tenantColumn = config.tenantColumn ?? 'tenant_id'\n const organizationColumn = config.organizationColumn ?? 'organization_id'\n\n let mapQuery = db\n .selectFrom(config.table)\n .select(config.targetColumn)\n .where(sourceColumn, 'in', ids)\n\n if (ctx.auth?.tenantId !== undefined) {\n mapQuery = mapQuery.where(sql<boolean>`${sql.ref(tenantColumn)} is not distinct from ${ctx.auth?.tenantId ?? null}`)\n }\n if (ctx.selectedOrganizationId) {\n mapQuery = mapQuery.where(organizationColumn, '=', ctx.selectedOrganizationId)\n } else if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length > 0) {\n mapQuery = mapQuery.where(organizationColumn, 'in', ctx.organizationIds)\n }\n\n const rows = await mapQuery.execute() as Array<Record<string, unknown>>\n return rows\n .map((row) => {\n const value = row[config.targetColumn]\n return typeof value === 'string' ? value : null\n })\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n}\n\nexport async function findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n sources,\n query,\n}: {\n ctx: CrudCtx\n sources: SearchTokenSource[]\n query: string\n}): Promise<string[] | null> {\n const trimmed = query.trim()\n if (!trimmed) return null\n\n const enrichedSources = await enrichSearchSourcesWithCustomFieldTokens(ctx, sources)\n const perSource = await Promise.all(\n enrichedSources.map(async (source) => {\n const rawIds = await findSearchTokenEntityIds({\n ctx,\n entityType: source.entityType,\n fields: source.fields,\n query: trimmed,\n })\n if (rawIds === null) return null\n return source.mapToEntityIds\n ? await mapScopedEntityIds({ ctx, ids: rawIds, config: source.mapToEntityIds })\n : rawIds\n }),\n )\n\n const matchedIds = new Set<string>()\n for (const entityIds of perSource) {\n if (entityIds === null) return null\n entityIds.forEach((id) => matchedIds.add(id))\n }\n\n return Array.from(matchedIds)\n}\n\nexport async function findMatchingEntityIdsBySearchTokens({\n ctx,\n entityType,\n fields,\n query,\n}: SearchTokenMatchInput): Promise<string[] | null> {\n return findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n query,\n sources: [{ entityType, fields }],\n })\n}\n\nexport function applyEntityIdRestriction(\n filters: Record<string, unknown>,\n ids: string[] | null,\n): void {\n if (ids === null) return\n const currentIdFilter =\n filters.id && typeof filters.id === 'object' && !Array.isArray(filters.id)\n ? (filters.id as { $eq?: unknown; $in?: unknown })\n : null\n const currentEq = typeof currentIdFilter?.$eq === 'string' ? currentIdFilter.$eq : null\n\n if (currentEq) {\n filters.id = ids.includes(currentEq) ? { $eq: currentEq } : { $eq: NO_MATCH_ID }\n return\n }\n\n filters.id = ids.length > 0 ? { $in: ids } : { $eq: NO_MATCH_ID }\n}\n\nexport function applyEntityIdExclusion(\n filters: Record<string, unknown>,\n ids: string[],\n): void {\n const uniqueIds = Array.from(new Set(ids.filter((id) => typeof id === 'string' && id.length > 0)))\n if (!uniqueIds.length) return\n\n const currentIdFilter =\n filters.id && typeof filters.id === 'object' && !Array.isArray(filters.id)\n ? (filters.id as { $eq?: unknown; $in?: unknown; $nin?: unknown })\n : null\n const currentEq = typeof currentIdFilter?.$eq === 'string' ? currentIdFilter.$eq : null\n const currentIn = Array.isArray(currentIdFilter?.$in)\n ? currentIdFilter.$in.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : null\n const currentNotIn = Array.isArray(currentIdFilter?.$nin)\n ? currentIdFilter.$nin.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : []\n\n if (currentEq) {\n filters.id = uniqueIds.includes(currentEq) ? { $eq: NO_MATCH_ID } : { $eq: currentEq }\n return\n }\n\n if (currentIn) {\n const nextIds = currentIn.filter((id) => !uniqueIds.includes(id))\n filters.id = nextIds.length > 0 ? { $in: nextIds } : { $eq: NO_MATCH_ID }\n return\n }\n\n filters.id = {\n ...(currentIdFilter ?? {}),\n $nin: Array.from(new Set([...currentNotIn, ...uniqueIds])),\n }\n}\n\nexport async function findMatchingEntityIdsWithQueryEngine({\n ctx,\n entityId,\n filters,\n customFieldSources,\n joins,\n}: {\n ctx: CrudCtx\n entityId: EntityId\n filters: Record<string, unknown>\n customFieldSources?: QueryCustomFieldSource[]\n joins?: QueryJoinEdge[]\n}): Promise<string[]> {\n const qe = ctx.container.resolve('queryEngine') as QueryEngine\n const ids = new Set<string>()\n const pageSize = 100\n let page = 1\n let total = 0\n\n do {\n const result = await qe.query(entityId, {\n fields: ['id'],\n filters,\n page: { page, pageSize },\n sort: [{ field: 'id', dir: SortDir.Asc }],\n tenantId: ctx.auth?.tenantId ?? undefined,\n organizationId: ctx.selectedOrganizationId ?? undefined,\n organizationIds: ctx.organizationIds ?? undefined,\n customFieldSources,\n joins,\n })\n\n total = result.total ?? 0\n for (const item of result.items ?? []) {\n const id = item && typeof item === 'object' ? (item as Record<string, unknown>).id : null\n if (typeof id === 'string' && id.length > 0) {\n ids.add(id)\n }\n }\n if (!result.items?.length) break\n page += 1\n } while (ids.size < total)\n\n return Array.from(ids)\n}\n\nexport { withScopedPayload, parseScopedCommandInput }\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,8BAA8B;AAEvC,SAAS,WAAW;AAIpB,SAAS,
|
|
4
|
+
"sourcesContent": ["import { createScopedApiHelpers } from '@open-mercato/shared/lib/api/scoped'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { sql } from 'kysely'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport type { QueryCustomFieldSource, QueryJoinEdge, QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { findEntityIdsBySearchTokensCompat, type SearchTokenDatabase } from '@open-mercato/shared/lib/search/tokenLookup'\nimport { SortDir } from '@open-mercato/shared/lib/query/types'\n\nconst { withScopedPayload, parseScopedCommandInput } = createScopedApiHelpers({\n messages: {\n tenantRequired: { key: 'customers.errors.tenant_required', fallback: 'Tenant context is required' },\n organizationRequired: { key: 'customers.errors.organization_required', fallback: 'Organization context is required' },\n },\n})\n\nconst NO_MATCH_ID = '00000000-0000-0000-0000-000000000000'\n\ntype SearchTokenMatchInput = {\n ctx: CrudCtx\n entityType: string\n fields: string[]\n query: string\n}\n\ntype SearchTokenSource = {\n entityType: string\n fields: string[]\n mapToEntityIds?: {\n table: string\n sourceColumn?: string\n targetColumn: string\n tenantColumn?: string\n organizationColumn?: string\n }\n}\n\nasync function enrichSearchSourcesWithCustomFieldTokens(\n ctx: CrudCtx,\n sources: SearchTokenSource[],\n): Promise<SearchTokenSource[]> {\n const entityTypes = Array.from(\n new Set(\n sources\n .map((source) => source.entityType)\n .filter((value): value is string => typeof value === 'string' && value.length > 0),\n ),\n )\n if (!entityTypes.length) return sources\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>() as any\n let defsQuery = db\n .selectFrom('custom_field_defs')\n .select(['entity_id', 'key', 'kind'])\n .where('entity_id', 'in', entityTypes)\n .where('is_active', '=', true)\n\n const tenantScope = ctx.auth?.tenantId ?? null\n defsQuery = defsQuery.where((eb: any) => eb.or([\n eb('tenant_id', '=', tenantScope),\n eb('tenant_id', 'is', null),\n ]))\n\n if (ctx.selectedOrganizationId) {\n defsQuery = defsQuery.where((eb: any) => eb.or([\n eb('organization_id', '=', ctx.selectedOrganizationId),\n eb('organization_id', 'is', null),\n ]))\n } else if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length > 0) {\n defsQuery = defsQuery.where((eb: any) => eb.or([\n eb('organization_id', 'in', ctx.organizationIds),\n eb('organization_id', 'is', null),\n ]))\n }\n\n const customFieldKeysByEntity = new Map<string, Set<string>>()\n const rows = await defsQuery.execute()\n for (const row of rows as Array<{ entity_id?: unknown; key?: unknown; kind?: unknown }>) {\n if (row.kind === 'attachment') continue\n const entityType = typeof row.entity_id === 'string' ? row.entity_id : null\n const key = typeof row.key === 'string' ? row.key.trim() : ''\n if (!entityType || !key) continue\n const bucket = customFieldKeysByEntity.get(entityType) ?? new Set<string>()\n bucket.add(`cf:${key}`)\n customFieldKeysByEntity.set(entityType, bucket)\n }\n\n return sources.map((source) => {\n const customFieldKeys = customFieldKeysByEntity.get(source.entityType)\n return {\n ...source,\n fields: Array.from(new Set([\n 'search_text',\n ...source.fields,\n ...(customFieldKeys ? Array.from(customFieldKeys) : []),\n ])),\n }\n })\n}\n\nasync function findSearchTokenEntityIds({\n ctx,\n entityType,\n fields,\n query,\n}: SearchTokenMatchInput): Promise<string[] | null> {\n const em = ctx.container.resolve('em') as EntityManager\n return findEntityIdsBySearchTokensCompat({\n db: em.getKysely<SearchTokenDatabase>(),\n entityType,\n query,\n fields,\n scope: {\n tenantId: ctx.auth?.tenantId !== undefined ? ctx.auth?.tenantId ?? null : undefined,\n organizationId: ctx.selectedOrganizationId ?? undefined,\n organizationIds: ctx.organizationIds,\n },\n })\n}\n\nasync function mapScopedEntityIds({\n ctx,\n ids,\n config,\n}: {\n ctx: CrudCtx\n ids: string[]\n config: NonNullable<SearchTokenSource['mapToEntityIds']>\n}): Promise<string[]> {\n if (!ids.length) return []\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>() as any\n const sourceColumn = config.sourceColumn ?? 'id'\n const tenantColumn = config.tenantColumn ?? 'tenant_id'\n const organizationColumn = config.organizationColumn ?? 'organization_id'\n\n let mapQuery = db\n .selectFrom(config.table)\n .select(config.targetColumn)\n .where(sourceColumn, 'in', ids)\n\n if (ctx.auth?.tenantId !== undefined) {\n mapQuery = mapQuery.where(sql<boolean>`${sql.ref(tenantColumn)} is not distinct from ${ctx.auth?.tenantId ?? null}`)\n }\n if (ctx.selectedOrganizationId) {\n mapQuery = mapQuery.where(organizationColumn, '=', ctx.selectedOrganizationId)\n } else if (Array.isArray(ctx.organizationIds) && ctx.organizationIds.length > 0) {\n mapQuery = mapQuery.where(organizationColumn, 'in', ctx.organizationIds)\n }\n\n const rows = await mapQuery.execute() as Array<Record<string, unknown>>\n return rows\n .map((row) => {\n const value = row[config.targetColumn]\n return typeof value === 'string' ? value : null\n })\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n}\n\nexport async function findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n sources,\n query,\n}: {\n ctx: CrudCtx\n sources: SearchTokenSource[]\n query: string\n}): Promise<string[] | null> {\n const trimmed = query.trim()\n if (!trimmed) return null\n\n const enrichedSources = await enrichSearchSourcesWithCustomFieldTokens(ctx, sources)\n const perSource = await Promise.all(\n enrichedSources.map(async (source) => {\n const rawIds = await findSearchTokenEntityIds({\n ctx,\n entityType: source.entityType,\n fields: source.fields,\n query: trimmed,\n })\n if (rawIds === null) return null\n return source.mapToEntityIds\n ? await mapScopedEntityIds({ ctx, ids: rawIds, config: source.mapToEntityIds })\n : rawIds\n }),\n )\n\n const matchedIds = new Set<string>()\n for (const entityIds of perSource) {\n if (entityIds === null) return null\n entityIds.forEach((id) => matchedIds.add(id))\n }\n\n return Array.from(matchedIds)\n}\n\nexport async function findMatchingEntityIdsBySearchTokens({\n ctx,\n entityType,\n fields,\n query,\n}: SearchTokenMatchInput): Promise<string[] | null> {\n return findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n query,\n sources: [{ entityType, fields }],\n })\n}\n\nexport function applyEntityIdRestriction(\n filters: Record<string, unknown>,\n ids: string[] | null,\n): void {\n if (ids === null) return\n const currentIdFilter =\n filters.id && typeof filters.id === 'object' && !Array.isArray(filters.id)\n ? (filters.id as { $eq?: unknown; $in?: unknown })\n : null\n const currentEq = typeof currentIdFilter?.$eq === 'string' ? currentIdFilter.$eq : null\n\n if (currentEq) {\n filters.id = ids.includes(currentEq) ? { $eq: currentEq } : { $eq: NO_MATCH_ID }\n return\n }\n\n filters.id = ids.length > 0 ? { $in: ids } : { $eq: NO_MATCH_ID }\n}\n\nexport function applyEntityIdExclusion(\n filters: Record<string, unknown>,\n ids: string[],\n): void {\n const uniqueIds = Array.from(new Set(ids.filter((id) => typeof id === 'string' && id.length > 0)))\n if (!uniqueIds.length) return\n\n const currentIdFilter =\n filters.id && typeof filters.id === 'object' && !Array.isArray(filters.id)\n ? (filters.id as { $eq?: unknown; $in?: unknown; $nin?: unknown })\n : null\n const currentEq = typeof currentIdFilter?.$eq === 'string' ? currentIdFilter.$eq : null\n const currentIn = Array.isArray(currentIdFilter?.$in)\n ? currentIdFilter.$in.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : null\n const currentNotIn = Array.isArray(currentIdFilter?.$nin)\n ? currentIdFilter.$nin.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : []\n\n if (currentEq) {\n filters.id = uniqueIds.includes(currentEq) ? { $eq: NO_MATCH_ID } : { $eq: currentEq }\n return\n }\n\n if (currentIn) {\n const nextIds = currentIn.filter((id) => !uniqueIds.includes(id))\n filters.id = nextIds.length > 0 ? { $in: nextIds } : { $eq: NO_MATCH_ID }\n return\n }\n\n filters.id = {\n ...(currentIdFilter ?? {}),\n $nin: Array.from(new Set([...currentNotIn, ...uniqueIds])),\n }\n}\n\nexport async function findMatchingEntityIdsWithQueryEngine({\n ctx,\n entityId,\n filters,\n customFieldSources,\n joins,\n}: {\n ctx: CrudCtx\n entityId: EntityId\n filters: Record<string, unknown>\n customFieldSources?: QueryCustomFieldSource[]\n joins?: QueryJoinEdge[]\n}): Promise<string[]> {\n const qe = ctx.container.resolve('queryEngine') as QueryEngine\n const ids = new Set<string>()\n const pageSize = 100\n let page = 1\n let total = 0\n\n do {\n const result = await qe.query(entityId, {\n fields: ['id'],\n filters,\n page: { page, pageSize },\n sort: [{ field: 'id', dir: SortDir.Asc }],\n tenantId: ctx.auth?.tenantId ?? undefined,\n organizationId: ctx.selectedOrganizationId ?? undefined,\n organizationIds: ctx.organizationIds ?? undefined,\n customFieldSources,\n joins,\n })\n\n total = result.total ?? 0\n for (const item of result.items ?? []) {\n const id = item && typeof item === 'object' ? (item as Record<string, unknown>).id : null\n if (typeof id === 'string' && id.length > 0) {\n ids.add(id)\n }\n }\n if (!result.items?.length) break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;AACjB,MAAI,OAAO;AACX,MAAI,QAAQ;AAEZ,KAAG;AACD,UAAM,SAAS,MAAM,GAAG,MAAM,UAAU;AAAA,MACtC,QAAQ,CAAC,IAAI;AAAA,MACb;AAAA,MACA,MAAM,EAAE,MAAM,SAAS;AAAA,MACvB,MAAM,CAAC,EAAE,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC;AAAA,MACxC,UAAU,IAAI,MAAM,YAAY;AAAA,MAChC,gBAAgB,IAAI,0BAA0B;AAAA,MAC9C,iBAAiB,IAAI,mBAAmB;AAAA,MACxC;AAAA,MACA;AAAA,IACF,CAAC;AAED,YAAQ,OAAO,SAAS;AACxB,eAAW,QAAQ,OAAO,SAAS,CAAC,GAAG;AACrC,YAAM,KAAK,QAAQ,OAAO,SAAS,WAAY,KAAiC,KAAK;AACrF,UAAI,OAAO,OAAO,YAAY,GAAG,SAAS,GAAG;AAC3C,YAAI,IAAI,EAAE;AAAA,MACZ;AAAA,IACF;AACA,QAAI,CAAC,OAAO,OAAO,OAAQ;AAC3B,YAAQ;AAAA,EACV,SAAS,IAAI,OAAO;AAEpB,SAAO,MAAM,KAAK,GAAG;AACvB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.js
CHANGED
|
@@ -18,6 +18,7 @@ import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuarde
|
|
|
18
18
|
import { flash } from "@open-mercato/ui/backend/FlashMessages";
|
|
19
19
|
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
20
20
|
import { translateWithFallback } from "@open-mercato/shared/lib/i18n/translate";
|
|
21
|
+
import { registerComponent } from "@open-mercato/shared/modules/widgets/component-registry";
|
|
21
22
|
const STATUS_OPTIONS = ["open", "in_progress", "win", "loose"];
|
|
22
23
|
const FALLBACK_CURRENCIES = [
|
|
23
24
|
{ code: "USD", isBase: true },
|
|
@@ -25,6 +26,8 @@ const FALLBACK_CURRENCIES = [
|
|
|
25
26
|
{ code: "GBP" },
|
|
26
27
|
{ code: "PLN" }
|
|
27
28
|
];
|
|
29
|
+
const QUICK_DEAL_DIALOG_COMPONENT_ID = "dialog:customers.deals.quickDeal";
|
|
30
|
+
const DEFAULT_QUICK_DEAL_PROBABILITY = 25;
|
|
28
31
|
const QUICK_DEAL_CONTEXT_ID = "customers-deals-kanban:quick-deal";
|
|
29
32
|
function QuickDealDialog({
|
|
30
33
|
open,
|
|
@@ -34,7 +37,8 @@ function QuickDealDialog({
|
|
|
34
37
|
currentUserId,
|
|
35
38
|
currentUserLabel,
|
|
36
39
|
companies = [],
|
|
37
|
-
currencies
|
|
40
|
+
currencies,
|
|
41
|
+
defaultProbability = DEFAULT_QUICK_DEAL_PROBABILITY
|
|
38
42
|
}) {
|
|
39
43
|
const t = useT();
|
|
40
44
|
const [formInstanceKey, setFormInstanceKey] = React.useState(0);
|
|
@@ -82,11 +86,11 @@ function QuickDealDialog({
|
|
|
82
86
|
valueCurrency: defaultCurrencyCode,
|
|
83
87
|
companyId: "",
|
|
84
88
|
status: "open",
|
|
85
|
-
probability:
|
|
89
|
+
probability: defaultProbability,
|
|
86
90
|
expectedCloseAt: "",
|
|
87
91
|
description: ""
|
|
88
92
|
}),
|
|
89
|
-
[defaultCurrencyCode]
|
|
93
|
+
[defaultCurrencyCode, defaultProbability]
|
|
90
94
|
);
|
|
91
95
|
const fields = React.useMemo(
|
|
92
96
|
() => {
|
|
@@ -310,8 +314,18 @@ function QuickDealDialog({
|
|
|
310
314
|
}
|
|
311
315
|
);
|
|
312
316
|
}
|
|
317
|
+
registerComponent({
|
|
318
|
+
id: QUICK_DEAL_DIALOG_COMPONENT_ID,
|
|
319
|
+
component: QuickDealDialog,
|
|
320
|
+
metadata: {
|
|
321
|
+
module: "customers",
|
|
322
|
+
description: 'Kanban quick-add deal dialog (pipeline board "+ deal").'
|
|
323
|
+
}
|
|
324
|
+
});
|
|
313
325
|
var QuickDealDialog_default = QuickDealDialog;
|
|
314
326
|
export {
|
|
327
|
+
DEFAULT_QUICK_DEAL_PROBABILITY,
|
|
328
|
+
QUICK_DEAL_DIALOG_COMPONENT_ID,
|
|
315
329
|
QuickDealDialog,
|
|
316
330
|
QuickDealDialog_default as default
|
|
317
331
|
};
|
package/dist/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../../src/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { z } from 'zod'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Avatar } from '@open-mercato/ui/primitives/avatar'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { ComboboxInput } from '@open-mercato/ui/backend/inputs/ComboboxInput'\nimport { createCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { translateWithFallback } from '@open-mercato/shared/lib/i18n/translate'\n\n// Deal status values written by the kanban flow. These intentionally do NOT include 'closed'\n// because the rest of the app only persists 'loose' for lost deals (see StatusFilterPopover\n// notes). 'in_progress' is kept for backwards compatibility with quick-deals created from\n// the previous version of this dialog. The labels are looked up via i18n at render time so\n// the historic typo 'loose' doesn't leak to operators \u2014 the storage value stays unchanged.\nconst STATUS_OPTIONS = ['open', 'in_progress', 'win', 'loose'] as const\n\n/**\n * Tenant currency option. The page resolves these from the currencies module (see\n * `useCurrencyDictionary`) and passes them in; we no longer hardcode the 4-currency\n * list that previously locked tenants on CZK/SEK/HUF/etc. out of quick-add.\n */\nexport type QuickDealCurrencyOption = {\n code: string\n label?: string\n isBase?: boolean\n}\n\nconst FALLBACK_CURRENCIES: QuickDealCurrencyOption[] = [\n { code: 'USD', isBase: true },\n { code: 'EUR' },\n { code: 'GBP' },\n { code: 'PLN' },\n]\n\nexport type QuickDealContext = {\n pipelineId: string\n pipelineName: string\n pipelineStageId: string\n pipelineStageLabel: string\n}\n\nexport type QuickDealCompanyOption = {\n id: string\n label: string\n}\n\ntype QuickDealDialogProps = {\n open: boolean\n context: QuickDealContext | null\n onClose: () => void\n onCreated: () => void\n currentUserId?: string\n currentUserLabel?: string\n companies?: QuickDealCompanyOption[]\n /**\n * Tenant currency list. When omitted (e.g. dictionary not yet loaded), we render a\n * conservative fallback so the dialog still works end-to-end. The default selection is\n * always the entry with `isBase: true`, falling back to the first item.\n */\n currencies?: QuickDealCurrencyOption[]\n}\n\ntype QuickDealFormValues = {\n title: string\n valueAmount: number | null\n valueCurrency: string\n companyId: string\n status: (typeof STATUS_OPTIONS)[number]\n probability: number | null\n expectedCloseAt: string\n description: string\n}\n\nconst QUICK_DEAL_CONTEXT_ID = 'customers-deals-kanban:quick-deal'\n\nexport function QuickDealDialog({\n open,\n context,\n onClose,\n onCreated,\n currentUserId,\n currentUserLabel,\n companies = [],\n currencies,\n}: QuickDealDialogProps): React.ReactElement | null {\n const t = useT()\n // Re-mount CrudForm whenever the dialog opens so cleared state is consistently fresh.\n // We also key on `context?.pipelineStageId` so reopening from a different stage doesn't\n // reuse stale field values (the page passes a fresh stage in `context` each time).\n const [formInstanceKey, setFormInstanceKey] = React.useState(0)\n React.useEffect(() => {\n if (open) setFormInstanceKey((current) => current + 1)\n }, [open])\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n retryLastMutation: () => Promise<boolean>\n }>({\n contextId: QUICK_DEAL_CONTEXT_ID,\n blockedMessage: translateWithFallback(t, 'ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n const titleRequiredMessage = translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.required',\n 'Title is required.',\n )\n\n // Default currency selection: tenant base currency, else first available, else 'USD' as\n // a last-resort literal that satisfies the form validator (which now accepts any 3-char\n // code rather than a hardcoded enum).\n const resolvedCurrencies = React.useMemo(\n () => (currencies && currencies.length > 0 ? currencies : FALLBACK_CURRENCIES),\n [currencies],\n )\n const defaultCurrencyCode = React.useMemo(() => {\n const base = resolvedCurrencies.find((currency) => currency.isBase)\n return base?.code ?? resolvedCurrencies[0]?.code ?? 'USD'\n }, [resolvedCurrencies])\n\n const formSchema = React.useMemo(\n () =>\n z.object({\n title: z.string().trim().min(1, titleRequiredMessage),\n valueAmount: z.number().min(0).nullable().optional(),\n // The set of valid currencies is tenant-defined and resolved at runtime; we accept\n // any non-empty string here and let the server (which knows the canonical list)\n // reject anything bogus.\n valueCurrency: z.string().min(1),\n companyId: z.string().optional(),\n status: z.enum(STATUS_OPTIONS),\n probability: z.number().min(0).max(100).nullable().optional(),\n expectedCloseAt: z.string().optional(),\n description: z.string().optional(),\n }),\n // Cast widens to QuickDealFormValues so CrudForm's TValues generic stays exact.\n [titleRequiredMessage],\n ) as unknown as z.ZodType<QuickDealFormValues>\n\n const initialValues = React.useMemo<Partial<QuickDealFormValues>>(\n () => ({\n title: '',\n valueAmount: null,\n valueCurrency: defaultCurrencyCode,\n companyId: '',\n status: 'open',\n probability: 25,\n expectedCloseAt: '',\n description: '',\n }),\n [defaultCurrencyCode],\n )\n\n const fields = React.useMemo<CrudField[]>(\n () => {\n const list: CrudField[] = [\n {\n // CrudForm auto-focuses the first field of the first group on mount; we don't\n // need (and CrudField doesn't accept) an explicit `autoFocus` prop here.\n id: 'title',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.title.label', 'Deal title'),\n type: 'text',\n required: true,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.placeholder',\n 'e.g. Q3 Expansion \u2014 Lighting Package',\n ),\n },\n {\n id: 'valueAmount',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.value', 'Value'),\n type: 'number',\n layout: 'half',\n placeholder: '0',\n },\n {\n id: 'valueCurrency',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.currency', 'Currency'),\n type: 'select',\n layout: 'half',\n options: resolvedCurrencies.map((currency) => ({\n value: currency.code,\n label: currency.label && currency.label !== currency.code\n ? `${currency.code} \u2014 ${currency.label}`\n : currency.code,\n })),\n },\n {\n // Company is a typeahead (ComboboxInput) rather than a plain <select>: tenants\n // with hundreds of companies get an unusable dropdown otherwise. The `seedOptions`\n // carry the most-recent companies the page already loaded; an async loader could\n // be added later to hit the companies search endpoint for full coverage.\n id: 'companyId',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.company', 'Company'),\n type: 'custom',\n component: ({ value, setValue }) => (\n <ComboboxInput\n value={typeof value === 'string' ? value : ''}\n onChange={(next) => setValue(next)}\n seedOptions={companies.map((company) => ({ value: company.id, label: company.label }))}\n placeholder={translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.companyPh',\n 'Pick a company or add new\u2026',\n )}\n allowCustomValues={false}\n />\n ),\n },\n ]\n // Owner is read-only display of the current user (mirrors original UX). Hidden when\n // we don't know the user \u2014 avoids confusing empty avatar cell.\n if (currentUserLabel) {\n list.push({\n id: 'owner',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.owner', 'Owner'),\n type: 'custom',\n readOnly: true,\n component: () => (\n <div className=\"flex h-9 items-center gap-2 rounded-md border border-input bg-card px-3 text-sm\">\n <Avatar label={currentUserLabel} size=\"sm\" />\n <span>{currentUserLabel}</span>\n </div>\n ),\n })\n }\n // Progressive disclosure: status + probability + close date + description live in\n // a separate \"More details\" group with `defaultExpanded: false` (configured via\n // collapsibleGroups on the host CrudForm).\n list.push(\n {\n id: 'status',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.status', 'Status'),\n type: 'select',\n // Storage value is preserved (`loose` etc.) \u2014 only the displayed label is\n // translated, so we never write a localised string back to the DB.\n options: STATUS_OPTIONS.map((statusValue) => ({\n value: statusValue,\n label: translateWithFallback(\n t,\n `customers.deals.kanban.quickDeal.status.${statusValue}`,\n statusValue,\n ),\n })),\n },\n {\n id: 'probability',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.probability', 'Probability'),\n type: 'number',\n layout: 'half',\n placeholder: '25',\n },\n {\n id: 'expectedCloseAt',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.expectedClose', 'Expected close'),\n type: 'date',\n layout: 'half',\n },\n {\n id: 'description',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.description', 'Description'),\n type: 'textarea',\n rows: 3,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.description.placeholder',\n 'Short context, decision makers or next steps. Markdown supported.',\n ),\n },\n )\n return list\n },\n [companies, currentUserLabel, resolvedCurrencies, t],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => [\n {\n id: 'basic',\n // No title \u2014 keep the basic section flush with the dialog header.\n fields: ['title', 'valueAmount', 'valueCurrency', 'companyId', ...(currentUserLabel ? ['owner'] : [])],\n },\n {\n id: 'more',\n title: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.more',\n 'More details (probability, close date, description)',\n ),\n fields: ['status', 'probability', 'expectedCloseAt', 'description'],\n },\n ],\n [currentUserLabel, t],\n )\n\n const handleSubmit = React.useCallback(\n async (values: QuickDealFormValues) => {\n if (!context) return\n const trimmedTitle = values.title.trim()\n if (!trimmedTitle.length) {\n throw createCrudFormError(titleRequiredMessage, { title: titleRequiredMessage })\n }\n const payload: Record<string, unknown> = {\n title: trimmedTitle,\n pipelineId: context.pipelineId,\n pipelineStageId: context.pipelineStageId,\n valueCurrency: values.valueCurrency,\n }\n if (typeof values.valueAmount === 'number' && Number.isFinite(values.valueAmount)) {\n payload.valueAmount = values.valueAmount\n }\n if (currentUserId) payload.ownerUserId = currentUserId\n if (values.companyId) payload.companyIds = [values.companyId]\n if (values.status) payload.status = values.status\n if (typeof values.probability === 'number' && Number.isFinite(values.probability)) {\n payload.probability = values.probability\n }\n if (values.expectedCloseAt && values.expectedCloseAt.trim().length) {\n payload.expectedCloseAt = values.expectedCloseAt\n }\n if (values.description && values.description.trim().length) {\n payload.description = values.description\n }\n const operation = () =>\n createCrud('customers/deals', payload, {\n errorMessage: translateWithFallback(t, 'customers.deals.create.error', 'Failed to create deal.'),\n })\n await runMutation({\n operation,\n context: {\n formId: QUICK_DEAL_CONTEXT_ID,\n resourceKind: 'customers.deal',\n retryLastMutation,\n },\n })\n flash(\n translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.success',\n 'Deal added to {stage}.',\n { stage: context.pipelineStageLabel },\n ),\n 'success',\n )\n onCreated()\n onClose()\n },\n [context, currentUserId, onClose, onCreated, retryLastMutation, runMutation, t, titleRequiredMessage],\n )\n\n if (!context) return null\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) onClose()\n }}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {translateWithFallback(t, 'customers.deals.kanban.quickDeal.title', 'Quick deal')}\n </DialogTitle>\n <DialogDescription>\n {translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.context',\n 'Pipeline: {pipeline} \u00B7 Stage: {stage}',\n { pipeline: context.pipelineName, stage: context.pipelineStageLabel },\n )}\n </DialogDescription>\n </DialogHeader>\n\n <CrudForm<QuickDealFormValues>\n key={`${context.pipelineStageId}:${formInstanceKey}`}\n embedded\n fields={fields}\n groups={groups}\n // The \"More details\" group starts collapsed; users can expand to set\n // status / probability / close date / description. Mirrors the previous\n // \"+ More details\" toggle.\n collapsibleGroups={{ pageType: 'customers.deals.kanban.quickDeal' }}\n initialValues={initialValues}\n schema={formSchema}\n submitLabel={translateWithFallback(t, 'customers.deals.kanban.quickDeal.submit', 'Add deal')}\n onSubmit={handleSubmit}\n />\n </DialogContent>\n </Dialog>\n )\n}\n\nexport default QuickDealDialog\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { z } from 'zod'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Avatar } from '@open-mercato/ui/primitives/avatar'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { ComboboxInput } from '@open-mercato/ui/backend/inputs/ComboboxInput'\nimport { createCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { translateWithFallback } from '@open-mercato/shared/lib/i18n/translate'\nimport { registerComponent } from '@open-mercato/shared/modules/widgets/component-registry'\n\n// Deal status values written by the kanban flow. These intentionally do NOT include 'closed'\n// because the rest of the app only persists 'loose' for lost deals (see StatusFilterPopover\n// notes). 'in_progress' is kept for backwards compatibility with quick-deals created from\n// the previous version of this dialog. The labels are looked up via i18n at render time so\n// the historic typo 'loose' doesn't leak to operators \u2014 the storage value stays unchanged.\nconst STATUS_OPTIONS = ['open', 'in_progress', 'win', 'loose'] as const\n\n/**\n * Tenant currency option. The page resolves these from the currencies module (see\n * `useCurrencyDictionary`) and passes them in; we no longer hardcode the 4-currency\n * list that previously locked tenants on CZK/SEK/HUF/etc. out of quick-add.\n */\nexport type QuickDealCurrencyOption = {\n code: string\n label?: string\n isBase?: boolean\n}\n\nconst FALLBACK_CURRENCIES: QuickDealCurrencyOption[] = [\n { code: 'USD', isBase: true },\n { code: 'EUR' },\n { code: 'GBP' },\n { code: 'PLN' },\n]\n\nexport type QuickDealContext = {\n pipelineId: string\n pipelineName: string\n pipelineStageId: string\n pipelineStageLabel: string\n}\n\nexport type QuickDealCompanyOption = {\n id: string\n label: string\n}\n\n/**\n * Registered component id for the kanban quick-add dialog. Downstream apps can\n * target it from `widgets/components.ts` to replace/wrap the dialog or to\n * transform its props \u2014 e.g. `defaultProbability: null` so quick-create stops\n * seeding a probability that overrides pipeline automation (#4329).\n */\nexport const QUICK_DEAL_DIALOG_COMPONENT_ID = 'dialog:customers.deals.quickDeal'\n\n/** Probability seeded into the quick-add form when the host passes no override. */\nexport const DEFAULT_QUICK_DEAL_PROBABILITY = 25\n\nexport type QuickDealDialogProps = {\n open: boolean\n context: QuickDealContext | null\n onClose: () => void\n onCreated: () => void\n currentUserId?: string\n currentUserLabel?: string\n companies?: QuickDealCompanyOption[]\n /**\n * Probability pre-filled in the collapsed \"More details\" group. `null` leaves\n * the field empty, so quick-create sends no `probability` at all and whatever\n * the pipeline/automation derives for the target stage stands. Defaults to\n * `DEFAULT_QUICK_DEAL_PROBABILITY` to preserve the historic behavior.\n */\n defaultProbability?: number | null\n /**\n * Tenant currency list. When omitted (e.g. dictionary not yet loaded), we render a\n * conservative fallback so the dialog still works end-to-end. The default selection is\n * always the entry with `isBase: true`, falling back to the first item.\n */\n currencies?: QuickDealCurrencyOption[]\n}\n\ntype QuickDealFormValues = {\n title: string\n valueAmount: number | null\n valueCurrency: string\n companyId: string\n status: (typeof STATUS_OPTIONS)[number]\n probability: number | null\n expectedCloseAt: string\n description: string\n}\n\nconst QUICK_DEAL_CONTEXT_ID = 'customers-deals-kanban:quick-deal'\n\nexport function QuickDealDialog({\n open,\n context,\n onClose,\n onCreated,\n currentUserId,\n currentUserLabel,\n companies = [],\n currencies,\n defaultProbability = DEFAULT_QUICK_DEAL_PROBABILITY,\n}: QuickDealDialogProps): React.ReactElement | null {\n const t = useT()\n // Re-mount CrudForm whenever the dialog opens so cleared state is consistently fresh.\n // We also key on `context?.pipelineStageId` so reopening from a different stage doesn't\n // reuse stale field values (the page passes a fresh stage in `context` each time).\n const [formInstanceKey, setFormInstanceKey] = React.useState(0)\n React.useEffect(() => {\n if (open) setFormInstanceKey((current) => current + 1)\n }, [open])\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n retryLastMutation: () => Promise<boolean>\n }>({\n contextId: QUICK_DEAL_CONTEXT_ID,\n blockedMessage: translateWithFallback(t, 'ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n const titleRequiredMessage = translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.required',\n 'Title is required.',\n )\n\n // Default currency selection: tenant base currency, else first available, else 'USD' as\n // a last-resort literal that satisfies the form validator (which now accepts any 3-char\n // code rather than a hardcoded enum).\n const resolvedCurrencies = React.useMemo(\n () => (currencies && currencies.length > 0 ? currencies : FALLBACK_CURRENCIES),\n [currencies],\n )\n const defaultCurrencyCode = React.useMemo(() => {\n const base = resolvedCurrencies.find((currency) => currency.isBase)\n return base?.code ?? resolvedCurrencies[0]?.code ?? 'USD'\n }, [resolvedCurrencies])\n\n const formSchema = React.useMemo(\n () =>\n z.object({\n title: z.string().trim().min(1, titleRequiredMessage),\n valueAmount: z.number().min(0).nullable().optional(),\n // The set of valid currencies is tenant-defined and resolved at runtime; we accept\n // any non-empty string here and let the server (which knows the canonical list)\n // reject anything bogus.\n valueCurrency: z.string().min(1),\n companyId: z.string().optional(),\n status: z.enum(STATUS_OPTIONS),\n probability: z.number().min(0).max(100).nullable().optional(),\n expectedCloseAt: z.string().optional(),\n description: z.string().optional(),\n }),\n // Cast widens to QuickDealFormValues so CrudForm's TValues generic stays exact.\n [titleRequiredMessage],\n ) as unknown as z.ZodType<QuickDealFormValues>\n\n const initialValues = React.useMemo<Partial<QuickDealFormValues>>(\n () => ({\n title: '',\n valueAmount: null,\n valueCurrency: defaultCurrencyCode,\n companyId: '',\n status: 'open',\n probability: defaultProbability,\n expectedCloseAt: '',\n description: '',\n }),\n [defaultCurrencyCode, defaultProbability],\n )\n\n const fields = React.useMemo<CrudField[]>(\n () => {\n const list: CrudField[] = [\n {\n // CrudForm auto-focuses the first field of the first group on mount; we don't\n // need (and CrudField doesn't accept) an explicit `autoFocus` prop here.\n id: 'title',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.title.label', 'Deal title'),\n type: 'text',\n required: true,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.placeholder',\n 'e.g. Q3 Expansion \u2014 Lighting Package',\n ),\n },\n {\n id: 'valueAmount',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.value', 'Value'),\n type: 'number',\n layout: 'half',\n placeholder: '0',\n },\n {\n id: 'valueCurrency',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.currency', 'Currency'),\n type: 'select',\n layout: 'half',\n options: resolvedCurrencies.map((currency) => ({\n value: currency.code,\n label: currency.label && currency.label !== currency.code\n ? `${currency.code} \u2014 ${currency.label}`\n : currency.code,\n })),\n },\n {\n // Company is a typeahead (ComboboxInput) rather than a plain <select>: tenants\n // with hundreds of companies get an unusable dropdown otherwise. The `seedOptions`\n // carry the most-recent companies the page already loaded; an async loader could\n // be added later to hit the companies search endpoint for full coverage.\n id: 'companyId',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.company', 'Company'),\n type: 'custom',\n component: ({ value, setValue }) => (\n <ComboboxInput\n value={typeof value === 'string' ? value : ''}\n onChange={(next) => setValue(next)}\n seedOptions={companies.map((company) => ({ value: company.id, label: company.label }))}\n placeholder={translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.companyPh',\n 'Pick a company or add new\u2026',\n )}\n allowCustomValues={false}\n />\n ),\n },\n ]\n // Owner is read-only display of the current user (mirrors original UX). Hidden when\n // we don't know the user \u2014 avoids confusing empty avatar cell.\n if (currentUserLabel) {\n list.push({\n id: 'owner',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.owner', 'Owner'),\n type: 'custom',\n readOnly: true,\n component: () => (\n <div className=\"flex h-9 items-center gap-2 rounded-md border border-input bg-card px-3 text-sm\">\n <Avatar label={currentUserLabel} size=\"sm\" />\n <span>{currentUserLabel}</span>\n </div>\n ),\n })\n }\n // Progressive disclosure: status + probability + close date + description live in\n // a separate \"More details\" group with `defaultExpanded: false` (configured via\n // collapsibleGroups on the host CrudForm).\n list.push(\n {\n id: 'status',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.status', 'Status'),\n type: 'select',\n // Storage value is preserved (`loose` etc.) \u2014 only the displayed label is\n // translated, so we never write a localised string back to the DB.\n options: STATUS_OPTIONS.map((statusValue) => ({\n value: statusValue,\n label: translateWithFallback(\n t,\n `customers.deals.kanban.quickDeal.status.${statusValue}`,\n statusValue,\n ),\n })),\n },\n {\n id: 'probability',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.probability', 'Probability'),\n type: 'number',\n layout: 'half',\n placeholder: '25',\n },\n {\n id: 'expectedCloseAt',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.expectedClose', 'Expected close'),\n type: 'date',\n layout: 'half',\n },\n {\n id: 'description',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.description', 'Description'),\n type: 'textarea',\n rows: 3,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.description.placeholder',\n 'Short context, decision makers or next steps. Markdown supported.',\n ),\n },\n )\n return list\n },\n [companies, currentUserLabel, resolvedCurrencies, t],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => [\n {\n id: 'basic',\n // No title \u2014 keep the basic section flush with the dialog header.\n fields: ['title', 'valueAmount', 'valueCurrency', 'companyId', ...(currentUserLabel ? ['owner'] : [])],\n },\n {\n id: 'more',\n title: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.more',\n 'More details (probability, close date, description)',\n ),\n fields: ['status', 'probability', 'expectedCloseAt', 'description'],\n },\n ],\n [currentUserLabel, t],\n )\n\n const handleSubmit = React.useCallback(\n async (values: QuickDealFormValues) => {\n if (!context) return\n const trimmedTitle = values.title.trim()\n if (!trimmedTitle.length) {\n throw createCrudFormError(titleRequiredMessage, { title: titleRequiredMessage })\n }\n const payload: Record<string, unknown> = {\n title: trimmedTitle,\n pipelineId: context.pipelineId,\n pipelineStageId: context.pipelineStageId,\n valueCurrency: values.valueCurrency,\n }\n if (typeof values.valueAmount === 'number' && Number.isFinite(values.valueAmount)) {\n payload.valueAmount = values.valueAmount\n }\n if (currentUserId) payload.ownerUserId = currentUserId\n if (values.companyId) payload.companyIds = [values.companyId]\n if (values.status) payload.status = values.status\n if (typeof values.probability === 'number' && Number.isFinite(values.probability)) {\n payload.probability = values.probability\n }\n if (values.expectedCloseAt && values.expectedCloseAt.trim().length) {\n payload.expectedCloseAt = values.expectedCloseAt\n }\n if (values.description && values.description.trim().length) {\n payload.description = values.description\n }\n const operation = () =>\n createCrud('customers/deals', payload, {\n errorMessage: translateWithFallback(t, 'customers.deals.create.error', 'Failed to create deal.'),\n })\n await runMutation({\n operation,\n context: {\n formId: QUICK_DEAL_CONTEXT_ID,\n resourceKind: 'customers.deal',\n retryLastMutation,\n },\n })\n flash(\n translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.success',\n 'Deal added to {stage}.',\n { stage: context.pipelineStageLabel },\n ),\n 'success',\n )\n onCreated()\n onClose()\n },\n [context, currentUserId, onClose, onCreated, retryLastMutation, runMutation, t, titleRequiredMessage],\n )\n\n if (!context) return null\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) onClose()\n }}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {translateWithFallback(t, 'customers.deals.kanban.quickDeal.title', 'Quick deal')}\n </DialogTitle>\n <DialogDescription>\n {translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.context',\n 'Pipeline: {pipeline} \u00B7 Stage: {stage}',\n { pipeline: context.pipelineName, stage: context.pipelineStageLabel },\n )}\n </DialogDescription>\n </DialogHeader>\n\n <CrudForm<QuickDealFormValues>\n key={`${context.pipelineStageId}:${formInstanceKey}`}\n embedded\n fields={fields}\n groups={groups}\n // The \"More details\" group starts collapsed; users can expand to set\n // status / probability / close date / description. Mirrors the previous\n // \"+ More details\" toggle.\n collapsibleGroups={{ pageType: 'customers.deals.kanban.quickDeal' }}\n initialValues={initialValues}\n schema={formSchema}\n submitLabel={translateWithFallback(t, 'customers.deals.kanban.quickDeal.submit', 'Add deal')}\n onSubmit={handleSubmit}\n />\n </DialogContent>\n </Dialog>\n )\n}\n\n// Register so downstream apps can reach the dialog from `widgets/components.ts`\n// (replace / wrap / propsTransform) instead of forking the whole kanban page\n// just to change a default (#4329).\nregisterComponent<QuickDealDialogProps>({\n id: QUICK_DEAL_DIALOG_COMPONENT_ID,\n component: QuickDealDialog,\n metadata: {\n module: 'customers',\n description: 'Kanban quick-add deal dialog (pipeline board \"+ deal\").',\n },\n})\n\nexport default QuickDealDialog\n"],
|
|
5
|
+
"mappings": ";AAsOY,cAuBA,YAvBA;AApOZ,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,SAAS,gBAAoD;AAC7D,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AACpC,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC,SAAS,yBAAyB;AAOlC,MAAM,iBAAiB,CAAC,QAAQ,eAAe,OAAO,OAAO;AAa7D,MAAM,sBAAiD;AAAA,EACrD,EAAE,MAAM,OAAO,QAAQ,KAAK;AAAA,EAC5B,EAAE,MAAM,MAAM;AAAA,EACd,EAAE,MAAM,MAAM;AAAA,EACd,EAAE,MAAM,MAAM;AAChB;AAoBO,MAAM,iCAAiC;AAGvC,MAAM,iCAAiC;AAoC9C,MAAM,wBAAwB;AAEvB,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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AAAA,YACR,aAAa,sBAAsB,GAAG,2CAA2C,UAAU;AAAA,YAC3F,UAAU;AAAA;AAAA,UAXL,GAAG,QAAQ,eAAe,IAAI,eAAe;AAAA,QAYpD;AAAA,SACF;AAAA;AAAA,EACF;AAEJ;AAKA,kBAAwC;AAAA,EACtC,IAAI;AAAA,EACJ,WAAW;AAAA,EACX,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AACF,CAAC;AAED,IAAO,0BAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -58,7 +58,8 @@ import { LaneCurrencyBreakdown } from "./components/LaneCurrencyBreakdown.js";
|
|
|
58
58
|
import { CurrencyFilterPopover } from "./components/CurrencyFilterPopover.js";
|
|
59
59
|
import { AddStageLane } from "./components/AddStageLane.js";
|
|
60
60
|
import {
|
|
61
|
-
QuickDealDialog
|
|
61
|
+
QuickDealDialog as DefaultQuickDealDialog,
|
|
62
|
+
QUICK_DEAL_DIALOG_COMPONENT_ID
|
|
62
63
|
} from "./components/QuickDealDialog.js";
|
|
63
64
|
import { AddStageDialog } from "./components/AddStageDialog.js";
|
|
64
65
|
import { StatusFilterPopover } from "./components/StatusFilterPopover.js";
|
|
@@ -71,6 +72,7 @@ import {
|
|
|
71
72
|
ActivityComposerDialog
|
|
72
73
|
} from "./components/ActivityComposerDialog.js";
|
|
73
74
|
import { BulkActionsBar } from "./components/BulkActionsBar.js";
|
|
75
|
+
import { useRegisteredComponent } from "@open-mercato/ui/backend/injection/useRegisteredComponent";
|
|
74
76
|
import { ChangeStageDialog } from "./components/ChangeStageDialog.js";
|
|
75
77
|
import { ChangeOwnerDialog } from "./components/ChangeOwnerDialog.js";
|
|
76
78
|
import { buildCrudExportUrl, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
|
|
@@ -278,6 +280,10 @@ function sortDeals(deals, option) {
|
|
|
278
280
|
}
|
|
279
281
|
function DealsKanbanPage() {
|
|
280
282
|
const t = useT();
|
|
283
|
+
const QuickDealDialog = useRegisteredComponent(
|
|
284
|
+
QUICK_DEAL_DIALOG_COMPONENT_ID,
|
|
285
|
+
DefaultQuickDealDialog
|
|
286
|
+
);
|
|
281
287
|
const router = useRouter();
|
|
282
288
|
const scopeVersion = useOrganizationScopeVersion();
|
|
283
289
|
const queryClient = useQueryClient();
|