@open-mercato/core 0.11.1-develop.8537.1.dd5134f251 → 0.11.1-develop.8541.1.955f210e1d
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/auth/services/rbacService.js +11 -12
- package/dist/modules/auth/services/rbacService.js.map +2 -2
- package/dist/modules/directory/utils/organizationScope.js +3 -2
- package/dist/modules/directory/utils/organizationScope.js.map +2 -2
- package/dist/modules/entities/api/encryption.js +13 -2
- package/dist/modules/entities/api/encryption.js.map +2 -2
- package/dist/modules/entities/api/records.js +4 -3
- package/dist/modules/entities/api/records.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js +22 -38
- package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js.map +2 -2
- package/dist/modules/progress/api/active/route.js +11 -3
- package/dist/modules/progress/api/active/route.js.map +2 -2
- package/dist/modules/progress/api/jobPermissions.js +42 -0
- package/dist/modules/progress/api/jobPermissions.js.map +7 -0
- package/dist/modules/progress/api/jobs/[id]/route.js +6 -11
- package/dist/modules/progress/api/jobs/[id]/route.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/services/rbacService.ts +12 -34
- package/src/modules/directory/utils/organizationScope.ts +3 -2
- package/src/modules/entities/api/encryption.ts +14 -2
- package/src/modules/entities/api/records.ts +4 -3
- package/src/modules/entities/backend/entities/user/[entityId]/records/page.tsx +25 -31
- package/src/modules/entities/i18n/de.json +20 -1
- package/src/modules/entities/i18n/en.json +20 -1
- package/src/modules/entities/i18n/es.json +20 -1
- package/src/modules/entities/i18n/ko.json +20 -1
- package/src/modules/entities/i18n/pl.json +20 -1
- package/src/modules/progress/api/active/route.ts +18 -3
- package/src/modules/progress/api/jobPermissions.ts +50 -0
- package/src/modules/progress/api/jobs/[id]/route.ts +7 -20
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
3
3
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
4
|
+
import { createProgressJobMutationPolicy, resolveProgressCancellationScope } from "../jobPermissions.js";
|
|
4
5
|
import {
|
|
5
6
|
hasReadableProgressScope,
|
|
7
|
+
hasWritableProgressScope,
|
|
6
8
|
resolveProgressRequestScope
|
|
7
9
|
} from "../requestScope.js";
|
|
8
10
|
const routeMetadata = {
|
|
@@ -30,10 +32,16 @@ async function GET(req) {
|
|
|
30
32
|
progressService.getActiveJobs(ctx),
|
|
31
33
|
progressService.getRecentlyCompletedJobs(ctx)
|
|
32
34
|
]);
|
|
35
|
+
const cancelScope = jobs.some((job) => job.cancellable) && hasWritableProgressScope(scope) ? await resolveProgressCancellationScope(container, auth, req) : null;
|
|
36
|
+
const canMutateJob = createProgressJobMutationPolicy(container, auth);
|
|
37
|
+
const active = await Promise.all(jobs.map(async (job) => ({
|
|
38
|
+
...formatJob(job),
|
|
39
|
+
canCancel: job.cancellable && cancelScope !== null && (cancelScope.filterIds === null || job.organizationId != null && cancelScope.filterIds.includes(job.organizationId)) && await canMutateJob(job)
|
|
40
|
+
})));
|
|
33
41
|
return NextResponse.json({
|
|
34
|
-
active
|
|
42
|
+
active,
|
|
35
43
|
recentlyCompleted: recentlyCompleted.map(formatJob)
|
|
36
|
-
});
|
|
44
|
+
}, { headers: { "Cache-Control": "private, no-store" } });
|
|
37
45
|
}
|
|
38
46
|
function formatJob(job) {
|
|
39
47
|
return {
|
|
@@ -56,7 +64,7 @@ function formatJob(job) {
|
|
|
56
64
|
const openApi = {
|
|
57
65
|
GET: {
|
|
58
66
|
summary: "Get active progress jobs",
|
|
59
|
-
description: "Returns
|
|
67
|
+
description: "Returns active and recently completed jobs for the progress top bar. Each active job includes canCancel for the authenticated caller.",
|
|
60
68
|
tags: ["Progress"],
|
|
61
69
|
responses: {
|
|
62
70
|
200: { description: "Active and recently completed jobs" }
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/progress/api/active/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { ProgressJob } from '../../data/entities'\nimport {\n hasReadableProgressScope,\n resolveProgressRequestScope,\n} from '../requestScope'\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['progress.view'] },\n}\n\nexport const metadata = routeMetadata\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ active: [], recentlyCompleted: [] }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const progressService = container.resolve('progressService') as import('../../lib/progressService').ProgressService\n const scope = await resolveProgressRequestScope(container, auth, req)\n if (!hasReadableProgressScope(scope)) {\n return NextResponse.json({ active: [], recentlyCompleted: [] })\n }\n\n const ctx = {\n tenantId: scope.tenantId,\n organizationId: scope.selectedId,\n organizationIds: scope.filterIds,\n }\n\n await progressService.markStaleJobsFailed(scope.tenantId, undefined, scope.selectedId, scope.filterIds)\n\n const [jobs, recentlyCompleted] = await Promise.all([\n progressService.getActiveJobs(ctx),\n progressService.getRecentlyCompletedJobs(ctx),\n ])\n\n
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,eAAe,EAAE;AAC/D;AAEO,MAAM,WAAW;AAExB,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,UAAU;AAC3B,WAAO,aAAa,KAAK,EAAE,QAAQ,CAAC,GAAG,mBAAmB,CAAC,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACjF;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,kBAAkB,UAAU,QAAQ,iBAAiB;AAC3D,QAAM,QAAQ,MAAM,4BAA4B,WAAW,MAAM,GAAG;AACpE,MAAI,CAAC,yBAAyB,KAAK,GAAG;AACpC,WAAO,aAAa,KAAK,EAAE,QAAQ,CAAC,GAAG,mBAAmB,CAAC,EAAE,CAAC;AAAA,EAChE;AAEA,QAAM,MAAM;AAAA,IACV,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,IACtB,iBAAiB,MAAM;AAAA,EACzB;AAEA,QAAM,gBAAgB,oBAAoB,MAAM,UAAU,QAAW,MAAM,YAAY,MAAM,SAAS;AAEtG,QAAM,CAAC,MAAM,iBAAiB,IAAI,MAAM,QAAQ,IAAI;AAAA,IAClD,gBAAgB,cAAc,GAAG;AAAA,IACjC,gBAAgB,yBAAyB,GAAG;AAAA,EAC9C,CAAC;AAED,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { ProgressJob } from '../../data/entities'\nimport { createProgressJobMutationPolicy, resolveProgressCancellationScope } from '../jobPermissions'\nimport {\n hasReadableProgressScope,\n hasWritableProgressScope,\n resolveProgressRequestScope,\n} from '../requestScope'\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['progress.view'] },\n}\n\nexport const metadata = routeMetadata\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ active: [], recentlyCompleted: [] }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const progressService = container.resolve('progressService') as import('../../lib/progressService').ProgressService\n const scope = await resolveProgressRequestScope(container, auth, req)\n if (!hasReadableProgressScope(scope)) {\n return NextResponse.json({ active: [], recentlyCompleted: [] })\n }\n\n const ctx = {\n tenantId: scope.tenantId,\n organizationId: scope.selectedId,\n organizationIds: scope.filterIds,\n }\n\n await progressService.markStaleJobsFailed(scope.tenantId, undefined, scope.selectedId, scope.filterIds)\n\n const [jobs, recentlyCompleted] = await Promise.all([\n progressService.getActiveJobs(ctx),\n progressService.getRecentlyCompletedJobs(ctx),\n ])\n\n const cancelScope = jobs.some((job) => job.cancellable) && hasWritableProgressScope(scope)\n ? await resolveProgressCancellationScope(container, auth, req)\n : null\n const canMutateJob = createProgressJobMutationPolicy(container, auth)\n const active = await Promise.all(jobs.map(async (job) => ({\n ...formatJob(job),\n canCancel: job.cancellable\n && cancelScope !== null\n && (cancelScope.filterIds === null\n || (job.organizationId != null && cancelScope.filterIds.includes(job.organizationId)))\n && await canMutateJob(job),\n })))\n\n return NextResponse.json({\n active,\n recentlyCompleted: recentlyCompleted.map(formatJob),\n }, { headers: { 'Cache-Control': 'private, no-store' } })\n}\n\nfunction formatJob(job: ProgressJob) {\n return {\n id: job.id,\n jobType: job.jobType,\n name: job.name,\n description: job.description,\n status: job.status,\n progressPercent: job.progressPercent,\n processedCount: job.processedCount,\n totalCount: job.totalCount,\n etaSeconds: job.etaSeconds,\n cancellable: job.cancellable,\n meta: job.meta ?? null,\n startedAt: job.startedAt?.toISOString() ?? null,\n finishedAt: job.finishedAt?.toISOString() ?? null,\n errorMessage: job.errorMessage,\n }\n}\n\nexport const openApi = {\n GET: {\n summary: 'Get active progress jobs',\n description: 'Returns active and recently completed jobs for the progress top bar. Each active job includes canCancel for the authenticated caller.',\n tags: ['Progress'],\n responses: {\n 200: { description: 'Active and recently completed jobs' },\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,iCAAiC,wCAAwC;AAClF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAA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AY,UAAU,SAAS,IAAI,cAAc,MAClF,MAAM,aAAa,GAAG;AAAA,EAC7B,EAAE,CAAC;AAEH,SAAO,aAAa,KAAK;AAAA,IACvB;AAAA,IACA,mBAAmB,kBAAkB,IAAI,SAAS;AAAA,EACpD,GAAG,EAAE,SAAS,EAAE,iBAAiB,oBAAoB,EAAE,CAAC;AAC1D;AAEA,SAAS,UAAU,KAAkB;AACnC,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,SAAS,IAAI;AAAA,IACb,MAAM,IAAI;AAAA,IACV,aAAa,IAAI;AAAA,IACjB,QAAQ,IAAI;AAAA,IACZ,iBAAiB,IAAI;AAAA,IACrB,gBAAgB,IAAI;AAAA,IACpB,YAAY,IAAI;AAAA,IAChB,YAAY,IAAI;AAAA,IAChB,aAAa,IAAI;AAAA,IACjB,MAAM,IAAI,QAAQ;AAAA,IAClB,WAAW,IAAI,WAAW,YAAY,KAAK;AAAA,IAC3C,YAAY,IAAI,YAAY,YAAY,KAAK;AAAA,IAC7C,cAAc,IAAI;AAAA,EACpB;AACF;AAEO,MAAM,UAAU;AAAA,EACrB,KAAK;AAAA,IACH,SAAS;AAAA,IACT,aAAa;AAAA,IACb,MAAM,CAAC,UAAU;AAAA,IACjB,WAAW;AAAA,MACT,KAAK,EAAE,aAAa,qCAAqC;AAAA,IAC3D;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { resolveFeatureCheckContext } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
2
|
+
import { hasWritableProgressScope, resolveProgressRequestScope } from "./requestScope.js";
|
|
3
|
+
const progressCancelFeatures = ["progress.cancel"];
|
|
4
|
+
function createProgressJobMutationPolicy(container, auth) {
|
|
5
|
+
const manageAccessByOrganization = /* @__PURE__ */ new Map();
|
|
6
|
+
return async (job) => {
|
|
7
|
+
if (job.startedByUserId === auth.sub) return true;
|
|
8
|
+
const organizationId = job.organizationId ?? null;
|
|
9
|
+
const knownAccess = manageAccessByOrganization.get(organizationId);
|
|
10
|
+
if (knownAccess) return knownAccess;
|
|
11
|
+
const rbac = container.resolve("rbacService");
|
|
12
|
+
const access = rbac.userHasAllFeatures(auth.sub, ["progress.manage"], {
|
|
13
|
+
tenantId: auth.tenantId ?? null,
|
|
14
|
+
organizationId
|
|
15
|
+
});
|
|
16
|
+
manageAccessByOrganization.set(organizationId, access);
|
|
17
|
+
return access;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
async function resolveProgressCancellationScope(container, auth, request) {
|
|
21
|
+
const cancelRequest = request.clone();
|
|
22
|
+
const { organizationId, scope: featureScope } = await resolveFeatureCheckContext({
|
|
23
|
+
container,
|
|
24
|
+
auth,
|
|
25
|
+
request: cancelRequest,
|
|
26
|
+
requiredFeatures: progressCancelFeatures
|
|
27
|
+
});
|
|
28
|
+
const rbac = container.resolve("rbacService");
|
|
29
|
+
const hasCancelFeature = await rbac.userHasAllFeatures(auth.sub, progressCancelFeatures, {
|
|
30
|
+
tenantId: featureScope.tenantId ?? auth.tenantId ?? null,
|
|
31
|
+
organizationId
|
|
32
|
+
});
|
|
33
|
+
if (!hasCancelFeature) return null;
|
|
34
|
+
const scope = await resolveProgressRequestScope(container, auth, cancelRequest);
|
|
35
|
+
return hasWritableProgressScope(scope) ? scope : null;
|
|
36
|
+
}
|
|
37
|
+
export {
|
|
38
|
+
createProgressJobMutationPolicy,
|
|
39
|
+
progressCancelFeatures,
|
|
40
|
+
resolveProgressCancellationScope
|
|
41
|
+
};
|
|
42
|
+
//# sourceMappingURL=jobPermissions.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/progress/api/jobPermissions.ts"],
|
|
4
|
+
"sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { resolveFeatureCheckContext } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { ProgressJob } from '../data/entities'\nimport { hasWritableProgressScope, resolveProgressRequestScope } from './requestScope'\n\nexport const progressCancelFeatures = ['progress.cancel']\n\nexport function createProgressJobMutationPolicy(container: AwilixContainer, auth: NonNullable<AuthContext>) {\n const manageAccessByOrganization = new Map<string | null, Promise<boolean>>()\n\n return async (job: Pick<ProgressJob, 'startedByUserId' | 'organizationId'>): Promise<boolean> => {\n if (job.startedByUserId === auth.sub) return true\n const organizationId = job.organizationId ?? null\n const knownAccess = manageAccessByOrganization.get(organizationId)\n if (knownAccess) return knownAccess\n\n const rbac = container.resolve<RbacService>('rbacService')\n const access = rbac.userHasAllFeatures(auth.sub, ['progress.manage'], {\n tenantId: auth.tenantId ?? null,\n organizationId,\n })\n manageAccessByOrganization.set(organizationId, access)\n return access\n }\n}\n\nexport async function resolveProgressCancellationScope(\n container: AwilixContainer,\n auth: NonNullable<AuthContext>,\n request: Request,\n) {\n const cancelRequest = request.clone()\n const { organizationId, scope: featureScope } = await resolveFeatureCheckContext({\n container,\n auth,\n request: cancelRequest,\n requiredFeatures: progressCancelFeatures,\n })\n const rbac = container.resolve<RbacService>('rbacService')\n const hasCancelFeature = await rbac.userHasAllFeatures(auth.sub, progressCancelFeatures, {\n tenantId: featureScope.tenantId ?? auth.tenantId ?? null,\n organizationId,\n })\n if (!hasCancelFeature) return null\n\n const scope = await resolveProgressRequestScope(container, auth, cancelRequest)\n return hasWritableProgressScope(scope) ? scope : null\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,kCAAkC;AAE3C,SAAS,0BAA0B,mCAAmC;AAE/D,MAAM,yBAAyB,CAAC,iBAAiB;AAEjD,SAAS,gCAAgC,WAA4B,MAAgC;AAC1G,QAAM,6BAA6B,oBAAI,IAAqC;AAE5E,SAAO,OAAO,QAAmF;AAC/F,QAAI,IAAI,oBAAoB,KAAK,IAAK,QAAO;AAC7C,UAAM,iBAAiB,IAAI,kBAAkB;AAC7C,UAAM,cAAc,2BAA2B,IAAI,cAAc;AACjE,QAAI,YAAa,QAAO;AAExB,UAAM,OAAO,UAAU,QAAqB,aAAa;AACzD,UAAM,SAAS,KAAK,mBAAmB,KAAK,KAAK,CAAC,iBAAiB,GAAG;AAAA,MACpE,UAAU,KAAK,YAAY;AAAA,MAC3B;AAAA,IACF,CAAC;AACD,+BAA2B,IAAI,gBAAgB,MAAM;AACrD,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,iCACpB,WACA,MACA,SACA;AACA,QAAM,gBAAgB,QAAQ,MAAM;AACpC,QAAM,EAAE,gBAAgB,OAAO,aAAa,IAAI,MAAM,2BAA2B;AAAA,IAC/E;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT,kBAAkB;AAAA,EACpB,CAAC;AACD,QAAM,OAAO,UAAU,QAAqB,aAAa;AACzD,QAAM,mBAAmB,MAAM,KAAK,mBAAmB,KAAK,KAAK,wBAAwB;AAAA,IACvF,UAAU,aAAa,YAAY,KAAK,YAAY;AAAA,IACpD;AAAA,EACF,CAAC;AACD,MAAI,CAAC,iBAAkB,QAAO;AAE9B,QAAM,QAAQ,MAAM,4BAA4B,WAAW,MAAM,aAAa;AAC9E,SAAO,yBAAyB,KAAK,IAAI,QAAQ;AACnD;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -3,6 +3,7 @@ import { z } from "zod";
|
|
|
3
3
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
4
4
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
5
5
|
import { updateProgressSchema } from "../../../data/validators.js";
|
|
6
|
+
import { createProgressJobMutationPolicy, progressCancelFeatures } from "../../jobPermissions.js";
|
|
6
7
|
import {
|
|
7
8
|
hasReadableProgressScope,
|
|
8
9
|
hasWritableProgressScope,
|
|
@@ -11,18 +12,10 @@ import {
|
|
|
11
12
|
const routeMetadata = {
|
|
12
13
|
GET: { requireAuth: true, requireFeatures: ["progress.view"] },
|
|
13
14
|
PUT: { requireAuth: true, requireFeatures: ["progress.update"] },
|
|
14
|
-
DELETE: { requireAuth: true, requireFeatures:
|
|
15
|
+
DELETE: { requireAuth: true, requireFeatures: progressCancelFeatures }
|
|
15
16
|
};
|
|
16
17
|
const metadata = routeMetadata;
|
|
17
18
|
const jobIdSchema = z.guid();
|
|
18
|
-
async function canMutateProgressJob(container, auth, job) {
|
|
19
|
-
if (job.startedByUserId === auth.sub) return true;
|
|
20
|
-
const rbacService = container.resolve("rbacService");
|
|
21
|
-
return rbacService.userHasAllFeatures(auth.sub, ["progress.manage"], {
|
|
22
|
-
tenantId: auth.tenantId ?? null,
|
|
23
|
-
organizationId: job.organizationId ?? null
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
19
|
function cannotCancelJobResponse() {
|
|
27
20
|
return NextResponse.json({ error: "Cannot cancel this job" }, { status: 400 });
|
|
28
21
|
}
|
|
@@ -96,7 +89,8 @@ async function PUT(req, { params }) {
|
|
|
96
89
|
userId: auth.sub
|
|
97
90
|
};
|
|
98
91
|
const existing = jobIdSchema.safeParse(params.id).success ? await progressService.getJob(params.id, progressContext) : null;
|
|
99
|
-
|
|
92
|
+
const canMutateJob = createProgressJobMutationPolicy(container, auth);
|
|
93
|
+
if (!existing || !await canMutateJob(existing)) {
|
|
100
94
|
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
101
95
|
}
|
|
102
96
|
const job = await progressService.updateProgress(params.id, parsed.data, progressContext);
|
|
@@ -121,7 +115,8 @@ async function DELETE(req, { params }) {
|
|
|
121
115
|
};
|
|
122
116
|
try {
|
|
123
117
|
const existing = await progressService.getJob(params.id, progressContext);
|
|
124
|
-
|
|
118
|
+
const canMutateJob = createProgressJobMutationPolicy(container, auth);
|
|
119
|
+
if (!existing || !await canMutateJob(existing)) {
|
|
125
120
|
return cannotCancelJobResponse();
|
|
126
121
|
}
|
|
127
122
|
await progressService.cancelJob(params.id, progressContext);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/progress/api/jobs/%5Bid%5D/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { updateProgressSchema } from '../../../data/validators'\nimport type { ProgressService } from '../../../lib/progressService'\nimport { createProgressJobMutationPolicy, progressCancelFeatures } from '../../jobPermissions'\nimport {\n hasReadableProgressScope,\n hasWritableProgressScope,\n resolveProgressRequestScope,\n} from '../../requestScope'\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['progress.view'] },\n PUT: { requireAuth: true, requireFeatures: ['progress.update'] },\n DELETE: { requireAuth: true, requireFeatures: progressCancelFeatures },\n}\n\nexport const metadata = routeMetadata\n\nconst jobIdSchema = z.guid()\n\nfunction cannotCancelJobResponse() {\n return NextResponse.json({ error: 'Cannot cancel this job' }, { status: 400 })\n}\n\nexport async function GET(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const scope = await resolveProgressRequestScope(container, auth, req)\n if (!hasReadableProgressScope(scope) || !jobIdSchema.safeParse(params.id).success) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n const progressService = container.resolve('progressService') as ProgressService\n const job = await progressService.getJob(params.id, {\n tenantId: scope.tenantId,\n organizationId: scope.selectedId,\n organizationIds: scope.filterIds,\n userId: auth.sub,\n })\n\n if (!job) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n\n return NextResponse.json({\n id: job.id,\n jobType: job.jobType,\n name: job.name,\n description: job.description,\n status: job.status,\n progressPercent: job.progressPercent,\n processedCount: job.processedCount,\n totalCount: job.totalCount,\n etaSeconds: job.etaSeconds,\n cancellable: job.cancellable,\n meta: job.meta,\n resultSummary: job.resultSummary,\n errorMessage: job.errorMessage,\n startedByUserId: job.startedByUserId,\n startedAt: job.startedAt?.toISOString() ?? null,\n heartbeatAt: job.heartbeatAt?.toISOString() ?? null,\n finishedAt: job.finishedAt?.toISOString() ?? null,\n parentJobId: job.parentJobId,\n partitionIndex: job.partitionIndex,\n partitionCount: job.partitionCount,\n createdAt: job.createdAt.toISOString(),\n updatedAt: job.updatedAt.toISOString(),\n tenantId: job.tenantId,\n organizationId: job.organizationId,\n })\n}\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const body = await req.json()\n const parsed = updateProgressSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid input', details: parsed.error.flatten() }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const scope = await resolveProgressRequestScope(container, auth, req)\n if (!hasWritableProgressScope(scope)) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n const progressService = container.resolve('progressService') as ProgressService\n const progressContext = {\n tenantId: scope.tenantId,\n organizationId: scope.selectedId,\n organizationIds: scope.filterIds,\n userId: auth.sub,\n }\n const existing = jobIdSchema.safeParse(params.id).success\n ? await progressService.getJob(params.id, progressContext)\n : null\n const canMutateJob = createProgressJobMutationPolicy(container, auth)\n if (!existing || !(await canMutateJob(existing))) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n\n const job = await progressService.updateProgress(params.id, parsed.data, progressContext)\n\n return NextResponse.json({ ok: true, progressPercent: job.progressPercent })\n}\n\nexport async function DELETE(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const progressService = container.resolve('progressService') as ProgressService\n const scope = await resolveProgressRequestScope(container, auth, req)\n if (!hasWritableProgressScope(scope)) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n const progressContext = {\n tenantId: scope.tenantId,\n organizationId: scope.selectedId,\n organizationIds: scope.filterIds,\n userId: auth.sub,\n }\n try {\n const existing = await progressService.getJob(params.id, progressContext)\n const canMutateJob = createProgressJobMutationPolicy(container, auth)\n if (!existing || !(await canMutateJob(existing))) {\n return cannotCancelJobResponse()\n }\n await progressService.cancelJob(params.id, progressContext)\n return NextResponse.json({ ok: true })\n } catch {\n return cannotCancelJobResponse()\n }\n}\n\nexport const openApi = {\n GET: {\n summary: 'Get progress job details',\n description: 'Returns full details of a specific progress job by ID.',\n tags: ['Progress'],\n responses: {\n 200: { description: 'Progress job details' },\n 404: { description: 'Job not found' },\n },\n },\n PUT: {\n summary: 'Update progress job',\n description: 'Updates progress metrics and heartbeat for a running job. Callers can update jobs they started; updating another user\\'s job requires progress.manage.',\n tags: ['Progress'],\n responses: {\n 200: { description: 'Progress updated' },\n 400: { description: 'Invalid input' },\n 404: { description: 'Job not found' },\n },\n },\n DELETE: {\n summary: 'Cancel progress job',\n description: 'Requests cancellation of a running or pending job. Callers can cancel jobs they started; cancelling another user\\'s job requires progress.manage.',\n tags: ['Progress'],\n responses: {\n 200: { description: 'Cancellation requested' },\n 400: { description: 'Cannot cancel this job' },\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,4BAA4B;AAErC,SAAS,iCAAiC,8BAA8B;AACxE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA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;AAAA,EACf;AACA,MAAI;AACF,UAAM,WAAW,MAAM,gBAAgB,OAAO,OAAO,IAAI,eAAe;AACxE,UAAM,eAAe,gCAAgC,WAAW,IAAI;AACpE,QAAI,CAAC,YAAY,CAAE,MAAM,aAAa,QAAQ,GAAI;AAChD,aAAO,wBAAwB;AAAA,IACjC;AACA,UAAM,gBAAgB,UAAU,OAAO,IAAI,eAAe;AAC1D,WAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AAAA,EACvC,QAAQ;AACN,WAAO,wBAAwB;AAAA,EACjC;AACF;AAEO,MAAM,UAAU;AAAA,EACrB,KAAK;AAAA,IACH,SAAS;AAAA,IACT,aAAa;AAAA,IACb,MAAM,CAAC,UAAU;AAAA,IACjB,WAAW;AAAA,MACT,KAAK,EAAE,aAAa,uBAAuB;AAAA,MAC3C,KAAK,EAAE,aAAa,gBAAgB;AAAA,IACtC;AAAA,EACF;AAAA,EACA,KAAK;AAAA,IACH,SAAS;AAAA,IACT,aAAa;AAAA,IACb,MAAM,CAAC,UAAU;AAAA,IACjB,WAAW;AAAA,MACT,KAAK,EAAE,aAAa,mBAAmB;AAAA,MACvC,KAAK,EAAE,aAAa,gBAAgB;AAAA,MACpC,KAAK,EAAE,aAAa,gBAAgB;AAAA,IACtC;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN,SAAS;AAAA,IACT,aAAa;AAAA,IACb,MAAM,CAAC,UAAU;AAAA,IACjB,WAAW;AAAA,MACT,KAAK,EAAE,aAAa,yBAAyB;AAAA,MAC7C,KAAK,EAAE,aAAa,yBAAyB;AAAA,IAC/C;AAAA,EACF;AACF;",
|
|
6
6
|
"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.8541.1.955f210e1d",
|
|
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.8541.1.955f210e1d",
|
|
272
|
+
"@open-mercato/shared": "0.11.1-develop.8541.1.955f210e1d",
|
|
273
|
+
"@open-mercato/ui": "0.11.1-develop.8541.1.955f210e1d",
|
|
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.8541.1.955f210e1d",
|
|
279
|
+
"@open-mercato/shared": "0.11.1-develop.8541.1.955f210e1d",
|
|
280
|
+
"@open-mercato/ui": "0.11.1-develop.8541.1.955f210e1d",
|
|
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",
|
|
@@ -79,6 +79,13 @@ function isAclData(value: unknown): value is AclData {
|
|
|
79
79
|
return true
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
function aclAllowsOrganizationScope(acl: AclData, organizationId: string | null): boolean {
|
|
83
|
+
if (acl.isSuperAdmin || !acl.organizations) return true
|
|
84
|
+
if (acl.organizations.includes('__all__')) return true
|
|
85
|
+
if (!organizationId) return acl.organizations.length > 0
|
|
86
|
+
return acl.organizations.includes(organizationId)
|
|
87
|
+
}
|
|
88
|
+
|
|
82
89
|
function isRestrictedRoleAcl(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {
|
|
83
90
|
return Array.isArray(acl.organizationsJson)
|
|
84
91
|
&& acl.organizationsJson.length > 0
|
|
@@ -912,15 +919,10 @@ export class RbacService {
|
|
|
912
919
|
): Promise<boolean> {
|
|
913
920
|
if (!required.length) return true
|
|
914
921
|
const acl = await this.loadAclWithEntityManager(em, userId, scope)
|
|
915
|
-
const organizationAllowed = acl.isSuperAdmin
|
|
916
|
-
|| !acl.organizations
|
|
917
|
-
|| !scope.organizationId
|
|
918
|
-
|| acl.organizations.includes(scope.organizationId)
|
|
919
|
-
|| acl.organizations.includes('__all__')
|
|
920
922
|
return authorizeFeatures(required, {
|
|
921
923
|
grantedFeatures: acl.features,
|
|
922
924
|
unrestricted: acl.isSuperAdmin,
|
|
923
|
-
scopeAllowed:
|
|
925
|
+
scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId),
|
|
924
926
|
})
|
|
925
927
|
}
|
|
926
928
|
|
|
@@ -931,14 +933,7 @@ export class RbacService {
|
|
|
931
933
|
): Promise<string[]> {
|
|
932
934
|
const acl = await this.loadAclWithEntityManager(em, userId, scope)
|
|
933
935
|
if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])
|
|
934
|
-
if (
|
|
935
|
-
acl.organizations
|
|
936
|
-
&& scope.organizationId
|
|
937
|
-
&& !acl.organizations.includes(scope.organizationId)
|
|
938
|
-
&& !acl.organizations.includes('__all__')
|
|
939
|
-
) {
|
|
940
|
-
return []
|
|
941
|
-
}
|
|
936
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []
|
|
942
937
|
return filterGrantsByEnabledModules(acl.features)
|
|
943
938
|
}
|
|
944
939
|
|
|
@@ -1016,15 +1011,10 @@ export class RbacService {
|
|
|
1016
1011
|
async userHasAllFeatures(userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean> {
|
|
1017
1012
|
if (!required.length) return true
|
|
1018
1013
|
const acl = await this.loadAcl(userId, scope)
|
|
1019
|
-
const organizationAllowed = acl.isSuperAdmin
|
|
1020
|
-
|| !acl.organizations
|
|
1021
|
-
|| !scope.organizationId
|
|
1022
|
-
|| acl.organizations.includes(scope.organizationId)
|
|
1023
|
-
|| acl.organizations.includes('__all__')
|
|
1024
1014
|
return authorizeFeatures(required, {
|
|
1025
1015
|
grantedFeatures: acl.features,
|
|
1026
1016
|
unrestricted: acl.isSuperAdmin,
|
|
1027
|
-
scopeAllowed:
|
|
1017
|
+
scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId),
|
|
1028
1018
|
})
|
|
1029
1019
|
}
|
|
1030
1020
|
|
|
@@ -1273,14 +1263,7 @@ export class RbacService {
|
|
|
1273
1263
|
): Promise<string[]> {
|
|
1274
1264
|
const acl = await this.loadAcl(userId, scope)
|
|
1275
1265
|
if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])
|
|
1276
|
-
if (
|
|
1277
|
-
acl.organizations &&
|
|
1278
|
-
scope.organizationId &&
|
|
1279
|
-
!acl.organizations.includes(scope.organizationId) &&
|
|
1280
|
-
!acl.organizations.includes('__all__')
|
|
1281
|
-
) {
|
|
1282
|
-
return []
|
|
1283
|
-
}
|
|
1266
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []
|
|
1284
1267
|
return filterGrantsByEnabledModules(acl.features)
|
|
1285
1268
|
}
|
|
1286
1269
|
|
|
@@ -1290,12 +1273,7 @@ export class RbacService {
|
|
|
1290
1273
|
scope: { tenantId: string | null; organizationId: string | null },
|
|
1291
1274
|
): Promise<string[]> {
|
|
1292
1275
|
const acl = await this.loadAcl(userId, scope)
|
|
1293
|
-
|
|
1294
|
-
|| !acl.organizations
|
|
1295
|
-
|| !scope.organizationId
|
|
1296
|
-
|| acl.organizations.includes(scope.organizationId)
|
|
1297
|
-
|| acl.organizations.includes('__all__')
|
|
1298
|
-
if (!organizationAllowed) return []
|
|
1276
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []
|
|
1299
1277
|
return resolveEffectiveFeatures(acl.isSuperAdmin ? ['*'] : acl.features)
|
|
1300
1278
|
}
|
|
1301
1279
|
}
|
|
@@ -597,7 +597,7 @@ export async function resolveFeatureCheckContext({
|
|
|
597
597
|
let scope = boundFeatureScope
|
|
598
598
|
? boundFeatureScope.scope
|
|
599
599
|
: await resolveOrganizationScopeForRequest({ container, auth, request, selectedId, tenantId })
|
|
600
|
-
|
|
600
|
+
let organizationId = boundFeatureScope
|
|
601
601
|
? boundFeatureScope.organizationId
|
|
602
602
|
: resolveFeatureCheckOrganizationId(scope, auth)
|
|
603
603
|
if (
|
|
@@ -635,7 +635,7 @@ export async function resolveFeatureCheckContext({
|
|
|
635
635
|
)
|
|
636
636
|
const approvedOrganizationIds = Array.from(new Set(
|
|
637
637
|
featureOrganizationIds.filter((featureOrganizationId) => candidateOrganizationIds.has(featureOrganizationId)),
|
|
638
|
-
))
|
|
638
|
+
)).sort((left, right) => left.localeCompare(right))
|
|
639
639
|
scope = {
|
|
640
640
|
...scope,
|
|
641
641
|
selectedId: null,
|
|
@@ -643,6 +643,7 @@ export async function resolveFeatureCheckContext({
|
|
|
643
643
|
allowedIds: approvedOrganizationIds,
|
|
644
644
|
tenantId: scope.tenantId,
|
|
645
645
|
}
|
|
646
|
+
if (!organizationId) organizationId = resolveFeatureCheckOrganizationId(scope, auth)
|
|
646
647
|
}
|
|
647
648
|
bindFeatureScopeToRequest(request, { userId: auth.sub, scope, organizationId })
|
|
648
649
|
}
|
|
@@ -4,7 +4,8 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
|
4
4
|
import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
5
5
|
import { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'
|
|
6
6
|
import { upsertEncryptionMapSchema } from '@open-mercato/core/modules/entities/data/validators'
|
|
7
|
-
import { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
7
|
+
import { CrudHttpError, forbidden, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
8
|
+
import { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'
|
|
8
9
|
import {
|
|
9
10
|
buildOptimisticLockConflictBody,
|
|
10
11
|
enforceCommandOptimisticLock,
|
|
@@ -62,6 +63,10 @@ export async function GET(req: Request) {
|
|
|
62
63
|
|
|
63
64
|
const container = await createRequestContainer()
|
|
64
65
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })
|
|
66
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) {
|
|
67
|
+
const denied = forbidden()
|
|
68
|
+
return NextResponse.json(denied.body, { status: denied.status })
|
|
69
|
+
}
|
|
65
70
|
const tenantId = scope.tenantId ?? auth.tenantId
|
|
66
71
|
const organizationId = scope.selectedId
|
|
67
72
|
const em = container.resolve('em') as any
|
|
@@ -108,6 +113,7 @@ export async function POST(req: Request) {
|
|
|
108
113
|
|
|
109
114
|
const container = await createRequestContainer()
|
|
110
115
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })
|
|
116
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) throw forbidden()
|
|
111
117
|
if (scope.selectionRejected) {
|
|
112
118
|
return NextResponse.json(
|
|
113
119
|
{
|
|
@@ -227,6 +233,8 @@ const conflictResponseSchema = z.object({
|
|
|
227
233
|
expectedUpdatedAt: z.string(),
|
|
228
234
|
})
|
|
229
235
|
|
|
236
|
+
const forbiddenResponseSchema = z.object({ error: z.string() })
|
|
237
|
+
|
|
230
238
|
const organizationSelectionInvalidResponseSchema = z.object({
|
|
231
239
|
error: z.string(),
|
|
232
240
|
code: z.literal('organization_selection_invalid'),
|
|
@@ -240,7 +248,10 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
240
248
|
summary: 'Fetch encryption map',
|
|
241
249
|
description: 'Returns the encrypted field map for the current tenant/organization scope.',
|
|
242
250
|
query: z.object({ entityId: z.string() }),
|
|
243
|
-
responses: [
|
|
251
|
+
responses: [
|
|
252
|
+
{ status: 200, description: 'Map', schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) },
|
|
253
|
+
{ status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },
|
|
254
|
+
],
|
|
244
255
|
},
|
|
245
256
|
POST: {
|
|
246
257
|
summary: 'Upsert encryption map',
|
|
@@ -248,6 +259,7 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
248
259
|
requestBody: { contentType: 'application/json', schema: upsertEncryptionMapSchema },
|
|
249
260
|
responses: [
|
|
250
261
|
{ status: 200, description: 'Saved', schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },
|
|
262
|
+
{ status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },
|
|
251
263
|
{ status: 409, description: 'Optimistic-lock conflict (stale write)', schema: conflictResponseSchema },
|
|
252
264
|
{ status: 422, description: 'Selected organization is unavailable', schema: organizationSelectionInvalidResponseSchema },
|
|
253
265
|
],
|
|
@@ -5,7 +5,7 @@ import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
|
5
5
|
import type { QueryEngine, QueryOptions, Where, Sort } from '@open-mercato/shared/lib/query/types'
|
|
6
6
|
import { normalizeExportFormat, serializeExport, defaultExportFilename, ensureColumns } from '@open-mercato/shared/lib/crud/exporters'
|
|
7
7
|
import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
|
|
8
|
-
import { resolveOrganizationScope, getSelectedOrganizationFromRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'
|
|
8
|
+
import { resolveOrganizationScope, resolveOrganizationScopeForRequest, getSelectedOrganizationFromRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'
|
|
9
9
|
import { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'
|
|
10
10
|
import { SYSTEM_ENTITY_RECORDS_BLOCKED_CODE } from '@open-mercato/shared/lib/data/engine'
|
|
11
11
|
import { parseBooleanToken, parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'
|
|
@@ -138,11 +138,12 @@ export async function GET(req: Request) {
|
|
|
138
138
|
}
|
|
139
139
|
|
|
140
140
|
try {
|
|
141
|
-
const
|
|
141
|
+
const container = await createRequestContainer()
|
|
142
|
+
const { resolve } = container
|
|
142
143
|
const qe = resolve('queryEngine') as QueryEngine
|
|
143
144
|
const em = resolve('em') as any
|
|
144
145
|
const rbac = resolve('rbacService') as RbacService
|
|
145
|
-
const scope = await
|
|
146
|
+
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })
|
|
146
147
|
let organizationIds: string[] | null = scope.filterIds
|
|
147
148
|
// Module-declared custom entities (ce.ts) carry frozen system-style ids and are never
|
|
148
149
|
// registered in `custom_entities`, so classification checks the declared registry plus
|
|
@@ -280,13 +280,13 @@ function RecordsPageInner({ params }: { params: { entityId?: string } }) {
|
|
|
280
280
|
<>
|
|
281
281
|
<Button asChild variant="outline" size="sm">
|
|
282
282
|
<Link href={`/backend/entities/user/${encodeURIComponent(entityId)}`}>
|
|
283
|
-
Edit Entity Definition
|
|
283
|
+
{t('entities.userEntities.records.actions.editDefinition', 'Edit Entity Definition')}
|
|
284
284
|
</Link>
|
|
285
285
|
</Button>
|
|
286
286
|
{hasAnyFormFields && (
|
|
287
287
|
<Button asChild>
|
|
288
288
|
<Link href={`/backend/entities/user/${encodeURIComponent(entityId)}/records/create`}>
|
|
289
|
-
Create
|
|
289
|
+
{t('entities.userEntities.records.form.submitCreate', 'Create')}
|
|
290
290
|
</Link>
|
|
291
291
|
</Button>
|
|
292
292
|
)}
|
|
@@ -300,54 +300,48 @@ function RecordsPageInner({ params }: { params: { entityId?: string } }) {
|
|
|
300
300
|
|
|
301
301
|
return (
|
|
302
302
|
<Page>
|
|
303
|
-
<PageBody>
|
|
304
|
-
<ContextHelp bulb title=
|
|
303
|
+
<PageBody className="[&_h1]:wrap-anywhere">
|
|
304
|
+
<ContextHelp bulb title={t('entities.userEntities.records.apiHelp.title')} className="mb-4">
|
|
305
305
|
<p className="mb-2">
|
|
306
|
-
|
|
306
|
+
{t('entities.userEntities.records.apiHelp.intro')}{' '}
|
|
307
307
|
<a className="underline" target="_blank" rel="noreferrer" href="https://docs.openmercato.com/user-guide/api-keys">
|
|
308
|
-
|
|
309
|
-
</a>
|
|
310
|
-
|
|
308
|
+
{t('entities.userEntities.records.apiHelp.guide')}
|
|
309
|
+
</a>
|
|
310
|
+
{' · '}
|
|
311
311
|
<a className="underline" target="_blank" rel="noreferrer" href="https://docs.openmercato.com/cli/api-keys">
|
|
312
|
-
|
|
313
|
-
</a>
|
|
314
|
-
before running these calls.
|
|
312
|
+
{t('entities.userEntities.records.apiHelp.cli')}
|
|
313
|
+
</a>
|
|
315
314
|
</p>
|
|
316
315
|
<div className="space-y-2">
|
|
317
316
|
<div>
|
|
318
|
-
<div className="font-medium mb-1">
|
|
317
|
+
<div className="font-medium mb-1">{t('entities.userEntities.records.apiHelp.environment')}</div>
|
|
319
318
|
<pre className="bg-muted p-3 rounded text-xs overflow-auto"><code>{`export BASE_URL="http://localhost:3000/api"
|
|
320
319
|
export API_KEY="<paste API key secret here>" # scoped with entities.features
|
|
321
320
|
export ENTITY_ID="${entityId}"
|
|
322
321
|
export RECORD_ID="<record uuid>"`}</code></pre>
|
|
323
322
|
<p className="text-muted-foreground mt-1">
|
|
324
|
-
|
|
325
|
-
<a className="underline" target="_blank" rel="noreferrer" href="https://docs.openmercato.com/user-guide/api-keys">
|
|
326
|
-
Managing API keys
|
|
327
|
-
</a>{' '}
|
|
328
|
-
walkthrough or mint one via{' '}
|
|
323
|
+
{t('entities.userEntities.records.apiHelp.keyHelp')}{' '}
|
|
329
324
|
<a className="underline" target="_blank" rel="noreferrer" href="https://docs.openmercato.com/cli/api-keys">
|
|
330
325
|
mercato api_keys add
|
|
331
|
-
</a
|
|
332
|
-
.
|
|
326
|
+
</a>.
|
|
333
327
|
</p>
|
|
334
328
|
</div>
|
|
335
329
|
|
|
336
330
|
<div>
|
|
337
|
-
<div className="font-medium mb-1">
|
|
331
|
+
<div className="font-medium mb-1">{t('entities.userEntities.records.apiHelp.list')}</div>
|
|
338
332
|
<pre className="bg-muted p-3 rounded text-xs overflow-auto"><code>{`curl -s -H "X-Api-Key: $API_KEY" \
|
|
339
333
|
"$BASE_URL/entities/records?entityId=$ENTITY_ID" | jq`}</code></pre>
|
|
340
334
|
</div>
|
|
341
335
|
|
|
342
336
|
<div>
|
|
343
|
-
<div className="font-medium mb-1">
|
|
337
|
+
<div className="font-medium mb-1">{t('entities.userEntities.records.apiHelp.read')}</div>
|
|
344
338
|
<pre className="bg-muted p-3 rounded text-xs overflow-auto"><code>{`curl -s -H "X-Api-Key: $API_KEY" \
|
|
345
339
|
"$BASE_URL/entities/records?entityId=$ENTITY_ID&id=$RECORD_ID" | jq`}</code></pre>
|
|
346
|
-
<p className="text-muted-foreground mt-1">
|
|
340
|
+
<p className="text-muted-foreground mt-1">{t('entities.userEntities.records.apiHelp.readNote')}</p>
|
|
347
341
|
</div>
|
|
348
342
|
|
|
349
343
|
<div>
|
|
350
|
-
<div className="font-medium mb-1">
|
|
344
|
+
<div className="font-medium mb-1">{t('entities.userEntities.records.apiHelp.create')}</div>
|
|
351
345
|
<pre className="bg-muted p-3 rounded text-xs overflow-auto"><code>{`curl -s -X POST \
|
|
352
346
|
-H "X-Api-Key: $API_KEY" \
|
|
353
347
|
-H "Content-Type: application/json" \
|
|
@@ -359,11 +353,11 @@ export RECORD_ID="<record uuid>"`}</code></pre>
|
|
|
359
353
|
}
|
|
360
354
|
}" \
|
|
361
355
|
"$BASE_URL/entities/records" | jq`}</code></pre>
|
|
362
|
-
<p className="text-muted-foreground mt-1">
|
|
356
|
+
<p className="text-muted-foreground mt-1">{t('entities.userEntities.records.apiHelp.createNote')}</p>
|
|
363
357
|
</div>
|
|
364
358
|
|
|
365
359
|
<div>
|
|
366
|
-
<div className="font-medium mb-1">
|
|
360
|
+
<div className="font-medium mb-1">{t('entities.userEntities.records.apiHelp.update')}</div>
|
|
367
361
|
<pre className="bg-muted p-3 rounded text-xs overflow-auto"><code>{`curl -s -X PUT \
|
|
368
362
|
-H "X-Api-Key: $API_KEY" \
|
|
369
363
|
-H "Content-Type: application/json" \
|
|
@@ -378,18 +372,18 @@ export RECORD_ID="<record uuid>"`}</code></pre>
|
|
|
378
372
|
</div>
|
|
379
373
|
|
|
380
374
|
<div>
|
|
381
|
-
<div className="font-medium mb-1">
|
|
375
|
+
<div className="font-medium mb-1">{t('entities.userEntities.records.apiHelp.delete')}</div>
|
|
382
376
|
<pre className="bg-muted p-3 rounded text-xs overflow-auto"><code>{`curl -s -X DELETE \
|
|
383
377
|
-H "X-Api-Key: $API_KEY" \
|
|
384
378
|
"$BASE_URL/entities/records?entityId=$ENTITY_ID&recordId=$RECORD_ID" | jq`}</code></pre>
|
|
385
379
|
</div>
|
|
386
380
|
|
|
387
381
|
<div className="text-muted-foreground">
|
|
388
|
-
|
|
382
|
+
{t('entities.userEntities.records.apiHelp.security')}
|
|
389
383
|
<ul className="list-disc pl-5 mt-1 space-y-1">
|
|
390
|
-
<li>
|
|
391
|
-
<li>
|
|
392
|
-
<li>
|
|
384
|
+
<li>{t('entities.userEntities.records.apiHelp.scope')}</li>
|
|
385
|
+
<li>{t('entities.userEntities.records.apiHelp.rotate')}</li>
|
|
386
|
+
<li>{t('entities.userEntities.records.apiHelp.protect')}</li>
|
|
393
387
|
</ul>
|
|
394
388
|
</div>
|
|
395
389
|
</div>
|
|
@@ -397,7 +391,7 @@ export RECORD_ID="<record uuid>"`}</code></pre>
|
|
|
397
391
|
<RelationDisplaysProvider displaysByField={relationDisplaysByField}>
|
|
398
392
|
<DataTable
|
|
399
393
|
stickyActionsColumn
|
|
400
|
-
title={
|
|
394
|
+
title={t('entities.userEntities.records.title', 'Records: {{entityId}}', { entityId })}
|
|
401
395
|
titleHeadingLevel={1}
|
|
402
396
|
entityId={entityId}
|
|
403
397
|
actions={actions}
|