@open-mercato/core 0.10.1-develop.7847.1.7d83dc5794 → 0.10.1-develop.7857.1.259928eb85

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.
Files changed (64) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/api/file/[id]/route.js +6 -1
  3. package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
  4. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +6 -1
  5. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
  6. package/dist/modules/attachments/api/library/[id]/route.js +16 -1
  7. package/dist/modules/attachments/api/library/[id]/route.js.map +2 -2
  8. package/dist/modules/attachments/api/route.js +11 -3
  9. package/dist/modules/attachments/api/route.js.map +2 -2
  10. package/dist/modules/attachments/cli.js +2 -0
  11. package/dist/modules/attachments/cli.js.map +2 -2
  12. package/dist/modules/attachments/data/validators.js +11 -0
  13. package/dist/modules/attachments/data/validators.js.map +2 -2
  14. package/dist/modules/attachments/index.js +10 -0
  15. package/dist/modules/attachments/index.js.map +2 -2
  16. package/dist/modules/attachments/lib/access-query.js +5 -1
  17. package/dist/modules/attachments/lib/access-query.js.map +2 -2
  18. package/dist/modules/attachments/lib/createFromBuffer.js +2 -0
  19. package/dist/modules/attachments/lib/createFromBuffer.js.map +2 -2
  20. package/dist/modules/attachments/lib/drivers/driverFactory.js +54 -33
  21. package/dist/modules/attachments/lib/drivers/driverFactory.js.map +2 -2
  22. package/dist/modules/attachments/lib/drivers/index.js +11 -1
  23. package/dist/modules/attachments/lib/drivers/index.js.map +2 -2
  24. package/dist/modules/attachments/lib/drivers/storageValidation.js +85 -0
  25. package/dist/modules/attachments/lib/drivers/storageValidation.js.map +7 -0
  26. package/dist/modules/attachments/lib/scoped-upload-service.js +3 -1
  27. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  28. package/dist/modules/attachments/lib/storageErrors.js +22 -0
  29. package/dist/modules/attachments/lib/storageErrors.js.map +7 -0
  30. package/dist/modules/customers/api/companies/[id]/route.js +4 -9
  31. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  32. package/dist/modules/customers/api/people/[id]/route.js +4 -9
  33. package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
  34. package/dist/modules/customers/components/detail/TaskDialog.js +2 -0
  35. package/dist/modules/customers/components/detail/TaskDialog.js.map +2 -2
  36. package/dist/modules/customers/lib/todoCompatibility.js +23 -0
  37. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  38. package/jest.config.cjs +1 -1
  39. package/package.json +8 -8
  40. package/src/modules/attachments/api/file/[id]/route.ts +7 -1
  41. package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +7 -1
  42. package/src/modules/attachments/api/library/[id]/route.ts +14 -1
  43. package/src/modules/attachments/api/route.ts +11 -3
  44. package/src/modules/attachments/cli.ts +2 -0
  45. package/src/modules/attachments/data/validators.ts +11 -0
  46. package/src/modules/attachments/i18n/de.json +1 -0
  47. package/src/modules/attachments/i18n/en.json +1 -0
  48. package/src/modules/attachments/i18n/es.json +1 -0
  49. package/src/modules/attachments/i18n/ko.json +1 -0
  50. package/src/modules/attachments/i18n/pl.json +1 -0
  51. package/src/modules/attachments/index.ts +12 -0
  52. package/src/modules/attachments/lib/access-query.ts +5 -1
  53. package/src/modules/attachments/lib/createFromBuffer.ts +2 -0
  54. package/src/modules/attachments/lib/drivers/driverFactory.ts +79 -55
  55. package/src/modules/attachments/lib/drivers/index.ts +13 -0
  56. package/src/modules/attachments/lib/drivers/storageValidation.ts +114 -0
  57. package/src/modules/attachments/lib/scoped-upload-service.ts +3 -1
  58. package/src/modules/attachments/lib/storageErrors.ts +21 -0
  59. package/src/modules/customer_accounts/AGENTS.md +1 -1
  60. package/src/modules/customers/api/companies/[id]/route.ts +6 -13
  61. package/src/modules/customers/api/people/[id]/route.ts +6 -13
  62. package/src/modules/customers/components/detail/TaskDialog.tsx +2 -0
  63. package/src/modules/customers/lib/todoCompatibility.ts +28 -0
  64. package/src/modules/sales/AGENTS.md +3 -3
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/lib/todoCompatibility.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport { isValidEntityIdShape } from '@open-mercato/shared/lib/query/engine'\nimport { parseBooleanFromUnknown } from '@open-mercato/shared/lib/boolean'\nimport {\n CustomerInteraction,\n CustomerTodoLink,\n} from '../data/entities'\nimport type { InteractionRecord } from './interactionCompatibility'\nimport {\n CUSTOMER_INTERACTION_TASK_SOURCE,\n EXAMPLE_TODO_SOURCE,\n resolveExampleIntegrationHref,\n} from './interactionCompatibility'\nimport { hydrateCanonicalInteractions, loadCustomerSummaries } from './interactionReadModel'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nexport type CustomerTodoRow = {\n id: string\n todoId: string\n todoSource: string\n todoTitle: string | null\n todoIsDone: boolean | null\n todoPriority?: number | null\n todoSeverity?: string | null\n todoDescription?: string | null\n todoDueAt?: string | null\n todoTimezone?: string | null\n todoCustomValues?: Record<string, unknown> | null\n todoOrganizationId: string | null\n todoUpdatedAt?: string | null\n organizationId: string\n tenantId: string\n createdAt: string\n externalHref?: string | null\n _integrations?: Record<string, unknown>\n customer: {\n id: string | null\n displayName: string | null\n kind: string | null\n }\n}\n\nexport type LegacyTodoDetail = {\n title: string | null\n isDone: boolean | null\n priority: number | null\n severity: string | null\n description: string | null\n dueAt: string | null\n organizationId: string | null\n updatedAt: string | null\n customValues: Record<string, unknown> | null\n}\n\ntype CustomerSummary = {\n id: string | null\n displayName: string | null\n kind: string | null\n}\n\ntype CustomersAuthLike = {\n tenantId: string | null\n orgId?: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype CustomersContainerLike = {\n resolve: (name: string) => unknown\n}\n\nexport type CanonicalTodoListResult = {\n items: CustomerTodoRow[]\n bridgeIds: Set<string>\n total: number\n}\n\nfunction emptyCanonicalTodoList(): CanonicalTodoListResult {\n return { items: [], bridgeIds: new Set(), total: 0 }\n}\n\nfunction isCollapsedRestrictedOrganizationScope(\n organizationIds: string[] | null | undefined,\n isUnrestricted: boolean | undefined,\n): boolean {\n return isUnrestricted !== true && (!organizationIds || organizationIds.length === 0)\n}\n\nexport type ListTodosPagination = { page: number; pageSize: number }\n\nfunction resolveLegacyTodoSource(source: string | null | undefined): string {\n return typeof source === 'string' && source.trim().length > 0\n ? source\n : EXAMPLE_TODO_SOURCE\n}\n\nfunction extractTodoTitle(record: Record<string, unknown>): string | null {\n // `task_name` / `taskName` carry a workflow user task's name; the query engine\n // returns the raw column on the ORM path and the camelCase property on the\n // indexed one, so both spellings are read.\n const candidates = ['title', 'subject', 'name', 'task_name', 'taskName', 'summary', 'text', 'description']\n for (const key of candidates) {\n const value = record[key]\n if (typeof value === 'string' && value.trim().length > 0) {\n return value.trim()\n }\n }\n return null\n}\n\nfunction parseNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = Number(trimmed)\n if (!Number.isNaN(parsed)) return parsed\n }\n return null\n}\n\nfunction parseDateValue(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString()\n }\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = new Date(trimmed)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction readCustomField(record: Record<string, unknown>, key: string): unknown {\n const custom = record.custom ?? record.customFields ?? record.cf\n if (custom && typeof custom === 'object') {\n const bucket = custom as Record<string, unknown>\n if (key in bucket) return bucket[key]\n }\n return undefined\n}\n\nexport function normalizeTodoSearch(value: string | undefined): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim().toLowerCase()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function sortTodoRows(rows: CustomerTodoRow[]): CustomerTodoRow[] {\n return [...rows].sort((left, right) => {\n const leftTime = new Date(left.createdAt).getTime()\n const rightTime = new Date(right.createdAt).getTime()\n if (leftTime === rightTime) {\n return right.id.localeCompare(left.id)\n }\n return rightTime - leftTime\n })\n}\n\nexport function filterTodoRows(rows: CustomerTodoRow[], search: string | null): CustomerTodoRow[] {\n if (!search) return rows\n return rows.filter((row) => {\n const haystack = [\n row.customer.displayName,\n row.todoTitle,\n row.todoDescription,\n ]\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .join(' ')\n .toLowerCase()\n return haystack.includes(search)\n })\n}\n\nexport function paginateTodoRows(\n rows: CustomerTodoRow[],\n page: number,\n pageSize: number,\n exportAll: boolean,\n): { items: CustomerTodoRow[]; total: number; page: number; pageSize: number; totalPages: number } {\n const total = rows.length\n if (exportAll) {\n return {\n items: rows,\n total,\n page: 1,\n pageSize: total,\n totalPages: 1,\n }\n }\n const start = (page - 1) * pageSize\n return {\n items: rows.slice(start, start + pageSize),\n total,\n page,\n pageSize,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n }\n}\n\nexport async function resolveLegacyTodoDetails(\n queryEngine: QueryEngine,\n links: CustomerTodoLink[],\n tenantId: string | null,\n organizationIds: Array<string | null>,\n): Promise<Map<string, LegacyTodoDetail>> {\n const details = new Map<string, LegacyTodoDetail>()\n if (!links.length || !tenantId) return details\n\n const scopedOrganizationIds = organizationIds.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n )\n\n const idsBySource = new Map<string, Set<string>>()\n for (const link of links) {\n const source = resolveLegacyTodoSource(link.todoSource)\n const id =\n typeof link.todoId === 'string' && link.todoId.trim().length > 0\n ? link.todoId\n : String(link.todoId ?? '')\n if (!id) continue\n if (!idsBySource.has(source)) idsBySource.set(source, new Set<string>())\n idsBySource.get(source)!.add(id)\n }\n\n for (const [source, idSet] of idsBySource.entries()) {\n const ids = Array.from(idSet)\n if (!ids.length) continue\n if (!isValidEntityIdShape(source)) {\n // A legacy/malformed `todoSource` (e.g. a bare module name written before\n // the value was required to be a `module:entity` id) does not resolve to\n // any real table. Querying it anyway surfaces a raw DB error (\"relation\n // ... does not exist\") as a dashboard-wide schema-mismatch banner instead\n // of just leaving that row's details unresolved.\n logger.warn('Skipping malformed legacy todo source', { component: 'todoCompatibility', source })\n continue\n }\n try {\n const result = await queryEngine.query<Record<string, unknown>>(source as EntityId, {\n tenantId,\n organizationIds: scopedOrganizationIds.length > 0 ? scopedOrganizationIds : undefined,\n filters: { id: { $in: ids } },\n includeCustomFields: ['priority', 'due_at', 'severity', 'description'],\n page: { page: 1, pageSize: Math.max(ids.length, 1) },\n })\n\n for (const item of result.items ?? []) {\n if (!item || typeof item !== 'object') continue\n const record = item as Record<string, unknown>\n const rawId =\n typeof record.id === 'string' && record.id.trim().length > 0\n ? record.id\n : String(record.id ?? '')\n if (!rawId) continue\n\n const isDone = (() => {\n const direct = parseBooleanFromUnknown(record.is_done)\n if (direct !== null) return direct\n const custom = parseBooleanFromUnknown(readCustomField(record, 'is_done'))\n if (custom !== null) return custom\n const generic = parseBooleanFromUnknown(record.isDone)\n if (generic !== null) return generic\n return parseBooleanFromUnknown(readCustomField(record, 'isDone'))\n })()\n\n const priority = (() => {\n const candidates = [\n record['cf:priority'],\n record['cf_priority'],\n record.priority,\n readCustomField(record, 'priority'),\n ]\n for (const candidate of candidates) {\n const parsed = parseNumber(candidate)\n if (parsed !== null) return parsed\n }\n return null\n })()\n\n const severity = (() => {\n const candidates = [\n record['cf:severity'],\n record['cf_severity'],\n record.severity,\n readCustomField(record, 'severity'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const description = (() => {\n const candidates = [\n record.description,\n record['cf:description'],\n record['cf_description'],\n readCustomField(record, 'description'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const dueAt = (() => {\n const candidates = [\n record.due_at,\n record.dueAt,\n record['cf:due_at'],\n record['cf_due_at'],\n readCustomField(record, 'due_at'),\n readCustomField(record, 'dueAt'),\n ]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n const organizationId = (() => {\n const candidates = [\n record.organization_id,\n record.organizationId,\n record['cf:organization_id'],\n record['cf_organization_id'],\n readCustomField(record, 'organization_id'),\n readCustomField(record, 'organizationId'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const customValues: Record<string, unknown> = {}\n const assignCustomValue = (key: string, value: unknown) => {\n const trimmedKey = key.trim()\n if (!trimmedKey.length) return\n customValues[trimmedKey] = value === undefined ? null : value\n }\n for (const [rawKey, rawValue] of Object.entries(record)) {\n if (rawKey.startsWith('cf:')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n } else if (rawKey.startsWith('cf_')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n }\n }\n const nestedCustom = record.custom ?? record.customFields ?? record.cf\n if (nestedCustom && typeof nestedCustom === 'object') {\n for (const [key, value] of Object.entries(nestedCustom as Record<string, unknown>)) {\n assignCustomValue(key, value)\n }\n }\n\n const updatedAt = (() => {\n const candidates = [record.updated_at, record.updatedAt]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n details.set(`${source}:${rawId}`, {\n title: extractTodoTitle(record),\n isDone,\n priority,\n severity,\n description,\n dueAt,\n organizationId,\n updatedAt,\n customValues: Object.keys(customValues).length > 0 ? customValues : null,\n })\n }\n } catch (err) {\n logger.warn('Failed to resolve todo details', { component: 'todoCompatibility', source, err })\n continue\n }\n }\n\n return details\n}\n\nexport async function listLegacyTodoRows(\n em: EntityManager,\n queryEngine: QueryEngine,\n tenantId: string,\n organizationIds: string[] | null,\n entityId: string | undefined,\n options?: { limit?: number | null; isUnrestricted?: boolean },\n): Promise<CustomerTodoRow[]> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return []\n }\n const where: Record<string, unknown> = { tenantId }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (entityId) {\n where.entity = entityId\n }\n\n const findOptions: Record<string, unknown> = {\n populate: ['entity'],\n orderBy: { createdAt: 'desc' },\n }\n if (typeof options?.limit === 'number' && Number.isFinite(options.limit) && options.limit > 0) {\n findOptions.limit = options.limit\n }\n\n const links = await em.find(CustomerTodoLink, where, findOptions as any)\n const details = await resolveLegacyTodoDetails(\n queryEngine,\n links,\n tenantId,\n organizationIds ?? [],\n )\n\n return links.map((link) => {\n const source = resolveLegacyTodoSource(link.todoSource)\n return mapLegacyTodoLinkToRow(\n link,\n details.get(`${source}:${link.todoId}`) ?? null,\n )\n })\n}\n\nexport async function listCanonicalTodoRows(\n em: EntityManager,\n container: CustomersContainerLike,\n auth: CustomersAuthLike,\n selectedOrganizationId: string | null,\n organizationIds: string[] | null,\n options?: {\n entityId?: string\n includeDeleted?: boolean\n source?: string | string[] | null\n pagination?: ListTodosPagination | null\n searchText?: string | null\n limit?: number | null\n isUnrestricted?: boolean\n },\n): Promise<CanonicalTodoListResult> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return emptyCanonicalTodoList()\n }\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n interactionType: 'task',\n }\n if (!options?.includeDeleted) {\n where.deletedAt = null\n }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (options?.entityId) {\n where.entity = options.entityId\n }\n if (options?.source) {\n where.source = Array.isArray(options.source) ? { $in: options.source } : options.source\n }\n const trimmedSearch =\n typeof options?.searchText === 'string' ? options.searchText.trim() : ''\n if (trimmedSearch.length > 0) {\n const pattern = `%${trimmedSearch}%`\n where.$or = [\n { title: { $ilike: pattern } },\n { body: { $ilike: pattern } },\n ]\n }\n\n const findOptions: Record<string, unknown> = {\n orderBy: { createdAt: 'desc' },\n }\n const pagination = options?.pagination ?? null\n if (pagination) {\n findOptions.offset = Math.max(0, (pagination.page - 1) * pagination.pageSize)\n findOptions.limit = pagination.pageSize\n } else if (\n typeof options?.limit === 'number' &&\n Number.isFinite(options.limit) &&\n options.limit > 0\n ) {\n findOptions.limit = options.limit\n }\n\n let interactions: CustomerInteraction[]\n let total: number\n if (pagination) {\n const [rows, count] = await em.findAndCount(CustomerInteraction, where, findOptions as any)\n interactions = rows\n total = count\n } else {\n interactions = await em.find(CustomerInteraction, where, findOptions as any)\n total = interactions.filter((interaction) => !interaction.deletedAt).length\n }\n const activeInteractions = interactions.filter((interaction) => !interaction.deletedAt)\n const groups = new Map<string, CustomerInteraction[]>()\n\n for (const interaction of activeInteractions) {\n const organizationId =\n typeof interaction.organizationId === 'string' && interaction.organizationId.trim().length > 0\n ? interaction.organizationId\n : selectedOrganizationId ?? ''\n const bucket = groups.get(organizationId)\n if (bucket) {\n bucket.push(interaction)\n } else {\n groups.set(organizationId, [interaction])\n }\n }\n\n const rowByInteractionId = new Map<string, CustomerTodoRow>()\n\n for (const [groupOrganizationId, groupedInteractions] of groups.entries()) {\n const scopedOrganizationId = groupOrganizationId.length > 0 ? groupOrganizationId : null\n const hydrated = await hydrateCanonicalInteractions({\n em,\n container,\n auth: {\n ...auth,\n orgId: auth.orgId ?? null,\n },\n selectedOrganizationId: scopedOrganizationId,\n interactions: groupedInteractions,\n })\n const customerIds = Array.from(\n new Set(\n hydrated\n .map((interaction) => interaction.entityId ?? null)\n .filter((value): value is string => !!value),\n ),\n )\n const customerSummaries = await loadCustomerSummaries(\n em,\n customerIds,\n auth.tenantId,\n scopedOrganizationId,\n )\n\n for (const interaction of hydrated) {\n rowByInteractionId.set(\n interaction.id,\n mapInteractionRecordToTodoRow(\n interaction,\n interaction.entityId ? customerSummaries.get(interaction.entityId) ?? null : null,\n ),\n )\n }\n }\n\n return {\n items: activeInteractions\n .map((interaction) => rowByInteractionId.get(interaction.id) ?? null)\n .filter((row): row is CustomerTodoRow => !!row),\n bridgeIds: new Set(interactions.map((interaction) => interaction.id)),\n total,\n }\n}\n\nexport function mapLegacyTodoLinkToRow(\n link: CustomerTodoLink,\n detail: LegacyTodoDetail | null,\n customerOverride?: CustomerSummary | null,\n): CustomerTodoRow {\n const entity = customerOverride ?? {\n id: typeof link.entity === 'string' ? null : link.entity.id,\n displayName: typeof link.entity === 'string' ? null : link.entity.displayName ?? null,\n kind: typeof link.entity === 'string' ? null : link.entity.kind ?? null,\n }\n\n return {\n id: link.id,\n todoId: link.todoId,\n todoSource: resolveLegacyTodoSource(link.todoSource),\n todoTitle: detail?.title ?? null,\n todoIsDone: detail?.isDone ?? null,\n todoPriority: detail?.priority ?? null,\n todoSeverity: detail?.severity ?? null,\n todoDescription: detail?.description ?? null,\n todoDueAt: detail?.dueAt ?? null,\n todoCustomValues: detail?.customValues ?? null,\n todoOrganizationId: detail?.organizationId ?? link.organizationId ?? null,\n todoUpdatedAt: detail?.updatedAt ?? null,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n createdAt: link.createdAt.toISOString(),\n _integrations: undefined,\n customer: entity,\n }\n}\n\nexport function mapInteractionRecordToTodoRow(\n interaction: InteractionRecord,\n customer: CustomerSummary | null,\n options?: { rowId?: string | null; todoSource?: string | null },\n): CustomerTodoRow {\n const customValues: Record<string, unknown> = { ...(interaction.customValues ?? {}) }\n if (interaction.priority !== undefined && customValues.priority === undefined) {\n customValues.priority = interaction.priority ?? null\n }\n if (interaction.body !== undefined && customValues.description === undefined) {\n customValues.description = interaction.body ?? null\n }\n if (interaction.scheduledAt !== undefined && customValues.due_at === undefined) {\n customValues.due_at = interaction.scheduledAt ?? null\n }\n\n return {\n id:\n typeof options?.rowId === 'string' && options.rowId.trim().length > 0\n ? options.rowId\n : interaction.id,\n todoId: interaction.id,\n todoSource:\n typeof options?.todoSource === 'string' && options.todoSource.trim().length > 0\n ? options.todoSource\n : CUSTOMER_INTERACTION_TASK_SOURCE,\n todoTitle: interaction.title ?? null,\n todoIsDone: interaction.status === 'done',\n todoPriority: interaction.priority ?? null,\n todoSeverity:\n typeof customValues.severity === 'string' && customValues.severity.trim().length > 0\n ? customValues.severity.trim()\n : null,\n todoDescription: interaction.body ?? null,\n todoDueAt: interaction.scheduledAt ?? null,\n todoTimezone: interaction.timezone ?? null,\n todoCustomValues: Object.keys(customValues).length > 0 ? customValues : null,\n todoOrganizationId: interaction.organizationId ?? null,\n todoUpdatedAt: interaction.updatedAt ?? null,\n organizationId: interaction.organizationId ?? '',\n tenantId: interaction.tenantId ?? '',\n createdAt: interaction.createdAt,\n externalHref: resolveExampleIntegrationHref(interaction),\n _integrations: interaction._integrations ?? undefined,\n customer: customer ?? {\n id: interaction.entityId ?? null,\n displayName: null,\n kind: null,\n },\n }\n}\n"],
5
- "mappings": "AAGA,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,6BAA6B;AACpE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAgEvC,SAAS,yBAAkD;AACzD,SAAO,EAAE,OAAO,CAAC,GAAG,WAAW,oBAAI,IAAI,GAAG,OAAO,EAAE;AACrD;AAEA,SAAS,uCACP,iBACA,gBACS;AACT,SAAO,mBAAmB,SAAS,CAAC,mBAAmB,gBAAgB,WAAW;AACpF;AAIA,SAAS,wBAAwB,QAA2C;AAC1E,SAAO,OAAO,WAAW,YAAY,OAAO,KAAK,EAAE,SAAS,IACxD,SACA;AACN;AAEA,SAAS,iBAAiB,QAAgD;AAIxE,QAAM,aAAa,CAAC,SA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AAc,YAAY,YAAY;AAAA,IACtC,kBAAkB,OAAO,KAAK,YAAY,EAAE,SAAS,IAAI,eAAe;AAAA,IACxE,oBAAoB,YAAY,kBAAkB;AAAA,IAClD,eAAe,YAAY,aAAa;AAAA,IACxC,gBAAgB,YAAY,kBAAkB;AAAA,IAC9C,UAAU,YAAY,YAAY;AAAA,IAClC,WAAW,YAAY;AAAA,IACvB,cAAc,8BAA8B,WAAW;AAAA,IACvD,eAAe,YAAY,iBAAiB;AAAA,IAC5C,UAAU,YAAY;AAAA,MACpB,IAAI,YAAY,YAAY;AAAA,MAC5B,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport { isValidEntityIdShape } from '@open-mercato/shared/lib/query/engine'\nimport { parseBooleanFromUnknown } from '@open-mercato/shared/lib/boolean'\nimport {\n CustomerInteraction,\n CustomerTodoLink,\n} from '../data/entities'\nimport type { InteractionRecord } from './interactionCompatibility'\nimport {\n CUSTOMER_INTERACTION_TASK_SOURCE,\n CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n EXAMPLE_TODO_SOURCE,\n resolveExampleIntegrationHref,\n} from './interactionCompatibility'\nimport { hydrateCanonicalInteractions, loadCustomerSummaries } from './interactionReadModel'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nexport async function countCustomerTodos(\n em: EntityManager,\n scope: { entityId: string; tenantId: string; organizationId: string },\n unified: boolean,\n): Promise<number> {\n const entityScope = {\n entity: scope.entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n }\n if (unified) {\n return em.count(CustomerInteraction, { ...entityScope, interactionType: 'task', deletedAt: null })\n }\n\n const adapterScope = {\n ...entityScope,\n interactionType: 'task',\n source: CUSTOMER_INTERACTION_TODO_ADAPTER_SOURCE,\n }\n const adapterIds = em.createQueryBuilder(CustomerInteraction).select('id').where(adapterScope)\n const [legacyCount, adapterCount] = await Promise.all([\n em.count(CustomerTodoLink, { ...entityScope, todoId: { $nin: adapterIds } }),\n em.count(CustomerInteraction, { ...adapterScope, deletedAt: null }),\n ])\n return legacyCount + adapterCount\n}\n\nexport type CustomerTodoRow = {\n id: string\n todoId: string\n todoSource: string\n todoTitle: string | null\n todoIsDone: boolean | null\n todoPriority?: number | null\n todoSeverity?: string | null\n todoDescription?: string | null\n todoDueAt?: string | null\n todoTimezone?: string | null\n todoCustomValues?: Record<string, unknown> | null\n todoOrganizationId: string | null\n todoUpdatedAt?: string | null\n organizationId: string\n tenantId: string\n createdAt: string\n externalHref?: string | null\n _integrations?: Record<string, unknown>\n customer: {\n id: string | null\n displayName: string | null\n kind: string | null\n }\n}\n\nexport type LegacyTodoDetail = {\n title: string | null\n isDone: boolean | null\n priority: number | null\n severity: string | null\n description: string | null\n dueAt: string | null\n organizationId: string | null\n updatedAt: string | null\n customValues: Record<string, unknown> | null\n}\n\ntype CustomerSummary = {\n id: string | null\n displayName: string | null\n kind: string | null\n}\n\ntype CustomersAuthLike = {\n tenantId: string | null\n orgId?: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype CustomersContainerLike = {\n resolve: (name: string) => unknown\n}\n\nexport type CanonicalTodoListResult = {\n items: CustomerTodoRow[]\n bridgeIds: Set<string>\n total: number\n}\n\nfunction emptyCanonicalTodoList(): CanonicalTodoListResult {\n return { items: [], bridgeIds: new Set(), total: 0 }\n}\n\nfunction isCollapsedRestrictedOrganizationScope(\n organizationIds: string[] | null | undefined,\n isUnrestricted: boolean | undefined,\n): boolean {\n return isUnrestricted !== true && (!organizationIds || organizationIds.length === 0)\n}\n\nexport type ListTodosPagination = { page: number; pageSize: number }\n\nfunction resolveLegacyTodoSource(source: string | null | undefined): string {\n return typeof source === 'string' && source.trim().length > 0\n ? source\n : EXAMPLE_TODO_SOURCE\n}\n\nfunction extractTodoTitle(record: Record<string, unknown>): string | null {\n // `task_name` / `taskName` carry a workflow user task's name; the query engine\n // returns the raw column on the ORM path and the camelCase property on the\n // indexed one, so both spellings are read.\n const candidates = ['title', 'subject', 'name', 'task_name', 'taskName', 'summary', 'text', 'description']\n for (const key of candidates) {\n const value = record[key]\n if (typeof value === 'string' && value.trim().length > 0) {\n return value.trim()\n }\n }\n return null\n}\n\nfunction parseNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = Number(trimmed)\n if (!Number.isNaN(parsed)) return parsed\n }\n return null\n}\n\nfunction parseDateValue(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString()\n }\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = new Date(trimmed)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction readCustomField(record: Record<string, unknown>, key: string): unknown {\n const custom = record.custom ?? record.customFields ?? record.cf\n if (custom && typeof custom === 'object') {\n const bucket = custom as Record<string, unknown>\n if (key in bucket) return bucket[key]\n }\n return undefined\n}\n\nexport function normalizeTodoSearch(value: string | undefined): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim().toLowerCase()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function sortTodoRows(rows: CustomerTodoRow[]): CustomerTodoRow[] {\n return [...rows].sort((left, right) => {\n const leftTime = new Date(left.createdAt).getTime()\n const rightTime = new Date(right.createdAt).getTime()\n if (leftTime === rightTime) {\n return right.id.localeCompare(left.id)\n }\n return rightTime - leftTime\n })\n}\n\nexport function filterTodoRows(rows: CustomerTodoRow[], search: string | null): CustomerTodoRow[] {\n if (!search) return rows\n return rows.filter((row) => {\n const haystack = [\n row.customer.displayName,\n row.todoTitle,\n row.todoDescription,\n ]\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .join(' ')\n .toLowerCase()\n return haystack.includes(search)\n })\n}\n\nexport function paginateTodoRows(\n rows: CustomerTodoRow[],\n page: number,\n pageSize: number,\n exportAll: boolean,\n): { items: CustomerTodoRow[]; total: number; page: number; pageSize: number; totalPages: number } {\n const total = rows.length\n if (exportAll) {\n return {\n items: rows,\n total,\n page: 1,\n pageSize: total,\n totalPages: 1,\n }\n }\n const start = (page - 1) * pageSize\n return {\n items: rows.slice(start, start + pageSize),\n total,\n page,\n pageSize,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n }\n}\n\nexport async function resolveLegacyTodoDetails(\n queryEngine: QueryEngine,\n links: CustomerTodoLink[],\n tenantId: string | null,\n organizationIds: Array<string | null>,\n): Promise<Map<string, LegacyTodoDetail>> {\n const details = new Map<string, LegacyTodoDetail>()\n if (!links.length || !tenantId) return details\n\n const scopedOrganizationIds = organizationIds.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n )\n\n const idsBySource = new Map<string, Set<string>>()\n for (const link of links) {\n const source = resolveLegacyTodoSource(link.todoSource)\n const id =\n typeof link.todoId === 'string' && link.todoId.trim().length > 0\n ? link.todoId\n : String(link.todoId ?? '')\n if (!id) continue\n if (!idsBySource.has(source)) idsBySource.set(source, new Set<string>())\n idsBySource.get(source)!.add(id)\n }\n\n for (const [source, idSet] of idsBySource.entries()) {\n const ids = Array.from(idSet)\n if (!ids.length) continue\n if (!isValidEntityIdShape(source)) {\n // A legacy/malformed `todoSource` (e.g. a bare module name written before\n // the value was required to be a `module:entity` id) does not resolve to\n // any real table. Querying it anyway surfaces a raw DB error (\"relation\n // ... does not exist\") as a dashboard-wide schema-mismatch banner instead\n // of just leaving that row's details unresolved.\n logger.warn('Skipping malformed legacy todo source', { component: 'todoCompatibility', source })\n continue\n }\n try {\n const result = await queryEngine.query<Record<string, unknown>>(source as EntityId, {\n tenantId,\n organizationIds: scopedOrganizationIds.length > 0 ? scopedOrganizationIds : undefined,\n filters: { id: { $in: ids } },\n includeCustomFields: ['priority', 'due_at', 'severity', 'description'],\n page: { page: 1, pageSize: Math.max(ids.length, 1) },\n })\n\n for (const item of result.items ?? []) {\n if (!item || typeof item !== 'object') continue\n const record = item as Record<string, unknown>\n const rawId =\n typeof record.id === 'string' && record.id.trim().length > 0\n ? record.id\n : String(record.id ?? '')\n if (!rawId) continue\n\n const isDone = (() => {\n const direct = parseBooleanFromUnknown(record.is_done)\n if (direct !== null) return direct\n const custom = parseBooleanFromUnknown(readCustomField(record, 'is_done'))\n if (custom !== null) return custom\n const generic = parseBooleanFromUnknown(record.isDone)\n if (generic !== null) return generic\n return parseBooleanFromUnknown(readCustomField(record, 'isDone'))\n })()\n\n const priority = (() => {\n const candidates = [\n record['cf:priority'],\n record['cf_priority'],\n record.priority,\n readCustomField(record, 'priority'),\n ]\n for (const candidate of candidates) {\n const parsed = parseNumber(candidate)\n if (parsed !== null) return parsed\n }\n return null\n })()\n\n const severity = (() => {\n const candidates = [\n record['cf:severity'],\n record['cf_severity'],\n record.severity,\n readCustomField(record, 'severity'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const description = (() => {\n const candidates = [\n record.description,\n record['cf:description'],\n record['cf_description'],\n readCustomField(record, 'description'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const dueAt = (() => {\n const candidates = [\n record.due_at,\n record.dueAt,\n record['cf:due_at'],\n record['cf_due_at'],\n readCustomField(record, 'due_at'),\n readCustomField(record, 'dueAt'),\n ]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n const organizationId = (() => {\n const candidates = [\n record.organization_id,\n record.organizationId,\n record['cf:organization_id'],\n record['cf_organization_id'],\n readCustomField(record, 'organization_id'),\n readCustomField(record, 'organizationId'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const customValues: Record<string, unknown> = {}\n const assignCustomValue = (key: string, value: unknown) => {\n const trimmedKey = key.trim()\n if (!trimmedKey.length) return\n customValues[trimmedKey] = value === undefined ? null : value\n }\n for (const [rawKey, rawValue] of Object.entries(record)) {\n if (rawKey.startsWith('cf:')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n } else if (rawKey.startsWith('cf_')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n }\n }\n const nestedCustom = record.custom ?? record.customFields ?? record.cf\n if (nestedCustom && typeof nestedCustom === 'object') {\n for (const [key, value] of Object.entries(nestedCustom as Record<string, unknown>)) {\n assignCustomValue(key, value)\n }\n }\n\n const updatedAt = (() => {\n const candidates = [record.updated_at, record.updatedAt]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n details.set(`${source}:${rawId}`, {\n title: extractTodoTitle(record),\n isDone,\n priority,\n severity,\n description,\n dueAt,\n organizationId,\n updatedAt,\n customValues: Object.keys(customValues).length > 0 ? customValues : null,\n })\n }\n } catch (err) {\n logger.warn('Failed to resolve todo details', { component: 'todoCompatibility', source, err })\n continue\n }\n }\n\n return details\n}\n\nexport async function listLegacyTodoRows(\n em: EntityManager,\n queryEngine: QueryEngine,\n tenantId: string,\n organizationIds: string[] | null,\n entityId: string | undefined,\n options?: { limit?: number | null; isUnrestricted?: boolean },\n): Promise<CustomerTodoRow[]> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return []\n }\n const where: Record<string, unknown> = { tenantId }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (entityId) {\n where.entity = entityId\n }\n\n const findOptions: Record<string, unknown> = {\n populate: ['entity'],\n orderBy: { createdAt: 'desc' },\n }\n if (typeof options?.limit === 'number' && Number.isFinite(options.limit) && options.limit > 0) {\n findOptions.limit = options.limit\n }\n\n const links = await em.find(CustomerTodoLink, where, findOptions as any)\n const details = await resolveLegacyTodoDetails(\n queryEngine,\n links,\n tenantId,\n organizationIds ?? [],\n )\n\n return links.map((link) => {\n const source = resolveLegacyTodoSource(link.todoSource)\n return mapLegacyTodoLinkToRow(\n link,\n details.get(`${source}:${link.todoId}`) ?? null,\n )\n })\n}\n\nexport async function listCanonicalTodoRows(\n em: EntityManager,\n container: CustomersContainerLike,\n auth: CustomersAuthLike,\n selectedOrganizationId: string | null,\n organizationIds: string[] | null,\n options?: {\n entityId?: string\n includeDeleted?: boolean\n source?: string | string[] | null\n pagination?: ListTodosPagination | null\n searchText?: string | null\n limit?: number | null\n isUnrestricted?: boolean\n },\n): Promise<CanonicalTodoListResult> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return emptyCanonicalTodoList()\n }\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n interactionType: 'task',\n }\n if (!options?.includeDeleted) {\n where.deletedAt = null\n }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (options?.entityId) {\n where.entity = options.entityId\n }\n if (options?.source) {\n where.source = Array.isArray(options.source) ? { $in: options.source } : options.source\n }\n const trimmedSearch =\n typeof options?.searchText === 'string' ? options.searchText.trim() : ''\n if (trimmedSearch.length > 0) {\n const pattern = `%${trimmedSearch}%`\n where.$or = [\n { title: { $ilike: pattern } },\n { body: { $ilike: pattern } },\n ]\n }\n\n const findOptions: Record<string, unknown> = {\n orderBy: { createdAt: 'desc' },\n }\n const pagination = options?.pagination ?? null\n if (pagination) {\n findOptions.offset = Math.max(0, (pagination.page - 1) * pagination.pageSize)\n findOptions.limit = pagination.pageSize\n } else if (\n typeof options?.limit === 'number' &&\n Number.isFinite(options.limit) &&\n options.limit > 0\n ) {\n findOptions.limit = options.limit\n }\n\n let interactions: CustomerInteraction[]\n let total: number\n if (pagination) {\n const [rows, count] = await em.findAndCount(CustomerInteraction, where, findOptions as any)\n interactions = rows\n total = count\n } else {\n interactions = await em.find(CustomerInteraction, where, findOptions as any)\n total = interactions.filter((interaction) => !interaction.deletedAt).length\n }\n const activeInteractions = interactions.filter((interaction) => !interaction.deletedAt)\n const groups = new Map<string, CustomerInteraction[]>()\n\n for (const interaction of activeInteractions) {\n const organizationId =\n typeof interaction.organizationId === 'string' && interaction.organizationId.trim().length > 0\n ? interaction.organizationId\n : selectedOrganizationId ?? ''\n const bucket = groups.get(organizationId)\n if (bucket) {\n bucket.push(interaction)\n } else {\n groups.set(organizationId, [interaction])\n }\n }\n\n const rowByInteractionId = new Map<string, CustomerTodoRow>()\n\n for (const [groupOrganizationId, groupedInteractions] of groups.entries()) {\n const scopedOrganizationId = groupOrganizationId.length > 0 ? groupOrganizationId : null\n const hydrated = await hydrateCanonicalInteractions({\n em,\n container,\n auth: {\n ...auth,\n orgId: auth.orgId ?? null,\n },\n selectedOrganizationId: scopedOrganizationId,\n interactions: groupedInteractions,\n })\n const customerIds = Array.from(\n new Set(\n hydrated\n .map((interaction) => interaction.entityId ?? null)\n .filter((value): value is string => !!value),\n ),\n )\n const customerSummaries = await loadCustomerSummaries(\n em,\n customerIds,\n auth.tenantId,\n scopedOrganizationId,\n )\n\n for (const interaction of hydrated) {\n rowByInteractionId.set(\n interaction.id,\n mapInteractionRecordToTodoRow(\n interaction,\n interaction.entityId ? customerSummaries.get(interaction.entityId) ?? null : null,\n ),\n )\n }\n }\n\n return {\n items: activeInteractions\n .map((interaction) => rowByInteractionId.get(interaction.id) ?? null)\n .filter((row): row is CustomerTodoRow => !!row),\n bridgeIds: new Set(interactions.map((interaction) => interaction.id)),\n total,\n }\n}\n\nexport function mapLegacyTodoLinkToRow(\n link: CustomerTodoLink,\n detail: LegacyTodoDetail | null,\n customerOverride?: CustomerSummary | null,\n): CustomerTodoRow {\n const entity = customerOverride ?? {\n id: typeof link.entity === 'string' ? null : link.entity.id,\n displayName: typeof link.entity === 'string' ? null : link.entity.displayName ?? null,\n kind: typeof link.entity === 'string' ? null : link.entity.kind ?? null,\n }\n\n return {\n id: link.id,\n todoId: link.todoId,\n todoSource: resolveLegacyTodoSource(link.todoSource),\n todoTitle: detail?.title ?? null,\n todoIsDone: detail?.isDone ?? null,\n todoPriority: detail?.priority ?? null,\n todoSeverity: detail?.severity ?? null,\n todoDescription: detail?.description ?? null,\n todoDueAt: detail?.dueAt ?? null,\n todoCustomValues: detail?.customValues ?? null,\n todoOrganizationId: detail?.organizationId ?? link.organizationId ?? null,\n todoUpdatedAt: detail?.updatedAt ?? null,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n createdAt: link.createdAt.toISOString(),\n _integrations: undefined,\n customer: entity,\n }\n}\n\nexport function mapInteractionRecordToTodoRow(\n interaction: InteractionRecord,\n customer: CustomerSummary | null,\n options?: { rowId?: string | null; todoSource?: string | null },\n): CustomerTodoRow {\n const customValues: Record<string, unknown> = { ...(interaction.customValues ?? {}) }\n if (interaction.priority !== undefined && customValues.priority === undefined) {\n customValues.priority = interaction.priority ?? null\n }\n if (interaction.body !== undefined && customValues.description === undefined) {\n customValues.description = interaction.body ?? null\n }\n if (interaction.scheduledAt !== undefined && customValues.due_at === undefined) {\n customValues.due_at = interaction.scheduledAt ?? null\n }\n\n return {\n id:\n typeof options?.rowId === 'string' && options.rowId.trim().length > 0\n ? options.rowId\n : interaction.id,\n todoId: interaction.id,\n todoSource:\n typeof options?.todoSource === 'string' && options.todoSource.trim().length > 0\n ? options.todoSource\n : CUSTOMER_INTERACTION_TASK_SOURCE,\n todoTitle: interaction.title ?? null,\n todoIsDone: interaction.status === 'done',\n todoPriority: interaction.priority ?? null,\n todoSeverity:\n typeof customValues.severity === 'string' && customValues.severity.trim().length > 0\n ? customValues.severity.trim()\n : null,\n todoDescription: interaction.body ?? null,\n todoDueAt: interaction.scheduledAt ?? null,\n todoTimezone: interaction.timezone ?? null,\n todoCustomValues: Object.keys(customValues).length > 0 ? customValues : null,\n todoOrganizationId: interaction.organizationId ?? null,\n todoUpdatedAt: interaction.updatedAt ?? null,\n organizationId: interaction.organizationId ?? '',\n tenantId: interaction.tenantId ?? '',\n createdAt: interaction.createdAt,\n externalHref: resolveExampleIntegrationHref(interaction),\n _integrations: interaction._integrations ?? undefined,\n customer: customer ?? {\n id: interaction.entityId ?? null,\n displayName: null,\n kind: null,\n },\n }\n}\n"],
5
+ "mappings": "AAGA,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,6BAA6B;AACpE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEvC,eAAsB,mBACpB,IACA,OACA,SACiB;AACjB,QAAM,cAAc;AAAA,IAClB,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,EACxB;AACA,MAAI,SAAS;AACX,WAAO,GAAG,MAAM,qBAAqB,EAAE,GAAG,aAAa,iBAAiB,QAAQ,WAAW,KAAK,CAAC;AAAA,EACnG;AAEA,QAAM,eAAe;AAAA,IACnB,GAAG;AAAA,IACH,iBAAiB;AAAA,IACjB,QAAQ;AAAA,EACV;AACA,QAAM,aAAa,GAAG,mBAAmB,mBAAmB,EAAE,OAAO,IAAI,EAAE,MAAM,YAAY;AAC7F,QAAM,CAAC,aAAa,YAAY,IAAI,MAAM,QAAQ,IAAI;AAAA,IACpD,GAAG,MAAM,kBAAkB,EAAE,GAAG,aAAa,QAAQ,EAAE,MAAM,WAAW,EAAE,CAAC;AAAA,IAC3E,GAAG,MAAM,qBAAqB,EAAE,GAAG,cAAc,WAAW,KAAK,CAAC;AAAA,EACpE,CAAC;AACD,SAAO,cAAc;AACvB;AAgEA,SAAS,yBAAkD;AACzD,SAAO,EAAE,OAAO,CAAC,GAAG,WAAW,oBAAI,IAAI,GAAG,OAAO,EAAE;AACrD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SAAS;AAAA,IAChC,YAAY,YAAY,WAAW;AAAA,IACnC,cAAc,YAAY,YAAY;AAAA,IACtC,cACE,OAAO,aAAa,aAAa,YAAY,aAAa,SAAS,KAAK,EAAE,SAAS,IAC/E,aAAa,SAAS,KAAK,IAC3B;AAAA,IACN,iBAAiB,YAAY,QAAQ;AAAA,IACrC,WAAW,YAAY,eAAe;AAAA,IACtC,cAAc,YAAY,YAAY;AAAA,IACtC,kBAAkB,OAAO,KAAK,YAAY,EAAE,SAAS,IAAI,eAAe;AAAA,IACxE,oBAAoB,YAAY,kBAAkB;AAAA,IAClD,eAAe,YAAY,aAAa;AAAA,IACxC,gBAAgB,YAAY,kBAAkB;AAAA,IAC9C,UAAU,YAAY,YAAY;AAAA,IAClC,WAAW,YAAY;AAAA,IACvB,cAAc,8BAA8B,WAAW;AAAA,IACvD,eAAe,YAAY,iBAAiB;AAAA,IAC5C,UAAU,YAAY;AAAA,MACpB,IAAI,YAAY,YAAY;AAAA,MAC5B,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
package/jest.config.cjs CHANGED
@@ -41,7 +41,7 @@ module.exports = {
41
41
  },
42
42
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
43
43
  transformIgnorePatterns: [
44
- 'node_modules/(?!(@mikro-orm|kysely|ai|@ai-sdk|ai-sdk-ollama|@workflow|@standard-schema|@tanstack/react-table|@tanstack/table-core|@tanstack/react-store|@tanstack/store)/)',
44
+ 'node_modules/(?!(sanitize-html|htmlparser2|domhandler|domutils|dom-serializer|domelementtype|entities|@mikro-orm|kysely|ai|@ai-sdk|ai-sdk-ollama|@workflow|@standard-schema|@tanstack/react-table|@tanstack/table-core|@tanstack/react-store|@tanstack/store)/)',
45
45
  ],
46
46
  testMatch: ['<rootDir>/src/**/__tests__/**/*.test.(ts|tsx)'],
47
47
  passWithNoTests: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.10.1-develop.7847.1.7d83dc5794",
3
+ "version": "0.10.1-develop.7857.1.259928eb85",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -258,7 +258,7 @@
258
258
  "pdf-lib": "^1.17.1",
259
259
  "pdfjs-dist": "^6.2.108",
260
260
  "resend": "^6.24.0",
261
- "sanitize-html": "2.17.5",
261
+ "sanitize-html": "2.18.1",
262
262
  "semver": "^7.8.5",
263
263
  "sharp": "^0.35.3",
264
264
  "svix": "^1.99.1",
@@ -266,16 +266,16 @@
266
266
  "zod": "^4.6.6"
267
267
  },
268
268
  "peerDependencies": {
269
- "@open-mercato/ai-assistant": "0.10.1-develop.7847.1.7d83dc5794",
270
- "@open-mercato/shared": "0.10.1-develop.7847.1.7d83dc5794",
271
- "@open-mercato/ui": "0.10.1-develop.7847.1.7d83dc5794",
269
+ "@open-mercato/ai-assistant": "0.10.1-develop.7857.1.259928eb85",
270
+ "@open-mercato/shared": "0.10.1-develop.7857.1.259928eb85",
271
+ "@open-mercato/ui": "0.10.1-develop.7857.1.259928eb85",
272
272
  "react": "^19.0.0",
273
273
  "react-dom": "^19.0.0"
274
274
  },
275
275
  "devDependencies": {
276
- "@open-mercato/ai-assistant": "0.10.1-develop.7847.1.7d83dc5794",
277
- "@open-mercato/shared": "0.10.1-develop.7847.1.7d83dc5794",
278
- "@open-mercato/ui": "0.10.1-develop.7847.1.7d83dc5794",
276
+ "@open-mercato/ai-assistant": "0.10.1-develop.7857.1.259928eb85",
277
+ "@open-mercato/shared": "0.10.1-develop.7857.1.259928eb85",
278
+ "@open-mercato/ui": "0.10.1-develop.7857.1.259928eb85",
279
279
  "@testing-library/dom": "^10.4.1",
280
280
  "@testing-library/jest-dom": "^7.0.1",
281
281
  "@testing-library/react": "^16.3.3",
@@ -1,3 +1,5 @@
1
+ import { withAttachmentStorageErrors } from '@open-mercato/core/modules/attachments/lib/storageErrors'
2
+ import { assertAttachmentStoragePartitionExists } from '@open-mercato/core/modules/attachments/lib/drivers/storageValidation'
1
3
  import { createAttachmentAccessContext, evaluateAttachmentAccess } from '../../../lib/access-runner'
2
4
  import { attachmentAccessErrorResponse } from '../../../lib/access-errors'
3
5
  import { NextRequest, NextResponse } from "next/server";
@@ -23,7 +25,7 @@ export const metadata = {
23
25
  GET: { requireAuth: false },
24
26
  };
25
27
 
26
- export async function GET(
28
+ async function readAttachmentFile(
27
29
  req: NextRequest,
28
30
  context: { params: Promise<{ id: string }> },
29
31
  ) {
@@ -64,6 +66,7 @@ export async function GET(
64
66
  const partition = await em.findOne(AttachmentPartition, {
65
67
  code: attachment.partitionCode,
66
68
  });
69
+ assertAttachmentStoragePartitionExists(Boolean(partition))
67
70
  if (!partition) {
68
71
  return NextResponse.json(
69
72
  { error: "Partition misconfigured" },
@@ -115,6 +118,8 @@ export async function GET(
115
118
  return new NextResponse(responseBody, { status: 200, headers });
116
119
  }
117
120
 
121
+ export const GET = withAttachmentStorageErrors(readAttachmentFile)
122
+
118
123
  export const openApi: OpenApiRouteDoc = {
119
124
  tag: attachmentsTag,
120
125
  summary: "Download attachment file",
@@ -131,6 +136,7 @@ export const openApi: OpenApiRouteDoc = {
131
136
  },
132
137
  ],
133
138
  errors: [
139
+ { status: 503, description: 'Attachment storage configuration rejected by policy', schema: attachmentErrorSchema },
134
140
  {
135
141
  status: 400,
136
142
  description: "Missing attachment ID",
@@ -1,3 +1,5 @@
1
+ import { withAttachmentStorageErrors } from '@open-mercato/core/modules/attachments/lib/storageErrors'
2
+ import { assertAttachmentStoragePartitionExists } from '@open-mercato/core/modules/attachments/lib/drivers/storageValidation'
1
3
  import { createAttachmentAccessContext, evaluateAttachmentAccess } from '../../../../lib/access-runner'
2
4
  import { attachmentAccessErrorResponse } from '../../../../lib/access-errors'
3
5
  import { NextRequest, NextResponse } from 'next/server'
@@ -37,7 +39,7 @@ export const metadata = {
37
39
  GET: { requireAuth: false },
38
40
  }
39
41
 
40
- export async function GET(
42
+ async function readAttachmentImage(
41
43
  req: NextRequest,
42
44
  context: { params: Promise<{ id: string; slug?: string[] | undefined }> }
43
45
  ) {
@@ -74,6 +76,7 @@ export async function GET(
74
76
  return NextResponse.json({ error: 'Not found' }, { status: 404 })
75
77
  }
76
78
  const partition = await em.findOne(AttachmentPartition, { code: attachment.partitionCode })
79
+ assertAttachmentStoragePartitionExists(Boolean(partition))
77
80
  if (!partition) {
78
81
  return NextResponse.json({ error: 'Partition misconfigured' }, { status: 500 })
79
82
  }
@@ -147,6 +150,8 @@ export async function GET(
147
150
  }
148
151
  }
149
152
 
153
+ export const GET = withAttachmentStorageErrors(readAttachmentImage)
154
+
150
155
  export const openApi: OpenApiRouteDoc = {
151
156
  tag: attachmentsTag,
152
157
  summary: 'Serve resized images',
@@ -162,6 +167,7 @@ export const openApi: OpenApiRouteDoc = {
162
167
  },
163
168
  ],
164
169
  errors: [
170
+ { status: 503, description: 'Attachment storage configuration rejected by policy', schema: attachmentErrorSchema },
165
171
  { status: 400, description: 'Invalid parameters, missing ID, or non-image attachment', schema: attachmentErrorSchema },
166
172
  { status: 401, description: 'Unauthorized - authentication required for private partitions', schema: attachmentErrorSchema },
167
173
  { status: 403, description: 'Forbidden - insufficient permissions', schema: attachmentErrorSchema },
@@ -1,3 +1,5 @@
1
+ import { withAttachmentStorageErrors } from '@open-mercato/core/modules/attachments/lib/storageErrors'
2
+ import { getAttachmentStoragePolicy } from '../../../lib/drivers/storageValidation'
1
3
  import { LockMode } from '@mikro-orm/core'
2
4
  import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
3
5
  import { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'
@@ -256,6 +258,16 @@ async function deleteAttachment(req: NextRequest, ctx: RouteContext) {
256
258
  tenantId: auth.tenantId,
257
259
  organizationId: auth.orgId,
258
260
  }
261
+ if (getAttachmentStoragePolicy() === 'strict') {
262
+ const preflightRecord = await findOneWithDecryption(em, Attachment, deleteFilter, undefined, {
263
+ tenantId: auth.tenantId, organizationId: auth.orgId,
264
+ })
265
+ if (!preflightRecord) return throwAttachmentAccessError(404)
266
+ await assertAttachmentOwnerAccess({ em, context: createAttachmentAccessContext(container), auth, attachment: preflightRecord, action: 'delete' })
267
+ await storageDriverFactory.resolveForPartition(preflightRecord.partitionCode, {
268
+ tenantId: preflightRecord.tenantId ?? auth.tenantId, organizationId: preflightRecord.organizationId ?? auth.orgId,
269
+ })
270
+ }
259
271
  const outcome = await em.transactional(async (tx) => {
260
272
  const candidate = await findOneWithDecryption(tx, Attachment, deleteFilter, undefined, {
261
273
  tenantId: auth.tenantId, organizationId: auth.orgId,
@@ -301,7 +313,7 @@ async function deleteAttachment(req: NextRequest, ctx: RouteContext) {
301
313
  }
302
314
 
303
315
  export const PATCH = withAttachmentAccessErrors(updateAttachment)
304
- export const DELETE = withAttachmentAccessErrors(deleteAttachment)
316
+ export const DELETE = withAttachmentAccessErrors(withAttachmentStorageErrors(deleteAttachment))
305
317
 
306
318
  export const openApi: OpenApiRouteDoc = {
307
319
  tag: attachmentsTag,
@@ -347,6 +359,7 @@ export const openApi: OpenApiRouteDoc = {
347
359
  { status: 200, description: 'Attachment deleted successfully', schema: z.object({ ok: z.literal(true) }) },
348
360
  ],
349
361
  errors: [
362
+ { status: 503, description: 'Attachment storage configuration rejected by policy', schema: attachmentErrorSchema },
350
363
  { status: 400, description: 'Invalid attachment ID', schema: attachmentErrorSchema },
351
364
  { status: 401, description: 'Unauthorized', schema: attachmentErrorSchema },
352
365
  { status: 404, description: 'Attachment not found', schema: attachmentErrorSchema },
@@ -1,3 +1,6 @@
1
+ import { attachmentErrorSchema } from './openapi'
2
+ import { withAttachmentStorageErrors } from '@open-mercato/core/modules/attachments/lib/storageErrors'
3
+ import { assertAttachmentStoragePartitionExists, getAttachmentStoragePolicy } from '@open-mercato/core/modules/attachments/lib/drivers/storageValidation'
1
4
  import { LockMode } from '@mikro-orm/core'
2
5
  import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
3
6
  import { prepareAttachmentMutation } from '../lib/access-mutation'
@@ -282,7 +285,7 @@ async function listRecordAttachments(req: Request) {
282
285
 
283
286
  export const GET = withAttachmentAccessErrors(listRecordAttachments)
284
287
 
285
- export async function POST(req: Request) {
288
+ async function uploadAttachment(req: Request) {
286
289
  const { t } = await resolveTranslations()
287
290
  const auth = await getAuthFromRequest(req)
288
291
  if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
@@ -384,7 +387,7 @@ export async function POST(req: Request) {
384
387
  if (uploadScope.denied) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
385
388
  const orgId = uploadScope.organizationId
386
389
  if (!orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
387
- await ensureDefaultPartitions(em)
390
+ if (getAttachmentStoragePolicy() === 'legacy') await ensureDefaultPartitions(em)
388
391
  // Optional per-field validations
389
392
  let partitionFromField: string | null = null
390
393
  let fieldMaxAttachmentSizeMb: number | null = null
@@ -457,6 +460,7 @@ export async function POST(req: Request) {
457
460
  let partition: AttachmentPartition | null = null
458
461
  for (const code of partitionCodeCandidates) {
459
462
  const record = await em.findOne(AttachmentPartition, { code })
463
+ assertAttachmentStoragePartitionExists(Boolean(record))
460
464
  if (record) {
461
465
  partition = record
462
466
  break
@@ -466,6 +470,7 @@ export async function POST(req: Request) {
466
470
  partition = await em.findOne(AttachmentPartition, { code: defaultPartitionCode })
467
471
  }
468
472
  if (!partition) {
473
+ assertAttachmentStoragePartitionExists(false)
469
474
  return NextResponse.json({ error: 'Storage partition is not configured.' }, { status: 400 })
470
475
  }
471
476
  await ensureAttachmentPartitionProtection(em, partition)
@@ -781,7 +786,8 @@ async function deleteAttachment(req: Request) {
781
786
  return NextResponse.json({ ok: true })
782
787
  }
783
788
 
784
- export const DELETE = withAttachmentAccessErrors(deleteAttachment)
789
+ export const POST = withAttachmentAccessErrors(withAttachmentStorageErrors(uploadAttachment))
790
+ export const DELETE = withAttachmentAccessErrors(withAttachmentStorageErrors(deleteAttachment))
785
791
 
786
792
  export const openApi: OpenApiRouteDoc = {
787
793
  summary: 'Manage entity attachments',
@@ -813,6 +819,7 @@ export const openApi: OpenApiRouteDoc = {
813
819
  { status: 200, description: 'Attachment stored successfully', schema: uploadResponseSchema },
814
820
  ],
815
821
  errors: [
822
+ { status: 503, description: 'Attachment storage configuration rejected by policy', schema: attachmentErrorSchema },
816
823
  { status: 400, description: 'Payload validation error', schema: errorSchema },
817
824
  { status: 401, description: 'Unauthorized', schema: errorSchema },
818
825
  { status: 403, description: 'Attachment violates field constraints', schema: errorSchema },
@@ -827,6 +834,7 @@ export const openApi: OpenApiRouteDoc = {
827
834
  { status: 404, description: 'Attachment not found', schema: errorSchema },
828
835
  ],
829
836
  errors: [
837
+ { status: 503, description: 'Attachment storage configuration rejected by policy', schema: attachmentErrorSchema },
830
838
  { status: 400, description: 'Missing attachment identifier', schema: errorSchema },
831
839
  { status: 401, description: 'Unauthorized', schema: errorSchema },
832
840
  { status: 403, description: 'Owner policy denies access', schema: errorSchema },
@@ -3,6 +3,7 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
3
3
  import type { EntityManager } from '@mikro-orm/postgresql'
4
4
  import { Attachment } from './data/entities'
5
5
  import type { StorageDriverFactory } from './lib/drivers'
6
+ import { isAttachmentStorageConfigurationError } from './lib/drivers/storageValidation'
6
7
  import { removeAttachmentRecord } from './lib/storageReferences'
7
8
 
8
9
  type ParsedArgs = Record<string, string | boolean>
@@ -93,6 +94,7 @@ const deleteAttachments: ModuleCli = {
93
94
  console.log(`Not found: ${missing.join(', ')}`)
94
95
  }
95
96
  } catch (err) {
97
+ if (isAttachmentStorageConfigurationError(err)) throw err
96
98
  console.error('[attachments] delete command failed:', err)
97
99
  }
98
100
  },
@@ -1,6 +1,17 @@
1
1
  import { z } from 'zod'
2
2
  import type { AttachmentAccessResolver } from '../lib/access-types'
3
3
 
4
+ export const attachmentStorageConfigurationSchema = z.custom<Record<string, unknown>>((value) => {
5
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
6
+ const prototype = Object.getPrototypeOf(value)
7
+ return prototype === Object.prototype || prototype === null
8
+ })
9
+
10
+ export const attachmentStorageScopeSchema = z.object({
11
+ tenantId: z.string(),
12
+ organizationId: z.string(),
13
+ }).refine((scope) => Boolean(scope.tenantId.trim()) === Boolean(scope.organizationId.trim()))
14
+
4
15
  export const attachmentAccessActionSchema = z.enum(['read', 'render', 'metadata', 'reassign', 'delete', 'export'])
5
16
  export const attachmentAccessSubjectFeaturesSchema = z.array(z.string())
6
17
  export const attachmentAccessSelectorSchema = z.string().min(1).max(200).regex(/^(?:\*|[^*\s]+(?:\.\*)?)$/)
@@ -13,6 +13,7 @@
13
13
  "attachments.errors.quotaRecoveryUnsupported": "Der Speichertreiber kann nicht an der Kontingent-Wiederherstellung teilnehmen.",
14
14
  "attachments.errors.quotaUnavailable": "Die Speicherkontingent-Abrechnung ist nicht verfügbar.",
15
15
  "attachments.errors.selectOrganization": "Wählen Sie eine bestimmte Organisation aus, bevor Sie einen Anhang hochladen.",
16
+ "attachments.errors.storageConfigurationInvalid": "Die Speicherkonfiguration für Anhänge ist nicht verfügbar.",
16
17
  "attachments.errors.storageFailed": "Die Anhangsdatei konnte nicht im Speicher abgelegt werden.",
17
18
  "attachments.errors.storagePathExists": "Der Zielspeicherpfad existiert bereits.",
18
19
  "attachments.errors.uploadFailed": "Das Hochladen des Anhangs ist fehlgeschlagen.",
@@ -13,6 +13,7 @@
13
13
  "attachments.errors.quotaRecoveryUnsupported": "Storage driver cannot participate in quota recovery.",
14
14
  "attachments.errors.quotaUnavailable": "Storage quota accounting is unavailable.",
15
15
  "attachments.errors.selectOrganization": "Select a specific organization before uploading an attachment.",
16
+ "attachments.errors.storageConfigurationInvalid": "Attachment storage configuration is unavailable.",
16
17
  "attachments.errors.storageFailed": "Failed to store the attachment file.",
17
18
  "attachments.errors.storagePathExists": "The target storage path already exists.",
18
19
  "attachments.errors.uploadFailed": "Attachment upload failed.",
@@ -13,6 +13,7 @@
13
13
  "attachments.errors.quotaRecoveryUnsupported": "El controlador de almacenamiento no puede participar en la recuperación de cuota.",
14
14
  "attachments.errors.quotaUnavailable": "La contabilidad de la cuota de almacenamiento no está disponible.",
15
15
  "attachments.errors.selectOrganization": "Selecciona una organización específica antes de subir un adjunto.",
16
+ "attachments.errors.storageConfigurationInvalid": "La configuración del almacenamiento de archivos adjuntos no está disponible.",
16
17
  "attachments.errors.storageFailed": "No se pudo almacenar el archivo adjunto.",
17
18
  "attachments.errors.storagePathExists": "La ruta de almacenamiento de destino ya existe.",
18
19
  "attachments.errors.uploadFailed": "Error al subir el archivo adjunto.",
@@ -13,6 +13,7 @@
13
13
  "attachments.errors.quotaRecoveryUnsupported": "저장 용량 복구가 지원되지 않습니다.",
14
14
  "attachments.errors.quotaUnavailable": "첨부파일 저장 용량 정보를 확인할 수 없습니다.",
15
15
  "attachments.errors.selectOrganization": "첨부파일을 업로드하기 전에 특정 조직을 선택하세요.",
16
+ "attachments.errors.storageConfigurationInvalid": "첨부 파일 저장소 구성을 사용할 수 없습니다.",
16
17
  "attachments.errors.storageFailed": "첨부 파일을 저장소에 기록하지 못했습니다.",
17
18
  "attachments.errors.storagePathExists": "대상 저장 경로가 이미 존재합니다.",
18
19
  "attachments.errors.uploadFailed": "첨부 파일 업로드에 실패했습니다.",
@@ -13,6 +13,7 @@
13
13
  "attachments.errors.quotaRecoveryUnsupported": "Sterownik przechowywania nie może uczestniczyć w odzyskiwaniu limitu.",
14
14
  "attachments.errors.quotaUnavailable": "Rozliczanie limitu przestrzeni dyskowej jest niedostępne.",
15
15
  "attachments.errors.selectOrganization": "Wybierz konkretną organizację przed przesłaniem załącznika.",
16
+ "attachments.errors.storageConfigurationInvalid": "Konfiguracja magazynu załączników jest niedostępna.",
16
17
  "attachments.errors.storageFailed": "Nie udało się zapisać pliku załącznika w magazynie.",
17
18
  "attachments.errors.storagePathExists": "Docelowa ścieżka przechowywania już istnieje.",
18
19
  "attachments.errors.uploadFailed": "Przesyłanie załącznika nie powiodło się.",
@@ -20,6 +20,18 @@ export {
20
20
  type ReleaseScopedAttachmentInput,
21
21
  } from './lib/attachment-service'
22
22
 
23
+ export {
24
+ AttachmentStorageConfigurationError,
25
+ getAttachmentStoragePolicy,
26
+ isAttachmentStorageConfigurationError,
27
+ registerStorageDriverValidator,
28
+ type AttachmentStoragePolicy,
29
+ type AttachmentStorageScope,
30
+ type AttachmentStorageValidationStage,
31
+ type AttachmentStorageValidationContext,
32
+ type AttachmentStorageValidator,
33
+ type AttachmentStorageConfigurationReason,
34
+ } from './lib/drivers/storageValidation'
23
35
  export type {
24
36
  AttachmentAccessAction,
25
37
  AttachmentAccessDecision,
@@ -9,6 +9,7 @@ import { evaluateAttachmentAccess, type AttachmentAccessContext } from './access
9
9
  import type { AttachmentAccessAction, AttachmentAccessRecord } from './access-types'
10
10
  import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
11
11
  import { attachmentAccessErrorBody, throwAttachmentAccessError } from './access-errors'
12
+ import { assertAttachmentStoragePartitionExists } from './drivers/storageValidation'
12
13
  import { readAttachmentMetadata } from './metadata'
13
14
 
14
15
  export function requiresAttachmentAccessScan(partitions: readonly AttachmentPartition[]): boolean {
@@ -31,7 +32,10 @@ export async function assertAttachmentOwnerAccess(input: {
31
32
  const partition = await findOneWithDecryption(input.em, AttachmentPartition, { code: input.attachment.partitionCode }, undefined, {
32
33
  tenantId: input.attachment.tenantId, organizationId: input.attachment.organizationId,
33
34
  })
34
- if (!partition) await throwAttachmentAccessError(404)
35
+ if (!partition) {
36
+ if (input.action === 'delete') assertAttachmentStoragePartitionExists(false)
37
+ await throwAttachmentAccessError(404)
38
+ }
35
39
  if (input.persistProtection) await ensureAttachmentPartitionProtection(input.em, partition!)
36
40
  const result = await evaluateAttachmentAccess({ ...input, partition: partition!, requireAuthForPublic: true })
37
41
  if (!result.ok) await throwAttachmentAccessError(result.status)
@@ -3,6 +3,7 @@ import type { EntityManager } from '@mikro-orm/postgresql'
3
3
  import { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'
4
4
  import { Attachment, AttachmentPartition } from '../data/entities'
5
5
  import { StorageDriverFactory } from './drivers'
6
+ import { assertAttachmentStoragePartitionExists } from './drivers/storageValidation'
6
7
  import { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'
7
8
  import { buildAttachmentFileUrl } from './imageUrls'
8
9
  import { mergeAttachmentMetadata, upsertAssignment } from './metadata'
@@ -54,6 +55,7 @@ export async function createAttachmentFromBuffer(input: CreateAttachmentFromBuff
54
55
 
55
56
  let partition = await em.findOne(AttachmentPartition, { code })
56
57
  if (!partition) {
58
+ assertAttachmentStoragePartitionExists(false)
57
59
  await ensureDefaultPartitions(em)
58
60
  partition = await em.findOne(AttachmentPartition, { code })
59
61
  }