@open-mercato/core 0.6.6 → 0.6.7-develop.6553.1.2ec7246e04

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/dist/generated/entities/gateway_session_initialization/index.js +23 -0
  3. package/dist/generated/entities/gateway_session_initialization/index.js.map +7 -0
  4. package/dist/generated/entities.ids.generated.js +1 -0
  5. package/dist/generated/entities.ids.generated.js.map +2 -2
  6. package/dist/generated/entity-fields-registry.js +12 -0
  7. package/dist/generated/entity-fields-registry.js.map +2 -2
  8. package/dist/modules/api_keys/api/keys/route.js +30 -13
  9. package/dist/modules/api_keys/api/keys/route.js.map +2 -2
  10. package/dist/modules/api_keys/cli.js +2 -1
  11. package/dist/modules/api_keys/cli.js.map +2 -2
  12. package/dist/modules/attachments/api/file/[id]/route.js +9 -7
  13. package/dist/modules/attachments/api/file/[id]/route.js.map +2 -2
  14. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +9 -7
  15. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
  16. package/dist/modules/attachments/api/route.js +21 -17
  17. package/dist/modules/attachments/api/route.js.map +2 -2
  18. package/dist/modules/attachments/components/AttachmentContentPreview.js +6 -35
  19. package/dist/modules/attachments/components/AttachmentContentPreview.js.map +2 -2
  20. package/dist/modules/attachments/lib/reconcileOrganization.js +110 -0
  21. package/dist/modules/attachments/lib/reconcileOrganization.js.map +7 -0
  22. package/dist/modules/attachments/lib/requestScope.js +10 -0
  23. package/dist/modules/attachments/lib/requestScope.js.map +7 -0
  24. package/dist/modules/audit_logs/backend/audit-logs/page.js +14 -24
  25. package/dist/modules/audit_logs/backend/audit-logs/page.js.map +2 -2
  26. package/dist/modules/auth/api/autologin.js +85 -0
  27. package/dist/modules/auth/api/autologin.js.map +7 -0
  28. package/dist/modules/auth/api/users/route.js +6 -2
  29. package/dist/modules/auth/api/users/route.js.map +2 -2
  30. package/dist/modules/auth/cli.js +3 -2
  31. package/dist/modules/auth/cli.js.map +2 -2
  32. package/dist/modules/auth/lib/autologin.js +19 -0
  33. package/dist/modules/auth/lib/autologin.js.map +7 -0
  34. package/dist/modules/configs/lib/upgrade-actions.js +22 -0
  35. package/dist/modules/configs/lib/upgrade-actions.js.map +2 -2
  36. package/dist/modules/customer_accounts/api/admin/roles/[id]/acl.js +1 -0
  37. package/dist/modules/customer_accounts/api/admin/roles/[id]/acl.js.map +2 -2
  38. package/dist/modules/customer_accounts/api/admin/roles/[id].js +17 -3
  39. package/dist/modules/customer_accounts/api/admin/roles/[id].js.map +2 -2
  40. package/dist/modules/customer_accounts/api/portal/users/[id]/roles.js +6 -1
  41. package/dist/modules/customer_accounts/api/portal/users/[id]/roles.js.map +2 -2
  42. package/dist/modules/customer_accounts/api/portal/users-invite.js +6 -1
  43. package/dist/modules/customer_accounts/api/portal/users-invite.js.map +2 -2
  44. package/dist/modules/customer_accounts/services/customerInvitationService.js +1 -0
  45. package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
  46. package/dist/modules/customer_accounts/services/customerRbacService.js +6 -1
  47. package/dist/modules/customer_accounts/services/customerRbacService.js.map +2 -2
  48. package/dist/modules/customer_accounts/widgets/injection-table.js +0 -2
  49. package/dist/modules/customer_accounts/widgets/injection-table.js.map +2 -2
  50. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js +7 -1
  51. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js.map +2 -2
  52. package/dist/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.js +2 -2
  53. package/dist/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.js.map +2 -2
  54. package/dist/modules/customers/components/detail/CompanyDetailTabs.js +37 -43
  55. package/dist/modules/customers/components/detail/CompanyDetailTabs.js.map +2 -2
  56. package/dist/modules/customers/components/detail/DealDetailTabs.js +23 -35
  57. package/dist/modules/customers/components/detail/DealDetailTabs.js.map +2 -2
  58. package/dist/modules/customers/components/detail/DetailTabsLayout.js +6 -21
  59. package/dist/modules/customers/components/detail/DetailTabsLayout.js.map +2 -2
  60. package/dist/modules/customers/components/detail/MobilePersonDetail.js +26 -32
  61. package/dist/modules/customers/components/detail/MobilePersonDetail.js.map +2 -2
  62. package/dist/modules/customers/components/detail/PersonDetailTabs.js +29 -39
  63. package/dist/modules/customers/components/detail/PersonDetailTabs.js.map +2 -2
  64. package/dist/modules/customers/components/detail/useDealsAccess.js +16 -0
  65. package/dist/modules/customers/components/detail/useDealsAccess.js.map +7 -0
  66. package/dist/modules/dashboards/api/roles/widgets/route.js +22 -3
  67. package/dist/modules/dashboards/api/roles/widgets/route.js.map +2 -2
  68. package/dist/modules/dashboards/api/users/widgets/route.js +22 -3
  69. package/dist/modules/dashboards/api/users/widgets/route.js.map +2 -2
  70. package/dist/modules/dashboards/cli.js +4 -3
  71. package/dist/modules/dashboards/cli.js.map +2 -2
  72. package/dist/modules/dashboards/lib/widgetAssignmentScope.js +9 -1
  73. package/dist/modules/dashboards/lib/widgetAssignmentScope.js.map +2 -2
  74. package/dist/modules/dictionaries/commands/entries.js +7 -14
  75. package/dist/modules/dictionaries/commands/entries.js.map +2 -2
  76. package/dist/modules/dictionaries/commands/entry-operations.js +7 -16
  77. package/dist/modules/dictionaries/commands/entry-operations.js.map +2 -2
  78. package/dist/modules/dictionaries/commands/factory.js +9 -3
  79. package/dist/modules/dictionaries/commands/factory.js.map +2 -2
  80. package/dist/modules/dictionaries/fields/dictionary.js +56 -41
  81. package/dist/modules/dictionaries/fields/dictionary.js.map +2 -2
  82. package/dist/modules/directory/utils/organizationScope.js +10 -3
  83. package/dist/modules/directory/utils/organizationScope.js.map +2 -2
  84. package/dist/modules/entities/api/records.js +5 -4
  85. package/dist/modules/entities/api/records.js.map +2 -2
  86. package/dist/modules/entities/backend/entities/system/[entityId]/page.meta.js +1 -0
  87. package/dist/modules/entities/backend/entities/system/[entityId]/page.meta.js.map +2 -2
  88. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +49 -49
  89. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  90. package/dist/modules/entities/backend/entities/user/[entityId]/page.meta.js +1 -0
  91. package/dist/modules/entities/backend/entities/user/[entityId]/page.meta.js.map +2 -2
  92. package/dist/modules/entities/cli.js +2 -1
  93. package/dist/modules/entities/cli.js.map +2 -2
  94. package/dist/modules/feature_toggles/api/check/boolean/route.js +0 -14
  95. package/dist/modules/feature_toggles/api/check/boolean/route.js.map +2 -2
  96. package/dist/modules/feature_toggles/defaults.json +8 -0
  97. package/dist/modules/integrations/backend/integrations/[id]/page.js +9 -80
  98. package/dist/modules/integrations/backend/integrations/[id]/page.js.map +2 -2
  99. package/dist/modules/payment_gateways/data/entities.js +45 -0
  100. package/dist/modules/payment_gateways/data/entities.js.map +2 -2
  101. package/dist/modules/payment_gateways/lib/gateway-service.js +173 -38
  102. package/dist/modules/payment_gateways/lib/gateway-service.js.map +3 -3
  103. package/dist/modules/payment_gateways/lib/session-idempotency.js +104 -0
  104. package/dist/modules/payment_gateways/lib/session-idempotency.js.map +7 -0
  105. package/dist/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.js +11 -0
  106. package/dist/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.js.map +7 -0
  107. package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js +16 -14
  108. package/dist/modules/planner/backend/planner/availability-rulesets/[id]/page.js.map +2 -2
  109. package/dist/modules/planner/components/AvailabilityRulesEditor.js +18 -30
  110. package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
  111. package/dist/modules/query_index/api/status.js +2 -8
  112. package/dist/modules/query_index/api/status.js.map +2 -2
  113. package/dist/modules/resources/backend/resources/resources/[id]/page.js +24 -24
  114. package/dist/modules/resources/backend/resources/resources/[id]/page.js.map +2 -2
  115. package/dist/modules/sales/backend/sales/channels/create/page.js +6 -0
  116. package/dist/modules/sales/backend/sales/channels/create/page.js.map +2 -2
  117. package/dist/modules/sales/backend/sales/channels/create/page.meta.js +2 -0
  118. package/dist/modules/sales/backend/sales/channels/create/page.meta.js.map +2 -2
  119. package/dist/modules/sales/backend/sales/channels/offers/page.js +6 -0
  120. package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
  121. package/dist/modules/sales/backend/sales/channels/offers/page.meta.js +2 -0
  122. package/dist/modules/sales/backend/sales/channels/offers/page.meta.js.map +2 -2
  123. package/dist/modules/sales/backend/sales/channels/page.js +6 -0
  124. package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
  125. package/dist/modules/sales/backend/sales/channels/page.meta.js +2 -0
  126. package/dist/modules/sales/backend/sales/channels/page.meta.js.map +2 -2
  127. package/dist/modules/sales/backend/sales/documents/[id]/page.js +6 -4
  128. package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
  129. package/dist/modules/sales/commands/documents.js +44 -0
  130. package/dist/modules/sales/commands/documents.js.map +2 -2
  131. package/dist/modules/sales/commands/returns.js +2 -27
  132. package/dist/modules/sales/commands/returns.js.map +2 -2
  133. package/dist/modules/sales/components/SalesChannelsDisabledNotice.js +15 -0
  134. package/dist/modules/sales/components/SalesChannelsDisabledNotice.js.map +7 -0
  135. package/dist/modules/sales/components/documents/AddressesSection.js +6 -2
  136. package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
  137. package/dist/modules/sales/components/documents/ItemsSection.js +1 -0
  138. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  139. package/dist/modules/sales/components/documents/LineItemDialog.js +9 -0
  140. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  141. package/dist/modules/sales/components/documents/SalesDocumentForm.js +51 -3
  142. package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
  143. package/dist/modules/sales/components/documents/SalesDocumentsTable.js +10 -8
  144. package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
  145. package/dist/modules/sales/components/documents/ShipmentDialog.js +59 -38
  146. package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
  147. package/dist/modules/sales/components/useSalesChannelsEnabled.js +44 -0
  148. package/dist/modules/sales/components/useSalesChannelsEnabled.js.map +7 -0
  149. package/dist/modules/sales/lib/calculations.js +6 -0
  150. package/dist/modules/sales/lib/calculations.js.map +2 -2
  151. package/dist/modules/sales/lib/salesChannelsToggle.js +18 -0
  152. package/dist/modules/sales/lib/salesChannelsToggle.js.map +7 -0
  153. package/dist/modules/sales/lib/salesChannelsToggleId.js +5 -0
  154. package/dist/modules/sales/lib/salesChannelsToggleId.js.map +7 -0
  155. package/dist/modules/sales/lib/shipments/snapshots.js +27 -1
  156. package/dist/modules/sales/lib/shipments/snapshots.js.map +2 -2
  157. package/dist/modules/staff/backend/staff/team-members/[id]/page.js +22 -25
  158. package/dist/modules/staff/backend/staff/team-members/[id]/page.js.map +2 -2
  159. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js +12 -14
  160. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js.map +2 -2
  161. package/dist/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.js +10 -29
  162. package/dist/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.js.map +2 -2
  163. package/dist/modules/sync_excel/lib/adapters/customers.js +19 -20
  164. package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
  165. package/dist/modules/sync_excel/lib/parser.js +185 -0
  166. package/dist/modules/sync_excel/lib/parser.js.map +2 -2
  167. package/dist/modules/sync_excel/lib/upload-storage.js +20 -1
  168. package/dist/modules/sync_excel/lib/upload-storage.js.map +2 -2
  169. package/generated/entities/gateway_session_initialization/index.ts +10 -0
  170. package/generated/entities.ids.generated.ts +1 -0
  171. package/generated/entity-fields-registry.ts +12 -0
  172. package/package.json +9 -8
  173. package/src/modules/api_keys/api/keys/route.ts +36 -13
  174. package/src/modules/api_keys/cli.ts +2 -3
  175. package/src/modules/attachments/api/file/[id]/route.ts +11 -7
  176. package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +11 -7
  177. package/src/modules/attachments/api/route.ts +26 -21
  178. package/src/modules/attachments/components/AttachmentContentPreview.tsx +9 -44
  179. package/src/modules/attachments/lib/reconcileOrganization.ts +188 -0
  180. package/src/modules/attachments/lib/requestScope.ts +27 -0
  181. package/src/modules/audit_logs/backend/audit-logs/page.tsx +12 -22
  182. package/src/modules/auth/api/autologin.ts +100 -0
  183. package/src/modules/auth/api/users/route.ts +11 -2
  184. package/src/modules/auth/cli.ts +3 -2
  185. package/src/modules/auth/lib/autologin.ts +36 -0
  186. package/src/modules/configs/i18n/de.json +5 -1
  187. package/src/modules/configs/i18n/en.json +5 -1
  188. package/src/modules/configs/i18n/es.json +5 -1
  189. package/src/modules/configs/i18n/pl.json +5 -1
  190. package/src/modules/configs/lib/upgrade-actions.ts +24 -0
  191. package/src/modules/customer_accounts/AGENTS.md +8 -6
  192. package/src/modules/customer_accounts/api/admin/roles/[id]/acl.ts +1 -0
  193. package/src/modules/customer_accounts/api/admin/roles/[id].ts +17 -3
  194. package/src/modules/customer_accounts/api/portal/users/[id]/roles.ts +6 -1
  195. package/src/modules/customer_accounts/api/portal/users-invite.ts +6 -1
  196. package/src/modules/customer_accounts/services/customerInvitationService.ts +1 -0
  197. package/src/modules/customer_accounts/services/customerRbacService.ts +9 -2
  198. package/src/modules/customer_accounts/widgets/injection-table.ts +0 -2
  199. package/src/modules/customers/backend/customers/companies-v2/[id]/page.tsx +11 -1
  200. package/src/modules/customers/backend/customers/deals/pipeline/components/ViewTabsRow.tsx +6 -2
  201. package/src/modules/customers/components/detail/CompanyDetailTabs.tsx +39 -55
  202. package/src/modules/customers/components/detail/DealDetailTabs.tsx +24 -49
  203. package/src/modules/customers/components/detail/DetailTabsLayout.tsx +13 -24
  204. package/src/modules/customers/components/detail/MobilePersonDetail.tsx +25 -31
  205. package/src/modules/customers/components/detail/PersonDetailTabs.tsx +29 -50
  206. package/src/modules/customers/components/detail/useDealsAccess.ts +19 -0
  207. package/src/modules/dashboards/api/roles/widgets/route.ts +22 -3
  208. package/src/modules/dashboards/api/users/widgets/route.ts +22 -3
  209. package/src/modules/dashboards/cli.ts +4 -9
  210. package/src/modules/dashboards/lib/widgetAssignmentScope.ts +18 -0
  211. package/src/modules/dictionaries/commands/entries.ts +7 -16
  212. package/src/modules/dictionaries/commands/entry-operations.ts +8 -18
  213. package/src/modules/dictionaries/commands/factory.ts +8 -2
  214. package/src/modules/dictionaries/fields/dictionary.tsx +55 -32
  215. package/src/modules/dictionaries/i18n/de.json +2 -0
  216. package/src/modules/dictionaries/i18n/en.json +2 -0
  217. package/src/modules/dictionaries/i18n/es.json +2 -0
  218. package/src/modules/dictionaries/i18n/pl.json +2 -0
  219. package/src/modules/directory/utils/organizationScope.ts +36 -2
  220. package/src/modules/entities/api/records.ts +5 -7
  221. package/src/modules/entities/backend/entities/system/[entityId]/page.meta.ts +1 -0
  222. package/src/modules/entities/backend/entities/user/[entityId]/page.meta.ts +1 -0
  223. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +51 -49
  224. package/src/modules/entities/cli.ts +2 -1
  225. package/src/modules/entities/i18n/de.json +34 -0
  226. package/src/modules/entities/i18n/en.json +34 -0
  227. package/src/modules/entities/i18n/es.json +34 -0
  228. package/src/modules/entities/i18n/pl.json +34 -0
  229. package/src/modules/feature_toggles/api/check/boolean/route.ts +0 -15
  230. package/src/modules/feature_toggles/defaults.json +8 -0
  231. package/src/modules/integrations/backend/integrations/[id]/page.tsx +16 -59
  232. package/src/modules/payment_gateways/data/entities.ts +39 -0
  233. package/src/modules/payment_gateways/lib/gateway-service.ts +211 -40
  234. package/src/modules/payment_gateways/lib/session-idempotency.ts +142 -0
  235. package/src/modules/payment_gateways/migrations/.snapshot-open-mercato.json +236 -0
  236. package/src/modules/payment_gateways/migrations/Migration20260709220938_payment_gateways.ts +10 -0
  237. package/src/modules/planner/backend/planner/availability-rulesets/[id]/page.tsx +14 -20
  238. package/src/modules/planner/components/AvailabilityRulesEditor.tsx +16 -34
  239. package/src/modules/query_index/api/status.ts +2 -8
  240. package/src/modules/resources/backend/resources/resources/[id]/page.tsx +27 -37
  241. package/src/modules/sales/backend/sales/channels/create/page.meta.ts +3 -0
  242. package/src/modules/sales/backend/sales/channels/create/page.tsx +7 -0
  243. package/src/modules/sales/backend/sales/channels/offers/page.meta.ts +3 -0
  244. package/src/modules/sales/backend/sales/channels/offers/page.tsx +7 -0
  245. package/src/modules/sales/backend/sales/channels/page.meta.ts +4 -0
  246. package/src/modules/sales/backend/sales/channels/page.tsx +7 -0
  247. package/src/modules/sales/backend/sales/documents/[id]/page.tsx +7 -5
  248. package/src/modules/sales/commands/documents.ts +65 -0
  249. package/src/modules/sales/commands/returns.ts +2 -32
  250. package/src/modules/sales/components/SalesChannelsDisabledNotice.tsx +21 -0
  251. package/src/modules/sales/components/documents/AddressesSection.tsx +6 -2
  252. package/src/modules/sales/components/documents/ItemsSection.tsx +5 -0
  253. package/src/modules/sales/components/documents/LineItemDialog.tsx +10 -0
  254. package/src/modules/sales/components/documents/SalesDocumentForm.tsx +53 -3
  255. package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +10 -8
  256. package/src/modules/sales/components/documents/ShipmentDialog.tsx +65 -40
  257. package/src/modules/sales/components/useSalesChannelsEnabled.ts +59 -0
  258. package/src/modules/sales/i18n/de.json +5 -0
  259. package/src/modules/sales/i18n/en.json +5 -0
  260. package/src/modules/sales/i18n/es.json +5 -0
  261. package/src/modules/sales/i18n/pl.json +5 -0
  262. package/src/modules/sales/lib/calculations.ts +15 -0
  263. package/src/modules/sales/lib/salesChannelsToggle.ts +26 -0
  264. package/src/modules/sales/lib/salesChannelsToggleId.ts +1 -0
  265. package/src/modules/sales/lib/shipments/snapshots.ts +30 -0
  266. package/src/modules/staff/backend/staff/team-members/[id]/page.tsx +25 -34
  267. package/src/modules/staff/backend/staff/teams/[id]/edit/page.tsx +11 -17
  268. package/src/modules/staff/lib/timesheets-projects-ui/SavedViewTabs.tsx +11 -28
  269. package/src/modules/sync_excel/lib/adapters/customers.ts +20 -22
  270. package/src/modules/sync_excel/lib/parser.ts +245 -0
  271. package/src/modules/sync_excel/lib/upload-storage.ts +23 -1
@@ -1225,6 +1225,18 @@ export const entityFieldsRegistry: Record<string, Record<string, string>> = {
1225
1225
  "updated_at": "updated_at",
1226
1226
  "value": "value"
1227
1227
  },
1228
+ "gateway_session_initialization": {
1229
+ "id": "id",
1230
+ "operation_key": "operation_key",
1231
+ "provider_key": "provider_key",
1232
+ "claim_token": "claim_token",
1233
+ "claimed_at": "claimed_at",
1234
+ "gateway_transaction_id": "gateway_transaction_id",
1235
+ "organization_id": "organization_id",
1236
+ "tenant_id": "tenant_id",
1237
+ "created_at": "created_at",
1238
+ "updated_at": "updated_at"
1239
+ },
1228
1240
  "gateway_transaction": {
1229
1241
  "id": "id",
1230
1242
  "payment_id": "payment_id",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.6.6",
3
+ "version": "0.6.7-develop.6553.1.2ec7246e04",
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",
257
- "@open-mercato/shared": "0.6.6",
258
- "@open-mercato/ui": "0.6.6",
256
+ "@open-mercato/ai-assistant": "0.6.7-develop.6553.1.2ec7246e04",
257
+ "@open-mercato/shared": "0.6.7-develop.6553.1.2ec7246e04",
258
+ "@open-mercato/ui": "0.6.7-develop.6553.1.2ec7246e04",
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",
264
- "@open-mercato/shared": "0.6.6",
265
- "@open-mercato/ui": "0.6.6",
263
+ "@open-mercato/ai-assistant": "0.6.7-develop.6553.1.2ec7246e04",
264
+ "@open-mercato/shared": "0.6.7-develop.6553.1.2ec7246e04",
265
+ "@open-mercato/ui": "0.6.7-develop.6553.1.2ec7246e04",
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",
@@ -285,5 +285,6 @@
285
285
  "type": "git",
286
286
  "url": "https://github.com/open-mercato/open-mercato",
287
287
  "directory": "packages/core"
288
- }
288
+ },
289
+ "stableVersion": "0.6.6"
289
290
  }
@@ -13,6 +13,8 @@ import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
13
13
  import { enforceTenantSelection, resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'
14
14
  import { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'
15
15
  import { assertActorCanGrantRoles } from '@open-mercato/core/modules/auth/lib/grantChecks'
16
+ import { isOrganizationAccessAllowed } from '@open-mercato/shared/lib/auth/organizationAccess'
17
+ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
16
18
 
17
19
  type ApiKeyCrudCtx = CrudCtx & {
18
20
  __apiKeySecret?: { secret: string; prefix: string }
@@ -297,10 +299,15 @@ const crud = makeCrudRoute<
297
299
 
298
300
  const allowedIds = ctx.organizationScope?.allowedIds ?? null
299
301
  const organizationId = input.organizationId ?? ctx.selectedOrganizationId ?? auth.orgId ?? null
300
- if (organizationId && Array.isArray(allowedIds) && allowedIds.length > 0) {
301
- if (!allowedIds.includes(organizationId)) {
302
- throw json({ error: translate('api_keys.errors.organizationOutOfScope', 'Organization out of scope') }, { status: 403 })
303
- }
302
+ const isSuperAdmin = await resolveIsSuperAdmin(scopedCtx)
303
+ if (
304
+ !isOrganizationAccessAllowed({
305
+ isSuperAdmin,
306
+ allowedOrganizationIds: allowedIds,
307
+ targetOrganizationId: organizationId,
308
+ })
309
+ ) {
310
+ throw json({ error: translate('api_keys.errors.organizationOutOfScope', 'Organization out of scope') }, { status: 403 })
304
311
  }
305
312
  scopedCtx.__apiKeyOrganizationId = organizationId ?? null
306
313
 
@@ -322,18 +329,34 @@ const crud = makeCrudRoute<
322
329
  const { translate } = await resolveTranslations()
323
330
  if (!auth?.tenantId) throw json({ error: translate('api_keys.errors.tenantRequired', 'Tenant context required') }, { status: 400 })
324
331
  const em = (ctx.container.resolve('em') as EntityManager)
325
- const record = await em.findOne(ApiKey, { id, deletedAt: null })
326
- if (!record) throw json({ error: translate('api_keys.errors.notFound', 'Not found') }, { status: 404 })
327
332
  const scopedCtx = ctx as ApiKeyCrudCtx
328
333
  const isSuperAdmin = await resolveIsSuperAdmin(scopedCtx)
329
- if (!isSuperAdmin && record.tenantId && record.tenantId !== auth.tenantId) {
330
- throw json({ error: translate('api_keys.errors.forbidden', 'Forbidden') }, { status: 403 })
331
- }
332
334
  const allowedIds = ctx.organizationScope?.allowedIds ?? null
333
- if (record.organizationId && Array.isArray(allowedIds) && allowedIds.length > 0) {
334
- if (!allowedIds.includes(record.organizationId)) {
335
- throw json({ error: translate('api_keys.errors.organizationOutOfScope', 'Organization out of scope') }, { status: 403 })
336
- }
335
+ const recordFilter: FilterQuery<ApiKey> = {
336
+ id,
337
+ tenantId: auth.tenantId,
338
+ deletedAt: null,
339
+ }
340
+ if (!isSuperAdmin && Array.isArray(allowedIds)) {
341
+ recordFilter.organizationId = { $in: allowedIds }
342
+ }
343
+ const record = await findOneWithDecryption(
344
+ em,
345
+ ApiKey,
346
+ recordFilter,
347
+ undefined,
348
+ { tenantId: auth.tenantId, organizationId: null },
349
+ )
350
+ if (
351
+ !record ||
352
+ record.tenantId !== auth.tenantId ||
353
+ !isOrganizationAccessAllowed({
354
+ isSuperAdmin,
355
+ allowedOrganizationIds: allowedIds,
356
+ targetOrganizationId: record.organizationId ?? null,
357
+ })
358
+ ) {
359
+ throw json({ error: translate('api_keys.errors.notFound', 'Not found') }, { status: 404 })
337
360
  }
338
361
  scopedCtx.__apiKeyOrganizationId = record.organizationId ?? null
339
362
  },
@@ -3,6 +3,7 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
3
3
  import { createApiKey } from './services/apiKeyService'
4
4
  import { Organization } from '@open-mercato/core/modules/directory/data/entities'
5
5
  import { Role } from '@open-mercato/core/modules/auth/data/entities'
6
+ import { parseCommaSeparatedList } from '@open-mercato/shared/lib/string'
6
7
 
7
8
  function parseArgs(rest: string[]): Record<string, string> {
8
9
  const args: Record<string, string> = {}
@@ -47,9 +48,7 @@ const addApiKey: ModuleCli = {
47
48
  return
48
49
  }
49
50
 
50
- const roleInputs = rolesCsv
51
- ? rolesCsv.split(',').map((value) => value.trim()).filter(Boolean)
52
- : []
51
+ const roleInputs = parseCommaSeparatedList(rolesCsv)
53
52
  const roleIds: string[] = []
54
53
  if (roleInputs.length) {
55
54
  for (const token of roleInputs) {
@@ -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
  }
@@ -1,6 +1,7 @@
1
1
  import * as React from 'react'
2
2
  import { MarkdownContent } from '@open-mercato/ui/backend/markdown'
3
3
  import { Button } from '@open-mercato/ui/primitives/button'
4
+ import { Tabs, TabsList, TabsTrigger } from '@open-mercato/ui/primitives/tabs'
4
5
 
5
6
  type Props = {
6
7
  content?: string | null
@@ -25,12 +26,6 @@ export function AttachmentContentPreview({
25
26
  const [tab, setTab] = React.useState<'source' | 'preview'>('source')
26
27
  const text = (content ?? '').trim()
27
28
 
28
- // ARIA IDs for accessibility
29
- const sourceTabId = 'attachment-content-preview-tab-source'
30
- const previewTabId = 'attachment-content-preview-tab-preview'
31
- const sourcePanelId = 'attachment-content-preview-panel-source'
32
- const previewPanelId = 'attachment-content-preview-panel-preview'
33
-
34
29
  if (!text) {
35
30
  return <div className="text-xs text-muted-foreground italic">{emptyLabel}</div>
36
31
  }
@@ -41,47 +36,18 @@ export function AttachmentContentPreview({
41
36
  return (
42
37
  <div className="space-y-2">
43
38
  {/* Tab Navigation */}
44
- <div className="border-b border-border">
45
- <nav className="flex items-center gap-4 text-xs" role="tablist" aria-label="Content preview mode">
46
- <button
47
- type="button"
48
- id={sourceTabId}
49
- role="tab"
50
- aria-selected={tab === 'source'}
51
- aria-controls={sourcePanelId}
52
- className={`-mb-px border-b-2 px-0 pb-2 font-medium transition-colors ${
53
- tab === 'source'
54
- ? 'border-accent-indigo text-foreground'
55
- : 'border-transparent text-muted-foreground hover:text-foreground'
56
- }`}
57
- onClick={() => setTab('source')}
58
- >
59
- {sourceLabel}
60
- </button>
61
- <button
62
- type="button"
63
- id={previewTabId}
64
- role="tab"
65
- aria-selected={tab === 'preview'}
66
- aria-controls={previewPanelId}
67
- className={`-mb-px border-b-2 px-0 pb-2 font-medium transition-colors ${
68
- tab === 'preview'
69
- ? 'border-accent-indigo text-foreground'
70
- : 'border-transparent text-muted-foreground hover:text-foreground'
71
- }`}
72
- onClick={() => setTab('preview')}
73
- >
74
- {previewLabel}
75
- </button>
76
- </nav>
77
- </div>
39
+ <Tabs value={tab} onValueChange={(value) => setTab(value as 'source' | 'preview')} variant="underline">
40
+ <TabsList className="w-full">
41
+ <TabsTrigger value="source">{sourceLabel}</TabsTrigger>
42
+ <TabsTrigger value="preview">{previewLabel}</TabsTrigger>
43
+ </TabsList>
44
+ </Tabs>
78
45
 
79
46
  {/* Tab Panels */}
80
47
  {tab === 'source' ? (
81
48
  <div
82
49
  role="tabpanel"
83
- id={sourcePanelId}
84
- aria-labelledby={sourceTabId}
50
+ aria-label={sourceLabel}
85
51
  data-testid="attachment-content-preview"
86
52
  className="whitespace-pre-wrap text-sm text-muted-foreground"
87
53
  >
@@ -90,8 +56,7 @@ export function AttachmentContentPreview({
90
56
  ) : (
91
57
  <div
92
58
  role="tabpanel"
93
- id={previewPanelId}
94
- aria-labelledby={previewTabId}
59
+ aria-label={previewLabel}
95
60
  data-testid="markdown-preview"
96
61
  >
97
62
  <MarkdownContent
@@ -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
+ }