@open-mercato/core 0.6.6-develop.6535.1.5cf43724de → 0.6.6-develop.6536.1.799f7f795b

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.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/attachments/lib/reconcileOrganization.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { Attachment } from '../data/entities'\n\nconst logger = createLogger('attachments').child({ component: 'reconcileOrganization' })\n\n/**\n * Virtual entity id for library attachments \u2014 these are not attached to a\n * parent record that owns an organization, so there is nothing to reconcile\n * against. They are counted as skipped rather than unresolved.\n */\nconst LIBRARY_ENTITY_ID = 'attachments:library'\n\nconst DEFAULT_BATCH_SIZE = 500\n\nexport type AttachmentOrgReconcileEntityStat = {\n scanned: number\n updated: number\n unresolved: number\n}\n\nexport type AttachmentOrgReconcileReport = {\n scanned: number\n updated: number\n unresolved: number\n skippedVirtual: number\n byEntity: Record<string, AttachmentOrgReconcileEntityStat>\n}\n\ntype AttachmentScanRow = {\n id: string\n entity_id: string | null\n record_id: string | null\n organization_id: string | null\n}\n\nfunction readParentOrganizationId(record: Record<string, unknown>): string | null {\n const raw = record['organization_id'] ?? record['organizationId']\n if (typeof raw === 'string' && raw.trim().length) return raw.trim()\n return null\n}\n\nfunction ensureBucket(\n report: AttachmentOrgReconcileReport,\n entityId: string,\n): AttachmentOrgReconcileEntityStat {\n const existing = report.byEntity[entityId]\n if (existing) return existing\n const bucket: AttachmentOrgReconcileEntityStat = { scanned: 0, updated: 0, unresolved: 0 }\n report.byEntity[entityId] = bucket\n return bucket\n}\n\n/**\n * Reconcile the `organization_id` of existing attachments to the organization\n * of the record they are attached to.\n *\n * Background (#3765): before the upload route became selected-organization\n * aware, a multi-org admin who switched the header organization uploaded files\n * that were silently stored under their *home* organization instead of the\n * selected one (the organization of the parent record). Those rows are now\n * invisible to org-scoped reads and stay orphaned. This heals them forward.\n *\n * The parent record's organization is the ground truth: an attachment is not\n * distinguishable from a legitimately home-org one by looking at the attachment\n * alone. Parent organizations are resolved generically through the Query Engine\n * by `entityId` (works for both base and custom entities, tenant-scoped and\n * organization-agnostic so the parent's real org is returned regardless of\n * which org the caller sits in) \u2014 the same mechanism the attachments module\n * already uses to enrich assignment details.\n *\n * The reconciliation is:\n * - idempotent \u2014 rows already matching their parent are left untouched;\n * - conservative \u2014 when the parent org cannot be resolved (unregistered\n * entity id, hard-deleted parent, parent without an org column) the row is\n * counted as `unresolved` and left as-is rather than guessed at;\n * - tenant-scoped \u2014 it reconciles every attachment in the tenant across all\n * organizations (the whole point is moving rows between orgs).\n *\n * Writes go through the passed `EntityManager` (which the caller runs inside a\n * transaction) so the whole reconciliation commits atomically.\n */\nexport async function reconcileAttachmentOrganizations(opts: {\n em: EntityManager\n queryEngine: QueryEngine\n tenantId: string\n batchSize?: number\n}): Promise<AttachmentOrgReconcileReport> {\n const { em, queryEngine, tenantId } = opts\n const batchSize = opts.batchSize && opts.batchSize > 0 ? opts.batchSize : DEFAULT_BATCH_SIZE\n const report: AttachmentOrgReconcileReport = {\n scanned: 0,\n updated: 0,\n unresolved: 0,\n skippedVirtual: 0,\n byEntity: {},\n }\n\n const rows = (await em.getConnection().execute(\n 'select id, entity_id, record_id, organization_id from attachments where tenant_id = ?',\n [tenantId],\n )) as AttachmentScanRow[]\n report.scanned = rows.length\n if (!rows.length) return report\n\n const groups = new Map<string, AttachmentScanRow[]>()\n for (const row of rows) {\n if (!row.id || !row.entity_id || !row.record_id) continue\n const list = groups.get(row.entity_id) ?? []\n list.push(row)\n groups.set(row.entity_id, list)\n }\n\n const pendingUpdates: Array<{ id: string; organizationId: string }> = []\n\n for (const [entityId, group] of groups) {\n const bucket = ensureBucket(report, entityId)\n bucket.scanned += group.length\n\n if (entityId === LIBRARY_ENTITY_ID) {\n report.skippedVirtual += group.length\n continue\n }\n\n const recordIds = Array.from(\n new Set(group.map((row) => row.record_id).filter((value): value is string => !!value)),\n )\n const parentOrgByRecordId = new Map<string, string | null>()\n let resolvable = true\n\n for (let index = 0; index < recordIds.length; index += batchSize) {\n const chunk = recordIds.slice(index, index + batchSize)\n try {\n const result = await queryEngine.query(entityId as any, {\n fields: ['id', 'organization_id'],\n filters: { id: chunk.length === 1 ? { $eq: chunk[0] } : { $in: chunk } },\n tenantId,\n withDeleted: true,\n page: { pageSize: Math.max(chunk.length, 1) },\n })\n for (const item of result.items ?? []) {\n const record = item as Record<string, unknown>\n const recordId = record.id != null ? String(record.id) : null\n if (!recordId) continue\n parentOrgByRecordId.set(recordId, readParentOrganizationId(record))\n }\n } catch (error) {\n resolvable = false\n logger.warn('org reconcile: cannot resolve parent organization for entity', {\n entityId,\n error,\n })\n break\n }\n }\n\n if (!resolvable) {\n bucket.unresolved += group.length\n report.unresolved += group.length\n continue\n }\n\n for (const row of group) {\n const target = row.record_id ? parentOrgByRecordId.get(row.record_id) : null\n if (!target) {\n bucket.unresolved += 1\n report.unresolved += 1\n continue\n }\n if ((row.organization_id ?? null) === target) continue\n pendingUpdates.push({ id: row.id, organizationId: target })\n bucket.updated += 1\n report.updated += 1\n }\n }\n\n for (let index = 0; index < pendingUpdates.length; index += batchSize) {\n const chunk = pendingUpdates.slice(index, index + batchSize)\n for (const update of chunk) {\n const reference = em.getReference(Attachment, update.id)\n reference.organizationId = update.organizationId\n }\n await em.flush()\n }\n\n return report\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAE7B,SAAS,kBAAkB;AAE3B,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,wBAAwB,CAAC;AAOvF,MAAM,oBAAoB;AAE1B,MAAM,qBAAqB;AAuB3B,SAAS,yBAAyB,QAAgD;AAChF,QAAM,MAAM,OAAO,iBAAiB,KAAK,OAAO,gBAAgB;AAChE,MAAI,OAAO,QAA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WAAW;AAClB,aAAO,WAAW;AAAA,IACpB;AAAA,EACF;AAEA,WAAS,QAAQ,GAAG,QAAQ,eAAe,QAAQ,SAAS,WAAW;AACrE,UAAM,QAAQ,eAAe,MAAM,OAAO,QAAQ,SAAS;AAC3D,eAAW,UAAU,OAAO;AAC1B,YAAM,YAAY,GAAG,aAAa,YAAY,OAAO,EAAE;AACvD,gBAAU,iBAAiB,OAAO;AAAA,IACpC;AACA,UAAM,GAAG,MAAM;AAAA,EACjB;AAEA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -0,0 +1,10 @@
1
+ import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
2
+ async function resolveAttachmentOrganizationId(container, auth, request) {
3
+ if (!auth) return null;
4
+ const scope = await resolveOrganizationScopeForRequest({ container, auth, request });
5
+ return scope?.selectedId ?? auth.orgId ?? null;
6
+ }
7
+ export {
8
+ resolveAttachmentOrganizationId
9
+ };
10
+ //# sourceMappingURL=requestScope.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/attachments/lib/requestScope.ts"],
4
+ "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\n\n/**\n * Resolve the organization an attachment request should act within.\n *\n * `auth.orgId` alone is NOT selected-organization aware for non-superadmin\n * principals: `applySuperAdminScope` only rewrites `orgId` from the\n * `om_selected_org` cookie for superadmins, so a regular multi-org admin who\n * switches the header organization keeps `auth.orgId` pinned to their own home\n * organization. The CRUD factory and other org-scoped routes derive the active\n * organization via `resolveOrganizationScopeForRequest` (cookie-driven and\n * RBAC-validated for ALL users, falling back to the home org when the selection\n * is absent or inaccessible). Attachments must do the same so uploaded files\n * land under \u2014 and are read back from \u2014 the currently selected organization\n * rather than the uploader's home organization (#3765).\n */\nexport async function resolveAttachmentOrganizationId(\n container: AwilixContainer,\n auth: AuthContext,\n request: Request,\n): Promise<string | null> {\n if (!auth) return null\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request })\n return scope?.selectedId ?? auth.orgId ?? null\n}\n"],
5
+ "mappings": "AAEA,SAAS,0CAA0C;AAgBnD,eAAsB,gCACpB,WACA,MACA,SACwB;AACxB,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,QAAQ,MAAM,mCAAmC,EAAE,WAAW,MAAM,QAAQ,CAAC;AACnF,SAAO,OAAO,cAAc,KAAK,SAAS;AAC5C;",
6
+ "names": []
7
+ }
@@ -1,4 +1,7 @@
1
1
  import * as semver from "semver";
2
+ import { createLogger } from "@open-mercato/shared/lib/logger";
3
+ import { reconcileAttachmentOrganizations } from "@open-mercato/core/modules/attachments/lib/reconcileOrganization";
4
+ const logger = createLogger("configs").child({ component: "upgrade-actions" });
2
5
  function compareVersions(a, b) {
3
6
  const cleanA = semver.valid(semver.coerce(a));
4
7
  const cleanB = semver.valid(semver.coerce(b));
@@ -11,6 +14,25 @@ function compareVersions(a, b) {
11
14
  return semver.compare(cleanA, cleanB);
12
15
  }
13
16
  const upgradeActions = [
17
+ {
18
+ id: "attachments.reconcile-organization",
19
+ version: "0.6.6",
20
+ messageKey: "configs.upgrades.attachmentsOrgReconcile.message",
21
+ ctaKey: "configs.upgrades.attachmentsOrgReconcile.cta",
22
+ successKey: "configs.upgrades.attachmentsOrgReconcile.success",
23
+ loadingKey: "configs.upgrades.attachmentsOrgReconcile.loading",
24
+ async run({ container, em, tenantId }) {
25
+ const queryEngine = container.resolve("queryEngine");
26
+ const report = await reconcileAttachmentOrganizations({ em, queryEngine, tenantId });
27
+ logger.info("attachments organization reconcile completed", {
28
+ tenantId,
29
+ scanned: report.scanned,
30
+ updated: report.updated,
31
+ unresolved: report.unresolved,
32
+ skippedVirtual: report.skippedVirtual
33
+ });
34
+ }
35
+ },
14
36
  {
15
37
  id: "customers.seed-interaction-statuses",
16
38
  version: "0.6.5",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/configs/lib/upgrade-actions.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport * as semver from 'semver'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\n\nexport type UpgradeActionContext = {\n tenantId: string\n organizationId: string\n container: AppContainer\n em: EntityManager\n}\n\nexport type UpgradeActionDefinition = {\n id: string\n version: string\n messageKey: string\n ctaKey: string\n successKey: string\n loadingKey?: string\n run: (ctx: UpgradeActionContext) => Promise<void>\n}\n\n/**\n * Compare two semantic version strings.\n * Uses the semver library for robust version comparison.\n * Returns negative if a < b, positive if a > b, 0 if equal.\n * Throws an error if either version string is invalid.\n */\nexport function compareVersions(a: string, b: string): number {\n const cleanA = semver.valid(semver.coerce(a))\n const cleanB = semver.valid(semver.coerce(b))\n if (!cleanA) {\n throw new Error(`Invalid version string: \"${a}\". Expected a valid semver format (e.g., \"1.2.3\").`)\n }\n if (!cleanB) {\n throw new Error(`Invalid version string: \"${b}\". Expected a valid semver format (e.g., \"1.2.3\").`)\n }\n return semver.compare(cleanA, cleanB)\n}\n\nexport const upgradeActions: UpgradeActionDefinition[] = [\n {\n id: 'customers.seed-interaction-statuses',\n version: '0.6.5',\n messageKey: 'customers.config.upgradeActions.interactionStatuses.message',\n ctaKey: 'customers.config.upgradeActions.interactionStatuses.cta',\n successKey: 'customers.config.upgradeActions.interactionStatuses.success',\n loadingKey: 'customers.config.upgradeActions.interactionStatuses.loading',\n // Existing tenants predate the `interaction_status` dictionary, so their status\n // dropdown is empty until seeded. New tenants get it via customers `seedDefaults`.\n // Lazy-imported so configs stays decoupled from customers (the catalog of actions\n // lives here, but customers code only loads when the action actually runs).\n run: async ({ em, tenantId, organizationId }) => {\n const [{ INTERACTION_STATUS_DEFAULTS }, { ensureDictionaryEntry }] = await Promise.all([\n import('@open-mercato/core/modules/customers/cli'),\n import('@open-mercato/core/modules/customers/commands/shared'),\n ])\n for (const entry of INTERACTION_STATUS_DEFAULTS) {\n await ensureDictionaryEntry(em, {\n tenantId,\n organizationId,\n kind: 'interaction_status',\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n })\n }\n },\n },\n]\n\nexport function actionsUpToVersion(version: string): UpgradeActionDefinition[] {\n return upgradeActions // NOSONAR \u2014 upgradeActions is populated at boot time by modules\n .filter((action) => compareVersions(action.version, version) <= 0)\n .sort((a, b) => compareVersions(a.version, b.version) || a.id.localeCompare(b.id))\n}\n\nexport function findUpgradeAction(actionId: string, maxVersion: string): UpgradeActionDefinition | undefined {\n const matches = actionsUpToVersion(maxVersion).filter((action) => action.id === actionId)\n if (!matches.length) return undefined\n return matches[matches.length - 1]\n}\n"],
5
- "mappings": "AACA,YAAY,YAAY;AA0BjB,SAAS,gBAAgB,GAAW,GAAmB;AAC5D,QAAM,SAAS,OAAO,MAAM,OAAO,OAAO,CAAC,CAAC;AAC5C,QAAM,SAAS,OAAO,MAAM,OAAO,OAAO,CAAC,CAAC;AAC5C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,4BAA4B,CAAC,oDAAoD;AAAA,EACnG;AACA,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,4BAA4B,CAAC,oDAAoD;AAAA,EACnG;AACA,SAAO,OAAO,QAAQ,QAAQ,MAAM;AACtC;AAEO,MAAM,iBAA4C;AAAA,EACvD;AAAA,IACE,IAAI;AAAA,IACJ,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,IAKZ,KAAK,OAAO,EAAE,IAAI,UAAU,eAAe,MAAM;AAC/C,YAAM,CAAC,EAAE,4BAA4B,GAAG,EAAE,sBAAsB,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,QACrF,OAAO,0CAA0C;AAAA,QACjD,OAAO,sDAAsD;AAAA,MAC/D,CAAC;AACD,iBAAW,SAAS,6BAA6B;AAC/C,cAAM,sBAAsB,IAAI;AAAA,UAC9B;AAAA,UACA;AAAA,UACA,MAAM;AAAA,UACN,OAAO,MAAM;AAAA,UACb,OAAO,MAAM;AAAA,UACb,OAAO,MAAM;AAAA,UACb,MAAM,MAAM;AAAA,QACd,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,mBAAmB,SAA4C;AAC7E,SAAO,eACJ,OAAO,CAAC,WAAW,gBAAgB,OAAO,SAAS,OAAO,KAAK,CAAC,EAChE,KAAK,CAAC,GAAG,MAAM,gBAAgB,EAAE,SAAS,EAAE,OAAO,KAAK,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC;AACrF;AAEO,SAAS,kBAAkB,UAAkB,YAAyD;AAC3G,QAAM,UAAU,mBAAmB,UAAU,EAAE,OAAO,CAAC,WAAW,OAAO,OAAO,QAAQ;AACxF,MAAI,CAAC,QAAQ,OAAQ,QAAO;AAC5B,SAAO,QAAQ,QAAQ,SAAS,CAAC;AACnC;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport * as semver from 'semver'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport { reconcileAttachmentOrganizations } from '@open-mercato/core/modules/attachments/lib/reconcileOrganization'\n\nconst logger = createLogger('configs').child({ component: 'upgrade-actions' })\n\nexport type UpgradeActionContext = {\n tenantId: string\n organizationId: string\n container: AppContainer\n em: EntityManager\n}\n\nexport type UpgradeActionDefinition = {\n id: string\n version: string\n messageKey: string\n ctaKey: string\n successKey: string\n loadingKey?: string\n run: (ctx: UpgradeActionContext) => Promise<void>\n}\n\n/**\n * Compare two semantic version strings.\n * Uses the semver library for robust version comparison.\n * Returns negative if a < b, positive if a > b, 0 if equal.\n * Throws an error if either version string is invalid.\n */\nexport function compareVersions(a: string, b: string): number {\n const cleanA = semver.valid(semver.coerce(a))\n const cleanB = semver.valid(semver.coerce(b))\n if (!cleanA) {\n throw new Error(`Invalid version string: \"${a}\". Expected a valid semver format (e.g., \"1.2.3\").`)\n }\n if (!cleanB) {\n throw new Error(`Invalid version string: \"${b}\". Expected a valid semver format (e.g., \"1.2.3\").`)\n }\n return semver.compare(cleanA, cleanB)\n}\n\nexport const upgradeActions: UpgradeActionDefinition[] = [\n {\n id: 'attachments.reconcile-organization',\n version: '0.6.6',\n messageKey: 'configs.upgrades.attachmentsOrgReconcile.message',\n ctaKey: 'configs.upgrades.attachmentsOrgReconcile.cta',\n successKey: 'configs.upgrades.attachmentsOrgReconcile.success',\n loadingKey: 'configs.upgrades.attachmentsOrgReconcile.loading',\n async run({ container, em, tenantId }) {\n const queryEngine = container.resolve('queryEngine') as QueryEngine\n const report = await reconcileAttachmentOrganizations({ em, queryEngine, tenantId })\n logger.info('attachments organization reconcile completed', {\n tenantId,\n scanned: report.scanned,\n updated: report.updated,\n unresolved: report.unresolved,\n skippedVirtual: report.skippedVirtual,\n })\n },\n },\n {\n id: 'customers.seed-interaction-statuses',\n version: '0.6.5',\n messageKey: 'customers.config.upgradeActions.interactionStatuses.message',\n ctaKey: 'customers.config.upgradeActions.interactionStatuses.cta',\n successKey: 'customers.config.upgradeActions.interactionStatuses.success',\n loadingKey: 'customers.config.upgradeActions.interactionStatuses.loading',\n // Existing tenants predate the `interaction_status` dictionary, so their status\n // dropdown is empty until seeded. New tenants get it via customers `seedDefaults`.\n // Lazy-imported so configs stays decoupled from customers (the catalog of actions\n // lives here, but customers code only loads when the action actually runs).\n run: async ({ em, tenantId, organizationId }) => {\n const [{ INTERACTION_STATUS_DEFAULTS }, { ensureDictionaryEntry }] = await Promise.all([\n import('@open-mercato/core/modules/customers/cli'),\n import('@open-mercato/core/modules/customers/commands/shared'),\n ])\n for (const entry of INTERACTION_STATUS_DEFAULTS) {\n await ensureDictionaryEntry(em, {\n tenantId,\n organizationId,\n kind: 'interaction_status',\n value: entry.value,\n label: entry.label,\n color: entry.color,\n icon: entry.icon,\n })\n }\n },\n },\n]\n\nexport function actionsUpToVersion(version: string): UpgradeActionDefinition[] {\n return upgradeActions // NOSONAR \u2014 upgradeActions is populated at boot time by modules\n .filter((action) => compareVersions(action.version, version) <= 0)\n .sort((a, b) => compareVersions(a.version, b.version) || a.id.localeCompare(b.id))\n}\n\nexport function findUpgradeAction(actionId: string, maxVersion: string): UpgradeActionDefinition | undefined {\n const matches = actionsUpToVersion(maxVersion).filter((action) => action.id === actionId)\n if (!matches.length) return undefined\n return matches[matches.length - 1]\n}\n"],
5
+ "mappings": "AACA,YAAY,YAAY;AAExB,SAAS,oBAAoB;AAE7B,SAAS,wCAAwC;AAEjD,MAAM,SAAS,aAAa,SAAS,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAyBtE,SAAS,gBAAgB,GAAW,GAAmB;AAC5D,QAAM,SAAS,OAAO,MAAM,OAAO,OAAO,CAAC,CAAC;AAC5C,QAAM,SAAS,OAAO,MAAM,OAAO,OAAO,CAAC,CAAC;AAC5C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,4BAA4B,CAAC,oDAAoD;AAAA,EACnG;AACA,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,4BAA4B,CAAC,oDAAoD;AAAA,EACnG;AACA,SAAO,OAAO,QAAQ,QAAQ,MAAM;AACtC;AAEO,MAAM,iBAA4C;AAAA,EACvD;AAAA,IACE,IAAI;AAAA,IACJ,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,MAAM,IAAI,EAAE,WAAW,IAAI,SAAS,GAAG;AACrC,YAAM,cAAc,UAAU,QAAQ,aAAa;AACnD,YAAM,SAAS,MAAM,iCAAiC,EAAE,IAAI,aAAa,SAAS,CAAC;AACnF,aAAO,KAAK,gDAAgD;AAAA,QAC1D;AAAA,QACA,SAAS,OAAO;AAAA,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",
3
+ "version": "0.6.6-develop.6536.1.799f7f795b",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -253,16 +253,16 @@
253
253
  "zod": "^4.4.3"
254
254
  },
255
255
  "peerDependencies": {
256
- "@open-mercato/ai-assistant": "0.6.6-develop.6535.1.5cf43724de",
257
- "@open-mercato/shared": "0.6.6-develop.6535.1.5cf43724de",
258
- "@open-mercato/ui": "0.6.6-develop.6535.1.5cf43724de",
256
+ "@open-mercato/ai-assistant": "0.6.6-develop.6536.1.799f7f795b",
257
+ "@open-mercato/shared": "0.6.6-develop.6536.1.799f7f795b",
258
+ "@open-mercato/ui": "0.6.6-develop.6536.1.799f7f795b",
259
259
  "react": "^19.0.0",
260
260
  "react-dom": "^19.0.0"
261
261
  },
262
262
  "devDependencies": {
263
- "@open-mercato/ai-assistant": "0.6.6-develop.6535.1.5cf43724de",
264
- "@open-mercato/shared": "0.6.6-develop.6535.1.5cf43724de",
265
- "@open-mercato/ui": "0.6.6-develop.6535.1.5cf43724de",
263
+ "@open-mercato/ai-assistant": "0.6.6-develop.6536.1.799f7f795b",
264
+ "@open-mercato/shared": "0.6.6-develop.6536.1.799f7f795b",
265
+ "@open-mercato/ui": "0.6.6-develop.6536.1.799f7f795b",
266
266
  "@testing-library/dom": "^10.4.1",
267
267
  "@testing-library/jest-dom": "^6.9.1",
268
268
  "@testing-library/react": "^16.3.1",
@@ -15,6 +15,7 @@ import {
15
15
  canRenderInlineAttachment,
16
16
  } from "@open-mercato/core/modules/attachments/lib/security";
17
17
  import { StorageDriverFactory } from '../../../lib/drivers';
18
+ import { resolveAttachmentOrganizationId } from '@open-mercato/core/modules/attachments/lib/requestScope';
18
19
 
19
20
  export const metadata = {
20
21
  GET: { requireAuth: false },
@@ -32,16 +33,19 @@ export async function GET(
32
33
  );
33
34
  }
34
35
  const auth = await getAuthFromRequest(req);
35
- const { resolve } = await createRequestContainer();
36
- const em = resolve("em") as EntityManager;
36
+ const container = await createRequestContainer();
37
+ const em = container.resolve("em") as EntityManager;
37
38
  const storageDriverFactory =
38
- (resolve("storageDriverFactory") as StorageDriverFactory | null) ??
39
+ (container.resolve("storageDriverFactory") as StorageDriverFactory | null) ??
39
40
  new StorageDriverFactory(em);
40
41
 
42
+ const scopedAuth = auth
43
+ ? { ...auth, orgId: await resolveAttachmentOrganizationId(container, auth, req) }
44
+ : auth;
41
45
  const findFilter: Record<string, unknown> = { id };
42
- if (auth && !isSuperAdminAuth(auth)) {
43
- if (auth.tenantId) findFilter.tenantId = auth.tenantId;
44
- if (auth.orgId) findFilter.organizationId = auth.orgId;
46
+ if (scopedAuth && !isSuperAdminAuth(scopedAuth)) {
47
+ if (scopedAuth.tenantId) findFilter.tenantId = scopedAuth.tenantId;
48
+ if (scopedAuth.orgId) findFilter.organizationId = scopedAuth.orgId;
45
49
  }
46
50
  const attachment = await em.findOne(Attachment, findFilter);
47
51
  if (!attachment) {
@@ -60,7 +64,7 @@ export async function GET(
60
64
  );
61
65
  }
62
66
 
63
- const access = checkAttachmentAccess(auth, attachment, partition);
67
+ const access = checkAttachmentAccess(scopedAuth, attachment, partition);
64
68
  if (!access.ok) {
65
69
  const message = access.status === 401 ? "Unauthorized" : "Forbidden";
66
70
  return NextResponse.json({ error: message }, { status: access.status });
@@ -20,6 +20,7 @@ import {
20
20
  validateImageMagicBytes,
21
21
  } from '@open-mercato/core/modules/attachments/lib/imageSafety'
22
22
  import { StorageDriverFactory } from '../../../../lib/drivers'
23
+ import { resolveAttachmentOrganizationId } from '@open-mercato/core/modules/attachments/lib/requestScope'
23
24
  import { createLogger } from '@open-mercato/shared/lib/logger'
24
25
 
25
26
  const logger = createLogger('attachments').child({ component: 'image' })
@@ -51,15 +52,18 @@ export async function GET(
51
52
  }
52
53
  const { width, height, cropType } = parsedQuery.data
53
54
 
54
- const { resolve } = await createRequestContainer()
55
- const em = resolve('em') as EntityManager
55
+ const container = await createRequestContainer()
56
+ const em = container.resolve('em') as EntityManager
56
57
  const storageDriverFactory =
57
- (resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)
58
+ (container.resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)
58
59
 
60
+ const scopedAuth = auth
61
+ ? { ...auth, orgId: await resolveAttachmentOrganizationId(container, auth, req) }
62
+ : auth
59
63
  const findFilter: Record<string, unknown> = { id }
60
- if (auth && !isSuperAdminAuth(auth)) {
61
- if (auth.tenantId) findFilter.tenantId = auth.tenantId
62
- if (auth.orgId) findFilter.organizationId = auth.orgId
64
+ if (scopedAuth && !isSuperAdminAuth(scopedAuth)) {
65
+ if (scopedAuth.tenantId) findFilter.tenantId = scopedAuth.tenantId
66
+ if (scopedAuth.orgId) findFilter.organizationId = scopedAuth.orgId
63
67
  }
64
68
  const attachment = await em.findOne(Attachment, findFilter)
65
69
  if (!attachment) {
@@ -72,7 +76,7 @@ export async function GET(
72
76
  if (!partition) {
73
77
  return NextResponse.json({ error: 'Partition misconfigured' }, { status: 500 })
74
78
  }
75
- const access = checkAttachmentAccess(auth, attachment, partition)
79
+ const access = checkAttachmentAccess(scopedAuth, attachment, partition)
76
80
  if (!access.ok) {
77
81
  const message = access.status === 401 ? 'Unauthorized' : 'Forbidden'
78
82
  return NextResponse.json({ error: message }, { status: access.status })
@@ -13,6 +13,7 @@ import { StorageDriverFactory } from '../lib/drivers'
13
13
  import { OcrService, shouldUseLlmOcr } from '../lib/ocrService'
14
14
  import { clearAttachmentThumbnailCache } from '../lib/thumbnailCache'
15
15
  import { assertAttachmentScopeInvariant } from '../lib/access'
16
+ import { resolveAttachmentOrganizationId } from '../lib/requestScope'
16
17
  import {
17
18
  mergeAttachmentMetadata,
18
19
  normalizeAttachmentAssignments,
@@ -198,10 +199,11 @@ export async function GET(req: Request) {
198
199
  }
199
200
  const { entityId, recordId, page, pageSize } = parsedQuery.data
200
201
 
201
- const { resolve } = await createRequestContainer()
202
- const em = resolve('em') as EntityManager
202
+ const container = await createRequestContainer()
203
+ const em = container.resolve('em') as EntityManager
204
+ const orgId = await resolveAttachmentOrganizationId(container, auth, req)
203
205
  const filter: Record<string, unknown> = { entityId, recordId, tenantId: auth.tenantId! }
204
- if (auth.orgId) filter.organizationId = auth.orgId
206
+ if (orgId) filter.organizationId = orgId
205
207
  const orderBy: Record<string, 'ASC' | 'DESC'> = { createdAt: 'DESC' }
206
208
  const usePaging = typeof page === 'number' && typeof pageSize === 'number'
207
209
  const total = usePaging ? await em.count(Attachment, filter) : null
@@ -224,7 +226,7 @@ export async function GET(req: Request) {
224
226
  },
225
227
  {
226
228
  tenantId: auth.tenantId ?? null,
227
- organizationId: auth.orgId ?? null,
229
+ organizationId: orgId ?? null,
228
230
  },
229
231
  )
230
232
  return NextResponse.json({
@@ -275,7 +277,6 @@ export async function POST(req: Request) {
275
277
  }, { status: 400 })
276
278
  }
277
279
  const tenantId = auth.tenantId
278
- const orgId = auth.orgId
279
280
 
280
281
  const contentType = req.headers.get('content-type') || ''
281
282
  if (!contentType.toLowerCase().includes('multipart/form-data')) {
@@ -301,11 +302,13 @@ export async function POST(req: Request) {
301
302
  const tags = parseFormTags(form.get('tags'))
302
303
  const assignmentsFromForm = parseFormAssignments(form.get('assignments'))
303
304
 
304
- const { resolve } = await createRequestContainer()
305
- const em = resolve('em') as EntityManager
306
- const dataEngine = resolve('dataEngine')
305
+ const container = await createRequestContainer()
306
+ const em = container.resolve('em') as EntityManager
307
+ const dataEngine = container.resolve('dataEngine')
307
308
  const storageDriverFactory =
308
- (resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)
309
+ (container.resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)
310
+ const orgId = await resolveAttachmentOrganizationId(container, auth, req)
311
+ if (!orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
309
312
  await ensureDefaultPartitions(em)
310
313
  // Optional per-field validations
311
314
  let partitionFromField: string | null = null
@@ -436,12 +439,12 @@ export async function POST(req: Request) {
436
439
  }
437
440
  const metadata = mergeAttachmentMetadata(null, { assignments, tags })
438
441
  const attachmentId = randomUUID()
439
- assertAttachmentScopeInvariant({ tenantId: auth.tenantId, organizationId: auth.orgId })
442
+ assertAttachmentScopeInvariant({ tenantId: auth.tenantId, organizationId: orgId })
440
443
  const att = em.create(Attachment, {
441
444
  id: attachmentId,
442
445
  entityId,
443
446
  recordId,
444
- organizationId: auth.orgId!,
447
+ organizationId: orgId,
445
448
  tenantId: auth.tenantId!,
446
449
  fileName: safeName,
447
450
  mimeType: fileMimeType,
@@ -545,17 +548,19 @@ export async function DELETE(req: Request) {
545
548
  const url = new URL(req.url)
546
549
  const id = url.searchParams.get('id') || ''
547
550
  if (!id) return NextResponse.json({ error: 'Attachment id is required' }, { status: 400 })
548
- const { resolve } = await createRequestContainer()
549
- const em = resolve('em') as EntityManager
550
- const dataEngine = resolve('dataEngine')
551
+ const container = await createRequestContainer()
552
+ const em = container.resolve('em') as EntityManager
553
+ const dataEngine = container.resolve('dataEngine')
551
554
  const storageDriverFactory =
552
- (resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)
553
- // Mirror the GET handler's superadmin bypass: a superadmin browsing with "All
554
- // organizations" selected has no concrete org, so scope the delete by tenant
555
- // only and let them remove any attachment in the tenant. Non-superadmins stay
556
- // scoped to their own organization (#3764).
555
+ (container.resolve('storageDriverFactory') as StorageDriverFactory | null) ?? new StorageDriverFactory(em)
556
+ // Resolve the currently selected organization (#3765) so a multi-org admin who
557
+ // switched the header org deletes within that org, not their pinned home org.
558
+ // A superadmin browsing with "All organizations" selected has no concrete org,
559
+ // so resolution returns null and the delete falls back to a tenant-only scope
560
+ // (#3764) — letting them remove any attachment in the tenant.
561
+ const orgId = await resolveAttachmentOrganizationId(container, auth, req)
557
562
  const deleteFilter: Record<string, unknown> = { id, tenantId: auth.tenantId! }
558
- if (auth.orgId) deleteFilter.organizationId = auth.orgId
563
+ if (orgId) deleteFilter.organizationId = orgId
559
564
  const record = await em.findOne(Attachment, deleteFilter)
560
565
  if (!record) return NextResponse.json({ error: 'Attachment not found' }, { status: 404 })
561
566
  await em.remove(record).flush()
@@ -565,7 +570,7 @@ export async function DELETE(req: Request) {
565
570
  if (record.storagePath) {
566
571
  const delDriver = await storageDriverFactory.resolveForPartition(record.partitionCode, {
567
572
  tenantId: record.tenantId ?? auth.tenantId!,
568
- organizationId: record.organizationId ?? auth.orgId ?? '',
573
+ organizationId: record.organizationId ?? orgId ?? '',
569
574
  })
570
575
  await delDriver.delete(record.partitionCode, record.storagePath)
571
576
  }
@@ -0,0 +1,188 @@
1
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
+ import { createLogger } from '@open-mercato/shared/lib/logger'
3
+ import type { QueryEngine } from '@open-mercato/shared/lib/query/types'
4
+ import { Attachment } from '../data/entities'
5
+
6
+ const logger = createLogger('attachments').child({ component: 'reconcileOrganization' })
7
+
8
+ /**
9
+ * Virtual entity id for library attachments — these are not attached to a
10
+ * parent record that owns an organization, so there is nothing to reconcile
11
+ * against. They are counted as skipped rather than unresolved.
12
+ */
13
+ const LIBRARY_ENTITY_ID = 'attachments:library'
14
+
15
+ const DEFAULT_BATCH_SIZE = 500
16
+
17
+ export type AttachmentOrgReconcileEntityStat = {
18
+ scanned: number
19
+ updated: number
20
+ unresolved: number
21
+ }
22
+
23
+ export type AttachmentOrgReconcileReport = {
24
+ scanned: number
25
+ updated: number
26
+ unresolved: number
27
+ skippedVirtual: number
28
+ byEntity: Record<string, AttachmentOrgReconcileEntityStat>
29
+ }
30
+
31
+ type AttachmentScanRow = {
32
+ id: string
33
+ entity_id: string | null
34
+ record_id: string | null
35
+ organization_id: string | null
36
+ }
37
+
38
+ function readParentOrganizationId(record: Record<string, unknown>): string | null {
39
+ const raw = record['organization_id'] ?? record['organizationId']
40
+ if (typeof raw === 'string' && raw.trim().length) return raw.trim()
41
+ return null
42
+ }
43
+
44
+ function ensureBucket(
45
+ report: AttachmentOrgReconcileReport,
46
+ entityId: string,
47
+ ): AttachmentOrgReconcileEntityStat {
48
+ const existing = report.byEntity[entityId]
49
+ if (existing) return existing
50
+ const bucket: AttachmentOrgReconcileEntityStat = { scanned: 0, updated: 0, unresolved: 0 }
51
+ report.byEntity[entityId] = bucket
52
+ return bucket
53
+ }
54
+
55
+ /**
56
+ * Reconcile the `organization_id` of existing attachments to the organization
57
+ * of the record they are attached to.
58
+ *
59
+ * Background (#3765): before the upload route became selected-organization
60
+ * aware, a multi-org admin who switched the header organization uploaded files
61
+ * that were silently stored under their *home* organization instead of the
62
+ * selected one (the organization of the parent record). Those rows are now
63
+ * invisible to org-scoped reads and stay orphaned. This heals them forward.
64
+ *
65
+ * The parent record's organization is the ground truth: an attachment is not
66
+ * distinguishable from a legitimately home-org one by looking at the attachment
67
+ * alone. Parent organizations are resolved generically through the Query Engine
68
+ * by `entityId` (works for both base and custom entities, tenant-scoped and
69
+ * organization-agnostic so the parent's real org is returned regardless of
70
+ * which org the caller sits in) — the same mechanism the attachments module
71
+ * already uses to enrich assignment details.
72
+ *
73
+ * The reconciliation is:
74
+ * - idempotent — rows already matching their parent are left untouched;
75
+ * - conservative — when the parent org cannot be resolved (unregistered
76
+ * entity id, hard-deleted parent, parent without an org column) the row is
77
+ * counted as `unresolved` and left as-is rather than guessed at;
78
+ * - tenant-scoped — it reconciles every attachment in the tenant across all
79
+ * organizations (the whole point is moving rows between orgs).
80
+ *
81
+ * Writes go through the passed `EntityManager` (which the caller runs inside a
82
+ * transaction) so the whole reconciliation commits atomically.
83
+ */
84
+ export async function reconcileAttachmentOrganizations(opts: {
85
+ em: EntityManager
86
+ queryEngine: QueryEngine
87
+ tenantId: string
88
+ batchSize?: number
89
+ }): Promise<AttachmentOrgReconcileReport> {
90
+ const { em, queryEngine, tenantId } = opts
91
+ const batchSize = opts.batchSize && opts.batchSize > 0 ? opts.batchSize : DEFAULT_BATCH_SIZE
92
+ const report: AttachmentOrgReconcileReport = {
93
+ scanned: 0,
94
+ updated: 0,
95
+ unresolved: 0,
96
+ skippedVirtual: 0,
97
+ byEntity: {},
98
+ }
99
+
100
+ const rows = (await em.getConnection().execute(
101
+ 'select id, entity_id, record_id, organization_id from attachments where tenant_id = ?',
102
+ [tenantId],
103
+ )) as AttachmentScanRow[]
104
+ report.scanned = rows.length
105
+ if (!rows.length) return report
106
+
107
+ const groups = new Map<string, AttachmentScanRow[]>()
108
+ for (const row of rows) {
109
+ if (!row.id || !row.entity_id || !row.record_id) continue
110
+ const list = groups.get(row.entity_id) ?? []
111
+ list.push(row)
112
+ groups.set(row.entity_id, list)
113
+ }
114
+
115
+ const pendingUpdates: Array<{ id: string; organizationId: string }> = []
116
+
117
+ for (const [entityId, group] of groups) {
118
+ const bucket = ensureBucket(report, entityId)
119
+ bucket.scanned += group.length
120
+
121
+ if (entityId === LIBRARY_ENTITY_ID) {
122
+ report.skippedVirtual += group.length
123
+ continue
124
+ }
125
+
126
+ const recordIds = Array.from(
127
+ new Set(group.map((row) => row.record_id).filter((value): value is string => !!value)),
128
+ )
129
+ const parentOrgByRecordId = new Map<string, string | null>()
130
+ let resolvable = true
131
+
132
+ for (let index = 0; index < recordIds.length; index += batchSize) {
133
+ const chunk = recordIds.slice(index, index + batchSize)
134
+ try {
135
+ const result = await queryEngine.query(entityId as any, {
136
+ fields: ['id', 'organization_id'],
137
+ filters: { id: chunk.length === 1 ? { $eq: chunk[0] } : { $in: chunk } },
138
+ tenantId,
139
+ withDeleted: true,
140
+ page: { pageSize: Math.max(chunk.length, 1) },
141
+ })
142
+ for (const item of result.items ?? []) {
143
+ const record = item as Record<string, unknown>
144
+ const recordId = record.id != null ? String(record.id) : null
145
+ if (!recordId) continue
146
+ parentOrgByRecordId.set(recordId, readParentOrganizationId(record))
147
+ }
148
+ } catch (error) {
149
+ resolvable = false
150
+ logger.warn('org reconcile: cannot resolve parent organization for entity', {
151
+ entityId,
152
+ error,
153
+ })
154
+ break
155
+ }
156
+ }
157
+
158
+ if (!resolvable) {
159
+ bucket.unresolved += group.length
160
+ report.unresolved += group.length
161
+ continue
162
+ }
163
+
164
+ for (const row of group) {
165
+ const target = row.record_id ? parentOrgByRecordId.get(row.record_id) : null
166
+ if (!target) {
167
+ bucket.unresolved += 1
168
+ report.unresolved += 1
169
+ continue
170
+ }
171
+ if ((row.organization_id ?? null) === target) continue
172
+ pendingUpdates.push({ id: row.id, organizationId: target })
173
+ bucket.updated += 1
174
+ report.updated += 1
175
+ }
176
+ }
177
+
178
+ for (let index = 0; index < pendingUpdates.length; index += batchSize) {
179
+ const chunk = pendingUpdates.slice(index, index + batchSize)
180
+ for (const update of chunk) {
181
+ const reference = em.getReference(Attachment, update.id)
182
+ reference.organizationId = update.organizationId
183
+ }
184
+ await em.flush()
185
+ }
186
+
187
+ return report
188
+ }
@@ -0,0 +1,27 @@
1
+ import type { AwilixContainer } from 'awilix'
2
+ import type { AuthContext } from '@open-mercato/shared/lib/auth/server'
3
+ import { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'
4
+
5
+ /**
6
+ * Resolve the organization an attachment request should act within.
7
+ *
8
+ * `auth.orgId` alone is NOT selected-organization aware for non-superadmin
9
+ * principals: `applySuperAdminScope` only rewrites `orgId` from the
10
+ * `om_selected_org` cookie for superadmins, so a regular multi-org admin who
11
+ * switches the header organization keeps `auth.orgId` pinned to their own home
12
+ * organization. The CRUD factory and other org-scoped routes derive the active
13
+ * organization via `resolveOrganizationScopeForRequest` (cookie-driven and
14
+ * RBAC-validated for ALL users, falling back to the home org when the selection
15
+ * is absent or inaccessible). Attachments must do the same so uploaded files
16
+ * land under — and are read back from — the currently selected organization
17
+ * rather than the uploader's home organization (#3765).
18
+ */
19
+ export async function resolveAttachmentOrganizationId(
20
+ container: AwilixContainer,
21
+ auth: AuthContext,
22
+ request: Request,
23
+ ): Promise<string | null> {
24
+ if (!auth) return null
25
+ const scope = await resolveOrganizationScopeForRequest({ container, auth, request })
26
+ return scope?.selectedId ?? auth.orgId ?? null
27
+ }
@@ -189,5 +189,9 @@
189
189
  "configs.systemStatus.variables.queryIndexWarmupThrottleMs.label": "Warmup-Drosselfenster",
190
190
  "configs.systemStatus.variables.scheduleAutoReindex.description": "Automatisch Query-Index-Neuindizierungsaufträge bei Lücken planen.",
191
191
  "configs.systemStatus.variables.scheduleAutoReindex.label": "Automatische Neuindizierung",
192
- "configs.systemStatus.viewDocs": "Dokumentation anzeigen"
192
+ "configs.systemStatus.viewDocs": "Dokumentation anzeigen",
193
+ "configs.upgrades.attachmentsOrgReconcile.cta": "Anhang-Organisationen abgleichen",
194
+ "configs.upgrades.attachmentsOrgReconcile.loading": "Anhang-Organisationen werden abgeglichen…",
195
+ "configs.upgrades.attachmentsOrgReconcile.message": "Version {{version}} behebt Anhänge, die unter der falschen Organisation gespeichert wurden. Führen Sie den Abgleich aus, um vorhandene Anhänge in die Organisation des zugehörigen Datensatzes zu verschieben.",
196
+ "configs.upgrades.attachmentsOrgReconcile.success": "Anhang-Organisationen abgeglichen."
193
197
  }
@@ -189,5 +189,9 @@
189
189
  "configs.systemStatus.variables.queryIndexWarmupThrottleMs.label": "Warmup throttle window",
190
190
  "configs.systemStatus.variables.scheduleAutoReindex.description": "Automatically schedule query index reindex jobs when gaps appear.",
191
191
  "configs.systemStatus.variables.scheduleAutoReindex.label": "Auto reindex",
192
- "configs.systemStatus.viewDocs": "View documentation"
192
+ "configs.systemStatus.viewDocs": "View documentation",
193
+ "configs.upgrades.attachmentsOrgReconcile.cta": "Reconcile attachment organizations",
194
+ "configs.upgrades.attachmentsOrgReconcile.loading": "Reconciling attachment organizations…",
195
+ "configs.upgrades.attachmentsOrgReconcile.message": "Version {{version}} fixes attachments that were saved under the wrong organization. Run the reconciliation to move existing attachments to the organization of the record they belong to.",
196
+ "configs.upgrades.attachmentsOrgReconcile.success": "Attachment organizations reconciled."
193
197
  }
@@ -189,5 +189,9 @@
189
189
  "configs.systemStatus.variables.queryIndexWarmupThrottleMs.label": "Ventana de limitación del calentamiento",
190
190
  "configs.systemStatus.variables.scheduleAutoReindex.description": "Programar automáticamente trabajos de reindexación cuando se detecten brechas.",
191
191
  "configs.systemStatus.variables.scheduleAutoReindex.label": "Reindexación automática",
192
- "configs.systemStatus.viewDocs": "Ver documentación"
192
+ "configs.systemStatus.viewDocs": "Ver documentación",
193
+ "configs.upgrades.attachmentsOrgReconcile.cta": "Reconciliar organizaciones de adjuntos",
194
+ "configs.upgrades.attachmentsOrgReconcile.loading": "Reconciliando organizaciones de adjuntos…",
195
+ "configs.upgrades.attachmentsOrgReconcile.message": "La versión {{version}} corrige los adjuntos guardados en la organización incorrecta. Ejecuta la reconciliación para mover los adjuntos existentes a la organización del registro al que pertenecen.",
196
+ "configs.upgrades.attachmentsOrgReconcile.success": "Organizaciones de adjuntos reconciliadas."
193
197
  }
@@ -189,5 +189,9 @@
189
189
  "configs.systemStatus.variables.queryIndexWarmupThrottleMs.label": "Okno throttlingu rozgrzewki",
190
190
  "configs.systemStatus.variables.scheduleAutoReindex.description": "Automatycznie uruchamia przebudowę indeksu zapytań, gdy wykryte zostaną luki.",
191
191
  "configs.systemStatus.variables.scheduleAutoReindex.label": "Automatyczna przebudowa indeksu",
192
- "configs.systemStatus.viewDocs": "Zobacz dokumentację"
192
+ "configs.systemStatus.viewDocs": "Zobacz dokumentację",
193
+ "configs.upgrades.attachmentsOrgReconcile.cta": "Uzgodnij organizacje załączników",
194
+ "configs.upgrades.attachmentsOrgReconcile.loading": "Uzgadnianie organizacji załączników…",
195
+ "configs.upgrades.attachmentsOrgReconcile.message": "Wersja {{version}} naprawia załączniki zapisane pod niewłaściwą organizacją. Uruchom uzgadnianie, aby przenieść istniejące załączniki do organizacji rekordu, do którego należą.",
196
+ "configs.upgrades.attachmentsOrgReconcile.success": "Organizacje załączników zostały uzgodnione."
193
197
  }