@autofleet/sadot 1.4.26 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/api/v1/definition/index.cjs +1 -1
  2. package/dist/api/v1/definition/index.cjs.map +1 -1
  3. package/dist/api/v1/definition/index.js +1 -1
  4. package/dist/api/v1/definition/index.js.map +1 -1
  5. package/dist/api/v1/definition/validations.cjs +1 -1
  6. package/dist/api/v1/definition/validations.cjs.map +1 -1
  7. package/dist/api/v1/definition/validations.js +1 -1
  8. package/dist/api/v1/definition/validations.js.map +1 -1
  9. package/dist/hooks/enrich.cjs +1 -1
  10. package/dist/hooks/enrich.cjs.map +1 -1
  11. package/dist/hooks/enrich.js +1 -1
  12. package/dist/hooks/enrich.js.map +1 -1
  13. package/dist/hooks/hooks.cjs +1 -1
  14. package/dist/hooks/hooks.cjs.map +1 -1
  15. package/dist/hooks/hooks.js +1 -1
  16. package/dist/hooks/hooks.js.map +1 -1
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/mat-path-state.cjs +2 -0
  22. package/dist/mat-path-state.cjs.map +1 -0
  23. package/dist/mat-path-state.js +2 -0
  24. package/dist/mat-path-state.js.map +1 -0
  25. package/dist/models/index.cjs +1 -1
  26. package/dist/models/index.cjs.map +1 -1
  27. package/dist/models/index.js +1 -1
  28. package/dist/models/index.js.map +1 -1
  29. package/dist/types/index.d.cts +7 -0
  30. package/dist/types/index.d.ts +7 -0
  31. package/dist/utils/constants/index.cjs +1 -1
  32. package/dist/utils/constants/index.cjs.map +1 -1
  33. package/dist/utils/constants/index.d.cts +2 -0
  34. package/dist/utils/constants/index.d.ts +2 -0
  35. package/dist/utils/constants/index.js +1 -1
  36. package/dist/utils/constants/index.js.map +1 -1
  37. package/dist/utils/validations/validators/index.cjs +1 -1
  38. package/dist/utils/validations/validators/index.cjs.map +1 -1
  39. package/dist/utils/validations/validators/index.js +1 -1
  40. package/dist/utils/validations/validators/index.js.map +1 -1
  41. package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs +2 -0
  42. package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs.map +1 -0
  43. package/dist/utils/validations/validators/multi-select-dropdown.validator.js +2 -0
  44. package/dist/utils/validations/validators/multi-select-dropdown.validator.js.map +1 -0
  45. package/dist/utils/validations/validators/multi-select-status.validator.cjs +2 -0
  46. package/dist/utils/validations/validators/multi-select-status.validator.cjs.map +1 -0
  47. package/dist/utils/validations/validators/multi-select-status.validator.js +2 -0
  48. package/dist/utils/validations/validators/multi-select-status.validator.js.map +1 -0
  49. package/dist/utils/validations/validators/multi-select.helpers.cjs +2 -0
  50. package/dist/utils/validations/validators/multi-select.helpers.cjs.map +1 -0
  51. package/dist/utils/validations/validators/multi-select.helpers.js +2 -0
  52. package/dist/utils/validations/validators/multi-select.helpers.js.map +1 -0
  53. package/dist/utils/validations/validators/status.validator.cjs.map +1 -1
  54. package/dist/utils/validations/validators/status.validator.js.map +1 -1
  55. package/package.json +1 -1
@@ -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`);let a=require(`@autofleet/errors`),o=require(`@autofleet/node-common`);const s=(0,o.Router)({logger:t.default}),c=`CustomFieldDefinition`,l=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());s.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=l(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 ${c} request`})}}),s.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:o}=e.params;try{let e=await n.findById(o);if(!e)throw new a.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 ${c} request`})}}),s.get(`/`,async(e,i)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:s}}=e,u=l(a);try{if(s){let e=await n.findByModelTypeId(s,{withDisabled:!0,modelType:u,entityIds:o});return i.json(e)}let e={modelType:u,...o&&o.length>0&&{entityId:o}},t=await n.findAll(e,{withDisabled:!0,enrichWithModelTypeIds:!0});return i.json(t)}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 ${c} request`})}}),s.patch(`/:customFieldDefinitionId`,async(e,o)=>{let{customFieldDefinitionId:s,modelName:u}=e.params,d=l(u);try{let t=await i.validateCustomFieldDefinitionUpdate(e.body);if(!await n.findByWhere({id:s,modelType:d}))throw new a.ResourceNotFoundError;let r=await n.update(s,{...t,modelType:d});return o.status(200).json(r)}catch(e){return t.default.error(`Failed to patch custom field definition`,e),r.default(e,o,{logger:t.default,message:`Error in update ${c} request`})}});var u=s;exports.default=u;
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 t={modelType:d,...e&&{entityId:s}},r=await n.findAll(t,{withDisabled:!0,enrichWithModelTypeIds:!0});return i.json(r)}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","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';\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 // 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,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { 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":"wRASA,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,CA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C,CAGA,MAAM,IAAIH,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
+ {"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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Z,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{ResourceNotFoundError as u}from"@autofleet/errors";import{Router as d}from"@autofleet/node-common";const f=d({logger:e}),p=`CustomFieldDefinition`,m=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());f.post(`/`,async(n,r)=>{let{modelName:i}=n.params,a=m(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 ${p} request`})}}),f.get(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:i}=t.params;try{let e=await r(i);if(!e)throw new u;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 ${p} request`})}}),f.get(`/`,async(t,r)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:c}}=t,l=m(a);try{if(c){let e=await i(c,{withDisabled:!0,modelType:l,entityIds:o});return r.json(e)}let e=await n({modelType:l,...o&&o.length>0&&{entityId:o}},{withDisabled:!0,enrichWithModelTypeIds:!0});return r.json(e)}catch(t){return e.error(`Failed to fetch custom field definitions`,t),s(t,r,{logger:e,message:`Error in get all ${p} request`})}}),f.patch(`/:customFieldDefinitionId`,async(t,n)=>{let{customFieldDefinitionId:r,modelName:i}=t.params,c=m(i);try{let e=await l(t.body);if(!await a({id:r,modelType:c}))throw new u;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 ${p} request`})}});var h=f;export{h as default};
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 e=!u.isMatPathEnabled?.()&&o&&o.length>0;if(c){let t=await i(c,{withDisabled:!0,modelType:l,entityIds:e?o:void 0});return r.json(t)}let t=await n({modelType:l,...e&&{entityId:o}},{withDisabled:!0,enrichWithModelTypeIds:!0});return r.json(t)}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';\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 // 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,\n });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { 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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AJvB,CACZ,YACA,GAAI,GAAa,EAAU,OAAS,GAAK,CAAE,SAAU,EAAW,CACjE,CACkE,CAAE,aAAc,GAAM,uBAAwB,GAAM,CAAC,CACxH,OAAO,EAAI,KAAK,EAAuB,OAChC,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDJ,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,MAAsF,4BAA6B,MAAO,EAAK,IAAQ,CAC5I,GAAM,CAAE,0BAAyB,aAAc,EAAI,OAC7C,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMK,EAAgD,MAAM,EAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAMC,EAA2B,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAI,EAGZ,IAAM,EAA+B,MAAMC,EACzC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDP,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
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,CAA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DJ,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,MAAsF,4BAA6B,MAAO,EAAK,IAAQ,CAC5I,GAAM,CAAE,0BAAyB,aAAc,EAAI,OAC7C,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMK,EAAgD,MAAM,EAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAMC,EAA2B,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAI,EAGZ,IAAM,EAA+B,MAAMC,EACzC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDP,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
@@ -1,2 +1,2 @@
1
- const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/constants/index.cjs`);let n=require(`joi`);n=e.__toESM(n);const r=n.default.object({name:n.default.string().required(),type:n.default.string(),size:n.default.string(),addedBy:n.default.string().uuid()}),i=n.default.object({value:n.default.string().required(),color:n.default.string().required()}),a=n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.SELECT,then:n.default.array().required().items(n.default.string()).min(1).unique(),otherwise:n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.STATUS,then:n.default.array().required().items(i).min(1).unique(`value`),otherwise:n.default.forbidden()})}),o=n.default.when(`fieldType`,{switch:[{is:t.CustomFieldDefinitionType.BOOLEAN,then:n.default.boolean().allow(null)},{is:t.CustomFieldDefinitionType.DATE,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.DATETIME,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.FILE,then:n.default.array().items(r).allow(null)},{is:t.CustomFieldDefinitionType.IMAGE,then:n.default.array().items(n.default.string().uri()).allow(null)},{is:t.CustomFieldDefinitionType.NUMBER,then:n.default.number().allow(null)},{is:t.CustomFieldDefinitionType.SELECT,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.STATUS,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.TEXT,then:n.default.string().allow(null)}]}),s=n.default.object({name:n.default.string().required(),displayName:n.default.string().required(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)).required(),entityId:n.default.string().guid().required(),entityType:n.default.string().required(),description:n.default.string(),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),c=n.default.object({displayName:n.default.string(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)),description:n.default.string().allow(null),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),l=e=>s.validateAsync(e,{abortEarly:!1}),u=e=>c.validateAsync(e,{abortEarly:!1});exports.validateCustomFieldDefinitionCreation=l,exports.validateCustomFieldDefinitionUpdate=u;
1
+ const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/constants/index.cjs`);let n=require(`joi`);n=e.__toESM(n);const r=n.default.object({name:n.default.string().required(),type:n.default.string(),size:n.default.string(),addedBy:n.default.string().uuid()}),i=n.default.object({value:n.default.string().required(),color:n.default.string().required()}),a=n.default.array().required().items(n.default.string()).min(1).unique(),o=n.default.array().required().items(i).min(1).unique(`value`),s=n.default.when(`fieldType`,{switch:[{is:t.CustomFieldDefinitionType.SELECT,then:a},{is:t.CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN,then:a},{is:t.CustomFieldDefinitionType.STATUS,then:o},{is:t.CustomFieldDefinitionType.MULTI_SELECT_STATUS,then:o}],otherwise:n.default.forbidden()}),c=n.default.array().items(n.default.string()).unique().allow(null),l=n.default.when(`fieldType`,{switch:[{is:t.CustomFieldDefinitionType.BOOLEAN,then:n.default.boolean().allow(null)},{is:t.CustomFieldDefinitionType.DATE,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.DATETIME,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.FILE,then:n.default.array().items(r).allow(null)},{is:t.CustomFieldDefinitionType.IMAGE,then:n.default.array().items(n.default.string().uri()).allow(null)},{is:t.CustomFieldDefinitionType.NUMBER,then:n.default.number().allow(null)},{is:t.CustomFieldDefinitionType.SELECT,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.STATUS,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.TEXT,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.MULTI_SELECT_STATUS,then:c},{is:t.CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN,then:c}]}),u=n.default.object({name:n.default.string().required(),displayName:n.default.string().required(),validation:s,defaultValue:l,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)).required(),entityId:n.default.string().guid().required(),entityType:n.default.string().required(),description:n.default.string(),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),d=n.default.object({displayName:n.default.string(),validation:s,defaultValue:l,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)),description:n.default.string().allow(null),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),f=e=>u.validateAsync(e,{abortEarly:!1}),p=e=>d.validateAsync(e,{abortEarly:!1});exports.validateCustomFieldDefinitionCreation=f,exports.validateCustomFieldDefinitionUpdate=p;
2
2
  //# sourceMappingURL=validations.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"validations.cjs","names":["Joi","CustomFieldDefinitionType"],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"8IAIA,MAAM,EAAuBA,EAAAA,QAAI,OAAO,CACtC,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyBA,EAAAA,QAAI,OAAO,CACxC,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC9B,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmBA,EAAAA,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AAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
1
+ {"version":3,"file":"validations.cjs","names":["Joi","CustomFieldDefinitionType"],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n\nconst stringOptionsSchema = Joi.array().required().items(Joi.string()).min(1)\n .unique();\nconst statusOptionsSchema = Joi.array().required().items(statusValidationObject).min(1)\n .unique('value');\n\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT},\n * {@link CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN MULTI_SELECT_DROPDOWN},\n * {@link CustomFieldDefinitionType.STATUS STATUS},\n * and\n * {@link CustomFieldDefinitionType.MULTI_SELECT_STATUS MULTI_SELECT_STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.SELECT, then: stringOptionsSchema },\n { is: CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN, then: stringOptionsSchema },\n { is: CustomFieldDefinitionType.STATUS, then: statusOptionsSchema },\n { is: CustomFieldDefinitionType.MULTI_SELECT_STATUS, then: statusOptionsSchema },\n ],\n otherwise: Joi.forbidden(),\n});\n\nconst multiSelectDefaultValueSchema = Joi.array().items(Joi.string()).unique().allow(null);\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.MULTI_SELECT_STATUS, then: multiSelectDefaultValueSchema },\n { is: CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN, then: multiSelectDefaultValueSchema },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"8IAIA,MAAM,EAAuBA,EAAAA,QAAI,OAAO,CACtC,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyBA,EAAAA,QAAI,OAAO,CACxC,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC9B,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAEI,EAAsBA,EAAAA,QAAI,OAAO,CAAC,UAAU,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,CAAC,IAAI,EAAE,CAC1E,QAAQ,CACL,EAAsBA,EAAAA,QAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAuB,CAAC,IAAI,EAAE,CACpF,OAAO,QAAQ,CAaZ,EAAmBA,EAAAA,QAAI,KAAK,YAAa,CAC7C,OAAQ,CACN,CAAE,GAAIC,EAAAA,0BAA0B,OAAQ,KAAM,EAAqB,CACnE,CAAE,GAAIA,EAAAA,0BAA0B,sBAAuB,KAAM,EAAqB,CAClF,CAAE,GAAIA,EAAAA,0BAA0B,OAAQ,KAAM,EAAqB,CACnE,CAAE,GAAIA,EAAAA,0BAA0B,oBAAqB,KAAM,EAAqB,CACjF,CACD,UAAWD,EAAAA,QAAI,WAAW,CAC3B,CAAC,CAEI,EAAgCA,EAAAA,QAAI,OAAO,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,CAAC,QAAQ,CAAC,MAAM,KAAK,CAEpF,EAAqBA,EAAAA,QAAI,KAAK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QAAQ,CAAC,MAAM,GAAG,OAAO,OAAOC,EAAAA,0BAA0B,CAAC,CAAC,UAAU,CACrF,SAAUD,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAYA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CACnC,YAAaA,EAAAA,QAAI,QAAQ,CACzB,SAAUA,EAAAA,QAAI,SAAS,CACvB,SAAUA,EAAAA,QAAI,SAAS,CACvB,mBAAoBA,EAAAA,QAAI,SAAS,CACjC,aAAcA,EAAAA,QAAI,OAAO,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAAC,CACrD,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAE3E,EAAoCA,EAAAA,QAAI,OAAO,CACnD,YAAaA,EAAAA,QAAI,QAAQ,CACzB,WAAY,EACZ,aAAc,EACd,UAAWA,EAAAA,QAAI,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAOC,EAAAA,0BAA0B,CAAC,CAC1E,YAAaD,EAAAA,QAAI,QAAQ,CAAC,MAAM,KAAK,CACrC,SAAUA,EAAAA,QAAI,SAAS,CACvB,SAAUA,EAAAA,QAAI,SAAS,CACvB,mBAAoBA,EAAAA,QAAI,SAAS,CACjC,aAAcA,EAAAA,QAAI,OAAO,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAAC,CACrD,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
@@ -1,2 +1,2 @@
1
- import{CustomFieldDefinitionType as e}from"../../../utils/constants/index.js";import t from"joi";const n=t.object({name:t.string().required(),type:t.string(),size:t.string(),addedBy:t.string().uuid()}),r=t.object({value:t.string().required(),color:t.string().required()}),i=t.when(`fieldType`,{is:e.SELECT,then:t.array().required().items(t.string()).min(1).unique(),otherwise:t.when(`fieldType`,{is:e.STATUS,then:t.array().required().items(r).min(1).unique(`value`),otherwise:t.forbidden()})}),a=t.when(`fieldType`,{switch:[{is:e.BOOLEAN,then:t.boolean().allow(null)},{is:e.DATE,then:t.date().allow(null)},{is:e.DATETIME,then:t.date().allow(null)},{is:e.FILE,then:t.array().items(n).allow(null)},{is:e.IMAGE,then:t.array().items(t.string().uri()).allow(null)},{is:e.NUMBER,then:t.number().allow(null)},{is:e.SELECT,then:t.string().allow(null)},{is:e.STATUS,then:t.string().allow(null)},{is:e.TEXT,then:t.string().allow(null)}]}),o=t.object({name:t.string().required(),displayName:t.string().required(),validation:i,defaultValue:a,fieldType:t.string().valid(...Object.values(e)).required(),entityId:t.string().guid().required(),entityType:t.string().required(),description:t.string(),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean(),modelTypeIds:t.array().items(t.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),s=t.object({displayName:t.string(),validation:i,defaultValue:a,fieldType:t.string().valid(...Object.values(e)),description:t.string().allow(null),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean(),modelTypeIds:t.array().items(t.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),c=e=>o.validateAsync(e,{abortEarly:!1}),l=e=>s.validateAsync(e,{abortEarly:!1});export{c as validateCustomFieldDefinitionCreation,l as validateCustomFieldDefinitionUpdate};
1
+ import{CustomFieldDefinitionType as e}from"../../../utils/constants/index.js";import t from"joi";const n=t.object({name:t.string().required(),type:t.string(),size:t.string(),addedBy:t.string().uuid()}),r=t.object({value:t.string().required(),color:t.string().required()}),i=t.array().required().items(t.string()).min(1).unique(),a=t.array().required().items(r).min(1).unique(`value`),o=t.when(`fieldType`,{switch:[{is:e.SELECT,then:i},{is:e.MULTI_SELECT_DROPDOWN,then:i},{is:e.STATUS,then:a},{is:e.MULTI_SELECT_STATUS,then:a}],otherwise:t.forbidden()}),s=t.array().items(t.string()).unique().allow(null),c=t.when(`fieldType`,{switch:[{is:e.BOOLEAN,then:t.boolean().allow(null)},{is:e.DATE,then:t.date().allow(null)},{is:e.DATETIME,then:t.date().allow(null)},{is:e.FILE,then:t.array().items(n).allow(null)},{is:e.IMAGE,then:t.array().items(t.string().uri()).allow(null)},{is:e.NUMBER,then:t.number().allow(null)},{is:e.SELECT,then:t.string().allow(null)},{is:e.STATUS,then:t.string().allow(null)},{is:e.TEXT,then:t.string().allow(null)},{is:e.MULTI_SELECT_STATUS,then:s},{is:e.MULTI_SELECT_DROPDOWN,then:s}]}),l=t.object({name:t.string().required(),displayName:t.string().required(),validation:o,defaultValue:c,fieldType:t.string().valid(...Object.values(e)).required(),entityId:t.string().guid().required(),entityType:t.string().required(),description:t.string(),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean(),modelTypeIds:t.array().items(t.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),u=t.object({displayName:t.string(),validation:o,defaultValue:c,fieldType:t.string().valid(...Object.values(e)),description:t.string().allow(null),required:t.boolean(),disabled:t.boolean(),blockEditingFromUI:t.boolean(),modelTypeIds:t.array().items(t.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),d=e=>l.validateAsync(e,{abortEarly:!1}),f=e=>u.validateAsync(e,{abortEarly:!1});export{d as validateCustomFieldDefinitionCreation,f as validateCustomFieldDefinitionUpdate};
2
2
  //# sourceMappingURL=validations.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validations.js","names":[],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"iGAIA,MAAM,EAAuB,EAAI,OAAO,CACtC,KAAM,EAAI,QAAQ,CAAC,UAAU,CAC7B,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CAClB,QAAS,EAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyB,EAAI,OAAO,CACxC,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC9B,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmB,EAAI,KAAK,YAAa,CAC7C,GAAI,EAA0B,OAC9B,KAAM,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAI,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC,QAAQ,CAChE,UAAW,EAAI,KAAK,YAAa,CAC/B,GAAI,EAA0B,OAC9B,KAAM,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAuB,CAAC,IAAI,EAAE,CAAC,OAAO,QAAQ,CACjF,UAAW,EAAI,WAAW,CAC3B,CAAC,CACH,CAAC,CAEI,EAAqB,EAAI,KAAK,YAAa,CAC/C,OAAQ,CACN,CAAE,GAAI,E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,UAAW,GAAS,IAAU,GAAM,CAAC,CAE3E,EAAoC,EAAI,OAAO,CACnD,YAAa,EAAI,QAAQ,CACzB,WAAY,EACZ,aAAc,EACd,UAAW,EAAI,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAO,EAA0B,CAAC,CAC1E,YAAa,EAAI,QAAQ,CAAC,MAAM,KAAK,CACrC,SAAU,EAAI,SAAS,CACvB,SAAU,EAAI,SAAS,CACvB,mBAAoB,EAAI,SAAS,CACjC,aAAc,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,MAAM,CAAC,CACrD,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
1
+ {"version":3,"file":"validations.js","names":[],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n\nconst stringOptionsSchema = Joi.array().required().items(Joi.string()).min(1)\n .unique();\nconst statusOptionsSchema = Joi.array().required().items(statusValidationObject).min(1)\n .unique('value');\n\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT},\n * {@link CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN MULTI_SELECT_DROPDOWN},\n * {@link CustomFieldDefinitionType.STATUS STATUS},\n * and\n * {@link CustomFieldDefinitionType.MULTI_SELECT_STATUS MULTI_SELECT_STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.SELECT, then: stringOptionsSchema },\n { is: CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN, then: stringOptionsSchema },\n { is: CustomFieldDefinitionType.STATUS, then: statusOptionsSchema },\n { is: CustomFieldDefinitionType.MULTI_SELECT_STATUS, then: statusOptionsSchema },\n ],\n otherwise: Joi.forbidden(),\n});\n\nconst multiSelectDefaultValueSchema = Joi.array().items(Joi.string()).unique().allow(null);\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.MULTI_SELECT_STATUS, then: multiSelectDefaultValueSchema },\n { is: CustomFieldDefinitionType.MULTI_SELECT_DROPDOWN, then: multiSelectDefaultValueSchema },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"iGAIA,MAAM,EAAuB,EAAI,OAAO,CACtC,KAAM,EAAI,QAAQ,CAAC,UAAU,CAC7B,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CAClB,QAAS,EAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyB,EAAI,OAAO,CACxC,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC9B,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAEI,EAAsB,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAI,QAAQ,CAAC,CAAC,IAAI,EAAE,CAC1E,QAAQ,CACL,EAAsB,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EAAuB,CAAC,IAAI,EAAE,CACpF,OAAO,QAAQ,CAaZ,EAAmB,EAAI,KAAK,YAAa,CAC7C,OAAQ,CACN,CAAE,GAAI,EAA0B,OAAQ,KAAM,EAAqB,CACnE,CAAE,GAAI,EAA0B,sBAAuB,KAAM,EAAqB,CAClF,CAAE,GAAI,EAA0B,OAAQ,KAAM,EAA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,GAAG,OAAO,OAAO,EAA0B,CAAC,CAAC,UAAU,CACrF,SAAU,EAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAY,EAAI,QAAQ,CAAC,UAAU,CACnC,YAAa,EAAI,QAAQ,CACzB,SAAU,EAAI,SAAS,CACvB,SAAU,EAAI,SAAS,CACvB,mBAAoB,EAAI,SAAS,CACjC,aAAc,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,MAAM,CAAC,CACrD,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAE3E,EAAoC,EAAI,OAAO,CACnD,YAAa,EAAI,QAAQ,CACzB,WAAY,EACZ,aAAc,EACd,UAAW,EAAI,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAO,EAA0B,CAAC,CAC1E,YAAa,EAAI,QAAQ,CAAC,MAAM,KAAK,CACrC,SAAU,EAAI,SAAS,CACvB,SAAU,EAAI,SAAS,CACvB,mBAAoB,EAAI,SAAS,CACjC,aAAc,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,MAAM,CAAC,CACrD,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
@@ -1,2 +1,2 @@
1
- const e=require(`../repository/definition.cjs`),t=require(`../repository/value.cjs`),n=require(`../repository/entries.cjs`),r=require(`../utils/scopeAttributes.cjs`),i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n.findEntriesByModelIds(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t.findValuesByModelIds(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{}),c=(t,n,c,l={},u={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r.default(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v));let y;if(!_)if(u.hasTypeId&&p.length>0&&p[0].typeId){let n=[...new Set(p.map(e=>e.typeId).filter(Boolean))];y=new Map,n.forEach(e=>y.set(e,new Set));let r=(await Promise.all(n.map(async n=>{let r=await e.findByModelTypeId(n,{withDisabled:!1,entityIds:h,modelType:t,modelOptions:l,transaction:f.transaction});return r.forEach(e=>y.get(n).add(e.id)),r}))).flat(),i=new Map;r.forEach(e=>{i.set(e.id,e)}),_=Promise.resolve(Array.from(i.values()))}else _=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_);let b=await _;if(b.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{b.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!g[n]&&(g[n]=[])})});let x=b.reduce((e,t)=>({...e,[t.id]:t}),{});b.forEach(e=>{let t=e.entityId;if(l?.useEntityIdFromInclude&&l.include){let n=l.include(m);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}g[t]&&g[t].push(e)});let S=p.map(e=>e.id),[C,w]=await Promise.all([o({instancesIds:S,options:f,sadotOptions:u}),a({instancesIds:S,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=C[t],i=r?s(r,x):{},a=u.useCustomFieldsEntries?w[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(t=>{y&&!y.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};var l=c;exports.default=l;
1
+ const e=require(`../repository/definition.cjs`),t=require(`../repository/value.cjs`),n=require(`../repository/entries.cjs`),r=require(`../utils/scopeAttributes.cjs`),i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n.findEntriesByModelIds(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t.findValuesByModelIds(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{}),c=(t,n,c,l={},u={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r.default(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v));let y;if(!_){let n=u.hasTypeId&&p.length>0&&p[0].typeId;_=(async(r=f.transaction)=>{if(n){let n=[...new Set(p.map(e=>e.typeId).filter(Boolean))];y=new Map,n.forEach(e=>y.set(e,new Set));let i=(await Promise.all(n.map(async n=>{let i=await e.findByModelTypeId(n,{withDisabled:!1,entityIds:h,modelType:t,modelOptions:l,transaction:r});return i.forEach(e=>y.get(n).add(e.id)),i}))).flat(),a=new Map;return i.forEach(e=>{a.set(e.id,e)}),Array.from(a.values())}return e.findByEntityIds(t,h,{transaction:r,modelOptions:l,attributes:i})})(),n||f.transaction?.definitionCache?.set(v,_)}let b=await _;if(b.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{b.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!g[n]&&(g[n]=[])})});let x=b.reduce((e,t)=>({...e,[t.id]:t}),{});b.forEach(e=>{let t=e.entityId;if(l?.useEntityIdFromInclude&&l.include){let n=l.include(m);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}g[t]&&g[t].push(e)});let S=p.map(e=>e.id),[C,w]=await Promise.all([o({instancesIds:S,options:f,sadotOptions:u}),a({instancesIds:S,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=C[t],i=r?s(r,x):{},a=u.useCustomFieldsEntries?w[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(t=>{y&&!y.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};var l=c;exports.default=l;
2
2
  //# sourceMappingURL=enrich.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction)\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction: options.transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"sKAUM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAA,EAAA,sBACzB,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA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I,EAAgB,EAAI,SAExB,GAAI,GAAc,wBAA0B,EAAa,QAAS,CAChE,IAAM,EAAkB,EAAa,QAAQ,EAAY,CACzD,IAAK,GAAM,CAAE,WAAW,EAAiB,CACvC,IAAM,EAAiB,EAAI,EAAO,OAAO,UAAY,EAAI,GAAG,EAAO,KAAK,YACxE,GAAI,EAAgB,CAClB,EAAgB,EAChB,QAKF,EAAwC,IAC1C,EAAwC,GAAe,KAAK,EAAI,EAElE,CAGF,IAAM,EAAe,EAAU,IAAI,GAAK,EAAE,GAAY,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C,EAGJ,IAAA,EAAe"}
1
+ {"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction).\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n const fetchDefinitions = async (transaction = options.transaction) => {\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n return Array.from(uniqueDefinitionsMap.values());\n }\n return DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n };\n\n customFieldDefinitionsPromise = fetchDefinitions();\n\n if (!shouldApplyTypeFiltering) {\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"sKAUM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAA,EAAA,sBACzB,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAA,EAAA,qBACxB,EACA,GAAW,EAAE,CACd,EAGw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AM,CAAE,WAAW,EAAiB,CACvC,IAAM,EAAiB,EAAI,EAAO,OAAO,UAAY,EAAI,GAAG,EAAO,KAAK,YACxE,GAAI,EAAgB,CAClB,EAAgB,EAChB,QAKF,EAAwC,IAC1C,EAAwC,GAAe,KAAK,EAAI,EAElE,CAGF,IAAM,EAAe,EAAU,IAAI,GAAK,EAAE,GAAY,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C,EAGJ,IAAA,EAAe"}
@@ -1,2 +1,2 @@
1
- import{findByEntityIds as e,findByModelTypeId as t}from"../repository/definition.js";import{findValuesByModelIds as n}from"../repository/value.js";import{findEntriesByModelIds as r}from"../repository/entries.js";import i from"../utils/scopeAttributes.js";const a=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],o=async({instancesIds:e,options:t,sadotOptions:n})=>{if(!n.useCustomFieldsEntries)return{};let i=await r(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},s=async({instancesIds:e,options:t,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await n(e,t??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),c=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var l=(n,r,l,u={},d={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(f,p)=>{if(p.originalAttributes?.length>0&&!p.originalAttributes?.includes?.(`customFields`))return;let m=Array.isArray(f)?f:[f];m=m.filter(Boolean);let h=i(m,r),g=[...new Set(h)].filter(Boolean),_=g.reduce((e,t)=>({...e,[t]:[]}),{}),v,y;p.transaction&&(p.transaction.definitionCache??=new Map,y=`${n}:${g.slice().sort().join(`,`)}`,v=p.transaction.definitionCache.get(y));let b;if(!v)if(d.hasTypeId&&m.length>0&&m[0].typeId){let e=[...new Set(m.map(e=>e.typeId).filter(Boolean))];b=new Map,e.forEach(e=>b.set(e,new Set));let r=(await Promise.all(e.map(async e=>{let r=await t(e,{withDisabled:!1,entityIds:g,modelType:n,modelOptions:u,transaction:p.transaction});return r.forEach(t=>b.get(e).add(t.id)),r}))).flat(),i=new Map;r.forEach(e=>{i.set(e.id,e)}),v=Promise.resolve(Array.from(i.values()))}else v=e(n,g,{transaction:p.transaction,modelOptions:u,attributes:a}),p.transaction?.definitionCache?.set(y,v);let x=await v;if(x.length===0){m.forEach(e=>{e.customFields={}});return}u?.include&&u.useEntityIdFromInclude&&u.include(h).forEach(({model:e})=>{x.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!_[n]&&(_[n]=[])})});let S=x.reduce((e,t)=>({...e,[t.id]:t}),{});x.forEach(e=>{let t=e.entityId;if(u?.useEntityIdFromInclude&&u.include){let n=u.include(h);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}_[t]&&_[t].push(e)});let C=m.map(e=>e.id),[w,T]=await Promise.all([s({instancesIds:C,options:p,sadotOptions:d}),o({instancesIds:C,options:p,sadotOptions:d})]);m.forEach(e=>{let{id:t}=e,n=w[t],i=n?c(n,S):{},a=d.useCustomFieldsEntries?T[t]:i;r.forEach(t=>{let n=_[e[t]];n&&n.length>0&&n.forEach(t=>{b&&!b.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,p.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),l===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{l as default};
1
+ import{findByEntityIds as e,findByModelTypeId as t}from"../repository/definition.js";import{findValuesByModelIds as n}from"../repository/value.js";import{findEntriesByModelIds as r}from"../repository/entries.js";import i from"../utils/scopeAttributes.js";const a=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],o=async({instancesIds:e,options:t,sadotOptions:n})=>{if(!n.useCustomFieldsEntries)return{};let i=await r(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},s=async({instancesIds:e,options:t,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await n(e,t??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),c=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var l=(n,r,l,u={},d={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(f,p)=>{if(p.originalAttributes?.length>0&&!p.originalAttributes?.includes?.(`customFields`))return;let m=Array.isArray(f)?f:[f];m=m.filter(Boolean);let h=i(m,r),g=[...new Set(h)].filter(Boolean),_=g.reduce((e,t)=>({...e,[t]:[]}),{}),v,y;p.transaction&&(p.transaction.definitionCache??=new Map,y=`${n}:${g.slice().sort().join(`,`)}`,v=p.transaction.definitionCache.get(y));let b;if(!v){let r=d.hasTypeId&&m.length>0&&m[0].typeId;v=(async(i=p.transaction)=>{if(r){let e=[...new Set(m.map(e=>e.typeId).filter(Boolean))];b=new Map,e.forEach(e=>b.set(e,new Set));let r=(await Promise.all(e.map(async e=>{let r=await t(e,{withDisabled:!1,entityIds:g,modelType:n,modelOptions:u,transaction:i});return r.forEach(t=>b.get(e).add(t.id)),r}))).flat(),a=new Map;return r.forEach(e=>{a.set(e.id,e)}),Array.from(a.values())}return e(n,g,{transaction:i,modelOptions:u,attributes:a})})(),r||p.transaction?.definitionCache?.set(y,v)}let x=await v;if(x.length===0){m.forEach(e=>{e.customFields={}});return}u?.include&&u.useEntityIdFromInclude&&u.include(h).forEach(({model:e})=>{x.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!_[n]&&(_[n]=[])})});let S=x.reduce((e,t)=>({...e,[t.id]:t}),{});x.forEach(e=>{let t=e.entityId;if(u?.useEntityIdFromInclude&&u.include){let n=u.include(h);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}_[t]&&_[t].push(e)});let C=m.map(e=>e.id),[w,T]=await Promise.all([s({instancesIds:C,options:p,sadotOptions:d}),o({instancesIds:C,options:p,sadotOptions:d})]);m.forEach(e=>{let{id:t}=e,n=w[t],i=n?c(n,S):{},a=d.useCustomFieldsEntries?T[t]:i;r.forEach(t=>{let n=_[e[t]];n&&n.length>0&&n.forEach(t=>{b&&!b.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,p.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),l===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{l as default};
2
2
  //# sourceMappingURL=enrich.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined","DefinitionRepo.findByModelTypeId","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction)\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction: options.transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"+PAUA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAMA,EAC/B,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAA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zE,GAAG,GACF,EAAW,IAAK,EAClB,EAAG,EAAE,CAAC,CAEP,EAAuB,QAAS,GAAa,CAC3C,IAAI,EAAgB,EAAI,SAExB,GAAI,GAAc,wBAA0B,EAAa,QAAS,CAChE,IAAM,EAAkB,EAAa,QAAQ,EAAY,CACzD,IAAK,GAAM,CAAE,WAAW,EAAiB,CACvC,IAAM,EAAiB,EAAI,EAAO,OAAO,UAAY,EAAI,GAAG,EAAO,KAAK,YACxE,GAAI,EAAgB,CAClB,EAAgB,EAChB,QAKF,EAAwC,IAC1C,EAAwC,GAAe,KAAK,EAAI,EAElE,CAGF,IAAM,EAAe,EAAU,IAAI,GAAK,EAAE,GAAY,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C"}
1
+ {"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined","DefinitionRepo.findByModelTypeId","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction).\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n const fetchDefinitions = async (transaction = options.transaction) => {\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n return Array.from(uniqueDefinitionsMap.values());\n }\n return DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n };\n\n customFieldDefinitionsPromise = fetchDefinitions();\n\n if (!shouldApplyTypeFiltering) {\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"+PAUA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAMA,EAC/B,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,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AAuB,QAAS,GAAa,CAC3C,IAAI,EAAgB,EAAI,SAExB,GAAI,GAAc,wBAA0B,EAAa,QAAS,CAChE,IAAM,EAAkB,EAAa,QAAQ,EAAY,CACzD,IAAK,GAAM,CAAE,WAAW,EAAiB,CACvC,IAAM,EAAiB,EAAI,EAAO,OAAO,UAAY,EAAI,GAAG,EAAO,KAAK,YACxE,GAAI,EAAgB,CAClB,EAAgB,EAChB,QAKF,EAAwC,IAC1C,EAAwC,GAAe,KAAK,EAAI,EAElE,CAGF,IAAM,EAAe,EAAU,IAAI,GAAK,EAAE,GAAY,CAGhD,CAAC,EAAuB,GAAkC,MAAM,QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C"}
@@ -1,2 +1,2 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../utils/constants/index.cjs`),r=require(`../errors/index.cjs`),i=require(`../repository/definition.cjs`),a=require(`../repository/validator.cjs`),o=require(`../utils/scopeAttributes.cjs`),s=require(`./utils/updateInstanceValues.cjs`);let c=require(`joi`);c=e.__toESM(c);let l=require(`@autofleet/errors`),u=require(`ajv`);u=e.__toESM(u);let d=require(`ajv-formats`);d=e.__toESM(d);let f=require(`ajv-errors`);f=e.__toESM(f);const p=[`id`,`schema`,`modelType`,`entityId`,`disabled`],m=new u.default({allErrors:!0,strict:!1,strictTypes:!1,$data:!0});(0,d.default)(m),(0,f.default)(m);const h=(e,t)=>({__proto__:null,...e,...t}),g=async(e,n)=>{if(!e.id||!e.customFields||Object.keys(e.customFields).length===0)return e.customFields||{};try{let r=await e.constructor.findOne({where:{id:e.id},attributes:[`customFields`],transaction:n.transaction,raw:!0});if(r?.customFields){let n=h(r.customFields,e.customFields);return t.default.debug(`sadot - fetched complete custom fields for validation`,{fieldsCount:Object.keys(n).length,updateFieldsCount:Object.keys(e.customFields).length}),n}}catch(e){t.default.error(`sadot - error fetching complete model for validation`,{error:e})}return e.customFields||{}},_=e=>{let t={...e.dataValues};(e.changed?.()||[]).forEach(n=>{let r=e.previous?.(n);r!==void 0&&(t[n]=r)});let n=e.previous?.(`customFields`);return n!==void 0&&(t.customFields=n),t},v=e=>e.reduce((e,t)=>{let n=((t.instancePath||``).split(`/`).filter(Boolean).join(`.`).replace(/^after\./,``)+(t.keyword===`required`?`.${t.params?.missingProperty}`:``)).replace(/^\./,``)||`root`;return e[n]=t.message||`Invalid value`,e},{}),y=async(e,n,r,i={},s=!1)=>{let c=e.constructor.name;t.default.debug(`sadot - validating model`,{isCreate:s,modelType:c});let u=o.default(e,r);if(t.default.debug(`sadot - identifiers`,{identifiers:u}),!u||Object.keys(u).length===0){t.default.debug(`sadot - skipping validation: no identifiers`);return}let d=Object.values(u)[0];if(t.default.debug(`sadot - entityId`,{entityId:d}),!d){t.default.debug(`sadot - skipping validation: no entityId`);return}let f,y;n.transaction&&(n.transaction.validationsCache??=new Map,y=`${c}-${d}`,f=n.transaction.validationsCache.get(y)),f||(f=a.findAllByModelType(c,d,{transaction:n.transaction,attributes:p,modelOptions:i}),n.transaction&&n?.transaction?.validationsCache.set(y,f));let b=await f;if(t.default.debug(`sadot - validators found`,{count:b.length}),!b.length){t.default.debug(`sadot - skipping validation: no validators found`);return}let x=null;s||(x=_(e));let S=s?e.customFields||{}:await g(e,n);for(let n of b){let{schema:r}=n,i=r;if(t.default.debug(`sadot - validating with schema`,{schema:r,hasAfterProps:!!i.properties?.after,hasBeforeProps:!!i.properties?.before}),s){if(i.properties?.after){let t=m.compile({...r,properties:{after:i.properties.after}});if(!t(JSON.parse(JSON.stringify({after:{...e.dataValues,customFields:S}})))){let e=t.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),n=v(t.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:n})}}}else{let n=m.compile(i),r=h(e.dataValues);r.customFields=S;let a={before:x,after:r},o=n(JSON.parse(JSON.stringify(a)));if(t.default.debug(`sadot - validation result`,{isValid:o,test:{before:x,after:r}}),!o){let e=n.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),t=v(n.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:t})}}}},b=async({modelType:e,modelOptions:t,identifiers:n,options:r,instance:a,hasTypeId:o})=>{let{include:s,useEntityIdFromInclude:c}=t;if(o&&a?.typeId)return i.findByModelTypeId(a.typeId,{withDisabled:!1,transaction:r.transaction,entityIds:n,modelType:e,modelOptions:t});let l={modelType:e,disabled:!1,...!c&&{entityId:n}};return await i.findAll(l,{withDisabled:!1,transaction:r.transaction,include:s?.(n)})},x=(e,t)=>{(e||[]).forEach(e=>{let{fieldType:i,name:a}=e;if([n.CustomFieldDefinitionType.DATE,n.CustomFieldDefinitionType.DATETIME].includes(i)){let e=t.customFields?.[a];if(e){let{value:n,error:i}=c.default.date().validate(e);if(i)throw new r.InvalidValueError(e,a,i);t.customFields[a]=n.toISOString()}}})},S=(e,n={},i={useCustomFieldsEntries:!1})=>async(a,c)=>{t.default.debug(`sadot - before create hook`);let{fields:l}=c,u=a.constructor.name,d=o.default(a,e),f=await b({modelType:u,modelOptions:n,identifiers:d,options:c,instance:a,hasTypeId:i.hasTypeId}),p=f.filter(e=>![null,void 0].includes(e.defaultValue));p.length&&(a.customFields||={},p.filter(e=>a.customFields?.[e.name]===void 0).forEach(({name:e,defaultValue:t})=>{a.customFields[e]=t}));let m;m=i.getRequiredCustomFields?await Promise.resolve(i.getRequiredCustomFields(a,f,c)):Array.from(new Set(f.filter(({required:e})=>e).map(({name:e})=>e)));let{customFields:h}=a,g=Object.keys(h??{}),_=m.filter(e=>!g.includes(e));if(_?.length)throw new r.MissingRequiredCustomFieldError(_);await y(a,c,e,n,!0),x(f,a);let v=l.indexOf(`customFields`);v===-1||!h||!Object.keys(h).length||(await s.default({modelId:a.id,modelType:u,identifiers:d,customFields:h,options:{useCustomFieldsEntries:i.useCustomFieldsEntries,transaction:c.transaction,modelOptions:n}}),l.splice(v,1))},C=(e,n={},r={useCustomFieldsEntries:!1})=>async(i,a)=>{t.default.debug(`sadot - before update hook`);let{fields:c}=a,l=i.constructor.name,u=o.default(i,e),d=await b({modelType:l,modelOptions:n,identifiers:u,options:a,instance:i,hasTypeId:r.hasTypeId});await y(i,a,e,n,!1),x(d,i);let f=c.indexOf(`customFields`);if(f>-1){let{customFields:e}=i;if(!Object.keys(e).length)return;await s.default({modelId:i.id,modelType:l,identifiers:u,customFields:e,options:{useCustomFieldsEntries:r.useCustomFieldsEntries,transaction:a.transaction,modelOptions:n}}),c.splice(f,1)}},w=e=>{e.individualHooks=!0},T=e=>{e.individualHooks=!0};exports.beforeBulkCreate=w,exports.beforeBulkUpdate=T,exports.beforeCreate=S,exports.beforeUpdate=C;
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../utils/constants/index.cjs`),r=require(`../errors/index.cjs`),i=require(`../repository/definition.cjs`),a=require(`../repository/validator.cjs`),o=require(`../utils/scopeAttributes.cjs`),s=require(`./utils/updateInstanceValues.cjs`);let c=require(`joi`);c=e.__toESM(c);let l=require(`@autofleet/errors`),u=require(`ajv`);u=e.__toESM(u);let d=require(`ajv-formats`);d=e.__toESM(d);let f=require(`ajv-errors`);f=e.__toESM(f);const p=[`id`,`schema`,`modelType`,`entityId`,`disabled`],m=new u.default({allErrors:!0,strict:!1,strictTypes:!1,$data:!0});(0,d.default)(m),(0,f.default)(m);const h=(e,t)=>({__proto__:null,...e,...t}),g=async(e,n)=>{if(!e.id||!e.customFields||Object.keys(e.customFields).length===0)return e.customFields||{};try{let r=await e.constructor.findOne({where:{id:e.id},attributes:[`customFields`],transaction:n.transaction,raw:!0});if(r?.customFields){let n=h(r.customFields,e.customFields);return t.default.debug(`sadot - fetched complete custom fields for validation`,{fieldsCount:Object.keys(n).length,updateFieldsCount:Object.keys(e.customFields).length}),n}}catch(e){t.default.error(`sadot - error fetching complete model for validation`,{error:e})}return e.customFields||{}},_=e=>{let t={...e.dataValues};(e.changed?.()||[]).forEach(n=>{let r=e.previous?.(n);r!==void 0&&(t[n]=r)});let n=e.previous?.(`customFields`);return n!==void 0&&(t.customFields=n),t},v=e=>e.reduce((e,t)=>{let n=((t.instancePath||``).split(`/`).filter(Boolean).join(`.`).replace(/^after\./,``)+(t.keyword===`required`?`.${t.params?.missingProperty}`:``)).replace(/^\./,``)||`root`;return e[n]=t.message||`Invalid value`,e},{}),y=async(e,n,r,i={},s=!1)=>{let c=e.constructor.name;t.default.debug(`sadot - validating model`,{isCreate:s,modelType:c});let u=o.default(e,r);if(t.default.debug(`sadot - identifiers`,{identifiers:u}),!u||Object.keys(u).length===0){t.default.debug(`sadot - skipping validation: no identifiers`);return}let d=Object.values(u)[0];if(t.default.debug(`sadot - entityId`,{entityId:d}),!d){t.default.debug(`sadot - skipping validation: no entityId`);return}let f,y;n.transaction&&(n.transaction.validationsCache??=new Map,y=`${c}-${d}`,f=n.transaction.validationsCache.get(y)),f||(f=a.findAllByModelType(c,d,{transaction:n.transaction,attributes:p,modelOptions:i}),n.transaction&&n?.transaction?.validationsCache.set(y,f));let b=await f;if(t.default.debug(`sadot - validators found`,{count:b.length}),!b.length){t.default.debug(`sadot - skipping validation: no validators found`);return}let x=null;s||(x=_(e));let S=s?e.customFields||{}:await g(e,n);for(let n of b){let{schema:r}=n,i=r;if(t.default.debug(`sadot - validating with schema`,{schema:r,hasAfterProps:!!i.properties?.after,hasBeforeProps:!!i.properties?.before}),s){if(i.properties?.after){let t=m.compile({...r,properties:{after:i.properties.after}});if(!t(JSON.parse(JSON.stringify({after:{...e.dataValues,customFields:S}})))){let e=t.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),n=v(t.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:n})}}}else{let n=m.compile(i),r=h(e.dataValues);r.customFields=S;let a={before:x,after:r},o=n(JSON.parse(JSON.stringify(a)));if(t.default.debug(`sadot - validation result`,{isValid:o,test:{before:x,after:r}}),!o){let e=n.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),t=v(n.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:t})}}}},b=async({modelType:e,modelOptions:t,identifiers:n,options:r,instance:a,sadotOptions:o})=>{let{include:s,useEntityIdFromInclude:c}=t;if(o.hasTypeId&&a?.typeId)return i.findByModelTypeId(a.typeId,{withDisabled:!1,transaction:r.transaction,entityIds:n,modelType:e,modelOptions:t});let l={modelType:e,disabled:!1,...!c&&{entityId:n}};return i.findAll(l,{withDisabled:!1,transaction:r.transaction,include:s?.(n)})},x=(e,t)=>{(e||[]).forEach(e=>{let{fieldType:i,name:a}=e;if([n.CustomFieldDefinitionType.DATE,n.CustomFieldDefinitionType.DATETIME].includes(i)){let e=t.customFields?.[a];if(e){let{value:n,error:i}=c.default.date().validate(e);if(i)throw new r.InvalidValueError(e,a,i);t.customFields[a]=n.toISOString()}}})},S=(e,n={},i={useCustomFieldsEntries:!1})=>async(a,c)=>{t.default.debug(`sadot - before create hook`);let{fields:l}=c,u=a.constructor.name,d=o.default(a,e),f=await b({modelType:u,modelOptions:n,identifiers:d,options:c,instance:a,sadotOptions:i}),p=f.filter(e=>![null,void 0].includes(e.defaultValue));p.length&&(a.customFields||={},p.filter(e=>a.customFields?.[e.name]===void 0).forEach(({name:e,defaultValue:t})=>{a.customFields[e]=t}));let m;m=i.getRequiredCustomFields?await Promise.resolve(i.getRequiredCustomFields(a,f,c)):Array.from(new Set(f.filter(({required:e})=>e).map(({name:e})=>e)));let{customFields:h}=a,g=Object.keys(h??{}),_=m.filter(e=>!g.includes(e));if(_?.length)throw new r.MissingRequiredCustomFieldError(_);await y(a,c,e,n,!0),x(f,a);let v=l.indexOf(`customFields`);v===-1||!h||!Object.keys(h).length||(await s.default({modelId:a.id,modelType:u,identifiers:d,customFields:h,options:{useCustomFieldsEntries:i.useCustomFieldsEntries,transaction:c.transaction,modelOptions:n}}),l.splice(v,1))},C=(e,n={},r={useCustomFieldsEntries:!1})=>async(i,a)=>{t.default.debug(`sadot - before update hook`);let{fields:c}=a,l=i.constructor.name,u=o.default(i,e),d=await b({modelType:l,modelOptions:n,identifiers:u,options:a,instance:i,sadotOptions:r});await y(i,a,e,n,!1),x(d,i);let f=c.indexOf(`customFields`);if(f>-1){let{customFields:e}=i;if(!Object.keys(e).length)return;await s.default({modelId:i.id,modelType:l,identifiers:u,customFields:e,options:{useCustomFieldsEntries:r.useCustomFieldsEntries,transaction:a.transaction,modelOptions:n}}),c.splice(f,1)}},w=e=>{e.individualHooks=!0},T=e=>{e.individualHooks=!0};exports.beforeBulkCreate=w,exports.beforeBulkUpdate=T,exports.beforeCreate=S,exports.beforeUpdate=C;
2
2
  //# sourceMappingURL=hooks.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.cjs","names":["ajv","Ajv","beforeFull: any","applyScopeToInstance","cacheKey: string | undefined","BadRequest","where: WhereOptions","CustomFieldDefinitionType","Joi","InvalidValueError","requiredFieldsNames: string[]","MissingRequiredCustomFieldError","updateInstanceValues"],"sources":["../../src/hooks/hooks.ts"],"sourcesContent":["import type {\n BulkCreateOptions, CreateOptions, Transactionable, UpdateOptions, WhereOptions,\n} from 'sequelize';\nimport Ajv from 'ajv';\nimport Joi from 'joi';\nimport addFormats from 'ajv-formats';\nimport { BadRequest } from '@autofleet/errors';\nimport ajvErrors from 'ajv-errors';\nimport logger from '../utils/logger';\nimport * as ValidatorRepo from '../repository/validator';\nimport * as DefinitionRepo from '../repository/definition';\nimport { InvalidValueError, MissingRequiredCustomFieldError } from '../errors';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\nimport updateInstanceValues from './utils/updateInstanceValues';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport type { CustomFieldDefinition } from '../models';\n\n// Include all required fields for proper validation\nconst CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = ['id', 'schema', 'modelType', 'entityId', 'disabled'];\n\n// Initialize Ajv with relaxed settings to avoid warnings\nconst ajv = new Ajv({\n allErrors: true,\n strict: false, // Disable strict mode to avoid warnings\n strictTypes: false, // Disable strict type checking\n $data: true, // Enable $data references\n});\n\naddFormats(ajv);\najvErrors(ajv);\n\n/**\n * Helper function to manually copy object properties\n * This is more efficient for large objects and avoids excessive object creation\n */\nconst manualObjectCopy = (sourceObj: Record<string, any>, additionalProps?: Record<string, any>): Record<string, any> =>\n ({ __proto__: null, ...sourceObj, ...additionalProps });\n\n/**\n * Fetches complete custom fields for an instance by merging DB values with update values\n * This is needed for partial updates to ensure all related fields are available for validation\n */\nconst getCompleteCustomFields = async (instance: any, options: Transactionable): Promise<Record<string, any>> => {\n // If we don't have an instance id or no custom fields being updated, return original fields\n if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) {\n return instance.customFields || {};\n }\n\n try {\n const ModelClass = instance.constructor;\n // Only select the customFields column to minimize data transfer\n const currentCustomFields = await ModelClass.findOne({\n where: { id: instance.id },\n attributes: ['customFields'],\n transaction: options.transaction,\n raw: true, // Get plain object instead of model instance for better performance\n });\n\n if (currentCustomFields?.customFields) {\n // Merge existing fields with update fields using our helper function\n const completeFields = manualObjectCopy(\n currentCustomFields.customFields,\n instance.customFields,\n );\n\n logger.debug('sadot - fetched complete custom fields for validation', {\n fieldsCount: Object.keys(completeFields).length,\n updateFieldsCount: Object.keys(instance.customFields).length,\n });\n\n return completeFields;\n }\n } catch (error) {\n logger.error('sadot - error fetching complete model for validation', { error });\n // Continue with partial data if we can't fetch the complete model\n }\n\n return instance.customFields || {};\n};\n\nconst buildPreChangeState = (instance: any) => {\n const beforeFull: any = { ...instance.dataValues };\n\n const changedKeys: string[] = instance.changed?.() || [];\n changedKeys.forEach((key) => {\n const prevVal = instance.previous?.(key);\n if (prevVal !== undefined) {\n beforeFull[key] = prevVal;\n }\n });\n\n const prevCF = instance.previous?.('customFields');\n if (prevCF !== undefined) {\n beforeFull.customFields = prevCF;\n }\n\n return beforeFull;\n};\n\nconst formatAjvErrors = (\n errors: {\n instancePath?: string;\n keyword: string;\n message?: string;\n params?: Record<string, any>;\n }[],\n): Record<string, string> => errors.reduce((acc, err) => {\n const basePath = (err.instancePath || '')\n .split('/')\n .filter(Boolean)\n .join('.')\n .replace(/^after\\./, '');\n\n const missingProp = err.keyword === 'required' ? `.${err.params?.missingProperty}` : '';\n const key = (basePath + missingProp).replace(/^\\./, '') || 'root';\n\n const message = err.message || 'Invalid value';\n acc[key] = message;\n\n return acc;\n}, {} as Record<string, string>);\n\n/**\n * Validates the model using custom validators\n */\nconst validateModel = async (\n instance: any,\n options: TransactionOptions,\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n isCreate = false,\n): Promise<void> => {\n const modelType = instance.constructor.name;\n\n logger.debug('sadot - validating model', { isCreate, modelType });\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n logger.debug('sadot - identifiers', { identifiers });\n\n // Skip if no identifiers\n if (!identifiers || Object.keys(identifiers).length === 0) {\n logger.debug('sadot - skipping validation: no identifiers');\n return;\n }\n\n // Find the entityId from identifiers (fleetId, businessModelId, etc.)\n const entityId = Object.values(identifiers)[0]; // Get the first value as entityId\n\n logger.debug('sadot - entityId', { entityId });\n\n if (!entityId) {\n logger.debug('sadot - skipping validation: no entityId');\n return;\n }\n\n let validatorsPromise;\n let cacheKey: string | undefined;\n if (options.transaction) {\n options.transaction.validationsCache ??= new Map();\n cacheKey = `${modelType}-${entityId}`;\n validatorsPromise = options.transaction.validationsCache.get(cacheKey);\n }\n\n if (!validatorsPromise) {\n validatorsPromise = ValidatorRepo.findAllByModelType(\n modelType,\n entityId,\n {\n transaction: options.transaction,\n attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,\n modelOptions,\n },\n );\n if (options.transaction) {\n options?.transaction?.validationsCache!.set(cacheKey!, validatorsPromise);\n }\n }\n const validators = await validatorsPromise;\n\n logger.debug('sadot - validators found', { count: validators.length });\n\n if (!validators.length) {\n logger.debug('sadot - skipping validation: no validators found');\n return;\n }\n\n // For updates, get the previous values\n let originalValues = null;\n if (!isCreate) {\n originalValues = buildPreChangeState(instance);\n }\n\n // Get complete custom fields by merging DB values with update values\n // This is especially important for partial updates to ensure all related fields are available\n const completeCustomFields = !isCreate\n ? await getCompleteCustomFields(instance, options)\n : instance.customFields || {};\n\n for (const validator of validators) {\n const { schema } = validator;\n const typedSchema = schema as Record<string, any>;\n\n logger.debug('sadot - validating with schema', {\n schema,\n hasAfterProps: !!typedSchema.properties?.after,\n hasBeforeProps: !!typedSchema.properties?.before,\n });\n\n if (isCreate) {\n // For create operations, we only need the 'after' state\n if (typedSchema.properties?.after) {\n const validateSchema = ajv.compile({\n ...schema,\n // Focus only on the 'after' validation part for create\n properties: {\n after: typedSchema.properties.after,\n },\n });\n\n const isValid = validateSchema(JSON.parse(JSON.stringify({\n after: {\n ...instance.dataValues,\n customFields: completeCustomFields,\n },\n })));\n\n if (!isValid) {\n const errorDetails = validateSchema.errors?.map(err =>\n `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n } else {\n // For update operations, we need both before and after\n const validateSchema = ajv.compile(typedSchema);\n\n // Create after object with our helper function\n const afterObj = manualObjectCopy(instance.dataValues);\n\n // Add complete custom fields\n afterObj.customFields = completeCustomFields;\n\n // Create validation payload\n const payload = {\n before: originalValues,\n after: afterObj,\n };\n\n // Validate\n const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));\n\n logger.debug('sadot - validation result', {\n isValid,\n test: {\n before: originalValues,\n after: afterObj,\n },\n });\n\n if (!isValid) {\n const errorDetails = validateSchema\n .errors\n ?.map(err => `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n }\n};\n\nconst getFieldDefinitions = async ({\n modelType,\n modelOptions,\n identifiers,\n options,\n instance,\n hasTypeId,\n}: {\n modelType: any;\n modelOptions: ModelOptions;\n identifiers: any[];\n options: any;\n instance?: any;\n hasTypeId?: boolean;\n}) => {\n const { include, useEntityIdFromInclude } = modelOptions;\n\n // If hasTypeId is enabled and instance has a typeId, filter by modelTypeId\n if (hasTypeId && instance?.typeId) {\n return DefinitionRepo.findByModelTypeId(instance.typeId, {\n withDisabled: false,\n transaction: options.transaction,\n entityIds: identifiers,\n modelType,\n modelOptions,\n });\n }\n\n // Otherwise, use the standard findAll\n const where: WhereOptions = {\n modelType,\n disabled: false,\n ...(!useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, {\n withDisabled: false,\n transaction: options.transaction,\n include: include?.(identifiers),\n });\n return fieldDefinitions;\n};\n\nconst formatDates = (fieldDefinitions: CustomFieldDefinition[], instance: any) => {\n (fieldDefinitions || []).forEach((fieldDefinition) => {\n const { fieldType, name } = fieldDefinition;\n if ([CustomFieldDefinitionType.DATE, CustomFieldDefinitionType.DATETIME].includes(fieldType)) {\n const value = instance.customFields?.[name];\n if (value) {\n const { value: joiValue, error: validationError } = Joi.date().validate(value);\n if (validationError) {\n throw new InvalidValueError(value, name, validationError);\n }\n instance.customFields[name] = joiValue.toISOString();\n }\n }\n });\n};\n\n/**\n * Hook to handle validation and custom fields during creation\n */\nexport const beforeCreate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'getRequiredCustomFields' | 'hasTypeId'> = {\n useCustomFieldsEntries: false,\n },\n) => async (\n instance: any,\n options: CreateOptions,\n): Promise<void> => {\n logger.debug('sadot - before create hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n // Step 1: Handle custom fields default values and required fields\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options, instance, hasTypeId: sadotOptions.hasTypeId,\n });\n\n // Apply default values\n const fieldsWithDefaultValue = fieldDefinitions.filter(def => ![null, undefined].includes(def.defaultValue));\n if (fieldsWithDefaultValue.length) {\n instance.customFields ||= {};\n fieldsWithDefaultValue\n .filter(def => (instance.customFields?.[def.name] === undefined))\n .forEach(({ name, defaultValue }) => {\n instance.customFields[name] = defaultValue;\n });\n }\n\n // Check for required fields\n let requiredFieldsNames: string[];\n\n if (sadotOptions.getRequiredCustomFields) {\n // Use consumer-provided logic to determine required fields\n requiredFieldsNames = await Promise.resolve(\n sadotOptions.getRequiredCustomFields(instance, fieldDefinitions, options),\n );\n } else {\n // Default behavior: use required flag from fieldDefinitions\n requiredFieldsNames = Array.from(\n new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)),\n );\n }\n\n const { customFields } = instance;\n const fieldsNames = Object.keys(customFields ?? {});\n const missingFields = requiredFieldsNames.filter(name => !fieldsNames.includes(name));\n if (missingFields?.length) {\n throw new MissingRequiredCustomFieldError(missingFields);\n }\n\n // Step 2: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, true);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 3: Save custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) {\n // No custom fields to update\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n};\n\n/**\n * Hook to handle validation and custom fields during update\n */\nexport const beforeUpdate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'getRequiredCustomFields' | 'hasTypeId'> = {\n useCustomFieldsEntries: false,\n },\n) => async (\n instance: any,\n options: UpdateOptions,\n): Promise<void> => {\n logger.debug('sadot - before update hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options, instance, hasTypeId: sadotOptions.hasTypeId,\n });\n\n // Step 1: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, false);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 2: Update custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx > -1) {\n const { customFields } = instance;\n\n if (!Object.keys(customFields).length) {\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n }\n};\n\n/**\n * Hook to enable individual hooks for bulk create operations\n */\nexport const beforeBulkCreate = (options: BulkCreateOptions): void => {\n // This will activate the beforeCreate hook on each instance\n options.individualHooks = true;\n};\n\n/**\n * Hook to enable individual hooks for bulk update operations\n */\nexport const beforeBulkUpdate = (options: UpdateOptions): void => {\n // This will activate the beforeUpdate hook on each instance\n options.individualHooks = true;\n};\n"],"mappings":"+gBAmBA,MAAM,EAAsC,CAAC,KAAM,SAAU,YAAa,WAAY,WAAW,CAG3FA,EAAM,IAAIC,EAAAA,QAAI,CAClB,UAAW,GACX,OAAQ,GACR,YAAa,GACb,MAAO,GACR,CAAC,eAESD,EAAI,eACLA,EAAI,CAMd,MAAM,GAAoB,EAAgC,KACvD,CAAE,UAAW,KAAM,GAAG,EAAW,GAAG,EAAiB,EAMlD,EAA0B,MAAO,EAAe,IAA2D,CAE/G,GAAI,CAAC,EAAS,IAAM,CAAC,EAAS,cAAgB,OAAO,KAAK,EAAS,aAAa,CAAC,SAAW,EAC1F,OAAO,EAAS,cAAgB,EAAE,CAGpC,GAAI,CAGF,IAAM,EAAsB,MAFT,EAAS,YAEiB,QAAQ,CACnD,MAAO,CAAE,GAAI,EAAS,GAAI,CAC1B,WAAY,CAAC,eAAe,CAC5B,YAAa,EAAQ,YACrB,IAAK,GACN,CAAC,CAEF,GAAI,GAAqB,aAAc,CAErC,IAAM,EAAiB,EACrB,EAAoB,aACpB,EAAS,aACV,CAOD,OALA,EAAA,QAAO,MAAM,wDAAyD,CACpE,YAAa,OAAO,KAAK,EAAe,CAAC,OACzC,kBAAmB,OAAO,KAAK,EAAS,aAAa,CAAC,OACvD,CAAC,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EAAS,CAGvC,IAAM,EAAkB,EAAQ,QAAQ,eAAe,CACnD,IAAoB,IAAM,CAAC,GAAgB,CAAC,OAAO,KAAK,EAAa,CAAC,SAM1E,MAAMC,EAAAA,QAAqB,CACzB,QAAS,EAAS,GAClB,YACA,cACA,eACA,QAAS,CACP,uBAAwB,EAAa,uBACrC,YAAa,EAAQ,YACrB,eACD,CACF,CAAC,CAGF,EAAQ,OAAO,EAAiB,EAAE,GAMvB,GACX,EACA,EAA6B,EAAE,CAC/B,EAA6G,CAC3G,uBAAwB,GACzB,GACE,MACH,EACA,IACkB,CAClB,EAAA,QAAO,MAAM,6BAA6B,CAC1C,GAAM,CAAE,UAAW,EACb,EAAY,EAAS,YAAY,KACjC,EAAcT,EAAAA,QAAqB,EAAU,EAAgB,CAE7D,EAAmB,MAAM,EAAoB,CACjD,YAAW,eAAc,cAAa,UAAS,WAAU,UAAW,EAAa,UAClF,CAAC,CAGF,MAAM,EAAc,EAAU,EAA+B,EAAiB,EAAc,GAAM,CAGlG,EAAY,EAAkB,EAAS,CAGvC,IAAM,EAAkB,EAAQ,QAAQ,eAAe,CACvD,GAAI,EAAkB,GAAI,CACxB,GAAM,CAAE,gBAAiB,EAEzB,GAAI,CAAC,OAAO,KAAK,EAAa,CAAC,OAC7B,OAIF,MAAMS,EAAAA,QAAqB,CACzB,QAAS,EAAS,GAClB,YACA,cACA,eACA,QAAS,CACP,uBAAwB,EAAa,uBACrC,YAAa,EAAQ,YACrB,eACD,CACF,CAAC,CAGF,EAAQ,OAAO,EAAiB,EAAE,GAOzB,EAAoB,GAAqC,CAEpE,EAAQ,gBAAkB,IAMf,EAAoB,GAAiC,CAEhE,EAAQ,gBAAkB"}
1
+ {"version":3,"file":"hooks.cjs","names":["ajv","Ajv","beforeFull: any","applyScopeToInstance","cacheKey: string | undefined","BadRequest","where: WhereOptions","CustomFieldDefinitionType","Joi","InvalidValueError","requiredFieldsNames: string[]","MissingRequiredCustomFieldError","updateInstanceValues"],"sources":["../../src/hooks/hooks.ts"],"sourcesContent":["import type {\n BulkCreateOptions, CreateOptions, Transactionable, UpdateOptions, WhereOptions,\n} from 'sequelize';\nimport Ajv from 'ajv';\nimport Joi from 'joi';\nimport addFormats from 'ajv-formats';\nimport { BadRequest } from '@autofleet/errors';\nimport ajvErrors from 'ajv-errors';\nimport logger from '../utils/logger';\nimport * as ValidatorRepo from '../repository/validator';\nimport * as DefinitionRepo from '../repository/definition';\nimport { InvalidValueError, MissingRequiredCustomFieldError } from '../errors';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\nimport updateInstanceValues from './utils/updateInstanceValues';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport type { CustomFieldDefinition } from '../models';\n\ntype HookSadotOptions = Pick<\n CustomFieldOptions,\n 'useCustomFieldsEntries' | 'getRequiredCustomFields' | 'hasTypeId'\n>;\n\n// Include all required fields for proper validation\nconst CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = ['id', 'schema', 'modelType', 'entityId', 'disabled'];\n\n// Initialize Ajv with relaxed settings to avoid warnings\nconst ajv = new Ajv({\n allErrors: true,\n strict: false, // Disable strict mode to avoid warnings\n strictTypes: false, // Disable strict type checking\n $data: true, // Enable $data references\n});\n\naddFormats(ajv);\najvErrors(ajv);\n\n/**\n * Helper function to manually copy object properties\n * This is more efficient for large objects and avoids excessive object creation\n */\nconst manualObjectCopy = (sourceObj: Record<string, any>, additionalProps?: Record<string, any>): Record<string, any> =>\n ({ __proto__: null, ...sourceObj, ...additionalProps });\n\n/**\n * Fetches complete custom fields for an instance by merging DB values with update values\n * This is needed for partial updates to ensure all related fields are available for validation\n */\nconst getCompleteCustomFields = async (instance: any, options: Transactionable): Promise<Record<string, any>> => {\n // If we don't have an instance id or no custom fields being updated, return original fields\n if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) {\n return instance.customFields || {};\n }\n\n try {\n const ModelClass = instance.constructor;\n // Only select the customFields column to minimize data transfer\n const currentCustomFields = await ModelClass.findOne({\n where: { id: instance.id },\n attributes: ['customFields'],\n transaction: options.transaction,\n raw: true, // Get plain object instead of model instance for better performance\n });\n\n if (currentCustomFields?.customFields) {\n // Merge existing fields with update fields using our helper function\n const completeFields = manualObjectCopy(\n currentCustomFields.customFields,\n instance.customFields,\n );\n\n logger.debug('sadot - fetched complete custom fields for validation', {\n fieldsCount: Object.keys(completeFields).length,\n updateFieldsCount: Object.keys(instance.customFields).length,\n });\n\n return completeFields;\n }\n } catch (error) {\n logger.error('sadot - error fetching complete model for validation', { error });\n // Continue with partial data if we can't fetch the complete model\n }\n\n return instance.customFields || {};\n};\n\nconst buildPreChangeState = (instance: any) => {\n const beforeFull: any = { ...instance.dataValues };\n\n const changedKeys: string[] = instance.changed?.() || [];\n changedKeys.forEach((key) => {\n const prevVal = instance.previous?.(key);\n if (prevVal !== undefined) {\n beforeFull[key] = prevVal;\n }\n });\n\n const prevCF = instance.previous?.('customFields');\n if (prevCF !== undefined) {\n beforeFull.customFields = prevCF;\n }\n\n return beforeFull;\n};\n\nconst formatAjvErrors = (\n errors: {\n instancePath?: string;\n keyword: string;\n message?: string;\n params?: Record<string, any>;\n }[],\n): Record<string, string> => errors.reduce((acc, err) => {\n const basePath = (err.instancePath || '')\n .split('/')\n .filter(Boolean)\n .join('.')\n .replace(/^after\\./, '');\n\n const missingProp = err.keyword === 'required' ? `.${err.params?.missingProperty}` : '';\n const key = (basePath + missingProp).replace(/^\\./, '') || 'root';\n\n const message = err.message || 'Invalid value';\n acc[key] = message;\n\n return acc;\n}, {} as Record<string, string>);\n\n/**\n * Validates the model using custom validators\n */\nconst validateModel = async (\n instance: any,\n options: TransactionOptions,\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n isCreate = false,\n): Promise<void> => {\n const modelType = instance.constructor.name;\n\n logger.debug('sadot - validating model', { isCreate, modelType });\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n logger.debug('sadot - identifiers', { identifiers });\n\n // Skip if no identifiers\n if (!identifiers || Object.keys(identifiers).length === 0) {\n logger.debug('sadot - skipping validation: no identifiers');\n return;\n }\n\n // Find the entityId from identifiers (fleetId, businessModelId, etc.)\n const entityId = Object.values(identifiers)[0]; // Get the first value as entityId\n\n logger.debug('sadot - entityId', { entityId });\n\n if (!entityId) {\n logger.debug('sadot - skipping validation: no entityId');\n return;\n }\n\n let validatorsPromise;\n let cacheKey: string | undefined;\n if (options.transaction) {\n options.transaction.validationsCache ??= new Map();\n cacheKey = `${modelType}-${entityId}`;\n validatorsPromise = options.transaction.validationsCache.get(cacheKey);\n }\n\n if (!validatorsPromise) {\n validatorsPromise = ValidatorRepo.findAllByModelType(\n modelType,\n entityId,\n {\n transaction: options.transaction,\n attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,\n modelOptions,\n },\n );\n if (options.transaction) {\n options?.transaction?.validationsCache!.set(cacheKey!, validatorsPromise);\n }\n }\n const validators = await validatorsPromise;\n\n logger.debug('sadot - validators found', { count: validators.length });\n\n if (!validators.length) {\n logger.debug('sadot - skipping validation: no validators found');\n return;\n }\n\n // For updates, get the previous values\n let originalValues = null;\n if (!isCreate) {\n originalValues = buildPreChangeState(instance);\n }\n\n // Get complete custom fields by merging DB values with update values\n // This is especially important for partial updates to ensure all related fields are available\n const completeCustomFields = !isCreate\n ? await getCompleteCustomFields(instance, options)\n : instance.customFields || {};\n\n for (const validator of validators) {\n const { schema } = validator;\n const typedSchema = schema as Record<string, any>;\n\n logger.debug('sadot - validating with schema', {\n schema,\n hasAfterProps: !!typedSchema.properties?.after,\n hasBeforeProps: !!typedSchema.properties?.before,\n });\n\n if (isCreate) {\n // For create operations, we only need the 'after' state\n if (typedSchema.properties?.after) {\n const validateSchema = ajv.compile({\n ...schema,\n // Focus only on the 'after' validation part for create\n properties: {\n after: typedSchema.properties.after,\n },\n });\n\n const isValid = validateSchema(JSON.parse(JSON.stringify({\n after: {\n ...instance.dataValues,\n customFields: completeCustomFields,\n },\n })));\n\n if (!isValid) {\n const errorDetails = validateSchema.errors?.map(err =>\n `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n } else {\n // For update operations, we need both before and after\n const validateSchema = ajv.compile(typedSchema);\n\n // Create after object with our helper function\n const afterObj = manualObjectCopy(instance.dataValues);\n\n // Add complete custom fields\n afterObj.customFields = completeCustomFields;\n\n // Create validation payload\n const payload = {\n before: originalValues,\n after: afterObj,\n };\n\n // Validate\n const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));\n\n logger.debug('sadot - validation result', {\n isValid,\n test: {\n before: originalValues,\n after: afterObj,\n },\n });\n\n if (!isValid) {\n const errorDetails = validateSchema\n .errors\n ?.map(err => `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n }\n};\n\nconst getFieldDefinitions = async ({\n modelType,\n modelOptions,\n identifiers,\n options,\n instance,\n sadotOptions,\n}: {\n modelType: any;\n modelOptions: ModelOptions;\n identifiers: any[];\n options: any;\n instance?: any;\n sadotOptions: HookSadotOptions;\n}) => {\n const { include, useEntityIdFromInclude } = modelOptions;\n\n if (sadotOptions.hasTypeId && instance?.typeId) {\n return DefinitionRepo.findByModelTypeId(instance.typeId, {\n withDisabled: false,\n transaction: options.transaction,\n entityIds: identifiers,\n modelType,\n modelOptions,\n });\n }\n const where: WhereOptions = {\n modelType,\n disabled: false,\n ...(!useEntityIdFromInclude && { entityId: identifiers }),\n };\n return DefinitionRepo.findAll(where, {\n withDisabled: false,\n transaction: options.transaction,\n include: include?.(identifiers),\n });\n};\n\nconst formatDates = (fieldDefinitions: CustomFieldDefinition[], instance: any) => {\n (fieldDefinitions || []).forEach((fieldDefinition) => {\n const { fieldType, name } = fieldDefinition;\n if ([CustomFieldDefinitionType.DATE, CustomFieldDefinitionType.DATETIME].includes(fieldType)) {\n const value = instance.customFields?.[name];\n if (value) {\n const { value: joiValue, error: validationError } = Joi.date().validate(value);\n if (validationError) {\n throw new InvalidValueError(value, name, validationError);\n }\n instance.customFields[name] = joiValue.toISOString();\n }\n }\n });\n};\n\n/**\n * Hook to handle validation and custom fields during creation\n */\nexport const beforeCreate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: HookSadotOptions = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: CreateOptions,\n): Promise<void> => {\n logger.debug('sadot - before create hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n // Step 1: Handle custom fields default values and required fields\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options, instance, sadotOptions,\n });\n\n // Apply default values\n const fieldsWithDefaultValue = fieldDefinitions.filter(def => ![null, undefined].includes(def.defaultValue));\n if (fieldsWithDefaultValue.length) {\n instance.customFields ||= {};\n fieldsWithDefaultValue\n .filter(def => (instance.customFields?.[def.name] === undefined))\n .forEach(({ name, defaultValue }) => {\n instance.customFields[name] = defaultValue;\n });\n }\n\n // Check for required fields\n let requiredFieldsNames: string[];\n\n if (sadotOptions.getRequiredCustomFields) {\n // Use consumer-provided logic to determine required fields\n requiredFieldsNames = await Promise.resolve(\n sadotOptions.getRequiredCustomFields(instance, fieldDefinitions, options),\n );\n } else {\n // Default behavior: use required flag from fieldDefinitions\n requiredFieldsNames = Array.from(\n new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)),\n );\n }\n\n const { customFields } = instance;\n const fieldsNames = Object.keys(customFields ?? {});\n const missingFields = requiredFieldsNames.filter(name => !fieldsNames.includes(name));\n if (missingFields?.length) {\n throw new MissingRequiredCustomFieldError(missingFields);\n }\n\n // Step 2: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, true);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 3: Save custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) {\n // No custom fields to update\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n};\n\n/**\n * Hook to handle validation and custom fields during update\n */\nexport const beforeUpdate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: HookSadotOptions = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: UpdateOptions,\n): Promise<void> => {\n logger.debug('sadot - before update hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options, instance, sadotOptions,\n });\n\n // Step 1: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, false);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 2: Update custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx > -1) {\n const { customFields } = instance;\n\n if (!Object.keys(customFields).length) {\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n }\n};\n\n/**\n * Hook to enable individual hooks for bulk create operations\n */\nexport const beforeBulkCreate = (options: BulkCreateOptions): void => {\n // This will activate the beforeCreate hook on each instance\n options.individualHooks = true;\n};\n\n/**\n * Hook to enable individual hooks for bulk update operations\n */\nexport const beforeBulkUpdate = (options: UpdateOptions): void => {\n // This will activate the beforeUpdate hook on each instance\n options.individualHooks = true;\n};\n"],"mappings":"+gBAwBA,MAAM,EAAsC,CAAC,KAAM,SAAU,YAAa,WAAY,WAAW,CAG3FA,EAAM,IAAIC,EAAAA,QAAI,CAClB,UAAW,GACX,OAAQ,GACR,YAAa,GACb,MAAO,GACR,CAAC,eAESD,EAAI,eACLA,EAAI,CAMd,MAAM,GAAoB,EAAgC,KACvD,CAAE,UAAW,KAAM,GAAG,EAAW,GAAG,EAAiB,EAMlD,EAA0B,MAAO,EAAe,IAA2D,CAE/G,GAAI,CAAC,EAAS,IAAM,CAAC,EAAS,cAAgB,OAAO,KAAK,EAAS,aAAa,CAAC,SAAW,EAC1F,OAAO,EAAS,cAAgB,EAAE,CAGpC,GAAI,CAGF,IAAM,EAAsB,MAFT,EAAS,YAEiB,QAAQ,CACnD,MAAO,CAAE,GAAI,EAAS,GAAI,CAC1B,WAAY,CAAC,eAAe,CAC5B,YAAa,EAAQ,YACrB,IAAK,GACN,CAAC,CAEF,GAAI,GAAqB,aAAc,CAErC,IAAM,EAAiB,EACrB,EAAoB,aACpB,EAAS,aACV,CAOD,OALA,EAAA,QAAO,MAAM,wDAAyD,CACpE,YAAa,OAAO,KAAK,EAAe,CAAC,OACzC,kBAAmB,OAAO,KAAK,EAAS,aAAa,CAAC,OACvD,CAAC,CAEK,SAEF,EAAO,CACd,EAAA,QAAO,MAAM,uDAAwD,CAAE,QAAO,CAAC,CAIjF,OAAO,EAAS,cAAgB,EAAE,EAG9B,EAAuB,GAAkB,CAC7C,IAAME,EAAkB,CAAE,GAAG,EAAS,WAAY,EAEpB,EAAS,WAAW,EAAI,EAAE,EAC5C,QAAS,GAAQ,CAC3B,IAAM,EAAU,EAAS,W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