@open-mercato/core 0.11.1-develop.8572.1.85986dc508 → 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.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/attachments/di.js +25 -0
- package/dist/modules/attachments/di.js.map +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +1 -1
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +2 -1
- package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
- package/dist/modules/dictionaries/api/context.js +11 -8
- package/dist/modules/dictionaries/api/context.js.map +2 -2
- package/dist/modules/dictionaries/api/route.js +2 -1
- package/dist/modules/dictionaries/api/route.js.map +2 -2
- package/dist/modules/dictionaries/commands/entries.js +30 -4
- package/dist/modules/dictionaries/commands/entries.js.map +2 -2
- package/dist/modules/entities/api/relations/options.js +85 -5
- package/dist/modules/entities/api/relations/options.js.map +2 -2
- package/dist/modules/staff/api/interceptors.js +28 -24
- package/dist/modules/staff/api/interceptors.js.map +2 -2
- package/dist/modules/staff/di.js +23 -0
- package/dist/modules/staff/di.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/attachments/di.ts +29 -0
- package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +1 -1
- package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +2 -1
- package/src/modules/dictionaries/api/context.ts +11 -8
- package/src/modules/dictionaries/api/route.ts +1 -0
- package/src/modules/dictionaries/commands/entries.ts +40 -3
- package/src/modules/entities/api/relations/options.ts +88 -6
- package/src/modules/staff/api/interceptors.ts +33 -26
- package/src/modules/staff/di.ts +25 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/dictionaries/commands/entries.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport {\n dictionaryEntryCommandCreateSchema,\n dictionaryEntryCommandUpdateSchema,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport {\n ensureDictionaryEntryScope,\n registerDictionaryEntryCommands,\n} from '@open-mercato/core/modules/dictionaries/commands/factory'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nasync function ensureDictionary(em: EntityManager
|
|
5
|
-
"mappings": "AACA,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Dictionary, DictionaryEntry } from '@open-mercato/core/modules/dictionaries/data/entities'\nimport {\n dictionaryEntryCommandCreateSchema,\n dictionaryEntryCommandUpdateSchema,\n} from '@open-mercato/core/modules/dictionaries/data/validators'\nimport {\n ensureDictionaryEntryScope,\n registerDictionaryEntryCommands,\n} from '@open-mercato/core/modules/dictionaries/commands/factory'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { CrudHttpError, forbidden } from '@open-mercato/shared/lib/crud/errors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nfunction normalizeScopeId(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction resolveSelectedOrganizationId(ctx: CommandRuntimeContext): string | null {\n return normalizeScopeId(ctx.selectedOrganizationId ?? ctx.organizationScope?.selectedId ?? null)\n}\n\nfunction resolveContextTenantId(ctx: CommandRuntimeContext): string | null {\n return normalizeScopeId(ctx.organizationScope?.tenantId ?? ctx.auth?.tenantId ?? null)\n}\n\nasync function ensureDictionary(\n em: EntityManager,\n id: string,\n ctx: CommandRuntimeContext,\n): Promise<Dictionary> {\n if (ctx.organizationScope?.selectionRejected) {\n throw forbidden()\n }\n const tenantId = resolveContextTenantId(ctx)\n const organizationId = resolveSelectedOrganizationId(ctx)\n const dictionary = await em.findOne(Dictionary, {\n id,\n deletedAt: null,\n ...(tenantId ? { tenantId } : {}),\n ...(organizationId ? { organizationId } : {}),\n })\n if (!dictionary) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n return dictionary\n}\n\nregisterDictionaryEntryCommands({\n commandPrefix: 'dictionaries.entries',\n resourceKind: 'dictionaries.entry',\n translationKeyPrefix: 'dictionaries.entries',\n createSchema: dictionaryEntryCommandCreateSchema,\n updateSchema: dictionaryEntryCommandUpdateSchema,\n ensureScope: ensureDictionaryEntryScope,\n duplicateError: 'An entry with this value already exists.',\n resolveDictionaryForCreate: async ({ em, ctx, parsed }) => {\n const dictionary = await ensureDictionary(em, parsed.dictionaryId, ctx)\n const scope = { tenantId: dictionary.tenantId, organizationId: dictionary.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n return { dictionary, scope }\n },\n resolveEntry: async ({ em, ctx, id }) => {\n if (ctx.organizationScope?.selectionRejected) {\n throw forbidden()\n }\n const entry = await findOneWithDecryption(em, DictionaryEntry, id, { populate: ['dictionary'] })\n if (!entry) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n const tenantId = resolveContextTenantId(ctx)\n const selectedOrganizationId = resolveSelectedOrganizationId(ctx)\n if (\n (tenantId && entry.tenantId !== tenantId) ||\n (selectedOrganizationId && entry.organizationId !== selectedOrganizationId)\n ) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n if (entry.dictionary.deletedAt) {\n throw new CrudHttpError(404, { error: 'Dictionary not found' })\n }\n const scope = { tenantId: entry.tenantId, organizationId: entry.organizationId }\n ensureDictionaryEntryScope(ctx, scope)\n return { entry, dictionary: entry.dictionary, scope }\n },\n ensureDictionaryForUndo: async ({ em, snapshot }) => {\n return em.findOne(Dictionary, snapshot.dictionaryId, { filters: false })\n },\n})\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,YAAY,uBAAuB;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,eAAe,iBAAiB;AACzC,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB,OAA+B;AACvD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,8BAA8B,KAA2C;AAChF,SAAO,iBAAiB,IAAI,0BAA0B,IAAI,mBAAmB,cAAc,IAAI;AACjG;AAEA,SAAS,uBAAuB,KAA2C;AACzE,SAAO,iBAAiB,IAAI,mBAAmB,YAAY,IAAI,MAAM,YAAY,IAAI;AACvF;AAEA,eAAe,iBACb,IACA,IACA,KACqB;AACrB,MAAI,IAAI,mBAAmB,mBAAmB;AAC5C,UAAM,UAAU;AAAA,EAClB;AACA,QAAM,WAAW,uBAAuB,GAAG;AAC3C,QAAM,iBAAiB,8BAA8B,GAAG;AACxD,QAAM,aAAa,MAAM,GAAG,QAAQ,YAAY;AAAA,IAC9C;AAAA,IACA,WAAW;AAAA,IACX,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,IAC/B,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC;AAAA,EAC7C,CAAC;AACD,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,uBAAuB,CAAC;AAAA,EAChE;AACA,SAAO;AACT;AAEA,gCAAgC;AAAA,EAC9B,eAAe;AAAA,EACf,cAAc;AAAA,EACd,sBAAsB;AAAA,EACtB,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,4BAA4B,OAAO,EA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|
4
4
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
5
5
|
import { CustomEntity } from "@open-mercato/core/modules/entities/data/entities";
|
|
6
|
+
import { SortDir } from "@open-mercato/shared/lib/query/types";
|
|
7
|
+
import { relationOptionAccessKey } from "@open-mercato/shared/lib/query/relationOptionAccess";
|
|
8
|
+
import { Organization } from "@open-mercato/core/modules/directory/data/entities";
|
|
6
9
|
import { escapeLikePattern } from "@open-mercato/shared/lib/db/escapeLikePattern";
|
|
7
10
|
import { listEntityMetadata } from "@open-mercato/shared/lib/db/entityMetadata";
|
|
8
11
|
import { resolveRegisteredEntityTableName } from "@open-mercato/shared/lib/query/engine";
|
|
9
|
-
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
12
|
+
import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
10
13
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
11
14
|
import { getModules, resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
12
15
|
import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
@@ -19,6 +22,13 @@ const metadata = {
|
|
|
19
22
|
GET: { requireAuth: true, requireFeatures: ["entities.definitions.view"] }
|
|
20
23
|
};
|
|
21
24
|
const ALLOWED_ROUTE_CONTEXT_FIELDS = /* @__PURE__ */ new Set(["kind", "entity_id", "product_id"]);
|
|
25
|
+
const RECORD_POLICY_TARGETS = /* @__PURE__ */ new Map([
|
|
26
|
+
["attachments", "attachments:attachment"],
|
|
27
|
+
["staff_time_entries", "staff:staff_time_entry"],
|
|
28
|
+
["staff_time_projects", "staff:staff_time_project"],
|
|
29
|
+
["staff_time_reports", "staff:staff_time_report"],
|
|
30
|
+
["staff_time_tasks", "staff:staff_time_task"]
|
|
31
|
+
]);
|
|
22
32
|
const DEFAULT_LABEL_FIELDS = ["name", "title", "code", "email", "id"];
|
|
23
33
|
const logger = createLogger("entities");
|
|
24
34
|
async function GET(req) {
|
|
@@ -67,6 +77,8 @@ async function GET(req) {
|
|
|
67
77
|
logger.warn("Relation options requested for an unresolvable entity id", { entityId });
|
|
68
78
|
return NextResponse.json({ items: [] });
|
|
69
79
|
}
|
|
80
|
+
const policyTarget = classification.kind === "system" && registeredTable ? RECORD_POLICY_TARGETS.get(registeredTable) : void 0;
|
|
81
|
+
if (policyTarget && policyTarget !== entityId) return forbidden();
|
|
70
82
|
const rbac = container.resolve("rbacService");
|
|
71
83
|
if (classification.kind === "custom" && !await rbac.userHasAllFeatures(
|
|
72
84
|
auth.sub,
|
|
@@ -86,6 +98,8 @@ async function GET(req) {
|
|
|
86
98
|
if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status });
|
|
87
99
|
throw error;
|
|
88
100
|
}
|
|
101
|
+
const resolveAccess = policyTarget ? container.resolve(relationOptionAccessKey(policyTarget), { allowUnregistered: true }) : void 0;
|
|
102
|
+
if (policyTarget && !resolveAccess) return forbidden();
|
|
89
103
|
const customEntity = await findOneWithDecryption(em, CustomEntity, {
|
|
90
104
|
entityId,
|
|
91
105
|
isActive: true,
|
|
@@ -119,15 +133,81 @@ async function GET(req) {
|
|
|
119
133
|
else if (ids.length > 1) filters.id = { $in: ids };
|
|
120
134
|
if (q) filters[labelField] = { $ilike: `%${escapeLikePattern(q)}%` };
|
|
121
135
|
const fields = Array.from(/* @__PURE__ */ new Set(["id", labelField, ...routeContextFields]));
|
|
122
|
-
const
|
|
136
|
+
const pageSize = Math.min(ids.length || 50, 100);
|
|
137
|
+
const queryOptions = {
|
|
123
138
|
tenantId: scope.tenantId,
|
|
124
139
|
...scope.organizationId ? { organizationId: scope.organizationId } : Array.isArray(organizationScope.filterIds) ? { organizationIds: organizationScope.filterIds } : {},
|
|
125
140
|
fields,
|
|
126
141
|
filters,
|
|
127
142
|
...classification.kind === "custom" ? { forceCustomEntityStorage: true } : {},
|
|
128
|
-
page: { page: 1, pageSize
|
|
129
|
-
}
|
|
130
|
-
|
|
143
|
+
page: { page: 1, pageSize }
|
|
144
|
+
};
|
|
145
|
+
let rows;
|
|
146
|
+
if (resolveAccess) {
|
|
147
|
+
const tenantId = scope.tenantId;
|
|
148
|
+
const organizationIds = scope.organizationId ? [scope.organizationId] : organizationScope.filterIds ?? (await findWithDecryption(
|
|
149
|
+
em,
|
|
150
|
+
Organization,
|
|
151
|
+
{ tenant: tenantId, deletedAt: null },
|
|
152
|
+
{ fields: ["id"] },
|
|
153
|
+
{ tenantId }
|
|
154
|
+
)).map((organization) => organization.id);
|
|
155
|
+
rows = [];
|
|
156
|
+
try {
|
|
157
|
+
for (const organizationId of organizationIds) {
|
|
158
|
+
if (requirement && !await rbac.userHasAllFeatures(auth.sub, requirement.view, { tenantId, organizationId })) continue;
|
|
159
|
+
const access = await resolveAccess({ auth: scopedAuth, container, tenantId, organizationId });
|
|
160
|
+
if (!access) continue;
|
|
161
|
+
const scopedOptions = {
|
|
162
|
+
...queryOptions,
|
|
163
|
+
organizationId,
|
|
164
|
+
organizationIds: void 0,
|
|
165
|
+
omitAutomaticTenantOrgScope: true
|
|
166
|
+
};
|
|
167
|
+
const scopeFilters = { tenant_id: tenantId, organization_id: organizationId };
|
|
168
|
+
const remaining = pageSize - rows.length;
|
|
169
|
+
if (access.authorizeIds) {
|
|
170
|
+
const candidateFilters = ids.length ? { id: { $in: ids } } : {};
|
|
171
|
+
let lastId;
|
|
172
|
+
while (rows.length < pageSize) {
|
|
173
|
+
const candidates = await qe.query(entityId, {
|
|
174
|
+
...scopedOptions,
|
|
175
|
+
fields: ["id"],
|
|
176
|
+
filters: { $and: [scopeFilters, candidateFilters, ...lastId ? [{ id: { $gt: lastId } }] : []] },
|
|
177
|
+
sort: [{ field: "id", dir: SortDir.Asc }],
|
|
178
|
+
page: { page: 1, pageSize: 100 }
|
|
179
|
+
});
|
|
180
|
+
if (candidates.items.length === 0) break;
|
|
181
|
+
const authorizedIds = await access.authorizeIds(candidates.items.map(({ id }) => id));
|
|
182
|
+
if (authorizedIds.length) {
|
|
183
|
+
const result = await qe.query(entityId, {
|
|
184
|
+
...scopedOptions,
|
|
185
|
+
filters: { $and: [scopeFilters, filters, { id: { $in: authorizedIds } }] },
|
|
186
|
+
page: { page: 1, pageSize: pageSize - rows.length }
|
|
187
|
+
});
|
|
188
|
+
rows.push(...result.items);
|
|
189
|
+
}
|
|
190
|
+
if (candidates.items.length < 100) break;
|
|
191
|
+
lastId = candidates.items.at(-1)?.id;
|
|
192
|
+
}
|
|
193
|
+
} else if (access.filters) {
|
|
194
|
+
const result = await qe.query(entityId, {
|
|
195
|
+
...scopedOptions,
|
|
196
|
+
filters: { $and: [scopeFilters, filters, access.filters] },
|
|
197
|
+
page: { page: 1, pageSize: remaining }
|
|
198
|
+
});
|
|
199
|
+
rows.push(...result.items);
|
|
200
|
+
}
|
|
201
|
+
if (rows.length >= pageSize) break;
|
|
202
|
+
}
|
|
203
|
+
} catch (error) {
|
|
204
|
+
if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status });
|
|
205
|
+
throw error;
|
|
206
|
+
}
|
|
207
|
+
} else {
|
|
208
|
+
rows = (await qe.query(entityId, queryOptions)).items ?? [];
|
|
209
|
+
}
|
|
210
|
+
const items = rows.map((it) => {
|
|
131
211
|
const routeContext = routeContextFields.reduce((acc, field) => {
|
|
132
212
|
if (it[field] !== void 0) {
|
|
133
213
|
acc[field] = it[field];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/entities/api/relations/options.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { CustomEntity } from '@open-mercato/core/modules/entities/data/entities'\nimport type { CustomEntitySpec } from '@open-mercato/shared/modules/entities'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { listEntityMetadata } from '@open-mercato/shared/lib/db/entityMetadata'\nimport { resolveRegisteredEntityTableName } from '@open-mercato/shared/lib/query/engine'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getModules, resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { classifyRecordsEntity } from '../../lib/entityClassification'\nimport { assertEntityAclForRequest, resolveEntityAclRequirement } from '../../lib/entityAcl'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { getSelectedOrganizationFromRequest, resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { isAllOrganizationsSelection } from '@open-mercato/core/modules/directory/constants'\nimport { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['entities.definitions.view'] },\n}\n\nconst ALLOWED_ROUTE_CONTEXT_FIELDS = new Set(['kind', 'entity_id', 'product_id'])\nconst DEFAULT_LABEL_FIELDS = ['name', 'title', 'code', 'email', 'id']\n\nconst logger = createLogger('entities')\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const entityId = url.searchParams.get('entityId') || ''\n const requestedLabelField = url.searchParams.get('labelField') || ''\n const q = url.searchParams.get('q') || ''\n const ids = Array.from(\n new Set(\n (url.searchParams.get('ids') || '')\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0),\n ),\n )\n const routeContextFields = Array.from(\n new Set(\n (url.searchParams.get('routeContextFields') || '')\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => ALLOWED_ROUTE_CONTEXT_FIELDS.has(entry)),\n ),\n )\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n if (!entityId) return NextResponse.json({ items: [] })\n const parsed = relationOptionsQuerySchema.safeParse({\n entityId,\n labelField: requestedLabelField,\n q,\n ids: url.searchParams.get('ids') ?? undefined,\n routeContextFields: url.searchParams.get('routeContextFields') ?? undefined,\n })\n if (!parsed.success) return NextResponse.json({ error: translate('api.errors.badRequest', 'Bad request') }, { status: 400 })\n\n const container = await createRequestContainer()\n const qe = container.resolve('queryEngine') as QueryEngine\n const em = container.resolve('em') as EntityManager\n\n const organizationScope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const forbidden = () => NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })\n if (!organizationScope.tenantId || organizationScope.selectionRejected || isExplicitlyEmptyOrganizationScope(organizationScope)) return forbidden()\n const requestedOrganizationId = getSelectedOrganizationFromRequest(req)?.trim()\n if (requestedOrganizationId && !isAllOrganizationsSelection(requestedOrganizationId) && organizationScope.selectedId !== requestedOrganizationId) return forbidden()\n const scope = { tenantId: organizationScope.tenantId, organizationId: organizationScope.selectedId }\n const scopedAuth = { ...auth, tenantId: scope.tenantId, orgId: scope.organizationId }\n const classification = await classifyRecordsEntity(em, entityId, scope)\n const declared = getModules().flatMap((entry) => entry.customEntities ?? []).find((entry) => entry.id === entityId) as CustomEntitySpec | undefined\n const requirement = resolveEntityAclRequirement(entityId)\n const registeredTable = resolveRegisteredEntityTableName(em, entityId)\n\n if (requirement?.platformOnly || (classification.kind === 'system' && !requirement && !declared)) return forbidden()\n if (classification.kind === 'unknown' || (classification.kind === 'system' && !registeredTable)) {\n logger.warn('Relation options requested for an unresolvable entity id', { entityId })\n return NextResponse.json({ items: [] })\n }\n\n const rbac = container.resolve('rbacService') as RbacService\n if (classification.kind === 'custom' && !(await rbac.userHasAllFeatures(\n auth.sub,\n ['entities.records.view'],\n scope,\n ))) return forbidden()\n\n try {\n await assertEntityAclForRequest({\n auth: scopedAuth,\n entityId,\n action: 'view',\n isCustomEntity: classification.kind === 'custom',\n isRestricted: classification.restricted || declared?.accessRestricted === true,\n rbac,\n })\n } catch (error) {\n if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status })\n throw error\n }\n\n const customEntity = await findOneWithDecryption(em, CustomEntity, {\n entityId,\n isActive: true,\n deletedAt: null,\n $or: [\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n { tenantId: scope.tenantId, organizationId: null },\n { tenantId: null, organizationId: null },\n ],\n }, { orderBy: { tenantId: 'desc nulls last', organizationId: 'desc nulls last' } }, scope)\n const declaredLabel = declared?.labelField\n const configuredLabel = classification.kind === 'custom' ? customEntity?.labelField : undefined\n const labelCandidates = [declaredLabel, configuredLabel, ...DEFAULT_LABEL_FIELDS]\n .filter((field): field is string => Boolean(field))\n const metadata = registeredTable\n ? listEntityMetadata(em).find((entry) => entry.tableName === registeredTable)\n : undefined\n const columnsByLabel = new Map<string, string>()\n for (const property of Object.values(metadata?.properties ?? {})) {\n if (property.fieldNames?.length !== 1) continue\n const [column] = property.fieldNames\n if (!labelCandidates.includes(property.name) && !labelCandidates.includes(column)) continue\n columnsByLabel.set(property.name, column)\n columnsByLabel.set(column, column)\n }\n const customLabelAliases = classification.kind === 'custom'\n ? labelCandidates.map((field) => field.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase())\n : []\n if (requestedLabelField && !labelCandidates.includes(requestedLabelField) &&\n !columnsByLabel.has(requestedLabelField) && !customLabelAliases.includes(requestedLabelField)) {\n return NextResponse.json({ error: translate('api.errors.badRequest', 'Bad request') }, { status: 400 })\n }\n const systemLabel = [requestedLabelField, ...labelCandidates]\n .map((field) => columnsByLabel.get(field))\n .find((column) => column !== undefined)\n const labelField = classification.kind === 'custom'\n ? requestedLabelField || configuredLabel || declaredLabel || 'id'\n : systemLabel ?? 'id'\n const filters: Record<string, unknown> = {}\n if (ids.length === 1) filters.id = ids[0]\n else if (ids.length > 1) filters.id = { $in: ids }\n if (q) filters[labelField] = { $ilike: `%${escapeLikePattern(q)}%` }\n const fields = Array.from(new Set(['id', labelField, ...routeContextFields]))\n const res = await qe.query<Record<string, unknown>>(entityId, {\n tenantId: scope.tenantId,\n ...(scope.organizationId\n ? { organizationId: scope.organizationId }\n : Array.isArray(organizationScope.filterIds) ? { organizationIds: organizationScope.filterIds } : {}),\n fields,\n filters,\n ...(classification.kind === 'custom' ? { forceCustomEntityStorage: true } : {}),\n page: { page: 1, pageSize: Math.min(ids.length || 50, 100) },\n })\n const items = (res.items || []).map((it: Record<string, unknown>) => {\n const routeContext = routeContextFields.reduce<Record<string, unknown>>((acc, field) => {\n if (it[field] !== undefined) {\n acc[field] = it[field]\n }\n return acc\n }, {})\n return {\n value: String(it.id),\n label: String(it[labelField] ?? it.id),\n ...(Object.keys(routeContext).length > 0 ? { routeContext } : {}),\n }\n })\n return NextResponse.json({ items })\n}\n\nconst relationOptionsQuerySchema = z.object({\n entityId: z.string().min(1),\n labelField: z.string().optional(),\n q: z.string().optional(),\n ids: z.string().optional(),\n routeContextFields: z.string().optional(),\n})\n\nconst relationOptionsResponseSchema = z.object({\n items: z.array(\n z.object({\n value: z.string(),\n label: z.string(),\n routeContext: z.record(z.string(), z.unknown()).optional(),\n })\n ),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Relation options lookup',\n methods: {\n GET: {\n summary: 'List relation options',\n description: 'Returns up to 100 option entries for populating relation dropdowns, requiring target read access and accepting only declared or fixed safe label fields. An entityId that matches neither an active custom entity nor a registered ORM entity yields an empty option list.',\n query: relationOptionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Option list',\n schema: relationOptionsResponseSchema,\n },\n {\n status: 400,\n description: 'Unsafe label selector',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 403,\n description: 'Target entity access denied',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { CustomEntity } from '@open-mercato/core/modules/entities/data/entities'\nimport type { CustomEntitySpec } from '@open-mercato/shared/modules/entities'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { SortDir, type QueryEngine, type QueryOptions } from '@open-mercato/shared/lib/query/types'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { relationOptionAccessKey, type RelationOptionAccess } from '@open-mercato/shared/lib/query/relationOptionAccess'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { listEntityMetadata } from '@open-mercato/shared/lib/db/entityMetadata'\nimport { resolveRegisteredEntityTableName } from '@open-mercato/shared/lib/query/engine'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getModules, resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { classifyRecordsEntity } from '../../lib/entityClassification'\nimport { assertEntityAclForRequest, resolveEntityAclRequirement } from '../../lib/entityAcl'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { getSelectedOrganizationFromRequest, resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { isAllOrganizationsSelection } from '@open-mercato/core/modules/directory/constants'\nimport { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['entities.definitions.view'] },\n}\n\nconst ALLOWED_ROUTE_CONTEXT_FIELDS = new Set(['kind', 'entity_id', 'product_id'])\nconst RECORD_POLICY_TARGETS = new Map([\n ['attachments', 'attachments:attachment'],\n ['staff_time_entries', 'staff:staff_time_entry'],\n ['staff_time_projects', 'staff:staff_time_project'],\n ['staff_time_reports', 'staff:staff_time_report'],\n ['staff_time_tasks', 'staff:staff_time_task'],\n])\nconst DEFAULT_LABEL_FIELDS = ['name', 'title', 'code', 'email', 'id']\n\nconst logger = createLogger('entities')\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const entityId = url.searchParams.get('entityId') || ''\n const requestedLabelField = url.searchParams.get('labelField') || ''\n const q = url.searchParams.get('q') || ''\n const ids = Array.from(\n new Set(\n (url.searchParams.get('ids') || '')\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0),\n ),\n )\n const routeContextFields = Array.from(\n new Set(\n (url.searchParams.get('routeContextFields') || '')\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => ALLOWED_ROUTE_CONTEXT_FIELDS.has(entry)),\n ),\n )\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n if (!entityId) return NextResponse.json({ items: [] })\n const parsed = relationOptionsQuerySchema.safeParse({\n entityId,\n labelField: requestedLabelField,\n q,\n ids: url.searchParams.get('ids') ?? undefined,\n routeContextFields: url.searchParams.get('routeContextFields') ?? undefined,\n })\n if (!parsed.success) return NextResponse.json({ error: translate('api.errors.badRequest', 'Bad request') }, { status: 400 })\n\n const container = await createRequestContainer()\n const qe = container.resolve('queryEngine') as QueryEngine\n const em = container.resolve('em') as EntityManager\n\n const organizationScope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const forbidden = () => NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })\n if (!organizationScope.tenantId || organizationScope.selectionRejected || isExplicitlyEmptyOrganizationScope(organizationScope)) return forbidden()\n const requestedOrganizationId = getSelectedOrganizationFromRequest(req)?.trim()\n if (requestedOrganizationId && !isAllOrganizationsSelection(requestedOrganizationId) && organizationScope.selectedId !== requestedOrganizationId) return forbidden()\n const scope = { tenantId: organizationScope.tenantId, organizationId: organizationScope.selectedId }\n const scopedAuth = { ...auth, tenantId: scope.tenantId, orgId: scope.organizationId }\n const classification = await classifyRecordsEntity(em, entityId, scope)\n const declared = getModules().flatMap((entry) => entry.customEntities ?? []).find((entry) => entry.id === entityId) as CustomEntitySpec | undefined\n const requirement = resolveEntityAclRequirement(entityId)\n const registeredTable = resolveRegisteredEntityTableName(em, entityId)\n\n if (requirement?.platformOnly || (classification.kind === 'system' && !requirement && !declared)) return forbidden()\n if (classification.kind === 'unknown' || (classification.kind === 'system' && !registeredTable)) {\n logger.warn('Relation options requested for an unresolvable entity id', { entityId })\n return NextResponse.json({ items: [] })\n }\n const policyTarget = classification.kind === 'system' && registeredTable\n ? RECORD_POLICY_TARGETS.get(registeredTable)\n : undefined\n if (policyTarget && policyTarget !== entityId) return forbidden()\n\n const rbac = container.resolve('rbacService') as RbacService\n if (classification.kind === 'custom' && !(await rbac.userHasAllFeatures(\n auth.sub,\n ['entities.records.view'],\n scope,\n ))) return forbidden()\n\n try {\n await assertEntityAclForRequest({\n auth: scopedAuth,\n entityId,\n action: 'view',\n isCustomEntity: classification.kind === 'custom',\n isRestricted: classification.restricted || declared?.accessRestricted === true,\n rbac,\n })\n } catch (error) {\n if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status })\n throw error\n }\n\n const resolveAccess = policyTarget\n ? container.resolve<RelationOptionAccess>(relationOptionAccessKey(policyTarget), { allowUnregistered: true })\n : undefined\n if (policyTarget && !resolveAccess) return forbidden()\n\n const customEntity = await findOneWithDecryption(em, CustomEntity, {\n entityId,\n isActive: true,\n deletedAt: null,\n $or: [\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n { tenantId: scope.tenantId, organizationId: null },\n { tenantId: null, organizationId: null },\n ],\n }, { orderBy: { tenantId: 'desc nulls last', organizationId: 'desc nulls last' } }, scope)\n const declaredLabel = declared?.labelField\n const configuredLabel = classification.kind === 'custom' ? customEntity?.labelField : undefined\n const labelCandidates = [declaredLabel, configuredLabel, ...DEFAULT_LABEL_FIELDS]\n .filter((field): field is string => Boolean(field))\n const metadata = registeredTable\n ? listEntityMetadata(em).find((entry) => entry.tableName === registeredTable)\n : undefined\n const columnsByLabel = new Map<string, string>()\n for (const property of Object.values(metadata?.properties ?? {})) {\n if (property.fieldNames?.length !== 1) continue\n const [column] = property.fieldNames\n if (!labelCandidates.includes(property.name) && !labelCandidates.includes(column)) continue\n columnsByLabel.set(property.name, column)\n columnsByLabel.set(column, column)\n }\n const customLabelAliases = classification.kind === 'custom'\n ? labelCandidates.map((field) => field.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase())\n : []\n if (requestedLabelField && !labelCandidates.includes(requestedLabelField) &&\n !columnsByLabel.has(requestedLabelField) && !customLabelAliases.includes(requestedLabelField)) {\n return NextResponse.json({ error: translate('api.errors.badRequest', 'Bad request') }, { status: 400 })\n }\n const systemLabel = [requestedLabelField, ...labelCandidates]\n .map((field) => columnsByLabel.get(field))\n .find((column) => column !== undefined)\n const labelField = classification.kind === 'custom'\n ? requestedLabelField || configuredLabel || declaredLabel || 'id'\n : systemLabel ?? 'id'\n const filters: Record<string, unknown> = {}\n if (ids.length === 1) filters.id = ids[0]\n else if (ids.length > 1) filters.id = { $in: ids }\n if (q) filters[labelField] = { $ilike: `%${escapeLikePattern(q)}%` }\n const fields = Array.from(new Set(['id', labelField, ...routeContextFields]))\n const pageSize = Math.min(ids.length || 50, 100)\n const queryOptions: QueryOptions = {\n tenantId: scope.tenantId,\n ...(scope.organizationId\n ? { organizationId: scope.organizationId }\n : Array.isArray(organizationScope.filterIds) ? { organizationIds: organizationScope.filterIds } : {}),\n fields,\n filters,\n ...(classification.kind === 'custom' ? { forceCustomEntityStorage: true } : {}),\n page: { page: 1, pageSize },\n }\n let rows: Record<string, unknown>[]\n if (resolveAccess) {\n const tenantId = scope.tenantId\n const organizationIds = scope.organizationId\n ? [scope.organizationId]\n : organizationScope.filterIds ?? (await findWithDecryption(\n em, Organization, { tenant: tenantId, deletedAt: null }, { fields: ['id'] }, { tenantId },\n )).map((organization) => organization.id)\n rows = []\n try {\n for (const organizationId of organizationIds) {\n if (requirement && !(await rbac.userHasAllFeatures(auth.sub, requirement.view, { tenantId, organizationId }))) continue\n const access = await resolveAccess({ auth: scopedAuth, container, tenantId, organizationId })\n if (!access) continue\n const scopedOptions = {\n ...queryOptions,\n organizationId,\n organizationIds: undefined,\n omitAutomaticTenantOrgScope: true,\n }\n const scopeFilters = { tenant_id: tenantId, organization_id: organizationId }\n const remaining = pageSize - rows.length\n if (access.authorizeIds) {\n const candidateFilters = ids.length ? { id: { $in: ids } } : {}\n let lastId: string | undefined\n while (rows.length < pageSize) {\n const candidates = await qe.query<{ id: string }>(entityId, {\n ...scopedOptions,\n fields: ['id'],\n filters: { $and: [scopeFilters, candidateFilters, ...(lastId ? [{ id: { $gt: lastId } }] : [])] },\n sort: [{ field: 'id', dir: SortDir.Asc }],\n page: { page: 1, pageSize: 100 },\n })\n if (candidates.items.length === 0) break\n const authorizedIds = await access.authorizeIds(candidates.items.map(({ id }) => id))\n if (authorizedIds.length) {\n const result = await qe.query<Record<string, unknown>>(entityId, {\n ...scopedOptions,\n filters: { $and: [scopeFilters, filters, { id: { $in: authorizedIds } }] },\n page: { page: 1, pageSize: pageSize - rows.length },\n })\n rows.push(...result.items)\n }\n if (candidates.items.length < 100) break\n lastId = candidates.items.at(-1)?.id\n }\n } else if (access.filters) {\n const result = await qe.query<Record<string, unknown>>(entityId, {\n ...scopedOptions,\n filters: { $and: [scopeFilters, filters, access.filters] },\n page: { page: 1, pageSize: remaining },\n })\n rows.push(...result.items)\n }\n if (rows.length >= pageSize) break\n }\n } catch (error) {\n if (isCrudHttpError(error)) return NextResponse.json(error.body, { status: error.status })\n throw error\n }\n } else {\n rows = (await qe.query<Record<string, unknown>>(entityId, queryOptions)).items ?? []\n }\n const items = rows.map((it) => {\n const routeContext = routeContextFields.reduce<Record<string, unknown>>((acc, field) => {\n if (it[field] !== undefined) {\n acc[field] = it[field]\n }\n return acc\n }, {})\n return {\n value: String(it.id),\n label: String(it[labelField] ?? it.id),\n ...(Object.keys(routeContext).length > 0 ? { routeContext } : {}),\n }\n })\n return NextResponse.json({ items })\n}\n\nconst relationOptionsQuerySchema = z.object({\n entityId: z.string().min(1),\n labelField: z.string().optional(),\n q: z.string().optional(),\n ids: z.string().optional(),\n routeContextFields: z.string().optional(),\n})\n\nconst relationOptionsResponseSchema = z.object({\n items: z.array(\n z.object({\n value: z.string(),\n label: z.string(),\n routeContext: z.record(z.string(), z.unknown()).optional(),\n })\n ),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Relation options lookup',\n methods: {\n GET: {\n summary: 'List relation options',\n description: 'Returns up to 100 option entries for populating relation dropdowns, requiring target read access and accepting only declared or fixed safe label fields. An entityId that matches neither an active custom entity nor a registered ORM entity yields an empty option list.',\n query: relationOptionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Option list',\n schema: relationOptionsResponseSchema,\n },\n {\n status: 400,\n description: 'Unsafe label selector',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 403,\n description: 'Target entity access denied',\n schema: z.object({ error: z.string() }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,oBAA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AAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,QACxC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["metadata"]
|
|
7
7
|
}
|
|
@@ -17,6 +17,31 @@ async function hasManageAllFeature(context) {
|
|
|
17
17
|
{ grantedFeatures: context.userFeatures ?? [] }
|
|
18
18
|
);
|
|
19
19
|
}
|
|
20
|
+
async function scopeTimeEntryList(query, context) {
|
|
21
|
+
if (await hasManageAllFeature(context)) {
|
|
22
|
+
return { ok: true };
|
|
23
|
+
}
|
|
24
|
+
const staffMember = await getStaffMemberByUserId(
|
|
25
|
+
context.em,
|
|
26
|
+
context.userId,
|
|
27
|
+
context.tenantId ?? null,
|
|
28
|
+
context.organizationId ?? null
|
|
29
|
+
);
|
|
30
|
+
if (!staffMember) {
|
|
31
|
+
return {
|
|
32
|
+
ok: false,
|
|
33
|
+
statusCode: 403,
|
|
34
|
+
message: "User is not a staff member."
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
ok: true,
|
|
39
|
+
query: {
|
|
40
|
+
...query ?? {},
|
|
41
|
+
staffMemberId: staffMember.id
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
20
45
|
const interceptors = [
|
|
21
46
|
{
|
|
22
47
|
id: "staff.timesheets.self-scope-widget-data",
|
|
@@ -66,33 +91,12 @@ const interceptors = [
|
|
|
66
91
|
methods: ["GET"],
|
|
67
92
|
priority: 70,
|
|
68
93
|
async before(request, context) {
|
|
69
|
-
|
|
70
|
-
return { ok: true };
|
|
71
|
-
}
|
|
72
|
-
const staffMember = await getStaffMemberByUserId(
|
|
73
|
-
context.em,
|
|
74
|
-
context.userId,
|
|
75
|
-
context.tenantId ?? null,
|
|
76
|
-
context.organizationId ?? null
|
|
77
|
-
);
|
|
78
|
-
if (!staffMember) {
|
|
79
|
-
return {
|
|
80
|
-
ok: false,
|
|
81
|
-
statusCode: 403,
|
|
82
|
-
message: "User is not a staff member."
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
return {
|
|
86
|
-
ok: true,
|
|
87
|
-
query: {
|
|
88
|
-
...request.query ?? {},
|
|
89
|
-
staffMemberId: staffMember.id
|
|
90
|
-
}
|
|
91
|
-
};
|
|
94
|
+
return scopeTimeEntryList(request.query, context);
|
|
92
95
|
}
|
|
93
96
|
}
|
|
94
97
|
];
|
|
95
98
|
export {
|
|
96
|
-
interceptors
|
|
99
|
+
interceptors,
|
|
100
|
+
scopeTimeEntryList
|
|
97
101
|
};
|
|
98
102
|
//# sourceMappingURL=interceptors.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/staff/api/interceptors.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ApiInterceptor, InterceptorContext } from '@open-mercato/shared/lib/crud/api-interceptor'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { getStaffMemberByUserId } from '../lib/staffMemberResolver'\n\ntype RbacServiceLike = {\n userHasAllFeatures: (\n userId: string,\n required: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n}\n\n/**\n * Checks whether the caller has manage_all rights, honoring wildcard ACL grants\n * (`staff.*`, `*`) and the super-admin flag.\n *\n * `context.userFeatures` is populated only on CRUD-factory routes (factory.ts\n * calls `rbacService.getGrantedFeatures`). Custom routes that wire interceptors\n * manually (like `dashboards/widgets/data`) pass `auth.features` directly, and\n * the JWT does NOT include features \u2014 so we must fall back to loading the ACL\n * from `rbacService.userHasAllFeatures`, which is cached and wildcard-aware.\n */\nasync function hasManageAllFeature(context: InterceptorContext): Promise<boolean> {\n try {\n const rbac = context.container.resolve('rbacService') as RbacServiceLike | undefined\n if (rbac?.userHasAllFeatures) {\n return await rbac.userHasAllFeatures(\n context.userId,\n ['staff.timesheets.manage_all'],\n { tenantId: context.tenantId ?? null, organizationId: context.organizationId ?? null },\n )\n }\n } catch {\n // Fall back to the already-loaded snapshot below.\n }\n return authorizeFeatures(\n ['staff.timesheets.manage_all'],\n { grantedFeatures: context.userFeatures ?? [] },\n )\n}\n\nexport const interceptors: ApiInterceptor[] = [\n {\n id: 'staff.timesheets.self-scope-widget-data',\n targetRoute: 'dashboards/widgets/data',\n methods: ['POST'],\n priority: 70,\n async before(request, context) {\n const entityType = request.body?.entityType\n if (entityType !== 'staff:staff_time_entries') {\n return { ok: true }\n }\n\n if (await hasManageAllFeature(context)) {\n return { ok: true }\n }\n\n const staffMember = await getStaffMemberByUserId(\n context.em,\n context.userId,\n context.tenantId ?? null,\n context.organizationId ?? null,\n )\n\n if (!staffMember) {\n return {\n ok: false,\n statusCode: 403,\n message: 'User is not a staff member.',\n }\n }\n\n const existingFilters = Array.isArray(request.body?.filters) ? request.body.filters : []\n const otherFilters = existingFilters.filter(\n (f: Record<string, unknown>) => f.field !== 'staffMemberId',\n )\n\n return {\n ok: true,\n body: {\n ...request.body,\n filters: [\n ...otherFilters,\n { field: 'staffMemberId', operator: 'eq', value: staffMember.id },\n ],\n },\n }\n },\n },\n {\n id: 'staff.timesheets.self-scope-time-entries',\n targetRoute: 'staff/timesheets/time-entries',\n methods: ['GET'],\n priority: 70,\n async before(request, context) {\n
|
|
5
|
-
"mappings": "AACA,SAAS,yBAAyB;AAClC,SAAS,8BAA8B;AAoBvC,eAAe,oBAAoB,SAA+C;AAChF,MAAI;AACF,UAAM,OAAO,QAAQ,UAAU,QAAQ,aAAa;AACpD,QAAI,MAAM,oBAAoB;AAC5B,aAAO,MAAM,K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EACF;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,aAAa;AAAA,IACb,SAAS,CAAC,KAAK;AAAA,IACf,UAAU;AAAA,IACV,MAAM,OAAO,SAAS,SAAS;AAC7B,
|
|
4
|
+
"sourcesContent": ["import type { ApiInterceptor, InterceptorContext } from '@open-mercato/shared/lib/crud/api-interceptor'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { getStaffMemberByUserId } from '../lib/staffMemberResolver'\n\ntype RbacServiceLike = {\n userHasAllFeatures: (\n userId: string,\n required: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n}\n\n/**\n * Checks whether the caller has manage_all rights, honoring wildcard ACL grants\n * (`staff.*`, `*`) and the super-admin flag.\n *\n * `context.userFeatures` is populated only on CRUD-factory routes (factory.ts\n * calls `rbacService.getGrantedFeatures`). Custom routes that wire interceptors\n * manually (like `dashboards/widgets/data`) pass `auth.features` directly, and\n * the JWT does NOT include features \u2014 so we must fall back to loading the ACL\n * from `rbacService.userHasAllFeatures`, which is cached and wildcard-aware.\n */\nasync function hasManageAllFeature(context: InterceptorContext): Promise<boolean> {\n try {\n const rbac = context.container.resolve('rbacService') as RbacServiceLike | undefined\n if (rbac?.userHasAllFeatures) {\n return await rbac.userHasAllFeatures(\n context.userId,\n ['staff.timesheets.manage_all'],\n { tenantId: context.tenantId ?? null, organizationId: context.organizationId ?? null },\n )\n }\n } catch {\n // Fall back to the already-loaded snapshot below.\n }\n return authorizeFeatures(\n ['staff.timesheets.manage_all'],\n { grantedFeatures: context.userFeatures ?? [] },\n )\n}\n\nexport async function scopeTimeEntryList(\n query: Record<string, unknown> | undefined,\n context: InterceptorContext,\n) {\n if (await hasManageAllFeature(context)) {\n return { ok: true }\n }\n\n const staffMember = await getStaffMemberByUserId(\n context.em,\n context.userId,\n context.tenantId ?? null,\n context.organizationId ?? null,\n )\n\n if (!staffMember) {\n return {\n ok: false,\n statusCode: 403,\n message: 'User is not a staff member.',\n }\n }\n\n return {\n ok: true,\n query: {\n ...(query ?? {}),\n staffMemberId: staffMember.id,\n },\n }\n}\n\nexport const interceptors: ApiInterceptor[] = [\n {\n id: 'staff.timesheets.self-scope-widget-data',\n targetRoute: 'dashboards/widgets/data',\n methods: ['POST'],\n priority: 70,\n async before(request, context) {\n const entityType = request.body?.entityType\n if (entityType !== 'staff:staff_time_entries') {\n return { ok: true }\n }\n\n if (await hasManageAllFeature(context)) {\n return { ok: true }\n }\n\n const staffMember = await getStaffMemberByUserId(\n context.em,\n context.userId,\n context.tenantId ?? null,\n context.organizationId ?? null,\n )\n\n if (!staffMember) {\n return {\n ok: false,\n statusCode: 403,\n message: 'User is not a staff member.',\n }\n }\n\n const existingFilters = Array.isArray(request.body?.filters) ? request.body.filters : []\n const otherFilters = existingFilters.filter(\n (f: Record<string, unknown>) => f.field !== 'staffMemberId',\n )\n\n return {\n ok: true,\n body: {\n ...request.body,\n filters: [\n ...otherFilters,\n { field: 'staffMemberId', operator: 'eq', value: staffMember.id },\n ],\n },\n }\n },\n },\n {\n id: 'staff.timesheets.self-scope-time-entries',\n targetRoute: 'staff/timesheets/time-entries',\n methods: ['GET'],\n priority: 70,\n async before(request, context) {\n return scopeTimeEntryList(request.query, context)\n },\n },\n]\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,yBAAyB;AAClC,SAAS,8BAA8B;AAoBvC,eAAe,oBAAoB,SAA+C;AAChF,MAAI;AACF,UAAM,OAAO,QAAQ,UAAU,QAAQ,aAAa;AACpD,QAAI,MAAM,oBAAoB;AAC5B,aAAO,MAAM,KAAK;AAAA,QAChB,QAAQ;AAAA,QACR,CAAC,6BAA6B;AAAA,QAC9B,EAAE,UAAU,QAAQ,YAAY,MAAM,gBAAgB,QAAQ,kBAAkB,KAAK;AAAA,MACvF;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,CAAC,6BAA6B;AAAA,IAC9B,EAAE,iBAAiB,QAAQ,gBAAgB,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;AAEA,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM;AAAA,UACJ,GAAG,QAAQ;AAAA,UACX,SAAS;AAAA,YACP,GAAG;AAAA,YACH,EAAE,OAAO,iBAAiB,UAAU,MAAM,OAAO,YAAY,GAAG;AAAA,UAClE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,aAAa;AAAA,IACb,SAAS,CAAC,KAAK;AAAA,IACf,UAAU;AAAA,IACV,MAAM,OAAO,SAAS,SAAS;AAC7B,aAAO,mBAAmB,QAAQ,OAAO,OAAO;AAAA,IAClD;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/modules/staff/di.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defineProcessDiRegistrar } from "@open-mercato/shared/lib/di/process-registrar";
|
|
2
|
+
import { relationOptionAccessKey } from "@open-mercato/shared/lib/query/relationOptionAccess";
|
|
2
3
|
import { asValue } from "awilix";
|
|
3
4
|
import {
|
|
4
5
|
resolveAvailabilityWriteAccess
|
|
@@ -26,6 +27,27 @@ import {
|
|
|
26
27
|
import {
|
|
27
28
|
deriveProjectCode
|
|
28
29
|
} from "./lib/time-tracking/projectCode.js";
|
|
30
|
+
const timeEntryRelationAccess = async ({ auth, container, tenantId, organizationId }) => {
|
|
31
|
+
const { scopeTimeEntryList } = await import("./api/interceptors.js");
|
|
32
|
+
const scoped = await scopeTimeEntryList(void 0, {
|
|
33
|
+
userId: auth.sub,
|
|
34
|
+
tenantId,
|
|
35
|
+
organizationId,
|
|
36
|
+
container,
|
|
37
|
+
em: container.resolve("em")
|
|
38
|
+
});
|
|
39
|
+
if (!scoped.ok) return null;
|
|
40
|
+
const { buildScopedTimeEntryListFilters } = await import("./api/timesheets/time-entries/route.js");
|
|
41
|
+
return {
|
|
42
|
+
filters: await buildScopedTimeEntryListFilters({ page: 1, pageSize: 50, staffMemberId: scoped.query?.staffMemberId }, {
|
|
43
|
+
auth: { ...auth, tenantId, orgId: organizationId },
|
|
44
|
+
container,
|
|
45
|
+
organizationScope: null,
|
|
46
|
+
selectedOrganizationId: organizationId,
|
|
47
|
+
organizationIds: [organizationId]
|
|
48
|
+
})
|
|
49
|
+
};
|
|
50
|
+
};
|
|
29
51
|
function register(container) {
|
|
30
52
|
const resolver = { resolveAvailabilityWriteAccess };
|
|
31
53
|
const timeTrackingResolver = { resolveProjectAccess };
|
|
@@ -44,6 +66,7 @@ function register(container) {
|
|
|
44
66
|
generate: (name, taken, ctx) => deriveProjectCode(name, taken, ctx ?? void 0)
|
|
45
67
|
};
|
|
46
68
|
container.register({
|
|
69
|
+
[relationOptionAccessKey("staff:staff_time_entry")]: asValue(timeEntryRelationAccess),
|
|
47
70
|
availabilityAccessResolver: asValue(resolver),
|
|
48
71
|
timeTrackingAccessResolver: asValue(timeTrackingResolver),
|
|
49
72
|
timeRoundingResolver: asValue(timeRoundingResolver),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/staff/di.ts"],
|
|
4
|
-
"sourcesContent": ["import { defineProcessDiRegistrar } from '@open-mercato/shared/lib/di/process-registrar'\nimport { asValue } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport {\n resolveAvailabilityWriteAccess,\n type AvailabilityAccessContext,\n type AvailabilityWriteAccess,\n} from './lib/availabilityAccess'\nimport {\n resolveProjectAccess,\n type ProjectAccess,\n type ProjectAccessContext,\n} from './lib/time-tracking/access'\nimport {\n resolveTimeRoundingStrategy,\n roundMinutes,\n type RoundingSettings,\n type TimeRoundingStrategy,\n} from './lib/time-tracking/rounding'\nimport {\n resolveTimeRate,\n type TimeRateContext,\n} from './lib/time-tracking/cost'\nimport {\n resolveBillability,\n type BillabilityContext,\n} from './lib/time-tracking/billability'\nimport {\n resolveTimesheetCapacity,\n resolveTimesheetCapacityAsync,\n type CapacityContext,\n type CapacityDateRange,\n type CapacityResult,\n type ResolvedCapacity,\n} from './lib/time-tracking/capacity'\nimport {\n evaluateOverlapPolicies,\n type Overlap,\n type OverlapDecision,\n type OverlapPolicyContext,\n} from './lib/time-tracking/overlap'\nimport {\n deriveProjectCode,\n type ProjectCodeContext,\n} from './lib/time-tracking/projectCode'\nimport type { ScopedResolverContext } from './lib/time-tracking/registries/scope'\n\nexport type AvailabilityAccessResolver = {\n resolveAvailabilityWriteAccess(\n ctx: AvailabilityAccessContext,\n ): Promise<AvailabilityWriteAccess>\n}\n\nexport type TimeTrackingAccessResolver = {\n resolveProjectAccess(ctx: ProjectAccessContext): Promise<ProjectAccess>\n}\n\n/**\n * EP-32\u2026EP-41 keep their registries in plain module scope so the browser bundle\n * can reach them (four of the strategies back client previews that cannot\n * resolve DI). These DI keys are the SERVER entry point to the same registries:\n * they exist so an app can replace a resolver wholesale through `entry.overrides`\n * DI without patching the module, and so server code follows the \"never `new` a\n * resolver\" rule. Resolving one and calling the module function are equivalent.\n */\nexport type TimeRoundingResolver = {\n resolveStrategy(ctx?: ScopedResolverContext | null): TimeRoundingStrategy\n roundMinutes(raw: number, settings: RoundingSettings, ctx?: ScopedResolverContext | null): number\n}\n\nexport type TimeRateResolverService = {\n resolveRate(ctx: TimeRateContext): number | null\n}\n\nexport type BillabilityResolverService = {\n resolveBillability(ctx: BillabilityContext): boolean\n}\n\nexport type TimeCapacityResolver = {\n /** @deprecated Synchronous; never consults a provider's `resolveAsync`. Use `resolveCapacityAsync`. */\n resolveCapacity(\n staffMemberId: string | null,\n dateRange: CapacityDateRange,\n ctx: CapacityContext,\n ): CapacityResult\n resolveCapacityAsync?(\n staffMemberId: string | null,\n dateRange: CapacityDateRange,\n ctx: CapacityContext,\n ): Promise<ResolvedCapacity>\n}\n\nexport type OverlapPolicyResolver = {\n evaluate(spans: readonly Overlap[], ctx: OverlapPolicyContext): OverlapDecision\n}\n\nexport type ProjectCodeResolver = {\n generate(name: string, taken: Set<string>, ctx?: ProjectCodeContext | null): string\n}\n\nexport function register(container: AppContainer) {\n const resolver: AvailabilityAccessResolver = { resolveAvailabilityWriteAccess }\n const timeTrackingResolver: TimeTrackingAccessResolver = { resolveProjectAccess }\n const timeRoundingResolver: TimeRoundingResolver = {\n resolveStrategy: resolveTimeRoundingStrategy,\n roundMinutes,\n }\n const timeRateResolver: TimeRateResolverService = { resolveRate: resolveTimeRate }\n const timeBillabilityResolver: BillabilityResolverService = { resolveBillability }\n const timeCapacityResolver: TimeCapacityResolver = {\n resolveCapacity: resolveTimesheetCapacity,\n resolveCapacityAsync: resolveTimesheetCapacityAsync,\n }\n const timeOverlapPolicyResolver: OverlapPolicyResolver = { evaluate: evaluateOverlapPolicies }\n const timeProjectCodeResolver: ProjectCodeResolver = {\n generate: (name, taken, ctx) => deriveProjectCode(name, taken, ctx ?? undefined),\n }\n container.register({\n availabilityAccessResolver: asValue(resolver),\n timeTrackingAccessResolver: asValue(timeTrackingResolver),\n timeRoundingResolver: asValue(timeRoundingResolver),\n timeRateResolver: asValue(timeRateResolver),\n timeBillabilityResolver: asValue(timeBillabilityResolver),\n timeCapacityResolver: asValue(timeCapacityResolver),\n timeOverlapPolicyResolver: asValue(timeOverlapPolicyResolver),\n timeProjectCodeResolver: asValue(timeProjectCodeResolver),\n })\n}\n\ndefineProcessDiRegistrar(register)\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gCAAgC;AACzC,SAAS,eAAe;AAExB;AAAA,EACE;AAAA,OAGK;AACP;AAAA,EACE;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,OAEK;
|
|
4
|
+
"sourcesContent": ["import { defineProcessDiRegistrar } from '@open-mercato/shared/lib/di/process-registrar'\nimport { relationOptionAccessKey, type RelationOptionAccess } from '@open-mercato/shared/lib/query/relationOptionAccess'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { asValue } from 'awilix'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport {\n resolveAvailabilityWriteAccess,\n type AvailabilityAccessContext,\n type AvailabilityWriteAccess,\n} from './lib/availabilityAccess'\nimport {\n resolveProjectAccess,\n type ProjectAccess,\n type ProjectAccessContext,\n} from './lib/time-tracking/access'\nimport {\n resolveTimeRoundingStrategy,\n roundMinutes,\n type RoundingSettings,\n type TimeRoundingStrategy,\n} from './lib/time-tracking/rounding'\nimport {\n resolveTimeRate,\n type TimeRateContext,\n} from './lib/time-tracking/cost'\nimport {\n resolveBillability,\n type BillabilityContext,\n} from './lib/time-tracking/billability'\nimport {\n resolveTimesheetCapacity,\n resolveTimesheetCapacityAsync,\n type CapacityContext,\n type CapacityDateRange,\n type CapacityResult,\n type ResolvedCapacity,\n} from './lib/time-tracking/capacity'\nimport {\n evaluateOverlapPolicies,\n type Overlap,\n type OverlapDecision,\n type OverlapPolicyContext,\n} from './lib/time-tracking/overlap'\nimport {\n deriveProjectCode,\n type ProjectCodeContext,\n} from './lib/time-tracking/projectCode'\nimport type { ScopedResolverContext } from './lib/time-tracking/registries/scope'\n\nexport type AvailabilityAccessResolver = {\n resolveAvailabilityWriteAccess(\n ctx: AvailabilityAccessContext,\n ): Promise<AvailabilityWriteAccess>\n}\n\nexport type TimeTrackingAccessResolver = {\n resolveProjectAccess(ctx: ProjectAccessContext): Promise<ProjectAccess>\n}\n\n/**\n * EP-32\u2026EP-41 keep their registries in plain module scope so the browser bundle\n * can reach them (four of the strategies back client previews that cannot\n * resolve DI). These DI keys are the SERVER entry point to the same registries:\n * they exist so an app can replace a resolver wholesale through `entry.overrides`\n * DI without patching the module, and so server code follows the \"never `new` a\n * resolver\" rule. Resolving one and calling the module function are equivalent.\n */\nexport type TimeRoundingResolver = {\n resolveStrategy(ctx?: ScopedResolverContext | null): TimeRoundingStrategy\n roundMinutes(raw: number, settings: RoundingSettings, ctx?: ScopedResolverContext | null): number\n}\n\nexport type TimeRateResolverService = {\n resolveRate(ctx: TimeRateContext): number | null\n}\n\nexport type BillabilityResolverService = {\n resolveBillability(ctx: BillabilityContext): boolean\n}\n\nexport type TimeCapacityResolver = {\n /** @deprecated Synchronous; never consults a provider's `resolveAsync`. Use `resolveCapacityAsync`. */\n resolveCapacity(\n staffMemberId: string | null,\n dateRange: CapacityDateRange,\n ctx: CapacityContext,\n ): CapacityResult\n resolveCapacityAsync?(\n staffMemberId: string | null,\n dateRange: CapacityDateRange,\n ctx: CapacityContext,\n ): Promise<ResolvedCapacity>\n}\n\nexport type OverlapPolicyResolver = {\n evaluate(spans: readonly Overlap[], ctx: OverlapPolicyContext): OverlapDecision\n}\n\nexport type ProjectCodeResolver = {\n generate(name: string, taken: Set<string>, ctx?: ProjectCodeContext | null): string\n}\n\nconst timeEntryRelationAccess: RelationOptionAccess = async ({ auth, container, tenantId, organizationId }) => {\n const { scopeTimeEntryList } = await import('./api/interceptors')\n const scoped = await scopeTimeEntryList(undefined, {\n userId: auth.sub,\n tenantId,\n organizationId,\n container,\n em: container.resolve<EntityManager>('em'),\n })\n if (!scoped.ok) return null\n const { buildScopedTimeEntryListFilters } = await import('./api/timesheets/time-entries/route')\n return {\n filters: await buildScopedTimeEntryListFilters({ page: 1, pageSize: 50, staffMemberId: scoped.query?.staffMemberId }, {\n auth: { ...auth, tenantId, orgId: organizationId },\n container,\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: [organizationId],\n }),\n }\n}\n\nexport function register(container: AppContainer) {\n const resolver: AvailabilityAccessResolver = { resolveAvailabilityWriteAccess }\n const timeTrackingResolver: TimeTrackingAccessResolver = { resolveProjectAccess }\n const timeRoundingResolver: TimeRoundingResolver = {\n resolveStrategy: resolveTimeRoundingStrategy,\n roundMinutes,\n }\n const timeRateResolver: TimeRateResolverService = { resolveRate: resolveTimeRate }\n const timeBillabilityResolver: BillabilityResolverService = { resolveBillability }\n const timeCapacityResolver: TimeCapacityResolver = {\n resolveCapacity: resolveTimesheetCapacity,\n resolveCapacityAsync: resolveTimesheetCapacityAsync,\n }\n const timeOverlapPolicyResolver: OverlapPolicyResolver = { evaluate: evaluateOverlapPolicies }\n const timeProjectCodeResolver: ProjectCodeResolver = {\n generate: (name, taken, ctx) => deriveProjectCode(name, taken, ctx ?? undefined),\n }\n container.register({\n [relationOptionAccessKey('staff:staff_time_entry')]: asValue(timeEntryRelationAccess),\n availabilityAccessResolver: asValue(resolver),\n timeTrackingAccessResolver: asValue(timeTrackingResolver),\n timeRoundingResolver: asValue(timeRoundingResolver),\n timeRateResolver: asValue(timeRateResolver),\n timeBillabilityResolver: asValue(timeBillabilityResolver),\n timeCapacityResolver: asValue(timeCapacityResolver),\n timeOverlapPolicyResolver: asValue(timeOverlapPolicyResolver),\n timeProjectCodeResolver: asValue(timeProjectCodeResolver),\n })\n}\n\ndefineProcessDiRegistrar(register)\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,gCAAgC;AACzC,SAAS,+BAA0D;AAEnE,SAAS,eAAe;AAExB;AAAA,EACE;AAAA,OAGK;AACP;AAAA,EACE;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,OAEK;AAwDP,MAAM,0BAAgD,OAAO,EAAE,MAAM,WAAW,UAAU,eAAe,MAAM;AAC7G,QAAM,EAAE,mBAAmB,IAAI,MAAM,OAAO,oBAAoB;AAChE,QAAM,SAAS,MAAM,mBAAmB,QAAW;AAAA,IACjD,QAAQ,KAAK;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA,IAAI,UAAU,QAAuB,IAAI;AAAA,EAC3C,CAAC;AACD,MAAI,CAAC,OAA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names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.11.1-develop.
|
|
3
|
+
"version": "0.11.1-develop.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.
|
|
272
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
273
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
271
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.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.
|
|
279
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
280
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
278
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.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] }) =>
|
|
@@ -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.
|
|
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.
|
|
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
|
-
|
|
61
|
-
if (
|
|
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 ?? (
|
|
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)) {
|