@autofleet/sadot 1.3.11-beta.1 → 1.3.11

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.
@@ -1,2 +1,2 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../events/index.cjs`),n=require(`../errors/index.cjs`),r=require(`../utils/validations/index.cjs`),i=require(`../repository/definition.cjs`),a=require(`../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs`),o=require(`../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs`),s=require(`./CustomFieldDefinition.cjs`);let c=require(`sequelize-typescript`);var l,u,d,f,p;let m=class extends c.Model{static validateValueAgainstDefinition(e,t){let{validation:i,fieldType:a,name:o}=t;if(!r.validateFieldType(a))throw new n.InvalidFieldTypeError(a);if(e.value===null)return;let s=r.validateValue(e.value,a,i);if(s.error)throw new n.InvalidValueError(e.value,o,s.error)}static async validateCustomFieldValues(e){let t=e.map(e=>e.customFieldDefinitionId),n=[...new Set(t)],r=await i.findByIds(n,{withDisabled:!0});if(!r||r.length!==n.length)throw Error(`Definitions not found`);e.forEach(e=>{let t=r.find(t=>t.id===e.customFieldDefinitionId);t&&this.validateValueAgainstDefinition(e,t)})}static async validateCustomFieldValue(e){let{customFieldDefinitionId:t}=e,n=await i.findById(t,{withDisabled:!0});this.validateValueAgainstDefinition(e,n)}static afterSaveHandler(e,n){n.transaction?n.transaction.afterCommit(()=>t.sendDimEvent(e[0])):t.sendDimEvent(e[0])}};o.__decorate([c.PrimaryKey,(0,c.Column)({type:c.DataType.UUID,allowNull:!1}),a.__decorateMetadata(`design:type`,String)],m.prototype,`modelId`,void 0),o.__decorate([c.PrimaryKey,(0,c.ForeignKey)(()=>s.default),(0,c.Column)({type:c.DataType.UUID,allowNull:!1}),a.__decorateMetadata(`design:type`,String)],m.prototype,`customFieldDefinitionId`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.JSONB,allowNull:!0}),a.__decorateMetadata(`design:type`,Object)],m.prototype,`value`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.DATE,allowNull:!1}),a.__decorateMetadata(`design:type`,typeof(l=typeof Date<`u`&&Date)==`function`?l:Object)],m.prototype,`createdAt`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.DATE,allowNull:!0}),a.__decorateMetadata(`design:type`,typeof(u=typeof Date<`u`&&Date)==`function`?u:Object)],m.prototype,`updatedAt`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.DATE,allowNull:!0}),a.__decorateMetadata(`design:type`,typeof(d=typeof Date<`u`&&Date)==`function`?d:Object)],m.prototype,`deletedAt`,void 0),o.__decorate([(0,c.BelongsTo)(()=>s.default,{scope:{disabled:!1}}),a.__decorateMetadata(`design:type`,typeof(f=s.default!==void 0&&s.default)==`function`?f:Object)],m.prototype,`customFieldDefinition`,void 0),o.__decorate([c.BeforeBulkCreate,c.BeforeBulkUpdate,a.__decorateMetadata(`design:type`,Function),a.__decorateMetadata(`design:paramtypes`,[Array]),a.__decorateMetadata(`design:returntype`,Promise)],m,`validateCustomFieldValues`,null),o.__decorate([c.BeforeUpdate,c.BeforeCreate,c.BeforeUpsert,a.__decorateMetadata(`design:type`,Function),a.__decorateMetadata(`design:paramtypes`,[typeof(p=m!==void 0&&m)==`function`?p:Object]),a.__decorateMetadata(`design:returntype`,Promise)],m,`validateCustomFieldValue`,null),o.__decorate([c.AfterUpsert,a.__decorateMetadata(`design:type`,Function),a.__decorateMetadata(`design:paramtypes`,[Array,Object]),a.__decorateMetadata(`design:returntype`,void 0)],m,`afterSaveHandler`,null),m=o.__decorate([(0,c.Table)({tableName:`custom_field_values`,modelName:`CustomFieldValue`,timestamps:!0,indexes:[{name:`idx_custom_field_values_active_definition_id`,fields:[`customFieldDefinitionId`],where:{deleted_at:null}}]})],m);var h=m;exports.default=h;
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../events/index.cjs`),n=require(`../errors/index.cjs`),r=require(`../utils/validations/index.cjs`),i=require(`../repository/definition.cjs`),a=require(`../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs`),o=require(`../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs`),s=require(`./CustomFieldDefinition.cjs`);let c=require(`sequelize-typescript`);var l,u,d,f,p;let m=class extends c.Model{static validateValueAgainstDefinition(e,t){let{validation:i,fieldType:a,name:o}=t;if(!r.validateFieldType(a))throw new n.InvalidFieldTypeError(a);if(e.value===null)return;let s=r.validateValue(e.value,a,i);if(s.error)throw new n.InvalidValueError(e.value,o,s.error)}static async validateCustomFieldValues(e){let t=e.map(e=>e.customFieldDefinitionId),n=[...new Set(t)],r=await i.findByIds(n,{withDisabled:!0});if(!r||r.length!==n.length)throw Error(`Definitions not found`);e.forEach(e=>{let t=r.find(t=>t.id===e.customFieldDefinitionId);t&&this.validateValueAgainstDefinition(e,t)})}static async validateCustomFieldValue(e){let{customFieldDefinitionId:t}=e,n=await i.findById(t,{withDisabled:!0});this.validateValueAgainstDefinition(e,n)}static afterSaveHandler(e,n){n.transaction?n.transaction.afterCommit(()=>t.sendDimEvent(e[0])):t.sendDimEvent(e[0])}};o.__decorate([c.PrimaryKey,(0,c.Column)({type:c.DataType.UUID,allowNull:!1}),a.__decorateMetadata(`design:type`,String)],m.prototype,`modelId`,void 0),o.__decorate([c.PrimaryKey,(0,c.ForeignKey)(()=>s.default),(0,c.Column)({type:c.DataType.UUID,allowNull:!1}),a.__decorateMetadata(`design:type`,String)],m.prototype,`customFieldDefinitionId`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.JSONB,allowNull:!0}),a.__decorateMetadata(`design:type`,Object)],m.prototype,`value`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.DATE,allowNull:!1}),a.__decorateMetadata(`design:type`,typeof(l=typeof Date<`u`&&Date)==`function`?l:Object)],m.prototype,`createdAt`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.DATE,allowNull:!0}),a.__decorateMetadata(`design:type`,typeof(u=typeof Date<`u`&&Date)==`function`?u:Object)],m.prototype,`updatedAt`,void 0),o.__decorate([(0,c.Column)({type:c.DataType.DATE,allowNull:!0}),a.__decorateMetadata(`design:type`,typeof(d=typeof Date<`u`&&Date)==`function`?d:Object)],m.prototype,`deletedAt`,void 0),o.__decorate([(0,c.BelongsTo)(()=>s.default,{scope:{disabled:!1}}),a.__decorateMetadata(`design:type`,typeof(f=s.default!==void 0&&s.default)==`function`?f:Object)],m.prototype,`customFieldDefinition`,void 0),o.__decorate([c.BeforeBulkCreate,c.BeforeBulkUpdate,a.__decorateMetadata(`design:type`,Function),a.__decorateMetadata(`design:paramtypes`,[Array]),a.__decorateMetadata(`design:returntype`,Promise)],m,`validateCustomFieldValues`,null),o.__decorate([c.BeforeUpdate,c.BeforeCreate,c.BeforeUpsert,a.__decorateMetadata(`design:type`,Function),a.__decorateMetadata(`design:paramtypes`,[typeof(p=m!==void 0&&m)==`function`?p:Object]),a.__decorateMetadata(`design:returntype`,Promise)],m,`validateCustomFieldValue`,null),o.__decorate([c.AfterUpsert,a.__decorateMetadata(`design:type`,Function),a.__decorateMetadata(`design:paramtypes`,[Array,Object]),a.__decorateMetadata(`design:returntype`,void 0)],m,`afterSaveHandler`,null),m=o.__decorate([(0,c.Table)({tableName:`custom_field_values`,modelName:`CustomFieldValue`,timestamps:!0})],m);var h=m;exports.default=h;
2
2
  //# sourceMappingURL=CustomFieldValue.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CustomFieldValue.cjs","names":["CustomFieldValue","Model","validateFieldType","InvalidFieldTypeError","validateValue","InvalidValueError","sendDimEvent","PrimaryKey","DataType","CustomFieldDefinition","BeforeBulkCreate","BeforeBulkUpdate","BeforeUpdate","BeforeCreate","BeforeUpsert","AfterUpsert"],"sources":["../../src/models/CustomFieldValue.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n BelongsTo,\n ForeignKey,\n BeforeCreate,\n BeforeUpsert,\n AfterUpsert,\n BeforeUpdate,\n BeforeBulkCreate,\n BeforeBulkUpdate,\n} from 'sequelize-typescript';\nimport type { CreateOptions } from 'sequelize';\nimport { sendDimEvent } from '../events';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport { validateFieldType, validateValue } from '../utils/validations';\nimport * as CustomFieldDefinitionRepo from '../repository/definition';\nimport { InvalidFieldTypeError, InvalidValueError } from '../errors';\n\n@Table({\n tableName: 'custom_field_values',\n modelName: 'CustomFieldValue',\n timestamps: true,\n indexes: [\n {\n name: 'idx_custom_field_values_active_definition_id',\n fields: ['customFieldDefinitionId'],\n where: {\n deleted_at: null,\n },\n },\n ],\n})\nclass CustomFieldValue extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n modelId!: string;\n\n @PrimaryKey\n @ForeignKey(() => CustomFieldDefinition)\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n customFieldDefinitionId!: string;\n\n @Column({\n type: DataType.JSONB,\n allowNull: true,\n })\n value!: any;\n\n @Column({\n type: DataType.DATE,\n allowNull: false,\n })\n declare createdAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare updatedAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare deletedAt?: Date;\n\n @BelongsTo(() => CustomFieldDefinition, { scope: { disabled: false } })\n declare customFieldDefinition: CustomFieldDefinition;\n\n private static validateValueAgainstDefinition(\n instance: CustomFieldValue,\n definition: CustomFieldDefinition,\n ): void {\n const { validation, fieldType, name } = definition;\n const isValidFieldType = validateFieldType(fieldType);\n if (!isValidFieldType) {\n throw new InvalidFieldTypeError(fieldType);\n }\n // Always allow null values\n if (instance.value === null) return;\n const validateValueResponse = validateValue(instance.value, fieldType, validation);\n if (validateValueResponse.error) {\n throw new InvalidValueError(instance.value, name, validateValueResponse.error);\n }\n }\n\n @BeforeBulkCreate\n @BeforeBulkUpdate\n static async validateCustomFieldValues(instances: CustomFieldValue[]): Promise<void> {\n const ids = instances.map(instance => instance.customFieldDefinitionId);\n const uniqueIds = [...new Set(ids)];\n const definitions = await CustomFieldDefinitionRepo.findByIds(\n uniqueIds,\n { withDisabled: true },\n );\n\n if (!definitions || definitions.length !== uniqueIds.length) {\n throw new Error('Definitions not found');\n }\n\n instances.forEach((instance) => {\n const definition = definitions.find(d => d.id === instance.customFieldDefinitionId);\n if (definition) {\n this.validateValueAgainstDefinition(instance, definition);\n }\n });\n }\n\n @BeforeUpdate\n @BeforeCreate\n @BeforeUpsert\n static async validateCustomFieldValue(instance: CustomFieldValue): Promise<void> {\n const { customFieldDefinitionId } = instance;\n const cfd = await CustomFieldDefinitionRepo.findById(customFieldDefinitionId, { withDisabled: true });\n this.validateValueAgainstDefinition(instance, cfd!);\n }\n\n @AfterUpsert\n static afterSaveHandler(instance: CustomFieldValue[], options: CreateOptions): void {\n if (options.transaction) {\n options.transaction.afterCommit(() => sendDimEvent(instance[0]));\n } else {\n sendDimEvent(instance[0]);\n }\n }\n}\n\nexport default CustomFieldValue;\n"],"mappings":"ycAsBA,IAAA,EAAA,cAc+BC,EAAAA,KAAM,CA2CnC,OAAe,+BACb,EACA,EACM,CACN,GAAM,CAAE,aAAY,YAAW,QAAS,EAExC,GAAI,CADqBC,EAAAA,kBAAkB,EAAU,CAEnD,MAAM,IAAIC,EAAAA,sBAAsB,EAAU,CAG5C,GAAI,EAAS,QAAU,KAAM,OAC7B,IAAM,EAAwBC,EAAAA,cAAc,EAAS,MAAO,EAAW,EAAW,CAClF,GAAI,EAAsB,MACxB,MAAM,IAAIC,EAAAA,kBAAkB,EAAS,MAAO,EAAM,EAAsB,MAAM,CAIlF,aAEa,0BAA0B,EAA8C,CACnF,IAAM,EAAM,EAAU,IAAI,GAAY,EAAS,wBAAwB,CACjE,EAAY,CAAC,GAAG,IAAI,IAAI,EAAI,CAAC,CAC7B,EAAc,MAAA,EAAA,UAClB,EACA,CAAE,aAAc,GAAM,CACvB,CAED,GAAI,CAAC,GAAe,EAAY,SAA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EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,YAAA,IAAA,GAAA,mCAGeC,EAAAA,QAAuB,CAAE,MAAO,CAAE,SAAU,GAAO,CAAE,CAAC,CAAA,EAAA,mBAAA,cAAA,OAAA,EAAA,EAAA,UAAA,QAAA,EAAA,UAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,wBAAA,IAAA,GAAA,eAoBtEC,EAAAA,iBACAC,EAAAA,qNAqBAC,EAAAA,aACAC,EAAAA,aACAC,EAAAA,uPAOAC,EAAAA,2NAzGI,CACL,UAAW,sBACX,UAAW,mBACX,WAAY,GACZ,QAAS,CACP,CACE,KAAM,+CACN,OAAQ,CAAC,0BAA0B,CACnC,MAAO,CACL,WAAY,KACb,CACF,CACF,CACF,CAAC,CAAA,CAAA,EAAA,CAsGF,IAAA,EAAe"}
1
+ {"version":3,"file":"CustomFieldValue.cjs","names":["CustomFieldValue","Model","validateFieldType","InvalidFieldTypeError","validateValue","InvalidValueError","sendDimEvent","PrimaryKey","DataType","CustomFieldDefinition","BeforeBulkCreate","BeforeBulkUpdate","BeforeUpdate","BeforeCreate","BeforeUpsert","AfterUpsert"],"sources":["../../src/models/CustomFieldValue.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n BelongsTo,\n ForeignKey,\n BeforeCreate,\n BeforeUpsert,\n AfterUpsert,\n BeforeUpdate,\n BeforeBulkCreate,\n BeforeBulkUpdate,\n} from 'sequelize-typescript';\nimport type { CreateOptions } from 'sequelize';\nimport { sendDimEvent } from '../events';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport { validateFieldType, validateValue } from '../utils/validations';\nimport * as CustomFieldDefinitionRepo from '../repository/definition';\nimport { InvalidFieldTypeError, InvalidValueError } from '../errors';\n\n@Table({\n tableName: 'custom_field_values',\n modelName: 'CustomFieldValue',\n timestamps: true,\n})\nclass CustomFieldValue extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n modelId!: string;\n\n @PrimaryKey\n @ForeignKey(() => CustomFieldDefinition)\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n customFieldDefinitionId!: string;\n\n @Column({\n type: DataType.JSONB,\n allowNull: true,\n })\n value!: any;\n\n @Column({\n type: DataType.DATE,\n allowNull: false,\n })\n declare createdAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare updatedAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare deletedAt?: Date;\n\n @BelongsTo(() => CustomFieldDefinition, { scope: { disabled: false } })\n declare customFieldDefinition: CustomFieldDefinition;\n\n private static validateValueAgainstDefinition(\n instance: CustomFieldValue,\n definition: CustomFieldDefinition,\n ): void {\n const { validation, fieldType, name } = definition;\n const isValidFieldType = validateFieldType(fieldType);\n if (!isValidFieldType) {\n throw new InvalidFieldTypeError(fieldType);\n }\n // Always allow null values\n if (instance.value === null) return;\n const validateValueResponse = validateValue(instance.value, fieldType, validation);\n if (validateValueResponse.error) {\n throw new InvalidValueError(instance.value, name, validateValueResponse.error);\n }\n }\n\n @BeforeBulkCreate\n @BeforeBulkUpdate\n static async validateCustomFieldValues(instances: CustomFieldValue[]): Promise<void> {\n const ids = instances.map(instance => instance.customFieldDefinitionId);\n const uniqueIds = [...new Set(ids)];\n const definitions = await CustomFieldDefinitionRepo.findByIds(\n uniqueIds,\n { withDisabled: true },\n );\n\n if (!definitions || definitions.length !== uniqueIds.length) {\n throw new Error('Definitions not found');\n }\n\n instances.forEach((instance) => {\n const definition = definitions.find(d => d.id === instance.customFieldDefinitionId);\n if (definition) {\n this.validateValueAgainstDefinition(instance, definition);\n }\n });\n }\n\n @BeforeUpdate\n @BeforeCreate\n @BeforeUpsert\n static async validateCustomFieldValue(instance: CustomFieldValue): Promise<void> {\n const { customFieldDefinitionId } = instance;\n const cfd = await CustomFieldDefinitionRepo.findById(customFieldDefinitionId, { withDisabled: true });\n this.validateValueAgainstDefinition(instance, cfd!);\n }\n\n @AfterUpsert\n static afterSaveHandler(instance: CustomFieldValue[], options: CreateOptions): void {\n if (options.transaction) {\n options.transaction.afterCommit(() => sendDimEvent(instance[0]));\n } else {\n sendDimEvent(instance[0]);\n }\n }\n}\n\nexport default CustomFieldValue;\n"],"mappings":"ycAsBA,IAAA,EAAA,cAK+BC,EAAAA,KAAM,CA2CnC,OAAe,+BACb,EACA,EACM,CACN,GAAM,CAAE,aAAY,YAAW,QAAS,EAExC,GAAI,CADqBC,EAAAA,kBAAkB,EAAU,CAEnD,MAAM,IAAIC,EAAAA,sBAAsB,EAAU,CAG5C,GAAI,EAAS,QAAU,KAAM,OAC7B,IAAM,EAAwBC,EAAAA,cAAc,EAAS,MAAO,EAAW,EAAW,CAClF,GAAI,EAAsB,MACxB,MAAM,IAAIC,EAAAA,kBAAkB,EAAS,MAAO,EAAM,EAAsB,MAAM,CAIlF,aAEa,0BAA0B,EAA8C,CACnF,IAAM,EAAM,EAAU,IAAI,GAAY,EAAS,wBAAwB,CACjE,EAAY,CAAC,GAAG,IAAI,IAAI,EAAI,CAAC,CAC7B,EAAc,MAAA,EAAA,UAClB,EACA,CAAE,aAAc,GAAM,CACvB,CAED,GAAI,CAAC,GAAe,EAAY,SAAW,EAAU,OACnD,MAAU,MAAM,wBAAwB,CAG1C,EAAU,QAAS,GAAa,CAC9B,IAAM,EAAa,EAAY,KAAK,GAAK,EAAE,KAAO,EAAS,wBAAwB,CAC/E,GACF,KAAK,+BAA+B,EAAU,EAAW,EAE3D,CAGJ,aAGa,yBAAyB,EAA2C,CAC/E,GAAM,CAAE,2BAA4B,EAC9B,EAAM,MAAA,EAAA,SAAyC,EAAyB,CAAE,aAAc,GAAM,CAAC,CACrG,KAAK,+BAA+B,EAAU,EAAK,CAGrD,OACO,iBAAiB,EAA8B,EAA8B,CAC9E,EAAQ,YACV,EAAQ,YAAY,gBAAkBC,EAAAA,aAAa,EAAS,GAAG,CAAC,CAEhE,EAAA,aAAa,EAAS,GAAG,iBA/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e}from"../events/index.js";import{InvalidFieldTypeError as t,InvalidValueError as n}from"../errors/index.js";import{validateFieldType as r,validateValue as i}from"../utils/validations/index.js";import{findById as a,findByIds as o}from"../repository/definition.js";import{__decorateMetadata as s}from"../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js";import{__decorate as c}from"../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js";import l from"./CustomFieldDefinition.js";import{AfterUpsert as u,BeforeBulkCreate as d,BeforeBulkUpdate as f,BeforeCreate as p,BeforeUpdate as m,BeforeUpsert as h,BelongsTo as g,Column as _,DataType as v,ForeignKey as y,Model as b,PrimaryKey as x,Table as S}from"sequelize-typescript";var C,w,T,E,D;let O=class extends b{static validateValueAgainstDefinition(e,a){let{validation:o,fieldType:s,name:c}=a;if(!r(s))throw new t(s);if(e.value===null)return;let l=i(e.value,s,o);if(l.error)throw new n(e.value,c,l.error)}static async validateCustomFieldValues(e){let t=e.map(e=>e.customFieldDefinitionId),n=[...new Set(t)],r=await o(n,{withDisabled:!0});if(!r||r.length!==n.length)throw Error(`Definitions not found`);e.forEach(e=>{let t=r.find(t=>t.id===e.customFieldDefinitionId);t&&this.validateValueAgainstDefinition(e,t)})}static async validateCustomFieldValue(e){let{customFieldDefinitionId:t}=e,n=await a(t,{withDisabled:!0});this.validateValueAgainstDefinition(e,n)}static afterSaveHandler(t,n){n.transaction?n.transaction.afterCommit(()=>e(t[0])):e(t[0])}};c([x,_({type:v.UUID,allowNull:!1}),s(`design:type`,String)],O.prototype,`modelId`,void 0),c([x,y(()=>l),_({type:v.UUID,allowNull:!1}),s(`design:type`,String)],O.prototype,`customFieldDefinitionId`,void 0),c([_({type:v.JSONB,allowNull:!0}),s(`design:type`,Object)],O.prototype,`value`,void 0),c([_({type:v.DATE,allowNull:!1}),s(`design:type`,typeof(C=typeof Date<`u`&&Date)==`function`?C:Object)],O.prototype,`createdAt`,void 0),c([_({type:v.DATE,allowNull:!0}),s(`design:type`,typeof(w=typeof Date<`u`&&Date)==`function`?w:Object)],O.prototype,`updatedAt`,void 0),c([_({type:v.DATE,allowNull:!0}),s(`design:type`,typeof(T=typeof Date<`u`&&Date)==`function`?T:Object)],O.prototype,`deletedAt`,void 0),c([g(()=>l,{scope:{disabled:!1}}),s(`design:type`,typeof(E=l!==void 0&&l)==`function`?E:Object)],O.prototype,`customFieldDefinition`,void 0),c([d,f,s(`design:type`,Function),s(`design:paramtypes`,[Array]),s(`design:returntype`,Promise)],O,`validateCustomFieldValues`,null),c([m,p,h,s(`design:type`,Function),s(`design:paramtypes`,[typeof(D=O!==void 0&&O)==`function`?D:Object]),s(`design:returntype`,Promise)],O,`validateCustomFieldValue`,null),c([u,s(`design:type`,Function),s(`design:paramtypes`,[Array,Object]),s(`design:returntype`,void 0)],O,`afterSaveHandler`,null),O=c([S({tableName:`custom_field_values`,modelName:`CustomFieldValue`,timestamps:!0,indexes:[{name:`idx_custom_field_values_active_definition_id`,fields:[`customFieldDefinitionId`],where:{deleted_at:null}}]})],O);var k=O;export{k as default};
1
+ import{sendDimEvent as e}from"../events/index.js";import{InvalidFieldTypeError as t,InvalidValueError as n}from"../errors/index.js";import{validateFieldType as r,validateValue as i}from"../utils/validations/index.js";import{findById as a,findByIds as o}from"../repository/definition.js";import{__decorateMetadata as s}from"../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js";import{__decorate as c}from"../_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js";import l from"./CustomFieldDefinition.js";import{AfterUpsert as u,BeforeBulkCreate as d,BeforeBulkUpdate as f,BeforeCreate as p,BeforeUpdate as m,BeforeUpsert as h,BelongsTo as g,Column as _,DataType as v,ForeignKey as y,Model as b,PrimaryKey as x,Table as S}from"sequelize-typescript";var C,w,T,E,D;let O=class extends b{static validateValueAgainstDefinition(e,a){let{validation:o,fieldType:s,name:c}=a;if(!r(s))throw new t(s);if(e.value===null)return;let l=i(e.value,s,o);if(l.error)throw new n(e.value,c,l.error)}static async validateCustomFieldValues(e){let t=e.map(e=>e.customFieldDefinitionId),n=[...new Set(t)],r=await o(n,{withDisabled:!0});if(!r||r.length!==n.length)throw Error(`Definitions not found`);e.forEach(e=>{let t=r.find(t=>t.id===e.customFieldDefinitionId);t&&this.validateValueAgainstDefinition(e,t)})}static async validateCustomFieldValue(e){let{customFieldDefinitionId:t}=e,n=await a(t,{withDisabled:!0});this.validateValueAgainstDefinition(e,n)}static afterSaveHandler(t,n){n.transaction?n.transaction.afterCommit(()=>e(t[0])):e(t[0])}};c([x,_({type:v.UUID,allowNull:!1}),s(`design:type`,String)],O.prototype,`modelId`,void 0),c([x,y(()=>l),_({type:v.UUID,allowNull:!1}),s(`design:type`,String)],O.prototype,`customFieldDefinitionId`,void 0),c([_({type:v.JSONB,allowNull:!0}),s(`design:type`,Object)],O.prototype,`value`,void 0),c([_({type:v.DATE,allowNull:!1}),s(`design:type`,typeof(C=typeof Date<`u`&&Date)==`function`?C:Object)],O.prototype,`createdAt`,void 0),c([_({type:v.DATE,allowNull:!0}),s(`design:type`,typeof(w=typeof Date<`u`&&Date)==`function`?w:Object)],O.prototype,`updatedAt`,void 0),c([_({type:v.DATE,allowNull:!0}),s(`design:type`,typeof(T=typeof Date<`u`&&Date)==`function`?T:Object)],O.prototype,`deletedAt`,void 0),c([g(()=>l,{scope:{disabled:!1}}),s(`design:type`,typeof(E=l!==void 0&&l)==`function`?E:Object)],O.prototype,`customFieldDefinition`,void 0),c([d,f,s(`design:type`,Function),s(`design:paramtypes`,[Array]),s(`design:returntype`,Promise)],O,`validateCustomFieldValues`,null),c([m,p,h,s(`design:type`,Function),s(`design:paramtypes`,[typeof(D=O!==void 0&&O)==`function`?D:Object]),s(`design:returntype`,Promise)],O,`validateCustomFieldValue`,null),c([u,s(`design:type`,Function),s(`design:paramtypes`,[Array,Object]),s(`design:returntype`,void 0)],O,`afterSaveHandler`,null),O=c([S({tableName:`custom_field_values`,modelName:`CustomFieldValue`,timestamps:!0})],O);var k=O;export{k as default};
2
2
  //# sourceMappingURL=CustomFieldValue.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CustomFieldValue.js","names":["CustomFieldValue","CustomFieldDefinitionRepo.findByIds","CustomFieldDefinitionRepo.findById","CustomFieldDefinition"],"sources":["../../src/models/CustomFieldValue.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n BelongsTo,\n ForeignKey,\n BeforeCreate,\n BeforeUpsert,\n AfterUpsert,\n BeforeUpdate,\n BeforeBulkCreate,\n BeforeBulkUpdate,\n} from 'sequelize-typescript';\nimport type { CreateOptions } from 'sequelize';\nimport { sendDimEvent } from '../events';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport { validateFieldType, validateValue } from '../utils/validations';\nimport * as CustomFieldDefinitionRepo from '../repository/definition';\nimport { InvalidFieldTypeError, InvalidValueError } from '../errors';\n\n@Table({\n tableName: 'custom_field_values',\n modelName: 'CustomFieldValue',\n timestamps: true,\n indexes: [\n {\n name: 'idx_custom_field_values_active_definition_id',\n fields: ['customFieldDefinitionId'],\n where: {\n deleted_at: null,\n },\n },\n ],\n})\nclass CustomFieldValue extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n modelId!: string;\n\n @PrimaryKey\n @ForeignKey(() => CustomFieldDefinition)\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n customFieldDefinitionId!: string;\n\n @Column({\n type: DataType.JSONB,\n allowNull: true,\n })\n value!: any;\n\n @Column({\n type: DataType.DATE,\n allowNull: false,\n })\n declare createdAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare updatedAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare deletedAt?: Date;\n\n @BelongsTo(() => CustomFieldDefinition, { scope: { disabled: false } })\n declare customFieldDefinition: CustomFieldDefinition;\n\n private static validateValueAgainstDefinition(\n instance: CustomFieldValue,\n definition: CustomFieldDefinition,\n ): void {\n const { validation, fieldType, name } = definition;\n const isValidFieldType = validateFieldType(fieldType);\n if (!isValidFieldType) {\n throw new InvalidFieldTypeError(fieldType);\n }\n // Always allow null values\n if (instance.value === null) return;\n const validateValueResponse = validateValue(instance.value, fieldType, validation);\n if (validateValueResponse.error) {\n throw new InvalidValueError(instance.value, name, validateValueResponse.error);\n }\n }\n\n @BeforeBulkCreate\n @BeforeBulkUpdate\n static async validateCustomFieldValues(instances: CustomFieldValue[]): Promise<void> {\n const ids = instances.map(instance => instance.customFieldDefinitionId);\n const uniqueIds = [...new Set(ids)];\n const definitions = await CustomFieldDefinitionRepo.findByIds(\n uniqueIds,\n { withDisabled: true },\n );\n\n if (!definitions || definitions.length !== uniqueIds.length) {\n throw new Error('Definitions not found');\n }\n\n instances.forEach((instance) => {\n const definition = definitions.find(d => d.id === instance.customFieldDefinitionId);\n if (definition) {\n this.validateValueAgainstDefinition(instance, definition);\n }\n });\n }\n\n @BeforeUpdate\n @BeforeCreate\n @BeforeUpsert\n static async validateCustomFieldValue(instance: CustomFieldValue): Promise<void> {\n const { customFieldDefinitionId } = instance;\n const cfd = await CustomFieldDefinitionRepo.findById(customFieldDefinitionId, { withDisabled: true });\n this.validateValueAgainstDefinition(instance, cfd!);\n }\n\n @AfterUpsert\n static afterSaveHandler(instance: CustomFieldValue[], options: CreateOptions): void {\n if (options.transaction) {\n options.transaction.afterCommit(() => sendDimEvent(instance[0]));\n } else {\n sendDimEvent(instance[0]);\n }\n }\n}\n\nexport default CustomFieldValue;\n"],"mappings":"ixBAsBA,IAAA,EAAA,cAc+B,CAAM,CA2CnC,OAAe,+BACb,EACA,EACM,CACN,GAAM,CAAE,aAAY,YAAW,QAAS,EAExC,GAAI,CADqB,EAAkB,EAAU,CAEnD,MAAM,IAAI,EAAsB,EAAU,CAG5C,GAAI,EAAS,QAAU,KAAM,OAC7B,IAAM,EAAwB,EAAc,EAAS,MAAO,EAAW,EAAW,CAClF,GAAI,EAAsB,MACxB,MAAM,IAAI,EAAkB,EAAS,MAAO,EAAM,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AAA,UAAA,YAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,EAAA,OAAA,KAAA,KAAA,OAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,YAAA,IAAA,GAAA,IAGD,MAAgBA,EAAuB,CAAE,MAAO,CAAE,SAAU,GAAO,CAAE,CAAC,CAAA,EAAA,cAAA,OAAA,EAAA,IAAA,QAAA,IAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,wBAAA,IAAA,GAAA,IAoBtE,EACA,kIAqBA,EACA,EACA,wKAOA,iIAzGF,EAAM,CACL,UAAW,sBACX,UAAW,mBACX,WAAY,GACZ,QAAS,CACP,CACE,KAAM,+CACN,OAAQ,CAAC,0BAA0B,CACnC,MAAO,CACL,WAAY,KACb,CACF,CACF,CACF,CAAC,CAAA,CAAA,EAAA,CAsGF,IAAA,EAAe"}
1
+ {"version":3,"file":"CustomFieldValue.js","names":["CustomFieldValue","CustomFieldDefinitionRepo.findByIds","CustomFieldDefinitionRepo.findById","CustomFieldDefinition"],"sources":["../../src/models/CustomFieldValue.ts"],"sourcesContent":["import {\n Table,\n Column,\n Model,\n PrimaryKey,\n DataType,\n BelongsTo,\n ForeignKey,\n BeforeCreate,\n BeforeUpsert,\n AfterUpsert,\n BeforeUpdate,\n BeforeBulkCreate,\n BeforeBulkUpdate,\n} from 'sequelize-typescript';\nimport type { CreateOptions } from 'sequelize';\nimport { sendDimEvent } from '../events';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport { validateFieldType, validateValue } from '../utils/validations';\nimport * as CustomFieldDefinitionRepo from '../repository/definition';\nimport { InvalidFieldTypeError, InvalidValueError } from '../errors';\n\n@Table({\n tableName: 'custom_field_values',\n modelName: 'CustomFieldValue',\n timestamps: true,\n})\nclass CustomFieldValue extends Model {\n @PrimaryKey\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n modelId!: string;\n\n @PrimaryKey\n @ForeignKey(() => CustomFieldDefinition)\n @Column({\n type: DataType.UUID,\n allowNull: false,\n })\n customFieldDefinitionId!: string;\n\n @Column({\n type: DataType.JSONB,\n allowNull: true,\n })\n value!: any;\n\n @Column({\n type: DataType.DATE,\n allowNull: false,\n })\n declare createdAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare updatedAt?: Date;\n\n @Column({\n type: DataType.DATE,\n allowNull: true,\n })\n declare deletedAt?: Date;\n\n @BelongsTo(() => CustomFieldDefinition, { scope: { disabled: false } })\n declare customFieldDefinition: CustomFieldDefinition;\n\n private static validateValueAgainstDefinition(\n instance: CustomFieldValue,\n definition: CustomFieldDefinition,\n ): void {\n const { validation, fieldType, name } = definition;\n const isValidFieldType = validateFieldType(fieldType);\n if (!isValidFieldType) {\n throw new InvalidFieldTypeError(fieldType);\n }\n // Always allow null values\n if (instance.value === null) return;\n const validateValueResponse = validateValue(instance.value, fieldType, validation);\n if (validateValueResponse.error) {\n throw new InvalidValueError(instance.value, name, validateValueResponse.error);\n }\n }\n\n @BeforeBulkCreate\n @BeforeBulkUpdate\n static async validateCustomFieldValues(instances: CustomFieldValue[]): Promise<void> {\n const ids = instances.map(instance => instance.customFieldDefinitionId);\n const uniqueIds = [...new Set(ids)];\n const definitions = await CustomFieldDefinitionRepo.findByIds(\n uniqueIds,\n { withDisabled: true },\n );\n\n if (!definitions || definitions.length !== uniqueIds.length) {\n throw new Error('Definitions not found');\n }\n\n instances.forEach((instance) => {\n const definition = definitions.find(d => d.id === instance.customFieldDefinitionId);\n if (definition) {\n this.validateValueAgainstDefinition(instance, definition);\n }\n });\n }\n\n @BeforeUpdate\n @BeforeCreate\n @BeforeUpsert\n static async validateCustomFieldValue(instance: CustomFieldValue): Promise<void> {\n const { customFieldDefinitionId } = instance;\n const cfd = await CustomFieldDefinitionRepo.findById(customFieldDefinitionId, { withDisabled: true });\n this.validateValueAgainstDefinition(instance, cfd!);\n }\n\n @AfterUpsert\n static afterSaveHandler(instance: CustomFieldValue[], options: CreateOptions): void {\n if (options.transaction) {\n options.transaction.afterCommit(() => sendDimEvent(instance[0]));\n } else {\n sendDimEvent(instance[0]);\n }\n }\n}\n\nexport default CustomFieldValue;\n"],"mappings":"ixBAsBA,IAAA,EAAA,cAK+B,CAAM,CA2CnC,OAAe,+BACb,EACA,EACM,CACN,GAAM,CAAE,aAAY,YAAW,QAAS,EAExC,GAAI,CADqB,EAAkB,EAAU,CAEnD,MAAM,IAAI,EAAsB,EAAU,CAG5C,GAAI,EAAS,QAAU,KAAM,OAC7B,IAAM,EAAwB,EAAc,EAAS,MAAO,EAAW,EAAW,CAClF,GAAI,EAAsB,MACxB,MAAM,IAAI,EAAkB,EAAS,MAAO,EAAM,EAAsB,MAAM,CAIlF,aAEa,0BAA0B,EAA8C,CACnF,IAAM,EAAM,EAAU,IAAI,GAAY,EAAS,wBAAwB,CACjE,EAAY,CAAC,GAAG,IAAI,IAAI,EAAI,CAAC,CAC7B,EAAc,MAAMC,EACxB,EACA,CAAE,aAAc,GAAM,CACvB,CAED,GAAI,CAAC,GAAe,EAAY,SAAW,EAAU,OACnD,MAAU,MAAM,wBAAwB,CAG1C,EAAU,QAAS,GAAa,CAC9B,IAAM,EAAa,EAAY,KAAK,GAAK,EAAE,KAAO,EAAS,wBAAwB,CAC/E,GACF,KAAK,+BAA+B,EAAU,EAAW,EAE3D,CAGJ,aAGa,yBAAyB,EAA2C,CAC/E,GAAM,CAAE,2BAA4B,EAC9B,EAAM,MAAMC,EAAmC,EAAyB,CAAE,aAAc,GAAM,CAAC,CACrG,KAAK,+BAA+B,EAAU,EAAK,CAGrD,OACO,iBAAiB,EAA8B,EAA8B,CAC9E,EAAQ,YACV,EAAQ,YAAY,gBAAkB,EAAa,EAAS,GAAG,CAAC,CAEhE,EAAa,EAAS,GAAG,MA/F5B,EACA,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,2DAGD,EACA,MAAiBC,EAAsB,CACvC,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,2EAGD,EAAO,CACN,KAAM,EAAS,MACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,CAAA,CAAA,EAAA,UAAA,QAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,EAAA,OAAA,KAAA,KAAA,OAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,YAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,EAAA,OAAA,KAAA,KAAA,OAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,YAAA,IAAA,GAAA,IAGD,EAAO,CACN,KAAM,EAAS,KACf,UAAW,GACZ,CAAC,CAAA,EAAA,cAAA,OAAA,EAAA,OAAA,KAAA,KAAA,OAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,YAAA,IAAA,GAAA,IAGD,MAAgBA,EAAuB,CAAE,MAAO,CAAE,SAAU,GAAO,CAAE,CAAC,CAAA,EAAA,cAAA,OAAA,EAAA,IAAA,QAAA,IAAA,WAAA,EAAA,OAAA,CAAA,CAAA,EAAA,UAAA,wBAAA,IAAA,GAAA,IAoBtE,EACA,kIAqBA,EACA,EACA,wKAOA,iIAhGF,EAAM,CACL,UAAW,sBACX,UAAW,mBACX,WAAY,GACb,CAAC,CAAA,CAAA,EAAA,CAsGF,IAAA,EAAe"}
@@ -1,2 +1,2 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`);let d=require(`sequelize`);const f=[a.default,i.default,s.default,o.default],p=`sadot-migration`,m=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,h=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1}={})=>{let p=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let m=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];e.addModels(m),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`);let h=e.define(`SequelizeMeta`,{name:{type:d.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let g=await h.findAll({where:{name:{[d.Op.like]:`${a}%`}},raw:!0}),_=g.at(-1),v=g.findIndex(e=>e.name===p);if(t.default.info(`custom-fields: migrations`,{migrations:g,currentSadotSchemaVersion:_,expectedSchemaVersionIndex:v}),(!_||_.name!==p)&&(t.default.info(`custom-fields: syncing models`),await r.default.sync({alter:!0}),await n.default.sync({alter:!0}),await l.default.sync({alter:!0}),s&&await c.default.sync({alter:!0}),f&&await u.default.sync({alter:!0}),v===-1&&await h.create({name:p}),t.default.info(`custom-fields: models synced`),g.length&&v!==-1&&v<g.length-1)){let e=g.slice(v+1);await h.destroy({where:{name:{[d.Op.in]:e.map(e=>e.name)}}})}},g=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(f),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=h,exports.initTestModels=g;
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`);let d=require(`sequelize`);const f=[a.default,i.default,s.default,o.default],p=`sadot-migration`,m=`49c9dd1d-b1cc-445b-a911-fd349d783110`,h=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`49c9dd1d-b1cc-445b-a911-fd349d783110`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1}={})=>{let p=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let m=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];e.addModels(m),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`);let h=e.define(`SequelizeMeta`,{name:{type:d.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let g=await h.findAll({where:{name:{[d.Op.like]:`${a}%`}},raw:!0}),_=g.at(-1),v=g.findIndex(e=>e.name===p);if(t.default.info(`custom-fields: migrations`,{migrations:g,currentSadotSchemaVersion:_,expectedSchemaVersionIndex:v}),(!_||_.name!==p)&&(t.default.info(`custom-fields: syncing models`),await r.default.sync({alter:!0}),await n.default.sync({alter:!0}),await l.default.sync({alter:!0}),s&&await c.default.sync({alter:!0}),f&&await u.default.sync({alter:!0}),v===-1&&await h.create({name:p}),t.default.info(`custom-fields: models synced`),g.length&&v!==-1&&v<g.length-1)){let e=g.slice(v+1);await h.destroy({where:{name:{[d.Op.in]:e.map(e=>e.name)}}})}},g=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(f),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=h,exports.initTestModels=g;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', { migrations, currentSadotSchemaVersion, expectedSchemaVersionIndex });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n await CustomFieldDefinition.sync({ alter: true });\n await CustomFieldValue.sync({ alter: true });\n await CustomValidator.sync({ alter: true });\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n }\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n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AAAA,GAAG,IAAK,EAAmB,IAAI,GAAM,EAAU,KAAK,CAAE,CAAE,CAAE,CAAC,GAK3G,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAA,QAAO,KAAK,sDAAsD,CAE9D,CAACR,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAMA,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAMA,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAA,QAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAAA,QAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAAA,QAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAAA,QAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAAA,QAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
1
+ {"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '49c9dd1d-b1cc-445b-a911-fd349d783110';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', { migrations, currentSadotSchemaVersion, expectedSchemaVersionIndex });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n await CustomFieldDefinition.sync({ alter: true });\n await CustomFieldValue.sync({ alter: true });\n await CustomValidator.sync({ alter: true });\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n }\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"sgBAsBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAEjB,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,IACD,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAA,QAAO,KAAK,iDAAiD,CAEzD,CAACC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EAAAA,QACAC,EAAAA,QACAC,EAAAA,QACA,GAAI,EAAyB,CAACC,EAAAA,QAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAAA,QAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,I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,EAAA,QAAO,KAAK,oCAAoC"}
@@ -1,2 +1,2 @@
1
- import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{DataTypes as u,Op as d}from"sequelize";const f=[i,r,o,a],p=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:f=!1,useModelTypeMapping:p=!1}={})=>{let m=`${a}_${o}${f?`_withEntries`:``}${p?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let h=[n,t,c,...f?[s]:[],...p?[l]:[]];r.addModels(h),p&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`);let g=r.define(`SequelizeMeta`,{name:{type:u.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let _=await g.findAll({where:{name:{[d.like]:`${a}%`}},raw:!0}),v=_.at(-1),y=_.findIndex(e=>e.name===m);if(e.info(`custom-fields: migrations`,{migrations:_,currentSadotSchemaVersion:v,expectedSchemaVersionIndex:y}),(!v||v.name!==m)&&(e.info(`custom-fields: syncing models`),await n.sync({alter:!0}),await t.sync({alter:!0}),await c.sync({alter:!0}),f&&await s.sync({alter:!0}),p&&await l.sync({alter:!0}),y===-1&&await g.create({name:m}),e.info(`custom-fields: models synced`),_.length&&y!==-1&&y<_.length-1)){let e=_.slice(y+1);await g.destroy({where:{name:{[d.in]:e.map(e=>e.name)}}})}},m=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(f),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{p as initTables,m as initTestModels};
1
+ import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{DataTypes as u,Op as d}from"sequelize";const f=[i,r,o,a],p=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`49c9dd1d-b1cc-445b-a911-fd349d783110`,useCustomFieldsEntries:f=!1,useModelTypeMapping:p=!1}={})=>{let m=`${a}_${o}${f?`_withEntries`:``}${p?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let h=[n,t,c,...f?[s]:[],...p?[l]:[]];r.addModels(h),p&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`);let g=r.define(`SequelizeMeta`,{name:{type:u.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let _=await g.findAll({where:{name:{[d.like]:`${a}%`}},raw:!0}),v=_.at(-1),y=_.findIndex(e=>e.name===m);if(e.info(`custom-fields: migrations`,{migrations:_,currentSadotSchemaVersion:v,expectedSchemaVersionIndex:y}),(!v||v.name!==m)&&(e.info(`custom-fields: syncing models`),await n.sync({alter:!0}),await t.sync({alter:!0}),await c.sync({alter:!0}),f&&await s.sync({alter:!0}),p&&await l.sync({alter:!0}),y===-1&&await g.create({name:m}),e.info(`custom-fields: models synced`),_.length&&y!==-1&&y<_.length-1)){let e=_.slice(y+1);await g.destroy({where:{name:{[d.in]:e.map(e=>e.name)}}})}},m=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(f),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{p as initTables,m as initTestModels};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', { migrations, currentSadotSchemaVersion, expectedSchemaVersionIndex });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n await CustomFieldDefinition.sync({ alter: true });\n await CustomFieldValue.sync({ alter: true });\n await CustomValidator.sync({ alter: true });\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n }\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"+eAsBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,IACD,EAAE,GACP,CAClB,IAA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AoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
1
+ {"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '49c9dd1d-b1cc-445b-a911-fd349d783110';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', { migrations, currentSadotSchemaVersion, expectedSchemaVersionIndex });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n await CustomFieldDefinition.sync({ alter: true });\n await CustomFieldValue.sync({ alter: true });\n await CustomValidator.sync({ alter: true });\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n }\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"+eAsBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAKtF,EAAa,MACjB,EACA,EACA,CACE,eAAe,kBACf,gBAAgB,uCAChB,yBAAyB,GACzB,sBAAsB,IACD,EAAE,GACP,CAClB,IAAM,EAA+B,GAAG,EAAa,GAAG,IAAgB,EAAyB,eAAiB,KAAK,EAAsB,mBAAqB,KAGlK,GAFA,EAAO,KAAK,iDAAiD,CAEzD,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAEpE,IAAMC,EAAsC,CAC1CC,EACAC,EACAC,EACA,GAAI,EAAyB,CAACC,EAAmB,CAAG,EAAE,CACtD,GAAI,EAAsB,CAACC,EAAwB,CAAG,EAAE,CACzD,CAED,EAAU,UAAU,EAAiB,CAGjC,IACF,EAAsB,QAAQA,EAAyB,CACrD,WAAY,0BACZ,GAAI,oBACL,CAAC,CACF,EAAwB,UAAUJ,EAAuB,CACvD,WAAY,0BACZ,GAAI,wBACL,CAAC,EAGJ,EAAsB,SAAS,gBAAmB,CAChD,IAAM,EAAO,GAAS,CAItB,OAHK,GAAM,YAGJ,CACL,MAAO,CACL,SAAU,CACR,GAAG,OAAO,KAAK,EAAK,YAAY,OAAO,CACvC,GAAG,OAAO,KAAK,EAAK,YAAY,eAAe,CAC/C,GAAG,OAAO,KAAK,EAAK,YAAY,cAAc,CAC/C,CACF,CACF,CAVQ,EAAE,EAWX,CAEF,EAAgB,SAAS,gBAAmB,CAC1C,IAAM,EAAO,GAAS,CAItB,OAHK,GAAM,YAGJ,CACL,MAAO,CACL,SAAU,CACR,GAAG,OAAO,KAAK,EAAK,YAAY,OAAO,CACvC,GAAG,OAAO,KAAK,EAAK,YAAY,eAAe,CAC/C,GAAG,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B,KAAO,IAAwC,CAGpE,GAFA,EAAO,KAAK,sDAAsD,CAE9D,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAM,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAM,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAO,KAAK,mCAAmC,CAC/C,MAAMT,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
@@ -1,2 +1,2 @@
1
- const e=require(`../../_virtual/rolldown_runtime.cjs`),t=require(`../constants/index.cjs`);let n=require(`sequelize`),r=require(`sequelize-typescript`),i=require(`node:crypto`);const a=(e=5)=>Array.from({length:e},()=>`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.charAt((0,i.randomInt)(52))).join(``),o=(e,i,a,o=[t.CustomFieldDefinitionType.DATETIME,t.CustomFieldDefinitionType.DATE])=>{let s=o.map(e=>`'${e}'`).join(`,`),c=`SELECT cv.model_id FROM "custom_field_values" AS cv INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id AND cd.entity_id = '${a}' AND cd.model_type = '${i.name}' AND cd.deleted_at IS NULL`+(s?` AND cd.field_type NOT IN (${s})`:``)+` WHERE cv.deleted_at IS NULL AND CAST(cv.value AS TEXT) ILIKE :searchTerm`;return{where:{id:{[n.Op.in]:r.Sequelize.literal(`(${c})`)}},replacements:{searchTerm:`%${e}%`}}};exports.generateCustomFieldSearchQueryPayload=o,exports.generateRandomString=a;
1
+ const e=require(`../../_virtual/rolldown_runtime.cjs`),t=require(`../constants/index.cjs`);let n=require(`sequelize`),r=require(`sequelize-typescript`),i=require(`node:crypto`);const a=(e=5)=>Array.from({length:e},()=>`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.charAt((0,i.randomInt)(52))).join(``),o=(e,i,a,o=[t.CustomFieldDefinitionType.DATETIME,t.CustomFieldDefinitionType.DATE])=>{let s=o.map(e=>`'${e}'`).join(`,`),c=`EXISTS ( SELECT 1 FROM "custom_field_values" AS "cv" INNER JOIN custom_field_definitions AS cd ON cd.entity_id = '${a}' AND cv.custom_field_definition_id = cd.id AND cd.model_type = '${i.name}' ${s?`AND cd.field_type NOT IN (${s})`:``} WHERE "cv"."deleted_at" IS NULL AND "cv"."model_id" = "${i.name}"."id" AND CAST("cv"."value" AS TEXT) ILIKE :searchTerm)`;return{where:{[n.Op.or]:[r.Sequelize.where(r.Sequelize.literal(c),!0)]},replacements:{searchTerm:`%${e}%`}}};exports.generateCustomFieldSearchQueryPayload=o,exports.generateRandomString=a;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["CustomFieldDefinitionType","Op","Sequelize"],"sources":["../../../src/utils/helpers/index.ts"],"sourcesContent":["import { type WhereOptions, Op, type BindOrReplacements } from 'sequelize';\nimport { type ModelStatic, Sequelize } from 'sequelize-typescript';\nimport { randomInt } from 'node:crypto';\nimport { CustomFieldDefinitionType } from '../constants';\n\n/**\n * Builds a WHERE clause and replacements for free-text search by custom fields.\n *\n * This function constructs a WHERE clause and replacement bindings that allow searching\n * for a given term within custom fields associated with a specific model type and entity ID.\n * The WHERE clause and replacements are designed to be added to the main query.\n *\n * @param {string} searchTerm - The term to search for within custom fields.\n * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.\n * @param {string} entityId - The entity ID to filter the custom fields by.\n * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types\n * to exclude from the search\n *\n * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements\n * for Sequelize.\n */\n\ninterface CustomFieldsSearchPayload {\n where: WhereOptions;\n replacements: BindOrReplacements;\n}\n\nexport const generateRandomString = (length = 5): string => {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n return Array.from({ length }, () => characters.charAt(randomInt(characters.length))).join('');\n};\n\nexport const generateCustomFieldSearchQueryPayload = (\n searchTerm: string,\n model: ModelStatic,\n entityId: string,\n customFieldsTypesToExclude: CustomFieldDefinitionType[] = [\n CustomFieldDefinitionType.DATETIME,\n CustomFieldDefinitionType.DATE,\n ],\n): CustomFieldsSearchPayload => {\n const excludedTypesString = customFieldsTypesToExclude.map(type => `'${type}'`).join(',');\n\n const subQuery = 'SELECT cv.model_id'\n + ' FROM \"custom_field_values\" AS cv'\n + ' INNER JOIN custom_field_definitions AS cd'\n + ' ON cv.custom_field_definition_id = cd.id'\n + ` AND cd.entity_id = '${entityId}'`\n + ` AND cd.model_type = '${model.name}'`\n + ` AND cd.deleted_at IS NULL`\n + (excludedTypesString ? ` AND cd.field_type NOT IN (${excludedTypesString})` : '')\n + ' WHERE cv.deleted_at IS NULL'\n + ' AND CAST(cv.value AS TEXT) ILIKE :searchTerm';\n\n return {\n where: {\n id: {\n [Op.in]: Sequelize.literal(`(${subQuery})`),\n },\n },\n replacements: { searchTerm: `%${searchTerm}%` },\n };\n};\n"],"mappings":"iLA2BA,MAAa,GAAwB,EAAS,IAErC,MAAM,KAAK,CAAE,SAAQ,KAAQ,uDAAW,QAAA,EAAA,EAAA,WAAiB,GAAkB,CAAC,CAAC,CAAC,KAAK,GAAG,CAGlF,GACX,EACA,EACA,EACA,EAA0D,CACxDA,EAAAA,0BAA0B,SAC1BA,EAAAA,0BAA0B,KAC3B,GAC6B,CAC9B,IAAM,EAAsB,EAA2B,IAAI,GAAQ,IAAI,EAAK,GAAG,CAAC,KAAK,IAAI,CAEnF,EAAW,8JAIW,EAAS,yBACR,EAAM,KAAK,8BAEnC,EAAsB,8BAA8B,EAAoB,GAAK,IAC9E,4EAGJ,MAAO,CACL,MAAO,CACL,GAAI,EACDC,EAAAA,GAAG,IAAKC,EAAAA,UAAU,QAAQ,IAAI,EAAS,GAAG,CAC5C,CACF,CACD,aAAc,CAAE,WAAY,IAAI,EAAW,GAAI,CAChD"}
1
+ {"version":3,"file":"index.cjs","names":["CustomFieldDefinitionType","Op","Sequelize"],"sources":["../../../src/utils/helpers/index.ts"],"sourcesContent":["import { type WhereOptions, Op, type BindOrReplacements } from 'sequelize';\nimport { type ModelStatic, Sequelize } from 'sequelize-typescript';\nimport { randomInt } from 'node:crypto';\nimport { CustomFieldDefinitionType } from '../constants';\n\n/**\n * Builds a WHERE clause and replacements for free-text search by custom fields.\n *\n * This function constructs a WHERE clause and replacement bindings that allow searching\n * for a given term within custom fields associated with a specific model type and entity ID.\n * The WHERE clause and replacements are designed to be added to the main query.\n *\n * @param {string} searchTerm - The term to search for within custom fields.\n * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.\n * @param {string} entityId - The entity ID to filter the custom fields by.\n * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types\n * to exclude from the search\n *\n * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements\n * for Sequelize.\n */\n\ninterface CustomFieldsSearchPayload {\n where: WhereOptions;\n replacements: BindOrReplacements;\n}\n\nexport const generateRandomString = (length = 5): string => {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n return Array.from({ length }, () => characters.charAt(randomInt(characters.length))).join('');\n};\n\nexport const generateCustomFieldSearchQueryPayload = (\n searchTerm: string,\n model: ModelStatic,\n entityId: string,\n customFieldsTypesToExclude: CustomFieldDefinitionType[] = [\n CustomFieldDefinitionType.DATETIME,\n CustomFieldDefinitionType.DATE,\n ],\n): CustomFieldsSearchPayload => {\n const excludedTypesString = customFieldsTypesToExclude.map(type => `'${type}'`).join(',');\n\n const subQuery = 'EXISTS ('\n + ' SELECT 1'\n + ' FROM \"custom_field_values\" AS \"cv\"'\n + ' INNER JOIN custom_field_definitions AS cd '\n + ` ON cd.entity_id = '${entityId}'`\n + ' AND cv.custom_field_definition_id = cd.id'\n + ` AND cd.model_type = '${model.name}'`\n + ` ${excludedTypesString ? `AND cd.field_type NOT IN (${excludedTypesString})` : ''}`\n + ' WHERE'\n + ' \"cv\".\"deleted_at\" IS NULL'\n + ` AND \"cv\".\"model_id\" = \"${model.name}\".\"id\"`\n + ' AND CAST(\"cv\".\"value\" AS TEXT) ILIKE :searchTerm)';\n\n return {\n where: {\n [Op.or]: [\n Sequelize.where(Sequelize.literal(subQuery), true),\n ],\n },\n replacements: { searchTerm: `%${searchTerm}%` },\n };\n};\n"],"mappings":"iLA2BA,MAAa,GAAwB,EAAS,IAErC,MAAM,KAAK,CAAE,SAAQ,KAAQ,uDAAW,QAAA,EAAA,EAAA,WAAiB,GAAkB,CAAC,CAAC,CAAC,KAAK,GAAG,CAGlF,GACX,EACA,EACA,EACA,EAA0D,CACxDA,EAAAA,0BAA0B,SAC1BA,EAAAA,0BAA0B,KAC3B,GAC6B,CAC9B,IAAM,EAAsB,EAA2B,IAAI,GAAQ,IAAI,EAAK,GAAG,CAAC,KAAK,IAAI,CAEnF,EAAW,sHAIU,EAAS,mEAEP,EAAM,KAAK,IAChC,EAAsB,6BAA6B,EAAoB,GAAK,GAAA,0DAGrD,EAAM,KAAK,0DAG1C,MAAO,CACL,MAAO,EACJC,EAAAA,GAAG,IAAK,CACPC,EAAAA,UAAU,MAAMA,EAAAA,UAAU,QAAQ,EAAS,CAAE,GAAK,CACnD,CACF,CACD,aAAc,CAAE,WAAY,IAAI,EAAW,GAAI,CAChD"}
@@ -1,2 +1,2 @@
1
- import{CustomFieldDefinitionType as e}from"../constants/index.js";import{Op as t}from"sequelize";import{Sequelize as n}from"sequelize-typescript";import{randomInt as r}from"node:crypto";const i=(e=5)=>Array.from({length:e},()=>`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.charAt(r(52))).join(``),a=(r,i,a,o=[e.DATETIME,e.DATE])=>{let s=o.map(e=>`'${e}'`).join(`,`),c=`SELECT cv.model_id FROM "custom_field_values" AS cv INNER JOIN custom_field_definitions AS cd ON cv.custom_field_definition_id = cd.id AND cd.entity_id = '${a}' AND cd.model_type = '${i.name}' AND cd.deleted_at IS NULL`+(s?` AND cd.field_type NOT IN (${s})`:``)+` WHERE cv.deleted_at IS NULL AND CAST(cv.value AS TEXT) ILIKE :searchTerm`;return{where:{id:{[t.in]:n.literal(`(${c})`)}},replacements:{searchTerm:`%${r}%`}}};export{a as generateCustomFieldSearchQueryPayload,i as generateRandomString};
1
+ import{CustomFieldDefinitionType as e}from"../constants/index.js";import{Op as t}from"sequelize";import{Sequelize as n}from"sequelize-typescript";import{randomInt as r}from"node:crypto";const i=(e=5)=>Array.from({length:e},()=>`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`.charAt(r(52))).join(``),a=(r,i,a,o=[e.DATETIME,e.DATE])=>{let s=o.map(e=>`'${e}'`).join(`,`),c=`EXISTS ( SELECT 1 FROM "custom_field_values" AS "cv" INNER JOIN custom_field_definitions AS cd ON cd.entity_id = '${a}' AND cv.custom_field_definition_id = cd.id AND cd.model_type = '${i.name}' ${s?`AND cd.field_type NOT IN (${s})`:``} WHERE "cv"."deleted_at" IS NULL AND "cv"."model_id" = "${i.name}"."id" AND CAST("cv"."value" AS TEXT) ILIKE :searchTerm)`;return{where:{[t.or]:[n.where(n.literal(c),!0)]},replacements:{searchTerm:`%${r}%`}}};export{a as generateCustomFieldSearchQueryPayload,i as generateRandomString};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/utils/helpers/index.ts"],"sourcesContent":["import { type WhereOptions, Op, type BindOrReplacements } from 'sequelize';\nimport { type ModelStatic, Sequelize } from 'sequelize-typescript';\nimport { randomInt } from 'node:crypto';\nimport { CustomFieldDefinitionType } from '../constants';\n\n/**\n * Builds a WHERE clause and replacements for free-text search by custom fields.\n *\n * This function constructs a WHERE clause and replacement bindings that allow searching\n * for a given term within custom fields associated with a specific model type and entity ID.\n * The WHERE clause and replacements are designed to be added to the main query.\n *\n * @param {string} searchTerm - The term to search for within custom fields.\n * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.\n * @param {string} entityId - The entity ID to filter the custom fields by.\n * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types\n * to exclude from the search\n *\n * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements\n * for Sequelize.\n */\n\ninterface CustomFieldsSearchPayload {\n where: WhereOptions;\n replacements: BindOrReplacements;\n}\n\nexport const generateRandomString = (length = 5): string => {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n return Array.from({ length }, () => characters.charAt(randomInt(characters.length))).join('');\n};\n\nexport const generateCustomFieldSearchQueryPayload = (\n searchTerm: string,\n model: ModelStatic,\n entityId: string,\n customFieldsTypesToExclude: CustomFieldDefinitionType[] = [\n CustomFieldDefinitionType.DATETIME,\n CustomFieldDefinitionType.DATE,\n ],\n): CustomFieldsSearchPayload => {\n const excludedTypesString = customFieldsTypesToExclude.map(type => `'${type}'`).join(',');\n\n const subQuery = 'SELECT cv.model_id'\n + ' FROM \"custom_field_values\" AS cv'\n + ' INNER JOIN custom_field_definitions AS cd'\n + ' ON cv.custom_field_definition_id = cd.id'\n + ` AND cd.entity_id = '${entityId}'`\n + ` AND cd.model_type = '${model.name}'`\n + ` AND cd.deleted_at IS NULL`\n + (excludedTypesString ? ` AND cd.field_type NOT IN (${excludedTypesString})` : '')\n + ' WHERE cv.deleted_at IS NULL'\n + ' AND CAST(cv.value AS TEXT) ILIKE :searchTerm';\n\n return {\n where: {\n id: {\n [Op.in]: Sequelize.literal(`(${subQuery})`),\n },\n },\n replacements: { searchTerm: `%${searchTerm}%` },\n };\n};\n"],"mappings":"0LA2BA,MAAa,GAAwB,EAAS,IAErC,MAAM,KAAK,CAAE,SAAQ,KAAQ,uDAAW,OAAO,EAAU,GAAkB,CAAC,CAAC,CAAC,KAAK,GAAG,CAGlF,GACX,EACA,EACA,EACA,EAA0D,CACxD,EAA0B,SAC1B,EAA0B,KAC3B,GAC6B,CAC9B,IAAM,EAAsB,EAA2B,IAAI,GAAQ,IAAI,EAAK,GAAG,CAAC,KAAK,IAAI,CAEnF,EAAW,8JAIW,EAAS,yBACR,EAAM,KAAK,8BAEnC,EAAsB,8BAA8B,EAAoB,GAAK,IAC9E,4EAGJ,MAAO,CACL,MAAO,CACL,GAAI,EACD,EAAG,IAAK,EAAU,QAAQ,IAAI,EAAS,GAAG,CAC5C,CACF,CACD,aAAc,CAAE,WAAY,IAAI,EAAW,GAAI,CAChD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/utils/helpers/index.ts"],"sourcesContent":["import { type WhereOptions, Op, type BindOrReplacements } from 'sequelize';\nimport { type ModelStatic, Sequelize } from 'sequelize-typescript';\nimport { randomInt } from 'node:crypto';\nimport { CustomFieldDefinitionType } from '../constants';\n\n/**\n * Builds a WHERE clause and replacements for free-text search by custom fields.\n *\n * This function constructs a WHERE clause and replacement bindings that allow searching\n * for a given term within custom fields associated with a specific model type and entity ID.\n * The WHERE clause and replacements are designed to be added to the main query.\n *\n * @param {string} searchTerm - The term to search for within custom fields.\n * @param {ModelStatic} model - The Sequelize model representing the entity type to search for.\n * @param {string} entityId - The entity ID to filter the custom fields by.\n * @param {CustomFieldDefinitionType[]} excludedCustomFieldsTypes - An array of custom field types\n * to exclude from the search\n *\n * @returns {CustomFieldsSearchPayload} - An object containing the WHERE clause and replacements\n * for Sequelize.\n */\n\ninterface CustomFieldsSearchPayload {\n where: WhereOptions;\n replacements: BindOrReplacements;\n}\n\nexport const generateRandomString = (length = 5): string => {\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n return Array.from({ length }, () => characters.charAt(randomInt(characters.length))).join('');\n};\n\nexport const generateCustomFieldSearchQueryPayload = (\n searchTerm: string,\n model: ModelStatic,\n entityId: string,\n customFieldsTypesToExclude: CustomFieldDefinitionType[] = [\n CustomFieldDefinitionType.DATETIME,\n CustomFieldDefinitionType.DATE,\n ],\n): CustomFieldsSearchPayload => {\n const excludedTypesString = customFieldsTypesToExclude.map(type => `'${type}'`).join(',');\n\n const subQuery = 'EXISTS ('\n + ' SELECT 1'\n + ' FROM \"custom_field_values\" AS \"cv\"'\n + ' INNER JOIN custom_field_definitions AS cd '\n + ` ON cd.entity_id = '${entityId}'`\n + ' AND cv.custom_field_definition_id = cd.id'\n + ` AND cd.model_type = '${model.name}'`\n + ` ${excludedTypesString ? `AND cd.field_type NOT IN (${excludedTypesString})` : ''}`\n + ' WHERE'\n + ' \"cv\".\"deleted_at\" IS NULL'\n + ` AND \"cv\".\"model_id\" = \"${model.name}\".\"id\"`\n + ' AND CAST(\"cv\".\"value\" AS TEXT) ILIKE :searchTerm)';\n\n return {\n where: {\n [Op.or]: [\n Sequelize.where(Sequelize.literal(subQuery), true),\n ],\n },\n replacements: { searchTerm: `%${searchTerm}%` },\n };\n};\n"],"mappings":"0LA2BA,MAAa,GAAwB,EAAS,IAErC,MAAM,KAAK,CAAE,SAAQ,KAAQ,uDAAW,OAAO,EAAU,GAAkB,CAAC,CAAC,CAAC,KAAK,GAAG,CAGlF,GACX,EACA,EACA,EACA,EAA0D,CACxD,EAA0B,SAC1B,EAA0B,KAC3B,GAC6B,CAC9B,IAAM,EAAsB,EAA2B,IAAI,GAAQ,IAAI,EAAK,GAAG,CAAC,KAAK,IAAI,CAEnF,EAAW,sHAIU,EAAS,mEAEP,EAAM,KAAK,IAChC,EAAsB,6BAA6B,EAAoB,GAAK,GAAA,0DAGrD,EAAM,KAAK,0DAG1C,MAAO,CACL,MAAO,EACJ,EAAG,IAAK,CACP,EAAU,MAAM,EAAU,QAAQ,EAAS,CAAE,GAAK,CACnD,CACF,CACD,aAAc,CAAE,WAAY,IAAI,EAAW,GAAI,CAChD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/sadot",
3
- "version": "1.3.11-beta.1",
3
+ "version": "1.3.11",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,10 +52,10 @@
52
52
  "express": "^4.21.2",
53
53
  "npm-watch": "^0.11.0",
54
54
  "supertest": "^7.0.0",
55
- "@autofleet/logger": "^4.2.46",
56
55
  "@autofleet/errors": "^3.1.42",
57
- "@autofleet/node-common": "^4.3.2",
58
- "@autofleet/zehut": "^4.8.5"
56
+ "@autofleet/logger": "^4.2.46",
57
+ "@autofleet/zehut": "^4.8.5",
58
+ "@autofleet/node-common": "^4.3.2"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@autofleet/errors": "^3",