@autofleet/sadot 1.6.8 → 1.6.9-beta.0
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/dist/api/v1/definition/index.cjs +1 -1
- package/dist/api/v1/definition/index.cjs.map +1 -1
- package/dist/api/v1/definition/index.js +1 -1
- package/dist/api/v1/definition/index.js.map +1 -1
- package/dist/models/index.cjs +1 -1
- package/dist/models/index.cjs.map +1 -1
- package/dist/models/index.js +1 -1
- package/dist/models/index.js.map +1 -1
- package/dist/repository/definition.cjs +1 -1
- package/dist/repository/definition.cjs.map +1 -1
- package/dist/repository/definition.js +1 -1
- package/dist/repository/definition.js.map +1 -1
- package/package.json +6 -6
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../../../repository/definition.cjs`),r=require(`../errors.cjs`),i=require(`./validations.cjs`),a=require(`../../../mat-path-state.cjs`);let o=require(`@autofleet/errors`),s=require(`@autofleet/node-common`);const c=(0,s.Router)({logger:t.default}),l=`CustomFieldDefinition`,u=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());c.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=u(o);try{let t=await i.validateCustomFieldDefinitionCreation(e.body),r=await n.create({...t,modelType:s});return a.status(201).json(r)}catch(e){return t.default.error(`Failed to create custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in create ${l} request`})}}),c.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:a}=e.params;try{let e=await n.findById(a);if(!e)throw new o.ResourceNotFoundError;return i.json(e)}catch(e){return t.default.error(`Failed to fetch custom field definition`,e),r.default(e,i,{logger:t.default,message:`Error in get ${l} request`})}}),c.get(`/`,async(e,i)=>{let{params:{modelName:o},query:{entityIds:s,modelTypeId:c}}=e,d=u(o);try{let e=!a.matPathState.isMatPathEnabled?.()&&s&&s.length>0;if(c){let t=await n.findByModelTypeId(c,{withDisabled:!0,modelType:d,entityIds:e?s:void 0});return i.json(t)}let
|
|
1
|
+
const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../../../repository/definition.cjs`),r=require(`../errors.cjs`),i=require(`./validations.cjs`),a=require(`../../../mat-path-state.cjs`);let o=require(`@autofleet/errors`),s=require(`@autofleet/node-common`);const c=(0,s.Router)({logger:t.default}),l=`CustomFieldDefinition`,u=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());c.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=u(o);try{let t=await i.validateCustomFieldDefinitionCreation(e.body),r=await n.create({...t,modelType:s});return a.status(201).json(r)}catch(e){return t.default.error(`Failed to create custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in create ${l} request`})}}),c.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:a}=e.params;try{let e=await n.findById(a);if(!e)throw new o.ResourceNotFoundError;return i.json(e)}catch(e){return t.default.error(`Failed to fetch custom field definition`,e),r.default(e,i,{logger:t.default,message:`Error in get ${l} request`})}}),c.get(`/`,async(e,i)=>{let{params:{modelName:o},query:{entityIds:s,modelTypeId:c}}=e,d=u(o);try{let e=!a.matPathState.isMatPathEnabled?.()&&s&&s.length>0;if(t.default.info(`[SADOT] get all custom-definitions`,{modelType:d,modelName:o,entityIds:s,modelTypeId:c}),c){let t=await n.findByModelTypeId(c,{withDisabled:!0,modelType:d,entityIds:e?s:void 0});return i.json(t)}let r={modelType:d,...e&&{entityId:s}},l=await n.findAll(r,{withDisabled:!0,enrichWithModelTypeIds:!0});return i.json(l)}catch(e){return t.default.error(`Failed to fetch custom field definitions`,e),r.default(e,i,{logger:t.default,message:`Error in get all ${l} request`})}}),c.patch(`/:customFieldDefinitionId`,async(e,a)=>{let{customFieldDefinitionId:s,modelName:c}=e.params,d=u(c);try{let t=await i.validateCustomFieldDefinitionUpdate(e.body);if(!await n.findByWhere({id:s,modelType:d}))throw new o.ResourceNotFoundError;let r=await n.update(s,{...t,modelType:d});return a.status(200).json(r)}catch(e){return t.default.error(`Failed to patch custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in update ${l} request`})}});var d=c;exports.default=d;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","matPathState","customFieldDefinitions","validatedPayload: UpdateCustomFieldDefinition","validateCustomFieldDefinitionUpdate"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\nimport { matPathState } from '../../../mat-path-state';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // When mat-path is active, drop the explicit `entityId IN (entityIds)` WHERE filter — RLS\n // on `custom_field_definitions` (applied via decorateModelMethods) restricts the result\n // to the caller's visible scope (fleet + ancestor partners). If the WHERE clause kept the\n // requested entityIds, partner CFDs (whose entity_id differs from the requested fleet's\n // entityId) would be filtered out by the WHERE before RLS could include them.\n const applyEntityIdsFilter = !matPathState.isMatPathEnabled?.() && entityIds && entityIds.length > 0;\n\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds: applyEntityIdsFilter ? entityIds : undefined,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(applyEntityIdsFilter && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"iUAUA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMC,EAAgD,MAAMC,EAAAA,sCAAsC,EAAI,KAAK,CAErG,EAAwB,MAAA,EAAA,OAA4B,CACxD,GAAG,EACH,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAA,EAAA,SAA8B,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAIC,EAAAA,sBAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,gBAAgB,EAAO,UAAW,CAAC,GAE9F,CAKF,EAAO,IAA6G,IAAK,MAAO,EAAK,IAAQ,CAC3I,GAAM,CAAE,OAAQ,CAAE,aAAa,MAAO,CAAE,YAAW,gBAAkB,EAE/D,EAAY,EAAa,EAAU,CACzC,GAAI,CAMF,IAAM,EAAuB,CAACE,EAAAA,aAAa,oBAAoB,EAAI,GAAa,EAAU,OAAS,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","matPathState","customFieldDefinitions","validatedPayload: UpdateCustomFieldDefinition","validateCustomFieldDefinitionUpdate"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\nimport { matPathState } from '../../../mat-path-state';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // When mat-path is active, drop the explicit `entityId IN (entityIds)` WHERE filter — RLS\n // on `custom_field_definitions` (applied via decorateModelMethods) restricts the result\n // to the caller's visible scope (fleet + ancestor partners). If the WHERE clause kept the\n // requested entityIds, partner CFDs (whose entity_id differs from the requested fleet's\n // entityId) would be filtered out by the WHERE before RLS could include them.\n const applyEntityIdsFilter = !matPathState.isMatPathEnabled?.() && entityIds && entityIds.length > 0;\n\n logger.info('[SADOT] get all custom-definitions', { modelType, modelName, entityIds, modelTypeId });\n\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds: applyEntityIdsFilter ? entityIds : undefined,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(applyEntityIdsFilter && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"iUAUA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMC,EAAgD,MAAMC,EAAAA,sCAAsC,EAAI,KAAK,CAErG,EAAwB,MAAA,EAAA,OAA4B,CACxD,GAAG,EACH,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF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EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMI,EAAgD,MAAMC,EAAAA,oCAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAA,EAAA,YAAiC,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAIJ,EAAAA,sBAGZ,IAAM,EAA+B,MAAA,EAAA,OACnC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../../../utils/logger/index.js";import{create as t,findAll as n,findById as r,findByModelTypeId as i,findByWhere as a,update as o}from"../../../repository/definition.js";import s from"../errors.js";import{validateCustomFieldDefinitionCreation as c,validateCustomFieldDefinitionUpdate as l}from"./validations.js";import{matPathState as u}from"../../../mat-path-state.js";import{ResourceNotFoundError as d}from"@autofleet/errors";import{Router as f}from"@autofleet/node-common";const p=f({logger:e}),m=`CustomFieldDefinition`,h=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());p.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=h(i);try{let e=await t({...await c(n.body),modelType:a});return r.status(201).json(e)}catch(t){return e.error(`Failed to create custom field definition`,t),s(t,r,{logger:e,message:`Error in create ${m} request`})}}),p.get(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:i}=t.params;try{let e=await r(i);if(!e)throw new d;return n.json(e)}catch(t){return e.error(`Failed to fetch custom field definition`,t),s(t,n,{logger:e,message:`Error in get ${m} request`})}}),p.get(`/`,async(t,r)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:c}}=t,l=h(a);try{let
|
|
1
|
+
import e from"../../../utils/logger/index.js";import{create as t,findAll as n,findById as r,findByModelTypeId as i,findByWhere as a,update as o}from"../../../repository/definition.js";import s from"../errors.js";import{validateCustomFieldDefinitionCreation as c,validateCustomFieldDefinitionUpdate as l}from"./validations.js";import{matPathState as u}from"../../../mat-path-state.js";import{ResourceNotFoundError as d}from"@autofleet/errors";import{Router as f}from"@autofleet/node-common";const p=f({logger:e}),m=`CustomFieldDefinition`,h=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());p.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=h(i);try{let e=await t({...await c(n.body),modelType:a});return r.status(201).json(e)}catch(t){return e.error(`Failed to create custom field definition`,t),s(t,r,{logger:e,message:`Error in create ${m} request`})}}),p.get(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:i}=t.params;try{let e=await r(i);if(!e)throw new d;return n.json(e)}catch(t){return e.error(`Failed to fetch custom field definition`,t),s(t,n,{logger:e,message:`Error in get ${m} request`})}}),p.get(`/`,async(t,r)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:c}}=t,l=h(a);try{let t=!u.isMatPathEnabled?.()&&o&&o.length>0;if(e.info(`[SADOT] get all custom-definitions`,{modelType:l,modelName:a,entityIds:o,modelTypeId:c}),c){let e=await i(c,{withDisabled:!0,modelType:l,entityIds:t?o:void 0});return r.json(e)}let s=await n({modelType:l,...t&&{entityId:o}},{withDisabled:!0,enrichWithModelTypeIds:!0});return r.json(s)}catch(t){return e.error(`Failed to fetch custom field definitions`,t),s(t,r,{logger:e,message:`Error in get all ${m} request`})}}),p.patch(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:r,modelName:i}=t.params,c=h(i);try{let e=await l(t.body);if(!await a({id:r,modelType:c}))throw new d;let i=await o(r,{...e,modelType:c});return n.status(200).json(i)}catch(t){return e.error(`Failed to patch custom field definition`,t),s(t,n,{logger:e,message:`Error in update ${m} request`})}});var g=p;export{g as default};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","customFieldDefinitions","DefinitionRepo.findByModelTypeId","DefinitionRepo.findAll","validatedPayload: UpdateCustomFieldDefinition","DefinitionRepo.findByWhere","DefinitionRepo.update"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\nimport { matPathState } from '../../../mat-path-state';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // When mat-path is active, drop the explicit `entityId IN (entityIds)` WHERE filter — RLS\n // on `custom_field_definitions` (applied via decorateModelMethods) restricts the result\n // to the caller's visible scope (fleet + ancestor partners). If the WHERE clause kept the\n // requested entityIds, partner CFDs (whose entity_id differs from the requested fleet's\n // entityId) would be filtered out by the WHERE before RLS could include them.\n const applyEntityIdsFilter = !matPathState.isMatPathEnabled?.() && entityIds && entityIds.length > 0;\n\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds: applyEntityIdsFilter ? entityIds : undefined,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(applyEntityIdsFilter && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"0eAUA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CAGF,IAAM,EAAwB,MAAME,EAAsB,CACxD,GAHoD,MAAM,EAAsC,EAAI,KAAK,CAIzG,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAMC,EAAwB,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAI,EAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,gBAAgB,EAAO,UAAW,CAAC,GAE9F,CAKF,EAAO,IAA6G,IAAK,MAAO,EAAK,IAAQ,CAC3I,GAAM,CAAE,OAAQ,CAAE,aAAa,MAAO,CAAE,YAAW,gBAAkB,EAE/D,EAAY,EAAa,EAAU,CACzC,GAAI,CAMF,IAAM,EAAuB,CAAC,EAAa,oBAAoB,EAAI,GAAa,EAAU,OAAS,
|
|
1
|
+
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","customFieldDefinitions","DefinitionRepo.findByModelTypeId","DefinitionRepo.findAll","validatedPayload: UpdateCustomFieldDefinition","DefinitionRepo.findByWhere","DefinitionRepo.update"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\nimport { matPathState } from '../../../mat-path-state';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // When mat-path is active, drop the explicit `entityId IN (entityIds)` WHERE filter — RLS\n // on `custom_field_definitions` (applied via decorateModelMethods) restricts the result\n // to the caller's visible scope (fleet + ancestor partners). If the WHERE clause kept the\n // requested entityIds, partner CFDs (whose entity_id differs from the requested fleet's\n // entityId) would be filtered out by the WHERE before RLS could include them.\n const applyEntityIdsFilter = !matPathState.isMatPathEnabled?.() && entityIds && entityIds.length > 0;\n\n logger.info('[SADOT] get all custom-definitions', { modelType, modelName, entityIds, modelTypeId });\n\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, {\n withDisabled: true,\n modelType,\n entityIds: applyEntityIdsFilter ? entityIds : undefined,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(applyEntityIdsFilter && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"0eAUA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CAGF,IAAM,EAAwB,MAAME,EAAsB,CACxD,GAHoD,MAAM,EAAsC,EAAI,KAAK,CAIzG,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAMC,EAAwB,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAI,EAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QA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EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
package/dist/models/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`),d=require(`../migrations/index.cjs`);let f=require(`sequelize`);const p=[a.default,i.default,s.default,o.default],m=`sadot-migration`,h=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,g=async(e,{schemaPrefix:i,schemaVersion:a,useCustomFieldsEntries:o,useModelTypeMapping:s})=>{let d=e.define(`SequelizeMeta`,{name:{type:f.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let p=await d.findAll({where:{name:{[f.Op.like]:`${i}%`}},raw:!0}),m=p.at(-1),h=p.findIndex(e=>e.name===a);if(t.default.info(`custom-fields: migrations`,{currentMigrations:p,currentSadotSchemaVersion:m,newSadotSchemaVersion:a,expectedSchemaVersionIndex:h}),!m||m.name!==a){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),o&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),s&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),h===-1&&(await d.create({name:a}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),p.length&&h!==-1&&h<p.length-1){let e=p.slice(h+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await d.destroy({where:{name:{[f.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},_=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1,runLegacyMigrations:p=!1,isMatPathEnabled:m}={})=>{let h=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let _=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];if(e.addModels(_),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`),p){t.default.info(`custom-fields: running legacy sync migrations`),await g(e,{schemaPrefix:a,schemaVersion:h,useCustomFieldsEntries:s,useModelTypeMapping:f});return}t.default.info(`custom-fields: starting umzug migrations`),await d.runSadotMigrations(e,{useCustomFieldsEntries:s,useModelTypeMapping:f}),t.default.info(`custom-fields: umzug migrations complete`)},v=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(p),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=_,exports.initTestModels=v;
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`),d=require(`../migrations/index.cjs`);let f=require(`sequelize`);const p=[a.default,i.default,s.default,o.default],m=`sadot-migration`,h=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,g=async(e,{schemaPrefix:i,schemaVersion:a,useCustomFieldsEntries:o,useModelTypeMapping:s})=>{let d=e.define(`SequelizeMeta`,{name:{type:f.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let p=await d.findAll({where:{name:{[f.Op.like]:`${i}%`}},raw:!0}),m=p.at(-1),h=p.findIndex(e=>e.name===a);if(t.default.info(`custom-fields: migrations`,{currentMigrations:p,currentSadotSchemaVersion:m,newSadotSchemaVersion:a,expectedSchemaVersionIndex:h}),!m||m.name!==a){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),o&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),s&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),h===-1&&(await d.create({name:a}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),p.length&&h!==-1&&h<p.length-1){let e=p.slice(h+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await d.destroy({where:{name:{[f.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},_=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1,runLegacyMigrations:p=!1,isMatPathEnabled:m}={})=>{let h=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let _=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];if(e.addModels(_),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{if(t.default.info(`[SADOT] CustomFieldDefinition userScope started`),m?.())return{};let e=i();return t.default.info(`[SADOT] CustomFieldDefinition user`,{user:e,userPermissions:e?.permissions}),e?.permissions?(t.default.info(``),{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}):{}}),l.default.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`),p){t.default.info(`custom-fields: running legacy sync migrations`),await g(e,{schemaPrefix:a,schemaVersion:h,useCustomFieldsEntries:s,useModelTypeMapping:f});return}t.default.info(`custom-fields: starting umzug migrations`),await d.runSadotMigrations(e,{useCustomFieldsEntries:s,useModelTypeMapping:f}),t.default.info(`custom-fields: umzug migrations complete`)},v=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(p),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=_,exports.initTestModels=v;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","DataTypes","Op","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","productionModels: ProductionModel[]","runSadotMigrations"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n runLegacyMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\n/**\n * Legacy migration approach using sequelize.sync({ alter: true }).\n * TODO: Remove this function once all consumers have migrated to umzug.\n */\nconst legacySyncMigrations = async (\n sequelize: Sequelize,\n {\n schemaPrefix,\n schemaVersion,\n useCustomFieldsEntries,\n useModelTypeMapping,\n }: { schemaPrefix: string; schemaVersion: string; useCustomFieldsEntries: boolean; useModelTypeMapping: boolean; },\n): Promise<void> => {\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === schemaVersion);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: schemaVersion,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== schemaVersion) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: schemaVersion });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n runLegacyMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (runLegacyMigrations) {\n logger.info('custom-fields: running legacy sync migrations');\n await legacySyncMigrations(sequelize, { schemaPrefix, schemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION, useCustomFieldsEntries, useModelTypeMapping });\n return;\n }\n\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAMjB,EAAuB,MAC3B,EACA,CACE,eACA,gBACA,yBACA,yBAEgB,CAClB,IAAM,EAAgBC,EAAU,OAC9B,gBACA,CACE,KAAM,CACJ,KAAMC,EAAAA,UAAU,OAChB,UAAW,GACX,OAAQ,GACR,WAAY,GACZ,cAAe,GAChB,CACF,CACD,CACE,UAAW,gBACX,WAAY,GACZ,OAAQ,SACT,CACF,CAED,EAAA,QAAO,KAAK,qCAAqC,CACjD,IAAM,EAAa,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAGC,EAAAA,GAAG,MAAO,GAAG,EAAa,GAAI,CAAE,CAAE,IAAK,GAAM,CAAC,CAC3G,EAA4B,EAAW,GAAG,GAAG,CAC7C,EAA6B,EAAW,UAAU,GAAM,EAAU,OAAS,EAAc,CAQ/F,GANA,EAAA,QAAO,KAAK,4BAA6B,CACvC,kBAAmB,E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AO,KAAK,gDAAgD,CAC5D,MAAM,EAAqBH,EAAW,CAAE,eAAc,cAAe,EAA8B,yBAAwB,sBAAqB,CAAC,CACjJ,OAGF,EAAA,QAAO,KAAK,2CAA2C,CACvD,MAAMS,EAAAA,mBAAmBT,EAAW,CAAE,yBAAwB,sBAAqB,CAAC,CACpF,EAAA,QAAO,KAAK,2CAA2C,EAGnD,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAA,QAAO,KAAK,sDAAsD,CAE9D,CAACA,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAMA,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAMA,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAA,QAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAAA,QAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAAA,QAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAAA,QAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAAA,QAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","DataTypes","Op","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","productionModels: ProductionModel[]","runSadotMigrations"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n runLegacyMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\n/**\n * Legacy migration approach using sequelize.sync({ alter: true }).\n * TODO: Remove this function once all consumers have migrated to umzug.\n */\nconst legacySyncMigrations = async (\n sequelize: Sequelize,\n {\n schemaPrefix,\n schemaVersion,\n useCustomFieldsEntries,\n useModelTypeMapping,\n }: { schemaPrefix: string; schemaVersion: string; useCustomFieldsEntries: boolean; useModelTypeMapping: boolean; },\n): Promise<void> => {\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === schemaVersion);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: schemaVersion,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== schemaVersion) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: schemaVersion });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n runLegacyMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n logger.info('[SADOT] CustomFieldDefinition userScope started');\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n logger.info('[SADOT] CustomFieldDefinition user', { user, userPermissions: user?.permissions });\n if (!user?.permissions) {\n return {};\n }\n logger.info('')\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (runLegacyMigrations) {\n logger.info('custom-fields: running legacy sync migrations');\n await legacySyncMigrations(sequelize, { schemaPrefix, schemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION, useCustomFieldsEntries, useModelTypeMapping });\n return;\n }\n\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAMjB,EAAuB,MAC3B,EACA,CACE,eACA,gBACA,yBACA,yBAEgB,CAClB,IAAM,EAAgBC,EAAU,OAC9B,gBACA,CACE,KAAM,CACJ,KAAMC,EAAAA,UAAU,OAChB,UAAW,GACX,OAAQ,GACR,WAAY,GACZ,cAAe,GAChB,CACF,CACD,CACE,UAAW,gBACX,WAAY,GACZ,OAAQ,SACT,CACF,CAED,EAAA,QAAO,KAAK,qCAAqC,CACjD,IAAM,EAAa,MAAM,EAAc,QAAQ,CA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import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{runSadotMigrations as u}from"../migrations/index.js";import{DataTypes as d,Op as f}from"sequelize";const p=[i,r,o,a],m=async(r,{schemaPrefix:i,schemaVersion:a,useCustomFieldsEntries:o,useModelTypeMapping:u})=>{let p=r.define(`SequelizeMeta`,{name:{type:d.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let m=await p.findAll({where:{name:{[f.like]:`${i}%`}},raw:!0}),h=m.at(-1),g=m.findIndex(e=>e.name===a);if(e.info(`custom-fields: migrations`,{currentMigrations:m,currentSadotSchemaVersion:h,newSadotSchemaVersion:a,expectedSchemaVersionIndex:g}),!h||h.name!==a){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),o&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),u&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),g===-1&&(await p.create({name:a}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),m.length&&g!==-1&&g<m.length-1){let t=m.slice(g+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await p.destroy({where:{name:{[f.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},h=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:d=!1,useModelTypeMapping:f=!1,runLegacyMigrations:p=!1,isMatPathEnabled:h}={})=>{let g=`${a}_${o}${d?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let _=[n,t,c,...d?[s]:[],...f?[l]:[]];if(r.addModels(_),f&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{if(h?.())return{};let
|
|
1
|
+
import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{runSadotMigrations as u}from"../migrations/index.js";import{DataTypes as d,Op as f}from"sequelize";const p=[i,r,o,a],m=async(r,{schemaPrefix:i,schemaVersion:a,useCustomFieldsEntries:o,useModelTypeMapping:u})=>{let p=r.define(`SequelizeMeta`,{name:{type:d.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let m=await p.findAll({where:{name:{[f.like]:`${i}%`}},raw:!0}),h=m.at(-1),g=m.findIndex(e=>e.name===a);if(e.info(`custom-fields: migrations`,{currentMigrations:m,currentSadotSchemaVersion:h,newSadotSchemaVersion:a,expectedSchemaVersionIndex:g}),!h||h.name!==a){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),o&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),u&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),g===-1&&(await p.create({name:a}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),m.length&&g!==-1&&g<m.length-1){let t=m.slice(g+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await p.destroy({where:{name:{[f.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},h=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:d=!1,useModelTypeMapping:f=!1,runLegacyMigrations:p=!1,isMatPathEnabled:h}={})=>{let g=`${a}_${o}${d?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let _=[n,t,c,...d?[s]:[],...f?[l]:[]];if(r.addModels(_),f&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{if(e.info(`[SADOT] CustomFieldDefinition userScope started`),h?.())return{};let t=i();return e.info(`[SADOT] CustomFieldDefinition user`,{user:t,userPermissions:t?.permissions}),t?.permissions?(e.info(``),{where:{entityId:[...Object.keys(t.permissions.fleets),...Object.keys(t.permissions.businessModels),...Object.keys(t.permissions.demandSources)]}}):{}}),c.addScope(`userScope`,()=>{if(h?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`),p){e.info(`custom-fields: running legacy sync migrations`),await m(r,{schemaPrefix:a,schemaVersion:g,useCustomFieldsEntries:d,useModelTypeMapping:f});return}e.info(`custom-fields: starting umzug migrations`),await u(r,{useCustomFieldsEntries:d,useModelTypeMapping:f}),e.info(`custom-fields: umzug migrations complete`)},g=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(p),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{h as initTables,g as initTestModels};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/models/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","productionModels: ProductionModel[]"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n runLegacyMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\n/**\n * Legacy migration approach using sequelize.sync({ alter: true }).\n * TODO: Remove this function once all consumers have migrated to umzug.\n */\nconst legacySyncMigrations = async (\n sequelize: Sequelize,\n {\n schemaPrefix,\n schemaVersion,\n useCustomFieldsEntries,\n useModelTypeMapping,\n }: { schemaPrefix: string; schemaVersion: string; useCustomFieldsEntries: boolean; useModelTypeMapping: boolean; },\n): Promise<void> => {\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === schemaVersion);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: schemaVersion,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== schemaVersion) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: schemaVersion });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n runLegacyMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (runLegacyMigrations) {\n logger.info('custom-fields: running legacy sync migrations');\n await legacySyncMigrations(sequelize, { schemaPrefix, schemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION, useCustomFieldsEntries, useModelTypeMapping });\n return;\n }\n\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAStF,EAAuB,MAC3B,EACA,CACE,eACA,gBACA,yBACA,yBAEgB,CAClB,IAAM,EAAgB,EAAU,OAC9B,gBACA,CACE,KAAM,CACJ,KAAM,EAAU,OAChB,UAAW,GACX,OAAQ,GACR,WAAY,GACZ,cAAe,GAChB,CACF,CACD,CACE,UAAW,gBACX,WAAY,GACZ,OAAQ,SACT,CACF,CAED,EAAO,KAAK,qCAAqC,CACjD,IAAM,EAAa,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAG,EAAG,MAAO,GAAG,EAAa,GAAI,CAAE,CAAE,IAAK,GAAM,CAAC,CAC3G,EAA4B,EAAW,GAAG,GAAG,CAC7C,EAA6B,EAAW,UAAU,GAAM,EAAU,OAAS,EAAc,CAQ/F,GANA,EAAO,KAAK,4BAA6B,CACvC,kBAAmB,EACnB,4BACA,sBAAuB,EACvB,6BACD,CAAC,CACE,CAAC,GAA8B,EAAkC,OAAS,EAAe,CAC3F,EAAO,KAAK,gCAAgC,CAC5C,GAAI,CA2BF,GA1BA,MAAMC,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,2DAA2D,CAEvE,MAAM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Aa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","productionModels: ProductionModel[]"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n runLegacyMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\n/**\n * Legacy migration approach using sequelize.sync({ alter: true }).\n * TODO: Remove this function once all consumers have migrated to umzug.\n */\nconst legacySyncMigrations = async (\n sequelize: Sequelize,\n {\n schemaPrefix,\n schemaVersion,\n useCustomFieldsEntries,\n useModelTypeMapping,\n }: { schemaPrefix: string; schemaVersion: string; useCustomFieldsEntries: boolean; useModelTypeMapping: boolean; },\n): Promise<void> => {\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === schemaVersion);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: schemaVersion,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== schemaVersion) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: schemaVersion });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n runLegacyMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n logger.info('[SADOT] CustomFieldDefinition userScope started');\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n logger.info('[SADOT] CustomFieldDefinition user', { user, userPermissions: user?.permissions });\n if (!user?.permissions) {\n return {};\n }\n logger.info('')\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (runLegacyMigrations) {\n logger.info('custom-fields: running legacy sync migrations');\n await legacySyncMigrations(sequelize, { schemaPrefix, schemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION, useCustomFieldsEntries, useModelTypeMapping });\n return;\n }\n\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAStF,EAAuB,MAC3B,EACA,CACE,eACA,gBACA,yBACA,yBAEgB,CAClB,IAAM,EAAgB,EAAU,OAC9B,gBACA,CACE,KAAM,CACJ,KAAM,EAAU,OAChB,UAAW,GACX,OAAQ,GACR,WAAY,GACZ,cAAe,GAChB,CACF,CACD,CACE,UAAW,gBACX,WAAY,GACZ,OAAQ,SACT,CACF,CAED,EAAO,KAAK,qCAAqC,CACjD,IAAM,EAAa,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAG,EAAG,MAAO,GAAG,EAAa,GAAI,CAAE,CAAE,IAAK,GAAM,CAAC,CAC3G,EAA4B,EAAW,GAAG,GAAG,CAC7C,EAA6B,EAAW,UAAU,GAAM,EAAU,OAAS,EAAc,CAQ/F,GANA,EAAO,KAAK,4BAA6B,CACvC,kBAAmB,EACnB,4BACA,sBAAuB,EACvB,6BACD,CAAC,CACE,CAAC,GAA8B,EAAkC,OAAS,EAAe,CAC3F,EAAO,KAAK,gCAAgC,CAC5C,GAAI,CA2BF,GA1BA,MAAMC,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,2DAA2D,CAEvE,MAAMC,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,EAAO,KAAK,sDAAsD,CAElE,MAAMC,EAAgB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC3C,EAAO,KAAK,qDAAqD,CAG7D,IACF,MAAMC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KAAK,mCAAmC,CAC/C,MAAMJ,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../errors/index.cjs`),r=require(`../models/CustomFieldDefinition.cjs`),i=require(`../models/CustomFieldModelTypeMap.cjs`);require(`../models/index.cjs`);let a=require(`sequelize`);const o=()=>`modelTypeMappings`in(r.default.associations||{}),s=e=>!e||!Array.isArray(e)?[]:e.map(e=>e.modelTypeId||e.dataValues?.modelTypeId).filter(e=>!!e),c=e=>{let t=e;return e.modelTypeIds=s(t.modelTypeMappings??t.dataValues?.modelTypeMappings),e},l=async e=>{let{modelTypeIds:t,...n}=e,a=await r.default.sequelize.transaction(async e=>{let a=await r.default.create(n,{transaction:e});return t?.length&&await i.default.bulkCreate(t.map(e=>({customFieldDefinitionId:a.id,modelTypeId:e})),{transaction:e}),a});return a.modelTypeIds=t??[],a},u=async(e,n={withDisabled:!1})=>{let i=n.withDisabled?r.default.unscoped():r.default,a=n.include;if(n.enrichWithModelTypeIds&&o()){let e={association:`modelTypeMappings`,required:!1,attributes:[`modelTypeId`]};a=n.include?Array.isArray(n.include)?[...n.include,e]:[n.include,e]:e}t.default.info(`[SADOT] where`,{where:e});let s=await i.scope(`userScope`).findAll({where:e,transaction:n.transaction,raw:!n.enrichWithModelTypeIds,logging:e=>t.default.info(`QUERY CFD`,e),include:a});return n.enrichWithModelTypeIds&&o()?s.map(c):s},d=(e,t={withDisabled:!1})=>u({id:{[a.Op.in]:e}},t),f=async(e,t={withDisabled:!1})=>{let{withDisabled:n}=t,i=n?r.default.unscoped().scope(`userScope`):r.default.scope(`userScope`),a=o(),s=await i.findByPk(e,{include:a?[{association:`modelTypeMappings`,required:!1,attributes:[`modelTypeId`]}]:void 0});return s?a?c(s):s:null},p=async(e,t,n={})=>{let{include:i,useEntityIdFromInclude:o}=n.modelOptions,s={modelType:e,...!o&&{entityId:{[a.Op.in]:t}}};return r.default.findAll({where:s,transaction:n.transaction,include:i?.(t),raw:!0})},m=e=>r.default.scope(`userScope`).findOne({where:e}),h=async(e,t)=>{let{modelTypeIds:n,...a}=t,o=await r.default.sequelize.transaction(async t=>{let o=(await r.default.scope(`userScope`).update(a,{where:{id:e},returning:!0,individualHooks:!0,transaction:t}))[1][0];if(n){let r=await i.default.findAll({where:{customFieldDefinitionId:e},attributes:[`id`,`modelTypeId`],raw:!0,transaction:t}),a=r.map(e=>e.modelTypeId),s=n.filter(e=>!a.includes(e)),c=r.filter(e=>!n.includes(e.modelTypeId)),l=c.length>0||s.length>0;c.length>0&&await i.default.destroy({where:{id:c.map(e=>e.id)},transaction:t}),s.length>0&&await i.default.bulkCreate(s.map(t=>({customFieldDefinitionId:e,modelTypeId:t})),{transaction:t}),l&&(o.changed(`updatedAt`,!0),await o.save({transaction:t}))}return o});return o.modelTypeIds=n??[],o},g=async(e,t={withDisabled:!1,modelType:``})=>{let{withDisabled:n,entityIds:i,modelType:s,modelOptions:l}=t,{include:u,useEntityIdFromInclude:d}=l??{},f={modelType:s,...!d&&i&&i.length>0&&{entityId:{[a.Op.in]:i}}},p=n?r.default.unscoped():r.default,m=o(),h=[];if(m&&h.push({association:`modelTypeMappings`,required:!1,attributes:[`id`,`modelTypeId`]}),d&&u&&i){let e=u(i);h.push(...e)}let g=await p.scope(`userScope`).findAll({where:f,include:h.length>0?h:void 0,raw:!1,transaction:t.transaction}),_=m?g.filter(t=>{let n=t.modelTypeMappings??t.dataValues?.modelTypeMappings??[];return!Array.isArray(n)||n.length===0?!0:n.some(t=>(t.modelTypeId??t.dataValues?.modelTypeId)===e)}):g;return m?_.map(c):_},_=async(e,{findAll:t,modelOptions:r={},withDisabled:i=!1,...o}={withDisabled:!1,modelOptions:{}})=>{let{modelType:s}=e[0]?.dataValues??{},c=new Set,l=[],d=new Set;e.forEach(e=>{let{dataValues:{modelId:t,entityId:n,customFields:r}}=e;l.push(t),d.add(n),Object.keys(r??{}).forEach(e=>{c.add(e)})});let f={modelType:s,entityId:{[a.Op.in]:Array.from(d)},name:{[a.Op.in]:Array.from(c)}},p=await(t??u)(f,{withDisabled:i,modelOptions:r,...o}),m=p.filter(e=>c.has(e.name)),h=Object.fromEntries(m.map(e=>[e.name,e]));if(!p?.length||m.length!==c.size)throw new n.MissingDefinitionError(Array.from(c).filter(e=>!h[e]));return h};exports.create=l,exports.findAll=u,exports.findByEntityIds=p,exports.findById=f,exports.findByIds=d,exports.findByModelTypeId=g,exports.findByWhere=m,exports.getCustomFieldDefinitionsDictionary=_,exports.update=h;
|
|
2
2
|
//# sourceMappingURL=definition.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definition.cjs","names":["CustomFieldDefinition","CustomFieldModelTypeMap","includeToUse: Includeable | Includeable[] | undefined","modelTypeMappingsInclude: Includeable","Op","where: WhereOptions","baseWhere: WhereOptions","includeArray: any[]","MissingDefinitionError"],"sources":["../../src/repository/definition.ts"],"sourcesContent":["import {\n Op,\n type Includeable, type Transaction, type FindOptions, type WhereOptions, type Transactionable,\n} from 'sequelize';\nimport { CustomFieldDefinition, CustomFieldModelTypeMap, type CustomFieldEntries } from '../models';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';\nimport type { ModelOptions } from '../types';\nimport { MissingDefinitionError } from '../errors';\n\n/**\n * Interface for mapping association data (can be raw or Sequelize model instance)\n */\ninterface MappingData {\n modelTypeId?: string;\n dataValues?: {\n modelTypeId?: string;\n };\n}\n\n/**\n * Check if the modelTypeMappings association exists on CustomFieldDefinition\n * The association is only created when useModelTypeMapping: true is passed to initTables\n */\nconst hasModelTypeMappingsAssociation = (): boolean =>\n 'modelTypeMappings' in (CustomFieldDefinition.associations || {});\n\n/**\n * Helper to extract modelTypeIds from the modelTypeMappings association data\n * Handles both raw and non-raw Sequelize results\n */\nconst extractModelTypeIdsFromMappings = (mappings: MappingData[]): string[] => {\n if (!mappings || !Array.isArray(mappings)) {\n return [];\n }\n\n return mappings\n .map((m: MappingData) => m.modelTypeId || m.dataValues?.modelTypeId)\n .filter(id => Boolean(id)) as string[];\n};\n\n/**\n * Helper to extract modelTypeIds from a definition with loaded association\n * Handles the common pattern of getting mappings from a definition\n */\nconst enrichDefinitionWithModelTypeIds = (\n definition: CustomFieldDefinition,\n): CustomFieldDefinition & { modelTypeIds?: string[]; } => {\n const defWithMappings = definition as CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n };\n const mappings = defWithMappings.modelTypeMappings ?? defWithMappings.dataValues?.modelTypeMappings;\n definition.modelTypeIds = extractModelTypeIdsFromMappings(mappings);\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const create = async (\n data: CreateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const customFieldDefinition = await CustomFieldDefinition.create(definitionData as any, {\n transaction,\n });\n\n if (modelTypeIds?.length) {\n await CustomFieldModelTypeMap.bulkCreate(\n modelTypeIds.map(modelTypeId => ({\n customFieldDefinitionId: customFieldDefinition.id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n return customFieldDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\ninterface SadotFindOptions {\n withDisabled?: boolean;\n transaction?: Transaction | null;\n include?: Includeable | Includeable[];\n enrichWithModelTypeIds?: boolean;\n}\n\ntype SadotGetDefinitionsByEntityIdsOptions = FindOptions & { modelOptions?: ModelOptions; findAll?: typeof findAll; } & Pick<SadotFindOptions, 'withDisabled'>;\n\nexport const findAll = async (\n where: WhereOptions,\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => {\n const queryModel = options.withDisabled\n ? CustomFieldDefinition.unscoped()\n : CustomFieldDefinition;\n\n // Build include array - ensure we maintain the type compatibility\n let includeToUse: Includeable | Includeable[] | undefined = options.include;\n\n // If enrichWithModelTypeIds is requested and the association exists, include it to avoid N+1 queries\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n const modelTypeMappingsInclude: Includeable = {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n };\n\n if (options.include) {\n // Combine existing includes with modelTypeMappings\n includeToUse = Array.isArray(options.include)\n ? [...options.include, modelTypeMappingsInclude]\n : [options.include, modelTypeMappingsInclude];\n } else {\n includeToUse = modelTypeMappingsInclude;\n }\n }\n\n const definitions = await queryModel.scope('userScope').findAll({\n where,\n transaction: options.transaction,\n raw: !options.enrichWithModelTypeIds,\n include: includeToUse,\n });\n\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n // Extract modelTypeIds from the included association data instead of making N queries\n return definitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return definitions;\n};\n\nexport const findByIds = (\n ids: string[],\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => findAll({ id: { [Op.in]: ids } }, options);\n\nexport const findById = async (\n id: string,\n options: Pick<SadotFindOptions, 'withDisabled'> = { withDisabled: false },\n): Promise<CustomFieldDefinition | null> => {\n const { withDisabled } = options;\n\n const queryModel = withDisabled\n ? CustomFieldDefinition.unscoped().scope('userScope')\n : CustomFieldDefinition.scope('userScope');\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n\n const definition = await queryModel.findByPk(id, {\n include: includeModelTypeMappings ? [\n {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n },\n ] : undefined,\n });\n\n if (!definition) {\n return null;\n }\n\n // Extract modelTypeIds from the included association data if the association exists\n if (includeModelTypeMappings) {\n return enrichDefinitionWithModelTypeIds(definition);\n }\n\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const findByEntityIds = async (\n modelType: string,\n entityIds: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldDefinition[]> => {\n const { include, useEntityIdFromInclude } = options.modelOptions!;\n const where: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n return CustomFieldDefinition.findAll({\n where,\n transaction: options.transaction,\n include: include?.(entityIds),\n raw: true,\n });\n};\n\nexport const findByWhere = (where: WhereOptions<CustomFieldDefinition>): Promise<CustomFieldDefinition | null> =>\n CustomFieldDefinition.scope('userScope').findOne({\n where,\n });\n\nexport const findDefinitionsByModels = async (\n modelTypes: string[],\n options?: Transactionable,\n): Promise<CustomFieldDefinition[]> => {\n const query: WhereOptions<CreateCustomFieldDefinition> = { modelType: { [Op.in]: modelTypes } };\n return CustomFieldDefinition.findAll({\n where: query,\n transaction: options?.transaction,\n });\n};\n\nexport const update = async (\n id: string,\n data: UpdateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const updatedDefinition = (await CustomFieldDefinition.scope('userScope').update(definitionData, {\n where: { id },\n returning: true,\n individualHooks: true,\n transaction,\n }))[1][0];\n\n if (modelTypeIds) {\n const existingMappings = await CustomFieldModelTypeMap.findAll({\n where: { customFieldDefinitionId: id },\n attributes: ['id', 'modelTypeId'],\n raw: true,\n transaction,\n });\n\n const existingTypeIds = existingMappings.map(m => m.modelTypeId);\n\n const toAdd = modelTypeIds.filter(typeId => !existingTypeIds.includes(typeId));\n const toRemove = existingMappings.filter(m => !modelTypeIds.includes(m.modelTypeId));\n\n // Check if there are any mapping changes\n const hasMappingChanges = toRemove.length > 0 || toAdd.length > 0;\n\n if (toRemove.length > 0) {\n await CustomFieldModelTypeMap.destroy({\n where: {\n id: toRemove.map(m => m.id),\n },\n transaction,\n });\n }\n\n if (toAdd.length > 0) {\n await CustomFieldModelTypeMap.bulkCreate(\n toAdd.map(modelTypeId => ({\n customFieldDefinitionId: id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n // Touch the definition to update its updatedAt timestamp after mapping changes\n if (hasMappingChanges) {\n updatedDefinition.changed('updatedAt', true);\n await updatedDefinition.save({ transaction });\n }\n }\n\n return updatedDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const disable = (id: string): Promise<[affectedCount: number]> =>\n CustomFieldDefinition.update(\n { disabled: true },\n { where: { id } },\n );\n\nexport const destroy = (id: string): Promise<number> =>\n CustomFieldDefinition.destroy({ where: { id } });\n\n/**\n * Return the names of the required fields for a given model\n */\nexport const getRequiredFields = async (\n modelType: string,\n modelId: string | string[],\n entityId: string | string[],\n modelOptions: ModelOptions = {},\n): Promise<string[]> => {\n const entityIds = Array.isArray(entityId) ? entityId : [entityId];\n const { include, useEntityIdFromInclude } = modelOptions;\n\n const where: WhereOptions = {\n modelType,\n required: true,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n const requiredFields = await CustomFieldDefinition.findAll({\n where,\n include: include?.(entityIds),\n logging: true,\n });\n const requiredFieldsNames = requiredFields.map(definition => definition.name);\n return [...new Set(requiredFieldsNames)];\n};\n\n/**\n * @returns A promise resolving with a dictionary of custom field definitions by name.\n * @throws A {@link MissingDefinitionError} if any of the custom fields doesn't have a definition.\n */\n/**\n * Find custom field definitions applicable to a specific model type instance\n *\n * Returns definitions that either:\n * 1. Have NO mappings (apply to all instances of this model type)\n * 2. Have a mapping to this specific model type instance\n */\nexport const findByModelTypeId = async (\n modelTypeId: string,\n options: Pick<SadotFindOptions, 'withDisabled' | 'transaction'> & { entityIds?: string[]; modelType: string; modelOptions?: ModelOptions; } = { withDisabled: false, modelType: '' },\n): Promise<CustomFieldDefinition[]> => {\n const { withDisabled, entityIds, modelType, modelOptions } = options;\n\n const { include, useEntityIdFromInclude } = modelOptions ?? {};\n\n const baseWhere: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && entityIds && entityIds.length > 0 && { entityId: { [Op.in]: entityIds } }),\n };\n\n const queryModel = withDisabled\n ? (CustomFieldDefinition as any).unscoped()\n : CustomFieldDefinition;\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n const includeArray: any[] = [];\n\n // Only include the association if it exists\n if (includeModelTypeMappings) {\n includeArray.push({\n association: 'modelTypeMappings',\n required: false,\n attributes: ['id', 'modelTypeId'],\n });\n }\n\n if (useEntityIdFromInclude && include && entityIds) {\n const contextIncludes = include(entityIds);\n includeArray.push(...contextIncludes);\n }\n\n const definitions = await queryModel.scope('userScope').findAll({\n where: baseWhere,\n include: includeArray.length > 0 ? includeArray : undefined,\n raw: false,\n transaction: options.transaction,\n });\n\n // Only filter by modelTypeId if the association exists\n const filteredDefinitions = includeModelTypeMappings ? definitions.filter((def: CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n }) => {\n const mappings = def.modelTypeMappings ?? def.dataValues?.modelTypeMappings ?? [];\n\n if (!Array.isArray(mappings) || mappings.length === 0) {\n return true;\n }\n\n const hasMatch = mappings.some((mapping: MappingData) => {\n const mappingTypeId = mapping.modelTypeId ?? mapping.dataValues?.modelTypeId;\n return mappingTypeId === modelTypeId;\n });\n\n return hasMatch;\n }) : definitions;\n\n // Use association data to extract modelTypeIds if the association exists\n if (includeModelTypeMappings) {\n return filteredDefinitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return filteredDefinitions as (CustomFieldDefinition & { modelTypeIds?: string[]; })[];\n};\n\nexport const getCustomFieldDefinitionsDictionary = async (\n instances: CustomFieldEntries[],\n {\n findAll: _findAll,\n modelOptions = {},\n withDisabled = false,\n ...options\n }: SadotGetDefinitionsByEntityIdsOptions = { withDisabled: false, modelOptions: {} },\n): Promise<Record<string, CustomFieldDefinition>> => {\n const { modelType } = instances[0]?.dataValues ?? {};\n const customFields = new Set<string>();\n const modelIds = [];\n const entityIds = new Set<string>();\n instances.forEach((instance) => {\n const { dataValues: { modelId, entityId, customFields: instanceCustomFields } } = instance;\n modelIds.push(modelId);\n entityIds.add(entityId);\n\n Object.keys(instanceCustomFields ?? {}).forEach((fieldName) => {\n customFields.add(fieldName);\n });\n });\n\n const where: WhereOptions = {\n modelType,\n entityId: { [Op.in]: Array.from(entityIds) },\n name: { [Op.in]: Array.from(customFields) },\n };\n\n const findAllToUse = _findAll ?? findAll;\n\n // @ts-expect-error findAll doesn't expect modelOptions at all.\n const definitions = await findAllToUse(where, { withDisabled, modelOptions, ...options });\n\n const matchedDefinitions = definitions.filter(def => customFields.has(def.name));\n const matchedDefinitionsByName = Object.fromEntries(matchedDefinitions.map(definition => [definition.name, definition]));\n\n if (!definitions?.length || matchedDefinitions.length !== customFields.size) {\n const unmatchedCustomFields = Array.from(customFields).filter(customField => !matchedDefinitionsByName[customField]);\n throw new MissingDefinitionError(unmatchedCustomFields);\n }\n\n return matchedDefinitionsByName;\n};\n"],"mappings":"mPAuBA,MAAM,MACJ,sBAAwBA,EAAAA,QAAsB,cAAgB,EAAE,EAM5D,EAAmC,GACnC,CAAC,GAAY,CAAC,MAAM,QAAQ,EAAS,CAChC,EAAE,CAGJ,EACJ,IAAK,GAAmB,EAAE,aAAe,EAAE,YAAY,YAAY,CACnE,OAAO,GAAM,EAAQ,EAAI,CAOxB,EACJ,GACyD,CACzD,IAAM,EAAkB,EAMxB,MADA,GAAW,aAAe,EADT,EAAgB,mBAAqB,EAAgB,YAAY,kBACf,CAC5D,GAGI,EAAS,KACpB,IACmC,CACnC,GAAM,C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ToUse: Includeable | Includeable[] | undefined","modelTypeMappingsInclude: Includeable","logger","Op","where: WhereOptions","baseWhere: WhereOptions","includeArray: any[]","MissingDefinitionError"],"sources":["../../src/repository/definition.ts"],"sourcesContent":["import {\n Op,\n type Includeable, type Transaction, type FindOptions, type WhereOptions, type Transactionable,\n} from 'sequelize';\nimport { CustomFieldDefinition, CustomFieldModelTypeMap, type CustomFieldEntries } from '../models';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';\nimport type { ModelOptions } from '../types';\nimport { MissingDefinitionError } from '../errors';\nimport logger from '../utils/logger';\n\n/**\n * Interface for mapping association data (can be raw or Sequelize model instance)\n */\ninterface MappingData {\n modelTypeId?: string;\n dataValues?: {\n modelTypeId?: string;\n };\n}\n\n/**\n * Check if the modelTypeMappings association exists on CustomFieldDefinition\n * The association is only created when useModelTypeMapping: true is passed to initTables\n */\nconst hasModelTypeMappingsAssociation = (): boolean =>\n 'modelTypeMappings' in (CustomFieldDefinition.associations || {});\n\n/**\n * Helper to extract modelTypeIds from the modelTypeMappings association data\n * Handles both raw and non-raw Sequelize results\n */\nconst extractModelTypeIdsFromMappings = (mappings: MappingData[]): string[] => {\n if (!mappings || !Array.isArray(mappings)) {\n return [];\n }\n\n return mappings\n .map((m: MappingData) => m.modelTypeId || m.dataValues?.modelTypeId)\n .filter(id => Boolean(id)) as string[];\n};\n\n/**\n * Helper to extract modelTypeIds from a definition with loaded association\n * Handles the common pattern of getting mappings from a definition\n */\nconst enrichDefinitionWithModelTypeIds = (\n definition: CustomFieldDefinition,\n): CustomFieldDefinition & { modelTypeIds?: string[]; } => {\n const defWithMappings = definition as CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n };\n const mappings = defWithMappings.modelTypeMappings ?? defWithMappings.dataValues?.modelTypeMappings;\n definition.modelTypeIds = extractModelTypeIdsFromMappings(mappings);\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const create = async (\n data: CreateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const customFieldDefinition = await CustomFieldDefinition.create(definitionData as any, {\n transaction,\n });\n\n if (modelTypeIds?.length) {\n await CustomFieldModelTypeMap.bulkCreate(\n modelTypeIds.map(modelTypeId => ({\n customFieldDefinitionId: customFieldDefinition.id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n return customFieldDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\ninterface SadotFindOptions {\n withDisabled?: boolean;\n transaction?: Transaction | null;\n include?: Includeable | Includeable[];\n enrichWithModelTypeIds?: boolean;\n}\n\ntype SadotGetDefinitionsByEntityIdsOptions = FindOptions & { modelOptions?: ModelOptions; findAll?: typeof findAll; } & Pick<SadotFindOptions, 'withDisabled'>;\n\nexport const findAll = async (\n where: WhereOptions,\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => {\n const queryModel = options.withDisabled\n ? CustomFieldDefinition.unscoped()\n : CustomFieldDefinition;\n\n // Build include array - ensure we maintain the type compatibility\n let includeToUse: Includeable | Includeable[] | undefined = options.include;\n\n // If enrichWithModelTypeIds is requested and the association exists, include it to avoid N+1 queries\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n const modelTypeMappingsInclude: Includeable = {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n };\n\n if (options.include) {\n // Combine existing includes with modelTypeMappings\n includeToUse = Array.isArray(options.include)\n ? [...options.include, modelTypeMappingsInclude]\n : [options.include, modelTypeMappingsInclude];\n } else {\n includeToUse = modelTypeMappingsInclude;\n }\n }\n\n logger.info('[SADOT] where', { where });\n\n const definitions = await queryModel.scope('userScope').findAll({\n where,\n transaction: options.transaction,\n raw: !options.enrichWithModelTypeIds,\n logging: (query) => logger.info('QUERY CFD', query),\n include: includeToUse,\n });\n\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n // Extract modelTypeIds from the included association data instead of making N queries\n return definitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return definitions;\n};\n\nexport const findByIds = (\n ids: string[],\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => findAll({ id: { [Op.in]: ids } }, options);\n\nexport const findById = async (\n id: string,\n options: Pick<SadotFindOptions, 'withDisabled'> = { withDisabled: false },\n): Promise<CustomFieldDefinition | null> => {\n const { withDisabled } = options;\n\n const queryModel = withDisabled\n ? CustomFieldDefinition.unscoped().scope('userScope')\n : CustomFieldDefinition.scope('userScope');\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n\n const definition = await queryModel.findByPk(id, {\n include: includeModelTypeMappings ? [\n {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n },\n ] : undefined,\n });\n\n if (!definition) {\n return null;\n }\n\n // Extract modelTypeIds from the included association data if the association exists\n if (includeModelTypeMappings) {\n return enrichDefinitionWithModelTypeIds(definition);\n }\n\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const findByEntityIds = async (\n modelType: string,\n entityIds: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldDefinition[]> => {\n const { include, useEntityIdFromInclude } = options.modelOptions!;\n const where: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n return CustomFieldDefinition.findAll({\n where,\n transaction: options.transaction,\n include: include?.(entityIds),\n raw: true,\n });\n};\n\nexport const findByWhere = (where: WhereOptions<CustomFieldDefinition>): Promise<CustomFieldDefinition | null> =>\n CustomFieldDefinition.scope('userScope').findOne({\n where,\n });\n\nexport const findDefinitionsByModels = async (\n modelTypes: string[],\n options?: Transactionable,\n): Promise<CustomFieldDefinition[]> => {\n const query: WhereOptions<CreateCustomFieldDefinition> = { modelType: { [Op.in]: modelTypes } };\n return CustomFieldDefinition.findAll({\n where: query,\n transaction: options?.transaction,\n });\n};\n\nexport const update = async (\n id: string,\n data: UpdateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const updatedDefinition = (await CustomFieldDefinition.scope('userScope').update(definitionData, {\n where: { id },\n returning: true,\n individualHooks: true,\n transaction,\n }))[1][0];\n\n if (modelTypeIds) {\n const existingMappings = await CustomFieldModelTypeMap.findAll({\n where: { customFieldDefinitionId: id },\n attributes: ['id', 'modelTypeId'],\n raw: true,\n transaction,\n });\n\n const existingTypeIds = existingMappings.map(m => m.modelTypeId);\n\n const toAdd = modelTypeIds.filter(typeId => !existingTypeIds.includes(typeId));\n const toRemove = existingMappings.filter(m => !modelTypeIds.includes(m.modelTypeId));\n\n // Check if there are any mapping changes\n const hasMappingChanges = toRemove.length > 0 || toAdd.length > 0;\n\n if (toRemove.length > 0) {\n await CustomFieldModelTypeMap.destroy({\n where: {\n id: toRemove.map(m => m.id),\n },\n transaction,\n });\n }\n\n if (toAdd.length > 0) {\n await CustomFieldModelTypeMap.bulkCreate(\n toAdd.map(modelTypeId => ({\n customFieldDefinitionId: id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n // Touch the definition to update its updatedAt timestamp after mapping changes\n if (hasMappingChanges) {\n updatedDefinition.changed('updatedAt', true);\n await updatedDefinition.save({ transaction });\n }\n }\n\n return updatedDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const disable = (id: string): Promise<[affectedCount: number]> =>\n CustomFieldDefinition.update(\n { disabled: true },\n { where: { id } },\n );\n\nexport const destroy = (id: string): Promise<number> =>\n CustomFieldDefinition.destroy({ where: { id } });\n\n/**\n * Return the names of the required fields for a given model\n */\nexport const getRequiredFields = async (\n modelType: string,\n modelId: string | string[],\n entityId: string | string[],\n modelOptions: ModelOptions = {},\n): Promise<string[]> => {\n const entityIds = Array.isArray(entityId) ? entityId : [entityId];\n const { include, useEntityIdFromInclude } = modelOptions;\n\n const where: WhereOptions = {\n modelType,\n required: true,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n const requiredFields = await CustomFieldDefinition.findAll({\n where,\n include: include?.(entityIds),\n logging: true,\n });\n const requiredFieldsNames = requiredFields.map(definition => definition.name);\n return [...new Set(requiredFieldsNames)];\n};\n\n/**\n * @returns A promise resolving with a dictionary of custom field definitions by name.\n * @throws A {@link MissingDefinitionError} if any of the custom fields doesn't have a definition.\n */\n/**\n * Find custom field definitions applicable to a specific model type instance\n *\n * Returns definitions that either:\n * 1. Have NO mappings (apply to all instances of this model type)\n * 2. Have a mapping to this specific model type instance\n */\nexport const findByModelTypeId = async (\n modelTypeId: string,\n options: Pick<SadotFindOptions, 'withDisabled' | 'transaction'> & { entityIds?: string[]; modelType: string; modelOptions?: ModelOptions; } = { withDisabled: false, modelType: '' },\n): Promise<CustomFieldDefinition[]> => {\n const { withDisabled, entityIds, modelType, modelOptions } = options;\n\n const { include, useEntityIdFromInclude } = modelOptions ?? {};\n\n const baseWhere: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && entityIds && entityIds.length > 0 && { entityId: { [Op.in]: entityIds } }),\n };\n\n const queryModel = withDisabled\n ? (CustomFieldDefinition as any).unscoped()\n : CustomFieldDefinition;\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n const includeArray: any[] = [];\n\n // Only include the association if it exists\n if (includeModelTypeMappings) {\n includeArray.push({\n association: 'modelTypeMappings',\n required: false,\n attributes: ['id', 'modelTypeId'],\n });\n }\n\n if (useEntityIdFromInclude && include && entityIds) {\n const contextIncludes = include(entityIds);\n includeArray.push(...contextIncludes);\n }\n\n const definitions = await queryModel.scope('userScope').findAll({\n where: baseWhere,\n include: includeArray.length > 0 ? includeArray : undefined,\n raw: false,\n transaction: options.transaction,\n });\n\n // Only filter by modelTypeId if the association exists\n const filteredDefinitions = includeModelTypeMappings ? definitions.filter((def: CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n }) => {\n const mappings = def.modelTypeMappings ?? def.dataValues?.modelTypeMappings ?? [];\n\n if (!Array.isArray(mappings) || mappings.length === 0) {\n return true;\n }\n\n const hasMatch = mappings.some((mapping: MappingData) => {\n const mappingTypeId = mapping.modelTypeId ?? mapping.dataValues?.modelTypeId;\n return mappingTypeId === modelTypeId;\n });\n\n return hasMatch;\n }) : definitions;\n\n // Use association data to extract modelTypeIds if the association exists\n if (includeModelTypeMappings) {\n return filteredDefinitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return filteredDefinitions as (CustomFieldDefinition & { modelTypeIds?: string[]; })[];\n};\n\nexport const getCustomFieldDefinitionsDictionary = async (\n instances: CustomFieldEntries[],\n {\n findAll: _findAll,\n modelOptions = {},\n withDisabled = false,\n ...options\n }: SadotGetDefinitionsByEntityIdsOptions = { withDisabled: false, modelOptions: {} },\n): Promise<Record<string, CustomFieldDefinition>> => {\n const { modelType } = instances[0]?.dataValues ?? {};\n const customFields = new Set<string>();\n const modelIds = [];\n const entityIds = new Set<string>();\n instances.forEach((instance) => {\n const { dataValues: { modelId, entityId, customFields: instanceCustomFields } } = instance;\n modelIds.push(modelId);\n entityIds.add(entityId);\n\n Object.keys(instanceCustomFields ?? {}).forEach((fieldName) => {\n customFields.add(fieldName);\n });\n });\n\n const where: WhereOptions = {\n modelType,\n entityId: { [Op.in]: Array.from(entityIds) },\n name: { [Op.in]: Array.from(customFields) },\n };\n\n const findAllToUse = _findAll ?? findAll;\n\n // @ts-expect-error findAll doesn't expect modelOptions at all.\n const definitions = await findAllToUse(where, { withDisabled, modelOptions, ...options });\n\n const matchedDefinitions = definitions.filter(def => customFields.has(def.name));\n const matchedDefinitionsByName = Object.fromEntries(matchedDefinitions.map(definition => [definition.name, definition]));\n\n if (!definitions?.length || matchedDefinitions.length !== customFields.size) {\n const unmatchedCustomFields = Array.from(customFields).filter(customField => !matchedDefinitionsByName[customField]);\n throw new MissingDefinitionError(unmatchedCustomFields);\n }\n\n return matchedDefinitionsByName;\n};\n"],"mappings":"0RAwBA,MAAM,MACJ,sBAAwBA,EAAAA,QAAsB,cAAgB,EAAE,EAM5D,EAAmC,GACnC,CAAC,GAAY,CAAC,MAAM,QAAQ,EAAS,CAChC,EAAE,CAGJ,EACJ,IAAK,GAAmB,EAAE,aAAe,EAAE,YAAY,YAAY,CACnE,OAAO,GAAM,EAAQ,EAAI,CAOxB,EACJ,GACyD,CACzD,IAAM,EAAkB,EAMxB,MADA,GAAW,aAAe,EADT,EAAgB,mBAAqB,EAAgB,YAAY,kBACf,CAC5D,GAGI,EAAS,KACpB,IACmC,CACnC,GAAM,CAAE,eAAc,GAAG,GAAmB,EAEtC,EAAS,MAAMA,EAAAA,QAAsB,UAAW,YAAY,KAAO,IAA6B,CACpG,IAAM,EAAwB,MAAMA,EAAAA,QAAsB,OAAO,EAAuB,CACtF,cACD,CAAC,CAYF,OAVI,GAAc,QAChB,MAAMC,EAAAA,QAAwB,WAC5B,EAAa,IAAI,IAAgB,CAC/B,wBAAyB,EAAsB,GAC/C,cACD,EAAE,CACH,CAAE,cAAa,CAChB,CAGI,GACP,CAIF,MAFA,GAAO,aAAe,GAAgB,EAAE,CAEjC,GAYI,EAAU,MACrB,EACA,EAA4B,CAAE,aAAc,GAAO,GACd,CACrC,IAAM,EAAa,EAAQ,aACvBD,EAAAA,QAAsB,UAAU,CAChCA,EAAAA,QAGAE,EAAwD,EAAQ,QAGpE,GAAI,EAAQ,wBAA0B,GAAiC,CAAE,CACvE,IAAMC,EAAwC,CAC5C,YAAa,oBACb,SAAU,GACV,WAAY,CAAC,cAAc,CAC5B,CAED,AAME,EANE,EAAQ,QAEK,MAAM,QAAQ,EAAQ,QAAQ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EAAE,CAAC,CAAC,QAAS,GAAc,CAC7D,EAAa,IAAI,EAAU,EAC3B,EACF,CAEF,IAAMF,EAAsB,CAC1B,YACA,SAAU,EAAGD,EAAAA,GAAG,IAAK,MAAM,KAAK,EAAU,CAAE,CAC5C,KAAM,EAAGA,EAAAA,GAAG,IAAK,MAAM,KAAK,EAAa,CAAE,CAC5C,CAKK,EAAc,MAHC,GAAY,GAGM,EAAO,CAAE,eAAc,eAAc,GAAG,EAAS,CAAC,CAEnF,EAAqB,EAAY,OAAO,GAAO,EAAa,IAAI,EAAI,KAAK,CAAC,CAC1E,EAA2B,OAAO,YAAY,EAAmB,IAAI,GAAc,CAAC,EAAW,KAAM,EAAW,CAAC,CAAC,CAExH,GAAI,CAAC,GAAa,QAAU,EAAmB,SAAW,EAAa,KAErE,MAAM,IAAII,EAAAA,uBADoB,MAAM,KAAK,EAAa,CAAC,OAAO,GAAe,CAAC,EAAyB,GAAa,CAC7D,CAGzD,OAAO"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{MissingDefinitionError as
|
|
1
|
+
import e from"../utils/logger/index.js";import{MissingDefinitionError as t}from"../errors/index.js";import n from"../models/CustomFieldDefinition.js";import r from"../models/CustomFieldModelTypeMap.js";import"../models/index.js";import{Op as i}from"sequelize";const a=()=>`modelTypeMappings`in(n.associations||{}),o=e=>!e||!Array.isArray(e)?[]:e.map(e=>e.modelTypeId||e.dataValues?.modelTypeId).filter(e=>!!e),s=e=>{let t=e;return e.modelTypeIds=o(t.modelTypeMappings??t.dataValues?.modelTypeMappings),e},c=async e=>{let{modelTypeIds:t,...i}=e,a=await n.sequelize.transaction(async e=>{let a=await n.create(i,{transaction:e});return t?.length&&await r.bulkCreate(t.map(e=>({customFieldDefinitionId:a.id,modelTypeId:e})),{transaction:e}),a});return a.modelTypeIds=t??[],a},l=async(t,r={withDisabled:!1})=>{let i=r.withDisabled?n.unscoped():n,o=r.include;if(r.enrichWithModelTypeIds&&a()){let e={association:`modelTypeMappings`,required:!1,attributes:[`modelTypeId`]};o=r.include?Array.isArray(r.include)?[...r.include,e]:[r.include,e]:e}e.info(`[SADOT] where`,{where:t});let c=await i.scope(`userScope`).findAll({where:t,transaction:r.transaction,raw:!r.enrichWithModelTypeIds,logging:t=>e.info(`QUERY CFD`,t),include:o});return r.enrichWithModelTypeIds&&a()?c.map(s):c},u=(e,t={withDisabled:!1})=>l({id:{[i.in]:e}},t),d=async(e,t={withDisabled:!1})=>{let{withDisabled:r}=t,i=r?n.unscoped().scope(`userScope`):n.scope(`userScope`),o=a(),c=await i.findByPk(e,{include:o?[{association:`modelTypeMappings`,required:!1,attributes:[`modelTypeId`]}]:void 0});return c?o?s(c):c:null},f=async(e,t,r={})=>{let{include:a,useEntityIdFromInclude:o}=r.modelOptions,s={modelType:e,...!o&&{entityId:{[i.in]:t}}};return n.findAll({where:s,transaction:r.transaction,include:a?.(t),raw:!0})},p=e=>n.scope(`userScope`).findOne({where:e}),m=async(e,t)=>{let{modelTypeIds:i,...a}=t,o=await n.sequelize.transaction(async t=>{let o=(await n.scope(`userScope`).update(a,{where:{id:e},returning:!0,individualHooks:!0,transaction:t}))[1][0];if(i){let n=await r.findAll({where:{customFieldDefinitionId:e},attributes:[`id`,`modelTypeId`],raw:!0,transaction:t}),a=n.map(e=>e.modelTypeId),s=i.filter(e=>!a.includes(e)),c=n.filter(e=>!i.includes(e.modelTypeId)),l=c.length>0||s.length>0;c.length>0&&await r.destroy({where:{id:c.map(e=>e.id)},transaction:t}),s.length>0&&await r.bulkCreate(s.map(t=>({customFieldDefinitionId:e,modelTypeId:t})),{transaction:t}),l&&(o.changed(`updatedAt`,!0),await o.save({transaction:t}))}return o});return o.modelTypeIds=i??[],o},h=async(e,t={withDisabled:!1,modelType:``})=>{let{withDisabled:r,entityIds:o,modelType:c,modelOptions:l}=t,{include:u,useEntityIdFromInclude:d}=l??{},f={modelType:c,...!d&&o&&o.length>0&&{entityId:{[i.in]:o}}},p=r?n.unscoped():n,m=a(),h=[];if(m&&h.push({association:`modelTypeMappings`,required:!1,attributes:[`id`,`modelTypeId`]}),d&&u&&o){let e=u(o);h.push(...e)}let g=await p.scope(`userScope`).findAll({where:f,include:h.length>0?h:void 0,raw:!1,transaction:t.transaction}),_=m?g.filter(t=>{let n=t.modelTypeMappings??t.dataValues?.modelTypeMappings??[];return!Array.isArray(n)||n.length===0?!0:n.some(t=>(t.modelTypeId??t.dataValues?.modelTypeId)===e)}):g;return m?_.map(s):_},g=async(e,{findAll:n,modelOptions:r={},withDisabled:a=!1,...o}={withDisabled:!1,modelOptions:{}})=>{let{modelType:s}=e[0]?.dataValues??{},c=new Set,u=[],d=new Set;e.forEach(e=>{let{dataValues:{modelId:t,entityId:n,customFields:r}}=e;u.push(t),d.add(n),Object.keys(r??{}).forEach(e=>{c.add(e)})});let f={modelType:s,entityId:{[i.in]:Array.from(d)},name:{[i.in]:Array.from(c)}},p=await(n??l)(f,{withDisabled:a,modelOptions:r,...o}),m=p.filter(e=>c.has(e.name)),h=Object.fromEntries(m.map(e=>[e.name,e]));if(!p?.length||m.length!==c.size)throw new t(Array.from(c).filter(e=>!h[e]));return h};export{c as create,l as findAll,f as findByEntityIds,d as findById,u as findByIds,h as findByModelTypeId,p as findByWhere,g as getCustomFieldDefinitionsDictionary,m as update};
|
|
2
2
|
//# sourceMappingURL=definition.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definition.js","names":["CustomFieldDefinition","CustomFieldModelTypeMap","includeToUse: Includeable | Includeable[] | undefined","modelTypeMappingsInclude: Includeable","where: WhereOptions","baseWhere: WhereOptions","includeArray: any[]"],"sources":["../../src/repository/definition.ts"],"sourcesContent":["import {\n Op,\n type Includeable, type Transaction, type FindOptions, type WhereOptions, type Transactionable,\n} from 'sequelize';\nimport { CustomFieldDefinition, CustomFieldModelTypeMap, type CustomFieldEntries } from '../models';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';\nimport type { ModelOptions } from '../types';\nimport { MissingDefinitionError } from '../errors';\n\n/**\n * Interface for mapping association data (can be raw or Sequelize model instance)\n */\ninterface MappingData {\n modelTypeId?: string;\n dataValues?: {\n modelTypeId?: string;\n };\n}\n\n/**\n * Check if the modelTypeMappings association exists on CustomFieldDefinition\n * The association is only created when useModelTypeMapping: true is passed to initTables\n */\nconst hasModelTypeMappingsAssociation = (): boolean =>\n 'modelTypeMappings' in (CustomFieldDefinition.associations || {});\n\n/**\n * Helper to extract modelTypeIds from the modelTypeMappings association data\n * Handles both raw and non-raw Sequelize results\n */\nconst extractModelTypeIdsFromMappings = (mappings: MappingData[]): string[] => {\n if (!mappings || !Array.isArray(mappings)) {\n return [];\n }\n\n return mappings\n .map((m: MappingData) => m.modelTypeId || m.dataValues?.modelTypeId)\n .filter(id => Boolean(id)) as string[];\n};\n\n/**\n * Helper to extract modelTypeIds from a definition with loaded association\n * Handles the common pattern of getting mappings from a definition\n */\nconst enrichDefinitionWithModelTypeIds = (\n definition: CustomFieldDefinition,\n): CustomFieldDefinition & { modelTypeIds?: string[]; } => {\n const defWithMappings = definition as CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n };\n const mappings = defWithMappings.modelTypeMappings ?? defWithMappings.dataValues?.modelTypeMappings;\n definition.modelTypeIds = extractModelTypeIdsFromMappings(mappings);\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const create = async (\n data: CreateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const customFieldDefinition = await CustomFieldDefinition.create(definitionData as any, {\n transaction,\n });\n\n if (modelTypeIds?.length) {\n await CustomFieldModelTypeMap.bulkCreate(\n modelTypeIds.map(modelTypeId => ({\n customFieldDefinitionId: customFieldDefinition.id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n return customFieldDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\ninterface SadotFindOptions {\n withDisabled?: boolean;\n transaction?: Transaction | null;\n include?: Includeable | Includeable[];\n enrichWithModelTypeIds?: boolean;\n}\n\ntype SadotGetDefinitionsByEntityIdsOptions = FindOptions & { modelOptions?: ModelOptions; findAll?: typeof findAll; } & Pick<SadotFindOptions, 'withDisabled'>;\n\nexport const findAll = async (\n where: WhereOptions,\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => {\n const queryModel = options.withDisabled\n ? CustomFieldDefinition.unscoped()\n : CustomFieldDefinition;\n\n // Build include array - ensure we maintain the type compatibility\n let includeToUse: Includeable | Includeable[] | undefined = options.include;\n\n // If enrichWithModelTypeIds is requested and the association exists, include it to avoid N+1 queries\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n const modelTypeMappingsInclude: Includeable = {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n };\n\n if (options.include) {\n // Combine existing includes with modelTypeMappings\n includeToUse = Array.isArray(options.include)\n ? [...options.include, modelTypeMappingsInclude]\n : [options.include, modelTypeMappingsInclude];\n } else {\n includeToUse = modelTypeMappingsInclude;\n }\n }\n\n const definitions = await queryModel.scope('userScope').findAll({\n where,\n transaction: options.transaction,\n raw: !options.enrichWithModelTypeIds,\n include: includeToUse,\n });\n\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n // Extract modelTypeIds from the included association data instead of making N queries\n return definitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return definitions;\n};\n\nexport const findByIds = (\n ids: string[],\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => findAll({ id: { [Op.in]: ids } }, options);\n\nexport const findById = async (\n id: string,\n options: Pick<SadotFindOptions, 'withDisabled'> = { withDisabled: false },\n): Promise<CustomFieldDefinition | null> => {\n const { withDisabled } = options;\n\n const queryModel = withDisabled\n ? CustomFieldDefinition.unscoped().scope('userScope')\n : CustomFieldDefinition.scope('userScope');\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n\n const definition = await queryModel.findByPk(id, {\n include: includeModelTypeMappings ? [\n {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n },\n ] : undefined,\n });\n\n if (!definition) {\n return null;\n }\n\n // Extract modelTypeIds from the included association data if the association exists\n if (includeModelTypeMappings) {\n return enrichDefinitionWithModelTypeIds(definition);\n }\n\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const findByEntityIds = async (\n modelType: string,\n entityIds: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldDefinition[]> => {\n const { include, useEntityIdFromInclude } = options.modelOptions!;\n const where: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n return CustomFieldDefinition.findAll({\n where,\n transaction: options.transaction,\n include: include?.(entityIds),\n raw: true,\n });\n};\n\nexport const findByWhere = (where: WhereOptions<CustomFieldDefinition>): Promise<CustomFieldDefinition | null> =>\n CustomFieldDefinition.scope('userScope').findOne({\n where,\n });\n\nexport const findDefinitionsByModels = async (\n modelTypes: string[],\n options?: Transactionable,\n): Promise<CustomFieldDefinition[]> => {\n const query: WhereOptions<CreateCustomFieldDefinition> = { modelType: { [Op.in]: modelTypes } };\n return CustomFieldDefinition.findAll({\n where: query,\n transaction: options?.transaction,\n });\n};\n\nexport const update = async (\n id: string,\n data: UpdateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const updatedDefinition = (await CustomFieldDefinition.scope('userScope').update(definitionData, {\n where: { id },\n returning: true,\n individualHooks: true,\n transaction,\n }))[1][0];\n\n if (modelTypeIds) {\n const existingMappings = await CustomFieldModelTypeMap.findAll({\n where: { customFieldDefinitionId: id },\n attributes: ['id', 'modelTypeId'],\n raw: true,\n transaction,\n });\n\n const existingTypeIds = existingMappings.map(m => m.modelTypeId);\n\n const toAdd = modelTypeIds.filter(typeId => !existingTypeIds.includes(typeId));\n const toRemove = existingMappings.filter(m => !modelTypeIds.includes(m.modelTypeId));\n\n // Check if there are any mapping changes\n const hasMappingChanges = toRemove.length > 0 || toAdd.length > 0;\n\n if (toRemove.length > 0) {\n await CustomFieldModelTypeMap.destroy({\n where: {\n id: toRemove.map(m => m.id),\n },\n transaction,\n });\n }\n\n if (toAdd.length > 0) {\n await CustomFieldModelTypeMap.bulkCreate(\n toAdd.map(modelTypeId => ({\n customFieldDefinitionId: id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n // Touch the definition to update its updatedAt timestamp after mapping changes\n if (hasMappingChanges) {\n updatedDefinition.changed('updatedAt', true);\n await updatedDefinition.save({ transaction });\n }\n }\n\n return updatedDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const disable = (id: string): Promise<[affectedCount: number]> =>\n CustomFieldDefinition.update(\n { disabled: true },\n { where: { id } },\n );\n\nexport const destroy = (id: string): Promise<number> =>\n CustomFieldDefinition.destroy({ where: { id } });\n\n/**\n * Return the names of the required fields for a given model\n */\nexport const getRequiredFields = async (\n modelType: string,\n modelId: string | string[],\n entityId: string | string[],\n modelOptions: ModelOptions = {},\n): Promise<string[]> => {\n const entityIds = Array.isArray(entityId) ? entityId : [entityId];\n const { include, useEntityIdFromInclude } = modelOptions;\n\n const where: WhereOptions = {\n modelType,\n required: true,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n const requiredFields = await CustomFieldDefinition.findAll({\n where,\n include: include?.(entityIds),\n logging: true,\n });\n const requiredFieldsNames = requiredFields.map(definition => definition.name);\n return [...new Set(requiredFieldsNames)];\n};\n\n/**\n * @returns A promise resolving with a dictionary of custom field definitions by name.\n * @throws A {@link MissingDefinitionError} if any of the custom fields doesn't have a definition.\n */\n/**\n * Find custom field definitions applicable to a specific model type instance\n *\n * Returns definitions that either:\n * 1. Have NO mappings (apply to all instances of this model type)\n * 2. Have a mapping to this specific model type instance\n */\nexport const findByModelTypeId = async (\n modelTypeId: string,\n options: Pick<SadotFindOptions, 'withDisabled' | 'transaction'> & { entityIds?: string[]; modelType: string; modelOptions?: ModelOptions; } = { withDisabled: false, modelType: '' },\n): Promise<CustomFieldDefinition[]> => {\n const { withDisabled, entityIds, modelType, modelOptions } = options;\n\n const { include, useEntityIdFromInclude } = modelOptions ?? {};\n\n const baseWhere: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && entityIds && entityIds.length > 0 && { entityId: { [Op.in]: entityIds } }),\n };\n\n const queryModel = withDisabled\n ? (CustomFieldDefinition as any).unscoped()\n : CustomFieldDefinition;\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n const includeArray: any[] = [];\n\n // Only include the association if it exists\n if (includeModelTypeMappings) {\n includeArray.push({\n association: 'modelTypeMappings',\n required: false,\n attributes: ['id', 'modelTypeId'],\n });\n }\n\n if (useEntityIdFromInclude && include && entityIds) {\n const contextIncludes = include(entityIds);\n includeArray.push(...contextIncludes);\n }\n\n const definitions = await queryModel.scope('userScope').findAll({\n where: baseWhere,\n include: includeArray.length > 0 ? includeArray : undefined,\n raw: false,\n transaction: options.transaction,\n });\n\n // Only filter by modelTypeId if the association exists\n const filteredDefinitions = includeModelTypeMappings ? definitions.filter((def: CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n }) => {\n const mappings = def.modelTypeMappings ?? def.dataValues?.modelTypeMappings ?? [];\n\n if (!Array.isArray(mappings) || mappings.length === 0) {\n return true;\n }\n\n const hasMatch = mappings.some((mapping: MappingData) => {\n const mappingTypeId = mapping.modelTypeId ?? mapping.dataValues?.modelTypeId;\n return mappingTypeId === modelTypeId;\n });\n\n return hasMatch;\n }) : definitions;\n\n // Use association data to extract modelTypeIds if the association exists\n if (includeModelTypeMappings) {\n return filteredDefinitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return filteredDefinitions as (CustomFieldDefinition & { modelTypeIds?: string[]; })[];\n};\n\nexport const getCustomFieldDefinitionsDictionary = async (\n instances: CustomFieldEntries[],\n {\n findAll: _findAll,\n modelOptions = {},\n withDisabled = false,\n ...options\n }: SadotGetDefinitionsByEntityIdsOptions = { withDisabled: false, modelOptions: {} },\n): Promise<Record<string, CustomFieldDefinition>> => {\n const { modelType } = instances[0]?.dataValues ?? {};\n const customFields = new Set<string>();\n const modelIds = [];\n const entityIds = new Set<string>();\n instances.forEach((instance) => {\n const { dataValues: { modelId, entityId, customFields: instanceCustomFields } } = instance;\n modelIds.push(modelId);\n entityIds.add(entityId);\n\n Object.keys(instanceCustomFields ?? {}).forEach((fieldName) => {\n customFields.add(fieldName);\n });\n });\n\n const where: WhereOptions = {\n modelType,\n entityId: { [Op.in]: Array.from(entityIds) },\n name: { [Op.in]: Array.from(customFields) },\n };\n\n const findAllToUse = _findAll ?? findAll;\n\n // @ts-expect-error findAll doesn't expect modelOptions at all.\n const definitions = await findAllToUse(where, { withDisabled, modelOptions, ...options });\n\n const matchedDefinitions = definitions.filter(def => customFields.has(def.name));\n const matchedDefinitionsByName = Object.fromEntries(matchedDefinitions.map(definition => [definition.name, definition]));\n\n if (!definitions?.length || matchedDefinitions.length !== customFields.size) {\n const unmatchedCustomFields = Array.from(customFields).filter(customField => !matchedDefinitionsByName[customField]);\n throw new MissingDefinitionError(unmatchedCustomFields);\n }\n\n return matchedDefinitionsByName;\n};\n"],"mappings":"4NAuBA,MAAM,MACJ,sBAAwBA,EAAsB,cAAgB,EAAE,EAM5D,EAAmC,GACnC,CAAC,GAAY,CAAC,MAAM,QAAQ,EAAS,CAChC,EAAE,CAGJ,EACJ,IAAK,GAAmB,EAAE,aAAe,EAAE,YAAY,YAAY,CACnE,OAAO,GAAM,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Includeable[] | undefined","modelTypeMappingsInclude: Includeable","logger","where: WhereOptions","baseWhere: WhereOptions","includeArray: any[]"],"sources":["../../src/repository/definition.ts"],"sourcesContent":["import {\n Op,\n type Includeable, type Transaction, type FindOptions, type WhereOptions, type Transactionable,\n} from 'sequelize';\nimport { CustomFieldDefinition, CustomFieldModelTypeMap, type CustomFieldEntries } from '../models';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';\nimport type { ModelOptions } from '../types';\nimport { MissingDefinitionError } from '../errors';\nimport logger from '../utils/logger';\n\n/**\n * Interface for mapping association data (can be raw or Sequelize model instance)\n */\ninterface MappingData {\n modelTypeId?: string;\n dataValues?: {\n modelTypeId?: string;\n };\n}\n\n/**\n * Check if the modelTypeMappings association exists on CustomFieldDefinition\n * The association is only created when useModelTypeMapping: true is passed to initTables\n */\nconst hasModelTypeMappingsAssociation = (): boolean =>\n 'modelTypeMappings' in (CustomFieldDefinition.associations || {});\n\n/**\n * Helper to extract modelTypeIds from the modelTypeMappings association data\n * Handles both raw and non-raw Sequelize results\n */\nconst extractModelTypeIdsFromMappings = (mappings: MappingData[]): string[] => {\n if (!mappings || !Array.isArray(mappings)) {\n return [];\n }\n\n return mappings\n .map((m: MappingData) => m.modelTypeId || m.dataValues?.modelTypeId)\n .filter(id => Boolean(id)) as string[];\n};\n\n/**\n * Helper to extract modelTypeIds from a definition with loaded association\n * Handles the common pattern of getting mappings from a definition\n */\nconst enrichDefinitionWithModelTypeIds = (\n definition: CustomFieldDefinition,\n): CustomFieldDefinition & { modelTypeIds?: string[]; } => {\n const defWithMappings = definition as CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n };\n const mappings = defWithMappings.modelTypeMappings ?? defWithMappings.dataValues?.modelTypeMappings;\n definition.modelTypeIds = extractModelTypeIdsFromMappings(mappings);\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const create = async (\n data: CreateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const customFieldDefinition = await CustomFieldDefinition.create(definitionData as any, {\n transaction,\n });\n\n if (modelTypeIds?.length) {\n await CustomFieldModelTypeMap.bulkCreate(\n modelTypeIds.map(modelTypeId => ({\n customFieldDefinitionId: customFieldDefinition.id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n return customFieldDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\ninterface SadotFindOptions {\n withDisabled?: boolean;\n transaction?: Transaction | null;\n include?: Includeable | Includeable[];\n enrichWithModelTypeIds?: boolean;\n}\n\ntype SadotGetDefinitionsByEntityIdsOptions = FindOptions & { modelOptions?: ModelOptions; findAll?: typeof findAll; } & Pick<SadotFindOptions, 'withDisabled'>;\n\nexport const findAll = async (\n where: WhereOptions,\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => {\n const queryModel = options.withDisabled\n ? CustomFieldDefinition.unscoped()\n : CustomFieldDefinition;\n\n // Build include array - ensure we maintain the type compatibility\n let includeToUse: Includeable | Includeable[] | undefined = options.include;\n\n // If enrichWithModelTypeIds is requested and the association exists, include it to avoid N+1 queries\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n const modelTypeMappingsInclude: Includeable = {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n };\n\n if (options.include) {\n // Combine existing includes with modelTypeMappings\n includeToUse = Array.isArray(options.include)\n ? [...options.include, modelTypeMappingsInclude]\n : [options.include, modelTypeMappingsInclude];\n } else {\n includeToUse = modelTypeMappingsInclude;\n }\n }\n\n logger.info('[SADOT] where', { where });\n\n const definitions = await queryModel.scope('userScope').findAll({\n where,\n transaction: options.transaction,\n raw: !options.enrichWithModelTypeIds,\n logging: (query) => logger.info('QUERY CFD', query),\n include: includeToUse,\n });\n\n if (options.enrichWithModelTypeIds && hasModelTypeMappingsAssociation()) {\n // Extract modelTypeIds from the included association data instead of making N queries\n return definitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return definitions;\n};\n\nexport const findByIds = (\n ids: string[],\n options: SadotFindOptions = { withDisabled: false },\n): Promise<CustomFieldDefinition[]> => findAll({ id: { [Op.in]: ids } }, options);\n\nexport const findById = async (\n id: string,\n options: Pick<SadotFindOptions, 'withDisabled'> = { withDisabled: false },\n): Promise<CustomFieldDefinition | null> => {\n const { withDisabled } = options;\n\n const queryModel = withDisabled\n ? CustomFieldDefinition.unscoped().scope('userScope')\n : CustomFieldDefinition.scope('userScope');\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n\n const definition = await queryModel.findByPk(id, {\n include: includeModelTypeMappings ? [\n {\n association: 'modelTypeMappings',\n required: false,\n attributes: ['modelTypeId'],\n },\n ] : undefined,\n });\n\n if (!definition) {\n return null;\n }\n\n // Extract modelTypeIds from the included association data if the association exists\n if (includeModelTypeMappings) {\n return enrichDefinitionWithModelTypeIds(definition);\n }\n\n return definition as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const findByEntityIds = async (\n modelType: string,\n entityIds: string[],\n options: FindOptions & { modelOptions?: ModelOptions; } = {},\n): Promise<CustomFieldDefinition[]> => {\n const { include, useEntityIdFromInclude } = options.modelOptions!;\n const where: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n return CustomFieldDefinition.findAll({\n where,\n transaction: options.transaction,\n include: include?.(entityIds),\n raw: true,\n });\n};\n\nexport const findByWhere = (where: WhereOptions<CustomFieldDefinition>): Promise<CustomFieldDefinition | null> =>\n CustomFieldDefinition.scope('userScope').findOne({\n where,\n });\n\nexport const findDefinitionsByModels = async (\n modelTypes: string[],\n options?: Transactionable,\n): Promise<CustomFieldDefinition[]> => {\n const query: WhereOptions<CreateCustomFieldDefinition> = { modelType: { [Op.in]: modelTypes } };\n return CustomFieldDefinition.findAll({\n where: query,\n transaction: options?.transaction,\n });\n};\n\nexport const update = async (\n id: string,\n data: UpdateCustomFieldDefinition,\n): Promise<CustomFieldDefinition> => {\n const { modelTypeIds, ...definitionData } = data;\n\n const result = await CustomFieldDefinition.sequelize!.transaction(async (transaction: Transaction) => {\n const updatedDefinition = (await CustomFieldDefinition.scope('userScope').update(definitionData, {\n where: { id },\n returning: true,\n individualHooks: true,\n transaction,\n }))[1][0];\n\n if (modelTypeIds) {\n const existingMappings = await CustomFieldModelTypeMap.findAll({\n where: { customFieldDefinitionId: id },\n attributes: ['id', 'modelTypeId'],\n raw: true,\n transaction,\n });\n\n const existingTypeIds = existingMappings.map(m => m.modelTypeId);\n\n const toAdd = modelTypeIds.filter(typeId => !existingTypeIds.includes(typeId));\n const toRemove = existingMappings.filter(m => !modelTypeIds.includes(m.modelTypeId));\n\n // Check if there are any mapping changes\n const hasMappingChanges = toRemove.length > 0 || toAdd.length > 0;\n\n if (toRemove.length > 0) {\n await CustomFieldModelTypeMap.destroy({\n where: {\n id: toRemove.map(m => m.id),\n },\n transaction,\n });\n }\n\n if (toAdd.length > 0) {\n await CustomFieldModelTypeMap.bulkCreate(\n toAdd.map(modelTypeId => ({\n customFieldDefinitionId: id,\n modelTypeId,\n })),\n { transaction },\n );\n }\n\n // Touch the definition to update its updatedAt timestamp after mapping changes\n if (hasMappingChanges) {\n updatedDefinition.changed('updatedAt', true);\n await updatedDefinition.save({ transaction });\n }\n }\n\n return updatedDefinition;\n });\n\n result.modelTypeIds = modelTypeIds ?? [];\n\n return result as CustomFieldDefinition & { modelTypeIds?: string[]; };\n};\n\nexport const disable = (id: string): Promise<[affectedCount: number]> =>\n CustomFieldDefinition.update(\n { disabled: true },\n { where: { id } },\n );\n\nexport const destroy = (id: string): Promise<number> =>\n CustomFieldDefinition.destroy({ where: { id } });\n\n/**\n * Return the names of the required fields for a given model\n */\nexport const getRequiredFields = async (\n modelType: string,\n modelId: string | string[],\n entityId: string | string[],\n modelOptions: ModelOptions = {},\n): Promise<string[]> => {\n const entityIds = Array.isArray(entityId) ? entityId : [entityId];\n const { include, useEntityIdFromInclude } = modelOptions;\n\n const where: WhereOptions = {\n modelType,\n required: true,\n ...(!useEntityIdFromInclude && { entityId: { [Op.in]: entityIds } }),\n };\n\n const requiredFields = await CustomFieldDefinition.findAll({\n where,\n include: include?.(entityIds),\n logging: true,\n });\n const requiredFieldsNames = requiredFields.map(definition => definition.name);\n return [...new Set(requiredFieldsNames)];\n};\n\n/**\n * @returns A promise resolving with a dictionary of custom field definitions by name.\n * @throws A {@link MissingDefinitionError} if any of the custom fields doesn't have a definition.\n */\n/**\n * Find custom field definitions applicable to a specific model type instance\n *\n * Returns definitions that either:\n * 1. Have NO mappings (apply to all instances of this model type)\n * 2. Have a mapping to this specific model type instance\n */\nexport const findByModelTypeId = async (\n modelTypeId: string,\n options: Pick<SadotFindOptions, 'withDisabled' | 'transaction'> & { entityIds?: string[]; modelType: string; modelOptions?: ModelOptions; } = { withDisabled: false, modelType: '' },\n): Promise<CustomFieldDefinition[]> => {\n const { withDisabled, entityIds, modelType, modelOptions } = options;\n\n const { include, useEntityIdFromInclude } = modelOptions ?? {};\n\n const baseWhere: WhereOptions = {\n modelType,\n ...(!useEntityIdFromInclude && entityIds && entityIds.length > 0 && { entityId: { [Op.in]: entityIds } }),\n };\n\n const queryModel = withDisabled\n ? (CustomFieldDefinition as any).unscoped()\n : CustomFieldDefinition;\n\n const includeModelTypeMappings = hasModelTypeMappingsAssociation();\n const includeArray: any[] = [];\n\n // Only include the association if it exists\n if (includeModelTypeMappings) {\n includeArray.push({\n association: 'modelTypeMappings',\n required: false,\n attributes: ['id', 'modelTypeId'],\n });\n }\n\n if (useEntityIdFromInclude && include && entityIds) {\n const contextIncludes = include(entityIds);\n includeArray.push(...contextIncludes);\n }\n\n const definitions = await queryModel.scope('userScope').findAll({\n where: baseWhere,\n include: includeArray.length > 0 ? includeArray : undefined,\n raw: false,\n transaction: options.transaction,\n });\n\n // Only filter by modelTypeId if the association exists\n const filteredDefinitions = includeModelTypeMappings ? definitions.filter((def: CustomFieldDefinition & {\n modelTypeMappings?: MappingData[];\n dataValues?: { modelTypeMappings?: MappingData[]; };\n }) => {\n const mappings = def.modelTypeMappings ?? def.dataValues?.modelTypeMappings ?? [];\n\n if (!Array.isArray(mappings) || mappings.length === 0) {\n return true;\n }\n\n const hasMatch = mappings.some((mapping: MappingData) => {\n const mappingTypeId = mapping.modelTypeId ?? mapping.dataValues?.modelTypeId;\n return mappingTypeId === modelTypeId;\n });\n\n return hasMatch;\n }) : definitions;\n\n // Use association data to extract modelTypeIds if the association exists\n if (includeModelTypeMappings) {\n return filteredDefinitions.map(enrichDefinitionWithModelTypeIds);\n }\n\n return filteredDefinitions as (CustomFieldDefinition & { modelTypeIds?: string[]; })[];\n};\n\nexport const getCustomFieldDefinitionsDictionary = async (\n instances: CustomFieldEntries[],\n {\n findAll: _findAll,\n modelOptions = {},\n withDisabled = false,\n ...options\n }: SadotGetDefinitionsByEntityIdsOptions = { withDisabled: false, modelOptions: {} },\n): Promise<Record<string, CustomFieldDefinition>> => {\n const { modelType } = instances[0]?.dataValues ?? {};\n const customFields = new Set<string>();\n const modelIds = [];\n const entityIds = new Set<string>();\n instances.forEach((instance) => {\n const { dataValues: { modelId, entityId, customFields: instanceCustomFields } } = instance;\n modelIds.push(modelId);\n entityIds.add(entityId);\n\n Object.keys(instanceCustomFields ?? {}).forEach((fieldName) => {\n customFields.add(fieldName);\n });\n });\n\n const where: WhereOptions = {\n modelType,\n entityId: { [Op.in]: Array.from(entityIds) },\n name: { [Op.in]: Array.from(customFields) },\n };\n\n const findAllToUse = _findAll ?? findAll;\n\n // @ts-expect-error findAll doesn't expect modelOptions at all.\n const definitions = await findAllToUse(where, { withDisabled, modelOptions, ...options });\n\n const matchedDefinitions = definitions.filter(def => customFields.has(def.name));\n const matchedDefinitionsByName = Object.fromEntries(matchedDefinitions.map(definition => [definition.name, definition]));\n\n if (!definitions?.length || matchedDefinitions.length !== customFields.size) {\n const unmatchedCustomFields = Array.from(customFields).filter(customField => !matchedDefinitionsByName[customField]);\n throw new MissingDefinitionError(unmatchedCustomFields);\n }\n\n return matchedDefinitionsByName;\n};\n"],"mappings":"oQAwBA,MAAM,MACJ,sBAAwBA,EAAsB,cAAgB,EAAE,EAM5D,EAAmC,GACnC,CAAC,GAAY,CAAC,MAAM,QAAQ,EAAS,CAChC,EAAE,CAGJ,EACJ,IAAK,GAAmB,EAAE,aAAe,EAAE,YAAY,YAAY,CACnE,OAAO,GAAM,EAAQ,EAAI,CAOxB,EACJ,GACyD,CACzD,IAAM,EAAkB,EAMxB,MADA,GAAW,aAAe,EADT,EAAgB,mBAAqB,EAAgB,YAAY,kBACf,CAC5D,GAGI,EAAS,KACpB,IACmC,CACnC,GAAM,CAAE,eAAc,GAAG,GAAmB,EAEtC,EAAS,MAAMA,EAAsB,UAAW,YAAY,KAAO,IAA6B,CACpG,IAAM,EAAwB,MAAMA,EAAsB,OAAO,EAAuB,CACtF,cACD,CAAC,CAYF,OAVI,GAAc,QAChB,MAAMC,EAAwB,WAC5B,EAAa,IAAI,IAAgB,CAC/B,wBAAyB,EAAsB,GAC/C,cACD,EAAE,CACH,CAAE,cAAa,CAChB,CAGI,GACP,CAIF,MAFA,GAAO,aAAe,GAAgB,EAAE,CAEjC,GAYI,EAAU,MACrB,EACA,EAA4B,CAAE,aAAc,GAAO,GACd,CACrC,IAAM,EAAa,EAAQ,aACvBD,EAAsB,UAAU,CAChCA,EAGAE,EAAwD,EAAQ,QAGpE,GAAI,EAAQ,wBAA0B,GAAiC,CAAE,CACvE,IAAMC,EAAwC,CAC5C,YAAa,oBACb,SAAU,GACV,WAAY,CAAC,cAAc,CAC5B,CAED,AAME,EANE,EAAQ,QAEK,MAAM,QAAQ,EAAQ,QAAQ,CACzC,CAAC,GAAG,EAAQ,QAAS,EAAyB,CAC9C,CAAC,EAAQ,QAAS,EA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AK,EAAa,CAAE,CAC5C,CAKK,EAAc,MAHC,GAAY,GAGM,EAAO,CAAE,eAAc,eAAc,GAAG,EAAS,CAAC,CAEnF,EAAqB,EAAY,OAAO,GAAO,EAAa,IAAI,EAAI,KAAK,CAAC,CAC1E,EAA2B,OAAO,YAAY,EAAmB,IAAI,GAAc,CAAC,EAAW,KAAM,EAAW,CAAC,CAAC,CAExH,GAAI,CAAC,GAAa,QAAU,EAAmB,SAAW,EAAa,KAErE,MAAM,IAAI,EADoB,MAAM,KAAK,EAAa,CAAC,OAAO,GAAe,CAAC,EAAyB,GAAa,CAC7D,CAGzD,OAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autofleet/sadot",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.9-beta.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -46,17 +46,17 @@
|
|
|
46
46
|
"sequelize": "^6.37.7",
|
|
47
47
|
"sequelize-typescript": "^2.1.6",
|
|
48
48
|
"umzug": "^3.8.3",
|
|
49
|
-
"@autofleet/events": "^5.3.
|
|
49
|
+
"@autofleet/events": "^5.3.18"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@types/express": "^4.17.17",
|
|
53
53
|
"express": "^4.21.2",
|
|
54
54
|
"npm-watch": "^0.11.0",
|
|
55
55
|
"supertest": "^7.0.0",
|
|
56
|
-
"@autofleet/
|
|
57
|
-
"@autofleet/
|
|
58
|
-
"@autofleet/
|
|
59
|
-
"@autofleet/zehut": "^4.12.
|
|
56
|
+
"@autofleet/logger": "^4.5.6",
|
|
57
|
+
"@autofleet/errors": "^3.3.2",
|
|
58
|
+
"@autofleet/node-common": "^4.3.18",
|
|
59
|
+
"@autofleet/zehut": "^4.12.14"
|
|
60
60
|
},
|
|
61
61
|
"peerDependencies": {
|
|
62
62
|
"@autofleet/errors": "^3",
|