@open-mercato/core 0.11.1-develop.8516.1.497643e13b → 0.11.1-develop.8521.1.204f384ec3
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.
|
@@ -20,6 +20,7 @@ import { Organization } from "@open-mercato/core/modules/directory/data/entities
|
|
|
20
20
|
import { CustomEntity } from "@open-mercato/core/modules/entities/data/entities";
|
|
21
21
|
import { Role } from "@open-mercato/core/modules/auth/data/entities";
|
|
22
22
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
23
|
+
import { isExplicitlyEmptyOrganizationScope } from "@open-mercato/shared/lib/auth/organizationScope";
|
|
23
24
|
import {
|
|
24
25
|
applySidebarPreference,
|
|
25
26
|
findSidebarPreference,
|
|
@@ -220,6 +221,7 @@ async function resolveBackendChromePayload({
|
|
|
220
221
|
let scopedTenantId = auth.tenantId ?? null;
|
|
221
222
|
let concretelySelectedOrganizationId = null;
|
|
222
223
|
let allowNavigation = true;
|
|
224
|
+
let organizationScopeIsEmpty = false;
|
|
223
225
|
try {
|
|
224
226
|
const { organizationId, scope, allowedOrganizationIds } = await resolveFeatureCheckContext({
|
|
225
227
|
container,
|
|
@@ -231,6 +233,7 @@ async function resolveBackendChromePayload({
|
|
|
231
233
|
scopedOrganizationId = organizationId;
|
|
232
234
|
scopedTenantId = scope.tenantId ?? auth.tenantId ?? null;
|
|
233
235
|
concretelySelectedOrganizationId = scope.selectedId ?? null;
|
|
236
|
+
organizationScopeIsEmpty = isExplicitlyEmptyOrganizationScope(scope);
|
|
234
237
|
if (Array.isArray(allowedOrganizationIds) && allowedOrganizationIds.length === 0) {
|
|
235
238
|
allowNavigation = false;
|
|
236
239
|
}
|
|
@@ -333,7 +336,7 @@ async function resolveBackendChromePayload({
|
|
|
333
336
|
);
|
|
334
337
|
const requestOrganizationId = request ? getSelectedOrganizationFromRequest(request) : null;
|
|
335
338
|
const fallbackOrganizationId = selectedOrganizationId ?? requestOrganizationId ?? auth.orgId ?? null;
|
|
336
|
-
const brandOrganizationId = scopedOrganizationId ?? (fallbackOrganizationId && !isAllOrganizationsSelection(fallbackOrganizationId) ? fallbackOrganizationId : null);
|
|
339
|
+
const brandOrganizationId = organizationScopeIsEmpty ? null : scopedOrganizationId ?? (fallbackOrganizationId && !isAllOrganizationsSelection(fallbackOrganizationId) ? fallbackOrganizationId : null);
|
|
337
340
|
let brand = null;
|
|
338
341
|
let currentOrganization = null;
|
|
339
342
|
if (brandOrganizationId && scopedTenantId) {
|
|
@@ -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 buildProfileSections,\n buildSettingsSections,\n computeSettingsPathPrefixes,\n convertToSectionNavGroups,\n mergeSectionsWithDiscovered,\n type AdminNavItem,\n type SettingsSection,\n type SettingsSectionItem,\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 { 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 findSidebarPreference,\n loadFirstRoleSidebarPreference,\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\n/**\n * Settings section weights, keyed by the untranslated group id each page declares as `pageGroupKey`.\n *\n * Mirrors `defaultGroupOrder` above: an id, never a rendered label, so the panel keeps its intended\n * order in every locale and an app-side module can place its own section deterministically (#4843).\n */\nexport const settingsSectionOrder: Record<string, number> = {\n 'settings.sections.system': 1,\n 'settings.sections.auth': 2,\n 'customer_accounts.settings.section': 3,\n 'settings.sections.dataDesigner': 4,\n 'settings.sections.moduleConfigs': 5,\n 'currencies.nav.group': 6,\n 'settings.sections.directory': 7,\n 'settings.sections.featureToggles': 8,\n}\n\n/**\n * Profile section weights, keyed by the untranslated group id, exactly like `settingsSectionOrder`.\n *\n * Only the built-in account section is ranked; a module contributing its own profile group sorts\n * after it on the shared 999 fallback rather than displacing the account pages.\n */\nexport const profileSectionOrder: Record<string, number> = {\n 'profile.sections.account': 1,\n}\n\n/**\n * Path prefixes that put the shell into profile mode: the static list plus every href the resolved\n * profile sections actually link to.\n *\n * `computeSettingsPathPrefixes` is deliberately not reused \u2014 it also registers each item's parent\n * directory, which is harmless for `/backend/settings/*` but would hand profile mode a whole\n * unrelated subtree if a module hosts its profile page outside `/backend/profile/`.\n */\nfunction resolveProfilePathPrefixes(sections: SettingsSection[]): string[] {\n const prefixes = new Set(profilePathPrefixes)\n const visitItems = (items: SettingsSectionItem[]) => {\n for (const item of items) {\n prefixes.add(item.href)\n if (item.children?.length) visitItems(item.children)\n }\n }\n for (const section of sections) visitItems(section.items)\n return Array.from(prefixes)\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\nconst NAV_ITEM_FALLBACK_WEIGHT = 10_000\n\n/**\n * The weight a nav entry sorts by, using the same `priority ?? order` precedence as `buildAdminNav`.\n *\n * `serializeNavItem` emits this resolved number rather than the raw declaration, including the\n * fallback, so a consumer that re-sorts by the field it receives lands on the order it was served in.\n * Emitting the raw `priority ?? order` would leave `order` undefined on any page declaring neither \u2014\n * and the `(a.order ?? 0) - (b.order ?? 0)` idiom this codebase uses elsewhere would then hoist those\n * pages to the top instead of leaving them last (#4845).\n */\nfunction resolveNavItemWeight(item: AdminNavItem): number {\n return item.priority ?? item.order ?? NAV_ITEM_FALLBACK_WEIGHT\n}\n\nfunction sortNavItemsByWeight(items: AdminNavItem[]): AdminNavItem[] {\n return [...items].sort((a, b) => {\n const weightDifference = resolveNavItemWeight(a) - resolveNavItemWeight(b)\n if (weightDifference !== 0) return weightDifference\n return a.title.localeCompare(b.title)\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 order: resolveNavItemWeight(item),\n children: item.children\n ? await Promise.all(sortNavItemsByWeight(item.children).map((child) => serializeNavItem(child)))\n : 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 'staff.time_tracking.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 : NAV_ITEM_FALLBACK_WEIGHT\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, Omit<NavGroupWithWeight, 'items'> & { entries: AdminNavItem[] }>()\n for (const entry of entries) {\n const weight = resolveNavItemWeight(entry)\n const existing = groupMap.get(entry.groupId)\n if (existing) {\n existing.entries.push(entry)\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 entries: [entry],\n weight,\n })\n }\n const groups: NavGroupWithWeight[] = []\n for (const { entries: groupItems, ...group } of groupMap.values()) {\n groups.push({\n ...group,\n items: await Promise.all(sortNavItemsByWeight(groupItems).map((entry) => serializeNavItem(entry))),\n })\n }\n return normalizeGroupWeights(groups)\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 getEffectiveFeatures: (userId: string, scope: { tenantId: string | null; organizationId: string | null }) => Promise<string[]>\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 grantedFeatures = allowNavigation\n ? await rbac.getEffectiveFeatures(auth.sub, {\n tenantId: scopedTenantId,\n organizationId: scopedOrganizationId,\n })\n : []\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 findSidebarPreference(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 // The profile sidebar mirrors the profile dropdown: the static baseline covers the `navHidden`\n // pages route discovery drops, and every other `pageContext: 'profile'` page is derived from the\n // manifest so a module adding one lands in both surfaces at once (#5594).\n const resolvedProfileSections = mergeSectionsWithDiscovered(\n profileSections,\n buildProfileSections(entries, profileSectionOrder),\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 preserveAspectRatio: !!organization.logoPreserveAspectRatio,\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(\n convertToSectionNavGroups(resolvedProfileSections, translate),\n ),\n profilePathPrefixes: resolveProfilePathPrefixes(resolvedProfileSections),\n grantedFeatures,\n roles: Array.isArray(auth.roles) ? auth.roles : [],\n brand,\n currentOrganization,\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 buildProfileSections,\n buildSettingsSections,\n computeSettingsPathPrefixes,\n convertToSectionNavGroups,\n mergeSectionsWithDiscovered,\n type AdminNavItem,\n type SettingsSection,\n type SettingsSectionItem,\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 { 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 { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'\nimport {\n applySidebarPreference,\n findSidebarPreference,\n loadFirstRoleSidebarPreference,\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\n/**\n * Settings section weights, keyed by the untranslated group id each page declares as `pageGroupKey`.\n *\n * Mirrors `defaultGroupOrder` above: an id, never a rendered label, so the panel keeps its intended\n * order in every locale and an app-side module can place its own section deterministically (#4843).\n */\nexport const settingsSectionOrder: Record<string, number> = {\n 'settings.sections.system': 1,\n 'settings.sections.auth': 2,\n 'customer_accounts.settings.section': 3,\n 'settings.sections.dataDesigner': 4,\n 'settings.sections.moduleConfigs': 5,\n 'currencies.nav.group': 6,\n 'settings.sections.directory': 7,\n 'settings.sections.featureToggles': 8,\n}\n\n/**\n * Profile section weights, keyed by the untranslated group id, exactly like `settingsSectionOrder`.\n *\n * Only the built-in account section is ranked; a module contributing its own profile group sorts\n * after it on the shared 999 fallback rather than displacing the account pages.\n */\nexport const profileSectionOrder: Record<string, number> = {\n 'profile.sections.account': 1,\n}\n\n/**\n * Path prefixes that put the shell into profile mode: the static list plus every href the resolved\n * profile sections actually link to.\n *\n * `computeSettingsPathPrefixes` is deliberately not reused \u2014 it also registers each item's parent\n * directory, which is harmless for `/backend/settings/*` but would hand profile mode a whole\n * unrelated subtree if a module hosts its profile page outside `/backend/profile/`.\n */\nfunction resolveProfilePathPrefixes(sections: SettingsSection[]): string[] {\n const prefixes = new Set(profilePathPrefixes)\n const visitItems = (items: SettingsSectionItem[]) => {\n for (const item of items) {\n prefixes.add(item.href)\n if (item.children?.length) visitItems(item.children)\n }\n }\n for (const section of sections) visitItems(section.items)\n return Array.from(prefixes)\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\nconst NAV_ITEM_FALLBACK_WEIGHT = 10_000\n\n/**\n * The weight a nav entry sorts by, using the same `priority ?? order` precedence as `buildAdminNav`.\n *\n * `serializeNavItem` emits this resolved number rather than the raw declaration, including the\n * fallback, so a consumer that re-sorts by the field it receives lands on the order it was served in.\n * Emitting the raw `priority ?? order` would leave `order` undefined on any page declaring neither \u2014\n * and the `(a.order ?? 0) - (b.order ?? 0)` idiom this codebase uses elsewhere would then hoist those\n * pages to the top instead of leaving them last (#4845).\n */\nfunction resolveNavItemWeight(item: AdminNavItem): number {\n return item.priority ?? item.order ?? NAV_ITEM_FALLBACK_WEIGHT\n}\n\nfunction sortNavItemsByWeight(items: AdminNavItem[]): AdminNavItem[] {\n return [...items].sort((a, b) => {\n const weightDifference = resolveNavItemWeight(a) - resolveNavItemWeight(b)\n if (weightDifference !== 0) return weightDifference\n return a.title.localeCompare(b.title)\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 order: resolveNavItemWeight(item),\n children: item.children\n ? await Promise.all(sortNavItemsByWeight(item.children).map((child) => serializeNavItem(child)))\n : 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 'staff.time_tracking.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 : NAV_ITEM_FALLBACK_WEIGHT\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, Omit<NavGroupWithWeight, 'items'> & { entries: AdminNavItem[] }>()\n for (const entry of entries) {\n const weight = resolveNavItemWeight(entry)\n const existing = groupMap.get(entry.groupId)\n if (existing) {\n existing.entries.push(entry)\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 entries: [entry],\n weight,\n })\n }\n const groups: NavGroupWithWeight[] = []\n for (const { entries: groupItems, ...group } of groupMap.values()) {\n groups.push({\n ...group,\n items: await Promise.all(sortNavItemsByWeight(groupItems).map((entry) => serializeNavItem(entry))),\n })\n }\n return normalizeGroupWeights(groups)\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 getEffectiveFeatures: (userId: string, scope: { tenantId: string | null; organizationId: string | null }) => Promise<string[]>\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 let organizationScopeIsEmpty = false\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 organizationScopeIsEmpty = isExplicitlyEmptyOrganizationScope(scope)\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 grantedFeatures = allowNavigation\n ? await rbac.getEffectiveFeatures(auth.sub, {\n tenantId: scopedTenantId,\n organizationId: scopedOrganizationId,\n })\n : []\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 findSidebarPreference(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 // The profile sidebar mirrors the profile dropdown: the static baseline covers the `navHidden`\n // pages route discovery drops, and every other `pageContext: 'profile'` page is derived from the\n // manifest so a module adding one lands in both surfaces at once (#5594).\n const resolvedProfileSections = mergeSectionsWithDiscovered(\n profileSections,\n buildProfileSections(entries, profileSectionOrder),\n )\n\n const requestOrganizationId = request ? getSelectedOrganizationFromRequest(request) : null\n const fallbackOrganizationId = selectedOrganizationId ?? requestOrganizationId ?? auth.orgId ?? null\n const brandOrganizationId = organizationScopeIsEmpty\n ? null\n : 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 preserveAspectRatio: !!organization.logoPreserveAspectRatio,\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(\n convertToSectionNavGroups(resolvedProfileSections, translate),\n ),\n profilePathPrefixes: resolveProfilePathPrefixes(resolvedProfileSections),\n grantedFeatures,\n roles: Array.isArray(auth.roles) ? auth.roles : [],\n brand,\n currentOrganization,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAsKwC;AAzJxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,uCAAuC;AAChD,SAAS,qBAAqB,uBAAuB;AACrD,SAAS,8BAA8B;AACvC,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,SAAS,0CAA0C;AACnD;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,QAA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AmE;AACvE,MAAI,uBAAuB,gBAAgB;AACzC,QAAI;AACF,YAAM,eAAe,MAAM;AAAA,QACzB;AAAA,QACA;AAAA,QACA,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,YACzB,qBAAqB,CAAC,CAAC,aAAa;AAAA,UACtC;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;AAAA,MACrB,0BAA0B,yBAAyB,SAAS;AAAA,IAC9D;AAAA,IACA,qBAAqB,2BAA2B,uBAAuB;AAAA,IACvE;AAAA,IACA,OAAO,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,QAAQ,CAAC;AAAA,IACjD;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.11.1-develop.
|
|
3
|
+
"version": "0.11.1-develop.8521.1.204f384ec3",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -268,16 +268,16 @@
|
|
|
268
268
|
"zod": "^4.6.6"
|
|
269
269
|
},
|
|
270
270
|
"peerDependencies": {
|
|
271
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
272
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
273
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
271
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8521.1.204f384ec3",
|
|
272
|
+
"@open-mercato/shared": "0.11.1-develop.8521.1.204f384ec3",
|
|
273
|
+
"@open-mercato/ui": "0.11.1-develop.8521.1.204f384ec3",
|
|
274
274
|
"react": "^19.0.0",
|
|
275
275
|
"react-dom": "^19.0.0"
|
|
276
276
|
},
|
|
277
277
|
"devDependencies": {
|
|
278
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
279
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
280
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
278
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8521.1.204f384ec3",
|
|
279
|
+
"@open-mercato/shared": "0.11.1-develop.8521.1.204f384ec3",
|
|
280
|
+
"@open-mercato/ui": "0.11.1-develop.8521.1.204f384ec3",
|
|
281
281
|
"@testing-library/dom": "^10.4.1",
|
|
282
282
|
"@testing-library/jest-dom": "^7.0.1",
|
|
283
283
|
"@testing-library/react": "^16.3.3",
|
|
@@ -35,6 +35,7 @@ import { Organization } from '@open-mercato/core/modules/directory/data/entities
|
|
|
35
35
|
import { CustomEntity } from '@open-mercato/core/modules/entities/data/entities'
|
|
36
36
|
import { Role } from '@open-mercato/core/modules/auth/data/entities'
|
|
37
37
|
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
38
|
+
import { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'
|
|
38
39
|
import {
|
|
39
40
|
applySidebarPreference,
|
|
40
41
|
findSidebarPreference,
|
|
@@ -367,6 +368,7 @@ export async function resolveBackendChromePayload({
|
|
|
367
368
|
// resolved id cannot answer "which organization am I viewing".
|
|
368
369
|
let concretelySelectedOrganizationId: string | null = null
|
|
369
370
|
let allowNavigation = true
|
|
371
|
+
let organizationScopeIsEmpty = false
|
|
370
372
|
|
|
371
373
|
try {
|
|
372
374
|
const { organizationId, scope, allowedOrganizationIds } = await resolveFeatureCheckContext({
|
|
@@ -379,6 +381,7 @@ export async function resolveBackendChromePayload({
|
|
|
379
381
|
scopedOrganizationId = organizationId
|
|
380
382
|
scopedTenantId = scope.tenantId ?? auth.tenantId ?? null
|
|
381
383
|
concretelySelectedOrganizationId = scope.selectedId ?? null
|
|
384
|
+
organizationScopeIsEmpty = isExplicitlyEmptyOrganizationScope(scope)
|
|
382
385
|
if (Array.isArray(allowedOrganizationIds) && allowedOrganizationIds.length === 0) {
|
|
383
386
|
allowNavigation = false
|
|
384
387
|
}
|
|
@@ -505,8 +508,10 @@ export async function resolveBackendChromePayload({
|
|
|
505
508
|
|
|
506
509
|
const requestOrganizationId = request ? getSelectedOrganizationFromRequest(request) : null
|
|
507
510
|
const fallbackOrganizationId = selectedOrganizationId ?? requestOrganizationId ?? auth.orgId ?? null
|
|
508
|
-
const brandOrganizationId =
|
|
509
|
-
|
|
511
|
+
const brandOrganizationId = organizationScopeIsEmpty
|
|
512
|
+
? null
|
|
513
|
+
: scopedOrganizationId
|
|
514
|
+
?? (fallbackOrganizationId && !isAllOrganizationsSelection(fallbackOrganizationId) ? fallbackOrganizationId : null)
|
|
510
515
|
|
|
511
516
|
let brand: BackendChromePayload['brand'] = null
|
|
512
517
|
// Resolved here rather than left to callers. `brand` only populates when the organization has a
|