@open-mercato/core 0.11.1-develop.8567.1.a167594505 → 0.11.1-develop.8581.1.535dac92b7

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 (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/di.js +25 -0
  3. package/dist/modules/attachments/di.js.map +2 -2
  4. package/dist/modules/catalog/lib/productScopeReindex.js +1 -1
  5. package/dist/modules/catalog/lib/productScopeReindex.js.map +2 -2
  6. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +1 -1
  7. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
  8. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +2 -1
  9. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  10. package/dist/modules/dictionaries/api/context.js +11 -8
  11. package/dist/modules/dictionaries/api/context.js.map +2 -2
  12. package/dist/modules/dictionaries/api/route.js +2 -1
  13. package/dist/modules/dictionaries/api/route.js.map +2 -2
  14. package/dist/modules/dictionaries/commands/entries.js +30 -4
  15. package/dist/modules/dictionaries/commands/entries.js.map +2 -2
  16. package/dist/modules/entities/api/relations/options.js +85 -5
  17. package/dist/modules/entities/api/relations/options.js.map +2 -2
  18. package/dist/modules/payment_gateways/lib/gateway-service.js +1 -1
  19. package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
  20. package/dist/modules/query_index/api/purge.js +1 -1
  21. package/dist/modules/query_index/api/purge.js.map +2 -2
  22. package/dist/modules/query_index/api/reindex.js +1 -1
  23. package/dist/modules/query_index/api/reindex.js.map +2 -2
  24. package/dist/modules/query_index/cli.js +2 -2
  25. package/dist/modules/query_index/cli.js.map +2 -2
  26. package/dist/modules/query_index/lib/engine.js +5 -1
  27. package/dist/modules/query_index/lib/engine.js.map +2 -2
  28. package/dist/modules/query_index/subscribers/purge.js +3 -3
  29. package/dist/modules/query_index/subscribers/purge.js.map +2 -2
  30. package/dist/modules/query_index/subscribers/reindex.js +11 -13
  31. package/dist/modules/query_index/subscribers/reindex.js.map +2 -2
  32. package/dist/modules/staff/api/interceptors.js +28 -24
  33. package/dist/modules/staff/api/interceptors.js.map +2 -2
  34. package/dist/modules/staff/di.js +23 -0
  35. package/dist/modules/staff/di.js.map +2 -2
  36. package/dist/modules/workflows/components/fields/ActivityConfigFields.js +2 -0
  37. package/dist/modules/workflows/components/fields/ActivityConfigFields.js.map +2 -2
  38. package/dist/modules/workflows/events.js +13 -0
  39. package/dist/modules/workflows/events.js.map +2 -2
  40. package/dist/modules/workflows/lib/activity-executor.js +13 -8
  41. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  42. package/package.json +7 -7
  43. package/src/modules/attachments/di.ts +29 -0
  44. package/src/modules/catalog/lib/productScopeReindex.ts +1 -1
  45. package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +1 -1
  46. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +2 -1
  47. package/src/modules/dictionaries/api/context.ts +11 -8
  48. package/src/modules/dictionaries/api/route.ts +1 -0
  49. package/src/modules/dictionaries/commands/entries.ts +40 -3
  50. package/src/modules/entities/api/relations/options.ts +88 -6
  51. package/src/modules/payment_gateways/lib/gateway-service.ts +2 -2
  52. package/src/modules/query_index/api/purge.ts +1 -1
  53. package/src/modules/query_index/api/reindex.ts +1 -1
  54. package/src/modules/query_index/cli.ts +2 -2
  55. package/src/modules/query_index/lib/engine.ts +5 -1
  56. package/src/modules/query_index/subscribers/purge.ts +5 -4
  57. package/src/modules/query_index/subscribers/reindex.ts +14 -15
  58. package/src/modules/staff/api/interceptors.ts +33 -26
  59. package/src/modules/staff/di.ts +25 -0
  60. package/src/modules/workflows/components/fields/ActivityConfigFields.tsx +2 -0
  61. package/src/modules/workflows/events.ts +14 -0
  62. package/src/modules/workflows/lib/activity-executor.ts +16 -10
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.11.1-develop.8567.1.a167594505",
3
+ "version": "0.11.1-develop.8581.1.535dac92b7",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -268,16 +268,16 @@
268
268
  "zod": "^4.6.6"
269
269
  },
270
270
  "peerDependencies": {
271
- "@open-mercato/ai-assistant": "0.11.1-develop.8567.1.a167594505",
272
- "@open-mercato/shared": "0.11.1-develop.8567.1.a167594505",
273
- "@open-mercato/ui": "0.11.1-develop.8567.1.a167594505",
271
+ "@open-mercato/ai-assistant": "0.11.1-develop.8581.1.535dac92b7",
272
+ "@open-mercato/shared": "0.11.1-develop.8581.1.535dac92b7",
273
+ "@open-mercato/ui": "0.11.1-develop.8581.1.535dac92b7",
274
274
  "react": "^19.0.0",
275
275
  "react-dom": "^19.0.0"
276
276
  },
277
277
  "devDependencies": {
278
- "@open-mercato/ai-assistant": "0.11.1-develop.8567.1.a167594505",
279
- "@open-mercato/shared": "0.11.1-develop.8567.1.a167594505",
280
- "@open-mercato/ui": "0.11.1-develop.8567.1.a167594505",
278
+ "@open-mercato/ai-assistant": "0.11.1-develop.8581.1.535dac92b7",
279
+ "@open-mercato/shared": "0.11.1-develop.8581.1.535dac92b7",
280
+ "@open-mercato/ui": "0.11.1-develop.8581.1.535dac92b7",
281
281
  "@testing-library/dom": "^10.4.1",
282
282
  "@testing-library/jest-dom": "^7.0.1",
283
283
  "@testing-library/react": "^16.3.3",
@@ -1,4 +1,9 @@
1
1
  import { defineProcessDiRegistrar, asScopedService } from '@open-mercato/shared/lib/di/process-registrar'
2
+ import { relationOptionAccessKey, type RelationOptionAccess } from '@open-mercato/shared/lib/query/relationOptionAccess'
3
+ import { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
4
+ import type { EntityManager } from '@mikro-orm/postgresql'
5
+ import { scanAuthorizedAttachments } from './lib/access-query'
6
+ import { Attachment, AttachmentPartition } from './data/entities'
2
7
  import { createAttachmentAccessContext } from './lib/access-runner'
3
8
  import { asFunction, asValue } from 'awilix'
4
9
  import type { AppContainer } from '@open-mercato/shared/lib/di/container'
@@ -19,8 +24,32 @@ import {
19
24
  } from './lib/documentStructure/service'
20
25
  import { enqueueDocumentStructureExtraction } from './lib/documentStructure/queue'
21
26
 
27
+ const attachmentRelationAccess: RelationOptionAccess = async ({ auth, container, tenantId, organizationId }) => {
28
+ const em = container.resolve<EntityManager>('em')
29
+ const scope = { tenantId, organizationId }
30
+ const partitions = await findWithDecryption(em, AttachmentPartition, {}, undefined, scope)
31
+ const deadline = Date.now() + 15_000
32
+ return {
33
+ authorizeIds: async (ids) => {
34
+ const { records } = await scanAuthorizedAttachments({
35
+ auth: { ...auth, tenantId, orgId: organizationId },
36
+ context: createAttachmentAccessContext(container),
37
+ partitions,
38
+ deadline,
39
+ loadBatch: (offset) => offset === 0
40
+ ? findWithDecryption(em, Attachment, { ...scope, id: { $in: ids } }, {
41
+ fields: ['id', 'entityId', 'recordId', 'partitionCode', 'tenantId', 'organizationId', 'fileName', 'mimeType', 'storageMetadata'],
42
+ }, scope)
43
+ : Promise.resolve([]),
44
+ })
45
+ return records.map((record) => record.id)
46
+ },
47
+ }
48
+ }
49
+
22
50
  export function register(container: AppContainer) {
23
51
  container.register({
52
+ [relationOptionAccessKey('attachments:attachment')]: asValue(attachmentRelationAccess),
24
53
  attachmentQuotaRecoveryScheduler: asValue(scheduleAttachmentQuotaRecovery),
25
54
  [DOCUMENT_STRUCTURE_ENGINES_DI_KEY]: asFunction(() => createDocumentStructureEngineRegistry()).singleton(),
26
55
  [ATTACHMENT_DOCUMENT_STRUCTURE_SERVICE_DI_KEY]: asScopedService((container) => (asFunction(({ em }: { em: ConstructorParameters<typeof StorageDriverFactory>[0] }) =>
@@ -121,7 +121,7 @@ export async function reindexProductsForCategorySubtree(
121
121
  tenantId: target.tenantId,
122
122
  organizationId: target.organizationId,
123
123
  },
124
- { persistent: true, deliverInline: false },
124
+ { persistent: true, deliverInline: false, tenantId: target.tenantId, organizationId: target.organizationId },
125
125
  )
126
126
  return { mode: 'reindex', productCount: productIds.length }
127
127
  }
@@ -133,7 +133,7 @@ export async function PATCH(req: Request, ctx: { params?: { dictionaryId?: strin
133
133
  DictionaryEntry,
134
134
  updatedEntryId,
135
135
  { populate: ['dictionary'] },
136
- { tenantId: context.auth.tenantId ?? null, organizationId: context.auth.orgId ?? null },
136
+ { tenantId: context.tenantId, organizationId: context.organizationId },
137
137
  )
138
138
  if (!updated) {
139
139
  throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_update_failed', 'Failed to update dictionary entry') })
@@ -204,6 +204,7 @@ export async function POST(req: Request, ctx: { params?: { dictionaryId?: string
204
204
  }
205
205
  const { dictionaryId } = paramsSchema.parse({ dictionaryId: ctx.params?.dictionaryId })
206
206
  const payload = createDictionaryEntrySchema.parse(await req.json().catch(() => ({})))
207
+ await loadDictionary(context, dictionaryId)
207
208
  const guardUserId = resolveDictionaryActorId(context.auth)
208
209
  const guardResult = await validateCrudMutationGuard(context.container, {
209
210
  tenantId: context.tenantId,
@@ -248,7 +249,7 @@ export async function POST(req: Request, ctx: { params?: { dictionaryId?: string
248
249
  DictionaryEntry,
249
250
  createdEntryId,
250
251
  { populate: ['dictionary'] },
251
- { tenantId: context.auth.tenantId ?? null, organizationId: context.auth.orgId ?? null },
252
+ { tenantId: context.tenantId, organizationId: context.organizationId },
252
253
  )
253
254
  if (!entry) {
254
255
  throw new CrudHttpError(500, { error: context.translate('dictionaries.errors.entry_create_failed', 'Failed to create dictionary entry') })
@@ -4,7 +4,7 @@ import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
4
4
  import { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'
5
5
  import { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'
6
6
  import { Organization } from '@open-mercato/core/modules/directory/data/entities'
7
- import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
7
+ import { CrudHttpError, forbidden } from '@open-mercato/shared/lib/crud/errors'
8
8
  import type { EntityManager } from '@mikro-orm/postgresql'
9
9
  import type { AwilixContainer } from 'awilix'
10
10
  import type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
@@ -41,6 +41,9 @@ export async function resolveDictionariesRouteContext(req: Request): Promise<Dic
41
41
  }
42
42
 
43
43
  const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })
44
+ if (scope?.selectionRejected) {
45
+ throw forbidden()
46
+ }
44
47
  const em = (container.resolve('em') as EntityManager)
45
48
  const tenantId: string = scope?.tenantId ?? auth.tenantId
46
49
  const organizationId = resolveSingleOrganizationIdOrDeny(scope, auth) ?? null
@@ -57,14 +60,14 @@ export async function resolveDictionariesRouteContext(req: Request): Promise<Dic
57
60
  if (normalized) candidateIds.add(normalized)
58
61
  }
59
62
 
60
- pushCandidate(organizationId)
61
- if (Array.isArray(scope?.filterIds)) {
63
+ const selectedOrganizationId = normalizeId(scope?.selectedId)
64
+ if (selectedOrganizationId) {
65
+ pushCandidate(selectedOrganizationId)
66
+ } else if (Array.isArray(scope?.filterIds)) {
62
67
  for (const id of scope.filterIds) pushCandidate(id)
68
+ } else if (organizationId) {
69
+ pushCandidate(organizationId)
63
70
  }
64
- if (Array.isArray(scope?.allowedIds)) {
65
- for (const id of scope.allowedIds) pushCandidate(id)
66
- }
67
- pushCandidate(auth.orgId ?? null)
68
71
 
69
72
  const readableOrganizationIds = new Set<string>()
70
73
  try {
@@ -101,7 +104,7 @@ export async function resolveDictionariesRouteContext(req: Request): Promise<Dic
101
104
  auth,
102
105
  organizationScope: scope,
103
106
  selectedOrganizationId: organizationId,
104
- organizationIds: scope?.filterIds ?? (auth.orgId ? [auth.orgId] : null),
107
+ organizationIds: scope?.filterIds ?? (organizationId ? [organizationId] : null),
105
108
  request: req,
106
109
  }
107
110
 
@@ -159,6 +159,7 @@ export async function POST(req: Request) {
159
159
  entrySortMode: resolveDictionaryEntrySortMode(dictionary.entrySortMode),
160
160
  createdAt: dictionary.createdAt,
161
161
  updatedAt: dictionary.updatedAt,
162
+ organizationId: dictionary.organizationId,
162
163
  }, { status: 201 })
163
164
  } catch (err) {
164
165
  if (isCrudHttpError(err)) {
@@ -8,13 +8,39 @@ import {
8
8
  ensureDictionaryEntryScope,
9
9
  registerDictionaryEntryCommands,
10
10
  } from '@open-mercato/core/modules/dictionaries/commands/factory'
11
- import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
11
+ import type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
12
+ import { CrudHttpError, forbidden } from '@open-mercato/shared/lib/crud/errors'
12
13
  import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
13
14
 
14
- async function ensureDictionary(em: EntityManager, id: string): Promise<Dictionary> {
15
+ function normalizeScopeId(value: unknown): string | null {
16
+ if (typeof value !== 'string') return null
17
+ const trimmed = value.trim()
18
+ return trimmed.length > 0 ? trimmed : null
19
+ }
20
+
21
+ function resolveSelectedOrganizationId(ctx: CommandRuntimeContext): string | null {
22
+ return normalizeScopeId(ctx.selectedOrganizationId ?? ctx.organizationScope?.selectedId ?? null)
23
+ }
24
+
25
+ function resolveContextTenantId(ctx: CommandRuntimeContext): string | null {
26
+ return normalizeScopeId(ctx.organizationScope?.tenantId ?? ctx.auth?.tenantId ?? null)
27
+ }
28
+
29
+ async function ensureDictionary(
30
+ em: EntityManager,
31
+ id: string,
32
+ ctx: CommandRuntimeContext,
33
+ ): Promise<Dictionary> {
34
+ if (ctx.organizationScope?.selectionRejected) {
35
+ throw forbidden()
36
+ }
37
+ const tenantId = resolveContextTenantId(ctx)
38
+ const organizationId = resolveSelectedOrganizationId(ctx)
15
39
  const dictionary = await em.findOne(Dictionary, {
16
40
  id,
17
41
  deletedAt: null,
42
+ ...(tenantId ? { tenantId } : {}),
43
+ ...(organizationId ? { organizationId } : {}),
18
44
  })
19
45
  if (!dictionary) {
20
46
  throw new CrudHttpError(404, { error: 'Dictionary not found' })
@@ -31,16 +57,27 @@ registerDictionaryEntryCommands({
31
57
  ensureScope: ensureDictionaryEntryScope,
32
58
  duplicateError: 'An entry with this value already exists.',
33
59
  resolveDictionaryForCreate: async ({ em, ctx, parsed }) => {
34
- const dictionary = await ensureDictionary(em, parsed.dictionaryId)
60
+ const dictionary = await ensureDictionary(em, parsed.dictionaryId, ctx)
35
61
  const scope = { tenantId: dictionary.tenantId, organizationId: dictionary.organizationId }
36
62
  ensureDictionaryEntryScope(ctx, scope)
37
63
  return { dictionary, scope }
38
64
  },
39
65
  resolveEntry: async ({ em, ctx, id }) => {
66
+ if (ctx.organizationScope?.selectionRejected) {
67
+ throw forbidden()
68
+ }
40
69
  const entry = await findOneWithDecryption(em, DictionaryEntry, id, { populate: ['dictionary'] })
41
70
  if (!entry) {
42
71
  throw new CrudHttpError(404, { error: 'Dictionary entry not found' })
43
72
  }
73
+ const tenantId = resolveContextTenantId(ctx)
74
+ const selectedOrganizationId = resolveSelectedOrganizationId(ctx)
75
+ if (
76
+ (tenantId && entry.tenantId !== tenantId) ||
77
+ (selectedOrganizationId && entry.organizationId !== selectedOrganizationId)
78
+ ) {
79
+ throw new CrudHttpError(404, { error: 'Dictionary entry not found' })
80
+ }
44
81
  if (entry.dictionary.deletedAt) {
45
82
  throw new CrudHttpError(404, { error: 'Dictionary not found' })
46
83
  }
@@ -5,12 +5,14 @@ import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
5
5
  import { CustomEntity } from '@open-mercato/core/modules/entities/data/entities'
6
6
  import type { CustomEntitySpec } from '@open-mercato/shared/modules/entities'
7
7
  import type { EntityManager } from '@mikro-orm/postgresql'
8
- import type { QueryEngine } from '@open-mercato/shared/lib/query/types'
8
+ import { SortDir, type QueryEngine, type QueryOptions } from '@open-mercato/shared/lib/query/types'
9
9
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
10
+ import { relationOptionAccessKey, type RelationOptionAccess } from '@open-mercato/shared/lib/query/relationOptionAccess'
11
+ import { Organization } from '@open-mercato/core/modules/directory/data/entities'
10
12
  import { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'
11
13
  import { listEntityMetadata } from '@open-mercato/shared/lib/db/entityMetadata'
12
14
  import { resolveRegisteredEntityTableName } from '@open-mercato/shared/lib/query/engine'
13
- import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
15
+ import { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
14
16
  import { createLogger } from '@open-mercato/shared/lib/logger'
15
17
  import { getModules, resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
16
18
  import { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
@@ -26,6 +28,13 @@ export const metadata = {
26
28
  }
27
29
 
28
30
  const ALLOWED_ROUTE_CONTEXT_FIELDS = new Set(['kind', 'entity_id', 'product_id'])
31
+ const RECORD_POLICY_TARGETS = new Map([
32
+ ['attachments', 'attachments:attachment'],
33
+ ['staff_time_entries', 'staff:staff_time_entry'],
34
+ ['staff_time_projects', 'staff:staff_time_project'],
35
+ ['staff_time_reports', 'staff:staff_time_report'],
36
+ ['staff_time_tasks', 'staff:staff_time_task'],
37
+ ])
29
38
  const DEFAULT_LABEL_FIELDS = ['name', 'title', 'code', 'email', 'id']
30
39
 
31
40
  const logger = createLogger('entities')
@@ -85,6 +94,10 @@ export async function GET(req: Request) {
85
94
  logger.warn('Relation options requested for an unresolvable entity id', { entityId })
86
95
  return NextResponse.json({ items: [] })
87
96
  }
97
+ const policyTarget = classification.kind === 'system' && registeredTable
98
+ ? RECORD_POLICY_TARGETS.get(registeredTable)
99
+ : undefined
100
+ if (policyTarget && policyTarget !== entityId) return forbidden()
88
101
 
89
102
  const rbac = container.resolve('rbacService') as RbacService
90
103
  if (classification.kind === 'custom' && !(await rbac.userHasAllFeatures(
@@ -107,6 +120,11 @@ export async function GET(req: Request) {
107
120
  throw error
108
121
  }
109
122
 
123
+ const resolveAccess = policyTarget
124
+ ? container.resolve<RelationOptionAccess>(relationOptionAccessKey(policyTarget), { allowUnregistered: true })
125
+ : undefined
126
+ if (policyTarget && !resolveAccess) return forbidden()
127
+
110
128
  const customEntity = await findOneWithDecryption(em, CustomEntity, {
111
129
  entityId,
112
130
  isActive: true,
@@ -150,7 +168,8 @@ export async function GET(req: Request) {
150
168
  else if (ids.length > 1) filters.id = { $in: ids }
151
169
  if (q) filters[labelField] = { $ilike: `%${escapeLikePattern(q)}%` }
152
170
  const fields = Array.from(new Set(['id', labelField, ...routeContextFields]))
153
- const res = await qe.query<Record<string, unknown>>(entityId, {
171
+ const pageSize = Math.min(ids.length || 50, 100)
172
+ const queryOptions: QueryOptions = {
154
173
  tenantId: scope.tenantId,
155
174
  ...(scope.organizationId
156
175
  ? { organizationId: scope.organizationId }
@@ -158,9 +177,72 @@ export async function GET(req: Request) {
158
177
  fields,
159
178
  filters,
160
179
  ...(classification.kind === 'custom' ? { forceCustomEntityStorage: true } : {}),
161
- page: { page: 1, pageSize: Math.min(ids.length || 50, 100) },
162
- })
163
- const items = (res.items || []).map((it: Record<string, unknown>) => {
180
+ page: { page: 1, pageSize },
181
+ }
182
+ let rows: Record<string, unknown>[]
183
+ if (resolveAccess) {
184
+ const tenantId = scope.tenantId
185
+ const organizationIds = scope.organizationId
186
+ ? [scope.organizationId]
187
+ : organizationScope.filterIds ?? (await findWithDecryption(
188
+ em, Organization, { tenant: tenantId, deletedAt: null }, { fields: ['id'] }, { tenantId },
189
+ )).map((organization) => organization.id)
190
+ rows = []
191
+ try {
192
+ for (const organizationId of organizationIds) {
193
+ if (requirement && !(await rbac.userHasAllFeatures(auth.sub, requirement.view, { tenantId, organizationId }))) continue
194
+ const access = await resolveAccess({ auth: scopedAuth, container, tenantId, organizationId })
195
+ if (!access) continue
196
+ const scopedOptions = {
197
+ ...queryOptions,
198
+ organizationId,
199
+ organizationIds: undefined,
200
+ omitAutomaticTenantOrgScope: true,
201
+ }
202
+ const scopeFilters = { tenant_id: tenantId, organization_id: organizationId }
203
+ const remaining = pageSize - rows.length
204
+ if (access.authorizeIds) {
205
+ const candidateFilters = ids.length ? { id: { $in: ids } } : {}
206
+ let lastId: string | undefined
207
+ while (rows.length < pageSize) {
208
+ const candidates = await qe.query<{ id: string }>(entityId, {
209
+ ...scopedOptions,
210
+ fields: ['id'],
211
+ filters: { $and: [scopeFilters, candidateFilters, ...(lastId ? [{ id: { $gt: lastId } }] : [])] },
212
+ sort: [{ field: 'id', dir: SortDir.Asc }],
213
+ page: { page: 1, pageSize: 100 },
214
+ })
215
+ if (candidates.items.length === 0) break
216
+ const authorizedIds = await access.authorizeIds(candidates.items.map(({ id }) => id))
217
+ if (authorizedIds.length) {
218
+ const result = await qe.query<Record<string, unknown>>(entityId, {
219
+ ...scopedOptions,
220
+ filters: { $and: [scopeFilters, filters, { id: { $in: authorizedIds } }] },
221
+ page: { page: 1, pageSize: pageSize - rows.length },
222
+ })
223
+ rows.push(...result.items)
224
+ }
225
+ if (candidates.items.length < 100) break
226
+ lastId = candidates.items.at(-1)?.id
227
+ }
228
+ } else if (access.filters) {
229
+ const result = await qe.query<Record<string, unknown>>(entityId, {
230
+ ...scopedOptions,
231
+ filters: { $and: [scopeFilters, filters, access.filters] },
232
+ page: { page: 1, pageSize: remaining },
233
+ })
234
+ rows.push(...result.items)
235
+ }
236
+ if (rows.length >= pageSize) break
237
+ }
238
+ } catch (error) {
239
+ if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status })
240
+ throw error
241
+ }
242
+ } else {
243
+ rows = (await qe.query<Record<string, unknown>>(entityId, queryOptions)).items ?? []
244
+ }
245
+ const items = rows.map((it) => {
164
246
  const routeContext = routeContextFields.reduce<Record<string, unknown>>((acc, field) => {
165
247
  if (it[field] !== undefined) {
166
248
  acc[field] = it[field]
@@ -183,7 +183,7 @@ export function createPaymentGatewayService(deps: PaymentGatewayServiceDeps) {
183
183
  throw new Error('Transaction is missing provider session id')
184
184
  }
185
185
 
186
- async function emitStatusEvent(status: UnifiedPaymentStatus, payload: Record<string, unknown>) {
186
+ async function emitStatusEvent(status: UnifiedPaymentStatus, payload: Record<string, unknown> & { tenantId: string; organizationId: string }) {
187
187
  type PaymentGatewayEventId = Parameters<typeof emitPaymentGatewayEvent>[0]
188
188
  const eventMap: Partial<Record<UnifiedPaymentStatus, PaymentGatewayEventId>> = {
189
189
  authorized: 'payment_gateways.payment.authorized',
@@ -194,7 +194,7 @@ export function createPaymentGatewayService(deps: PaymentGatewayServiceDeps) {
194
194
  }
195
195
  const eventId = eventMap[status]
196
196
  if (!eventId) return
197
- await emitPaymentGatewayEvent(eventId, payload)
197
+ await emitPaymentGatewayEvent(eventId, payload, { tenantId: payload.tenantId, organizationId: payload.organizationId })
198
198
  }
199
199
 
200
200
  async function writeTransactionLog(
@@ -58,7 +58,7 @@ export async function POST(req: Request) {
58
58
  await bus.emitEvent(
59
59
  'query_index.purge',
60
60
  { entityType, organizationId: auth.orgId, tenantId: auth.tenantId },
61
- { persistent: true, deliverInline: false },
61
+ { persistent: true, deliverInline: false, tenantId: auth.tenantId, organizationId: auth.orgId },
62
62
  )
63
63
  await recordIndexerLog(
64
64
  { em: em ?? undefined },
@@ -123,7 +123,7 @@ export async function POST(req: Request) {
123
123
  return bus.emitEvent(
124
124
  'query_index.reindex',
125
125
  payload,
126
- { persistent: true, deliverInline: false },
126
+ { persistent: true, deliverInline: false, tenantId: auth.tenantId, organizationId: auth.orgId },
127
127
  )
128
128
  }),
129
129
  )
@@ -1142,7 +1142,7 @@ const purge: ModuleCli = {
1142
1142
  await bus.emitEvent(
1143
1143
  'query_index.purge',
1144
1144
  { entityType: entity, organizationId: orgId, tenantId },
1145
- { persistent: true },
1145
+ { persistent: true, tenantId: tenantId ?? null, organizationId: orgId ?? null },
1146
1146
  )
1147
1147
  await recordIndexerLog(
1148
1148
  { em: em ?? undefined },
@@ -1165,7 +1165,7 @@ const purge: ModuleCli = {
1165
1165
  await bus.emitEvent(
1166
1166
  'query_index.purge',
1167
1167
  { entityType: id, organizationId: orgId, tenantId },
1168
- { persistent: true },
1168
+ { persistent: true, tenantId: tenantId ?? null, organizationId: orgId ?? null },
1169
1169
  )
1170
1170
  await recordIndexerLog(
1171
1171
  { em: em ?? undefined },
@@ -3066,7 +3066,11 @@ export class HybridQueryEngine implements QueryEngine {
3066
3066
 
3067
3067
  void Promise.resolve().then(async () => {
3068
3068
  try {
3069
- await bus.emitEvent('query_index.reindex', payload, { persistent: true })
3069
+ await bus.emitEvent('query_index.reindex', payload, {
3070
+ persistent: true,
3071
+ tenantId: payload.tenantId,
3072
+ organizationId: payload.organizationId,
3073
+ })
3070
3074
  if (this.isDebugVerbosity()) this.debug('query:auto-reindex:scheduled', context)
3071
3075
  } catch (err) {
3072
3076
  logger.warn('Failed to schedule auto reindex', { ...context, err })
@@ -1,4 +1,5 @@
1
1
  import type { EntityManager } from '@mikro-orm/postgresql'
2
+ import type { SubscriberContext } from '@open-mercato/events'
2
3
  import { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'
3
4
  import { recordIndexerLog } from '@open-mercato/shared/lib/indexers/status-log'
4
5
  import { refreshCoverageSnapshot } from '../lib/coverage'
@@ -6,12 +7,12 @@ import { purgeIndexScope } from '../lib/purge'
6
7
 
7
8
  export const metadata = { event: 'query_index.purge', persistent: true }
8
9
 
9
- export default async function handle(payload: any, ctx: { resolve: <T=any>(name: string) => T }) {
10
- const em = ctx.resolve<EntityManager>('em')
10
+ export default async function handle(payload: { entityType?: unknown }, ctx: SubscriberContext) {
11
11
  const entityType = String(payload?.entityType || '')
12
12
  if (!entityType) return
13
- const orgId = payload?.organizationId ?? null
14
- const tenantId = payload?.tenantId ?? null
13
+ if (!ctx.eventScope) throw new Error('[internal] Query index purge requires trusted event scope')
14
+ const { tenantId, organizationId: orgId = null } = ctx.eventScope
15
+ const em = ctx.resolve<EntityManager>('em')
15
16
 
16
17
  try {
17
18
  await recordIndexerLog(
@@ -1,4 +1,5 @@
1
1
  import type { EntityManager } from '@mikro-orm/postgresql'
2
+ import type { SubscriberContext } from '@open-mercato/events'
2
3
  import { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'
3
4
  import { recordIndexerLog } from '@open-mercato/shared/lib/indexers/status-log'
4
5
  import { reindexEntity } from '../lib/reindexer'
@@ -29,7 +30,17 @@ function forkReindexEntityManager(em: EntityManager): EntityManager {
29
30
  return fork.call(em, { clear: true, freshEventManager: true, useContext: false })
30
31
  }
31
32
 
32
- export default async function handle(payload: any, ctx: { resolve: <T=any>(name: string) => T }) {
33
+ export default async function handle(payload: Record<string, unknown>, ctx: SubscriberContext) {
34
+ const entityType = String(payload?.entityType || '')
35
+ if (!entityType) return
36
+ if (!ctx.eventScope) throw new Error('[internal] Query index reindex requires trusted event scope')
37
+ const allowAllTenants = ctx.eventScope.tenantId === null && ctx.eventScope.allowAllTenants === true
38
+ const { tenantId, organizationId } = resolveQueryIndexReindexScope({
39
+ tenantId: allowAllTenants ? undefined : ctx.eventScope.tenantId,
40
+ organizationId: ctx.eventScope.organizationId,
41
+ allowAllTenants,
42
+ })
43
+
33
44
  const em = forkReindexEntityManager(ctx.resolve<EntityManager>('em'))
34
45
  const eventBus = ctx.resolve<any>('eventBus')
35
46
  let vectorService: VectorIndexService | null = null
@@ -38,14 +49,10 @@ export default async function handle(payload: any, ctx: { resolve: <T=any>(name:
38
49
  } catch {
39
50
  vectorService = null
40
51
  }
41
- const entityType = String(payload?.entityType || '')
42
- if (!entityType) return
43
- let tenantId: string | null | undefined = payload?.tenantId
44
- let organizationId: string | null | undefined = payload?.organizationId
45
52
  const forceFull: boolean = Boolean(payload?.force)
46
53
  const batchSize = Number.isFinite(payload?.batchSize) ? Number(payload.batchSize) : undefined
47
- const partitionCount = Number.isFinite(payload?.partitionCount) ? Math.max(1, Math.trunc(payload.partitionCount)) : undefined
48
- const partitionIndex = Number.isFinite(payload?.partitionIndex) ? Math.max(0, Math.trunc(payload.partitionIndex)) : undefined
54
+ const partitionCount = Number.isFinite(payload?.partitionCount) ? Math.max(1, Math.trunc(Number(payload.partitionCount))) : undefined
55
+ const partitionIndex = Number.isFinite(payload?.partitionIndex) ? Math.max(0, Math.trunc(Number(payload.partitionIndex))) : undefined
49
56
  const resetCoverage = typeof payload?.resetCoverage === 'boolean' ? payload.resetCoverage : undefined
50
57
  const requestedByUserId = typeof payload?.requestedByUserId === 'string' ? payload.requestedByUserId : null
51
58
 
@@ -136,14 +143,6 @@ export default async function handle(payload: any, ctx: { resolve: <T=any>(name:
136
143
  }
137
144
 
138
145
  try {
139
- const resolvedScope = resolveQueryIndexReindexScope({
140
- tenantId: payload?.tenantId,
141
- organizationId: payload?.organizationId,
142
- allowAllTenants: payload?.allowAllTenants === true,
143
- })
144
- tenantId = resolvedScope.tenantId
145
- organizationId = resolvedScope.organizationId
146
-
147
146
  await recordIndexerLog(
148
147
  { em },
149
148
  {
@@ -39,6 +39,38 @@ async function hasManageAllFeature(context: InterceptorContext): Promise<boolean
39
39
  )
40
40
  }
41
41
 
42
+ export async function scopeTimeEntryList(
43
+ query: Record<string, unknown> | undefined,
44
+ context: InterceptorContext,
45
+ ) {
46
+ if (await hasManageAllFeature(context)) {
47
+ return { ok: true }
48
+ }
49
+
50
+ const staffMember = await getStaffMemberByUserId(
51
+ context.em,
52
+ context.userId,
53
+ context.tenantId ?? null,
54
+ context.organizationId ?? null,
55
+ )
56
+
57
+ if (!staffMember) {
58
+ return {
59
+ ok: false,
60
+ statusCode: 403,
61
+ message: 'User is not a staff member.',
62
+ }
63
+ }
64
+
65
+ return {
66
+ ok: true,
67
+ query: {
68
+ ...(query ?? {}),
69
+ staffMemberId: staffMember.id,
70
+ },
71
+ }
72
+ }
73
+
42
74
  export const interceptors: ApiInterceptor[] = [
43
75
  {
44
76
  id: 'staff.timesheets.self-scope-widget-data',
@@ -93,32 +125,7 @@ export const interceptors: ApiInterceptor[] = [
93
125
  methods: ['GET'],
94
126
  priority: 70,
95
127
  async before(request, context) {
96
- if (await hasManageAllFeature(context)) {
97
- return { ok: true }
98
- }
99
-
100
- const staffMember = await getStaffMemberByUserId(
101
- context.em,
102
- context.userId,
103
- context.tenantId ?? null,
104
- context.organizationId ?? null,
105
- )
106
-
107
- if (!staffMember) {
108
- return {
109
- ok: false,
110
- statusCode: 403,
111
- message: 'User is not a staff member.',
112
- }
113
- }
114
-
115
- return {
116
- ok: true,
117
- query: {
118
- ...(request.query ?? {}),
119
- staffMemberId: staffMember.id,
120
- },
121
- }
128
+ return scopeTimeEntryList(request.query, context)
122
129
  },
123
130
  },
124
131
  ]
@@ -1,4 +1,6 @@
1
1
  import { defineProcessDiRegistrar } from '@open-mercato/shared/lib/di/process-registrar'
2
+ import { relationOptionAccessKey, type RelationOptionAccess } from '@open-mercato/shared/lib/query/relationOptionAccess'
3
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
4
  import { asValue } from 'awilix'
3
5
  import type { AppContainer } from '@open-mercato/shared/lib/di/container'
4
6
  import {
@@ -98,6 +100,28 @@ export type ProjectCodeResolver = {
98
100
  generate(name: string, taken: Set<string>, ctx?: ProjectCodeContext | null): string
99
101
  }
100
102
 
103
+ const timeEntryRelationAccess: RelationOptionAccess = async ({ auth, container, tenantId, organizationId }) => {
104
+ const { scopeTimeEntryList } = await import('./api/interceptors')
105
+ const scoped = await scopeTimeEntryList(undefined, {
106
+ userId: auth.sub,
107
+ tenantId,
108
+ organizationId,
109
+ container,
110
+ em: container.resolve<EntityManager>('em'),
111
+ })
112
+ if (!scoped.ok) return null
113
+ const { buildScopedTimeEntryListFilters } = await import('./api/timesheets/time-entries/route')
114
+ return {
115
+ filters: await buildScopedTimeEntryListFilters({ page: 1, pageSize: 50, staffMemberId: scoped.query?.staffMemberId }, {
116
+ auth: { ...auth, tenantId, orgId: organizationId },
117
+ container,
118
+ organizationScope: null,
119
+ selectedOrganizationId: organizationId,
120
+ organizationIds: [organizationId],
121
+ }),
122
+ }
123
+ }
124
+
101
125
  export function register(container: AppContainer) {
102
126
  const resolver: AvailabilityAccessResolver = { resolveAvailabilityWriteAccess }
103
127
  const timeTrackingResolver: TimeTrackingAccessResolver = { resolveProjectAccess }
@@ -116,6 +140,7 @@ export function register(container: AppContainer) {
116
140
  generate: (name, taken, ctx) => deriveProjectCode(name, taken, ctx ?? undefined),
117
141
  }
118
142
  container.register({
143
+ [relationOptionAccessKey('staff:staff_time_entry')]: asValue(timeEntryRelationAccess),
119
144
  availabilityAccessResolver: asValue(resolver),
120
145
  timeTrackingAccessResolver: asValue(timeTrackingResolver),
121
146
  timeRoundingResolver: asValue(timeRoundingResolver),