@open-mercato/core 0.6.7-develop.6593.1.0ecf630f1e → 0.6.7-develop.6594.1.5581f765f4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/custom_entity/index.js +2 -0
  3. package/dist/generated/entities/custom_entity/index.js.map +2 -2
  4. package/dist/generated/entity-fields-registry.js +1 -0
  5. package/dist/generated/entity-fields-registry.js.map +2 -2
  6. package/dist/modules/auth/api/features.js +14 -0
  7. package/dist/modules/auth/api/features.js.map +2 -2
  8. package/dist/modules/entities/api/entities.js +20 -0
  9. package/dist/modules/entities/api/entities.js.map +2 -2
  10. package/dist/modules/entities/api/entity-settings.js +89 -0
  11. package/dist/modules/entities/api/entity-settings.js.map +7 -0
  12. package/dist/modules/entities/api/records.js +46 -25
  13. package/dist/modules/entities/api/records.js.map +2 -2
  14. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +13 -4
  15. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  16. package/dist/modules/entities/backend/entities/user/create/page.js +27 -2
  17. package/dist/modules/entities/backend/entities/user/create/page.js.map +2 -2
  18. package/dist/modules/entities/data/entities.js +4 -0
  19. package/dist/modules/entities/data/entities.js.map +2 -2
  20. package/dist/modules/entities/lib/entityAcl.js +17 -4
  21. package/dist/modules/entities/lib/entityAcl.js.map +3 -3
  22. package/dist/modules/entities/lib/install-from-ce.js +2 -0
  23. package/dist/modules/entities/lib/install-from-ce.js.map +2 -2
  24. package/dist/modules/entities/lib/recordFeatures.js +24 -0
  25. package/dist/modules/entities/lib/recordFeatures.js.map +7 -0
  26. package/dist/modules/entities/lib/register.js +3 -0
  27. package/dist/modules/entities/lib/register.js.map +2 -2
  28. package/dist/modules/entities/lib/restrictedEntityFeatures.js +62 -0
  29. package/dist/modules/entities/lib/restrictedEntityFeatures.js.map +7 -0
  30. package/dist/modules/entities/migrations/Migration20260716120000.js +13 -0
  31. package/dist/modules/entities/migrations/Migration20260716120000.js.map +7 -0
  32. package/generated/entities/custom_entity/index.ts +1 -0
  33. package/generated/entity-fields-registry.ts +1 -0
  34. package/package.json +7 -7
  35. package/src/modules/auth/api/features.ts +17 -0
  36. package/src/modules/entities/api/entities.ts +28 -0
  37. package/src/modules/entities/api/entity-settings.ts +103 -0
  38. package/src/modules/entities/api/records.ts +70 -29
  39. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +12 -3
  40. package/src/modules/entities/backend/entities/user/create/page.tsx +33 -1
  41. package/src/modules/entities/data/entities.ts +6 -0
  42. package/src/modules/entities/i18n/de.json +3 -0
  43. package/src/modules/entities/i18n/en.json +3 -0
  44. package/src/modules/entities/i18n/es.json +3 -0
  45. package/src/modules/entities/i18n/pl.json +3 -0
  46. package/src/modules/entities/lib/entityAcl.ts +27 -5
  47. package/src/modules/entities/lib/install-from-ce.ts +2 -0
  48. package/src/modules/entities/lib/recordFeatures.ts +48 -0
  49. package/src/modules/entities/lib/register.ts +4 -0
  50. package/src/modules/entities/lib/restrictedEntityFeatures.ts +98 -0
  51. package/src/modules/entities/migrations/.snapshot-open-mercato.json +10 -0
  52. package/src/modules/entities/migrations/Migration20260716120000.ts +13 -0
@@ -2,6 +2,8 @@ import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import { getModules } from "@open-mercato/shared/lib/i18n/server";
5
+ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
6
+ import { synthesizeRestrictedEntityFeatures } from "@open-mercato/core/modules/entities/lib/restrictedEntityFeatures";
5
7
  const metadata = {
6
8
  GET: { requireAuth: true, requireFeatures: ["auth.acl.manage"] }
7
9
  };
@@ -33,6 +35,18 @@ async function GET(req) {
33
35
  return base;
34
36
  })
35
37
  );
38
+ try {
39
+ const { resolve } = await createRequestContainer();
40
+ const em = resolve("em");
41
+ const synthesized = await synthesizeRestrictedEntityFeatures(em, auth.tenantId ?? null);
42
+ for (const item of synthesized) {
43
+ const deps = normalizeDependsOn(item.dependsOn);
44
+ const base = { id: item.id, title: item.title, module: item.module };
45
+ if (deps) base.dependsOn = deps;
46
+ items.push(base);
47
+ }
48
+ } catch {
49
+ }
36
50
  const byId = /* @__PURE__ */ new Map();
37
51
  for (const it of items) if (!byId.has(it.id)) byId.set(it.id, it);
38
52
  const list = Array.from(byId.values()).sort((a, b) => a.module.localeCompare(b.module) || a.id.localeCompare(b.id));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/api/features.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n}\n\ntype FeatureItem = {\n id: string\n title: string\n module: string\n dependsOn?: string[]\n}\n\nfunction normalizeDependsOn(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: string[] = []\n for (const entry of value) {\n if (typeof entry !== 'string') continue\n const trimmed = entry.trim()\n if (!trimmed) continue\n out.push(trimmed)\n }\n if (out.length === 0) return undefined\n return Array.from(new Set(out))\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const modules = getModules()\n const items: FeatureItem[] = (modules || []).flatMap((m: any) =>\n (m.features || []).map((f: any) => {\n const deps = normalizeDependsOn(f?.dependsOn)\n const base: FeatureItem = {\n id: String(f.id),\n title: String(f.title || f.id),\n module: String(f.module || m.id),\n }\n if (deps) base.dependsOn = deps\n return base\n })\n )\n // Deduplicate by id (keep first occurrence)\n const byId = new Map<string, FeatureItem>()\n for (const it of items) if (!byId.has(it.id)) byId.set(it.id, it)\n const list = Array.from(byId.values()).sort((a, b) => a.module.localeCompare(b.module) || a.id.localeCompare(b.id))\n\n // Build module info map\n const moduleInfo = new Map<string, { id: string; title: string }>()\n for (const m of modules) {\n if (m.id) {\n moduleInfo.set(m.id, { id: m.id, title: (m.info as any)?.title || m.id })\n }\n }\n\n return NextResponse.json({ items: list, modules: Array.from(moduleInfo.values()) })\n}\n\nconst featureItemSchema = z.object({\n id: z.string(),\n title: z.string(),\n module: z.string(),\n dependsOn: z.array(z.string()).optional(),\n})\n\nconst featureModuleSchema = z.object({\n id: z.string(),\n title: z.string(),\n})\n\nconst featuresResponseSchema = z.object({\n items: z.array(featureItemSchema),\n modules: z.array(featureModuleSchema),\n})\n\nconst featuresMethodDoc: OpenApiMethodDoc = {\n summary: 'List declared feature flags',\n description: 'Returns all static features contributed by the enabled modules along with their module source.',\n tags: ['Authentication & Accounts'],\n responses: [\n {\n status: 200,\n description: 'Aggregated feature catalog',\n schema: featuresResponseSchema,\n },\n ],\n errors: [\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'List declared feature flags',\n methods: {\n GET: featuresMethodDoc,\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,kBAAkB;AAEpB,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AACjE;AASA,SAAS,mBAAmB,OAAsC;AAChE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO;AAClC,QAAM,MAAgB,CAAC;AACvB,aAAW,SAAS,OAAO;AACzB,QAAI,OAAO,UAAU,SAAU;AAC/B,UAAM,UAAU,MAAM,KAAK;AAC3B,QAAI,CAAC,QAAS;AACd,QAAI,KAAK,OAAO;AAAA,EAClB;AACA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,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,IAAI,EAAE,OAAO;AAAA,EACb,OAAO,EAAE,OAAO;AAAA,EAChB,QAAQ,EAAE,OAAO;AAAA,EACjB,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAC1C,CAAC;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,IAAI,EAAE,OAAO;AAAA,EACb,OAAO,EAAE,OAAO;AAClB,CAAC;AAED,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,OAAO,EAAE,MAAM,iBAAiB;AAAA,EAChC,SAAS,EAAE,MAAM,mBAAmB;AACtC,CAAC;AAED,MAAM,oBAAsC;AAAA,EAC1C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,2BAA2B;AAAA,EAClC,WAAW;AAAA,IACT;AAAA,MACE,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN;AAAA,MACE,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,IACxC;AAAA,EACF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,EACP;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { synthesizeRestrictedEntityFeatures } from '@open-mercato/core/modules/entities/lib/restrictedEntityFeatures'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n}\n\ntype FeatureItem = {\n id: string\n title: string\n module: string\n dependsOn?: string[]\n}\n\nfunction normalizeDependsOn(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: string[] = []\n for (const entry of value) {\n if (typeof entry !== 'string') continue\n const trimmed = entry.trim()\n if (!trimmed) continue\n out.push(trimmed)\n }\n if (out.length === 0) return undefined\n return Array.from(new Set(out))\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const modules = getModules()\n const items: FeatureItem[] = (modules || []).flatMap((m: any) =>\n (m.features || []).map((f: any) => {\n const deps = normalizeDependsOn(f?.dependsOn)\n const base: FeatureItem = {\n id: String(f.id),\n title: String(f.title || f.id),\n module: String(f.module || m.id),\n }\n if (deps) base.dependsOn = deps\n return base\n })\n )\n // Append synthesized per-entity features for the tenant's restricted custom\n // entities so they can be granted in the ACL editor. Tenant-scoped; never\n // throws (falls back to the static catalog on any failure).\n try {\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as any\n const synthesized = await synthesizeRestrictedEntityFeatures(em, auth.tenantId ?? null)\n for (const item of synthesized) {\n const deps = normalizeDependsOn(item.dependsOn)\n const base: FeatureItem = { id: item.id, title: item.title, module: item.module }\n if (deps) base.dependsOn = deps\n items.push(base)\n }\n } catch {}\n\n // Deduplicate by id (keep first occurrence)\n const byId = new Map<string, FeatureItem>()\n for (const it of items) if (!byId.has(it.id)) byId.set(it.id, it)\n const list = Array.from(byId.values()).sort((a, b) => a.module.localeCompare(b.module) || a.id.localeCompare(b.id))\n\n // Build module info map\n const moduleInfo = new Map<string, { id: string; title: string }>()\n for (const m of modules) {\n if (m.id) {\n moduleInfo.set(m.id, { id: m.id, title: (m.info as any)?.title || m.id })\n }\n }\n\n return NextResponse.json({ items: list, modules: Array.from(moduleInfo.values()) })\n}\n\nconst featureItemSchema = z.object({\n id: z.string(),\n title: z.string(),\n module: z.string(),\n dependsOn: z.array(z.string()).optional(),\n})\n\nconst featureModuleSchema = z.object({\n id: z.string(),\n title: z.string(),\n})\n\nconst featuresResponseSchema = z.object({\n items: z.array(featureItemSchema),\n modules: z.array(featureModuleSchema),\n})\n\nconst featuresMethodDoc: OpenApiMethodDoc = {\n summary: 'List declared feature flags',\n description: 'Returns all static features contributed by the enabled modules along with their module source.',\n tags: ['Authentication & Accounts'],\n responses: [\n {\n status: 200,\n description: 'Aggregated feature catalog',\n schema: featuresResponseSchema,\n },\n ],\n errors: [\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'List declared feature flags',\n methods: {\n GET: featuresMethodDoc,\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AACvC,SAAS,0CAA0C;AAE5C,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AACjE;AASA,SAAS,mBAAmB,OAAsC;AAChE,MAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO;AAClC,QAAM,MAAgB,CAAC;AACvB,aAAW,SAAS,OAAO;AACzB,QAAI,OAAO,UAAU,SAAU;AAC/B,UAAM,UAAU,MAAM,KAAK;AAC3B,QAAI,CAAC,QAAS;AACd,QAAI,KAAK,OAAO;AAAA,EAClB;AACA,MAAI,IAAI,WAAW,EAAG,QAAO;AAC7B,SAAO,MAAM,KAAK,IAAI,IAAI,GAAG,CAAC;AAChC;AAEA,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,KAAM,QAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAC9E,QAAM,UAAU,WAAW;AAC3B,QAAM,SAAwB,WAAW,CAAC,GAAG;AAAA,IAAQ,CAAC,OACn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,SAAS,MAAM,KAAK,WAAW,OAAO,CAAC,EAAE,CAAC;AACpF;AAEA,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACjC,IAAI,EAAE,OAAO;AAAA,EACb,OAAO,EAAE,OAAO;AAAA,EAChB,QAAQ,EAAE,OAAO;AAAA,EACjB,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAC1C,CAAC;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,IAAI,EAAE,OAAO;AAAA,EACb,OAAO,EAAE,OAAO;AAClB,CAAC;AAED,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,OAAO,EAAE,MAAM,iBAAiB;AAAA,EAChC,SAAS,EAAE,MAAM,mBAAmB;AACtC,CAAC;AAED,MAAM,oBAAsC;AAAA,EAC1C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,2BAA2B;AAAA,EAClC,WAAW;AAAA,IACT;AAAA,MACE,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN;AAAA,MACE,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAAA,IACxC;AAAA,EACF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,EACP;AACF;",
6
6
  "names": []
7
7
  }
@@ -55,6 +55,7 @@ async function GET(req) {
55
55
  labelField: c.labelField ?? void 0,
56
56
  defaultEditor: c.defaultEditor ?? void 0,
57
57
  showInSidebar: c.showInSidebar ?? false,
58
+ accessRestricted: c.accessRestricted ?? false,
58
59
  updatedAt: c.updatedAt instanceof Date ? c.updatedAt.toISOString() : c.updatedAt ?? void 0
59
60
  }));
60
61
  const byId = /* @__PURE__ */ new Map();
@@ -97,6 +98,7 @@ async function POST(req) {
97
98
  return NextResponse.json({ error: "Validation failed", details: parsed.error.flatten() }, { status: 400 });
98
99
  }
99
100
  const input = parsed.data;
101
+ const accessRestrictedExplicit = body != null && typeof body === "object" && Object.prototype.hasOwnProperty.call(body, "accessRestricted");
100
102
  const container = await createRequestContainer();
101
103
  const { resolve } = container;
102
104
  const em = resolve("em");
@@ -133,6 +135,7 @@ async function POST(req) {
133
135
  mutationPayload: input
134
136
  });
135
137
  if (guard.blockedResponse) return guard.blockedResponse;
138
+ const isCreate = !ent;
136
139
  if (!ent) ent = em.create(CustomEntity, { ...where, createdAt: /* @__PURE__ */ new Date() });
137
140
  ent.label = input.label;
138
141
  ent.description = input.description ?? null;
@@ -140,6 +143,22 @@ async function POST(req) {
140
143
  ent.labelField = input.labelField ?? ent.labelField ?? null;
141
144
  ent.defaultEditor = input.defaultEditor ?? ent.defaultEditor ?? null;
142
145
  ent.showInSidebar = input.showInSidebar ?? ent.showInSidebar ?? false;
146
+ if (accessRestrictedExplicit) {
147
+ ent.accessRestricted = input.accessRestricted === true;
148
+ } else if (isCreate) {
149
+ let policyDefault = false;
150
+ try {
151
+ const moduleConfigService = resolve("moduleConfigService");
152
+ policyDefault = await moduleConfigService.getValue("entities", "newEntitiesRestrictedByDefault", {
153
+ defaultValue: false,
154
+ scope: { tenantId: auth.tenantId ?? null }
155
+ }) === true;
156
+ } catch {
157
+ }
158
+ ent.accessRestricted = policyDefault;
159
+ } else {
160
+ ent.accessRestricted = ent.accessRestricted ?? false;
161
+ }
143
162
  ent.updatedAt = /* @__PURE__ */ new Date();
144
163
  em.persist(ent);
145
164
  await em.flush();
@@ -203,6 +222,7 @@ const entitySummarySchema = z.object({
203
222
  labelField: z.string().optional(),
204
223
  defaultEditor: z.string().optional(),
205
224
  showInSidebar: z.boolean().optional(),
225
+ accessRestricted: z.boolean().optional(),
206
226
  updatedAt: z.string().optional(),
207
227
  count: z.number()
208
228
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/entities/api/entities.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, CustomFieldDef } from '@open-mercato/core/modules/entities/data/entities'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport { upsertCustomEntitySchema } from '@open-mercato/core/modules/entities/data/validators'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { isSystemEntitySelectable } from '@open-mercato/shared/lib/entities/system-entities'\nimport { SYSTEM_ENTITY_RECORDS_BLOCKED_CODE, isOrmBackedSystemEntityId } from '@open-mercato/shared/lib/data/engine'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n beginEntitiesMutationGuard,\n ENTITY_DEFINITION_RESOURCE_KIND,\n} from './definitions.mutation-guard'\n\nconst CUSTOM_ENTITY_DEFINITION_RESOURCE_KIND = ENTITY_DEFINITION_RESOURCE_KIND\n\nexport const metadata = {\n GET: { requireAuth: true },\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as any\n\n // Generated entities from code\n const AllEntities = getEntityIds()\n const generated: { entityId: string; source: 'code'; label: string }[] = []\n for (const modId of Object.keys(AllEntities)) {\n const entities = (AllEntities as any)[modId] as Record<string, string>\n for (const k of Object.keys(entities)) {\n const id = entities[k]\n if (!isSystemEntitySelectable(id)) continue\n generated.push({ entityId: id, source: 'code', label: id })\n }\n }\n\n // Custom user-defined entities (global/org/tenant scoped)\n const where: any = { isActive: true }\n where.$and = [\n { $or: [ { organizationId: auth.orgId ?? undefined as any }, { organizationId: null } ] },\n { $or: [ { tenantId: auth.tenantId ?? undefined as any }, { tenantId: null } ] },\n ]\n const customs = await em.find(CustomEntity as any, where as any, { orderBy: { entityId: 'asc' } as any })\n // Resolve overlay precedence: prefer organization/tenant-specific over global\n const customByEntityId = new Map<string, any>()\n for (const c of customs as any[]) {\n const specificity = (c.organizationId ? 2 : 0) + (c.tenantId ? 1 : 0)\n const prev = customByEntityId.get(c.entityId)\n const prevSpec = prev ? ((prev.organizationId ? 2 : 0) + (prev.tenantId ? 1 : 0)) : -1\n if (!prev || specificity > prevSpec) customByEntityId.set(c.entityId, c)\n }\n\n const custom = Array.from(customByEntityId.values())\n .filter((c) => isSystemEntitySelectable(c.entityId))\n .map((c) => ({\n entityId: c.entityId,\n source: 'custom' as const,\n label: c.label,\n description: c.description ?? undefined,\n labelField: (c as any).labelField ?? undefined,\n defaultEditor: (c as any).defaultEditor ?? undefined,\n showInSidebar: (c as any).showInSidebar ?? false,\n updatedAt: c.updatedAt instanceof Date ? c.updatedAt.toISOString() : (c.updatedAt ?? undefined),\n }))\n\n const byId = new Map<string, any>()\n for (const g of generated) byId.set(g.entityId, g)\n for (const cu of custom) {\n const existing = byId.get(cu.entityId)\n byId.set(cu.entityId, { ...existing, ...cu, source: existing?.source ?? cu.source })\n }\n\n // Count field definitions scoped to current tenant/org (same scoping as custom entities)\n const defsWhere: any = { isActive: true }\n defsWhere.$and = [\n //{ $or: [ { organizationId: auth.orgId ?? undefined as any }, { organizationId: null } ] }, // the entities and custom fields are defined per tenant\n { tenantId: auth.tenantId ?? undefined as any },\n ]\n const defs = await em.find(CustomFieldDef as any, defsWhere as any)\n // Count distinct field names (keys) per entityId\n const keySets = new Map<string, Set<string>>()\n for (const d of defs as any[]) {\n const eid = String(d.entityId)\n const k = String(d.key)\n if (!isSystemEntitySelectable(eid)) continue\n const set = keySets.get(eid) || new Set<string>()\n set.add(k)\n keySets.set(eid, set)\n }\n const counts: Record<string, number> = {}\n for (const [eid, set] of keySets.entries()) counts[eid] = set.size\n\n const items = Array.from(byId.values()).map((it: any) => ({ ...it, count: counts[it.entityId] || 0 }))\n return NextResponse.json({ items })\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const parsed = upsertCustomEntitySchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Validation failed', details: parsed.error.flatten() }, { status: 400 })\n }\n const input = parsed.data\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = resolve('em') as any\n\n // A registration for a module-declared, table-backed system entity would flip\n // query-engine classification to doc storage for the whole entity type (#2939's\n // failure mode via another door) \u2014 refuse to create one.\n if (isOrmBackedSystemEntityId(em, input.entityId)) {\n return NextResponse.json(\n { error: 'System entities cannot be registered as custom entities', code: SYSTEM_ENTITY_RECORDS_BLOCKED_CODE, entityId: input.entityId },\n { status: 400 },\n )\n }\n\n const where: any = { entityId: input.entityId, organizationId: auth.orgId ?? null, tenantId: auth.tenantId ?? null }\n let ent = await em.findOne(CustomEntity, where)\n if (ent) {\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: CUSTOM_ENTITY_DEFINITION_RESOURCE_KIND,\n resourceId: ent.id,\n current: ent.updatedAt ?? null,\n request: req,\n })\n } catch (lockError) {\n if (isCrudHttpError(lockError)) {\n return NextResponse.json(lockError.body, { status: lockError.status })\n }\n throw lockError\n }\n }\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: ENTITY_DEFINITION_RESOURCE_KIND,\n resourceId: ent ? ent.id : input.entityId,\n operation: ent ? 'update' : 'create',\n mutationPayload: input as unknown as Record<string, unknown>,\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n if (!ent) ent = em.create(CustomEntity, { ...where, createdAt: new Date() })\n ent.label = input.label\n ent.description = input.description ?? null\n ent.isActive = input.isActive ?? true\n ent.labelField = input.labelField ?? ent.labelField ?? null\n ent.defaultEditor = input.defaultEditor ?? ent.defaultEditor ?? null\n ent.showInSidebar = input.showInSidebar ?? ent.showInSidebar ?? false\n ent.updatedAt = new Date()\n em.persist(ent)\n await em.flush()\n await guard.runAfterSuccess()\n // Invalidate sidebar/nav cache for tenant scope (also when tenantId is null)\n try {\n const cache = (await createRequestContainer()).resolve('cache') as any\n if (cache) {\n await cache.deleteByTags([`nav:entities:${auth.tenantId || 'null'}`])\n }\n } catch {}\n return NextResponse.json({ ok: true, item: { id: ent.id, entityId: ent.entityId, label: ent.label, description: ent.description ?? undefined } })\n}\n\nexport async function DELETE(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const entityId = body?.entityId\n if (!entityId) return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = resolve('em') as any\n\n const where: any = { entityId, organizationId: auth.orgId ?? null, tenantId: auth.tenantId ?? null }\n const ent = await em.findOne(CustomEntity, where)\n if (!ent) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: ENTITY_DEFINITION_RESOURCE_KIND,\n resourceId: ent.id,\n operation: 'delete',\n mutationPayload: { entityId },\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n ent.isActive = false\n ent.updatedAt = new Date()\n ent.deletedAt = ent.deletedAt ?? new Date()\n em.persist(ent)\n await em.flush()\n await guard.runAfterSuccess()\n // Invalidate sidebar/nav cache for tenant scope (also when tenantId is null)\n try {\n const cache = (await createRequestContainer()).resolve('cache') as any\n if (cache) {\n await cache.deleteByTags([`nav:entities:${auth.tenantId || 'null'}`])\n }\n } catch {}\n return NextResponse.json({ ok: true })\n}\n\nconst entitySummarySchema = z.object({\n entityId: z.string(),\n source: z.enum(['code', 'custom']),\n label: z.string(),\n description: z.string().optional(),\n labelField: z.string().optional(),\n defaultEditor: z.string().optional(),\n showInSidebar: z.boolean().optional(),\n updatedAt: z.string().optional(),\n count: z.number(),\n})\n\nconst entityListResponseSchema = z.object({\n items: z.array(entitySummarySchema),\n})\n\nconst deleteEntityRequestSchema = z.object({\n entityId: z.string(),\n})\n\nconst upsertCustomEntityResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string().uuid(),\n entityId: z.string(),\n label: z.string(),\n description: z.string().optional(),\n }),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage custom entities',\n methods: {\n GET: {\n summary: 'List available entities',\n description: 'Returns generated and custom entities scoped to the caller with field counts per entity.',\n responses: [\n {\n status: 200,\n description: 'List of entities',\n schema: entityListResponseSchema,\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n POST: {\n summary: 'Upsert custom entity',\n description: 'Creates or updates a tenant/org scoped custom entity definition.',\n requestBody: {\n contentType: 'application/json',\n schema: upsertCustomEntitySchema,\n },\n responses: [\n {\n status: 200,\n description: 'Entity saved',\n schema: upsertCustomEntityResponseSchema,\n },\n {\n status: 400,\n description: 'Validation error',\n schema: z.object({\n error: z.string(),\n details: z.any().optional(),\n }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n DELETE: {\n summary: 'Soft delete custom entity',\n description: 'Marks the specified custom entity inactive within the current scope.',\n requestBody: {\n contentType: 'application/json',\n schema: deleteEntityRequestSchema,\n },\n responses: [\n {\n status: 200,\n description: 'Entity deleted',\n schema: z.object({ ok: z.boolean() }),\n },\n {\n status: 400,\n description: 'Missing entity id',\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 status: 404,\n description: 'Entity not found in scope',\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,cAAc,sBAAsB;AAC7C,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AAEzC,SAAS,gCAAgC;AACzC,SAAS,oCAAoC,iCAAiC;AAC9E,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,yCAAyC;AAExC,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,KAAK;AAAA,EACzB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAAA,EAC5E,QAAQ,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAChF;AAEA,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,YAAa,CAAC,KAAK,SAAS,CAAC,KAAK,aAAe,QAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAEvI,QAAM,EAAE,QAAQ,IAAI,MAAM,uBAAuB;AACjD,QAAM,KAAK,QAAQ,IAAI;AAGvB,QAAM,cAAc,aAAa;AACjC,QAAM,YAAmE,CAAC;AAC1E,aAAW,SAAS,OAAO,KAAK,WAAW,GAAG;AAC5C,UAAM,WAAY,YAAoB,KAAK;AAC3C,eAAW,KAAK,OAAO,KAAK,QAAQ,GAAG;AACrC,YAAM,KAAK,SAAS,CAAC;AACrB,UAAI,CAAC,yBAAyB,EAAE,EAAG;AACnC,gBAAU,KAAK,EAAE,UAAU,IAAI,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AS,EAAE,IAAI,EAAE,SAAS;AAAA,UAC5B,CAAC;AAAA,QACH;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,IACA,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAAA,QACtC;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,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;",
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, CustomFieldDef } from '@open-mercato/core/modules/entities/data/entities'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport { upsertCustomEntitySchema } from '@open-mercato/core/modules/entities/data/validators'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { isSystemEntitySelectable } from '@open-mercato/shared/lib/entities/system-entities'\nimport { SYSTEM_ENTITY_RECORDS_BLOCKED_CODE, isOrmBackedSystemEntityId } from '@open-mercato/shared/lib/data/engine'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n beginEntitiesMutationGuard,\n ENTITY_DEFINITION_RESOURCE_KIND,\n} from './definitions.mutation-guard'\n\nconst CUSTOM_ENTITY_DEFINITION_RESOURCE_KIND = ENTITY_DEFINITION_RESOURCE_KIND\n\nexport const metadata = {\n GET: { requireAuth: true },\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId || (!auth.orgId && !auth.isSuperAdmin)) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const { resolve } = await createRequestContainer()\n const em = resolve('em') as any\n\n // Generated entities from code\n const AllEntities = getEntityIds()\n const generated: { entityId: string; source: 'code'; label: string }[] = []\n for (const modId of Object.keys(AllEntities)) {\n const entities = (AllEntities as any)[modId] as Record<string, string>\n for (const k of Object.keys(entities)) {\n const id = entities[k]\n if (!isSystemEntitySelectable(id)) continue\n generated.push({ entityId: id, source: 'code', label: id })\n }\n }\n\n // Custom user-defined entities (global/org/tenant scoped)\n const where: any = { isActive: true }\n where.$and = [\n { $or: [ { organizationId: auth.orgId ?? undefined as any }, { organizationId: null } ] },\n { $or: [ { tenantId: auth.tenantId ?? undefined as any }, { tenantId: null } ] },\n ]\n const customs = await em.find(CustomEntity as any, where as any, { orderBy: { entityId: 'asc' } as any })\n // Resolve overlay precedence: prefer organization/tenant-specific over global\n const customByEntityId = new Map<string, any>()\n for (const c of customs as any[]) {\n const specificity = (c.organizationId ? 2 : 0) + (c.tenantId ? 1 : 0)\n const prev = customByEntityId.get(c.entityId)\n const prevSpec = prev ? ((prev.organizationId ? 2 : 0) + (prev.tenantId ? 1 : 0)) : -1\n if (!prev || specificity > prevSpec) customByEntityId.set(c.entityId, c)\n }\n\n const custom = Array.from(customByEntityId.values())\n .filter((c) => isSystemEntitySelectable(c.entityId))\n .map((c) => ({\n entityId: c.entityId,\n source: 'custom' as const,\n label: c.label,\n description: c.description ?? undefined,\n labelField: (c as any).labelField ?? undefined,\n defaultEditor: (c as any).defaultEditor ?? undefined,\n showInSidebar: (c as any).showInSidebar ?? false,\n accessRestricted: (c as any).accessRestricted ?? false,\n updatedAt: c.updatedAt instanceof Date ? c.updatedAt.toISOString() : (c.updatedAt ?? undefined),\n }))\n\n const byId = new Map<string, any>()\n for (const g of generated) byId.set(g.entityId, g)\n for (const cu of custom) {\n const existing = byId.get(cu.entityId)\n byId.set(cu.entityId, { ...existing, ...cu, source: existing?.source ?? cu.source })\n }\n\n // Count field definitions scoped to current tenant/org (same scoping as custom entities)\n const defsWhere: any = { isActive: true }\n defsWhere.$and = [\n //{ $or: [ { organizationId: auth.orgId ?? undefined as any }, { organizationId: null } ] }, // the entities and custom fields are defined per tenant\n { tenantId: auth.tenantId ?? undefined as any },\n ]\n const defs = await em.find(CustomFieldDef as any, defsWhere as any)\n // Count distinct field names (keys) per entityId\n const keySets = new Map<string, Set<string>>()\n for (const d of defs as any[]) {\n const eid = String(d.entityId)\n const k = String(d.key)\n if (!isSystemEntitySelectable(eid)) continue\n const set = keySets.get(eid) || new Set<string>()\n set.add(k)\n keySets.set(eid, set)\n }\n const counts: Record<string, number> = {}\n for (const [eid, set] of keySets.entries()) counts[eid] = set.size\n\n const items = Array.from(byId.values()).map((it: any) => ({ ...it, count: counts[it.entityId] || 0 }))\n return NextResponse.json({ items })\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const parsed = upsertCustomEntitySchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Validation failed', details: parsed.error.flatten() }, { status: 400 })\n }\n const input = parsed.data\n // Distinguish \"caller did not send the field\" (apply tenant default-restricted\n // policy on create) from \"caller explicitly chose false\".\n const accessRestrictedExplicit = body != null && typeof body === 'object'\n && Object.prototype.hasOwnProperty.call(body, 'accessRestricted')\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = resolve('em') as any\n\n // A registration for a module-declared, table-backed system entity would flip\n // query-engine classification to doc storage for the whole entity type (#2939's\n // failure mode via another door) \u2014 refuse to create one.\n if (isOrmBackedSystemEntityId(em, input.entityId)) {\n return NextResponse.json(\n { error: 'System entities cannot be registered as custom entities', code: SYSTEM_ENTITY_RECORDS_BLOCKED_CODE, entityId: input.entityId },\n { status: 400 },\n )\n }\n\n const where: any = { entityId: input.entityId, organizationId: auth.orgId ?? null, tenantId: auth.tenantId ?? null }\n let ent = await em.findOne(CustomEntity, where)\n if (ent) {\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: CUSTOM_ENTITY_DEFINITION_RESOURCE_KIND,\n resourceId: ent.id,\n current: ent.updatedAt ?? null,\n request: req,\n })\n } catch (lockError) {\n if (isCrudHttpError(lockError)) {\n return NextResponse.json(lockError.body, { status: lockError.status })\n }\n throw lockError\n }\n }\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: ENTITY_DEFINITION_RESOURCE_KIND,\n resourceId: ent ? ent.id : input.entityId,\n operation: ent ? 'update' : 'create',\n mutationPayload: input as unknown as Record<string, unknown>,\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n const isCreate = !ent\n if (!ent) ent = em.create(CustomEntity, { ...where, createdAt: new Date() })\n ent.label = input.label\n ent.description = input.description ?? null\n ent.isActive = input.isActive ?? true\n ent.labelField = input.labelField ?? ent.labelField ?? null\n ent.defaultEditor = input.defaultEditor ?? ent.defaultEditor ?? null\n ent.showInSidebar = input.showInSidebar ?? ent.showInSidebar ?? false\n // Never silently flip a security control on a partial upsert. `access_restricted`\n // changes ONLY when the caller explicitly sends the field. On create without it,\n // fall back to the tenant default-restricted policy; on update without it, keep\n // the entity's current value (a metadata-only update must not un-restrict).\n if (accessRestrictedExplicit) {\n ent.accessRestricted = input.accessRestricted === true\n } else if (isCreate) {\n let policyDefault = false\n try {\n const moduleConfigService = resolve('moduleConfigService') as {\n getValue: (m: string, n: string, o?: { defaultValue?: unknown; scope?: { tenantId?: string | null } }) => Promise<unknown>\n }\n policyDefault = (await moduleConfigService.getValue('entities', 'newEntitiesRestrictedByDefault', {\n defaultValue: false,\n scope: { tenantId: auth.tenantId ?? null },\n })) === true\n } catch {}\n ent.accessRestricted = policyDefault\n } else {\n ent.accessRestricted = ent.accessRestricted ?? false\n }\n ent.updatedAt = new Date()\n em.persist(ent)\n await em.flush()\n await guard.runAfterSuccess()\n // Invalidate sidebar/nav cache for tenant scope (also when tenantId is null)\n try {\n const cache = (await createRequestContainer()).resolve('cache') as any\n if (cache) {\n await cache.deleteByTags([`nav:entities:${auth.tenantId || 'null'}`])\n }\n } catch {}\n return NextResponse.json({ ok: true, item: { id: ent.id, entityId: ent.entityId, label: ent.label, description: ent.description ?? undefined } })\n}\n\nexport async function DELETE(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.orgId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n let body: any\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const entityId = body?.entityId\n if (!entityId) return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = resolve('em') as any\n\n const where: any = { entityId, organizationId: auth.orgId ?? null, tenantId: auth.tenantId ?? null }\n const ent = await em.findOne(CustomEntity, where)\n if (!ent) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n\n const guard = await beginEntitiesMutationGuard({\n container,\n auth,\n req,\n resourceKind: ENTITY_DEFINITION_RESOURCE_KIND,\n resourceId: ent.id,\n operation: 'delete',\n mutationPayload: { entityId },\n })\n if (guard.blockedResponse) return guard.blockedResponse\n\n ent.isActive = false\n ent.updatedAt = new Date()\n ent.deletedAt = ent.deletedAt ?? new Date()\n em.persist(ent)\n await em.flush()\n await guard.runAfterSuccess()\n // Invalidate sidebar/nav cache for tenant scope (also when tenantId is null)\n try {\n const cache = (await createRequestContainer()).resolve('cache') as any\n if (cache) {\n await cache.deleteByTags([`nav:entities:${auth.tenantId || 'null'}`])\n }\n } catch {}\n return NextResponse.json({ ok: true })\n}\n\nconst entitySummarySchema = z.object({\n entityId: z.string(),\n source: z.enum(['code', 'custom']),\n label: z.string(),\n description: z.string().optional(),\n labelField: z.string().optional(),\n defaultEditor: z.string().optional(),\n showInSidebar: z.boolean().optional(),\n accessRestricted: z.boolean().optional(),\n updatedAt: z.string().optional(),\n count: z.number(),\n})\n\nconst entityListResponseSchema = z.object({\n items: z.array(entitySummarySchema),\n})\n\nconst deleteEntityRequestSchema = z.object({\n entityId: z.string(),\n})\n\nconst upsertCustomEntityResponseSchema = z.object({\n ok: z.literal(true),\n item: z.object({\n id: z.string().uuid(),\n entityId: z.string(),\n label: z.string(),\n description: z.string().optional(),\n }),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage custom entities',\n methods: {\n GET: {\n summary: 'List available entities',\n description: 'Returns generated and custom entities scoped to the caller with field counts per entity.',\n responses: [\n {\n status: 200,\n description: 'List of entities',\n schema: entityListResponseSchema,\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n POST: {\n summary: 'Upsert custom entity',\n description: 'Creates or updates a tenant/org scoped custom entity definition.',\n requestBody: {\n contentType: 'application/json',\n schema: upsertCustomEntitySchema,\n },\n responses: [\n {\n status: 200,\n description: 'Entity saved',\n schema: upsertCustomEntityResponseSchema,\n },\n {\n status: 400,\n description: 'Validation error',\n schema: z.object({\n error: z.string(),\n details: z.any().optional(),\n }),\n },\n {\n status: 401,\n description: 'Missing authentication',\n schema: z.object({ error: z.string() }),\n },\n ],\n },\n DELETE: {\n summary: 'Soft delete custom entity',\n description: 'Marks the specified custom entity inactive within the current scope.',\n requestBody: {\n contentType: 'application/json',\n schema: deleteEntityRequestSchema,\n },\n responses: [\n {\n status: 200,\n description: 'Entity deleted',\n schema: z.object({ ok: z.boolean() }),\n },\n {\n status: 400,\n description: 'Missing entity id',\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 status: 404,\n description: 'Entity not found in scope',\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,cAAc,sBAAsB;AAC7C,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AAEzC,SAAS,gCAAgC;AACzC,SAAS,oCAAoC,iCAAiC;AAC9E,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,yCAAyC;AAExC,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,KAAK;AAAA,EACzB,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAAA,EAC5E,QAAQ,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAChF;AAEA,eAAsB,IAAI,KAAc;AACtC,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,QAAQ,CAAC,KAAK,YAAa,CAAC,KAAK,SAAS,CAAC,KAAK,aAAe,QAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAEvI,QAAM,EAAE,QAAQ,IAAI,MAAM,uBAAuB;AACjD,Q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AW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AAAA,QACtC;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,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": []
7
7
  }
@@ -0,0 +1,89 @@
1
+ import { NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
+ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
+ const CONFIG_MODULE = "entities";
6
+ const NEW_ENTITIES_RESTRICTED_KEY = "newEntitiesRestrictedByDefault";
7
+ const metadata = {
8
+ GET: { requireAuth: true, requireFeatures: ["entities.definitions.view"] },
9
+ PUT: { requireAuth: true, requireFeatures: ["entities.definitions.manage"] }
10
+ };
11
+ async function readPolicy(tenantId) {
12
+ try {
13
+ const { resolve } = await createRequestContainer();
14
+ const moduleConfigService = resolve("moduleConfigService");
15
+ const value = await moduleConfigService.getValue(CONFIG_MODULE, NEW_ENTITIES_RESTRICTED_KEY, {
16
+ defaultValue: false,
17
+ scope: { tenantId }
18
+ });
19
+ return value === true;
20
+ } catch {
21
+ return false;
22
+ }
23
+ }
24
+ async function GET(req) {
25
+ const auth = await getAuthFromRequest(req);
26
+ if (!auth || !auth.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
27
+ const newEntitiesRestrictedByDefault = await readPolicy(auth.tenantId ?? null);
28
+ return NextResponse.json({ newEntitiesRestrictedByDefault });
29
+ }
30
+ const putBodySchema = z.object({
31
+ newEntitiesRestrictedByDefault: z.boolean()
32
+ });
33
+ async function PUT(req) {
34
+ const auth = await getAuthFromRequest(req);
35
+ if (!auth || !auth.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
36
+ let body;
37
+ try {
38
+ body = await req.json();
39
+ } catch {
40
+ return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
41
+ }
42
+ const parsed = putBodySchema.safeParse(body);
43
+ if (!parsed.success) {
44
+ return NextResponse.json({ error: "Validation failed", details: parsed.error.flatten() }, { status: 400 });
45
+ }
46
+ const { resolve } = await createRequestContainer();
47
+ const moduleConfigService = resolve("moduleConfigService");
48
+ await moduleConfigService.setValue(
49
+ CONFIG_MODULE,
50
+ NEW_ENTITIES_RESTRICTED_KEY,
51
+ parsed.data.newEntitiesRestrictedByDefault,
52
+ { tenantId: auth.tenantId ?? null }
53
+ );
54
+ return NextResponse.json({ ok: true, newEntitiesRestrictedByDefault: parsed.data.newEntitiesRestrictedByDefault });
55
+ }
56
+ const settingsResponseSchema = z.object({
57
+ newEntitiesRestrictedByDefault: z.boolean()
58
+ });
59
+ const openApi = {
60
+ tag: "Entities",
61
+ summary: "Custom entity workspace settings",
62
+ methods: {
63
+ GET: {
64
+ summary: "Get custom entity settings",
65
+ description: "Returns the tenant-scoped default-restricted policy for new custom entities.",
66
+ responses: [
67
+ { status: 200, description: "Current settings", schema: settingsResponseSchema },
68
+ { status: 401, description: "Missing authentication", schema: z.object({ error: z.string() }) }
69
+ ]
70
+ },
71
+ PUT: {
72
+ summary: "Update custom entity settings",
73
+ description: "Sets the tenant-scoped default-restricted policy for new custom entities.",
74
+ requestBody: { schema: putBodySchema },
75
+ responses: [
76
+ { status: 200, description: "Updated settings", schema: z.object({ ok: z.boolean(), newEntitiesRestrictedByDefault: z.boolean() }) },
77
+ { status: 400, description: "Invalid payload", schema: z.object({ error: z.string() }) },
78
+ { status: 401, description: "Missing authentication", schema: z.object({ error: z.string() }) }
79
+ ]
80
+ }
81
+ }
82
+ };
83
+ export {
84
+ GET,
85
+ PUT,
86
+ metadata,
87
+ openApi
88
+ };
89
+ //# sourceMappingURL=entity-settings.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/entities/api/entity-settings.ts"],
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 type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\n\n// Tenant-scoped policy: when true, new custom entities are created with\n// `access_restricted = true` unless the create request explicitly sets the flag.\nconst CONFIG_MODULE = 'entities'\nconst NEW_ENTITIES_RESTRICTED_KEY = 'newEntitiesRestrictedByDefault'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['entities.definitions.view'] },\n PUT: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\ntype ModuleConfigServiceLike = {\n getValue: (\n moduleId: string,\n name: string,\n options?: { defaultValue?: unknown; scope?: { tenantId?: string | null } },\n ) => Promise<unknown>\n setValue: (\n moduleId: string,\n name: string,\n value: unknown,\n scope?: { tenantId?: string | null },\n ) => Promise<unknown>\n}\n\nasync function readPolicy(tenantId: string | null): Promise<boolean> {\n try {\n const { resolve } = await createRequestContainer()\n const moduleConfigService = resolve('moduleConfigService') as ModuleConfigServiceLike\n const value = await moduleConfigService.getValue(CONFIG_MODULE, NEW_ENTITIES_RESTRICTED_KEY, {\n defaultValue: false,\n scope: { tenantId },\n })\n return value === true\n } catch {\n return false\n }\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const newEntitiesRestrictedByDefault = await readPolicy(auth.tenantId ?? null)\n return NextResponse.json({ newEntitiesRestrictedByDefault })\n}\n\nconst putBodySchema = z.object({\n newEntitiesRestrictedByDefault: z.boolean(),\n})\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth || !auth.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n let body: unknown\n try { body = await req.json() } catch { return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n const parsed = putBodySchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Validation failed', details: parsed.error.flatten() }, { status: 400 })\n }\n const { resolve } = await createRequestContainer()\n const moduleConfigService = resolve('moduleConfigService') as ModuleConfigServiceLike\n await moduleConfigService.setValue(\n CONFIG_MODULE,\n NEW_ENTITIES_RESTRICTED_KEY,\n parsed.data.newEntitiesRestrictedByDefault,\n { tenantId: auth.tenantId ?? null },\n )\n return NextResponse.json({ ok: true, newEntitiesRestrictedByDefault: parsed.data.newEntitiesRestrictedByDefault })\n}\n\nconst settingsResponseSchema = z.object({\n newEntitiesRestrictedByDefault: z.boolean(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Custom entity workspace settings',\n methods: {\n GET: {\n summary: 'Get custom entity settings',\n description: 'Returns the tenant-scoped default-restricted policy for new custom entities.',\n responses: [\n { status: 200, description: 'Current settings', schema: settingsResponseSchema },\n { status: 401, description: 'Missing authentication', schema: z.object({ error: z.string() }) },\n ],\n },\n PUT: {\n summary: 'Update custom entity settings',\n description: 'Sets the tenant-scoped default-restricted policy for new custom entities.',\n requestBody: { schema: putBodySchema },\n responses: [\n { status: 200, description: 'Updated settings', schema: z.object({ ok: z.boolean(), newEntitiesRestrictedByDefault: z.boolean() }) },\n { status: 400, description: 'Invalid payload', schema: z.object({ error: z.string() }) },\n { status: 401, description: 'Missing authentication', schema: z.object({ error: z.string() }) },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA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EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACvF,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,MAChG;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -13,36 +13,57 @@ import { getModules } from "@open-mercato/shared/lib/i18n/server";
13
13
  import { assertEntityAclForRequest } from "../lib/entityAcl.js";
14
14
  import { createLogger } from "@open-mercato/shared/lib/logger";
15
15
  const logger = createLogger("entities").child({ component: "records" });
16
- let declaredCustomEntityIds = null;
17
- function isDeclaredCustomEntity(entityId) {
18
- if (declaredCustomEntityIds === null) {
16
+ let declaredCustomEntityRestricted = null;
17
+ function loadDeclaredCustomEntities() {
18
+ if (declaredCustomEntityRestricted === null) {
19
19
  try {
20
20
  const mods = getModules();
21
- if (Array.isArray(mods) && mods.length) {
22
- const ids = /* @__PURE__ */ new Set();
23
- for (const mod of mods) {
24
- for (const spec of mod?.customEntities ?? []) {
25
- if (spec?.id) ids.add(spec.id);
26
- }
21
+ const map = /* @__PURE__ */ new Map();
22
+ for (const mod of mods ?? []) {
23
+ for (const spec of mod?.customEntities ?? []) {
24
+ if (spec?.id) map.set(spec.id, spec.accessRestricted === true);
27
25
  }
28
- declaredCustomEntityIds = ids;
29
26
  }
27
+ declaredCustomEntityRestricted = map;
30
28
  } catch {
31
29
  }
32
30
  }
33
- return declaredCustomEntityIds?.has(entityId) ?? false;
31
+ return declaredCustomEntityRestricted ?? /* @__PURE__ */ new Map();
32
+ }
33
+ function isDeclaredCustomEntity(entityId) {
34
+ return loadDeclaredCustomEntities().has(entityId);
35
+ }
36
+ async function findScopedCustomEntity(em, CustomEntity, entityId, scope) {
37
+ const { tenantId, organizationId } = scope;
38
+ const candidates = [
39
+ { entityId, organizationId, tenantId },
40
+ { entityId, organizationId: null, tenantId },
41
+ { entityId, organizationId: null, tenantId: null }
42
+ ];
43
+ const seen = /* @__PURE__ */ new Set();
44
+ for (const where of candidates) {
45
+ const key = JSON.stringify(where);
46
+ if (seen.has(key)) continue;
47
+ seen.add(key);
48
+ const row = await em.findOne(CustomEntity, where);
49
+ if (row) return row;
50
+ }
51
+ return null;
34
52
  }
35
53
  const CUSTOM_ENTITY_RECORD_RESOURCE_KIND = "entities.record";
36
- async function classifyRecordsEntity(em, entityId) {
37
- if (isOrmBackedSystemEntityId(em, entityId)) return "system";
38
- if (isDeclaredCustomEntity(entityId)) return "custom";
54
+ async function classifyRecordsEntity(em, entityId, scope) {
55
+ if (isOrmBackedSystemEntityId(em, entityId)) return { kind: "system", restricted: false };
56
+ const declared = loadDeclaredCustomEntities();
57
+ if (declared.has(entityId)) return { kind: "custom", restricted: declared.get(entityId) === true };
39
58
  try {
40
59
  const { CustomEntity } = await import("../data/entities.js");
41
- const found = await em.findOne(CustomEntity, { entityId });
42
- if (found) return "custom";
60
+ const scoped = await findScopedCustomEntity(em, CustomEntity, entityId, scope);
61
+ if (scoped) return { kind: "custom", restricted: scoped.accessRestricted === true };
62
+ const anyRow = await em.findOne(CustomEntity, { entityId });
63
+ if (anyRow) return { kind: "custom", restricted: false };
43
64
  } catch {
44
65
  }
45
- return "unknown";
66
+ return { kind: "unknown", restricted: false };
46
67
  }
47
68
  function systemEntityRecordsRejection(entityId) {
48
69
  return NextResponse.json(
@@ -125,10 +146,10 @@ async function GET(req) {
125
146
  const rbac = resolve("rbacService");
126
147
  const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
127
148
  let organizationIds = scope.filterIds;
128
- const entityKind = await classifyRecordsEntity(em, entityId);
149
+ const { kind: entityKind, restricted: isRestricted } = await classifyRecordsEntity(em, entityId, { tenantId: auth.tenantId ?? null, organizationId: scope.selectedId ?? auth.orgId ?? null });
129
150
  if (entityKind === "system") return systemEntityRecordsRejection(entityId);
130
151
  const isCustomEntity = entityKind === "custom";
131
- await assertEntityAclForRequest({ auth, entityId, action: "view", isCustomEntity, rbac });
152
+ await assertEntityAclForRequest({ auth, entityId, action: "view", isCustomEntity, isRestricted, rbac });
132
153
  if (organizationIds && organizationIds.length === 0) {
133
154
  return NextResponse.json({ items: [], total: 0, page, pageSize, totalPages: 0 });
134
155
  }
@@ -324,10 +345,10 @@ async function POST(req) {
324
345
  const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
325
346
  const targetOrgId = scope.selectedId ?? auth.orgId;
326
347
  if (!targetOrgId) return NextResponse.json({ error: "Organization context is required" }, { status: 400 });
327
- const entityKind = await classifyRecordsEntity(em, entityId);
348
+ const { kind: entityKind, restricted: isRestricted } = await classifyRecordsEntity(em, entityId, { tenantId: auth.tenantId ?? null, organizationId: scope.selectedId ?? auth.orgId ?? null });
328
349
  if (entityKind === "system") return systemEntityRecordsRejection(entityId);
329
350
  const isCustomEntity = entityKind === "custom";
330
- await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, rbac });
351
+ await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, isRestricted, rbac });
331
352
  for (const reservedKey of ["id", "created_at", "createdAt", "updated_at", "updatedAt", "deleted_at", "deletedAt"]) {
332
353
  delete values[reservedKey];
333
354
  }
@@ -389,10 +410,10 @@ async function PUT(req) {
389
410
  const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
390
411
  const targetOrgId = scope.selectedId ?? auth.orgId;
391
412
  if (!targetOrgId) return NextResponse.json({ error: "Organization context is required" }, { status: 400 });
392
- const entityKind = await classifyRecordsEntity(em, entityId);
413
+ const { kind: entityKind, restricted: isRestricted } = await classifyRecordsEntity(em, entityId, { tenantId: auth.tenantId ?? null, organizationId: scope.selectedId ?? auth.orgId ?? null });
393
414
  if (entityKind === "system") return systemEntityRecordsRejection(entityId);
394
415
  const isCustomEntity = entityKind === "custom";
395
- await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, rbac });
416
+ await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, isRestricted, rbac });
396
417
  for (const reservedKey of ["id", "created_at", "createdAt", "updated_at", "updatedAt", "deleted_at", "deletedAt"]) {
397
418
  delete values[reservedKey];
398
419
  }
@@ -479,10 +500,10 @@ async function DELETE(req) {
479
500
  const scope = await resolveOrganizationScope({ em, rbac, auth, selectedId: getSelectedOrganizationFromRequest(req) });
480
501
  const targetOrgId = scope.selectedId ?? auth.orgId;
481
502
  if (!targetOrgId) return NextResponse.json({ error: "Organization context is required" }, { status: 400 });
482
- const entityKind = await classifyRecordsEntity(em, entityId);
503
+ const { kind: entityKind, restricted: isRestricted } = await classifyRecordsEntity(em, entityId, { tenantId: auth.tenantId ?? null, organizationId: scope.selectedId ?? auth.orgId ?? null });
483
504
  if (entityKind === "system") return systemEntityRecordsRejection(entityId);
484
505
  const isCustomEntity = entityKind === "custom";
485
- await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, rbac });
506
+ await assertEntityAclForRequest({ auth, entityId, action: "manage", isCustomEntity, isRestricted, rbac });
486
507
  try {
487
508
  const currentUpdatedAt = await readCustomEntityRecordUpdatedAt(em, {
488
509
  entityType: entityId,