PageSourceSearch

https://app.triplebooks.com/_next/static/chunks/3clnu7psv5q2i.js?dpl=dpl_7RAwMMrGbS6V2SVZk55kmXYGFCAA

js triplebooks.com collected 2026-10-09 22:58:41 UTC 467,603 bytes, 1 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,739788,952716,157252,86311,150429,852792,e=>{"use strict";let t,n,d=Symbol.for("drizzle:entityKind");function a(e,t){if(!e||"object"!=typeof e)return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,d))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(d in n&&n[d]===t[d])return!0;n=Object.getPrototypeOf(n)}return!1}Symbol.for("drizzle:hasOwnEntityKind"),e.s(["entityKind",0,d,"is",0,a],952716);let i=Symbol.for("drizzle:Name"),o=Symbol.for("drizzle:Schema"),l=Symbol.for("drizzle:Columns"),r=Symbol.for("drizzle:ExtraConfigColumns"),s=Symbol.for("drizzle:OriginalName"),_=Symbol.for("drizzle:BaseName"),u=Symbol.for("drizzle:IsAlias"),c=Symbol.for("drizzle:ExtraConfigBuilder"),p=Symbol.for("drizzle:IsDrizzleTable");class y{static [d]="Table";static Symbol={Name:i,Schema:o,OriginalName:s,Columns:l,ExtraConfigColumns:r,BaseName:_,IsAlias:u,ExtraConfigBuilder:c};[i];[s];[o];[l];[r];[_];[u]=!1;[p]=!0;[c]=void 0;constructor(e,t,n){this[i]=this[s]=e,this[o]=t,this[_]=n}}e.s(["IsAlias",0,u,"Table",0,y,"getTableName",0,function(e){return e[i]}],157252);class m{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static [d]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}e.s(["Column",0,m],86311);class f{static [d]="ColumnBuilder";config;constructor(e,t,n){this.config={name:e,keyAsName:""===e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){""===this.config.name&&(this.config.name=e)}}class N{static [d]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:d}=e();return{name:t,columns:n,foreignTable:d[0].table,foreignColumns:d}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new I(e,this)}}class I{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static [d]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),d=t.map(e=>e.name),a=n.map(e=>e.name),o=[this.table[i],...d,n[0].table[i],...a];return e??`${o.join("_")}_fk`}}function g(e,...t){return e(...t)}function b(e,t){return`${e[i]}_${t.join("_")}_unique`}class h{constructor(e,t){this.name=t,this.columns=e}static [d]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new x(e,this.columns,this.nullsNotDistinctConfig,this.name)}}class v{static [d]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new h(e,this.name)}}class x{constructor(e,t,n,d){this.table=e,this.columns=t,this.name=d??b(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static [d]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}function A(e,t,n){for(let d=t;d<e.length;d++){let a=e[d];if("\\"===a){d++;continue}if('"'===a)return[e.slice(t,d).replace(/\\/g,""),d+1];if(!n&&(","===a||"}"===a))return[e.slice(t,d).replace(/\\/g,""),d]}return[e.slice(t).replace(/\\/g,""),e.length]}class D extends f{foreignKeyConfigs=[];static [d]="PgColumnBuilder";array(e){return new k(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:d})=>g((n,d)=>{let a=new N(()=>({columns:[e],foreignColumns:[n()]}));return d.onUpdate&&a.onUpdate(d.onUpdate),d.onDelete&&a.onDelete(d.onDelete),a.build(t)},n,d))}buildExtraConfigColumn(e){return new E(e,this.config)}}class w extends m{constructor(e,t){t.uniqueName||(t.uniqueName=b(e,[t.name])),super(e,t),this.table=e}static [d]="PgColumn"}class E extends w{static [d]="ExtraConfigColumn";
1getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}}class R{static [d]="IndexedColumn";constructor(e,t,n,d){this.name=e,this.keyAsName=t,this.type=n,this.indexConfig=d}name;keyAsName;type;indexConfig}class k extends D{static [d]="PgArrayBuilder";constructor(e,t,n){super(e,"array","PgArray"),this.config.baseBuilder=t,this.config.size=n}build(e){let t=this.config.baseBuilder.build(e);return new T(e,this.config,t)}}class T extends w{constructor(e,t,n,d){super(e,t),this.baseColumn=n,this.range=d,this.size=t.size}size;static [d]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=function(e){let[t]=function e(t,n=0){let d=[],a=n,i=!1;for(;a<t.length;){let o=t[a];if(","===o){(i||a===n)&&d.push(""),i=!0,a++;continue}if(i=!1,"\\"===o){a+=2;continue}if('"'===o){let[e,n]=A(t,a+1,!0);d.push(e),a=n;continue}if("}"===o)return[d,a+1];if("{"===o){let[n,i]=e(t,a+1);d.push(n),a=i;continue}let[l,r]=A(t,a,!1);d.push(l),a=r}return[d,a]}(e,1);return t}(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,t=!1){let n=e.map(e=>null===e?null:a(this.baseColumn,T)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return t?n:function e(t){return`{${t.map(t=>Array.isArray(t)?e(t):"string"==typeof t?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${t}`).join(",")}}`}(n)}}class S extends D{static [d]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn"),this.config.enum=t}build(e){return new C(e,this.config)}}class C extends w{static [d]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}}let P=Symbol.for("drizzle:isPgEnum");class O extends D{static [d]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn"),this.config.enum=t}build(e){return new K(e,this.config)}}class K extends w{static [d]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}}function L(e,t){var n;let d,a;return Array.isArray(t)?d=Object.assign(e=>new O(e??"",d),{enumName:e,enumValues:[...t],schema:void 0,[P]:!0}):(n=void 0,a=Object.assign(e=>new S(e??"",a),{enumName:e,enumValues:Object.values(t),schema:n,[P]:!0}))}class q{static [d]="Subquery";constructor(e,t,n,d=!1,a=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:n,isWith:d,usedTables:a}}}class j extends q{static [d]="WithSubquery"}let U=(e,d)=>t?(n||(n=t.trace.getTracer("drizzle-orm","0.45.1")),g((t,n)=>n.startActiveSpan(e,e=>{try{return d(e)}catch(n){throw e.setStatus({code:t.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{e.end()}}),t,n)):d(),B=Symbol.for("drizzle:ViewBaseConfig");e.s(["ViewBaseConfig",0,B],150429);class M{static [d]="FakePrimitiveParam"}function F(e){return null!=e&&"function"==typeof e.getSQL}class V{static [d]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new H([this])}}class H{constructor(e){for(const t of(this.queryChunks=e,e))if(a(t,y)){const e=t[y.Symbol.Schema];this.usedTables.push(void 0===e?t[y.Symbol.Name]:e+"."+t[y.Symbol.Name])}}static [d]="SQL";decoder=G;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return U("drizzle.buildSQL",t=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){let n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:d,escapeName:i,escapeParam:o,prepareTyping:l,inlineParams:r,paramStartIndex:s}=n;var _=e.map(e=>{if(a(e,V))return{sql:e.value.join(""),params:[]};if(a(e,$))return{sql:i(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){let t=[new V("(")];for(let[n,d]of e.entries())t.push(d),n<e.length-1&&t.push(new V(", "));return t.push(new V(")")),this.buildQueryFromSourceParams(t,n)}if(a(e,H))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:r||e.shouldInlineParams});if(a(e,y)){let t=e[y.Symbol.Schema],n=e[y.Symbol.Name];return{sql:void 0===t||e[u]?i(n):i(t)+"."+i(n),params:[]}}if(a(e,m)){let n=d.getColumnCasing(e);if("indexes"===t.invokeSource)return{sql:i(n),params:[]};let a=e.table[y.Symbol.Schema];return{sql:e.table[u]||void 0===a?i(e.table[y.Symbol.Name])+"."+i(n):i(a)+"."+i(e.table[y.Symbol.Name])+"."+i(n),params:[]}}if(a(e,et)){let t=e[B].schema,n=e[B].name;return{sql:void 0===t||e[B].isAlias?i(n):i(t)+"."+i(n),params:[]}}
1if(a(e,Q)){if(a(e.value,Z))return{sql:o(s.value++,e),params:[e],typings:["none"]};let t=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(a(t,H))return this.buildQueryFromSourceParams([t],n);if(r)return{sql:this.mapInlineParam(t,n),params:[]};let d=["none"];return l&&(d=[l(e.encoder)]),{sql:o(s.value++,t),params:[t],typings:d}}return a(e,Z)?{sql:o(s.value++,e),params:[e],typings:["none"]}:a(e,H.Aliased)&&void 0!==e.fieldAlias?{sql:i(e.fieldAlias),params:[]}:a(e,q)?e._.isWith?{sql:i(e._.alias),params:[]}:this.buildQueryFromSourceParams([new V("("),e._.sql,new V(") "),new $(e._.alias)],n):e&&"function"==typeof e&&P in e&&!0===e[P]?e.schema?{sql:i(e.schema)+"."+i(e.enumName),params:[]}:{sql:i(e.enumName),params:[]}:F(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new V("("),e.getSQL(),new V(")")],n):r?{sql:this.mapInlineParam(e,n),params:[]}:{sql:o(s.value++,e),params:[e],typings:["none"]}});let c={sql:"",params:[]};for(let e of _)c.sql+=e.sql,c.params.push(...e.params),e.typings?.length&&(c.typings||(c.typings=[]),c.typings.push(...e.typings));return c}mapInlineParam(e,{escapeString:t}){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return t(e);if("object"==typeof e){let n=e.toString();return"[object Object]"===n?t(JSON.stringify(e)):t(n)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new H.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}}class ${constructor(e){this.value=e}static [d]="Name";brand;getSQL(){return new H([this])}}let G={mapFromDriverValue:e=>e},z={mapToDriverValue:e=>e};({...G,...z});class Q{constructor(e,t=z){this.value=e,this.encoder=t}static [d]="Param";brand;getSQL(){return new H([this])}}function Y(e,...t){let n=[];for(let[d,a]of((t.length>0||e.length>0&&""!==e[0])&&n.push(new V(e[0])),t.entries()))n.push(a,new V(e[d+1]));return new H(n)}(W=Y||(Y={})).empty=function(){return new H([])},W.fromList=function(e){return new H(e)},W.raw=function(e){return new H([new V(e)])},W.join=function(e,t){let n=[];for(let[d,a]of e.entries())d>0&&void 0!==t&&n.push(t),n.push(a);return new H(n)},W.identifier=function(e){return new $(e)},W.placeholder=function(e){return new Z(e)},W.param=function(e,t){return new Q(e,t)};var W,J=H||(H={});class X{constructor(e,t){this.sql=e,this.fieldAlias=t}static [d]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new X(this.sql,this.fieldAlias)}}J.Aliased=X;class Z{constructor(e){this.name=e}static [d]="Placeholder";getSQL(){return new H([this])}}let ee=Symbol.for("drizzle:IsDrizzleView");class et{static [d]="View";[B];[ee]=!0;constructor({name:e,schema:t,selectedFields:n,query:d}){this[B]={name:e,originalName:e,schema:t,selectedFields:n,query:d,isExisting:!d,isAlias:!1}}getSQL(){return new H([this])}}function en(e,t){return{name:"string"==typeof e&&e.length>0?e:"",config:"object"==typeof e?e:t}}m.prototype.getSQL=function(){return new H([this])},y.prototype.getSQL=function(){return new H([this])},q.prototype.getSQL=function(){return new H([this])},e.s(["Param",0,Q,"Placeholder",0,Z,"SQL",0,H,"StringChunk",0,V,"View",0,et,"isDriverValueEncoder",0,function(e){return"object"==typeof e&&null!==e&&"mapToDriverValue"in e&&"function"==typeof e.mapToDriverValue},"isSQLWrapper",0,F,"sql",0,Y],852792),"u"<typeof TextDecoder||new TextDecoder;class ed extends D{static [d]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:"always",sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:"byDefault",sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class ea extends ed{static [d]="PgBigInt53Builder";constructor(e){super(e,"number","PgBigInt53")}build(e){return new ei(e,this.config)}}class ei extends w{static [d]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}}class eo extends ed{static [d]="PgBigInt64Builder";constructor(e){super(e,"bigint","PgBigInt64")}build(e){return new el(e,this.config)}}class el extends w{static [d]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(e){return BigInt(e)}}function er(e,t){let{name:n,config:d}=en(e,t);return"number"===d.mode?new ea(n):new eo(n)}
1class es extends D{static [d]="PgBigSerial53Builder";constructor(e){super(e,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new e_(e,this.config)}}class e_ extends w{static [d]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}}class eu extends D{static [d]="PgBigSerial64Builder";constructor(e){super(e,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(e){return new ec(e,this.config)}}class ec extends w{static [d]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(e){return BigInt(e)}}function ep(e,t){let{name:n,config:d}=en(e,t);return"number"===d.mode?new es(n):new eu(n)}class ey extends D{static [d]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new em(e,this.config)}}class em extends w{static [d]="PgBoolean";getSQLType(){return"boolean"}}function ef(e){return new ey(e??"")}class eN extends D{static [d]="PgCharBuilder";constructor(e,t){super(e,"string","PgChar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new eI(e,this.config)}}class eI extends w{static [d]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"char":`char(${this.length})`}}function eg(e,t={}){let{name:n,config:d}=en(e,t);return new eN(n,d)}class eb extends D{static [d]="PgCidrBuilder";constructor(e){super(e,"string","PgCidr")}build(e){return new eh(e,this.config)}}class eh extends w{static [d]="PgCidr";getSQLType(){return"cidr"}}function ev(e){return new eb(e??"")}class ex extends D{static [d]="PgCustomColumnBuilder";constructor(e,t,n){super(e,"custom","PgCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new eA(e,this.config)}}class eA extends w{static [d]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return"function"==typeof this.mapFrom?this.mapFrom(e):e}mapToDriverValue(e){return"function"==typeof this.mapTo?this.mapTo(e):e}}function eD(e){return(t,n)=>{let{name:d,config:a}=en(t,n);return new ex(d,a,e)}}class ew extends D{static [d]="PgDateColumnBaseBuilder";defaultNow(){return this.default(Y`now()`)}}class eE extends ew{static [d]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new eR(e,this.config)}}class eR extends w{static [d]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?new Date(e):e}mapToDriverValue(e){return e.toISOString()}}class ek extends ew{static [d]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new eT(e,this.config)}}class eT extends w{static [d]="PgDateString";
1getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?e:e.toISOString().slice(0,-14)}}function eS(e,t){let{name:n,config:d}=en(e,t);return d?.mode==="date"?new eE(n):new ek(n)}class eC extends D{static [d]="PgDoublePrecisionBuilder";constructor(e){super(e,"number","PgDoublePrecision")}build(e){return new eP(e,this.config)}}class eP extends w{static [d]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(e){return"string"==typeof e?Number.parseFloat(e):e}}function eO(e){return new eC(e??"")}class eK extends D{static [d]="PgInetBuilder";constructor(e){super(e,"string","PgInet")}build(e){return new eL(e,this.config)}}class eL extends w{static [d]="PgInet";getSQLType(){return"inet"}}function eq(e){return new eK(e??"")}class ej extends ed{static [d]="PgIntegerBuilder";constructor(e){super(e,"number","PgInteger")}build(e){return new eU(e,this.config)}}class eU extends w{static [d]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(e){return"string"==typeof e?Number.parseInt(e):e}}function eB(e){return new ej(e??"")}class eM extends D{static [d]="PgIntervalBuilder";constructor(e,t){super(e,"string","PgInterval"),this.config.intervalConfig=t}build(e){return new eF(e,this.config)}}class eF extends w{static [d]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let e=this.fields?` ${this.fields}`:"",t=this.precision?`(${this.precision})`:"";return`interval${e}${t}`}}function eV(e,t={}){let{name:n,config:d}=en(e,t);return new eM(n,d)}class eH extends D{static [d]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new e$(e,this.config)}}class e$ extends w{static [d]="PgJson";constructor(e,t){super(e,t)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{}return e}}function eG(e){return new eH(e??"")}class ez extends D{static [d]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new eQ(e,this.config)}}class eQ extends w{static [d]="PgJsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{}return e}}function eY(e){return new ez(e??"")}class eW extends D{static [d]="PgLineBuilder";constructor(e){super(e,"array","PgLine")}build(e){return new eJ(e,this.config)}}class eJ extends w{static [d]="PgLine";getSQLType(){return"line"}mapFromDriverValue(e){let[t,n,d]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(n),Number.parseFloat(d)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}}class eX extends D{static [d]="PgLineABCBuilder";constructor(e){super(e,"json","PgLineABC")}build(e){return new eZ(e,this.config)}}class eZ extends w{static [d]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(e){let[t,n,d]=e.slice(1,-1).split(",");return{a:Number.parseFloat(t),b:Number.parseFloat(n),c:Number.parseFloat(d)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}}function e0(e,t){let{name:n,config:d}=en(e,t);return d?.mode&&"tuple"!==d.mode?new eX(n):new eW(n)}class e1 extends D{static [d]="PgMacaddrBuilder";constructor(e){super(e,"string","PgMacaddr")}build(e){return new e2(e,this.config)}}class e2 extends w{static [d]="PgMacaddr";getSQLType(){return"macaddr"}}function e4(e){return new e1(e??"")}class e6 extends D{static [d]="PgMacaddr8Builder";constructor(e){super(e,"string","PgMacaddr8")}build(e){return new e8(e,this.config)}}class e8 extends w{static [d]="PgMacaddr8";getSQLType(){return"macaddr8"}}function e5(e){return new e6(e??"")}class e3 extends D{static [d]="PgNumericBuilder";constructor(e,t,n){super(e,"string","PgNumeric"),this.config.precision=t,this.config.scale=n}build(e){return new e9(e,this.config)}}class e9 extends w{static [d]="PgNumeric";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return"string"==typeof e?e:String(e)}getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class e7 extends D{static [d]="PgNumericNumberBuilder";constructor(e,t,n){super(e,"number","PgNumericNumber"),this.config.precision=t,this.config.scale=n}build(e){return new te(e,this.config)}}class te extends w{static [d]="PgNumericNumber";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class tt extends D{static [d]="PgNumericBigIntBuilder";constructor(e,t,n){super(e,"bigint","PgNumericBigInt"),this.config.precision=t,this.config.scale=n}build(e){return new tn(e,this.config)}}class tn extends w{static [d]="PgNumericBigInt";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}function td(e,t){let{name:n,config:d}=en(e,t),a=d?.mode;return"number"===a?new e7(n,d?.precision,d?.scale):"bigint"===a?new tt(n,d?.precision,d?.scale):new e3(n,d?.precision,d?.scale)}class ta extends D{static [d]="PgPointTupleBuilder";constructor(e){super(e,"array","PgPointTuple")}build(e){return new ti(e,this.config)}}class ti extends w{static [d]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(e){if("string"==typeof e){let[t,n]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(n)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}}class to extends D{static [d]="PgPointObjectBuilder";constructor(e){super(e,"json","PgPointObject")}build(e){return new tl(e,this.config)}}class tl extends w{static [d]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(e){if("string"==typeof e){let[t,n]=e.slice(1,-1).split(",");return{x:Number.parseFloat(t),y:Number.parseFloat(n)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}}function tr(e,t){let{name:n,config:d}=en(e,t);return d?.mode&&"tuple"!==d.mode?new to(n):new ta(n)}function ts(e,t){let n=new DataView(new ArrayBuffer(8));for(let d=0;d<8;d++)n.setUint8(d,e[t+d]);return n.getFloat64(0,!0)}function t_(e){let t=function(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(Number.parseInt(e.slice(n,n+2),16));return new Uint8Array(t)}(e),n=0,d=t[0];n+=1;
1let a=new DataView(t.buffer),i=a.getUint32(n,1===d);if(n+=4,0x20000000&i&&(a.getUint32(n,1===d),n+=4),(65535&i)==1){let e=ts(t,n),d=ts(t,n+=8);return n+=8,[e,d]}throw Error("Unsupported geometry type")}class tu extends D{static [d]="PgGeometryBuilder";constructor(e){super(e,"array","PgGeometry")}build(e){return new tc(e,this.config)}}class tc extends w{static [d]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){return t_(e)}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}}class tp extends D{static [d]="PgGeometryObjectBuilder";constructor(e){super(e,"json","PgGeometryObject")}build(e){return new ty(e,this.config)}}class ty extends w{static [d]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){let t=t_(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}}function tm(e,t){let{name:n,config:d}=en(e,t);return d?.mode&&"tuple"!==d.mode?new tp(n):new tu(n)}class tf extends D{static [d]="PgRealBuilder";constructor(e,t){super(e,"number","PgReal"),this.config.length=t}build(e){return new tN(e,this.config)}}class tN extends w{static [d]="PgReal";constructor(e,t){super(e,t)}getSQLType(){return"real"}mapFromDriverValue=e=>"string"==typeof e?Number.parseFloat(e):e}function tI(e){return new tf(e??"")}class tg extends D{static [d]="PgSerialBuilder";constructor(e){super(e,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new tb(e,this.config)}}class tb extends w{static [d]="PgSerial";getSQLType(){return"serial"}}function th(e){return new tg(e??"")}class tv extends ed{static [d]="PgSmallIntBuilder";constructor(e){super(e,"number","PgSmallInt")}build(e){return new tx(e,this.config)}}class tx extends w{static [d]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=e=>"string"==typeof e?Number(e):e}function tA(e){return new tv(e??"")}class tD extends D{static [d]="PgSmallSerialBuilder";constructor(e){super(e,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new tw(e,this.config)}}class tw extends w{static [d]="PgSmallSerial";getSQLType(){return"smallserial"}}function tE(e){return new tD(e??"")}class tR extends D{static [d]="PgTextBuilder";constructor(e,t){super(e,"string","PgText"),this.config.enumValues=t.enum}build(e){return new tk(e,this.config)}}class tk extends w{static [d]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function tT(e,t={}){let{name:n,config:d}=en(e,t);return new tR(n,d)}class tS extends ew{constructor(e,t,n){super(e,"string","PgTime"),this.withTimezone=t,this.precision=n,this.config.withTimezone=t,this.config.precision=n}static [d]="PgTimeBuilder";build(e){return new tC(e,this.config)}}class tC extends w{static [d]="PgTime";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){let e=void 0===this.precision?"":`(${this.precision})`;return`time${e}${this.withTimezone?" with time zone":""}`}}function tP(e,t={}){let{name:n,config:d}=en(e,t);return new tS(n,d.withTimezone??!1,d.precision)}class tO extends ew{static [d]="PgTimestampBuilder";constructor(e,t,n){super(e,"date","PgTimestamp"),this.config.withTimezone=t,this.config.precision=n}build(e){return new tK(e,this.config)}}class tK extends w{static [d]="PgTimestamp";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){let e=void 0===this.precision?"":` (${this.precision})`;return`timestamp${e}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){return"string"==typeof e?new Date(this.withTimezone?e:e+"+0000"):e}mapToDriverValue=e=>e.toISOString()}class tL extends ew{static [d]="PgTimestampStringBuilder";constructor(e,t,n){super(e,"string","PgTimestampString"),this.config.withTimezone=t,this.config.precision=n}build(e){return new tq(e,this.config)}}class tq extends w{static [d]="PgTimestampString";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){let e=void 0===this.precision?"":`(${this.precision})`;return`timestamp${e}
1${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){if("string"==typeof e)return e;let t=e.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let n=e.getTimezoneOffset();return`${t}${n<=0?"+":"-"}${Math.floor(Math.abs(n)/60).toString().padStart(2,"0")}`}return t}}function tj(e,t={}){let{name:n,config:d}=en(e,t);return d?.mode==="string"?new tL(n,d.withTimezone??!1,d.precision):new tO(n,d?.withTimezone??!1,d?.precision)}class tU extends D{static [d]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(Y`gen_random_uuid()`)}build(e){return new tB(e,this.config)}}class tB extends w{static [d]="PgUUID";getSQLType(){return"uuid"}}function tM(e){return new tU(e??"")}class tF extends D{static [d]="PgVarcharBuilder";constructor(e,t){super(e,"string","PgVarchar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new tV(e,this.config)}}class tV extends w{static [d]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"varchar":`varchar(${this.length})`}}function tH(e,t={}){let{name:n,config:d}=en(e,t);return new tF(n,d)}class t$ extends D{static [d]="PgBinaryVectorBuilder";constructor(e,t){super(e,"string","PgBinaryVector"),this.config.dimensions=t.dimensions}build(e){return new tG(e,this.config)}}class tG extends w{static [d]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function tz(e,t){let{name:n,config:d}=en(e,t);return new t$(n,d)}class tQ extends D{static [d]="PgHalfVectorBuilder";constructor(e,t){super(e,"array","PgHalfVector"),this.config.dimensions=t.dimensions}build(e){return new tY(e,this.config)}}class tY extends w{static [d]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(e=>Number.parseFloat(e))}}function tW(e,t){let{name:n,config:d}=en(e,t);return new tQ(n,d)}class tJ extends D{static [d]="PgSparseVectorBuilder";constructor(e,t){super(e,"string","PgSparseVector"),this.config.dimensions=t.dimensions}build(e){return new tX(e,this.config)}}class tX extends w{static [d]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function tZ(e,t){let{name:n,config:d}=en(e,t);return new tJ(n,d)}class t0 extends D{static [d]="PgVectorBuilder";constructor(e,t){super(e,"array","PgVector"),this.config.dimensions=t.dimensions}build(e){return new t1(e,this.config)}}class t1 extends w{static [d]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(e=>Number.parseFloat(e))}}function t2(e,t){let{name:n,config:d}=en(e,t);return new t0(n,d)}let t4=Symbol.for("drizzle:PgInlineForeignKeys"),t6=Symbol.for("drizzle:EnableRLS");class t8 extends y{static [d]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:t4,EnableRLS:t6});[t4]=[];[t6]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}}let t5=(e,t,n)=>(function(e,t,n,d,a=e){let i=new t8(e,d,a),o="function"==typeof t?t({bigint:er,bigserial:ep,boolean:ef,char:eg,cidr:ev,customType:eD,date:eS,doublePrecision:eO,inet:eq,integer:eB,interval:eV,json:eG,jsonb:eY,line:e0,macaddr:e4,macaddr8:e5,numeric:td,point:tr,geometry:tm,real:tI,serial:th,smallint:tA,smallserial:tE,text:tT,time:tP,timestamp:tj,uuid:tM,varchar:tH,bit:tz,halfvec:tW,sparsevec:tZ,vector:t2}):t,l=Object.fromEntries(Object.entries(o).map(([e,t])=>{t.setName(e);let n=t.build(i);return i[t4].push(...t.buildForeignKeys(n,i)),[e,n]})),r=Object.fromEntries(Object.entries(o).map(([e,t])=>(t.setName(e),[e,t.buildExtraConfigColumn(i)]))),s=Object.assign(i,l);return s[y.Symbol.Columns]=l,s[y.Symbol.ExtraConfigColumns]=r,n&&(s[t8.Symbol.ExtraConfigBuilder]=n),Object.assign(s,{enableRLS:()=>(s[t8.Symbol.EnableRLS]=!0,s)})})(e,t,n,void 0);class t3{constructor(e,t){this.unique=e,this.name=t}static [d]="PgIndexBuilderOn";on(...e){return new t9(e.map(e=>{if(a(e,H))return e;let t=new R(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...e){return new t9(e.map(e=>{if(a(e,H))return e;let t=new R(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=e.defaultConfig,t}),this.unique,!0,this.name)}using(e,...t){return new t9(t.map(e=>{if(a(e,H))return e;let t=new R(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),t}),this.unique,!0,this.name,e)}}class t9{static [d]="PgIndexBuilder";config;constructor(e,t,n,d,a="btree"){this.config={name:d,columns:e,unique:t,only:n,method:a}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new t7(this.config,e)}}class t7{static [d]="PgIndex";config;constructor(e,t){this.config={...e,table:t}}}function ne(e){return new t3(!1,e)}function nt(e){return new t3(!0,e)}function nn(...e){return e[0].columns?new nd(e[0].columns,e[0].name):new nd(e)}class nd{static [d]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new na(e,this.columns,this.name)}}class na{constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static [d]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[t8.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}let ni=eD({dataType:()=>"vector(1024)"}),no=L("event_source",["MANUAL","IMPORT","INTEGRATION","SYSTEM","PROTOCOL"]),nl=L("item_kind",["inventory","non_inventory","service","bundle"]),nr=L("item_sourcing_method",["stock","dropship","make_to_order","none"]),ns=L("direction",["DEBIT","CREDIT"]),n_=L("account_type",["ASSET","LIABILITY","EQUITY","REVENUE","EXPENSE"]),nu=L("entity_type",["OPERATING","HOLDING","FUND","TRUST","PERSONAL"]),nc=L("entity_sub_type",["C_CORP","S_CORP","LLC_SINGLE","LLC_MULTI","LP","LLP","SOLE_PROP","NON_PROFIT","REVOCABLE_TRUST","IRREVOCABLE_TRUST","CHARITABLE_TRUST","TESTAMENTARY_TRUST","BUSINESS_TRUST"]),np=L("entity_legal_status",["active","dissolved"]),ny=L("book_type",["GAAP","TAX","MANAGEMENT","FUND_ADMIN","FIDUCIARY","IFRS","REGULATORY","CONSOLIDATION","CUSTOM"]),nm=L("pack_layer",["KERNEL","STANDARD","INDUSTRY","ENTITY","MODULE"]),nf=L("pack_status",["DRAFT","PUBLISHED","SUPERSEDED","DEPRECATED"]),nN=L("entry_status",["PENDING_APPROVAL","POSTED","REVERSED"]),nI=L("period_status",["OPEN","SOFT_CLOSED","HARD_CLOSED","MIGRATED"]),ng=L("schedule_status",["ACTIVE","COMPLETED","SUPERSEDED"]),nb=L("schedule_period_status",["PENDING","POSTED","SKIPPED","CANCELLED"]),nh=L("trace_status",["SUCCESS","REJECTED","ERROR"]),nv=L("actor_type",["USER","SYSTEM","AI_PROPOSED","AI_APPROVED"]),nx=L("proposal_type",["POSTING_RULE","ACCOUNT_MAPPING","EVENT_CLASSIFICATION"]),nA=L("proposal_status",["PENDING","APPROVED","REJECTED","EXPIRED"]),nD=L("cortex_proposal_status",["pen
1ding","executed","rejected","expired"]),nw=L("cortex_agent_visibility",["private","entity"]),nE=L("cortex_agent_invocation_source",["chat","cron","manual"]),nR=L("settlement_source_type",["ONCHAIN","PAYMENT_INTENT","PROTOCOL","MANUAL","SHIELDED","EXCHANGE","COLLECTION"]),nk=L("settlement_direction",["INBOUND","OUTBOUND"]);t5("entity_access",{id:tM("id").primaryKey().defaultRandom(),userId:tM("user_id").notNull(),entityId:tM("entity_id").notNull().references(()=>nP.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("entity_access_user_idx").on(e.userId),ne("entity_access_entity_idx").on(e.entityId),nt("entity_access_user_entity_idx").on(e.userId,e.entityId)]);let nT=t5("rbac_roles",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").references(()=>nP.id,{onDelete:"cascade"}),key:tT("key").notNull(),name:tT("name").notNull(),description:tT("description"),isSystem:ef("is_system").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("rbac_roles_entity_idx").on(e.entityId),nt("rbac_roles_entity_key_idx").on(e.entityId,e.key)]),nS=t5("rbac_permissions",{id:tM("id").primaryKey().defaultRandom(),key:tT("key").notNull(),app:tT("app").notNull(),description:tT("description"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("rbac_permissions_key_idx").on(e.key),ne("rbac_permissions_app_idx").on(e.app)]);t5("rbac_role_permissions",{id:tM("id").primaryKey().defaultRandom(),roleId:tM("role_id").notNull().references(()=>nT.id,{onDelete:"cascade"}),permissionId:tM("permission_id").notNull().references(()=>nS.id,{onDelete:"cascade"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("rbac_role_permissions_unique_idx").on(e.roleId,e.permissionId),ne("rbac_role_permissions_role_idx").on(e.roleId),ne("rbac_role_permissions_permission_idx").on(e.permissionId)]),t5("rbac_user_roles",{id:tM("id").primaryKey().defaultRandom(),userId:tM("user_id").notNull(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),roleId:tM("role_id").notNull().references(()=>nT.id,{onDelete:"cascade"}),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("rbac_user_roles_unique_idx").on(e.userId,e.entityId,e.roleId),ne("rbac_user_roles_user_entity_idx").on(e.userId,e.entityId),ne("rbac_user_roles_role_idx").on(e.roleId)]);let nC=L("custom_field_type",["text","textarea","number","currency","boolean","date","datetime","single_select","multi_select","email","phone","url","json"]);t5("custom_field_definitions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),app:tT("app").notNull(),objectType:tT("object_type").notNull(),key:tT("key").notNull(),label:tT("label").notNull(),type:nC("type").notNull().default("text"),required:ef("required").notNull().default(!1),encrypted:ef("encrypted").notNull().default(!1),position:eB("position").notNull().default(0),options:eY("options").$type().default([]),validation:eY("validation").$type(),metadata:eY("metadata").$type(),ar
1chivedAt:tj("archived_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("custom_field_definitions_unique_idx").on(e.entityId,e.app,e.objectType,e.key),ne("custom_field_definitions_entity_app_idx").on(e.entityId,e.app),ne("custom_field_definitions_entity_object_idx").on(e.entityId,e.objectType)]);let nP=t5("entities",{id:tM("id").primaryKey().defaultRandom(),name:tT("name").notNull(),legalName:tT("legal_name").notNull(),type:nu("type").notNull(),subType:nc("sub_type"),functionalCurrency:tT("functional_currency").notNull(),fiscalYearStartMonth:eB("fiscal_year_start_month").notNull().default(1),periodType:tT("period_type").notNull().default("MONTHLY"),jurisdiction:tT("jurisdiction"),taxId:tT("tax_id"),industry:tT("industry"),naicsCode:tT("naics_code"),inceptionDate:eS("inception_date"),legalStatus:np("legal_status").notNull().default("active"),dissolvedAt:eS("dissolved_at"),dissolutionNote:tT("dissolution_note"),parentEntityId:tM("parent_entity_id").references(()=>nP.id,{onDelete:"restrict"}),ownershipPercentage:tT("ownership_percentage"),consolidationGroupId:tM("consolidation_group_id"),timezone:tT("timezone").notNull().default("UTC"),enforceSod:ef("enforce_sod").notNull().default(!1),requireAiApproval:ef("require_ai_approval").notNull().default(!1),autoMatchThreshold:eB("auto_match_threshold").notNull().default(90),autopilotMode:tT("autopilot_mode").notNull().default("review"),autopilotConfidenceThreshold:eB("autopilot_confidence_threshold").notNull().default(90),trackVendorMasterOnCardSpend:ef("track_vendor_master_on_card_spend").notNull().default(!1),devModeEnabled:ef("dev_mode_enabled").notNull().default(!1),devModeGoLiveDate:eS("dev_mode_go_live_date"),autonomousPostingThreshold:td("autonomous_posting_threshold",{precision:20,scale:2}),encryptedDek:tT("encrypted_dek"),dekVersion:eB("dek_version").notNull().default(1),protocolEntityId:tT("protocol_entity_id"),globalRegistryId:tM("global_registry_id"),protocolPublicKey:tT("protocol_public_key"),protocolPrivateKey:tT("protocol_private_key"),protocolEndpoint:tT("protocol_endpoint"),protocolDomain:tT("protocol_domain"),protocolCapabilities:eY("protocol_capabilities"),protocolWalletAddress:tT("protocol_wallet_address"),bridgeCustomerId:tT("bridge_customer_id"),email:tT("email"),emailVerifiedAt:tj("email_verified_at"),cutoverDate:eS("cutover_date"),migrationSource:tT("migration_source"),provisioningSource:tT("provisioning_source"),primaryAddressId:tM("primary_address_id").references(()=>lo.id,{onDelete:"set null"}),archivedAt:tj("archived_at"),createdAt:tj("created_at").notNull().defaultNow()});t5("entity_parentage_closure",{entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),ancestorId:tM("ancestor_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),descendantId:tM("descendant_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),depth:eB("depth").notNull()},e=>[nn({columns:[e.entityId,e.ancestorId,e.descendantId]}),ne("entity_parentage_closure_entity_desc_idx").on(e.entityId,e.descendantId),ne("entity_parentage_closure_entity_anc_idx").on(e.entityId,e.ancestorId)]),t5("entity_hub_surface_disabled",{entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),href:tT("href").notNull(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nn({columns:[e.entityId,e.href]}),ne("entity_hub_surface_disabled_entity_idx").on(e.entityId)]);let nO=L("dek_rotation_status",["PENDING","IN_PROGRESS","COMPLETED","FAILED"]),nK=t5("dek_key_versions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),version:eB("version").notNull(),encryptedDek:tT("encrypted_dek").notNull(),status:nO("status").notNull().default("PENDING"),tablesTotal:eB("tables_total"),tablesCompleted:eB("tables_completed").notNull().default(0),rowsReencrypted:eB("rows_reencrypted").notNull().default(0),errorMessage:tT("error_message"),createdAt:tj("created_at").notNull().defaultNow(),completedAt:tj("completed_at")},e=>[ne("dek_versions_entity_idx").on(e.entityId),ne("dek_versions_entity_version_idx").on(e.entityId,e.version)]),nL=L("rule_pack_source",["platform","tenant","ai"]),nq=t5("books",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),type:ny("type").notNull(),rulePackId:tM("rule_pack_id"),isPrimary:ef("is_primary").notNull().default(!1),requiresApproval:ef("requires_approval").notNull().default(!1),costBasisMethod:tT("cost_basis_method").default("FIFO"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("books_entity_idx").on(e.entityId)]),nj=t5("ledgers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),slug:tT("slug"),metadata:eY("metadata"),isDefault:ef("is_default").notNull().default(!1),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ledgers_entity_idx").on(e.entityId),nt("ledgers_entity_slug_unique").on(e.entityId,e.slug).where(Y`${e.slug} IS NOT NULL`),nt("ledgers_entity_default_unique").on(e.entityId).where(Y`${e.isDefault} = true`)]);t5("book_rule_packs",{id:tM("id").primaryKey().defaultRandom(),bookId:tM("book_id").notNull().references(()=>nq.id),packId:tM("pack_id").notNull().references(()=>nz.id),priority:eB("priority").notNull().default(0),source:nL("source").notNull().default("platform"),locked:ef("locked").notNull().default(!1),appliedBy:tT("applied_by")},e=>[ne("book_rule_packs_book_idx").on(e.bookId),nt("book_rule_packs_unique").on(e.bookId,e.packId)]);let nU=t5("accounts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),code:tT("code").notNull(),name:tT("name").notNull(),type:n_("type").notNull(),normalBalance:ns("normal_balance").notNull(),parentId:tM("parent_id").references(()=>nU.id),isActive:ef("is_active").notNull().default(!0),isLocked:ef("is_locked").notNull().default(!1),requiresReconciliation:ef("requires_reconciliation").notNull().default(!1),currency:tT("currency"),tags:eY("tags"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("accounts_entity_idx").on(e.entityId),nt("accounts_entity_code_idx").on(e.entityId,e.code),ne("accounts_requires_recon_idx").on(e.entityId,e.requiresReconciliation)]);t5("account_hierarchy_closure",{entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),ancestorId:tM("ancestor_id").notNull().references(()=>nU.id,{onDelete:"cascade"}),descendantId:tM("descendant_id").notNull().references(()=>nU.id,{onDelete:"cascade"}),depth:eB("depth").notNull()},e=>[nn({columns:[e.entityId,e.ancestorId,e.descendantId]}),ne("account_h_closure_entity_desc_idx").on(e.entityId,e.descendantId),ne("account_h_closure_entity_anc_idx").on(e.entityId,e.ancestorId),ne("account_h_closure_entity_anc_depth_idx").on(e.entityId,e.ancestorId,e.depth)]),t5("account_balances",{id:tM("id").primaryKey().defaultRandom(),accountId:tM("account_id").notNull().references(()=>nU.id),entityId:tM("entity_id").notNull().references(()=>nP.id),bookId:tM("book_id").notNull().references(()=>nq.id,{onDelete:"cascade"}),currency:tT("currency").notNull().default("USD"),balance:tT("balance").notNull().default("0"),functionalBalance:tT("functional_balance").notNull().default("0"),debitTotal:tT("debit_total").notNull().default("0"),creditTotal:tT("credit_total").notNull().default("0"),entryCount:eB("entry_count").notNull().default(0),lastEntryDate:eS("last_entry_date"),lastEntryId:tM("last_entry_id"),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("acct_bal_account_book_currency_idx").on(e.accountId,e.bookId,e.currency),ne("acct_bal_entity_idx").on(e.entityId),ne("acct_bal_entity_book_idx").on(e.entityId,e.bookId)]),t5("account_mappings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),logicalRole:tT("logical_role").notNull(),accountId:tM("account_id").notNull().references(()=>nU.id),conditions:eY("conditions"),priority:eB("priority").notNull().default(0),packLayer:nm("pack_layer").notNull(),effectiveDate:eS("effective_date").notNull(),expirationDate:eS("expiration_date")},e=>[ne("account_mappings_entity_role_idx").on(e.entityId,e.logicalRole)]);let nB=t5("events",{id:tM("id").primaryKey().defaultRandom(),type:tT("type").notNull(),timestamp:tj("timestamp").notNull(),entityId:tM("entity_id").notNull().references(()=>nP.id),source:no("source").notNull(),actorType:nv("actor_type").notNull(),correlationId:tM("correlation_id"),userId:tM("user_id"),attributionKind:tT("attribution_kind").$type(),idempotencyKey:tT("idempotency_key").notNull(),schemaVersion:tT("schema_version").notNull(),payload:eY("payload").notNull(),metadata:eY("metadata"),disposedAt:tj("disposed_at"),disposedBy:tM("disposed_by"),disposedReason:tT("disposed_reason"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("events_idempotency_idx").on(e.idempotencyKey),ne("events_entity_type_idx").on(e.entityId,e.type),ne("events_timestamp_idx").on(e.timestamp),ne("events_disposed_idx").on(e.disposedAt)]),nM=L("intercompany_transaction_type",["GOODS","SERVICES","ROYALTY","LOAN_INTEREST","COST_SHARING","OTHER"]),nF=L("transfer_pricing_method",["CUP","COST_PLUS","RESALE_MINUS","TNMM","PROFIT_SPLIT","OTHER"]),nV=t5("journal_entries",{id:tM("id").primaryKey().defaultRandom(),eventId:tM("event_id").references(()=>nB.id),bookId:tM("book_id").notNull().references(()=>nq.id),entityId:tM("entity_id").notNull().references(()=>nP.id),ledgerId:tM("ledger_id").notNull().references(()=>nj.id),entryDate:eS("entry_date").notNull(),effectiveDate:eS("effective_date").notNull(),authorizedDate:eS("authorized_date"),rulePackId:tM("rule_pack_id"),ruleVersion:tT("rule_version"),ruleName:tT("rule_name"),executionTraceId:tM("execution_trace_id"),status:nN("status").notNull().default("POSTED"),actorType:nv("actor_type").notNull().default("SYSTEM"),createdByUserId:tM("created_by_user_id"),reversalOf:tM("reversal_of").references(()=>nV.id),isAdjusting:ef("is_adjusting").notNull().default(!1),isSystemGenerated:ef("is_system_generated").notNull().default(!0),tags:eY("tags"),attachments:eY("attachments"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("journal_entries_event_idx").on(e.eventId),ne("journal_entries_book_idx").on(e.bookId),ne("journal_entries_entity_book_idx").on(e.entityId,e.bookId),ne("journal_entries_entity_ledger_idx").on(e.entityId,e.ledgerId),ne("journal_entries_date_idx").on(e.entryDate),ne("journal_entries_authorized_date_idx").on(e.entityId,e.authorizedDate),ne("journal_entries_event_book_idx").on(e.eventId,e.bookId),ne("journal_entries_site_idx").on(e.entityId,e.siteId),ne("journal_entries_created_by_user_idx").on(e.entityId,e.createdByUserId),nt("journal_entries_event_book_unique_idx").on(e.eventId,e.bookId).where(Y`reversal_of IS NULL AND event_id IS NOT NULL`),nt("journal_entries_reversal_of_unique_idx").on(e.reversalOf).where(Y`reversal_of IS NOT NULL`)]),nH=t5("journal_lines",{id:tM("id").primaryKey().defaultRandom(),entryId:tM("entry_id").notNull().references(()=>nV.id),accountId:tM("account_id").notNull().references(()=>nU.id),accountRole:tT("account_role"),direction:ns("direction").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull(),functionalAmount:tT("functional_amount").notNull(),functionalCurrency:tT("functional_currency").notNull(),fxRate:tT("fx_rate"),fxRateDate:tj("fx_rate_date"),counterpartyEntityId:tM("counterparty_entity_id"),dimensions:eY("dimensions"),memo:tT("memo"),memoTokens:eY("memo_tokens"),quantity:tT("quantity"),lotId:tM("lot_id"),lineOrder:eB("line_order").notNull(),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),ledgerId:tM("ledger_id").references(()=>nj.id,{onDelete:"set null"})},e=>[ne("journal_lines_entry_idx").on(e.entryId),ne("journal_lines_account_idx").on(e.accountId),ne("journal_lines_memo_tokens_idx").using("gin",e.memoTokens),ne("journal_lines_site_account_idx").on(e.siteId,e.accountId),ne("journal_lines_ledger_account_idx").on(e.ledgerId,e.accountId)]);t5("intercompany_transactions",{id:tM("id").primaryKey().defaultRandom(),eventId:tM("event_id").notNull().references(()=>
1nB.id,{onDelete:"cascade"}),fromEntityId:tM("from_entity_id").notNull().references(()=>nP.id),toEntityId:tM("to_entity_id").notNull().references(()=>nP.id),transactionType:nM("transaction_type").notNull().default("SERVICES"),pricingMethod:nF("pricing_method"),amount:tT("amount").notNull(),currency:tT("currency").notNull(),costBase:tT("cost_base"),markupPct:tT("markup_pct"),narrative:tT("narrative"),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),proposalId:tM("proposal_id").references(()=>dJ.id,{onDelete:"set null"}),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("intercompany_transactions_event_idx").on(e.eventId),ne("intercompany_transactions_from_idx").on(e.fromEntityId),ne("intercompany_transactions_to_idx").on(e.toEntityId),ne("intercompany_transactions_document_idx").on(e.documentId),ne("intercompany_transactions_proposal_idx").on(e.proposalId)]),t5("fx_rates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").references(()=>nP.id),fromCurrency:tT("from_currency").notNull(),toCurrency:tT("to_currency").notNull(),rate:td("rate",{precision:38,scale:18}).notNull(),rateDate:eS("rate_date").notNull(),source:tT("source").notNull(),importedAt:tj("imported_at").notNull().defaultNow()},e=>[nt("fx_rates_unique_idx").on(e.fromCurrency,e.toCurrency,e.rateDate,e.source,e.entityId),ne("fx_rates_entity_idx").on(e.entityId)]);let n$=t5("accounting_periods",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),bookId:tM("book_id").notNull().references(()=>nq.id),startDate:eS("start_date").notNull(),endDate:eS("end_date").notNull(),fiscalYear:eB("fiscal_year").notNull(),periodNumber:eB("period_number").notNull(),status:nI("status").notNull().default("OPEN"),closedBy:tM("closed_by"),closedAt:tj("closed_at"),closureMethod:tT("closure_method"),reopenedCount:eB("reopened_count").notNull().default(0)},e=>[ne("accounting_periods_entity_book_idx").on(e.entityId,e.bookId),nt("accounting_periods_unique_idx").on(e.entityId,e.bookId,e.fiscalYear,e.periodNumber)]),nG=t5("period_snapshots",{id:tM("id").primaryKey().defaultRandom(),periodId:tM("period_id").notNull().references(()=>n$.id),entityId:tM("entity_id").notNull().references(()=>nP.id),bookId:tM("book_id").notNull().references(()=>nq.id),version:eB("version").notNull().default(1),balances:eY("balances").notNull(),snapshotHash:tT("snapshot_hash").notNull(),journalMerkleRoot:tT("journal_merkle_root").notNull(),rulePackHash:tT("rule_pack_hash"),executionGraphHash:tT("execution_graph_hash"),balanceMerkleLeaves:eY("balance_merkle_leaves"),journalMerkleLeaves:eY("journal_merkle_leaves"),isRestated:ef("is_restated").notNull().default(!1),isMigrated:ef("is_migrated").notNull().default(!1),supersedesSnapshotId:tM("supersedes_snapshot_id"),createdAt:tj("created_at").notNull().defaultNow(),anchoredOnchain:ef("anchored_onchain").notNull().default(!1),anchorTxHash:tT("anch
1or_tx_hash"),anchorChainId:eB("anchor_chain_id")},e=>[ne("period_snapshots_period_idx").on(e.periodId)]),nz=t5("rule_packs",{id:tM("id").primaryKey().defaultRandom(),name:tT("name").notNull(),slug:tT("slug"),version:tT("version").notNull().default("1.0.0"),layer:nm("layer").notNull(),industry:tT("industry"),entityId:tM("entity_id").references(()=>nP.id),status:nf("status").notNull().default("DRAFT"),effectiveDate:eS("effective_date").notNull(),expirationDate:eS("expiration_date"),contentHash:tT("content_hash"),source:nL("source").notNull().default("platform"),manifestBundle:tT("manifest_bundle"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("rule_packs_entity_idx").on(e.entityId),ne("rule_packs_slug_status_idx").on(e.slug,e.status),nt("rule_packs_global_slug_published_unique").on(e.slug).where(Y`${e.entityId} IS NULL AND ${e.status} = 'PUBLISHED' AND ${e.slug} IS NOT NULL`)]),nQ=L("rule_type",["EVENT_MATCH","POSTING","ACCRUAL","FX","INTERCOMPANY","CONSOLIDATION","PRESENTATION"]),nY=L("rule_action",["APPLY","OVERRIDE","DISABLE","EXTEND"]);t5("rules",{id:tM("id").primaryKey().defaultRandom(),packId:tM("pack_id").notNull().references(()=>nz.id),name:tT("name").notNull(),type:nQ("type").notNull().default("POSTING"),priority:eB("priority").notNull().default(0),action:nY("action").notNull().default("APPLY"),eventType:tT("event_type").notNull(),basis:tT("basis"),validSources:eY("valid_sources"),dslSource:tT("dsl_source"),matchConditions:eY("match_conditions"),postingTemplate:eY("posting_template").notNull(),metadata:eY("metadata"),contentHash:tT("content_hash"),source:nL("source").notNull().default("platform"),platformManaged:ef("platform_managed").notNull().default(!0),editedAt:tj("edited_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("rules_pack_idx").on(e.packId),ne("rules_event_type_idx").on(e.eventType)]);let nW=L("schedule_method",["STRAIGHT_LINE","CUSTOM_PATTERN"]),nJ=L("schedule_type",["DEFERRED_REVENUE","PREPAID_EXPENSE","ACCRUED_EXPENSE","ACCRUED_REVENUE"]),nX=t5("accrual_schedules",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),bookId:tM("book_id").notNull().references(()=>nq.id),sourceEventId:tM("source_event_id").references(()=>nB.id),sourceJournalEntryId:tM("source_journal_entry_id").references(()=>nV.id),scheduleType:nJ("schedule_type").notNull(),method:nW("method").notNull().default("STRAIGHT_LINE"),description:tT("description").notNull(),totalAmount:tT("total_amount").notNull(),recognizedAmount:tT("recognized_amount").notNull().default("0"),currency:tT("currency").notNull().default("USD"),startDate:eS("start_date").notNull(),endDate:eS("end_date").notNull(),sourceRole:tT("source_role").notNull(),targetRole:tT("target_role").notNull(),autoReverse:ef("auto_reverse").notNull().default(!1),status:ng("status").notNull().default("ACTIVE"),supersededById:tM("superseded_by_id"),ruleVersion:tT("rule_version"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("accrual_schedules_entity_idx").on(e.entityId),ne("accrual_schedules_book_idx").on(e.bookId),ne("accrual_schedules_status_idx").on(e.status)]);t5("schedule_entries",{id:tM("id").primaryKey().defaultRandom(),scheduleId:tM("schedule_id").notNull().references(()=>nX.id),periodIndex:eB("period_index").notNull(),periodStart:eS("period_start").notNull(),periodEnd:eS("period_end").notNull(),amount:tT("amount").notNull(),status:nb("status").notNull().default("PENDING"),journalEntryId:tM("journal_entry_id").references(()=>nV.id),postedAt:tj("posted_at")},e=>[ne("schedule_entries_schedule_idx").on(e.scheduleId),ne("schedule_entries_status_idx").on(e.status)]);let nZ=L("staged_tx_status",["PENDING","VALIDATED","UNMATCHED","NEEDS_REVIEW","MATCHED","CONFIRMED","EXCLUDED","QUARANTINED","PROCESSED","REJECTED","VARIANCE"]),n0=L("import_method",["PLAID","CSV","ONCHAIN_SCAN","MANUAL","API","BRIDGE_CARD","MERCURY","STRIPE","QUICKBOOKS","WEBHOOK","EDI","AI_EXTRACT","BREX","RAMP","DEEL","XERO","APPLE_CARD_STATEMENT","APPLE_FINANCEKIT","VENMO_STATEMENT","COINBASE","STATEMENT_PDF"]),n1=L("financial_account_type",["DEPOSITORY","CREDIT_CARD","LOAN","INVESTMENT","WALLET","CARD","CUSTODIAN"]),n2=L("investment_transaction_type",["BUY","SELL","DIVIDEND","INTEREST","TRANSFER","FEE","SPLIT","MERGER","SPINOFF","RETURN_OF_CAPITAL","OTHER"]),n4=t5("staged_transactions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),accountId:tM("account_id").references(()=>nU.id),importMethod:n0("import_method").notNull(),accountType:n1("account_type"),accountSubtype:tT("account_subtype"),treasuryAccountId:tM("treasury_account_id").references(()=>n7.id),sourceFormat:tT("source_format"),importBatchId:tT("import_batch_id").notNull(),txDate:e
1S("tx_date").notNull(),authorizedTxDate:eS("authorized_tx_date"),description:tT("description").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USD"),reference:tT("reference"),externalId:tT("external_id"),txHash:tT("tx_hash"),contentHash:tT("content_hash"),chain:tT("chain"),networkTier:tT("network_tier"),counterparty:tT("counterparty"),category:tT("category"),subcategory:tT("subcategory"),symbol:tT("symbol"),quantity:tT("quantity"),pricePerUnit:tT("price_per_unit"),investmentTransactionType:n2("investment_transaction_type"),securityId:tT("security_id"),rawData:eY("raw_data"),status:nZ("status").notNull().default("UNMATCHED"),matchedEventId:tM("matched_event_id").references(()=>nB.id),matchedJournalEntryId:tM("matched_journal_entry_id").references(()=>nV.id),matchConfidence:eB("match_confidence"),reconciledAt:tj("reconciled_at"),reconciledBy:tT("reconciled_by"),canonicalPayload:eY("canonical_payload"),validationErrors:eY("validation_errors"),quarantineReason:tT("quarantine_reason"),eventType:tT("event_type"),processedAt:tj("processed_at"),suggestedEventType:tT("suggested_event_type"),suggestedAccountId:tM("suggested_account_id").references(()=>nU.id),suggestedCounterparty:tT("suggested_counterparty"),suggestedVendorId:tM("suggested_vendor_id").references(()=>dn.id,{onDelete:"set null"}),suggestedMemo:tT("suggested_memo"),postingNote:tT("posting_note"),businessPartyId:tM("business_party_id").references(()=>sg.id,{onDelete:"set null"}),suggestionConfidence:eB("suggestion_confidence"),suggestionAccountConfidence:eB("suggestion_account_confidence"),suggestionSource:tT("suggestion_source"),enrichmentFlags:eY("enrichment_flags"),autoPostedSource:tT("auto_posted_source"),autoPostedAt:tj("auto_posted_at"),aiSuggestedEventType:tT("ai_suggested_event_type"),aiSuggestedAccountId:tM("ai_suggested_account_id").references(()=>nU.id,{onDelete:"set null"}),aiSuggestionConfidence:eB("ai_suggestion_confidence"),aiSuggestionReason:tT("ai_suggestion_reason"),aiSuggestionModel:tT("ai_suggestion_model"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("staged_tx_entity_idx").on(e.entityId),ne("staged_tx_batch_idx").on(e.importBatchId),ne("staged_tx_status_idx").on(e.status),ne("staged_tx_date_idx").on(e.txDate),nt("staged_tx_entity_external_id_idx").on(e.entityId,e.externalId).where(Y`external_id IS NOT NULL`),nt("staged_tx_entity_content_hash_idx").on(e.entityId,e.contentHash).where(Y`content_hash IS NOT NULL`),ne("staged_tx_network_tier_idx").on(e.networkTier),ne("staged_tx_event_type_idx").on(e.eventType),ne("staged_tx_symbol_idx").on(e.symbol),ne("staged_tx_entity_status_idx").on(e.entityId,e.status),ne("staged_tx_auth_date_idx").on(e.entityId,e.authorizedTxDate),ne("staged_tx_auto_posted_at_idx").on(e.entityId,e.autoPostedAt)]);t5("review_actions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),stagedTransactionId:tM("staged_transaction_id").notNull().references(()=>n4.id),suggestionSource:tT("suggestion_source"),suggestedEventType:tT("suggested_event_type"),suggestedAccountId:tM("suggested_account_id").references(()=>nU.id),finalEventType:tT("final_event_type"),finalAccountId:tM("final_account_id").references(()=>nU.id),aiSuggestedEventType:tT("ai_suggested_event_type"),aiSuggestedAccountId:tM("ai_suggested_account_id").references(()=>nU.id,{onDelete:"set null"}),aiOverrode:ef("ai_overrode"),action:tT("action").notNull(),reviewerId:tT("reviewer_id").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("review_actions_entity_idx").on(e.entityId),ne("review_actions_staged_tx_idx").on(e.stagedTransactionId),ne("review_actions_reviewer_idx").on(e.reviewerId)]),t5("import_ai_suggestion_cache",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),contentHash:tT("content_hash").notNull(),payload:tT("payload").notNull(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("import_ai_suggestion_cache_entity_hash_uidx").on(e.entityId,e.contentHash),ne("import_ai_suggestion_cache_entity_idx").on(e.entityId)]),t5("crm_enrichment_ai_cache",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),companyId:tM("company_id").notNull().references(()=>i7.id,{onDelete:"cascade"}),snapshotHash:tT("snapshot_hash").notNull(),payload:tT("payload").notNull(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("crm_enrichment_ai_cache_entity_company_hash_uidx").on(e.entityId,e.companyId,e.snapshotHash),ne("crm_enrichment_ai_cache_entity_idx").on(e.entityId)]);let n6=L("classification_layer",["rule","signal","deterministic","learned","llm","human"]),n8=L("classification_status",["chosen","needs_review","failed"]);t5("classification_decisions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),stagedTransactionId:tM("staged_transaction_id").references(()=>n4.id),layer:n6("layer").notNull(),status:n8("status").notNull(),featureHash:tT("feature_hash").notNull(),features:tT("features"),candidates:tT("candidates"),chosenEventType:tT("chosen_event_type"),chosenAccountId:tM("chosen_account_id").references(()=>nU.id),confidence:eB("confidence").notNull().default(0),modelId:tT("model_id"),promptVersion:tT("prompt_version"),policyVersion:tT("policy_version").notNull().default("v1"),latencyMs:eB("latency_ms").notNull().default(0),costCents:eB("cost_cents").notNull().default(0),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("classification_decisions_entity_idx").on(e.entityId),ne("classification_decisions_entity_hash_idx").on(e.entityId,e.featureHash),ne("classification_decisions_staged_tx_idx").on(e.stagedTransactionId),ne("classification_decisions_entity_created_idx").on(e.entityId,e.createdAt)]),t5("classification_cache",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),featureHash:tT("feature_hash").notNull(),layer:n6("layer").notNull(),chosenEventType:tT("chosen_event_type").notNull(),chosenAccountId:tM("chosen_account_id").references(()=>nU.id),confidence:eB("confidence").notNull(),modelId:tT("model_id"),promptVersion:tT("prompt_version"),policyVersion:tT("policy_version").notNull().default("v1"),hitCount:eB("hit_count").notNull().default(0),lastUsedAt:tj("last_used_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("classification_cache_entity_hash_uidx").on(e.entityId,e.featureHash),ne("classification_cache_entity_idx").on(e.entityId)]),t5("classification_policies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),policyVersion:tT("policy_version").notNull().default("v1"),enabled:ef("enabled").notNull().default(!1),ruleFloor:eB("rule_floor").notNull().default(90),signalFloor:eB("signal_floor").notNull().default(30),deterministicFloor:eB("deterministic_floor").notNull().default(60),learnedFloor:eB("learned_floor").notNull().default(70),llmFloor:eB("llm_floor").notNull().default(75),reviewDollarThresholdCents:eB("review_dollar_threshold_cents"),llmDailyCostCapCents:eB("llm_daily_cost_cap_cents").notNull().default(500),allowedLayers:eY("allowed_layers").$type().notNull().default(Y`'["rule","signal","deterministic","learned"]'::jsonb`),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("classification_policies_entity_uidx").on(e.entityId)]),t5("learned_patterns",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),featureHash:tT("feature_hash").notNull(),eventType:tT("event_type").notNull(),accountId:tM("account_id").references(()=>nU.id),hitCount:eB("hit_count").notNull().default(1),overrideCount:eB("override_count").notNull().default(0),lastAcceptedAt:tj("last_accepted_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("learned_patterns_entity_hash_uidx").on(e.entityId,e.featureHash),ne("learned_patterns_entity_idx").on(e.entityId),ne("learned_patterns_entity_event_idx").on(e.entityId,e.eventType)]),t5("imported_positions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),accountId:tM("account_id").references(()=>nU.id),treasuryAccountId:tM("treasury_account_id").references(()=>n7.id),importMethod:n0("import_method").notNull(),accountType:n1("account_type"),sourceFormat:tT("source_format"),importBatchId:tT("import_batch_id").notNull(),asOfDate:eS("as_of_date").notNull(),asset:tT("asset").notNull(),ticker:tT("ticker"),cusip:tT("cusip"),isin:tT("isin"),quantity:tT("quantity").notNull(),costBasis:tT("cost_basis"),marketValue:tT("market_value"),marketPrice:tT("market_price"),currency:tT("currency").notNull().default("USD"),externalId:tT("external_id"),rawData:eY("raw_data"),status:nZ("status").notNull().default("UNMATCHED"),matchedAccountId:tM("matched_account_id").references(()=>nU.id),ledgerQuantity:tT("ledger_quantity"),variance:tT("variance"),matchConfidence:eB("match_confidence"),reconciledAt:tj("reconciled_at"),reconciledBy:tT("reconciled_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("imported_pos_entity_idx").on(e.entityId),ne("imported_pos_batch_idx").on(e.importBatchId),ne("imported_pos_status_idx").on(e.status),ne("imported_pos_date_idx").on(e.asOfDate),ne("imported_pos_asset_idx").on(e.asset)]),t5("imported_balances",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),accountId:tM("account_id").references(()=>nU.id),importMethod:n0("import_method").notNull(),accountType:n1("account_type"),sourceFormat:tT("source_format"),importBatchId:tT("import_batch_id").notNull(),asOfDate:eS("as_of_date").notNull(),accountRef:tT("account_ref").notNull(),balance:tT("balance").notNull(),currency:tT("currency").notNull().default("USD"),externalId:tT("external_id"),rawData:eY("raw_data"),status:nZ("status").notNull().default("UNMATCHED"),matchedAccountId:tM("matched_account_id").references(()=>nU.id),ledgerBalance:tT("ledger_balance"),variance:tT("variance"),matchConfidence:eB("match_confidence"),reconciledAt:tj("reconciled_at"),reconciledBy:tT("reconciled_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("imported_bal_entity_idx").on(e.entityId),ne("imported_bal_batch_idx").on(e.importBatchId),ne("imported_bal_status_idx").on(e.status),ne("imported_bal_date_idx").on(e.asOfDate)]);let n5=L("treasury_account_type",["DEPOSITORY","CREDIT_CARD","LOAN","INVESTMENT","WALLET","CARD","CUSTODIAN"]),n3=L("treasury_account_status",["ACTIVE","INACTIVE","FROZEN","CLOSED"]),n9=L("treasury_auto_post_policy",["REVIEW_ALL","PATTERNS_ONLY","PATTERNS_PLUS_RULES"]),n7=t5("treasury_accounts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),ledgerAccountId:tM("ledger_account_id").references(()=>nU.id),balancePoolId:tM("balance_pool_id").references(()=>nj.id,{onDelete:"set null"}),type:n5("type").notNull(),autoPostPolicy:n9("auto_post_policy").notNull().default("REVIEW_ALL"),name:tT("name").notNull(),institution:tT("institution"),accountNumber:tT("account_number"),routingNumber:tT("routing_number"),iban:tT("iban"),swiftBic:tT("swift_bic"),walletAddress:tT("wallet_address"),chain:tT("chain"),currency:tT("currency").notNull().default("USD"),isStablecoin:ef("is_stablecoin").notNull().default(!1),stablecoinPeg:tT("stablecoin_peg"),status:n3("status").notNull().default("ACTIVE"),metadata:eY("metadata"),plaidAccessToken:tT("plaid_access_token"),plaidItemId:tT("plaid_item_id"),plaidAccountId:tT("plaid_account_id"),plaidInstitutionId:tT("plaid_institution_id"),institutionLogoDocumentId:tM("institution_logo_document_id"),plaidProducts:eY("plaid_products"),plaidSyncCursor:tT("plaid_sync_cursor"),plaidInvestmentsCursor:tT("plaid_investments_cursor"),plaidLastSyncedAt:tj("plaid_last_synced_at"),scannerCursor:tT("scanner_cursor"),scannerL
1astSyncedAt:tj("scanner_last_synced_at"),provider:tT("provider"),providerAccountId:tT("provider_account_id"),providerMetadata:eY("provider_metadata").$type(),providerStatus:tT("provider_status"),lastProviderSyncAt:tj("last_provider_sync_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("treasury_acct_entity_idx").on(e.entityId),ne("treasury_acct_type_idx").on(e.type),ne("treasury_acct_balance_pool_idx").on(e.balancePoolId),ne("treasury_acct_provider_idx").on(e.provider,e.providerAccountId),ne("treasury_acct_plaid_institution_idx").on(e.plaidInstitutionId),ne("treasury_acct_institution_logo_idx").on(e.institutionLogoDocumentId)]);t5("treasury_balances",{id:tM("id").primaryKey().defaultRandom(),treasuryAccountId:tM("treasury_account_id").notNull().references(()=>n7.id),asOfDate:eS("as_of_date").notNull(),balance:tT("balance").notNull(),availableBalance:tT("available_balance"),currency:tT("currency").notNull(),balanceFunctional:tT("balance_functional"),source:tT("source").notNull().default("MANUAL"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("treasury_bal_acct_idx").on(e.treasuryAccountId),ne("treasury_bal_date_idx").on(e.asOfDate)]);let de=L("counterparty_type",["PROSPECT","CUSTOMER","VENDOR","BOTH","BRIDGE","PROTOCOL","EXCHANGE","SELF_EXTERNAL","PERSON"]),dt=L("counterparty_lifecycle_status",["active","inactive","defunct","bankrupt_ch11","bankrupt_ch7","dissolved"]),dn=t5("counterparties",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),type:de("type").notNull(),contactId:tM("contact_id").references(()=>la.id),walletAddress:tT("wallet_address"),walletAddressHmac:tT("wallet_address_hmac"),chain:tT("chain"),defaultCurrency:tT("default_currency").notNull().default("USD"),classifyAs:tT("classify_as"),roleTags:eY("role_tags").$type().default(null),notes:tT("notes"),metadata:eY("metadata"),primaryAddressId:tM("primary_address_id").references(()=>lo.id,{onDelete:"set null"}),currentLifecycleStatus:dt("current_lifecycle_status").notNull().default("active"),lifecycleEffectiveAt:eS("lifecycle_effective_at"),partyId:tM("party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("counterparty_entity_idx").on(e.entityId),ne("counterparty_type_idx").on(e.type),ne("counterparty_contact_idx").on(e.contactId),ne("counterparty_primary_address_idx").on(e.primaryAddressId),ne("counterparty_lifecycle_status_idx").on(e.entityId,e.currentLifecycleStatus),ne("counterparties_party_idx").on(e.partyId),ne("counterparties_wallet_address_hmac_idx").on(e.entityId,e.walletAddressHmac)]);t5("vendor_profiles",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),onboardingStatus:tT("onboarding_status").default("pending"),w9OnFile:ef("w9_on_file").notNull().default(!1),requires1099:ef("requires_1099").notNull().default(!1),form1099Type:tT("form_1099_type"),insuranceExpiresAt:eS("insurance_expires_at"),defaultPaymentTerms:tT("default_payment_terms"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("vendor_profiles_entity_idx").on(e.entityId),ne("vendor_profiles_counterparty_idx").on(e.counterpartyId),nt("vendor_profiles_entity_counterparty_unique").on(e.entityId,e.counterpartyId)]),t5("vendor_risk_scores",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),score:tT("score").notNull(),tier:tT("tier").notNull(),factors:eY("factors").$type(),computedAt:tj("computed_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("vendor_risk_scores_entity_idx").on(e.entityId),ne("vendor_risk_scores_counterparty_idx").on(e.counterpartyId),nt("vendor_risk_scores_entity_counterparty_unique").on(e.entityId,e.counterpartyId)]);let dd=L("deal_addback_status",["YES","NO","REVIEW"]),da=L("deal_adjustment_category",["RECURRING","NON_RECURRING","DISCRETIONARY","NON_OPERATING"]);t5("deal_vendor_reviews",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),vendorKey:tT("vendor_key").notNull(),vendorLabel:tT("vendor_label").notNull(),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"set null"}),addBackStatus:dd("add_back_status").notNull().default("REVIEW"),adjustmentCategory:da("adjustment_category"),note:tT("note"),reviewedBy:tM("reviewed_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("deal_vendor_reviews_entity_idx").on(e.entityId),nt("deal_vendor_reviews_entity_vendor_uidx").on(e.entityId,e.vendorKey)]),t5("deal_expense_line_reviews",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),journalLineId:tM("journal_line_id").notNull().references(()=>nH.id,{onDelete:"cascade"}),addBackStatus:dd("add_back_status").notNull().default("REVIEW"),adjustmentCategory:da("adjustment_category"),note:tT("note"),reviewedBy:tM("reviewed_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("deal_expense_line_reviews_entity_idx").on(e.entityId),nt("deal_expense_line_reviews_entity_line_uidx").on(e.entityId,e.journalLineId)]),t5("deal_owner_comp_lines",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),ownerName:tT("owner_name").notNull(),actualCompensation:tT("actual_compensation").notNull(),marketReplacement:tT("market_replacement").notNull(),note:tT("note"),sortOrder:eB("sort_order").notNull().default(0),reviewedBy:tM("reviewed_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("deal_owner_comp_lines_entity_idx").on(e.entityId)]),t5("ap_automation_jobs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"set null"}),status:tT("status").notNull().default("queued"),source:tT("source").notNull().default("upload"),payload:eY("payload").$type(),errorMessage:tT("error_message"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("ap_automation_jobs_entity_idx").on(e.entityId),ne("ap_automation_jobs_status_idx").on(e.entityId,e.status)]),t5("vendor_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("ar_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("treasury_attestation_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("treasury_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()});let di=L("verifiable_scope_purpose",["RESERVE_ATTESTATION","PERIOD_CLOSE","RECEIVABLE_EXPORT","CUSTOM"]),dl=L("verification_binding_kind",["ORACLE_PLAID","ORACLE_STRIPE","ORACLE_CUSTODY","ORACLE_BANK_API","ONCHAIN_TX","ONCHAIN_BALANCE","ONCHAIN_SUPPLY","BILATERAL_ACK","MODULE_EXPENSES","MANUAL"]),dr=L("verification_binding_status",["BOUND","PENDING","UNBOUND","REJECTED"]),ds=t5("verifiable_scopes",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),slug:tT("slug").notNull(),name:tT("name").notNull(),description:tT("description"),purpose:di("purpose").notNull().default("CUSTOM"),balancePoolId:tM("balance_pool_id").references(()=>nj.id,{onDelete:"set null"}),rules:eY("rules").$type().notNull().default({}),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("verifiable_scopes_entity_slug_idx").on(e.entityId,e.slug),ne("verifiable_scopes_entity_purpose_idx").on(e.entityId,e.purpose)]);t5("verification_bindings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),scopeId:tM("scope_id").references(()=>ds.id,{onDelete:"set null"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"cascade"}),journalEntryId:tM("journal_entry_id").references(()=>nV.id,{onDelete:"cascade"}),bindingKind:dl("binding_kind").notNull(),status:dr("status").notNull().default("PENDING"),externalRef:tT("external_ref"),externalSource:tT("external_source"),attestationBundleHash:tT("attestation_bundle_hash"),observedAt:tj("observed_at"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("verification_bindings_entity_scope_idx").on(e.entityId,e.scopeId),ne("verification_bindings_event_idx").on(e.eventId),ne("verification_bindings_journal_idx").on(e.journalEntryId),ne("verification_bindings_external_ref_idx").on(e.externalRef)]);let d_=L("invoice_encumbrance_type",["EXCHANGE","FACTOR","INTERNAL_PLEDGE","OTHER"]),du=L("invoice_encumbrance_status",["ACTIVE","RELEASED"]),dc=L("ucc_clearance_status",["CLEAR","FILINGS_FOUND","STALE"]),dp=L("ucc_search_provider",["MANUAL","INTEGRATION"]),dy=L("qbo_sync_status",["PENDING","SYNCED","FAILED"]);t5("invoice_encumbrances",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),encumbranceType:d_("encumbrance_type").notNull(),holderRef:tT("holder_ref"),status:du("status").notNull().default("ACTIVE"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),releasedAt:tj("released_at")},e=>[ne("invoice_encumbrances_entity_idx").on(e.entityId),ne("invoice_encumbrances_invoice_idx").on(e.invoiceId),nt("invoice_encumbrances_one_active").on(e.invoiceId).where(Y`${e.status} = 'ACTIVE'`)]);let dm=t5("ucc_lien_searches",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),jurisdiction:tT("jurisdiction").notNull(),debtorLegalName:tT("debtor_legal_name").notNull(),searchDate:tj("search_date").notNull(),searchProvider:dp("search_provider").notNull(),filingsFound:eY("filings_found").$type(),clearanceStatus:dc("clearance_status").notNull(),certificateHash:tT("certificate_hash"),expiresAt:tj("expires_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ucc_lien_searches_entity_idx").on(e.entityId),ne("ucc_lien_searches_jurisdiction_idx").on(e.jurisdiction)]);t5("invoice_ucc_clearances",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),searchId:tM("search_id").notNull().references(()=>dm.id,{onDelete:"cascade"}),clearedAt:tj("cleared_at").notNull().defaultNow()},e=>[ne("invoice_ucc_clearances_entity_idx").on(e.entityId),ne("invoice_ucc_clearances_invoice_idx").on(e.invoiceId),ne("invoice_ucc_clearances_search_idx").on(e.searchId)]),t5("invoice_acknowledgments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),proposalId:tM("proposal_id").notNull().references(()=>dJ.id,{onDelete:"cascade"}),acceptToken:tT("accept_token"),status:tT("status").notNull(),tokenAckOnly:ef("token_ack_only").notNull().default(!1),externalSignerPublicKey:tT("external_signer_public_key"),externalSignerSignature:tT("external_signer_signature"),acceptedAt:tj("accepted_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("invoice_acknowledgments_entity_idx").on(e.entityId),ne("invoice_acknowledgments_invoice_idx").on(e.invoiceId),ne("invoice_acknowledgments_proposal_idx").on(e.proposalId),nt("invoice_acknowledgments_token_idx").on(e.acceptToken)]),t5("qbo_sync_outbox",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),eventType:tT("event_type").notNull(),resourceType:tT("resource_type").notNull(),resourceId:tM("resource_id").notNull(),payload:eY("payload").$type().notNull(),status:dy("status").notNull().default("PENDING"),qboRef:tT("qbo_ref"),errorMessage:tT("error_message"),createdAt:tj("created_at").notNull().defaultNow(),syncedAt:tj("synced_at")},e=>[ne("qbo_sync_outbox_entity_idx").on(e.entityId),ne("qbo_sync_outbox_status_idx").on(e.status),ne("qbo_sync_outbox_resource_idx").on(e.resourceType,e.resourceId)]),t5("sales_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>
1nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("expense_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("payroll_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("project_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()});let df=L("entity_deposit_payment_method_kind",["wire_check","usdc_wallet","bridge_virtual"]),dN=t5("entity_deposit_accounts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),label:tT("label").notNull(),paymentMethodKind:df("payment_method_kind").notNull().default("wire_check"),bankName:tT("bank_name"),routingNumber:tT("routing_number"),accountNumber:tT("account_number"),beneficiaryName:tT("beneficiary_name"),currency:tT("currency").notNull().default("USD"),isDefaultInvoicing:ef("is_default_invoicing").notNull().default(!1),isDefaultFundraising:ef("is_default_fundraising").notNull().default(!1),treasuryAccountId:tM("treasury_account_id").references(()=>n7.id,{onDelete:"set null"}),walletRecordId:tM("wallet_record_id").references(()=>lK.id,{onDelete:"set null"}),fundingAccountId:tM("funding_account_id").references(()=>l$.id,{onDelete:"set null"}),checkPayableTo:tT("check_payable_to"),checkMailingAddress:tT("check_mailing_address"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("entity_deposit_accounts_entity_idx").on(e.entityId),ne("entity_deposit_accounts_treasury_idx").on(e.treasuryAccountId),ne("entity_deposit_accounts_wallet_idx").on(e.walletRecordId),ne("entity_deposit_accounts_funding_idx").on(e.fundingAccountId)]);t5("vendor_portal_invites",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),tokenHash:tT("token_hash").notNull().unique(),label:tT("label"),expiresAt:tj("expires_at").notNull(),revokedAt:tj("revoked_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("vendor_portal_invites_entity_idx").on(e.entityId),ne("vendor_portal_invites_counterparty_idx").on(e.counterpartyId)]),t5("customer_site_portal_invites",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),tokenHash:tT("token_hash").notNull().unique(),label:tT("label"),expiresAt:tj("expires_at").notNull(),revokedAt:tj("revoked_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("customer_site_portal_invites_entity_idx").on(e.entityId),ne("customer_site_portal_invites_counterparty_idx").on(e.counterpartyId)]);let dI=L("invoice_status",["DRAFT","SENT","PARTIALLY_PAID","PAID","OVERDUE","VOID"]),dg=t5("invoices",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),customerId:tM("customer_id").notNull().references(()=>dn.id),invoiceNumber:tT("invoice_number").notNull(),issueDate:eS("issue_date").notNull(),dueDate:eS("due_date").notNull(),currency:tT("currency").notNull().default("USD"),subtotal:tT("subtotal").notNull(),taxAmount:tT("tax_amount").notNull().default("0"),totalAmount:tT("total_amount").notNull(),amountPaid:tT("amount_paid").notNull().default("0"),amountCredited:tT("amount_credited").notNull().default("0"),status:dI("status").notNull().default("DRAFT"),memo:tT("memo"),paymentTerms:tT("payment_terms"),acceptCrypto:ef("accept_crypto").notNull().default(!1),walletAddress:tT("wallet_address"),chain:tT("chain"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id").references(()=>dj.id),projectId:tM("project_id"),shareToken:tT("share_token"),paidAt:tj("paid_at"),revenueContractId:tM("revenue_contract_id").references(()=>a1.id,{onDelete:"set null"}),billToAddressId:tM("bill_to_address_id").references(()=>lo.id,{onDelete:"set null"}),shipToAddressId:tM("ship_to_address_id").references(()=>lo.id,{onDelete:"set null"}),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),billingPeriodStart:eS("billing_period_start"),billingPeriodEnd:eS("billing_period_end"),deliveryMemo:tT("delivery_memo"),sentAt:tj("sent_at"),lastSentConnectionId:tM("last_sent_connection_id").references(()=>ap.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("invoice_entity_idx").on(e.entityId),ne("invoice_customer_idx").on(e.customerId),ne("invoice_status_idx").on(e.status),ne("invoice_due_idx").on(e.dueDate),ne("invoice_project_idx").on(e.projectId),ne("invoices_revenue_contract_idx").on(e.revenueContractId),ne("invoices_bill_to_address_idx").on(e.b
1illToAddressId),ne("invoices_ship_to_address_idx").on(e.shipToAddressId),ne("invoices_site_idx").on(e.entityId,e.siteId),nt("invoice_number_entity_idx").on(e.entityId,e.invoiceNumber),nt("invoice_share_token_idx").on(e.shareToken)]);t5("invoice_line_items",{id:tM("id").primaryKey().defaultRandom(),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),description:tT("description").notNull(),quantity:tT("quantity").notNull().default("1"),unitPrice:tT("unit_price").notNull(),amount:tT("amount").notNull(),taxRateId:tM("tax_rate_id").references(()=>d3.id),taxAmount:tT("tax_amount"),revenueAccountId:tM("revenue_account_id").references(()=>nU.id),itemId:tM("item_id").references(()=>oL.id),itemKind:nl("item_kind"),sku:tT("sku"),unitOfMeasure:tT("unit_of_measure"),unitCostSnapshot:tT("unit_cost_snapshot"),parentLineId:tM("parent_line_id"),dropshipBillLineItemId:tM("dropship_bill_line_item_id").references(()=>dx.id),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"})},e=>[ne("line_item_invoice_idx").on(e.invoiceId),ne("line_item_tax_rate_idx").on(e.taxRateId),ne("line_item_item_idx").on(e.itemId),ne("line_item_parent_idx").on(e.parentLineId),ne("line_item_dropship_bill_idx").on(e.dropshipBillLineItemId),ne("line_item_site_idx").on(e.siteId)]);let db=L("bill_status",["DRAFT","RECEIVED","APPROVED","PARTIALLY_PAID","PAID","OVERDUE","VOID"]),dh=L("po_match_status",["UNMATCHED","PARTIAL","MATCHED","OVER"]),dv=t5("bills",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),vendorId:tM("vendor_id").notNull().references(()=>dn.id),billNumber:tT("bill_number").notNull(),vendorInvoiceNumber:tT("vendor_invoice_number"),documentFingerprintHmac:tT("document_fingerprint_hmac"),issueDate:eS("issue_date").notNull(),dueDate:eS("due_date").notNull(),currency:tT("currency").notNull().default("USD"),subtotal:tT("subtotal").notNull(),taxAmount:tT("tax_amount").notNull().default("0"),totalAmount:tT("total_amount").notNull(),amountPaid:tT("amount_paid").notNull().default("0"),amountDebited:tT("amount_debited").notNull().default("0"),status:db("status").notNull().default("DRAFT"),memo:tT("memo"),paymentTerms:tT("payment_terms"),payCrypto:ef("pay_crypto").notNull().default(!1),vendorWalletAddress:tT("vendor_wallet_address"),vendorChain:tT("vendor_chain"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id").references(()=>dj.id),paidAt:tj("paid_at"),purchaseOrderId:tM("purchase_order_id").references(()=>l0.id),poMatchStatus:dh("po_match_status"),matchedAmount:tT("matched_amount"),pendingStagedTransactionId:tM("pending_staged_transaction_id").references(()=>n4.id,{onDelete:"set null"}),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("bill_entity_idx").on(e.entityId),ne("bill_vendor_idx").on(e.vendorId),ne("bill_status_idx").on(e.status),ne("bill_due_idx").on(e.dueDate),ne("bill_po_idx").on(e.purchaseOrderId),ne("bill_site_idx").on(e.entityId,e.siteId),ne("bills_doc_fingerprint_idx").on(e.entityId,e.documentFingerprintHmac),ne("bills_pending_staged_tx_idx").on(e.entityId,e.pendingStagedTransactionId),nt("bills_pending_staged_tx_uidx").on(e.pendingStagedTransactionId),nt("bill_number_entity_idx").on(e.entityId,e.billNumber)]),dx=t5("bill_line_items",{id:tM("id").primaryKey().defaultRandom(),billId:tM("bill_id").notNull().references(()=>dv.id,{onDelete:"cascade"}),description:tT("description").notNull(),quantity:tT("quantity").notNull().default("1"),unitPrice:tT("unit_price").notNull(),amount:tT("amount").notNull(),expenseAccountId:tM("expense_account_id").references(()=>nU.id),itemId:tM("item_id").references(()=>oL.id),itemKind:nl("item_kind"),sku:tT("sku"),unitOfMeasure:tT("unit_of_measure"),unitCostSnapshot:tT("unit_cost_snapshot"),parentLineId:tM("parent_line_id"),salesOrderLineId:tM("sales_order_line_id").references(()=>l9.id),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"})},e=>
1[ne("bill_line_item_bill_idx").on(e.billId),ne("bill_line_item_item_idx").on(e.itemId),ne("bill_line_item_parent_idx").on(e.parentLineId),ne("bill_line_item_so_line_idx").on(e.salesOrderLineId),ne("bill_line_item_site_idx").on(e.siteId)]),dA=L("payment_type",["RECEIVABLE","PAYABLE"]),dD=L("payment_method",["ACH","WIRE","CHECK","CRYPTO","CREDIT_CARD","BANK_ACCOUNT","OTHER"]),dw=t5("counterparty_payment_methods",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),method:dD("method").notNull(),currency:tT("currency").notNull().default("USD"),bankRoutingNumber:tT("bank_routing_number"),bankAccountNumber:tT("bank_account_number"),bankAccountType:tT("bank_account_type"),walletAddress:tT("wallet_address"),chain:tT("chain"),iban:tT("iban"),swiftBic:tT("swift_bic"),accountProvider:tT("account_provider"),providerExternalAccountId:tT("provider_external_account_id"),providerMetadata:eY("provider_metadata").$type(),isDefault:ef("is_default").notNull().default(!1),verificationStatus:tT("verification_status"),accountHmac:tT("account_hmac"),addedAt:tj("added_at"),lastEditedAt:tj("last_edited_at"),cooldownUntil:tj("cooldown_until"),cooldownStartedBy:tM("cooldown_started_by"),callbackVerifiedAt:tj("callback_verified_at"),callbackVerifiedBy:tM("callback_verified_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cpm_entity_idx").on(e.entityId),ne("cpm_counterparty_idx").on(e.counterpartyId),ne("cpm_hmac_idx").on(e.accountHmac),ne("cpm_cooldown_idx").on(e.cooldownUntil),nt("cpm_counterparty_hmac_uidx").on(e.counterpartyId,e.accountHmac).where(Y`${e.accountHmac} is not null`)]),dE=L("bank_transfer_lifecycle",["requested","submitted","pending","settled","failed","returned","reversed","cancelled"]),dR=t5("payments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),type:dA("type").notNull(),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id),invoiceId:tM("invoice_id").references(()=>dg.id),billId:tM("bill_id").references(()=>dv.id),amount:tT("amount").notNull(),currency:tT("currency").notNull(),method:dD("method").notNull(),reference:tT("reference"),txHash:tT("tx_hash"),chain:tT("chain"),paymentDate:eS("payment_date").notNull(),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id").references(()=>dj.id),transferLifecycle:dE("transfer_lifecycle"),bankProvider:tT("bank_provider"),providerTransferId:tT("provider_transfer_id"),bankProviderMetadata:eY("bank_provider_metadata").$type(),idempotencyKey:tT("idempotency_key"),fromTreasuryAccountId:tM("from_treasury_account_id").references(()=>n7.id),toCounterpartyPaymentMethodId:tM("to_counterparty_payment_method_id").references(()=>dw.id),submittedAt:tj("submitted_at"),settledAt:tj("settled_at"),failedAt:tj("failed_at"),failureReason:tT("failure_reason"),returnCode:tT("return_code"),payrollRunId:tM("payroll_run_id").references(()=>iG.id),paymentFileId:tM("payment_file_id").references(()=>iw.id),approvalStatus:tT("approval_status"),approvalRequiredCount:eB("approval_required_count"),screeningStatus:tT("screening_status"),screeningAlertId:tM("screening_alert_id"),originatorName:tT("originator_name"),originatorAddress:tT("originator_address"),beneficiaryName:tT("beneficiary_name"),beneficiaryAddress:tT("beneficiary_address"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("payment_entity_idx").on(e.entityId),ne("payment_invoice_idx").on(e.invoiceId),ne("payment_bill_idx").on(e.billId),ne("payment_counterparty_idx").on(e.counterpartyId),ne("payment_treasury_idx").on(e.fromTreasuryAccountId),ne("payment_cpm_idx").on(e.toCounterpartyPaymentMethodId),ne("payment_payroll_run_idx").on(e.payrollRunId),ne("payment_provider_idx").on(e.bankProvider,e.providerTransferId),ne("payment_approval_status_idx").on(e.approvalStatus),ne("payment_site_idx").on(e.entityId,e.siteId),nt("payment_idempotency_uidx").on(e.idempotencyKey).where(Y`${e.idempotencyKey} is not null`)]);t5("bank_transfer_events",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),paymentId:tM("payment_id").references(()=>dR.id,{onDelete:"set null"}),treasuryAccountId:tM("treasury_account_id").references(()=>n7.id),provider:tT("provider").notNull(),providerEventId:tT("provider_event_id").notNull().unique(),eventType:tT("event_type").notNull(),receivedAt:tj("received_at").notNull().defaultNow(),processedAt:tj("processed_at"),payload:tT("payload"),error:tT("error"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("bte_entity_idx").on(e.entityId),ne("bte_payment_idx").on(e.paymentId),ne("bte_treasury_idx").on(e.treasuryAccountId),ne("bte_provider_event_idx").on(e.provider,e.eventType)]),t5("aml_customer_profile",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),industryNaics:tT("industry_naics"),businessPurpose:tT("business_purpose"),expectedOutflowBand:eY("expected_outflow_band").$type(),expectedInflowBand:eY("expected_inflow_band").$type(),expectedCounterpartyTypes:eY("expected_counterparty_types").$type(),expectedPaymentRails:eY("expected_payment_rails").$type(),expectedGeographies:eY("expected_geographies").$type(),cashIntensiveFlag:ef("cash_intensive_flag").notNull().default(!1),marketplaceFlag:ef("marketplace_flag").notNull().default(!1),cryptoAdjacentFlag:ef("crypto_adjacent_flag").notNull().default(!1),pepLinkage:ef("pep_linkage").notNull().default(!1),ofacScreenedAt:tj("ofac_screened_at"),adverseMediaScreenedAt:tj("adverse_media_screened_at"),riskRating:tT("risk_rating"),nextRefreshDueAt:tj("next_refresh_due_at"),eddRequired:ef("edd_required").notNull().default(!1),eddConditions:eY("edd_conditions").$type(),wireThresholdCents:eB("wire_threshold_cents").notNull().default(25e5),achThresholdCents:eB("ach_threshold_cents").notNull().default(5e6),wireAggregateDailyCents:eB("wire_aggregate_daily_cents").notNull().default(1e7),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("compliance_audit_log",{id:er("id",{mode:"number"}).primaryKey().generatedAlwaysAsIdentity({name:"compliance_audit_log_id_seq"}),occurredAt:tj("occurred_at").notNull().defaultNow(),actorKind:tT("actor_kind").notNull(),actorId:tT("actor_id"),entityId:tM("entity_id"),category:tT("category").notNull(),action:tT("action").notNull(),targetKind:tT("target_kind"),targetId:tT("target_id"),priorState:eY("prior_state"),nextState:eY("next_state"),rationale:tT("rationale"),attachments:eY("attachments")},e=>[ne("comp_audit_entity_occurred_idx").on(e.entityId,e.occurredAt),ne("comp_audit_category_idx").on(e.category),ne("comp_audit_target_idx").on(e.targetKind,e.targetId)]);let dk=t5("screening_alerts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),subjectKind:tT("subject_kind").notNull(),subjectId:tT("subject_id"),subjectName:tT("subject_name"),screenedAgainst:tT("screened_against").notNull(),matchedListEntries:eY("matched_list_entries").$type(),score:eB("score"),status:tT("status").notNull().default("OPEN"),outcome:tT("outcome"),reviewedBy:tM("reviewed_by"),reviewedAt:tj("reviewed_at"),reviewNotes:tT("review_notes"),context:eY("context").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("screening_alerts_entity_status_idx").on(e.entityId,e.status),ne("screening_alerts_subject_idx").on(e.subjectKind,e.subjectId)]);t5("bank_transfer_approvals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),paymentId:tM("payment_id").notNull().references(()=>dR.id,{onDelete:"cascade"}),requiredApprovals:eB("required_approvals").notNull().default(2),currentApprovals:eB("current_approvals").notNull().default(0),approvers:eY("approvers").$type().notNull().default(Y`'[]'::jsonb`),decliners:eY("decliners").$type().notNull().default(Y`'[]'::jsonb`),status:tT("status").notNull().default("PENDING"),requestedBy:tM("requested_by").notNull(),requestedAt:tj("requested_at").notNull().defaultNow(),decidedAt:tj("decided_at"),rationale:tT("rationale")},e=>[ne("bta_entity_status_idx").on(e.entityId,e.status),ne("bta_payment_idx").on(e.paymentId)]);let dT=t5("inbound_credits",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),treasuryAccountId:tM("treasury_account_id").references(()=>n7.id,{onDelete:"set null"}),provider:tT("provider").notNull().default("column"),providerTransferId:tT("provider_transfer_id"),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USD"),originatorName:tT("originator_name"),originatorAddress:tT("originator_address"),originatorAccountHmac:tT("originator_account_hmac"),originatorRoutingHmac:tT("originator_routing_hmac"),rail:tT("rail"),reference:tT("reference"),receivedAt:tj("received_at").notNull().defaultNow(),status:tT("status").notNull().default("PENDING_HOLD"),holdUntil:tj("hold_until"),releasedAt:tj("released_at"),matchedInvoiceId:tM("matched_invoice_id").references(()=>dg.id,{onDelete:"set null"}),matchedAt:tj("matched_at"),matchedBy:tM("matched_by"),matchStrategy:tT("match_strategy"),sanctionsScreenedAt:tj("sanctions_screened_at"),sanctionsAlertId:tM("sanctions_alert_id").references(()=>dk.id,{onDelete:"set null"}),ledgerEventId:tM("ledger_event_id"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inbound_credits_entity_status_idx").on(e.entityId,e.status),ne("inbound_credits_hold_until_idx").on(e.holdUntil),ne("inbound_credits_provider_id_idx").on(e.provider,e.providerTransferId),ne("inbound_credits_invoice_idx").on(e.matchedInvoiceId),nt("inbound_credits_provider_unique").on(e.provider,e.providerTransferId).where(Y`${e.providerTransferId} is not null`)]);t5("bsa_monitoring_alerts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),scenarioKey:tT("scenario_key").notNull(),subjectKind:tT("subject_kind"),subjectId:tT("subject_id"),score:eB("score"),summary:tT("summary"),details:eY("details").$type(),status:tT("status").notNull().default("OPEN"),disposition:tT("disposition"),assignedTo:tM("assigned_to"),resolvedBy:tM("resolved_by"),resolvedAt:tj("resolved_at"),sarFiled:ef("sar_filed").notNull().default(!1),sarFiledAt:tj("sar_filed_at"),sarReference:tT("sar_reference"),lookbackWindowDays:eB("lookback_window_days"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("bsa_alerts_entity_status_idx").on(e.entityId,e.status),ne("bsa_alerts_scenario_idx").on(e.scenarioKey,e.createdAt),nt("bsa_alerts_dedupe_idx").on(e.entityId,e.scenarioKey,e.subjectKind,e.subjectId).where(Y`${e.status} = 'OPEN' AND ${e.subjectId} is not null`)]),t5("column_transactions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),treasuryAccountId:tM("treasury_account_id").notNull().references(()=>n7.id,{onDelete:"cascade"}),provider:tT("provider").notNull().default("column"),providerTransactionId:tT("provider_transaction_id").notNull(),providerEventType:tT("provider_event_type"),direction:tT("direction").notNull(),rail:tT("rail"),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USD"),description:tT("description"),occurredAt:tj("occurred_at").notNull(),settledAt:tj("settled_at"),linkedPaymentId:tM("linked_payment_id").references(()=>dR.id,{onDelete:"set null"}),linkedInboundCreditId:tM("linked_inbound_credit_id").references(()=>dT.id,{onDelete:"set null"}),matchStatus:tT("match_status").notNull().default("UNMATCHED"),raw:eY("raw").$type(),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("column_transactions_provider_unique").on(e.provider,e.providerTransactionId),ne("column_transactions_account_occurred_idx").on(e.treasuryAccountId,e.occurredAt),ne("column_transactions_match_idx").on(e.entityId,e.matchStatus)]);let dS=t5("kyb_cases",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),status:tT("status").notNull().default("DRAFT"),stage:tT("stage").notNull().default("CIP_NOTICE"),applicantUserId:tM("applicant_user_id"),legalName:tT("legal_name"),einTaxId:tT("ein_tax_id"),formationJurisdiction:tT("formation_jurisdiction"),principalAddress:tT("principal_address"),naicsCode:tT("naics_code"),expectedOutflowCents:eB("expected_outflow_cents"),expectedInflowCents:eB("expected_inflow_cents"),businessPurpose:tT("business_purpose"),expectedCounterpartyTypes:eY("expected_counterparty_types").$type(),expectedPaymentRails:eY("expected_payment_rail
1s").$type(),expectedGeographies:eY("expected_geographies").$type(),signers:eY("signers").$type(),beneficialOwners:eY("beneficial_owners").$type(),controlPerson:eY("control_person").$type(),cipAcknowledgedAt:tj("cip_acknowledged_at"),esignAcknowledgedAt:tj("esign_acknowledged_at"),idVerificationStatus:tT("id_verification_status"),idVerificationProvider:tT("id_verification_provider"),idVerificationReference:tT("id_verification_reference"),idVerificationCompletedAt:tj("id_verification_completed_at"),sanctionsStatus:tT("sanctions_status"),sanctionsCompletedAt:tj("sanctions_completed_at"),riskRating:tT("risk_rating"),eddRequired:ef("edd_required").notNull().default(!1),forwardedToProviderAt:tj("forwarded_to_provider_at"),providerKybReference:tT("provider_kyb_reference"),activatedAt:tj("activated_at"),rejectedAt:tj("rejected_at"),rejectionReason:tT("rejection_reason"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("kyb_cases_entity_idx").on(e.entityId),ne("kyb_cases_status_idx").on(e.status),nt("kyb_cases_entity_active_unique").on(e.entityId).where(Y`${e.status} <> 'REJECTED'`)]);t5("kyb_case_events",{id:tM("id").primaryKey().defaultRandom(),caseId:tM("case_id").notNull().references(()=>dS.id,{onDelete:"cascade"}),occurredAt:tj("occurred_at").notNull().defaultNow(),actorKind:tT("actor_kind").notNull(),actorId:tT("actor_id"),eventType:tT("event_type").notNull(),fromStatus:tT("from_status"),toStatus:tT("to_status"),fromStage:tT("from_stage"),toStage:tT("to_stage"),payload:eY("payload").$type(),rationale:tT("rationale")},e=>[ne("kyb_case_events_case_idx").on(e.caseId,e.occurredAt)]),t5("kyb_case_documents",{id:tM("id").primaryKey().defaultRandom(),caseId:tM("case_id").notNull().references(()=>dS.id,{onDelete:"cascade"}),kind:tT("kind").notNull(),filename:tT("filename"),mimeType:tT("mime_type"),blobUrl:tT("blob_url"),blobMetadata:eY("blob_metadata").$type(),uploadedBy:tM("uploaded_by"),uploadedAt:tj("uploaded_at").notNull().defaultNow()},e=>[ne("kyb_case_documents_case_idx").on(e.caseId)]),t5("disputes",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),subjectKind:tT("subject_kind").notNull(),subjectId:tM("subject_id").notNull(),rail:tT("rail"),category:tT("category").notNull(),claimAmount:tT("claim_amount"),currency:tT("currency").notNull().default("USD"),summary:tT("summary"),details:tT("details"),evidence:eY("evidence").$type(),status:tT("status").notNull().default("OPEN"),deadlineAt:tj("deadline_at"),filedAt:tj("filed_at").notNull().defaultNow(),filedBy:tM("filed_by"),assignedTo:tM("assigned_to"),resolvedAt:tj("resolved_at"),resolution:tT("resolution"),remediationEventId:tM("remediation_event_id"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("disputes_entity_status_idx").on(e.entityId,e.status),ne("disputes_subject_idx").on(e.subjectKind,e.subjectId),ne("disputes_deadline_idx").on(e.deadlineAt)]);let dC=L("ar_ap_memo_status",["DRAFT","ISSUED","PARTIALLY_APPLIED","FULLY_APPLIED","VOID"]),dP=t5("credit_memos",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),customerId:tM("customer_id").notNull().references(()=>dn.id),creditNumber:tT("credit_number").notNull(),issueDate:eS("issue_date").notNull(),currency:tT("currency").notNull().default("USD"),subtotal:tT("subtotal").notNull(),taxAmount:tT("tax_amount").notNull().default("0"),totalAmount:tT("total_amount").notNull(),amountApplied:tT("amount_applied").notNull().default("0"),status:dC("status").notNull().default("DRAFT"),memo:tT("memo"),internalNotes:tT("internal_notes"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id").references(()=>dj.id),sourceType:tT("source_type"),sourceId:tM("source_id"),refundPaymentId:tM("refund_payment_id").references(()=>dR.id),functionalAmount:tT("functional_amount"),fxRate:tT("fx_rate"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("credit_memos_entity_idx").on(e.entityId),ne("credit_memos_customer_idx").on(e.customerId),ne("credit_memos_status_idx").on(e.status),nt("credit_memos_number_entity_idx").on(e.entityId,e.creditNumber)]);t5("credit_memo_line_items",{id:tM("id").primaryKey().defaultRandom(),creditMemoId:tM("credit_memo_
1id").notNull().references(()=>dP.id,{onDelete:"cascade"}),description:tT("description").notNull(),quantity:tT("quantity").notNull().default("1"),unitPrice:tT("unit_price").notNull(),amount:tT("amount").notNull(),revenueAccountId:tM("revenue_account_id").references(()=>nU.id),itemId:tM("item_id").references(()=>oL.id),itemKind:nl("item_kind"),sku:tT("sku"),unitOfMeasure:tT("unit_of_measure"),unitCostSnapshot:tT("unit_cost_snapshot"),parentLineId:tM("parent_line_id")},e=>[ne("credit_memo_line_memo_idx").on(e.creditMemoId),ne("credit_memo_line_item_idx").on(e.itemId),ne("credit_memo_line_parent_idx").on(e.parentLineId)]),t5("credit_memo_applications",{id:tM("id").primaryKey().defaultRandom(),creditMemoId:tM("credit_memo_id").notNull().references(()=>dP.id,{onDelete:"cascade"}),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),amount:tT("amount").notNull(),appliedAt:eS("applied_at").notNull(),eventId:tM("event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("credit_memo_app_memo_idx").on(e.creditMemoId),ne("credit_memo_app_invoice_idx").on(e.invoiceId)]);let dO=t5("debit_memos",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),vendorId:tM("vendor_id").notNull().references(()=>dn.id),debitNumber:tT("debit_number").notNull(),issueDate:eS("issue_date").notNull(),currency:tT("currency").notNull().default("USD"),subtotal:tT("subtotal").notNull(),taxAmount:tT("tax_amount").notNull().default("0"),totalAmount:tT("total_amount").notNull(),amountApplied:tT("amount_applied").notNull().default("0"),status:dC("status").notNull().default("DRAFT"),memo:tT("memo"),internalNotes:tT("internal_notes"),relatedBillId:tM("related_bill_id").references(()=>dv.id),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id").references(()=>dj.id),functionalAmount:tT("functional_amount"),fxRate:tT("fx_rate"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("debit_memos_entity_idx").on(e.entityId),ne("debit_memos_vendor_idx").on(e.vendorId),ne("debit_memos_status_idx").on(e.status),nt("debit_memos_number_entity_idx").on(e.entityId,e.debitNumber)]);t5("debit_memo_line_items",{id:tM("id").primaryKey().defaultRandom(),debitMemoId:tM("debit_memo_id").notNull().references(()=>dO.id,{onDelete:"cascade"}),description:tT("description").notNull(),quantity:tT("quantity").notNull().default("1"),unitPrice:tT("unit_price").notNull(),amount:tT("amount").notNull(),expenseAccountId:tM("expense_account_id").references(()=>nU.id),itemId:tM("item_id").references(()=>oL.id),itemKind:nl("item_kind"),sku:tT("sku"),unitOfMeasure:tT("unit_of_measure"),unitCostSnapshot:tT("unit_cost_snapshot"),parentLineId:tM("parent_line_id")},e=>[ne("debit_memo_line_memo_idx").on(e.debitMemoId),ne("debit_memo_line_item_idx").on(e.itemId),ne("debit_memo_line_parent_idx").on(e.parentLineId)]),t5("debit_memo_applications",{id:tM("id").primaryKey().defaultRandom(),debitMemoId:tM("debit_memo_id").notNull().references(()=>dO.id,{onDelete:"cascade"}),billId:tM("bill_id").notNull().references(()=>dv.id,{onDelete:"cascade"}),amount:tT("amount").notNull(),appliedAt:eS("applied_at").notNull(),eventId:tM("event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("debit_memo_app_memo_idx").on(e.debitMemoId),ne("debit_memo_app_bill_idx").on(e.billId)]);let dK=L("posting_mode",["SUMMARY","DETAIL"]),dL=t5("subledger_configs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),moduleKey:tT("module_key").notNull(),name:tT("name").notNull(),controlAccountId:tM("control_account_id").notNull().references(()=>nU.id),ledgerId:tM("ledger_id").notNull().references(()=>nj.id),postingMode:dK("posting_mode").notNull().default("SUMMARY"),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("subledger_configs_entity_idx").on(e.entityId),ne("subledger_configs_entity_ledger_idx").on(e.entityId,e.ledgerId),nt("subledger_configs_entity_module_ledger_idx").on(e.entityId,e.moduleKey,e.ledgerId)]),dq=L("batch_status",["PENDING","POSTED","REVERSED"]),dj=t5("subledger_batches",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),subledgerConfigId:tM("subledger_config_id").notNull().references(()=>dL.id),periodStart:eS("period_start").notNull(),periodEnd:eS("period_end").notNull(),transactionCount:eB("transaction_count").notNull(),journalEntryId:tM("journal_entry_id").references(()=>nV.id),status:dq("status").notNull().default("POSTED"),summary:eY("summary"),postedAt:tj("posted_at").notNull().defaultNow(),postedBy:tM("posted_by")},e=>[ne("subledger_batches_entity_idx").on(e.entityId),ne("subledger_batches_config_idx").on(e.subledgerConfigId),ne("subledger_batches_period_idx").on(e.periodStart,e.periodEnd)]),dU=L("investor_type",["LP","GP"]),dB=t5("investors",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),legalName:tT("legal_name"),type:dU("type").notNull(),email:tT("email"),walletAddress:tT("wallet_address"),chain:tT("chain"),commitment:tT("commitment").notNull(),currency:tT("currency").notNull().default("USD"),class:tT("class").notNull().default("A"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("investor_entity_idx").on(e.entityId),ne("investor_type_idx").on(e.type)]),dM=L("capital_activity_type",["CONTRIBUTION","DISTRIBUTION","ALLOCATION","ADJUSTMENT"]);t5("capital_activities",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),investorId:tM("investor_id").notNull().references(()=>dB.id),type:dM("type").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USD"),description:tT("description"),effectiveDate:eS("effective_date").notNull(),eventId:tM("event_id").references(()=>nB.id),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cap_activity_entity_idx").on(e.entityId),ne("cap_activity_investor_idx").on(e.investorId),ne("cap_activity_date_idx").on(e.effectiveDate)]),t5("nav_snapshots",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),asOfDate:eS("as_of_date").notNull(),totalAssets:tT("total_assets").notNull(),totalLiabilities:tT("total_liabilities").notNull(),nav:tT("nav").notNull(),totalUnits:tT("total_units"),navPerUnit:tT("nav_per_unit"),currency:tT("currency").notNull().default("USD"),breakdown:eY("breakdown"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("nav_entity_idx").on(e.entityId),ne("nav_date_idx").on(e.asOfDate)]);let dF=L("waterfall_tier_type",["RETURN_OF_CAPITAL","PREFERRED_RETURN","CATCH_UP","RESIDUAL_SPLIT"]);t5("waterfall_tiers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),tierOrder:eB("tier_order").notNull(),type:dF("type").notNull(),participants:tT("participants").notNull().default("ALL"),parameters:eY("parameters").notNull().default({}),label:tT("label"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("wf_tier_entity_idx").on(e.entityId),ne("wf_tier_order_idx").on(e.entityId,e.tierOrder)]);
1let dV=L("beneficiary_type",["INCOME","REMAINDER","BOTH"]),dH=L("trust_type",["REVOCABLE","IRREVOCABLE","TESTAMENTARY","CHARITABLE","SPECIAL_NEEDS","OTHER"]),d$=L("allocation_category",["PRINCIPAL","INCOME"]);t5("trust_metadata",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id).unique(),trustType:dH("trust_type").notNull(),trustDate:eS("trust_date"),grantorName:tT("grantor_name"),trusteeName:tT("trustee_name"),successorTrusteeName:tT("successor_trustee_name"),governingLaw:tT("governing_law"),einTaxId:tT("ein_tax_id"),terminationDate:eS("termination_date"),terminationConditions:tT("termination_conditions"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("trust_metadata_entity_idx").on(e.entityId)]);let dG=t5("beneficiaries",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),legalName:tT("legal_name"),type:dV("type").notNull(),email:tT("email"),walletAddress:tT("wallet_address"),chain:tT("chain"),distributionPercentage:tT("distribution_percentage"),isActive:ef("is_active").notNull().default(!0),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("beneficiary_entity_idx").on(e.entityId),ne("beneficiary_type_idx").on(e.type)]),dz=L("trust_distribution_status",["PENDING","APPROVED","PAID","VOID"]);t5("trust_distributions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),beneficiaryId:tM("beneficiary_id").notNull().references(()=>dG.id),category:d$("category").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USD"),description:tT("description"),effectiveDate:eS("effective_date").notNull(),status:dz("status").notNull().default("PENDING"),eventId:tM("event_id").references(()=>nB.id),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("trust_dist_entity_idx").on(e.entityId),ne("trust_dist_beneficiary_idx").on(e.beneficiaryId),ne("trust_dist_date_idx").on(e.effectiveDate),ne("trust_dist_status_idx").on(e.status)]),t5("ai_proposals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),type:nx("type").notNull(),status:nA("status").notNull().default("PENDING"),prompt:tT("prompt").notNull(),proposal:eY("proposal").notNull(),validationResult:eY("validation_result"),proposedBy:tT("proposed_by").notNull().default("ai"),reviewedBy:tT("reviewed_by"),reviewedAt:tj("reviewed_at"),rejectionReason:tT("rejection_reason"),expiresAt:tj("expires_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ai_proposals_entity_idx").on(e.entityId),ne("ai_proposals_status_idx").on(e.status),ne("ai_proposals_type_idx").on(e.type)]);let dQ=t5("chats",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),userId:tM("user_id").notNull(),title:tT("title").notNull().default("New chat"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("chats_entity_idx").on(e.entityId),ne("chats_user_idx").on(e.userId),ne("chats_updated_idx").on(e.updatedAt)]);t5("chat_messages",{id:tM("id").primaryKey().defaultRandom(),chatId:tM("chat_id").notNull().references(()=>dQ.id,{onDelete:"cascade"}),role:tT("role").notNull(),parts:eY("parts").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("chat_messages_chat_idx").on(e.chatId)]);let dY=L("transition_status",["PROPOSED","ACCEPTED","REJECTED","EXPIRED","FINALIZED","VOIDED","UNACKNOWLEDGED"]),dW=L("receipt_action",["ACCEPTED","REJECTED","COUNTER_PROPOSED"]),dJ=t5("transition_proposals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),counterpartyEntityId:tM("counterparty_entity_id").references(()=>nP.id),externalCounterpartyName:tT("external_counterparty_name"),externalCounterpartyRef:tT("external_counterparty_ref"),protocolVersion:tT("protocol_version").notNull().default("1.0.0"),schemaVersion:tT("schema_version").notNull().default("1.0.0"),eventType:tT("event_type").notNull(),effectiveDate:eS("effective_date").notNull(),expiresAt:tj("expires_at"),defaultExpirationHours:eB("default_expiration_hours"),amount:tT("amount").notNull(),currency:tT("currency").notNull(),fxRate:tT("fx_rate"),fxRateDate:eS("fx_rate_date"),proposerRoles:eY("proposer_roles").notNull(),counterpartyRoles:eY("counterparty_roles").notNull(),lineItems:eY("line_items"),taxLines:eY("tax_lines"),reference:tT("reference"),correlationId:tM("correlation_id"),memo:tT("memo"),payload:eY("payload").notNull(),contentHash:tT("content_hash").notNull(),proposerSignature:tT("proposer_signature"),proposerWrappedKey:tT("proposer_wrapped_key"),counterpartyWrappedKey:tT("counterparty_wrapped_key"),unilateral:ef("unilateral").notNull().default(!1),correctedProposalId:tM("corrected_proposal_id"),parentProposalId:tM("parent_proposal_id").references(()=>dJ.id,{onDelete:"set null"}),disputeReplayHash:tT("dispute_replay_hash"),status:dY("status").notNull().default("PROPOSED"),eventId:tM("event_id").references(()=>nB.id),counterpartyEventId:tM("counterparty_event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("transition_proposals_hash_idx").on(e.contentHash),ne("transition_proposals_entity_idx").on(e.entityId),ne("transition_proposals_counterparty_idx").on(e.counterpartyEntityId),ne("transition_proposals_status_idx").on(e.status),ne("transition_proposals_type_idx").on(e.eventType),ne("transition_proposals_correlation_idx").on(e.correlationId),ne("transition_proposals_parent_idx").on(e.parentProposalId)]);t5("proposal_source_links",{id:tM("id").primaryKey().defaultRandom(),proposalId:tM("proposal_id").notNull().references(()=>
1dJ.id,{onDelete:"cascade"}),sourceKind:tT("source_kind").notNull(),sourceId:tM("source_id").notNull(),role:tT("role").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("proposal_source_links_unique_idx").on(e.proposalId,e.sourceKind,e.sourceId,e.role),ne("proposal_source_links_proposal_idx").on(e.proposalId),ne("proposal_source_links_source_idx").on(e.sourceKind,e.sourceId)]),t5("commitment_receipts",{id:tM("id").primaryKey().defaultRandom(),proposalId:tM("proposal_id").notNull().references(()=>dJ.id),entityId:tM("entity_id").notNull().references(()=>nP.id),action:dW("action").notNull(),contentHash:tT("content_hash").notNull(),counterpartySignature:tT("counterparty_signature"),rejectionReason:tT("rejection_reason"),counterProposalId:tM("counter_proposal_id").references(()=>dJ.id),eventId:tM("event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("commitment_receipts_proposal_idx").on(e.proposalId),ne("commitment_receipts_entity_idx").on(e.entityId)]),t5("protocol_posting_receipts",{id:tM("id").primaryKey().defaultRandom(),proposalId:tM("proposal_id").notNull().references(()=>dJ.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id),partyRole:tT("party_role").notNull(),contentHash:tT("content_hash").notNull(),receiptHash:tT("receipt_hash").notNull(),eventId:tM("event_id").notNull().references(()=>nB.id),journalEntryIds:eY("journal_entry_ids").notNull().default([]),affectedRoles:eY("affected_roles").notNull().default([]),preSubledgerRoots:eY("pre_subledger_roots").notNull().default([]),postSubledgerRoots:eY("post_subledger_roots").notNull().default([]),entitySignature:tT("entity_signature"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("protocol_posting_receipts_party_idx").on(e.proposalId,e.entityId),ne("protocol_posting_receipts_proposal_idx").on(e.proposalId),ne("protocol_posting_receipts_entity_idx").on(e.entityId)]),t5("proposal_key_grants",{id:tM("id").primaryKey().defaultRandom(),proposalId:tM("proposal_id").notNull().references(()=>dJ.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id),wrappedKey:tT("wrapped_key").notNull(),grantedBy:tM("granted_by").notNull().references(()=>nP.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("proposal_key_grants_unique_idx").on(e.proposalId,e.entityId),ne("proposal_key_grants_entity_idx").on(e.entityId),ne("proposal_key_grants_proposal_idx").on(e.proposalId)]),t5("execution_traces",{id:tM("id").primaryKey().defaultRandom(),eventId:tM("event_id").notNull().references(()=>nB.id),bookId:tM("book_id").notNull().references(()=>nq.id),rulePackId:tM("rule_pack_id"),rulePackVersion:tT("rule_pack_version"),effectiveRuleGraphHash:tT("effective_rule_graph_hash"),evaluations:eY("evaluations").notNull(),journalEntryIds:eY("journal_entry_ids").notNull(),startedAt:tj("started_at").notNull(),completedAt:tj("completed_at").notNull(),status:nh("status").notNull(),errorMessage:tT("error_message")},e=>[ne("execution_traces_event_idx").on(e.eventId),ne("execution_traces_book_idx").on(e.bookId)]);let dX=L("tax_type",["SALES_TAX","VAT","GST","WITHHOLDING","INCOME","EXCISE","PAYROLL","CUSTOM"]),dZ=L("tax_calculation_method",["FLAT_PERCENT","PROGRESSIVE_BRACKETS","CAPPED_WAGE_PERCENT","MARGINAL_ABOVE_CUMULATIVE_GROSS"]),d0=L("cost_category",["HARD","SOFT","MIXED"]),d1=L("tax_plan_basis",["cash","accrual"]),d2=L("tax_plan_election_status",["planned","filed","revoked"]),d4=L("tax_estimate_mode",["preview","auto_post"]),d6=L("tax_qre_category",["wages","contractor","supplies","cloud_computing","other"]),d8=L("tax_rd_pay_frequency",["weekly","biweekly","semi_monthly","monthly"]),d5=L("tax_qre_source",["payroll","invoice","manual"]),d3=t5("tax_rates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),taxType:dX("tax_type").notNull(),jurisdiction:tT("jurisdiction").notNull(),rate:td("rate",{precision:10,scale:6}).notNull(),compoundRate:td("compound_rate",{precision:10,scale:6}),effectiveFrom:eS("effective_from").notNull(),effectiveTo:eS("effective_to"),isReverseCharge:ef("is_reverse_charge").notNull().default(!1),appliesToAccountTypes:eY("applies_to_account_types"),liabilityAccountCode:tT("liability_account_code"),receivableAccountCode:tT("receivable_account_code"),description:tT("description"),isActive:ef("is_active").notNull().default(!0),calculationMethod:dZ("calculation_method").notNull().default("FLAT_PERCENT"),payrollComponent:tT("payroll_component"),payrollFilingStatus:tT("payroll_filing_status"),payrollStandardDeductionAnnual
1:td("payroll_standard_deduction_annual",{precision:12,scale:2}),payrollWageCapAnnual:td("payroll_wage_cap_annual",{precision:14,scale:2}),payrollCumulativeThreshold:td("payroll_cumulative_threshold",{precision:14,scale:2}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("tax_rates_entity_idx").on(e.entityId),ne("tax_rates_jurisdiction_idx").on(e.entityId,e.jurisdiction),ne("tax_rates_type_idx").on(e.entityId,e.taxType),ne("tax_rates_payroll_idx").on(e.entityId,e.payrollComponent)]);t5("tax_rate_brackets",{id:tM("id").primaryKey().defaultRandom(),taxRateId:tM("tax_rate_id").notNull().references(()=>d3.id,{onDelete:"cascade"}),bracketOrder:eB("bracket_order").notNull(),thresholdMin:td("threshold_min",{precision:18,scale:2}).notNull(),thresholdMax:td("threshold_max",{precision:18,scale:2}),baseTax:td("base_tax",{precision:18,scale:2}).notNull().default("0"),marginalRate:td("marginal_rate",{precision:10,scale:6}).notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("tax_rate_brackets_rate_idx").on(e.taxRateId)]);let d9=t5("cost_categories",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),category:d0("category").notNull(),parentId:tM("parent_id"),accountCodePattern:tT("account_code_pattern"),isCapitalizable:ef("is_capitalizable").notNull().default(!1),usefulLifeMonths:eB("useful_life_months"),description:tT("description"),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cost_categories_entity_idx").on(e.entityId),ne("cost_categories_parent_idx").on(e.parentId)]);t5("tax_lines",{id:tM("id").primaryKey().defaultRandom(),journalEntryId:tM("journal_entry_id").notNull().references(()=>nV.id,{onDelete:"cascade"}),taxRateId:tM("tax_rate_id").notNull().references(()=>d3.id),baseAmount:tT("base_amount").notNull(),taxAmount:tT("tax_amount").notNull(),jurisdiction:tT("jurisdiction").notNull(),taxType:dX("tax_type_col").notNull(),isReverseCharge:ef("is_reverse_charge").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("tax_lines_journal_idx").on(e.journalEntryId),ne("tax_lines_rate_idx").on(e.taxRateId),ne("tax_lines_jurisdiction_idx").on(e.jurisdiction)]),t5("tax_plan_profiles",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}).unique(),defaultTaxYear:eB("default_tax_year"),accountingBasis:d1("accounting_basis"),notesEncrypted:tT("notes_encrypted"),estimateMode:d4("estimate_mode").notNull().default("preview"),incomeBookId:tM("income_book_id").references(()=>nq.id,{onDelete:"set null"}),federalPackEnabled:ef("federal_pack_enabled").notNull().default(!0),showFleetMiles:ef("show_fleet_miles").notNull().default(!1),caPackEnabled:ef("ca_pack_enabled").notNull().default(!1),dePackEnabled:ef("de_pack_enabled").notNull().default(!1),deAuthorizedShares:eB("de_authorized_shares"),section174Enabled:ef("section_174_enabled").notNull().default(!1),rdCreditEnabled:ef("rd_credit_enabled").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()}),t5("tax_plan_elections",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),jurisdictionCode:tT("jurisdiction_code").notNull(),electionCode:tT("election_code").notNull(),status:d2("status").notNull().default("planned"),effectiveFrom:eS("effective_from").notNull(),effectiveTo:eS("effective_to"),amountEncrypted:tT("amount_encrypted"),notesEncrypted:tT("notes_encrypted"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("tax_plan_elections_entity_idx").on(e.entityId)]);let d7=t5("tax_rd_projects",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),qualifiesForCredit:ef("qualifies_for_credit").notNull().default(!0),description:tT("description"),sortOrder:eB("sort_order").notNull().default(0),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("tax_rd_projects_entity_idx").on(e.entityId)]),ae=t5("tax_rd_compensation_policies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),personNameEncrypted:tT("person_name_encrypted").notNull(),roleLabel:tT("role_label"),annualSalaryEncrypted:tT("annual_salary_encrypted").notNull(),payFrequency:d8("pay_frequency").notNull().default("biweekly"),defaultQualifyingPercentEncrypted:tT("default_qualifying_percent_encrypted").notNull().default("100"),projectId:tM("project_id").references(()=>d7.id,{onDelete:"set null"}),effectiveFrom:eS("effective_from").notNull(),effectiveTo:eS("effective_to"),notesEncrypted:tT("notes_encrypted"),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("tax_rd_compensation_policies_entity_idx").on(e.entityId),ne("tax_rd_compensation_policies_project_idx").on(e.projectId)]);t5("tax_qre_entries",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),taxYear:eB("tax_year").notNull(),category:d6("category").notNull(),projectId:tM("project_id").references(()=>d7.id,{onDelete:"set null"}),compensationPolicyId:tM("compensation_policy_id").references(()=>ae.id,{onDelete:"set null"}),paidDate:eS("paid_date").notNull(),payPeriodLabel:tT("pay_period_label"),grossAmountEncrypted:tT("gross_amount_encrypted").notNull(),qualifyingPercentEncrypted:tT("qualifying_percent_encrypted").notNull(),descriptionEncrypted:tT("description_encrypted"),source:d5("source").notNull().default("manual"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("tax_qre_entries_entity_idx").on(e.entityId),ne("tax_qre_entries_entity_year_idx").on(e.entityId,e.taxYear),ne("tax_qre_entries_paid_date_idx").on(e.paidDate)]),t5("cost_reclassifications",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),journalEntryId:tM("journal_entry_id").references(()=>nV.id),fromCategoryId:tM("from_category_id").notNull().references(()=>d9.id),toCategoryId:tM("to_category_id").notNull().references(()=>d9.id),amount:td("amount",{precision:20,scale:8}).notNull(),effectiveDate:eS("effective_date").notNull(),reason:tT("reason"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cost_reclass_entity_idx").on(e.entityId),ne("cost_reclass_date_idx").on(e.effectiveDate)]);let at=L("payment_intent_type",["AP_PAYMENT","AR_COLLECTION","DISTRIBUTION","CAPITAL_CALL","TRANSFER"]),an=L("proof_type",["PERIOD_CLOSE","SOLVENCY","NAV","WATERFALL","SETTLEMENT","IC_RECONCILIATION","JOINSPLIT","INNOCENCE","RECEIVABLE","RECEIVABLE_BILATERAL","RECEIVABLE_POOL"]),ad=L("proof_status",["GENERATING","VALID","INVALID","FAILED"]),aa=L("payment_intent_status",["PENDING","SUBMITTED","CONFIRMED","FAILED","EXPIRED"]),ai=t5("payment_intents",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),type:at("type").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USDC"),chain:tT("chain").notNull().default("base"),fromWalletAddress:tT("from_wallet_address").notNull(),toWalletAddress:tT("to_wallet_address").notNull(),relatedInvoiceId:tM("related_invoice_id").references(()=>dg.id),relatedBillId:tM("related_bill_id").references(()=>dv.id),status:aa("status").notNull().default("PENDING"),txHash:tT("tx_hash"),expiresAt:tj("expires_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("payment_intent_entity_idx").on(e.entityId),ne("payment_intent_status_idx").on(e.status)]),ao=t5("proofs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),bookId:tM("book_id").notNull().references(()=>nq.id),periodId:tM("period_id").references(()=>n$.id),type:an("type").notNull(),status:ad("status").notNull().default("GENERATING"),publicInputs:eY("public_inputs").notNull(),proofBytes:tT("proof_bytes"),verificationKey:tT("verification_key"),generatedAt:tj("generated_at"),verifiedAt:tj("verified_at"),anchoredOnchain:ef("anchored_onchain").default(!1),anchorTxHash:tT("anch
1or_tx_hash"),anchorChainId:eB("anchor_chain_id"),snapshotId:tM("snapshot_id").references(()=>nG.id),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("proof_entity_idx").on(e.entityId),ne("proof_book_idx").on(e.bookId),ne("proof_period_idx").on(e.periodId),ne("proof_type_idx").on(e.type),ne("proof_status_idx").on(e.status)]);t5("receivable_proof_shares",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),proofId:tM("proof_id").references(()=>ao.id,{onDelete:"set null"}),shareId:tT("share_id").notNull(),bundleHash:tT("bundle_hash").notNull(),expiresAt:tj("expires_at"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("receivable_proof_shares_share_idx").on(e.shareId)]),t5("close_certificate_shares",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),periodId:tM("period_id").notNull().references(()=>n$.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id,{onDelete:"cascade"}),proofId:tM("proof_id").references(()=>ao.id,{onDelete:"set null"}),shareId:tT("share_id").notNull(),bundleHash:tT("bundle_hash").notNull(),expiresAt:tj("expires_at"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("close_certificate_shares_share_idx").on(e.shareId),ne("close_certificate_shares_period_idx").on(e.periodId)]),t5("balance_attestation_shares",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),shareId:tT("share_id").notNull(),bundleHash:tT("bundle_hash").notNull(),asOf:tj("as_of").notNull(),expiresAt:tj("expires_at"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("balance_attestation_shares_share_idx").on(e.shareId),ne("balance_attestation_shares_entity_idx").on(e.entityId)]),t5("receivable_export_log",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),bundleHash:tT("bundle_hash").notNull(),entitySignature:tT("entity_signature"),exportedBy:tM("exported_by"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("receivable_export_log_invoice_idx").on(e.invoiceId)]),t5("receivable_ledger_chunks",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id,{onDelete:"cascade"}),chunkRoot:tT("chunk_root").notNull(),openArMerkleRoot:tT("open_ar_merkle_root").notNull(),encumbranceMerkleRoot:tT("encumbrance_merkle_root").notNull(),auditChainHeadHash:tT("audit_chain_head_hash"),controlBalanceCents:tT("control_balance_cents").notNull(),asOfTimestamp:tj("as_of_timestamp").notNull(),anchorTxHash:tT("anch
1or_tx_hash"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("receivable_ledger_chunks_entity_idx").on(e.entityId),ne("receivable_ledger_chunks_root_idx").on(e.chunkRoot)]),t5("canonical_settlements",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),eventId:tM("event_id").references(()=>nB.id),sourceType:nR("source_type").notNull(),sourceId:tT("source_id").notNull(),eventType:tT("event_type").notNull(),direction:nk("direction").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull(),counterpartyId:tM("counterparty_id").references(()=>dn.id),counterpartyAddress:tT("counterparty_address"),counterpartyEntityId:tM("counterparty_entity_id").references(()=>nP.id),externalCounterpartyRef:tT("external_counterparty_ref"),externalCounterpartyName:tT("external_counterparty_name"),settlementDate:tj("settlement_date").notNull(),txHash:tT("tx_hash"),chain:tT("chain"),proofId:tM("proof_id").references(()=>ao.id),anchorTxHash:tT("anchor_tx_hash"),stagedTransactionId:tM("staged_transaction_id").references(()=>n4.id),paymentIntentId:tM("payment_intent_id").references(()=>ai.id),proposalId:tM("proposal_id").references(()=>dJ.id),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cs_entity_idx").on(e.entityId),ne("cs_source_type_idx").on(e.sourceType),ne("cs_event_type_idx").on(e.eventType),ne("cs_direction_idx").on(e.direction),ne("cs_settlement_date_idx").on(e.settlementDate),ne("cs_tx_hash_idx").on(e.txHash),nt("cs_source_unique_idx").on(e.sourceType,e.sourceId)]);let al=L("batch_frequency",["DAILY","WEEKLY","REALTIME"]);t5("settlement_batches",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),counterpartyEntityId:tM("counterparty_entity_id").references(()=>nP.id),frequency:al("frequency").notNull(),periodStart:tj("period_start").notNull(),periodEnd:tj("period_end").notNull(),transitionCount:eB("transition_count").notNull().default(0),netAmount:tT("net_amount"),currency:tT("currency"),proposalIds:eY("proposal_ids"),status:tT("status").notNull().default("OPEN"),finalizedAt:tj("finalized_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("sb_entity_idx").on(e.entityId),ne("sb_counterparty_idx").on(e.counterpartyEntityId),ne("sb_status_idx").on(e.status),ne("sb_period_idx").on(e.periodStart,e.periodEnd)]),t5("counterparty_settings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),counterpartyEntityId:tM("counterparty_entity_id").notNull().references(()=>
1nP.id),settlementMode:al("settlement_mode").notNull().default("DAILY"),autoFinalize:ef("auto_finalize").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("cs_entity_counterparty_idx").on(e.entityId,e.counterpartyEntityId)]);let ar=L("connection_provider",["plaid","mercury","column","stripe_revenue","quickbooks","xero","brex","ramp","coinbase","deel","csv_upload","custom_webhook","gmail","resend_email","github","cursor","google_ads","meta_ads","linkedin_ads","x_ads","twilio"]),as=L("connection_status",["ACTIVE","PAUSED","ERROR","DISCONNECTED"]),a_=L("sync_frequency",["MANUAL","HOURLY","DAILY","REALTIME"]),au=L("sync_status",["RUNNING","SUCCESS","PARTIAL","FAILED"]),ac=L("connection_mailbox_kind",["personal","shared"]),ap=t5("connections",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),provider:ar("provider").notNull(),displayName:tT("display_name").notNull(),status:as("status").notNull().default("ACTIVE"),credentials:tT("credentials"),config:eY("config").$type(),syncFrequency:a_("sync_frequency").notNull().default("MANUAL"),lastSyncAt:tj("last_sync_at"),lastSyncStatus:au("last_sync_status"),lastSyncError:tT("last_sync_error"),mailboxKind:ac("mailbox_kind"),connectedByIdentityId:tM("connected_by_identity_id"),sendAsEmail:tT("send_as_email"),mailboxLabel:tT("mailbox_label"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("conn_entity_idx").on(e.entityId),ne("conn_provider_idx").on(e.entityId,e.provider),ne("conn_entity_mailbox_idx").on(e.entityId,e.provider,e.mailboxKind)]);t5("sync_logs",{id:tM("id").primaryKey().defaultRandom(),connectionId:tM("connection_id").notNull().references(()=>ap.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),startedAt:tj("started_at").notNull().defaultNow(),completedAt:tj("completed_at"),status:au("status").notNull().default("RUNNING"),transactionsCreated:eB("transactions_created").notNull().default(0),duplicatesSkipped:eB("duplicates_skipped").notNull().default(0),quarantined:eB("quarantined").notNull().default(0),errors:eY("errors").$type().default([])},e=>[ne("synclog_conn_idx").on(e.connectionId),ne("synclog_entity_idx").on(e.entityId)]),t5("api_keys",{id:tM("id").primaryKey().defaultRandom(),userId:tM("user_id").notNull(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),keyHash:tT("key_hash").notNull(),keyPrefix:tT("key_prefix").notNull(),scopes:eY("scopes").$type().notNull(),rateLimit:eB("rate_limit").notNull().default(60),lastUsedAt:tj("last_used_at"),expiresAt:tj("expires_at"),revokedAt:tj("revoked_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("apikey_user_idx").on(e.userId),ne("apikey_entity_idx").on(e.entityId),nt("apikey_hash_idx").on(e.keyHash)]);let ay=t5("webhook_subscriptions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),url:tT("url").notNull(),events:eY("events").$type().notNull(),secret:tT("secret").notNull(),isActive:ef("is_active").notNull().default(!0),lastDeliveryAt:tj("last_delivery_at"),failureCount:eB("failure_count").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("whsub_entity_idx").on(e.entityId)]);t5("webhook_deliveries",{id:tM("id").primaryKey().defaultRandom(),subscriptionId:tM("subscription_id").notNull().references(()=>ay.id,{onDelete:"cascade"}),eventType:tT("event_type").notNull(),payload:eY("payload").$type().notNull(),statusCode:eB("status_code"),responseBody:tT("response_body"),attempts:eB("attempts").notNull().default(0),nextRetryAt:tj("next_retry_at"),deliveredAt:tj("delivered_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("whdel_sub_idx").on(e.subscriptionId),ne("whdel_retry_idx").on(e.nextRetryAt)]);let am=L("platform_event_status",["pending","processing","processed","failed","dead_letter"]);t5("platform_events",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),sourceApp:tT("source_app").notNull(),eventType:tT("event_type").notNull(),payload:eY("payload").$type().notNull(),dedupeKey:tT("dedupe_key"),status:am("status").notNull().default("pending"),error:tT("error"),availableAt:tj("available_at").notNull().defaultNow(),processedAt:tj("processed_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("platform_events_entity_idx").on(e.entityId),ne("platform_events_type_status_idx").on(e.eventType,e.status),ne("platform_events_available_idx").on(e.availableAt),nt("platform_events_dedupe_idx").on(e.entityId,e.dedupeKey)]),t5("platform_event_subscriptions",{id:tM("id").primaryKey().defaultRandom(),eventType:tT("event_type").notNull(),handlerName:tT("handler_name").notNull(),targetApp:tT("target_app").notNull(),active:ef("active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("platform_event_subscriptions_unique_idx").on(e.eventType,e.handlerName),ne("platform_event_subscriptions_active_idx").on(e.active)]);let af=L("partner_firm_status",["PENDING","ACTIVE","REJECTED"]),aN=t5("partner_firms",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),firmName:tT("firm_name").notNull(),contactEmail:tT("contact_email"),managedEntityCount:eB("managed_entity_count").notNull().default(0),isActive:ef("is_active").notNull().default(!0),status:af("status").notNull().default("PENDING"),description:tT("description"),websiteUrl:tT("website_url"),logoUrl:tT("logo_url"),location:tT("location"),services:eY("services").$type().notNull().default([]),approvedAt:tj("approved_at"),onboardedAt:tj("onboarded_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("pf_entity_idx").on(e.entityId),ne("pf_status_idx").on(e.status)]);t5("partner_client_entities",{id:tM("id").primaryKey().defaultRandom(),partnerFirmId:tM("partner_firm_id").notNull().references(()=>aN.id),entityId:tM("entity_id").notNull().references(()=>nP.id),billingMode:tT("billing_mode").notNull().default("consolidated"),isActive:ef("is_active").notNull().default(!0),onboardedAt:tj("onboarded_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("pce_partner_firm_idx").on(e.partnerFirmId),ne("pce_entity_idx").on(e.entityId),nt("pce_partner_entity_idx").on(e.partnerFirmId,e.entityId)]),t5("partner_entity_rollups",{id:tM("id").primaryKey().defaultRandom(),partnerFirmId:tM("partner_firm_id").notNull().references(()=>aN.id),entityId:tM("entity_id").notNull().references(()=>nP.id),pendingTransactions:eB("pending_transactions").notNull().default(0),reconPercentage:eB("recon_percentage").notNull().default(0),periodStatus:tT("period_status"),periodEndDate:eS("period_end_date"),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("per_partner_firm_idx").on(e.partnerFirmId),nt("per_partner_entity_idx").on(e.partnerFirmId,e.entityId)]),t5("admin_audit_logs",{id:tM("id").primaryKey().defaultRandom(),adminUserId:tM("admin_user_id").notNull(),action:tT("action").notNull(),targetType:tT("target_type").notNull(),targetId:tT("target_id"),metadata:eY("metadata").$type().default({}),ipAddress:tT("ip_address"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("audit_admin_idx").on(e.adminUserId),ne("audit_action_idx").on(e.action),ne("audit_target_idx").on(e.targetType,e.targetId),ne("audit_created_idx").on(e.createdAt)]),t5("match_patterns",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyPattern:tT("counterparty_pattern").notNull(),mappedAccountRole:tT("mapped_account_role"),mappedEventType:tT("mapped_event_type"),mappedAccountId:tM("mapped_account_id").references(()=>nU.id,{onDelete:"set null"}),mappedPayeeDisplayName:tT("mapped_payee_display_name"),savedAiReason:tT("saved_ai_reason"),savedAiEventType:tT("saved_ai_event_type"),savedAiAccountId:tM("saved_ai_account_id").references(()=>nU.id,{onDelete:"set null"}),matchCount:eB("match_count").notNull().default(1),lastUsedAt:tj("last_used_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow(),counterpartyAddressHmac:tT("counterparty_address_hmac"),tokenContract:tT("token_contract"),direction:tT("direction")},e=>[ne("match_patterns_entity_idx").on(e.entityId),ne("match_patterns_counterparty_idx").on(e.entityId,e.counterpartyPattern),ne("match_patterns_wallet_idx").on(e.entityId,e.counterpartyAddressHmac,e.tokenContract)]);let aI=L("token_classification_status",["spam","allowed","ignored"]);t5("token_classifications",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),chain:tT("chain").notNull(),contractAddress:tT("contract_address").notNull(),status:aI("status").notNull(),symbol:tT("symbol"),decidedBy:tT("decided_by").notNull().default("user"),decidedByIdentityId:tM("decided_by_identity_id"),reason:tT("reason"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("token_classifications_entity_contract_uidx").on(e.entityId,e.chain,e.contractAddress)]),t5("payee_directory",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),displayName:tT("display_name").notNull(),normalizedKeyHmac:tT("normalized_key_hmac").notNull(),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"set null"}),useCount:eB("use_count").notNull().default(0),lastUsedAt:tj("last_used_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("payee_directory_entity_idx").on(e.entityId),nt("payee_directory_entity_key_unique").on(e.entityId,e.normalizedKeyHmac),ne("payee_directory_counterparty_idx").on(e.counterpartyId),ne("payee_directory_entity_use_idx").on(e.entityId,e.useCount)]),t5("match_history",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),transactionId:tM("transaction_id").notNull().references(()=>n4.id),eventId:tM("event_id").references(()=>nB.id),accepted:ef("accepted").notNull(),confidence:eB("confidence").notNull(),matchReasons:eY("match_reasons").$type().default([]),matchedBy:tT("matched_by").notNull().default("auto"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("match_history_entity_idx").on(e.entityId),ne("match_history_tx_idx").on(e.transactionId)]);let ag=L("depreciation_method",["STRAIGHT_LINE","DECLINING_BALANCE"]),ab=L("fixed_asset_status",["ACTIVE","DISPOSED","FULLY_DEPRECIATED","CIP"]),ah=L("cip_status",["IN_PROGRESS","PLACED_IN_SERVICE"]),av=t5("fixed_assets",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),accountId:tM("account_id").notNull().references(()=>nU.id),name:tT("name").notNull(),description:tT("description"),acquiredDate:eS("acquired_date").notNull(),costBasis:td("cost_basis",{precision:20,scale:2}).notNull(),residualValue:td("residual_value",{precision:20,scale:2}).notNull().default("0"),usefulLifeMonths:eB("useful_life_months").notNull(),depreciationMethod:ag("depreciation_method").notNull().default("STRAIGHT_LINE"),status:ab("status").notNull().default("ACTIVE"),disposedDate:eS("disposed_date"),disposalProceeds:td("disposal_proceeds",{precision:20,scale:2}),impairmentLoss:td("impairment_loss",{precision:20,scale:2}),revaluationSurplus:td("revaluation_surplus",{precision:20,scale:2}),cipStatus:ah("cip_status"),componentParentId:tM("component_parent_id"),depreciationAccountId:tM("depreciation_account_id").references(()=>nU.id),accumulatedDepreciationAccountId:tM("accumulated_depreciation_account_id").references(()=>nU.id),costCategoryId:tM("cost_category_id").references(()=>d9.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("fixed_assets_entity_idx").on(e.entityId),ne("fixed_assets_book_idx").on(e.bookId),ne("fixed_assets_status_idx").on(e.status)]);t5("asset_transfers",{id:tM("id").primaryKey().defaultRandom(),assetId:tM("asset_id").notNull().references(()=>av.id),fromEntityId:tM("from_entity_id").notNull().references(()=>nP.id),toEntityId:tM("to_entity_id").notNull().references(()=>nP.id),transferDate:eS("transfer_date").notNull(),transferValue:td("transfer_value",{precision:20,scale:2}).notNull(),reason:tT("reason"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("asset_transfers_asset_idx").on(e.assetId)]);let ax=L("lot_asset_type",["CRYPTO","SECURITY","REAL_ESTATE","OTHER","OPTION"]),aA=L("lot_side",["LONG","SHORT"]),aD=L("lot_source",["NATIVE","IMPORTED","MANUAL"]),aw=L("lot_status",["OPEN","PARTIALLY_DISPOSED","FULLY_DISPOSED"]),aE=L("holding_period",["SHORT_TERM","LONG_TERM"]),aR=t5("tax_lots",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),asset:tT("asset").notNull(),assetType:ax("asset_type").notNull(),side:aA("side").notNull().default("LONG"),source:aD("source").notNull().default("NATIVE"),acquiredDate:eS("acquired_date").notNull(),quantity:td("quantity",{precision:38,scale:18}).notNull(),remainingQuantity:td("remaining_quantity",{precision:38,scale:18}).notNull(),costBasisPerUnit:td("cost_basis_per_unit",{precision:38,scale:18}).notNull(),totalCostBasis:td("total_cost_basis",{precision:20,scale:2}).notNull(),currency:tT("currency").notNull().default("USD"),sourceEventId:tM("source_event_id"),sourceJournalEntryId:tM("source_journal_entry_id"),externalRef:tT("external_ref"),brokerName:tT("broker_name"),status:aw("status").notNull().default("OPEN"),metadata:eY("metadata"),holdingPeriodStartDate:eS("holding_period_start_date"),washSaleAdjustment:td("wash_sale_adjustment",{precision:20,scale:2}).notNull().default("0"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("tax_lots_entity_idx").on(e.entityId),ne("tax_lots_book_idx").on(e.bookId),ne("tax_lots_asset_idx").on(e.entityId,e.bookId,e.asset),ne("tax_lots_status_idx").on(e.status)]),ak=t5("lot_disposals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),lotId:tM("lot_id").notNull().references(()=>aR.id),disposalEventId:tM("disposal_event_id"),disposalJournalEntryId:tM("disposal_journal_entry_id"),disposalDate:eS("disposal_date").notNull(),quantityDisposed:td("quantity_disposed",{precision:38,scale:18}).notNull(),proceeds:td("proceeds",{precision:20,scale:2}).notNull(),costBasis:td("cost_basis",{precision:20,scale:2}).notNull(),realizedGainLoss:td("realized_gain_loss",{precision:20,scale:2}).notNull(),holdingPeriod:aE("holding_period").notNull(),method:tT("method").notNull(),source:aD("source").notNull().default("NATIVE"),metadata:eY("metadata"),washSaleDisallowed:td("wash_sale_disallowed",{precision:20,scale:2}).notNull().default("0"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("lot_disposals_entity_idx").on(e.entityId),ne("lot_disposals_lot_idx").on(e.lotId),ne("lot_disposals_event_idx").on(e.disposalEventId)]),aT=L("wash_sale_status",["APPLIED","FLAGGED","DISMISSED"]),aS=t5("wash_sale_adjustments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),lossDisposalId:tM("loss_disposal_id").notNull().references(()=>ak.id),lossLotId:tM("loss_lot_id").notNull().references(()=>aR.id),replacementLotId:tM("replacement_lot_id").references(()=>aR.id),sourceReplacementLotId:tM("source_replacement_lot_id").references(()=>
1aR.id),lossDate:eS("loss_date").notNull(),replacementDate:eS("replacement_date"),matchedQuantity:td("matched_quantity",{precision:38,scale:18}).notNull(),replacementQuantity:td("replacement_quantity",{precision:38,scale:18}).notNull(),disallowedLoss:td("disallowed_loss",{precision:20,scale:2}).notNull(),status:aT("status").notNull(),reason:tT("reason").notNull(),permanentlyDisallowed:ef("permanently_disallowed").notNull().default(!1),tackedHoldingStartDate:eS("tacked_holding_start_date"),resolvedAt:tj("resolved_at"),resolutionNote:tT("resolution_note"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("wash_sale_adjustments_entity_book_idx").on(e.entityId,e.bookId),ne("wash_sale_adjustments_loss_disposal_idx").on(e.lossDisposalId),ne("wash_sale_adjustments_replacement_idx").on(e.replacementLotId),ne("wash_sale_adjustments_status_idx").on(e.status)]),aC=L("day_count_convention",["ACTUAL_360","ACTUAL_365","THIRTY_360"]),aP=L("loan_status",["ACTIVE","PAID_OFF","DEFAULTED"]),aO=L("payment_frequency",["MONTHLY","QUARTERLY","SEMI_ANNUAL","ANNUAL"]),aK=L("loan_type",["TERM","REVOLVING","INTEREST_ONLY","BALLOON"]),aL=t5("loan_schedules",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),name:tT("name").notNull(),principalAccountId:tM("principal_account_id").notNull().references(()=>nU.id),interestExpenseAccountId:tM("interest_expense_account_id").notNull().references(()=>nU.id),interestPayableAccountId:tM("interest_payable_account_id").notNull().references(()=>nU.id),principal:td("principal",{precision:20,scale:2}).notNull(),annualRate:td("annual_rate",{precision:10,scale:6}).notNull(),dayCountConvention:aC("day_count_convention").notNull().default("ACTUAL_360"),startDate:eS("start_date").notNull(),maturityDate:eS("maturity_date"),status:aP("status").notNull().default("ACTIVE"),loanType:aK("loan_type").notNull().default("TERM"),paymentFrequency:aO("payment_frequency").notNull().default("MONTHLY"),paymentAmount:td("payment_amount",{precision:20,scale:2}),compoundingFrequency:aO("compounding_frequency").default("MONTHLY"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("loan_schedules_entity_idx").on(e.entityId),ne("loan_schedules_book_idx").on(e.bookId),ne("loan_schedules_status_idx").on(e.status)]),aq=L("loan_payment_status",["PENDING","POSTED"]);t5("loan_payments",{id:tM("id").primaryKey().defaultRandom(),loanId:tM("loan_id").notNull().references(()=>aL.id),entityId:tM("entity_id").notNull().references(()=>nP.id),periodIndex:eB("period_index").notNull(),dueDate:eS("due_date").notNull(),paymentAmount:td("payment_amount",{precision:20,scale:2}).notNull(),principalPortion:td("principal_portion",{precision:20,scale:2}).notNull(),interestPortion:td("interest_portion",{precision:20,scale:2}).notNull(),balance:td("balance",{precision:20,scale:2}).notNull(),status:aq("loan_payment_status").notNull().default("PENDING"),journalEntryId:tM("journal_entry_id").references(()=>nV.id),paidAt:tj("paid_at")},e=>[ne("loan_payments_loan_idx").on(e.loanId),ne("loan_payments_entity_idx").on(e.entityId)]);let aj=L("loan_modification_type",["REFINANCE","EXTENSION","RATE_CHANGE","PRINCIPAL_CHANGE"]);t5("loan_modifications",{id:tM("id").primaryKey().defaultRandom(),loanId:tM("loan_id").notNull().references(()=>aL.id),modificationDate:eS("modification_date").notNull(),modificationType:aj("modification_type").notNull(),oldTerms:eY("old_terms").notNull(),newTerms:eY("new_terms").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("loan_modifications_loan_idx").on(e.loanId)]);let aU=L("loan_pipeline_stage",["INQUIRY","TERM_SHEET","UNDERWRITING","APPROVED","FUNDED"]),aB=L("loan_account_status",["DRAFT","APPROVED","FUNDED","ACTIVE","PAID_OFF","DEFAULTED","CHARGED_OFF"]),aM=t5("loan_product_templates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),templateKey:tT("template_key").notNull(),name:tT("name").notNull(),description:tT("description"),config:eY("config").notNull().default({}),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>
1[nt("loan_product_templates_entity_key_idx").on(e.entityId,e.templateKey),ne("loan_product_templates_entity_idx").on(e.entityId)]),aF=t5("loan_accounts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),productTemplateId:tM("product_template_id").references(()=>aM.id,{onDelete:"set null"}),productConfig:tT("product_config"),name:tT("name").notNull(),loanNumber:tT("loan_number"),borrowerCounterpartyId:tM("borrower_counterparty_id").references(()=>dn.id,{onDelete:"set null"}),status:aB("status").notNull().default("DRAFT"),loansReceivableAccountId:tM("loans_receivable_account_id").references(()=>nU.id),interestIncomeAccountId:tM("interest_income_account_id").references(()=>nU.id),feeIncomeAccountId:tM("fee_income_account_id").references(()=>nU.id),principalCommitted:tT("principal_committed"),principalOutstanding:tT("principal_outstanding"),annualRate:tT("annual_rate"),dayCountConvention:aC("day_count_convention").notNull().default("ACTUAL_360"),startDate:eS("start_date"),maturityDate:eS("maturity_date"),loanType:aK("loan_type").notNull().default("INTEREST_ONLY"),paymentFrequency:aO("payment_frequency").notNull().default("MONTHLY"),paymentAmount:tT("payment_amount"),feeAtCloseAmount:tT("fee_at_close_amount"),pointsBps:eB("points_bps"),currency:tT("currency").notNull().default("USD"),fundedAt:tj("funded_at"),fundingEventId:tM("funding_event_id").references(()=>nB.id),fundingTreasuryAccountId:tM("funding_treasury_account_id").references(()=>n7.id,{onDelete:"set null"}),approvedAt:tj("approved_at"),pipelineStage:aU("pipeline_stage").notNull().default("INQUIRY"),brokerCounterpartyId:tM("broker_counterparty_id").references(()=>dn.id,{onDelete:"set null"}),referralFeeAmount:tT("referral_fee_amount"),loanPackageSignatureRequestId:tM("loan_package_signature_request_id").references(()=>ri.id,{onDelete:"set null"}),lateFeeBps:eB("late_fee_bps"),defaultInterestBps:eB("default_interest_bps"),memo:tT("memo"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("loan_accounts_entity_idx").on(e.entityId),ne("loan_accounts_book_idx").on(e.bookId),ne("loan_accounts_status_idx").on(e.status),ne("loan_accounts_borrower_idx").on(e.borrowerCounterpartyId),ne("loan_accounts_pipeline_stage_idx").on(e.pipelineStage),ne("loan_accounts_broker_idx").on(e.brokerCounterpartyId),nt("loan_accounts_entity_number_idx").on(e.entityId,e.loanNumber)]),aV=t5("loan_account_schedules",{id:tM("id").primaryKey().defaultRandom(),loanAccountId:tM("loan_account_id").notNull().references(()=>aF.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),periodIndex:eB("period_index").notNull(),dueDate:eS("due_date").notNull(),paymentAmount:tT("payment_amount").notNull(),principalPortion:tT("principal_portion").notNull(),interestPortion:tT("interest_portion").notNull(),balance:tT("balance").notNull(),status:aq("loan_payment_status").notNull().default("PENDING"),journalEntryId:tM("journal_entry_id").references(()=>nV.id),paidAt:tj("paid_at")},e=>[ne("loan_account_schedules_loan_idx").on(e.loanAccountId),ne("loan_account_schedules_entity_idx").on(e.entityId),nt("loan_account_schedules_period_idx").on(e.loanAccountId,e.periodIndex)]),aH=t5("loan_account_payments",{id:tM("id").primaryKey().defaultRandom(),loanAccountId:tM("loan_account_id").notNull().references(()=>aF.id,{onDelete:"cascade"}),scheduleId:tM("schedule_id").references(()=>aV.id,{onDelete:"set null"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),paymentDate:eS("payment_date").notNull(),totalAmount:tT("total_amount").notNull(),principalPortion:tT("principal_portion").notNull(),interestPortion:tT("interest_portion").notNull(),feePortion:tT("fee_portion").notNull().default("0"),treasuryAccountId:tM("treasury_account_id"),eventId:tM("event_id").references(()=>nB.id),journalEntryId:tM("journal_entry_id").references(()=>nV.id),memo:tT("memo"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("loan_account_payments_loan_idx").on(e.loanAccountId),ne("loan_account_payments_entity_idx").on(e.entityId),ne("loan_account_payments_payment_date_idx").on(e.paymentDate)]),a$=L("loan_collateral_kind",["REAL_ESTATE"]);t5("loan_collateral",{id:tM("id").primaryKey().defaultRandom(),loanAccountId:tM("loan_account_id").notNull().references(()=>
1aF.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),kind:a$("kind").notNull().default("REAL_ESTATE"),propertyAddress:tT("property_address"),appraisedValue:tT("appraised_value"),lienPosition:eB("lien_position"),ltvBps:eB("ltv_bps"),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("loan_collateral_loan_idx").on(e.loanAccountId),ne("loan_collateral_entity_idx").on(e.entityId)]);let aG=L("loan_account_modification_type",["EXTENSION","RATE_CHANGE","PRINCIPAL_CHANGE","PAYOFF","DEFAULT","CHARGED_OFF"]);t5("loan_account_modifications",{id:tM("id").primaryKey().defaultRandom(),loanAccountId:tM("loan_account_id").notNull().references(()=>aF.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),modificationDate:eS("modification_date").notNull(),modificationType:aG("modification_type").notNull(),oldTerms:eY("old_terms").notNull(),newTerms:eY("new_terms").notNull(),memo:tT("memo"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("loan_account_modifications_loan_idx").on(e.loanAccountId),ne("loan_account_modifications_entity_idx").on(e.entityId)]);let az=L("lending_facility_status",["DRAFT","ACTIVE","SUSPENDED","CLOSED"]),aQ=t5("lending_facilities",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),name:tT("name").notNull(),currency:tT("currency").notNull().default("USD"),status:az("status").notNull().default("DRAFT"),committedAmount:tT("committed_amount").notNull(),deployedAmount:tT("deployed_amount").notNull().default("0"),gpPromoteBps:eB("gp_promote_bps").notNull().default(0),effectiveDate:eS("effective_date").notNull(),maturityDate:eS("maturity_date"),memo:tT("memo"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("lending_facilities_entity_idx").on(e.entityId)]);t5("lending_facility_commitments",{id:tM("id").primaryKey().defaultRandom(),facilityId:tM("facility_id").notNull().references(()=>aQ.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),participantCounterpartyId:tM("participant_counterparty_id").notNull().references(()=>dn.id),committedAmount:tT("committed_amount").notNull(),currency:tT("currency").notNull().default("USD"),committedAt:eS("committed_at").notNull(),memo:tT("memo"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("lending_facility_commitments_facility_idx").on(e.facilityId)]),t5("lending_facility_allocations",{id:tM("id").primaryKey().defaultRandom(),facilityId:tM("facility_id").notNull().references(()=>aQ.id,{onDelete:"cascade"}),loanAccountId:tM("loan_account_id").notNull().references(()=>aF.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),allocatedAmount:tT("allocated_amount").notNull(),allocationBps:eB("allocation_bps"),allocatedAt:eS("allocated_at").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("lending_facility_allocations_facility_idx").on(e.facilityId),ne("lending_facility_allocations_loan_idx").on(e.loanAccountId)]),t5("loan_participations",{id:tM("id").primaryKey().defaultRandom(),loanAccountId:tM("loan_account_id").notNull().references(()=>aF.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),participantCounterpartyId:tM("participant_counterparty_id").notNull().references(()=>dn.id),shareBps:eB("share_bps").notNull(),committedAmount:tT("committed_amount"),memo:tT("memo"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("loan_participations_loan_idx").on(e.loanAccountId),nt("loan_participations_loan_participant_idx").on(e.loanAccountId,e.participantCounterpartyId)]),t5("loan_participant_distributions",{id:tM("id").primaryKey().defaultRandom(),loanAccountId:tM("loan_account_id").notNull().references(()=>
1aF.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),participantCounterpartyId:tM("participant_counterparty_id").notNull().references(()=>dn.id),paymentId:tM("payment_id").references(()=>aH.id,{onDelete:"set null"}),distributionDate:eS("distribution_date").notNull(),interestAmount:tT("interest_amount").notNull().default("0"),principalAmount:tT("principal_amount").notNull().default("0"),feeAmount:tT("fee_amount").notNull().default("0"),source:tT("source").notNull().default("payment"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("loan_participant_distributions_loan_idx").on(e.loanAccountId)]);let aY=L("report_frequency",["DAILY","WEEKLY","MONTHLY","QUARTERLY"]);t5("report_subscriptions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),reportType:tT("report_type").notNull(),frequency:aY("frequency").notNull(),recipients:eY("recipients").$type().notNull(),bookId:tM("book_id").references(()=>nq.id),enabled:ef("enabled").notNull().default(!0),lastSentAt:tj("last_sent_at"),nextSendAt:tj("next_send_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("report_subs_entity_idx").on(e.entityId),ne("report_subs_next_send_idx").on(e.nextSendAt)]);let aW=t5("dimensions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),code:tT("code").notNull(),description:tT("description"),isRequired:ef("is_required").notNull().default(!1),isActive:ef("is_active").notNull().default(!0),sortOrder:eB("sort_order").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("dimensions_entity_idx").on(e.entityId),nt("dimensions_entity_code_idx").on(e.entityId,e.code)]);t5("dimension_values",{id:tM("id").primaryKey().defaultRandom(),dimensionId:tM("dimension_id").notNull().references(()=>aW.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),label:tT("label").notNull(),code:tT("code").notNull(),parentId:tM("parent_id"),isActive:ef("is_active").notNull().default(!0),sortOrder:eB("sort_order").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("dim_values_dimension_idx").on(e.dimensionId),nt("dim_values_dim_code_idx").on(e.dimensionId,e.code)]);let aJ=L("segment_report_type",["OPERATING","GEOGRAPHIC","PRODUCT_LINE","CUSTOM"]);t5("segments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),type:aJ("type").notNull(),dimensionId:tM("dimension_id").notNull().references(()=>aW.id),dimensionValueIds:eY("dimension_value_ids").$type().notNull(),isReportable:ef("is_reportable").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("segments_entity_idx").on(e.entityId)]);let aX=L("contract_status",["DRAFT","ACTIVE","MODIFIED","COMPLETED","CANCELLED"]),aZ=L("revenue_recognition_mode",["INVOICE_LED","ASC606_LED"]),a0=L("revenue_recognition_pattern",["POINT_IN_TIME","OVER_TIME_STRAIGHT_LINE","OVER_TIME_OUTPUT","OVER_TIME_INPUT","OVER_TIME_MILESTONE"]),a1=t5("contracts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),customerId:tM("customer_id").references(()=>dn.id),bookId:tM("book_id").notNull().references(()=>nq.id),contractNumber:tT("contract_number").notNull(),name:tT("name").notNull(),status:aX("status").notNull().default("DRAFT"),startDate:eS("start_date").notNull(),endDate:eS("end_date"),transactionPrice:td("transaction_price",{precision:20,scale:6}).notNull(),currency:tT("currency").notNull().default("USD"),variableConsideration:eY("variable_consideration").$type(),modifications:eY("modifications").$type(),notes:tT("notes"),revenueRecognitionMode:aZ("revenue_recognition_mode").notNull().default("INVOICE_LED"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("contracts_entity_idx").on(e.entityId),ne("contracts_customer_idx").on(e.customerId),nt("contracts_entity_number_idx").on(e.entityId,e.contractNumber)]),a2=t5("performance_obligations",{id:tM("id").primaryKey().defaultRandom(),contractId:tM("contract_id").notNull().references(()=>
1a1.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),description:tT("description").notNull(),standalonSellingPrice:td("standalone_selling_price",{precision:20,scale:6}).notNull(),allocatedPrice:td("allocated_price",{precision:20,scale:6}),recognitionPattern:a0("recognition_pattern").notNull(),startDate:eS("start_date"),endDate:eS("end_date"),milestones:eY("milestones").$type(),recognitionMetrics:eY("recognition_metrics").$type(),isSatisfied:ef("is_satisfied").notNull().default(!1),satisfiedAt:tj("satisfied_at"),recognizedAmount:td("recognized_amount",{precision:20,scale:6}).notNull().default("0"),scheduleId:tM("schedule_id").references(()=>nX.id),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("perf_obligations_contract_idx").on(e.contractId),ne("perf_obligations_entity_idx").on(e.entityId)]);t5("revenue_allocations",{id:tM("id").primaryKey().defaultRandom(),contractId:tM("contract_id").notNull().references(()=>a1.id,{onDelete:"cascade"}),obligationId:tM("obligation_id").notNull().references(()=>a2.id,{onDelete:"cascade"}),method:tT("method").notNull().default("relative_ssp"),allocationMethod:tT("allocation_method").notNull().default("relative_ssp"),allocatedAmount:td("allocated_amount",{precision:20,scale:6}).notNull(),allocationPercentage:td("allocation_percentage",{precision:10,scale:6}).notNull(),allocatedAt:tj("allocated_at").notNull().defaultNow()},e=>[ne("rev_alloc_contract_idx").on(e.contractId),ne("rev_alloc_obligation_idx").on(e.obligationId)]);let a4=L("lease_classification",["OPERATING","FINANCE"]),a6=L("lease_status",["DRAFT","ACTIVE","MODIFIED","EXPIRED","TERMINATED"]),a8=t5("leases",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),name:tT("name").notNull(),leaseNumber:tT("lease_number").notNull(),classification:a4("classification").notNull(),status:a6("status").notNull().default("DRAFT"),lesseeOrLessor:tT("lessee_or_lessor").notNull().default("lessee"),counterpartyId:tM("counterparty_id").references(()=>dn.id),assetDescription:tT("asset_description").notNull(),commencementDate:eS("commencement_date").notNull(),expirationDate:eS("expiration_date").notNull(),termMonths:eB("term_months").notNull(),baseMonthlyPayment:td("base_monthly_payment",{precision:20,scale:6}).notNull(),annualEscalation:td("annual_escalation",{precision:10,scale:6}).default("0"),discountRate:td("discount_rate",{precision:10,scale:6}).notNull(),initialDirectCosts:td("initial_direct_costs",{precision:20,scale:6}).default("0"),leaseIncentives:td("lease_incentives",{precision:20,scale:6}).default("0"),residualValueGuarantee:td("residual_value_guarantee",{precision:20,scale:6}).default("0"),purchaseOption:ef("purchase_option").notNull().default(!1),purchaseOptionPrice:td("purchase_option_price",{precision:20,scale:6}),renewalOptions:eY("renewal_options").$type(),currency:tT("currency").notNull().default("USD"),rouAssetAccountId:tM("rou_asset_account_id").references(()=>nU.id),leaseLiabilityAccountId:tM("lease_liability_account_id").references(()=>nU.id),rouAssetId:tM("rou_asset_id").references(()=>av.id),initialRouAssetValue:td("initial_rou_asset_value",{precision:20,scale:6}),initialLiabilityValue:td("initial_liability_value",{precision:20,scale:6}),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("leases_entity_idx").on(e.entityId),nt("leases_entity_number_idx").on(e.entityId,e.leaseNumber)]);t5("lease_payments",{id:tM("id").primaryKey().defaultRandom(),leaseId:tM("lease_id").notNull().references(()=>a8.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),periodIndex:eB("period_index").notNull(),dueDate:eS("due_date").notNull(),paymentAmount:td("payment_amount",{precision:20,scale:6}).notNull(),principalPortion:td("principal_portion",{precision:20,scale:6}),interestPortion:td("interest_portion",{precision:20,scale:6}),liabilityBalance:td("liability_balance",{precision:20,scale:6}),rouAssetBalance:td("rou_asset_balance",{precision:20,scale:6}),status:tT("status").notNull().default("PENDING"),journalEntryId:tM("journal_entry_id").references(()=>nV.id),paidAt:tj("paid_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("lease_payments_lease_idx").on(e.leaseId),ne("lease_payments_entity_idx").on(e.entityId),ne("lease_payments_due_idx").on(e.dueDate)]);let a5=L("push_device_platform",["ios","android"]);t5("push_devices",{id:tM("id").primaryKey().defaultRandom(),userId:tM("user_id").notNull(),token:tT("token").notNull(),platform:a5("platform").notNull(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("push_devices_user_idx").on(e.userId),nt("push_devices_token_idx").on(e.token)]);let a3=L("ocr_status",["PENDING","COMPLETE","FAILED"]),a9=t5("documents",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),folderId:tM("folder_id"),filename:tT("filename").notNull(),mimeType:tT("mime_type").notNull(),sizeBytes:eB("size_bytes").notNull(),blobUrl:tT("blob_url").notNull(),contentSha256:tT("content_sha256"),thumbnailUrl:tT("thumbnail_url"),ocrText:tT("ocr_text"),ocrStatus:a3("ocr_status").default("PENDING"),uploadedBy:tM("uploaded_by"),tags:eY("tags"),status:tT("status").notNull().default("active"),description:tT("description"),retentionPolicy:tT("retention_policy"),retentionExpiresAt:tj("retention_expires_at"),sortOrder:eB("sort_order"),deletedAt:tj("deleted_at"),deletedBy:tM("deleted_by"),currentRevisionId:tM("current_revision_
1id"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("documents_entity_idx").on(e.entityId),ne("documents_uploaded_by_idx").on(e.uploadedBy),ne("documents_folder_idx").on(e.folderId),ne("documents_entity_deleted_idx").on(e.entityId,e.deletedAt),ne("documents_entity_content_sha256_idx").on(e.entityId,e.contentSha256)]),a7=L("document_revision_source",["cortex_proposal","manual_edit","restore","named_checkpoint","api"]),ie=L("document_derivation_kind",["markdown_pdf_export","crm_proposal_pdf","html_pdf_export"]),it=t5("document_revisions",{id:tM("id").primaryKey().defaultRandom(),documentId:tM("document_id").notNull().references(()=>a9.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id),revisionNumber:eB("revision_number").notNull(),blobUrl:tT("blob_url").notNull(),sizeBytes:eB("size_bytes").notNull(),mimeType:tT("mime_type").notNull(),filename:tT("filename").notNull(),description:tT("description"),content:tT("content"),authorId:tM("author_id"),source:a7("source").notNull(),sourceProposalId:tM("source_proposal_id"),label:tT("label"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("document_revisions_document_idx").on(e.documentId),ne("document_revisions_entity_idx").on(e.entityId),nt("document_revisions_doc_number_idx").on(e.documentId,e.revisionNumber)]);t5("document_derivations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),childDocumentId:tM("child_document_id").notNull().references(()=>a9.id,{onDelete:"cascade"}),parentDocumentId:tM("parent_document_id").notNull().references(()=>a9.id,{onDelete:"cascade"}),parentRevisionId:tM("parent_revision_id").references(()=>it.id,{onDelete:"set null"}),kind:ie("kind").notNull(),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("document_derivations_child_idx").on(e.childDocumentId),ne("document_derivations_parent_idx").on(e.parentDocumentId),ne("document_derivations_parent_revision_idx").on(e.parentRevisionId)]),t5("document_links",{id:tM("id").primaryKey().defaultRandom(),documentId:tM("document_id").notNull().references(()=>a9.id,{onDelete:"cascade"}),linkableType:tT("linkable_type").notNull(),linkableId:tM("linkable_id").notNull(),sortOrder:eB("sort_order"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("document_links_doc_idx").on(e.documentId),ne("document_links_linkable_idx").on(e.linkableType,e.linkableId)]);let id=L("close_checklist_status",["IN_PROGRESS","COMPLETED"]),ia=L("checklist_item_status",["PENDING","IN_PROGRESS","COMPLETED","SKIPPED"]),ii=t5("close_templates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),periodType:tT("period_type").notNull().default("MONTHLY"),isDefault:ef("is_default").notNull().default(!1),tasks:eY("tasks").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("close_templates_entity_idx").on(e.entityId)]),io=t5("close_checklists",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),periodId:tM("period_id").notNull().references(()=>n$.id),templateId:tM("template_id").references(()=>ii.id),status:id("status").notNull().default("IN_PROGRESS"),startedAt:tj("started_at").notNull().defaultNow(),completedAt:tj("completed_at")},e=>[ne("close_checklists_entity_idx").on(e.entityId),ne("close_checklists_period_idx").on(e.periodId)]);t5("close_checklist_items",{id:tM("id").primaryKey().defaultRandom(),checklistId:tM("checklist_id").notNull().references(()=>io.id,{onDelete:"cascade"}),taskName:tT("task_name").notNull(),description:tT("description"),assigneeId:tM("assignee_id"),dueDate:eS("due_date"),status:ia("status").notNull().default("PENDING"),dependsOnItemId:tM("depends_on_item_id"),completedAt:tj("completed_at"),completedBy:tM("completed_by"),notes:tT("notes"),sortOrder:eB("sort_order").notNull().default(0),systemCheckFn:tT("system_check_fn")},e=>[ne("close_checklist_items_checklist_idx").on(e.checklistId),ne("close_checklist_items_assignee_idx").on(e.assigneeId)]);let il=L("accounting_task_status",["open","done","dismissed"]);t5("accounting_tasks",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),title:tT("title").notNull(),notes:tT("notes"),status:il("status").notNull().default("open"),dueDate:eS("due_date"),periodId:tM("period_id").references(()=>n$.id,{onDelete:"set null"}),accountHint:tT("account_hint"),tags:tT("tags").array().notNull().default(Y`'{}'::text[]`),completedAt:tj("completed_at"),assigneeId:tM("assignee_id"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("accounting_tasks_entity_status_idx").on(e.entityId,e.status),ne("accounting_tasks_entity_due_idx").on(e.entityId,e.dueDate),ne("accounting_tasks_entity_period_idx").on(e.entityId,e.periodId),ne("accounting_tasks_assignee_idx").on(e.assigneeId)]);let ir=L("approval_trigger_type",["JOURNAL_ENTRY","EVENT","INVOICE","BILL","PAYMENT","RECONCILIATION"]),is=L("approval_status",["PENDING","APPROVED","REJECTED","ESCALATED"]),i_=L("approval_decision",["APPROVE","REJECT"]),iu=t5("approval_policies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),triggerType:ir("trigger_type").notNull(),conditions:eY("conditions"),isActive:ef("is_active").notNull().default(!0),priority:eB("priority").notNull().default(0),autoApproveOnPlaid:ef("auto_approve_on_plaid").notNull().default(!1),autoApproveMaxVarianceCents:eB("auto_approve_max_variance_cents").notNull().default(0),autoApproveMaxPlaidStalenessHours:eB("auto_approve_max_plaid_staleness_hours").notNull().default(48),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("approval_policies_entity_idx").on(e.entityId),ne("approval_policies_trigger_idx").on(e.triggerType)]);t5("approval_steps",{id:tM("id").primaryKey().defaultRandom(),policyId:tM("policy_id").notNull().references(()=>iu.id,{onDelete:"cascade"}),stepOrder:eB("step_order").notNull(),approverRole:tT("approver_role"),approverId:tM("approver_id"),requiredCount:eB("required_count").notNull().default(1),autoApproveAfterHours:eB("auto_approve_after_hours")},e=>[ne("approval_steps_policy_idx").on(e.policyId)]);let ic=t5("approval_requests",{id:tM("id").primaryKey().defaultRandom(),policyId:tM("policy_id").notNull().references(()=>iu.id),entityId:tM("entity_id").notNull().references(()=>nP.id),subjectType:tT("subject_type").notNull(),subjectId:tM("subject_id").notNull(),status:is("status").notNull().default("PENDING"),currentStep:eB("current_step").notNull().default(1),requestedBy:tM("requested_by"),requestedAt:tj("requested_at").notNull().defaultNow(),resolvedAt:tj("resolved_at")},e=>[ne("approval_requests_entity_idx").on(e.entityId),ne("approval_requests_status_idx").on(e.status),ne("approval_requests_subject_idx").on(e.subjectType,e.subjectId)]);t5("approval_decisions",{id:tM("id").primaryKey().defaultRandom(),requestId:tM("request_id").notNull().references(()=>ic.id,{onDelete:"cascade"}),stepOrder:eB("step_order").notNull(),decidedBy:tM("decided_by"),decision:i_("decision").notNull(),reason:tT("reason"),decidedAt:tj("decided_at").notNull().defaultNow(),decisionSource:tT("decision_source").notNull().default("HUMAN"),decidedByAgent:tT("decided_by_agent")},e=>[ne("approval_decisions_request_idx").on(e.requestId)]);let ip=L("reconciliation_type",["BANK","ACCOUNT"]),iy=L("reconciliation_mode",["EXTERNAL","NATIVE_ATTESTATION"]),im=L("reconciliation_status",["NOT_STARTED","IN_PROGRESS","SUBMITTED","APPROVED","REJECTED"]),iN=L("reconciliation_adjustment_type",["OUTSTANDING_CHECK","DEPOSIT_IN_TRANSIT","BANK_ADJUSTMENT","BOOK_ADJUSTMENT","SCHEDULE_VARIANCE"]),iI=t5("reconciliations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),periodId:tM("period_id").notNull().references(()=>n$.id),accountId:tM("account_id").notNull().references(()=>nU.id),linkedAccountId:tM("linked_account_id").references(()=>n7.id),type:ip("type").notNull(),mode:iy("mode").notNull().default("EXTERNAL"),status:im("status").notNull().default("NOT_STARTED"),preparerId:tM("preparer_id"),dueDate:eS("due_date"),approvalRequestId:tM("approval_request_id").references(()=>ic.id),submittedAt:tj("submitted_at"),submittedBy:tM("submitted_by"),statementBalanceText:tT("statement_balance_text"),statementDate:eS("statement_date"),scheduleBalanceText:tT("schedule_balance_text"),ledgerBalanceText:tT("ledger_balance_text"),notesText:tT("notes_text"),rejectedReasonText:tT("rejected_reason_text"),attestationHash:tT("attestation_hash"),attestationPayloadText:tT("attestation_payload_text"),providerStatementRef:tT("provider_statement_ref"),evidenceSource:tT("evidence_source"),evidenceFetchedAt:tj("evidence_fetched_at"),nextCycleRequireHuman:ef("next_cycle_require_human").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("reconciliations_entity_period_account_idx").on(e.entityId,e.periodId,e.accountId),ne("reconciliations_entity_period_idx").on(e.entityId,e.periodId),ne("reconciliations_status_idx").on(e.status),ne("reconciliations_approval_request_idx").on(e.approvalRequestId)]);t5("reconciliation_cleared_entries",{id:tM("id").primaryKey().defaultRandom(),reconciliationId:tM("reconciliation_id").notNull().references(()=>
1iI.id,{onDelete:"cascade"}),journalEntryId:tM("journal_entry_id").notNull().references(()=>nV.id),clearedAt:eS("cleared_at").notNull(),clearedByIdentityId:tM("cleared_by_identity_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("recon_cleared_entries_unique_idx").on(e.reconciliationId,e.journalEntryId),ne("recon_cleared_entries_je_idx").on(e.journalEntryId)]),t5("reconciliation_adjustments",{id:tM("id").primaryKey().defaultRandom(),reconciliationId:tM("reconciliation_id").notNull().references(()=>iI.id,{onDelete:"cascade"}),type:iN("type").notNull(),amountText:tT("amount_text").notNull(),descriptionText:tT("description_text").notNull(),occurredOn:eS("occurred_on"),resolvedAt:tj("resolved_at"),resolvedByJournalEntryId:tM("resolved_by_journal_entry_id").references(()=>nV.id),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("recon_adjustments_recon_idx").on(e.reconciliationId)]);let ig=L("consolidation_method",["FULL","PROPORTIONAL","EQUITY"]),ib=t5("consolidation_groups",{id:tM("id").primaryKey().defaultRandom(),parentEntityId:tM("parent_entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),functionalCurrency:tT("functional_currency").notNull().default("USD"),method:ig("method").notNull().default("FULL"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("consolidation_groups_parent_idx").on(e.parentEntityId)]);t5("consolidation_memberships",{id:tM("id").primaryKey().defaultRandom(),groupId:tM("group_id").notNull().references(()=>ib.id,{onDelete:"cascade"}),childEntityId:tM("child_entity_id").notNull().references(()=>nP.id),ownershipPct:td("ownership_pct",{precision:5,scale:2}).notNull(),consolidationMethod:ig("consolidation_method").notNull().default("FULL"),acquiredDate:eS("acquired_date"),functionalCurrency:tT("functional_currency").notNull().default("USD")},e=>[ne("consolidation_memberships_group_idx").on(e.groupId),ne("consolidation_memberships_child_idx").on(e.childEntityId)]),t5("consolidation_group_entity_closure",{groupId:tM("group_id").notNull().references(()=>ib.id,{onDelete:"cascade"}),ancestorEntityId:tM("ancestor_entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),descendantEntityId:tM("descendant_entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),depth:eB("depth").notNull()},e=>[nn({columns:[e.groupId,e.ancestorEntityId,e.descendantEntityId]}),ne("consol_group_entity_closure_group_desc_idx").on(e.groupId,e.descendantEntityId),ne("consol_group_entity_closure_group_anc_idx").on(e.groupId,e.ancestorEntityId)]),t5("translation_adjustments",{id:tM("id").primaryKey().defaultRandom(),groupId:tM("group_id").notNull().references(()=>ib.id),childEntityId:tM("child_entity_id").notNull().references(()=>nP.id),periodId:tM("period_id").references(()=>n$.id),translationGainLoss:td("translation_gain_loss",{precision:20,scale:2}).notNull(),cumulativeTranslationAdjustment:td("cumulative_translation_adjustment",{precision:20,scale:2}).notNull(),closingRate:td("closing_rate",{precision:15,scale:8}),averageRate:td("average_rate",{precision:15,scale:8}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("translation_adj_group_idx").on(e.groupId),ne("translation_adj_child_idx").on(e.childEntityId)]),t5("consolidation_account_map",{id:tM("id").primaryKey().defaultRandom(),consolidationGroupId:tM("consolidation_group_id").notNull().references(()=>ib.id),subsidiaryAccountId:tM("subsidiary_account_id").notNull().references(()=>nU.id),groupAccountCode:tT("group_account_code").notNull(),groupAccountName:tT("group_account_name"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("consolidation_account_map_group_idx").on(e.consolidationGroupId),ne("consolidation_account_map_sub_acct_idx").on(e.subsidiaryAccountId)]),t5("consolidation_snapshots",{id:tM("id").primaryKey().defaultRandom(),groupId:tM("group_id").notNull().references(()=>ib.id),periodEndDate:eS("period_end_date").notNull(),data:eY("data").notNull(),createdAt:tj("created_at").notNull().defaultNow(),createdBy:tM("created_by")},e=>[ne("consolidation_snapshots_group_idx").on(e.groupId),ne("consolidation_snapshots_period_idx").on(e.periodEndDate)]);let ih=L("xbrl_standard",["US_GAAP","IFRS"]),iv=t5("xbrl_taxonomies",{id:tM("id").primaryKey().defaultRandom(),name:tT("name").notNull(),version:tT("version").notNull(),standard:ih("standard").notNull(),elements:eY("elements").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("xbrl_taxonomies_name_version_idx").on(e.name,e.version)]);t5("xbrl_mappings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),taxonomyId:tM("taxonomy_id").notNull().references(()=>iv.id),accountId:tM("account_id").notNull().references(()=>nU.id),xbrlElement:tT("xbrl_element").notNull(),xbrlContext:tT("xbrl_context")},e=>[ne("xbrl_mappings_entity_idx").on(e.entityId),ne("xbrl_mappings_taxonomy_idx").on(e.taxonomyId)]);let ix=L("filing_format",["XBRL","iXBRL","XLSX"]);t5("filing_history",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),filingType:tT("filing_type").notNull(),periodId:tM("period_id").references(()=>n$.id),format:ix("format").notNull(),fileUrl:tT("file_url"),generatedAt:tj("generated_at").notNull().defaultNow()},e=>[ne("filing_history_entity_idx").on(e.entityId)]);let iA=L("payment_file_type",["ACH_NACHA","SEPA_XML","SWIFT_MT103","ISO_20022"]),iD=L("payment_file_status",["DRAFT","GENERATED","SUBMITTED","PROCESSED","FAILED"]),iw=t5("payment_files",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),fileType:iA("file_type").notNull(),status:iD("payment_file_status").notNull().default("DRAFT"),fileContent:tT("file_content"),blobUrl:tT("blob_url"),paymentCount:eB("payment_count").notNull().default(0),totalAmount:td("total_amount",{precision:20,scale:2}),generatedAt:tj("generated_at").notNull().defaultNow(),submittedAt:tj("submitted_at")},e=>[ne("payment_files_entity_idx").on(e.entityId),ne("payment_files_status_idx").on(e.status)]),iE=L("bank_statement_format",["MT940","CAMT053","CSV","OFX"]);t5("bank_statement_imports",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),format:iE("format").notNull(),filename:tT("filename").notNull(),transactionCount:eB("transaction_count").notNull().default(0),importedAt:tj("imported_at").notNull().defaultNow()},e=>[ne("bank_statement_imports_entity_idx").on(e.entityId)]);let iR=L("payroll_provider",["ADP","GUSTO","DEEL","REMOTE","QUICKBOOKS","MANUAL"]),ik=t5("payroll_connections",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),provider:iR("provider").notNull(),credentials:tT("credentials"),lastSyncAt:tj("last_sync_at"),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("payroll_connections_entity_idx").on(e.entityId)]),iT=L("payroll_workflow_state",["draft","calculated","approved","posted","paying","paid","failed","voided"]),iS=L("payroll_component_kind",["earning","pre_tax_deduction","post_tax_deduction","employer_contribution","reimbursement"]),iC=L("tax_obligation_status",["open","scheduled","paid","filed"]),iP=L("payroll_run_status",["PENDING","POSTED","FAILED"]),iO=L("employee_type",["W2","1099"]),iK=L("employee_status",["active","terminated","on_leave"]),iL=L("pay_type",["
1salary","hourly"]),iq=L("pay_schedule",["weekly","biweekly","semi_monthly","monthly"]),ij=t5("payroll_schedules",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),frequency:iq("frequency").notNull().default("biweekly"),anchorDate:eS("anchor_date").notNull(),cutoffOffsetDays:eB("cutoff_offset_days").notNull().default(0),payOffsetDays:eB("pay_offset_days").notNull().default(0),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("payroll_schedules_entity_idx").on(e.entityId)]),iU=t5("payroll_components",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),kind:iS("kind").notNull(),code:tT("code").notNull(),name:tT("name").notNull(),taxability:eY("taxability").$type().default(null),glAccountId:tM("gl_account_id").references(()=>nU.id),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("payroll_components_entity_idx").on(e.entityId),nt("payroll_components_entity_code_uidx").on(e.entityId,e.code)]),iB=t5("tax_rule_versions",{id:tM("id").primaryKey().defaultRandom(),jurisdiction:tT("jurisdiction").notNull(),kind:tT("kind").notNull(),effectiveFrom:eS("effective_from").notNull(),effectiveTo:eS("effective_to"),payload:eY("payload").$type().notNull(),version:tT("version"),sourceUrl:tT("source_url"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("trv_jurisdiction_idx").on(e.jurisdiction,e.kind),nt("trv_jurisdiction_kind_effective_uidx").on(e.jurisdiction,e.kind,e.effectiveFrom)]);t5("tax_obligations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),jurisdiction:tT("jurisdiction").notNull(),kind:tT("kind").notNull(),periodStart:eS("period_start").notNull(),periodEnd:eS("period_end").notNull(),amount:tT("amount").notNull(),dueDate:eS("due_date").notNull(),status:iC("status").notNull().default("open"),locality:tT("locality"),paymentId:tM("payment_id").references(()=>dR.id,{onDelete:"set null"}),sourceKey:tT("source_key"),sourceEventId:tM("source_event_id").references(()=>nB.id,{onDelete:"set null"}),sourcePayrollRunId:tM("source_payroll_run_id"),remittedOn:eS("remitted_on"),remittanceReference:tT("remittance_reference"),remittedBy:tM("remitted_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("tax_obligations_entity_idx").on(e.entityId),ne("tax_obligations_due_idx").on(e.dueDate,e.status),ne("tax_obligations_source_run_idx").on(e.sourcePayrollRunId),nt("tax_obligations_entity_source_kind_uq").on(e.entityId,e.sourceKey,e.jurisdiction,e.kind).where(Y`${e.sourceKey} is not null`)]);let iM=t5("employees",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),firstName:tT("first_name").notNull(),lastName:tT("last_name").notNull(),type:iO("type").notNull().default("W2"),status:iK("status").notNull().default("active"),departmentId:tM("department_id"),title:tT("title"),hireDate:eS("hire_date").notNull(),terminationDate:eS("termination_date"),payType:iL("pay_type").notNull().default("salary"),payRate:td("pay_rate",{precision:12,scale:2}).notNull(),paySchedule:iq("pay_schedule").notNull().default("biweekly"),filingStatus:tT("filing_status"),federalAllowances:eB("federal_allowances").default(0),state:tT("state"),externalId:tT("external_id"),externalProvider:tT("external_provider"),metadata:eY("metadata"),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"set null"}),partyId:tM("party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("employees_entity_idx").on(e.entityId),ne("employees_type_idx").on(e.entityId,e.type),ne("employees_status_idx").on(e.entityId,e.status),ne("employees_department_id_idx").on(e.departmentId),ne("employees_counterparty_idx").on(e.counterpartyId),ne("employees_party_idx").on(e.partyId)]);t5("employee_compensation_components",{id:tM("id").primaryKey().defaultRandom(),employeeId:tM("employee_id").notNull().references(()=>
1iM.id,{onDelete:"cascade"}),componentId:tM("component_id").notNull().references(()=>iU.id,{onDelete:"cascade"}),amount:tT("amount"),rate:tT("rate"),cap:tT("cap"),effectiveFrom:eS("effective_from").notNull(),effectiveTo:eS("effective_to"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ecc_employee_idx").on(e.employeeId),ne("ecc_component_idx").on(e.componentId)]);let iF=t5("hr_departments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),code:tT("code"),parentId:tM("parent_id"),managerId:tM("manager_id").references(()=>iM.id),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("hr_departments_entity_idx").on(e.entityId),nt("hr_departments_entity_code_idx").on(e.entityId,e.code)]),iV=L("leave_request_status",["pending","approved","rejected","cancelled"]),iH=t5("hr_leave_types",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),isPaid:ef("is_paid").notNull().default(!0),color:tT("color"),defaultDaysPerYear:td("default_days_per_year",{precision:5,scale:1}),requiresApproval:ef("requires_approval").notNull().default(!0),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("hr_leave_types_entity_idx").on(e.entityId)]);t5("hr_leave_requests",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),employeeId:tM("employee_id").notNull().references(()=>iM.id,{onDelete:"cascade"}),leaveTypeId:tM("leave_type_id").notNull().references(()=>iH.id),startDate:eS("start_date").notNull(),endDate:eS("end_date").notNull(),days:td("days",{precision:5,scale:1}).notNull(),status:iV("status").notNull().default("pending"),reason:tT("reason"),approvedBy:tM("approved_by"),approvedAt:tj("approved_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("hr_leave_requests_entity_idx").on(e.entityId),ne("hr_leave_requests_employee_idx").on(e.employeeId),ne("hr_leave_requests_status_idx").on(e.entityId,e.status),ne("hr_leave_requests_dates_idx").on(e.entityId,e.startDate,e.endDate)]);let i$=L("benefit_type",["health_medical","health_dental","health_vision","401k","hsa","life_insurance","other"]);t5("employee_benefits",{id:tM("id").primaryKey().defaultRandom(),employeeId:tM("employee_id").notNull().references(()=>iM.id,{onDelete:"cascade"}),benefitType:i$("benefit_type").notNull(),employeeContribution:td("employee_contribution",{precision:12,scale:2}).notNull().default("0"),employerContribution:td("employer_contribution",{precision:12,scale:2}
1).notNull().default("0"),perPeriod:tT("per_period").notNull().default("per_pay"),effectiveFrom:eS("effective_from").notNull(),effectiveTo:eS("effective_to"),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("employee_benefits_employee_idx").on(e.employeeId)]);let iG=t5("payroll_runs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),connectionId:tM("connection_id").references(()=>ik.id),scheduleId:tM("schedule_id").references(()=>ij.id,{onDelete:"set null"}),payPeriodStart:eS("pay_period_start").notNull(),payPeriodEnd:eS("pay_period_end").notNull(),grossPay:td("gross_pay",{precision:20,scale:2}).notNull(),netPay:td("net_pay",{precision:20,scale:2}).notNull(),employerTaxes:td("employer_taxes",{precision:20,scale:2}).notNull(),employeeDeductions:td("employee_deductions",{precision:20,scale:2}).notNull(),status:iP("payroll_run_status").notNull().default("PENDING"),workflowState:iT("workflow_state"),idempotencyKey:tT("idempotency_key"),employerCounterpartyId:tM("employer_counterparty_id").references(()=>dn.id,{onDelete:"set null"}),eventId:tM("event_id").references(()=>nB.id),paySchedule:iq("pay_schedule_col"),checkDate:eS("check_date"),employeeCount:eB("employee_count"),totalBenefitsEmployee:td("total_benefits_employee",{precision:12,scale:2}).default("0"),totalBenefitsEmployer:td("total_benefits_employer",{precision:12,scale:2}).default("0"),totalFederalWithholding:td("total_federal_withholding",{precision:12,scale:2}).default("0"),totalStateWithholding:td("total_state_withholding",{precision:12,scale:2}).default("0"),totalSocialSecurity:td("total_social_security",{precision:12,scale:2}).default("0"),totalMedicare:td("total_medicare",{precision:12,scale:2}).default("0"),approvedBy:tM("approved_by"),approvedAt:tj("approved_at"),syncedAt:tj("synced_at"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),paymentFileId:tM("payment_file_id").references(()=>iw.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("payroll_runs_entity_idx").on(e.entityId),ne("payroll_runs_connection_idx").on(e.connectionId),ne("payroll_runs_schedule_idx").on(e.scheduleId),ne("payroll_runs_workflow_idx").on(e.entityId,e.workflowState),ne("payroll_runs_site_idx").on(e.entityId,e.siteId),ne("payroll_runs_payment_file_idx").on(e.paymentFileId),nt("payroll_runs_idempotency_uidx").on(e.idempotencyKey).where(Y`${e.idempotencyKey} is not null`)]),iz=t5("pay_stubs",{id:tM("id").primaryKey().defaultRandom(),payrollRunId:tM("payroll_run_id").notNull().references(()=>iG.id,{onDelete:"cascade"}),employeeId:tM("employee_id").notNull().references(()=>iM.id),hoursWorked:td("hours_worked",{precision:8,scale:2}),overtimeHours:td("overtime_hours",{precision:8,scale:2}).default("0"),grossPay:tT("gross_pay").notNull(),federalWithholding:tT("federal_withholding").notNull().default("0"),stateWithholding:tT("state_withholding").notNull().default("0"),socialSecurityEmployee:tT("social_security_employee").notNull().default("0"),medicareEmployee:tT("medicare_employee").notNull().default("0"),socialSecurityEmployer:tT("social_security_employer").notNull().default("0"),medicareEmployer:tT("medicare_employer").notNull().default("0"),otherDeductions:tT("other_deductions").notNull().default("0"),benefitsEmployee:tT("benefits_employee").notNull().default("0"),benefitsEmployer:tT("benefits_employer").notNull().default("0"),netPay:tT("net_pay").notNull(),ytdGross:td("ytd_gross",{precision:12,scale:2}),ytdFederalWithholding:td("ytd_federal_withholding",{precision:12,scale:2}),ytdSocialSecurity:td("ytd_social_security",{precision:12,scale:2}),ytdMedicare:td("ytd_medicare",{precision:12,scale:2}),ytdNet:td("ytd_net",{precision:12,scale:2}),effectiveFilingStatus:tT("effective_filing_status"),grossTaxableWages:tT("gross_taxable_wages"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("pay_stubs_run_idx").on(e.payrollRunId),ne("pay_stubs_employee_idx").on(e.employeeId)]);t5("payroll_run_lines",{id:tM("id").primaryKey().defaultRandom(),payrollRunId:tM("payroll_run_id").notNull().references(()=>
1iG.id,{onDelete:"cascade"}),payStubId:tM("pay_stub_id").notNull().references(()=>iz.id,{onDelete:"cascade"}),componentId:tM("component_id").references(()=>iU.id,{onDelete:"set null"}),kind:iS("kind").notNull(),amount:tT("amount").notNull(),taxableAmount:tT("taxable_amount"),lineMetadata:eY("line_metadata").$type().default(null),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("prl_run_idx").on(e.payrollRunId),ne("prl_stub_idx").on(e.payStubId),ne("prl_component_idx").on(e.componentId)]),t5("payroll_run_calculations",{id:tM("id").primaryKey().defaultRandom(),payStubId:tM("pay_stub_id").notNull().references(()=>iz.id,{onDelete:"cascade"}),taxRuleVersionId:tM("tax_rule_version_id").notNull().references(()=>iB.id,{onDelete:"restrict"}),computedAt:tj("computed_at").notNull().defaultNow(),calcInputs:eY("inputs").$type().notNull(),calcOutputs:eY("outputs").$type().notNull(),notes:tT("notes")},e=>[ne("prc_stub_idx").on(e.payStubId),ne("prc_rule_idx").on(e.taxRuleVersionId)]);let iQ=L("audit_category",["LEDGER","FINANCE","COMPLIANCE","SETTINGS","ACCESS","IMPORT","VERIFY","SYSTEM","HIERARCHY","CRM","INVOICING","EXPENSES","SERVICES","INVENTORY","PURCHASING","HR","ROUTES","SALES","DOCUMENTS","MANUFACTURING","SUBSCRIPTIONS","HELPDESK","MARKETING_AUTOMATION","MAINTENANCE","BI","ORG","GOVERNANCE","CAP_TABLE"]);t5("audit_logs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").references(()=>nP.id),userId:tM("user_id"),category:iQ("category").notNull(),action:tT("action").notNull(),description:tT("description").notNull(),targetType:tT("target_type"),targetId:tT("target_id"),metadata:eY("metadata"),ipAddress:tT("ip_address"),userAgent:tT("user_agent"),previousHash:tT("previous_hash"),entryHash:tT("entry_hash").notNull(),sequenceNumber:eB("sequence_number").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("audit_logs_entity_idx").on(e.entityId),ne("audit_logs_user_idx").on(e.userId),ne("audit_logs_category_idx").on(e.category),ne("audit_logs_created_idx").on(e.createdAt),ne("audit_logs_target_idx").on(e.targetType,e.targetId),ne("audit_logs_entity_seq_idx").on(e.entityId,e.sequenceNumber)]);let iY=L("change_request_status",["DRAFT","PENDING_APPROVAL","APPROVED","REJECTED","IMPLEMENTED","CLOSED"]),iW=L("change_risk_level",["LOW","MEDIUM","HIGH","CRITICAL"]),iJ=t5("change_requests",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),ticketId:tT("ticket_id"),title:tT("title").notNull(),description:tT("description").notNull(),riskLevel:iW("risk_level").notNull().default("MEDIUM"),category:tT("category").notNull(),requestedBy:tT("requested_by").notNull(),status:iY("status").notNull().default("DRAFT"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("change_requests_entity_idx").on(e.entityId),ne("change_requests_status_idx").on(e.status),ne("change_requests_requested_by_idx").on(e.requestedBy)]);t5("change_approvals",{id:tM("id").primaryKey().defaultRandom(),changeRequestId:tM("change_request_id").notNull().references(()=>iJ.id),decidedBy:tT("decided_by").notNull(),decision:tT("decision").notNull(),comments:tT("comments"),decidedAt:tj("decided_at").notNull().defaultNow()},e=>[ne("change_approvals_request_idx").on(e.changeRequestId)]);let iX=L("notification_type",["approval_pending","approval_resolved","sync_completed","sync_failed","close_deadline","usage_threshold","team_invite","comment_added","mention","system","crm_lead_assigned","crm_lead_won","invoice_overdue","invoice_paid","expense_submitted","expense_approved","service_job_assigned","service_job_completed","inventory_low_stock","purchase_order_approved","hr_leave_requested","hr_leave_approved","route_assigned","sales_quote_approved","document_signature_requested","document_signer_signed","document_signing_completed","crm_task_due","manufacturing_order_completed","subscription_payment_failed","helpdesk_ticket_assigned","marketing_campaign_completed","ads_morning_brief","maintenance_work_order_assigned","bi_report_ready","governance_filing_due","cursor_agent_pr_linked","bank_feed_review","auto
1pilot_digest","dev_mode_go_live","onchain_sync_completed","work_task_assigned","work_task_mentioned","work_task_due","work_task_comment","work_task_updated","work_sprint_update","investing_position_alert"]);t5("notifications",{id:tM("id").primaryKey().defaultRandom(),userId:tM("user_id").notNull(),entityId:tM("entity_id").references(()=>nP.id,{onDelete:"cascade"}),type:iX("type").notNull(),title:tT("title").notNull(),body:tT("body"),actionUrl:tT("action_url"),read:ef("read").notNull().default(!1),readAt:tj("read_at"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("notifications_user_idx").on(e.userId),ne("notifications_user_read_idx").on(e.userId,e.read),ne("notifications_entity_idx").on(e.entityId),ne("notifications_created_idx").on(e.createdAt)]);let iZ=L("notification_channel",["in_app","email","push"]);t5("notification_preferences",{id:tM("id").primaryKey().defaultRandom(),userId:tM("user_id").notNull(),type:iX("type").notNull(),channel:iZ("channel").notNull(),enabled:ef("enabled").notNull().default(!0),delivery:tT("delivery"),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("notif_pref_user_type_channel_idx").on(e.userId,e.type,e.channel)]);let i0=L("comment_target_type",["JOURNAL_ENTRY","EVENT","INVOICE","BILL","DOCUMENT","ACCOUNT"]),i1=t5("comments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),userId:tM("user_id").notNull(),targetType:i0("target_type").notNull(),targetId:tM("target_id").notNull(),body:tT("body").notNull(),mentions:eY("mentions").$type().default([]),parentId:tM("parent_id").references(()=>i1.id,{onDelete:"cascade"}),deletedAt:tj("deleted_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("comments_entity_idx").on(e.entityId),ne("comments_target_idx").on(e.targetType,e.targetId),ne("comments_user_idx").on(e.userId),ne("comments_parent_idx").on(e.parentId)]);t5("comment_reactions",{id:tM("id").primaryKey().defaultRandom(),commentId:tM("comment_id").notNull().references(()=>i1.id,{onDelete:"cascade"}),userId:tM("user_id").notNull(),emoji:tT("emoji").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("comment_reactions_comment_idx").on(e.commentId),nt("comment_reactions_unique_idx").on(e.commentId,e.userId,e.emoji)]);let i2=L("anomaly_severity",["LOW","MEDIUM","HIGH","CRITICAL"]),i4=L("anomaly_status",["OPEN","REVIEWED","DISMISSED","RESOLVED"]);t5("anomaly_flags",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),ruleCode:tT("rule_code").notNull(),severity:i2("severity").notNull(),status:i4("status").notNull().default("OPEN"),title:tT("title").notNull(),description:tT("description").notNull(),details:eY("details"),sourceTransactionId:tM("source_transaction_id"),sourceEventId:tM("source_event_id"),sourceJournalEntryId:tM("source_journal_entry_id"),accountId:tM("account_id"),amount:tT("amount"),currency:tT("currency"),reviewedAt:tj("reviewed_at"),reviewedBy:tT("reviewed_by"),reviewNote:tT("review_note"),detectedAt:tj("detected_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("anomaly_flags_entity_idx").on(e.entityId),ne("anomaly_flags_status_idx").on(e.status),ne("anomaly_flags_severity_idx").on(e.severity),ne("anomaly_flags_rule_idx").on(e.ruleCode),ne("anomaly_flags_detected_idx").on(e.detectedAt)]),t5("shielded_notes",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),noteCommitment:tT("note_commitment").notNull(),nullifierHash:tT("nullifier_hash"),token:tT("token").notNull(),amount:tT("amount").notNull(),salt:tT("salt").notNull(),recipientPubkey:tT("recipient_pubkey").notNull(),leafIndex:eB("leaf_index").notNull(),isSpent:ef("is_spent").notNull().default(!1),spentInTxHash:tT("spent_in_tx_hash"),createdInTxHash:tT("created_in_tx_hash"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("shielded_notes_entity_idx").on(e.entityId),ne("shielded_notes_commitment_idx").on(e.noteCommitment),ne("shielded_notes_nullifier_idx").on(e.nullifierHash),ne("shielded_notes_unspent_idx").on(e.entityId,e.isSpent),ne("shielded_notes_token_idx").on(e.entityId,e.token)]),t5("viewing_key_grants",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),auditorAddress:tT("auditor_address").notNull(),encryptedViewingKey:tT("encrypted_viewing_key").notNull(),scope:tT("scope").notNull().default("full"),grantedAt:tj("granted_at").notNull().defaultNow(),expiresAt:tj("expires_at"),revokedAt:tj("revoked_at")},e=>[ne("viewing_key_grants_entity_idx").on(e.entityId),ne("viewing_key_grants_auditor_idx").on(e.auditorAddress),ne("viewing_key_grants_active_idx").on(e.entityId,e.revokedAt)]),t5("protocol_webhook_nonces",{nonce:tT("nonce").primaryKey(),senderProtocolEntityId:tT("sender_protocol_entity_id").notNull(),receivedAt:tj("received_at").notNull().defaultNow()},e=>[ne("protocol_webhook_nonces_received_idx").on(e.receivedAt)]),t5("time_entries",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),firmEntityId:tM("firm_entity_id").notNull().references(()=>nP.id),userId:tM("user_id").notNull(),date:eS("date").notNull(),hours:td("hours",{precision:5,scale:2}).notNull(),description:tT("description"),billable:ef("billable").notNull().default(!0),rate:td("rate",{precision:10,scale:2}),invoiceId:tM("invoice_id"),engagementId:tM("engagement_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("te_entity_idx").on(e.entityId),ne("te_firm_idx").on(e.firmEntityId),ne("te_user_idx").on(e.userId),ne("te_date_idx").on(e.date)]);let i6=t5("engagements",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),firmEntityId:tM("firm_entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),type:tT("type").notNull().default("monthly_close"),recurrence:tT("recurrence"),startDate:eS("start_date").notNull(),endDate:eS("end_date"),status:tT("status").notNull().default("active"),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("eng_entity_idx").on(e.entityId),ne("eng_firm_idx").on(e.firmEntityId)]);t5("engagement_tasks",{id:tM("id").primaryKey().defaultRandom(),engagementId:tM("engagement_id").notNull().references(()=>i6.id),name:tT("name").notNull(),dueDate:eS("due_date"),assigneeUserId:tM("assignee_user_id"),status:tT("status").notNull().default("pending"),completedAt:tj("completed_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("engt_engagement_idx").on(e.engagementId),ne("engt_assignee_idx").on(e.assigneeUserId)]),t5("partner_referrals",{id:tM("id").primaryKey().defaultRandom(),referrerEntityId:tM("referrer_entity_id").notNull().references(()=>nP.id),referredEntityId:tM("referred_entity_id").references(()=>nP.id),referralCode:tT("referral_code").notNull().unique(),referredEmail
1:tT("referred_email"),status:tT("status").notNull().default("pending"),creditAmount:eB("credit_amount").notNull().default(0),creditAppliedAt:tj("credit_applied_at"),convertedAt:tj("converted_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("pr_referrer_idx").on(e.referrerEntityId),ne("pr_code_idx").on(e.referralCode),ne("pr_status_idx").on(e.status)]),t5("shareable_report_links",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),reportType:tT("report_type").notNull(),parameters:eY("parameters").$type().notNull(),token:tT("token").notNull().unique(),createdBy:tM("created_by").notNull(),expiresAt:tj("expires_at").notNull(),accessCount:eB("access_count").notNull().default(0),lastAccessedAt:tj("last_accessed_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("srl_entity_idx").on(e.entityId),ne("srl_token_idx").on(e.token),ne("srl_expires_idx").on(e.expiresAt)]);let i8=L("crm_company_status",["active","inactive"]),i5=L("crm_pipeline_stage_kind",["open","won","lost","disqualified"]),i3=L("crm_activity_type",["call","email","meeting","note","task","sms"]),i9=L("crm_task_status",["open","in_progress","done","cancelled"]),i7=t5("companies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id),name:tT("name").notNull(),legalName:tT("legal_name"),aliasNames:tT("alias_names"),website:tT("website"),linkedinUrl:tT("linkedin_url"),jurisdiction:tT("jurisdiction"),industry:tT("industry"),naicsCode:tT("naics_code"),notes:tT("notes"),status:i8("status").notNull().default("active"),ownerUserId:tM("owner_user_id"),parentCompanyId:tM("parent_company_id").references(()=>i7.id,{onDelete:"restrict"}),googlePlaceId:tT("google_place_id"),resolvedRegistryId:tM("resolved_registry_id"),logoDocumentId:tM("logo_document_id").references(()=>a9.id,{onDelete:"set null"}),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("companies_entity_idx").on(e.entityId),ne("companies_resolved_registry_idx").on(e.resolvedRegistryId),ne("companies_counterparty_idx").on(e.counterpartyId),ne("companies_status_idx").on(e.entityId,e.status),ne("companies_entity_status_owner_idx").on(e.entityId,e.status,e.ownerUserId),ne("companies_entity_naics_idx").on(e.entityId,e.naicsCode),ne("companies_entity_parent_idx").on(e.entityId,e.parentCompanyId),ne("companies_entity_google_place_id_idx").on(e.entityId,e.googlePlaceId),ne("companies_logo_document_idx").on(e.logoDocumentId)]);t5("company_hierarchy_closure",{entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),ancestorId:tM("ancestor_id").notNull().references(()=>i7.id,{onDelete:"cascade"}),descendantId:tM("descendant_id").notNull().references(()=>i7.id,{onDelete:"cascade"}),depth:eB("depth").notNull()},e=>[nn({columns:[e.entityId,e.ancestorId,e.descendantId]}),ne("company_h_closure_entity_desc_idx").on(e.entityId,e.descendantId),ne("company_h_closure_entity_anc_idx").on(e.entityId,e.ancestorId)]);let oe=L("site_kind",["office","warehouse","plant","service","territory","virtual","other"]),ot=L("site_status",["active","closed"]),on=t5("sites",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"cascade"}),parentSiteId:tM("parent_site_id"),name:tT("name").notNull(),code:tT("code"),roles:oe("roles").array().notNull().default(Y`'{office}'::site_kind[]`),status:ot("status").notNull().default("active"),openedAt:eS("opened_at"),closedAt:eS("closed_at"),managerContactId:tM("manager_contact_id").references(()=>la.id,{onDelete:"set null"}),hours:eY("hours").$type(),notes:tT("notes"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>{var t;return[ne("sites_entity_idx").on(e.entityId),ne("sites_entity_counterparty_idx").on(e.entityId,e.counterpartyId),ne("sites_entity_status_idx").on(e.entityId,e.status),ne("sites_entity_self_idx").on(e.entityId).where(Y`counterparty_id IS NULL`),ne("sites_parent_idx").on(e.parentSiteId),nt("sites_entity_party_code_idx").on(e.entityId,e.counterpartyId,e.code).where(Y`code IS NOT NULL`),(t={columns:[e.parentSiteId],foreignColumns:[e.id]},new N(function(){let{name:e,columns:n,foreignColumns:d}=t;return{name:e,columns:n,foreignColumns:d}})).onDelete("set null")]});t5("crm_contact_company_memberships",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),contactId:tM("contact_id").notNull().references(()=>la.id,{onDelete:"cascade"}),companyId:tM("company_id").notNull().references(()=>i7.id,{onDelete:"cascade"}),title:tT("title"),isPrimary:ef("is_primary").notNull().default(!1),startDate:eS("start_date"),endDate:eS("end_date"),notes:tT("notes"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("crm_ccm_entity_idx").on(e.entityId),ne("crm_ccm_contact_idx").on(e.contactId),ne("crm_ccm_company_idx").on(e.companyId),ne("crm_ccm_entity_contact_idx").on(e.entityId,e.contactId),ne("crm_ccm_entity_company_idx").on(e.entityId,e.companyId),ne("crm_ccm_entity_site_idx").on(e.entityId,e.siteId)]);let od=t5("crm_lead_sources",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("crm_lead_sources_entity_idx").on(e.entityId),nt("crm_lead_sources_entity_name_idx").on(e.entityId,e.name)]),oa=t5("crm_pipeline_stages",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),sortOrder:eB("sort_order").notNull().default(0),defaultProbabilityPct:eB("default_probability_pct").notNull().default(0),kind:i5("kind").notNull().default("open"),systemKey:tT("system_key"),colorKey:tT("color_key"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("crm_pipeline_stages_entity_idx").on(e.entityId),ne("crm_pipeline_stages_entity_sort_idx").on(e.entityId,e.sortOrder),nt("crm_pipeline_stages_entity_name_idx").on(e.entityId,e.name),nt("crm_pipeline_stages_entity_system_key_idx").on(e.entityId,e.systemKey)]),oi=t5("crm_leads",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),companyId:tM("company_id").references(()=>i7.id),contactId:tM("contact_id").references(()=>la.id),sourceId:tM("source_id").references(()=>od.id),title:tT("title").notNull(),stageId:tM("stage_id").notNull().references(()=>oa.id),expectedValue:td("expected_value",{precision:20,scale:2}),currency:tT("currency").notNull().default("USD"),ownerUserId:tM("owner_user_id"),expectedCloseDate:eS("expected_close_date"),wonAt:tj("won_at"),lostReason:tT("lost_reason"),notes:tT("notes"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("crm_leads_entity_idx").on(e.entityId),ne("crm_leads_company_idx").on(e.companyId),ne("crm_leads_stage_idx").on(e.entityId,e.stageId),ne("crm_leads_owner_idx").on(e.ownerUserId),ne("crm_leads_site_idx").on(e.entityId,e.siteId)]);t5("crm_lead_contacts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),leadId:tM("lead_id").notNull().references(()=>oi.id,{onDelete:"cascade"}),contactId:tM("contact_id").notNull().references(()=>la.id,{onDelete:"cascade"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("crm_lead_contacts_entity_idx").on(e.entityId),ne("crm_lead_contacts_lead_idx").on(e.leadId),ne("crm_lead_contacts_contact_idx").on(e.contactId),nt("crm_lead_contacts_lead_contact_idx").on(e.leadId,e.contactId)]),t5("crm_activities",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),companyId:tM("company_id").references(()=>i7.id),leadId:tM("lead_id").references(()=>oi.id,{onDelete:"cascade"}),contactId:tM("contact_id").references(()=>la.id),type:i3("type").notNull(),subject:tT("subject").notNull(),body:tT("body"),dueAt:tj("due_at"),completedAt:tj("completed_at"),createdBy:tM("created_by"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("crm_activities_entity_idx").on(e.entityId),ne("crm_activities_lead_idx").on(e.leadId),ne("crm_activities_company_idx").on(e.companyId),ne("crm_activities_site_idx").on(e.entityId,e.siteId)]),t5("crm_tasks",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),companyId:tM("company_id").references(()=>i7.id),leadId:tM("lead_id").references(()=>oi.id,{onDelete:"cascade"}),contactId:tM("contact_id").references(()=>la.id,{onDelete:"set null"}),title:tT("title").notNull(),status:i9("status").notNull().default("open"),assignedTo:tM("assigned_to"),dueAt:tj("due_at"),completedAt:tj("completed_at"),lastDueReminderAt:tj("last_due_reminder_at"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("crm_tasks_entity_idx").on(e.entityId),ne("crm_tasks_status_idx").on(e.entityId,e.status),ne("crm_tasks_assigned_idx").on(e.assignedTo),ne("crm_tasks_contact_idx").on(e.entityId,e.contactId),ne("crm_tasks_site_idx").on(e.entityId,e.siteId)]);let oo=L("service_type",["work_order","project","field_service"]),ol=L("job_status",["intake","in_progress","quality_check","ready","delivered","invoiced","planning","review","completed","scheduled","dispatched","on_site","cancelled"]),or=L("job_priority",["low","normal","high","urgent"]),os=L("job_work_scope",["client","internal"]),o_=L("job_line_status",["received","processing","completed"]),ou=L("route_status",["planned","in_progress","completed"]),oc=L("route_stop_type",["pickup","delivery","service"]),op=t5("jobs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),jobNumber:tT("job_number").notNull(),name:tT("name"),serviceType:oo("service_type").notNull().default("work_order"),workScope:os("work_scope").notNull().default("client"),customerId:tM("customer_id").references(()=>dn.id),status:ol("status").notNull().default("intake"),priority:or("priority").notNull().default("normal"),assignedTo:tM("assigned_to"),dueDate:tj("due_date"),scheduledStart:tj("scheduled_start"),scheduledEnd:tj("scheduled_end"),actualStart:tj("actual_start"),actualEnd:tj("actual_end"),completedAt:tj("completed_at"),billingModel:tT("billing_model"),hourlyRate:td("hourly_rate",{precision:20,scale:4}),estimatedHours:td("estimated_hours",{precision:10,scale:2}),address:tT("address"),serviceAddressId:tM("service_address_id").references(()=>lo.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata").$type(),quoteId:tM("quote_id").references(()=>l5.id,{onDelete:"set null"}),salesOrderId:tM("sales_order_id").references(()=>l3.id,{onDelete:"set null"}),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("jobs_entity_idx").on(e.entityId),ne("jobs_customer_idx").on(e.customerId),ne("jobs_status_idx").on(e.entityId,e.status),ne("jobs_service_type_idx").on(e.entityId,e.serviceType),ne("jobs_work_scope_idx").on(e.entityId,e.workScope),ne("jobs_service_address_idx").on(e.serviceAddressId),ne("jobs_quote_idx").on(e.quoteId),ne("jobs_sales_order_idx").on(e.salesOrderId),nt("jobs_entity_job_number_idx").on(e.entityId,e.jobNumber),ne("jobs_entity_site_idx").on(e.entityId,e.siteId)]),oy=L("project_time_timer_status",["running","paused"]);t5("project_time_timers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),userId:tM("user_id").notNull(),jobId:tM("job_id").notNull().references(()=>op.id,{onDelete:"cascade"}),taskId:tM("task_id"),description:tT("description"),billable:ef("billable").notNull().default(!1),status:oy("status").notNull().default("running"),segmentStartedAt:tj("segment_started_at").notNull(),accumulatedMs:eB("accumulated_ms").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("project_time_timers_entity_user_unique").on(e.entityId,e.userId),ne("project_time_timers_job_idx").on(e.jobId)]),t5("service_time_entries",{id:tM("id").primaryKey().defaultRandom(),jobId:tM("job_id").notNull().references(()=>op.id,{onDelete:"cascade"}),taskId:tM("task_id"),userId:tM("user_id"),date:eS("date").notNull(),hours:td("hours",{precision:10,scale:2}).notNull(),description:tT("description"),billable:ef("billable").notNull().default(!0),invoiced:ef("invoiced").notNull().default(!1),invoiceId:tM("invoice_id").references(()=>dg.id,{onDelete:"set null"}),projectCostPostingId:tM("project_cost_posting_id").references(()=>se.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("service_time_entries_job_idx").on(e.jobId),ne("service_time_entries_task_idx").on(e.taskId),ne("service_time_entries_user_date_idx").on(e.userId,e.date),ne("service_time_entries_invoice_idx").on(e.invoiceId)]),t5("invoice_send_log",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),invoiceId:tM("invoice_id").notNull().references(()=>dg.id,{onDelete:"cascade"}),connectionId:tM("connection_id").references(()=>ap.id,{onDelete:"set null"}),channel:tT("channel").notNull(),toEmail:tT("to_email").notNull(),billingPeriodStart:eS("billing_period_start"),billingPeriodEnd:eS("billing_period_end"),includedTimesheet:ef("included_timesheet").notNull().default(!1),entryCount:eB("entry_count").notNull().default(0),providerMessageId:tT("provider_message_id"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("invoice_send_log_invoice_idx").on(e.invoiceId),ne("invoice_send_log_entity_idx").on(e.entityId)]);let om=L("outbound_message_status",["draft","scheduled","sending","sent","failed","cancelled"]),of=t5("outbound_messages",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),status:om("status").notNull().default("draft"),connectionId:tM("connection_id").references(()=>ap.id,{onDelete:"set null"}),channel:tT("channel"),toEmail:tT("to_email"),ccEmails:tT("cc_emails"),bccEmails:tT("bcc_emails"),subject:tT("subject"),htmlBody:tT("html_body"),textBody:tT("text_body"),scheduledAt:tj("scheduled_at"),sentAt:tj("sent_at"),failedAt:tj("failed_at"),failureReason:tT("failure_reason"),providerMessageId:tT("provider_message_id"),contextType:tT("context_type").notNull(),contextId:tM("context_id").notNull(),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"set null"}),companyId:tM("company_id").references(()=>i7.id,{onDelete:"set null"}),leadId:tM("lead_id").references(()=>oi.id,{onDelete:"set null"}),contactId:tM("contact_id").references(()=>la.id,{onDelete:"set null"}),createdBy:tM("created_by"),updatedBy:tM("updated_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("outbound_messages_entity_idx").on(e.entityId),ne("outbound_messages_entity_status_scheduled_idx").on(e.entityId,e.status,e.scheduledAt),ne("outbound_messages_document_idx").on(e.documentId),ne("outbound_messages_context_idx").on(e.contextType,e.contextId)]);t5("outbound_message_attachments",{id:tM("id").primaryKey().defaultRandom(),messageId:tM("message_id").notNull().references(()=>of.id,{onDelete:"cascade"}),documentId:tM("document_id").notNull().references(()=>a9.id,{onDelete:"cascade"}),sortOrder:eB("sort_order").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("outbound_message_attachments_message_idx").on(e.messageId),ne("outbound_message_attachments_document_idx").on(e.documentId)]),t5("job_lines",{id:tM("id").primaryKey().defaultRandom(),jobId:tM("job_id").notNull().references(()=>op.id,{onDelete:"cascade"}),inventoryItemId:tM("inventory_item_id").references(()=>oL.id),skuCode:tT("sku_code"),description:tT("description"),quantity:eB("quantity").notNull().default(1),unitPrice:td("unit_price",{precision:20,scale:4}),status:o_("status").notNull().default("received"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("job_lines_job_idx").on(e.jobId)]);let oN=L("project_milestone_status",["pending","in_progress","complete"]),oI=L("project_sprint_status",["planned","active","completed","cancelled"]),og=L("project_sprint_scope_mode",["locked","flexible"]),ob=L("project_sprint_naming_mode",["
1sequence","date_range"]),oh=L("project_task_status",["todo","in_progress","review","done","blocked"]),ov=L("project_task_type",["bug","task","feature","improvement","spike","chore"]),ox=L("project_task_activity_author",["user","system","cortex"]),oA=t5("project_milestones",{id:tM("id").primaryKey().defaultRandom(),projectId:tM("project_id").notNull().references(()=>op.id,{onDelete:"cascade"}),name:tT("name").notNull(),description:tT("description"),targetDate:eS("target_date"),status:oN("status").notNull().default("pending"),isBillable:ef("is_billable").notNull().default(!1),amount:tT("amount"),sortOrder:eB("sort_order").notNull().default(0),salesOrderLineId:tM("sales_order_line_id").references(()=>l9.id,{onDelete:"set null"}),invoiceId:tM("invoice_id").references(()=>dg.id,{onDelete:"set null"}),invoicedAt:tj("invoiced_at"),completedAt:tj("completed_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("project_milestones_project_idx").on(e.projectId),ne("project_milestones_sales_order_line_idx").on(e.salesOrderLineId),ne("project_milestones_invoice_idx").on(e.invoiceId)]),oD=t5("project_sprints",{id:tM("id").primaryKey().defaultRandom(),projectId:tM("project_id").notNull().references(()=>op.id,{onDelete:"cascade"}),name:tT("name").notNull(),goal:tT("goal"),capacityPoints:eB("capacity_points"),capacityHours:td("capacity_hours",{precision:10,scale:2}),status:oI("status").notNull().default("planned"),startDate:eS("start_date").notNull(),endDate:eS("end_date").notNull(),scopeMode:og("scope_mode").notNull().default("flexible"),startedAt:tj("started_at"),completedAt:tj("completed_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("project_sprints_project_status_idx").on(e.projectId,e.status),ne("project_sprints_project_start_idx").on(e.projectId,e.startDate)]);t5("project_sprint_settings",{projectId:tM("project_id").primaryKey().references(()=>op.id,{onDelete:"cascade"}),durationWeeks:eB("duration_weeks").notNull().default(2),startWeekday:eB("start_weekday").notNull().default(1),autoCreateNext:ef("auto_create_next").notNull().default(!0),namingMode:ob("naming_mode").notNull().default("sequence"),sequencePrefix:tT("sequence_prefix").notNull().default("Sprint"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()});let ow=t5("project_tasks",{id:tM("id").primaryKey().defaultRandom(),projectId:tM("project_id").notNull().references(()=>op.id,{onDelete:"cascade"}),milestoneId:tM("milestone_id").references(()=>oA.id,{onDelete:"set null"}),sprintId:tM("sprint_id").references(()=>oD.id,{onDelete:"set null"}),parentTaskId:tM("parent_task_id"),title:tT("title").notNull(),description:tT("description"),status:oh("status").notNull().default("todo"),taskType:ov("task_type").notNull().default("task"),priority:or("priority").notNull().default("normal"),assigneeId:tM("assignee_id"),storyPoints:eB("story_points"),estimatedHours:td("estimated_hours",{precision:10,scale:2}),dueDate:eS("due_date"),sortOrder:eB("sort_order").notNull().default(0),externalLinks:eY("external_links").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("project_tasks_project_idx").on(e.projectId),ne("project_tasks_milestone_idx").on(e.milestoneId),ne("project_tasks_sprint_idx").on(e.sprintId),ne("project_tasks_assignee_idx").on(e.assigneeId),ne("project_tasks_status_idx").on(e.projectId,e.status),ne("project_tasks_task_type_idx").on(e.projectId,e.taskType),ne("project_tasks_priority_idx").on(e.projectId,e.priority),ne("project_tasks_project_sprint_idx").on(e.projectId,e.sprintId),ne("project_tasks_sprint_status_idx").on(e.sprintId,e.status)]);t5("project_task_activities",{id:tM("id").primaryKey().defaultRandom(),taskId:tM("task_id").notNull().references(()=>ow.id,{onDelete:"cascade"}),authorType:ox("author_type").notNull().default("user"),authorId:tM("author_id"),authorName:tT("author_name"),body:tT("body").notNull(),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("project_task_activities_task_idx").on(e.taskId),ne("project_task_activities_task_created_idx").on(e.taskId,e.createdAt)]),t5("project_task_watchers",{id:tM("id").primaryKey().defaultRandom(),taskId:tM("task_id").notNull().references(()=>
1ow.id,{onDelete:"cascade"}),userId:tM("user_id").notNull(),watching:ef("watching").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("project_task_watchers_task_user_idx").on(e.taskId,e.userId),ne("project_task_watchers_user_idx").on(e.userId)]),t5("project_task_notification_queue",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),taskId:tM("task_id").references(()=>ow.id,{onDelete:"cascade"}),sprintId:tM("sprint_id").references(()=>oD.id,{onDelete:"cascade"}),recipientId:tM("recipient_id").notNull(),actorId:tM("actor_id"),actorKind:tT("actor_kind").notNull().default("user"),actorVia:tT("actor_via"),kind:tT("kind").notNull(),detail:eY("detail").$type(),coalesceKey:tT("coalesce_key").notNull(),dedupeKey:tT("dedupe_key"),status:tT("status").notNull().default("pending"),emailMode:tT("email_mode"),error:tT("error"),createdAt:tj("created_at").notNull().defaultNow(),flushedAt:tj("flushed_at"),digestSentAt:tj("digest_sent_at")},e=>[nt("project_task_notification_queue_dedupe_idx").on(e.dedupeKey),ne("project_task_notification_queue_coalesce_idx").on(e.coalesceKey,e.status),ne("project_task_notification_queue_status_idx").on(e.status,e.createdAt),ne("project_task_notification_queue_recipient_idx").on(e.recipientId,e.status)]);let oE=t5("service_routes",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name"),description:tT("description"),routeDate:eS("route_date").notNull(),driverId:tM("driver_id"),vehicleId:tM("vehicle_id"),status:ou("status").notNull().default("planned"),notes:tT("notes"),startOdometer:tT("start_odometer"),endOdometer:tT("end_odometer"),totalMiles:tT("total_miles"),totalFuelCostCents:tT("total_fuel_cost_cents"),totalTollCostCents:tT("total_toll_cost_cents"),durationMinutes:eB("duration_minutes"),purpose:tT("purpose"),eventId:tM("event_id"),completedAt:tj("completed_at"),startSiteId:tM("start_site_id").references(()=>on.id,{onDelete:"set null"}),endSiteId:tM("end_site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("service_routes_entity_idx").on(e.entityId),ne("service_routes_date_idx").on(e.entityId,e.routeDate),ne("service_routes_status_idx").on(e.entityId,e.status),ne("service_routes_vehicle_idx").on(e.vehicleId),ne("service_routes_event_idx").on(e.eventId),ne("service_routes_entity_start_site_idx").on(e.entityId,e.startSiteId),ne("service_routes_entity_end_site_idx").on(e.entityId,e.endSiteId)]),oR=L("route_stop_status",["pending","arrived","in_progress","completed","skipped"]);t5("service_route_stops",{id:tM("id").primaryKey().defaultRandom(),routeId:tM("route_id").notNull().references(()=>oE.id,{onDelete:"cascade"}),customerId:tM("customer_id").references(()=>dn.id),stopOrder:eB("stop_order").notNull(),estimatedArrival:tj("estimated_arrival"),actualArrival:tj("actual_arrival"),jobId:tM("job_id").references(()=>op.id),stopType:oc("stop_type").notNull().default("service"),address:tT("address"),serviceAddressId:tM("service_address_id").references(()=>lo.id,{onDelete:"set null"}),contactName:tT("contact_name"),contactPhone:tT("contact_phone"),status:oR("status").notNull().default("pending"),milesToStop:tT("miles_to_stop"),serviceRevenueCents:tT("service_revenue_cents"),chargedToInvoiceId:tM("charged_to_invoice_id"),completedAt:tj("completed_at"),completionNotes:tT("completion_notes"),notes:tT("notes"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),salesOrderId:tM("sales_order_id"),deliveryWindowStart:tT("delivery_window_start"),deliveryWindowEnd:tT("delivery_window_end"),estimatedDeparture:tj("estimated_departure"),podPhotoDocumentId:tM("pod_photo_document_id").references(()=>a9.id,{onDelete:"set null"}),podSignature:tT("pod_signature"),podGeotagLat:tT("pod_geotag_lat"),podGeotagLng:tT("pod_geotag_lng"),podCapturedAt:tj("pod_captured_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("service_route_stops_route_idx").on(e.routeId),ne("service_route_stops_customer_idx").on(e.customerId),ne("service_route_stops_service_address_idx").on(e.serviceAddressId),nt("service_route_stops_unique_order_idx").on(e.routeId,e.stopOrder),ne("service_route_stops_site_idx").on(e.siteId),ne("service_route_stops_sales_order_idx").on(e.salesOrderId),ne("service_route_stops_pod_doc_idx").on(e.podPhotoDocumentId)]);let ok=t5("route_drivers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),phone:tT("phone"),email:tT("email"),licenseNumber:tT("license_number"),isActive:ef("is_active").notNull().default(!0),employeeId:tM("employee_id").references(()=>iM.id),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("route_drivers_entity_idx").on(e.entityId),ne("route_drivers_employee_idx").on(e.employeeId)]),oT=L("route_template_cadence",["daily","weekly","monthly","manual"]),oS=t5("route_templates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),description:tT("description"),cadence:oT("cadence").notNull().default("manual"),cadenceConfig:eY("cadence_config").$type(),defaultDriverId:tM("default_driver_id").references(()=>ok.id,{onDelete:"set null"}),defaultVehicleId:tM("default_vehicle_id"),startSiteId:tM("start_site_id").references(()=>on.id,{onDelete:"set null"}),endSiteId:tM("end_site_id").references(()=>on.id,{onDelete:"set null"}),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("route_templates_entity_idx").on(e.entityId),ne("route_templates_active_idx").on(e.entityId,e.isActive)]);t5("route_template_stops",{id:tM("id").primaryKey().defaultRandom(),templateId:tM("template_id").notNull().references(()=>oS.id,{onDelete:"cascade"}),stopOrder:eB("stop_order").notNull(),customerId:tM("customer_id").references(()=>dn.id,{onDelete:"set null"}),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),serviceAddressId:tM("service_address_id"),address:tT("address"),contactName:tT("contact_name"),contactPhone:tT("contact_phone"),stopType:oc("stop_type").notNull().default("service"),deliveryWindowStart:tT("delivery_window_start"),deliveryWindowEnd:tT("delivery_window_end"),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("route_template_stops_template_idx").on(e.templateId),nt("route_template_stops_unique_order_idx").on(e.templateId,e.stopOrder)]);let oC=L("inventory_costing_method",["FIFO","LIFO","WEIGHTED_AVERAGE","SPECIFIC_ID"]),oP=L("inventory_item_status",["ACTIVE","DISCONTINUED","ON_HOLD"]),oO=L("inventory_tx_type",["PURCHASE","SALE","ADJUSTMENT","TRANSFER","RETURN","WRITE_DOWN","SCRAP","COUNT_ADJUSTMENT"]),oK=L("inventory_count_status",["DRAFT","IN_PROGRESS","COMPLETED"]),oL=t5("inventory_items",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),sku:tT("sku").notNull(),name:tT("name").notNull(),description:tT("description"),category:tT("category"),unitOfMeasure:tT("unit_of_measure").notNull().default("EA"),kind:nl("kind").notNull().default("inventory"),isSellable:ef("is_sellable").notNull().default(!0),isPurchasable:ef("is_purchasable").notNull().default(!0),sourcingMethod:nr("sourcing_method").notNull().default("stock"),salesPrice:td("sales_price",{precision:20,scale:4}),salesAccountId:tM("sales_account_id").references(()=>nU.id),cogsAccountId:tM("cogs_account_id").references(()=>nU.id),inventoryAccountId:tM("inventory_account_id").references(()=>nU.id),costingMethod:oC("costing_method").notNull().default("FIFO"),reorderPoint:td("reorder_point",{precision:20,scale:4}),reorderQty:td("reorder_qty",{precision:20,scale:4}),defaultVendorId:tM("default_vendor_id").references(()=>dn.id),glAccountId:tM("gl_account_id").references(()=>nU.id),status:oP("status").notNull().default("ACTIVE"),quantityOnHand:td("quantity_on_hand",{precision:20,scale:4}).notNull().default("0"),averageCost:td("average_cost",{precision:20,scale:6}).notNull().default("0"),lastPurchaseCost:td("last_purchase_cost",{precision:20,scale:6}),primaryImageDocumentId:tM("primary_image_document_id").references(()=>a9.id,{onDelete:"set null"}),metadata:eY("metadata").$type().notNull().default({}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inv_items_entity_idx").on(e.entityId),ne("inv_items_sku_idx").on(e.entityId,e.sku),ne("inv_items_status_idx").on(e.entityId,e.status),ne("inv_items_category_idx").on(e.entityId,e.category),ne("inv_items_kind_idx").on(e.entityId,e.kind),ne("inv_items_sellable_idx").on(e.entityId,e.isSellable),ne("inv_items_purchasable_idx").on(e.entityId,e.isPurchasable),ne("inv_items_primary_image_idx").on(e.primaryImageDocumentId)]);t5("item_bundle_components",{id:tM("id").primaryKey().defaultRandom(),bundleItemId:tM("bundle_item_id").notNull().references(()=>
1oL.id,{onDelete:"cascade"}),componentItemId:tM("component_item_id").notNull().references(()=>oL.id),quantity:td("quantity",{precision:20,scale:4}).notNull().default("1"),revenueAllocationPct:td("revenue_allocation_pct",{precision:5,scale:2}),sequence:eB("sequence").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("item_bundle_components_bundle_idx").on(e.bundleItemId),nt("item_bundle_components_unique_idx").on(e.bundleItemId,e.componentItemId)]),t5("inventory_item_locations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id,{onDelete:"cascade"}),siteId:tM("site_id").notNull().references(()=>on.id,{onDelete:"restrict"}),bin:tT("bin"),quantityOnHand:td("quantity_on_hand",{precision:20,scale:4}).notNull().default("0"),quantityReserved:td("quantity_reserved",{precision:20,scale:4}).notNull().default("0"),reorderPoint:td("reorder_point",{precision:20,scale:4}),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inv_item_locations_entity_idx").on(e.entityId),nt("inv_item_locations_item_site_unique_idx").on(e.itemId,e.siteId),ne("inv_item_locations_site_idx").on(e.siteId),ne("inv_item_locations_bin_idx").on(e.siteId,e.bin).where(Y`bin IS NOT NULL`)]);let oq=t5("inventory_lots",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id,{onDelete:"cascade"}),lotNumber:tT("lot_number").notNull(),purchaseDate:eS("purchase_date").notNull(),quantity:td("quantity",{precision:20,scale:4}).notNull(),remainingQty:td("remaining_qty",{precision:20,scale:4}).notNull(),unitCost:tT("unit_cost").notNull(),expirationDate:eS("expiration_date"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),supplierRef:tT("supplier_ref"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("inv_lots_item_idx").on(e.itemId),ne("inv_lots_entity_idx").on(e.entityId),ne("inv_lots_remaining_idx").on(e.itemId,e.remainingQty),ne("inv_lots_site_idx").on(e.siteId)]);t5("inventory_transactions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id,{onDelete:"cascade"}),lotId:tM("lot_id").references(()=>oq.id),type:oO("type").notNull(),quantity:td("quantity",{precision:20,scale:4}).notNull(),unitCost:tT("unit_cost").notNull(),totalCost:tT("total_cost").notNull(),reference:tT("reference"),notes:tT("notes"),eventId:tM("event_id").references(()=>nB.id),journalEntryId:tM("journal_entry_id").references(()=>nV.id),transactionDate:eS("transaction_date").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("inv_tx_entity_idx").on(e.entityId),ne("inv_tx_item_idx").on(e.itemId),ne("inv_tx_type_idx").on(e.entityId,e.type),ne("inv_tx_date_idx").on(e.entityId,e.transactionDate)]);let oj=t5("inventory_counts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),countDate:eS("count_date").notNull(),status:oK("status").notNull().default("DRAFT"),notes:tT("notes"),completedAt:tj("completed_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("inv_counts_entity_idx").on(e.entityId),ne("inv_counts_status_idx").on(e.entityId,e.status)]);t5("inventory_count_lines",{id:tM("id").primaryKey().defaultRandom(),countId:tM("count_id").notNull().references(()=>oj.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id),expectedQty:td("expected_qty",{precision:20,scale:4}).notNull().default("0"),countedQty:td("counted_qty",{precision:20,scale:4}),varianceQty:td("variance_qty",{precision:20,scale:4}),varianceCost:td("variance_cost",{precision:20,scale:2}),notes:tT("notes")},e=>[ne("inv_cl_count_idx").on(e.countId),ne("inv_cl_item_idx").on(e.itemId)]);let oU=L("inventory_item_identifier_kind",["part_number","mpn","oem","upc","gtin","ean","isbn","customer_sku","asset_tag","cross_reference"]);t5("inventory_item_identifiers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id,{onDelete:"cascade"}),kind:oU("kind").notNull(),value:tT("value").notNull(),vendor:tT("vendor"),isPrimary:ef("is_primary").notNull().default(!1),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("inv_item_ids_item_idx").on(e.itemId),ne("inv_item_ids_kind_value_idx").on(e.entityId,e.kind,e.value),ne("inv_item_ids_value_idx").on(e.entityId,e.value),nt("inv_item_ids_unique_idx").on(e.itemId,e.kind,e.value),nt("inv_item_ids_one_primary_per_kind_idx").on(e.itemId,e.kind).where(Y`is_primary = true`)]),t5("inventory_item_customers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id),customerSiteId:tM("customer_site_id").references(()=>on.id,{onDelete:"set null"}),hasContract:ef("has_contract").notNull().default(!1),contractRef:tT("contract_ref"),contractStartDate:eS("contract_start_date"),contractEndDate:eS("contract_end_date"),reorderPoint:td("reorder_point",{precision:20,scale:4}),reorderQty:td("reorder_qty",{precision:20,scale:4}),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inv_item_customers_item_idx").on(e.itemId),ne("inv_item_customers_customer_idx").on(e.entityId,e.counterpartyId),ne("inv_item_customers_site_idx").on(e.customerSiteId),nt("inv_item_customers_unique_idx").on(e.itemId,e.counterpartyId,Y`COALESCE(${e.customerSiteId}, '00000000-0000-0000-0000-000000000000'::uuid)`)]);let oB=L("inventory_reservation_status",["ACTIVE","RELEASED","FULFILLED"]);t5("inventory_reservations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"set null"}),salesOrderId:tM("sales_order_id").references(()=>l3.id,{onDelete:"set null"}),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),quantity:td("quantity",{precision:20,scale:4}).notNull(),status:oB("status").notNull().default("ACTIVE"),reference:tT("reference"),notes:tT("notes"),neededByDate:eS("needed_by_date"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow(),closedAt:tj("closed_at")},e=>[ne("inv_reservations_entity_idx").on(e.entityId),ne("inv_reservations_item_idx").on(e.itemId),ne("inv_reservations_item_status_idx").on(e.itemId,e.status),ne("inv_reservations_customer_idx").on(e.entityId,e.counterpartyId),ne("inv_reservations_order_idx").on(e.salesOrderId),ne("inv_reservations_document_idx").on(e.documentId)]),t5("inventory_item_vendors",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),itemId:tM("item_id").notNull().references(()=>oL.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id),vendorPartNumber:tT("vendor_part_number"),vendorMpn:tT("vendor_mpn"),vendorOem:tT("vendor_oem"),vendorUrl:tT("vendor_url"),unitCost:tT("unit_cost"),currency:tT("currency").default("USD"),leadTimeDays:eB("lead_time_days"),moq:td("moq",{precision:20,scale:4}),packSize:td("pack_size",{precision:20,scale:4}),uomConversion:td("uom_conversion",{precision:20,scale:6}),isPreferred:ef("is_preferred").notNull().default(!1),isActive:ef("is_active").notNull().default(!0),notes:tT("notes"),lastPurchaseDate:eS("last_purchase_date"),lastPurchaseCost:tT("last_purchase_cost"),lastPoId:tM("last_po_id"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inv_item_vendors_item_idx").on(e.itemId),ne("inv_item_vendors_vendor_idx").on(e.entityId,e.counterpartyId),nt("inv_item_vendors_unique_idx").on(e.itemId,e.counterpartyId),nt("inv_item_vendors_one_preferred_idx").on(e.itemId).where(Y`${e.isPreferred}
1 = true`)]);let oM=L("inventory_import_job_status",["parsing","mapping","reviewing","committing","committed","failed","cancelled"]);t5("inventory_import_jobs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),uploadedBy:tM("uploaded_by"),sourceFilename:tT("source_filename").notNull(),sourceMimeType:tT("source_mime_type").notNull(),sourceSizeBytes:eB("source_size_bytes").notNull(),sourceBlobUrl:tT("source_blob_url").notNull(),sourceHash:tT("source_hash").notNull(),warehouseSiteId:tM("warehouse_site_id").references(()=>on.id,{onDelete:"set null"}),status:oM("status").notNull().default("parsing"),headerRowIndex:eB("header_row_index").notNull().default(0),aiDetection:tT("ai_detection"),columnMapping:eY("column_mapping").$type().notNull().default({}),parsedRows:eY("parsed_rows").$type().notNull().default([]),decisions:eY("decisions").$type().notNull().default({}),parseWarnings:eY("parse_warnings").$type().notNull().default([]),resultSummary:eY("result_summary").$type(),errorMessage:tT("error_message"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inv_import_jobs_entity_idx").on(e.entityId,e.createdAt),nt("inv_import_jobs_hash_idx").on(e.entityId,e.sourceHash)]);let oF=L("budget_status",["DRAFT","APPROVED","ARCHIVED"]),oV=t5("budget_versions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bookId:tM("book_id").notNull().references(()=>nq.id),name:tT("name").notNull(),fiscalYear:eB("fiscal_year").notNull(),status:oF("status").notNull().default("DRAFT"),notes:tT("notes"),approvedBy:tM("approved_by"),approvedAt:tj("approved_at"),copiedFromId:tM("copied_from_id").references(()=>oV.id),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("bv_entity_idx").on(e.entityId),ne("bv_entity_year_idx").on(e.entityId,e.fiscalYear),ne("bv_book_idx").on(e.bookId)]);t5("budget_lines",{id:tM("id").primaryKey().defaultRandom(),budgetVersionId:tM("budget_version_id").notNull().references(()=>oV.id,{onDelete:"cascade"}),accountId:tM("account_id").notNull().references(()=>nU.id),periodId:tM("period_id").notNull().references(()=>n$.id),amount:tT("amount").notNull().default("0"),dimensionFilter:eY("dimension_filter").$type(),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("bl_version_idx").on(e.budgetVersionId),ne("bl_account_idx").on(e.accountId),ne("bl_period_idx").on(e.periodId),nt("bl_unique_idx").on(e.budgetVersionId,e.accountId,e.periodId)]),t5("report_templates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),config:eY("config").$type().notNull(),createdBy:tM("created_by").notNull(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("rt_entity_idx").on(e.entityId)]);let oH=L("card_account_status",["PENDING","ACTIVE","FROZEN","CLOSED"]),o$=t5("card_accounts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),bridgeCardAccountId:tT("bridge_card_account_id").notNull().unique(),bridgeCustomerId:tT("bridge_customer_id").notNull(),status:oH("status").notNull().default("PENDING"),last4:tT("last4"),bin:tT("bin"),expiry:tT("expiry"),cardholderName:tT("cardholder_name").notNull(),cryptoAccountAddress:tT("crypto_account_address"),cryptoAccountChain:tT("crypto_account_chain"),linkedAccountId:tM("linked_account_id"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("card_acct_entity_idx").on(e.entityId),ne("card_acct_bridge_id_idx").on(e.bridgeCardAccountId)]),oG=L("card_transaction_status",["APPROVED","SETTLED","REVERSED","DENIED"]);t5("card_transactions",{id:tM("id").primaryKey().defaultRandom(),cardAccountId:tM("card_account_id").notNull().references(()=>o$.id),bridgeTransactionId:tT("bridge_transaction_id").notNull().unique(),status:oG("status").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USD"),billingAmount:tT("billing_amount"),merchantName:tT("merchant_name"),merchantCategoryCode:tT("merchant_category_code"),merchantCategory:tT("merchant_category"),merchantState:tT("merchant_state"),merchantCountry:tT("merchant_country"),merchantPostalCode:tT("merchant_postal_code"),cardPresent:ef("card_present"),entryMethod:tT("entry_method"),intentType:tT("intent_type"),enrichedMerchantName:tT("enriched_merchant_name"),enrichedPlaceId:tT("enriched_place_id"),enrichedAddress:tT("enriched_address"),enrichedLat:td("enriched_lat"),enrichedLng:td("enriched_lng"),enrichedPhotoUrl:tT("enriched_photo_url"),memo:tT("memo"),stagedTransactionId:tM("staged_transaction_id").references(()=>n4.id),rawWebhookData:eY("raw_webhook_data").$type(),eventId:tM("event_id").references(()=>nB.id),authorizedAt:tj("authorized_at"),settledAt:tj("settled_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("card_tx_card_acct_idx").on(e.cardAccountId),ne("card_tx_bridge_id_idx").on(e.bridgeTransactionId),ne("card_tx_status_idx").on(e.status),ne("card_tx_mcc_idx").on(e.merchantCategoryCode),ne("card_tx_event_idx").on(e.eventId)]),t5("merchant_places",{id:tM("id").primaryKey().defaultRandom(),merchantName:tT("merchant_name").notNull(),postalCode:tT("postal_code").notNull(),placeId:tT("place_id"),displayName:tT("display_name"),formattedAddress:tT("formatted_address"),lat:td("lat"),lng:td("lng"),photoReference:tT("photo_reference"),category:tT("category"),rating:td("rating"),lastRefreshedAt:tj("last_refreshed_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("merchant_place_lookup_idx").on(e.merchantName,e.postalCode)]);let oz=L("personal_task_status",["PROPOSED","CONFIRMED","DISMISSED","COMPLETED"]),oQ=L("inbound_email_processing_status",["SYNCED","CLASSIFYING","NEEDS_REVIEW","PROCESSED","SKIPPED","ERROR"]),oY=L("inbound_email_artifact_type",["invoice","receipt","purchase_order","contact","crm_thread","crm_meeting","document","task_personal","task_crm","task_project","task_work"]),oW=L("inbound_intake_pattern_action",["skip","route_artifact"]),oJ=L("inbound_intake_policy_mode",["auto","triage","skip"]),oX=L("inbound_email_artifact_status",["PROPOSED","CONFIRMED","DISMISSED","FAILED"]),oZ=t5("inbound_email_messages",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),connectionId:tM("connection_id").notNull().references(()=>ap.id,{onDelete:"cascade"}),gmailMessageId:tT("gmail_message_id").notNull(),gmailThreadId:tT("gmail_thread_id").notNull(),internalDate:er("internal_date",{mode:"number"}).notNull(),encryptedSubject:tT("encrypted_subject"),encryptedSnippet:tT("encrypted_snippet"),encryptedBody:tT("encrypted_body"),encryptedHtmlBody:tT("encrypted_html_body"),encryptedFrom:tT("encrypted_from"),encryptedTo:tT("encrypted_to"),encryptedCc:tT("encrypted_cc"),fromEmailHmac:tT("from_email_hmac"),fromDomain:tT("from_domain"),labelIds:eY("label_ids").$type(),hasAttachments:ef("has_attachments").notNull().default(!1),processingStatus:oQ("processing_status").notNull().default("SYNCED"),classification:eY("classification").$type(),lastError:tT("last_error"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("inbound_email_messages_entity_msg_uidx").on(e.entityId,e.gmailMessageId),ne("inbound_email_messages_entity_idx").on(e.entityId),ne("inbound_email_messages_conn_idx").on(e.connectionId),ne("inbound_email_messages_status_idx").on(e.entityId,e.processingStatus),ne("inbound_email_messages_thread_idx").on(e.entityId,e.gmailThreadId)]);t5("inbound_email_attachments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),messageId:tM("message_id").notNull().references(()=>oZ.id,{onDelete:"cascade"}),gmailAttachmentId:tT("gmail_attachment_id"),mimeType:tT("mime_type"),filename:tT("filename"),sha256:tT("sha256"),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),sizeBytes:eB("size_bytes"),contentId:tT("content_id"),isInline:ef("is_inline").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("inbound_email_attachments_message_idx").on(e.messageId),nt("inbound_email_attachments_msg_sha_uidx").on(e.messageId,e.sha256)]),t5("inbound_email_artifacts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),messageId:tM("message_id").notNull().references(()=>oZ.id,{onDelete:"cascade"}),artifactType:oY("artifact_type").notNull(),status:oX("status").notNull().default("PROPOSED"),targetTable:tT("target_table"),targetId:tM("target_id"),payload:eY("payload").$type(),createdByIdentityId:tM("created_by_identity_id"),lastError:tT("last_error"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inbound_email_artifacts_message_idx").on(e.messageId),ne("inbound_email_artifacts_entity_status_idx").on(e.entityId,e.status)]),t5("inbound_intake_patterns",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),senderDomain:tT("sender_domain"),subjectPrefix:tT("subject_prefix"),action:oW("action").notNull(),artifactType:oY("artifact_type"),matchCount:eB("match_count").notNull().default(1),lastUsedAt:tj("last_used_at").notNull().defaultNow(),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("inbound_intake_patterns_entity_idx").on(e.entityId),ne("inbound_intake_patterns_domain_idx").on(e.entityId,e.senderDomain)]),t5("inbound_intake_policies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),enabled:ef("enabled").notNull().default(!0),sharedMailboxPolicy:oJ("shared_mailbox_policy").notNull().default("triage"),personalMailboxPolicy:oJ("personal_mailbox_policy").notNull().default("auto"),requireCounterpartyForCrmTasks:ef("require_counterparty_for_crm_tasks").notNull().default(!0),skipUnknownPromotional:ef("skip_unknown_promotional").notNull().default(!0),autoFileProjectDocuments:ef("auto_file_project_documents").notNull().default(!0),allowedArtifactTypes:eY("allowed_artifact_types").$type().notNull().default(Y`'[]'::jsonb`),allowLlmStage:ef("allow_llm_stage").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("inbound_intake_policies_entity_uidx").on(e.entityId)]);let o0=L("phone_line_routing_mode",["forward_overlay","hosted","byoc"]),o1=L("phone_line_status",["provisioning","active","paused","error"]),o2=L("phone_call_direction",["inbou
1nd","outbound"]),o4=L("phone_call_status",["ringing","in_progress","completed","missed","failed","voicemail"]),o6=L("phone_call_disposition",["unassigned","intake_created","callback","spam","wrong_number","informational","other"]),o8=L("phone_call_intake_proposal_type",["work_order","service_job","route_stop"]),o5=L("phone_call_intake_proposal_status",["PROPOSED","CONFIRMED","DISMISSED"]),o3=t5("phone_lines",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),connectionId:tM("connection_id").notNull().references(()=>ap.id,{onDelete:"cascade"}),label:tT("label").notNull(),routingMode:o0("routing_mode").notNull().default("forward_overlay"),status:o1("status").notNull().default("provisioning"),publishedPhone:tT("published_phone"),publishedPhoneHmac:tT("published_phone_hmac"),twilioPhone:tT("twilio_phone"),twilioPhoneHmac:tT("twilio_phone_hmac"),twilioPhoneSid:tT("twilio_phone_sid"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),isPrimary:ef("is_primary").notNull().default(!1),ringTargets:eY("ring_targets").$type(),config:eY("config").$type(),lastError:tT("last_error"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("phone_lines_entity_idx").on(e.entityId),ne("phone_lines_connection_idx").on(e.connectionId),ne("phone_lines_entity_status_idx").on(e.entityId,e.status),ne("phone_lines_twilio_hmac_idx").on(e.entityId,e.twilioPhoneHmac),nt("phone_lines_entity_primary_uidx").on(e.entityId).where(Y`${e.isPrimary} = true`)]),o9=t5("phone_call_sessions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),lineId:tM("line_id").references(()=>o3.id,{onDelete:"set null"}),connectionId:tM("connection_id").references(()=>ap.id,{onDelete:"set null"}),direction:o2("direction").notNull(),twilioCallSid:tT("twilio_call_sid").notNull(),twilioParentCallSid:tT("twilio_parent_call_sid"),status:o4("status").notNull().default("ringing"),disposition:o6("disposition").notNull().default("unassigned"),callerPhone:tT("caller_phone"),callerPhoneHmac:tT("caller_phone_hmac"),calledPhone:tT("called_phone"),calledPhoneHmac:tT("called_phone_hmac"),matchedCounterpartyId:tM("matched_counterparty_id").references(()=>dn.id,{onDelete:"set null"}),matchedContactId:tM("matched_contact_id").references(()=>la.id,{onDelete:"set null"}),matchedPartyPhoneId:tM("matched_party_phone_id").references(()=>lr.id,{onDelete:"set null"}),answeredByIdentityId:tM("answered_by_identity_id"),handledByIdentityId:tM("handled_by_identity_id"),startedAt:tj("started_at").notNull().defaultNow(),answeredAt:tj("answered_at"),endedAt:tj("ended_at"),durationSeconds:eB("duration_seconds"),notes:tT("notes"),recordingUrl:tT("recording_url"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("phone_call_sessions_entity_sid_uidx").on(e.entityId,e.twilioCallSid),ne("phone_call_sessions_entity_idx").on(e.entityId),ne("phone_call_sessions_line_idx").on(e.lineId),ne("phone_call_sessions_entity_status_idx").on(e.entityId,e.status),ne("phone_call_sessions_caller_hmac_idx").on(e.entityId,e.callerPhoneHmac),ne("phone_call_sessions_counterparty_idx").on(e.matchedCounterpartyId),ne("phone_call_sessions_started_idx").on(e.entityId,e.startedAt)]);t5("phone_call_intake_proposals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),callSessionId:tM("call_session_id").notNull().references(()=>o9.id,{onDelete:"cascade"}),proposalType:o8("proposal_type").notNull(),status:o5("status").notNull().default("PROPOSED"),targetTable:tT("target_table"),targetId:tM("target_id"),payload:eY("payload").$type(),createdByIdentityId:tM("created_by_identity_id"),confirmedByIdentityId:tM("confirmed_by_identity_id"),lastError:tT("last_error"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("phone_call_intake_proposals_call_idx").on(e.callSessionId),ne("phone_call_intake_proposals_entity_status_idx").on(e.entityId,e.status)]);let o7=t5("crm_email_threads",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),connectionId:tM("connection_id").notNull().references(()=>ap.id,{onDelete:"cascade"}),gmailThreadId:tT("gmail_thread_id").notNull(),companyId:tM("company_id").references(()=>i7.id,{onDelete:"set null"}),leadId:tM("lead_id").references(()=>oi.id,{onDelete:"set null"}),contactId:tM("contact_id").references(()=>la.id,{onDelete:"set null"}),subjectPreview:tT("subject_preview"),lastMessageAt:tj("last_message_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("crm_email_threads_entity_thread_uidx").on(e.entityId,e.gmailThreadId),ne("crm_email_threads_company_idx").on(e.entityId,e.companyId)]);t5("crm_email_messages",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),threadId:tM("thread_id").notNull().references(()=>o7.id,{onDelete:"cascade"}),inboundMessageId:tM("inbound_message_id").references(()=>oZ.id,{onDelete:"set null"}),gmailMessageId:tT("gmail_message_id").notNull(),rfcMessageId:tT("rfc_message_id"),internalDate:er("internal_date",{mode:"number"}).notNull(),fromEmailHmac:tT("from_email_hmac"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("crm_email_messages_entity_gmail_uidx").on(e.entityId,e.gmailMessageId),ne("crm_email_messages_thread_idx").on(e.threadId)]),t5("personal_tasks",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),title:tT("title").notNull(),notes:tT("notes"),dueDate:eS("due_date"),dueTime:tT("due_time"),location:tT("location"),status:oz("status").notNull().default("PROPOSED"),sourceDocumentId:tM("source_document_id").references(()=>a9.id,{onDelete:"set null"}),sourceInboundMessageId:tM("source_inbound_message_id").references(()=>oZ.id,{onDelete:"set null"}),sourceStagedTransactionId:tM("source_staged_transaction_id").references(()=>n4.id,{onDelete:"set null"}),citationJson:eY("citation_json").$type(),confirmedAt:tj("confirmed_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("personal_tasks_entity_idx").on(e.entityId),ne("personal_tasks_status_idx").on(e.entityId,e.status),ne("personal_tasks_due_idx").on(e.entityId,e.dueDate)]);let le=L("contact_verification_status",["unverified","resolved","confirmed"]),lt=L("contact_kind",["PERSON","BUSINESS"]),ln=L("contact_status",["active","archived"]),ld=L("contact_source",["manual","platform_resolved","imported"]),la=t5("contacts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),kind:lt("kind").notNull().default("PERSON"),status:ln("status").notNull().default("active"),verificationStatus:le("verification_status").notNull().default("unverified"),source:ld("source").notNull().default("manual"),displayName:tT("display_name"),resolvedIdentityId:tM("resolved_identity_id"),metadata:eY("metadata").$type(),lastUsedAt:tj("last_used_at"),lastVerifiedAt:tj("last_verified_at"),partyId:tM("party_id").references(()=>sg.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("contacts_entity_idx").on(e.entityId),ne("contacts_entity_status_idx").on(e.entityId,e.status),ne("contacts_resolved_identity_idx").on(e.resolvedIdentityId),ne("contacts_party_idx").on(e.partyId)]),li=L("party_address_kind",["hq","registered","branch","mailing","billing","shipping","service"]),lo=t5("party_addresses",{id:tM("id").primaryKey().defaultRandom(),addressKey:tM("address_key").notNull(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"cascade"}),validFrom:tj("valid_from").notNull().defaultNow(),validUntil:tj("valid_until"),supersededBy:tM("superseded_by"),tombstonedAt:tj("tombstoned_at"),kind:li("kind").notNull(),usedFor:eY("used_for").$type().notNull().default([]),isPrimaryForKind:ef("is_primary_for_kind").notNull().default(!1),label:tT("label"),contactId:tM("contact_id").references(()=>la.id),addressLine1:tT("address_line1"),addressLine2:tT("address_line2"),city:tT("city"),region:tT("region"),postalCode:tT("postal_code"),country:tT("country"),phone:tT("phone"),latitude:td("latitude",{precision:10,scale:7}),longitude:td("longitude",{precision:10,scale:7}),addressHmac:tT("address_hmac"),source:tT("source"),sourceUrl:tT("source_url"),verifiedAt:tj("verified_at"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("party_addresses_entity_idx").on(e.entityId),ne("party_addresses_counterparty_idx").on(e.counterpartyId),ne("party_addresses_entity_self_idx").on(e.entityId).where(Y`counterparty_id IS NULL`),ne("party_addresses_address_key_idx").on(e.addressKey),ne("party_addresses_current_idx").on(e.entityId,e.counterpartyId,e.kind).where(Y`valid_until IS NULL`),nt("party_addresses_unique_primary_idx").on(e.entityId,e.counterpartyId,e.kind).where(Y`is_primary_for_kind AND valid_until IS NULL AND kind <> 'branch'`),ne("party_addresses_address_hmac_idx").on(e.entityId,e.addressHmac).where(Y`valid_until IS NULL`),ne("party_addresses_entity_site_idx").on(e.entityId,e.siteId)]),ll=L("party_phone_kind",["main","billing","ar","ap","sales","supp
1ort","fax","mobile","toll_free","other"]),lr=t5("party_phones",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"cascade"}),kind:ll("kind").notNull(),label:tT("label"),phone:tT("phone").notNull(),extension:tT("extension"),phoneHmac:tT("phone_hmac").notNull(),isPrimaryForKind:ef("is_primary_for_kind").notNull().default(!1),usedFor:eY("used_for").$type().notNull().default([]),source:tT("source").notNull().default("manual"),sourceUrl:tT("source_url"),notes:tT("notes"),verifiedAt:tj("verified_at"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("party_phones_entity_idx").on(e.entityId),ne("party_phones_counterparty_idx").on(e.counterpartyId),ne("party_phones_entity_self_idx").on(e.entityId).where(Y`counterparty_id IS NULL`),ne("party_phones_party_kind_idx").on(e.entityId,e.counterpartyId,e.kind),ne("party_phones_hmac_idx").on(e.entityId,e.phoneHmac),nt("party_phones_unique_primary_idx").on(e.entityId,e.counterpartyId,e.kind).where(Y`is_primary_for_kind`),ne("party_phones_entity_site_idx").on(e.entityId,e.siteId)]),ls=L("party_email_kind",["main","personal","work","billing","ar","ap","sales","support","marketing","other"]);t5("party_emails",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").references(()=>dn.id,{onDelete:"cascade"}),legalPartyId:tM("legal_party_id").references(()=>sg.id,{onDelete:"cascade"}),kind:ls("kind").notNull(),label:tT("label"),email:tT("email").notNull(),emailHmac:tT("email_hmac").notNull(),isPrimaryForKind:ef("is_primary_for_kind").notNull().default(!1),doNotEmail:ef("do_not_email").notNull().default(!1),usedFor:eY("used_for").$type().notNull().default([]),source:tT("source").notNull().default("manual"),sourceUrl:tT("source_url"),notes:tT("notes"),verifiedAt:tj("verified_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("party_emails_entity_idx").on(e.entityId),ne("party_emails_counterparty_idx").on(e.counterpartyId),ne("party_emails_legal_party_idx").on(e.legalPartyId),ne("party_emails_entity_self_idx").on(e.entityId).where(Y`counterparty_id IS NULL AND legal_party_id IS NULL`),ne("party_emails_party_kind_idx").on(e.entityId,e.counterpartyId,e.kind),ne("party_emails_entity_legal_party_kind_idx").on(e.entityId,e.legalPartyId,e.kind),ne("party_emails_hmac_idx").on(e.entityId,e.emailHmac),ne("party_emails_legal_party_hmac_idx").on(e.entityId,e.emailHmac).where(Y`legal_party_id IS NOT NULL`),nt("party_emails_unique_primary_idx").on(e.entityId,e.counterpartyId,e.kind).where(Y`is_primary_for_kind AND counterparty_id IS NOT NULL`),nt("party_emails_legal_party_kind_primary_idx").on(e.entityId,e.legalPartyId,e.kind).where(Y`is_primary_for_kind AND legal_party_id IS NOT NULL`)]);let l_=L("counterparty_relationship_type",["renamed_to","acquired_by","merged_into","divested_to","dba_of","subsidiary_of","rollup_to"]),lu=L("counterparty_relationship_source",["manual","website","cortex","public_record"]),lc=t5("counterparty_relationships",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),sourceCounterpartyId:tM("source_counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),targetCounterpartyId:tM("target_counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),relationshipType:l_("relationship_type").notNull(),effectiveFrom:eS("effective_from"),effectiveUntil:eS("effective_until"),ownershipPercentage:td("ownership_percentage",{precision:5,scale:2}),redirectBilling:ef("redirect_billing").notNull().default(!1),source:lu("source").notNull().default("manual"),sourceUrl:tT("source_url"),evidence:tT("evidence"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("counterparty_relationships_entity_idx").on(e.entityId),ne("counterparty_relationships_source_idx").on(e.entityId,e.sourceCounterpartyId,e.effectiveFrom),ne("counterparty_relationships_target_idx").on(e.entityId,e.targetCounterpartyId,e.effectiveFrom),ne("counterparty_relationships_current_idx").on(e.entityId,e.sourceCounterpartyId).where(Y`effective_until IS NULL`),nt("counterparty_relationships_unique_active_idx").on(e.entityId,e.sourceCounterpartyId,e.targetCounterpartyId,e.relationshipType,Y`COALESCE(${e.effectiveFrom}, DATE '0001-01-01')`).where(Y`effective_until IS NULL`)]),lp=L("document_redirect_decision_type",["invoice","bill","purchase_order","sales_order","quote"]);t5("document_redirect_decisions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),documentType:lp("document_type").notNull(),documentId:tM("document_id").notNull(),originalCounterpartyId:tM("original_counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),suggestedCounterpartyId:tM("suggested_counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),pickedCounterpartyId:tM("picked_counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),overridden:ef("overridden").notNull(),relationshipType:tT("relationship_type"),effectiveFrom:eS("effective_from"),decidedAt:tj("decided_at").notNull().defaultNow(),decidedBy:tM("decided_by")},e=>[ne("document_redirect_decisions_entity_idx").on(e.entityId),nt("document_redirect_decisions_doc_idx").on(e.entityId,e.documentType,e.documentId),ne("document_redirect_decisions_decided_at_idx").on(e.entityId,e.decidedAt),ne("document_redirect_decisions_overridden_idx").on(e.entityId).where(Y`overridden = true`)]);let ly=L("counterparty_lifecycle_event_type",["inactive","defunct","bankrupt_ch11","bankrupt_ch7","dissolved","reactivated","emerged"]),lm=L("counterparty_lifecycle_source",["manual","cortex","public_record","edgar"]),lf=t5("counterparty_lifecycle_events",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),counterpartyId:tM("counterparty_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),eventType:ly("event_type").notNull(),effectiveFrom:eS("effective_from"),effectiveUntil:eS("effective_until"),source:lm
1("source").notNull().default("manual"),sourceUrl:tT("source_url"),notes:tT("notes"),linkedRelationshipId:tM("linked_relationship_id").references(()=>lc.id,{onDelete:"set null"}),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("counterparty_lifecycle_entity_idx").on(e.entityId),ne("counterparty_lifecycle_counterparty_idx").on(e.entityId,e.counterpartyId,e.effectiveFrom),nt("counterparty_lifecycle_one_active_per_party_idx").on(e.entityId,e.counterpartyId).where(Y`effective_until IS NULL`)]),lN=L("counterparty_lifecycle_writeoff_draft_kind",["writeoff_ar","reserve_ar","escheat_ap","writeoff_ap"]);t5("counterparty_lifecycle_writeoff_drafts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),lifecycleEventId:tM("lifecycle_event_id").notNull().references(()=>lf.id,{onDelete:"cascade"}),journalEntryId:tM("journal_entry_id").notNull().references(()=>nV.id,{onDelete:"cascade"}),draftKind:lN("draft_kind").notNull(),sourceDocId:tM("source_doc_id").notNull(),amount:tT("amount").notNull(),currency:tT("currency").notNull(),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("lifecycle_writeoff_drafts_entity_idx").on(e.entityId),ne("lifecycle_writeoff_drafts_event_idx").on(e.entityId,e.lifecycleEventId),ne("lifecycle_writeoff_drafts_je_idx").on(e.journalEntryId),ne("lifecycle_writeoff_drafts_doc_idx").on(e.sourceDocId),nt("lifecycle_writeoff_drafts_event_doc_kind_idx").on(e.lifecycleEventId,e.sourceDocId,e.draftKind)]);let lI=L("succession_scan_mode",["website","public_record","both"]),lg=L("succession_scan_detector",["website","public_record"]),lb=L("succession_scan_run_status",["queued","running","completed","cancelled"]),lh=L("succession_scan_job_status",["queued","running","succeeded","failed","dead_letter"]),lv=t5("succession_scan_runs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),mode:lI("mode").notNull(),filters:eY("filters").notNull().default({}),status:lb("status").notNull().default("queued"),totalJobs:eB("total_jobs").notNull().default(0),completedJobs:eB("completed_jobs").notNull().default(0),failedJobs:eB("failed_jobs").notNull().default(0),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),startedAt:tj("started_at"),finishedAt:tj("finished_at")},e=>[ne("succession_scan_runs_entity_idx").on(e.entityId,e.createdAt),ne("succession_scan_runs_status_idx").on(e.entityId,e.status)]);t5("succession_scan_jobs",{id:tM("id").primaryKey().defaultRandom(),runId:tM("run_id").notNull().references(()=>lv.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),companyId:tM("company_id").notNull().references(()=>i7.id,{onDelete:"cascade"}),detector:lg("detector").notNull(),status:lh("status").notNull().default("queued"),attempt:eB("attempt").notNull().default(0),lastError:tT("last_error"),result:tT("result"),createdAt:tj("created_at").notNull().defaultNow(),startedAt:tj("started_at"),finishedAt:tj("finished_at")},e=>[ne("succession_scan_jobs_run_idx").on(e.runId),ne("succession_scan_jobs_entity_status_idx").on(e.entityId,e.status),nt("succession_scan_jobs_run_company_detector_idx").on(e.runId,e.companyId,e.detector)]),t5("counterparty_merge_audit",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),canonicalCounterpartyId:tM("canonical_counterparty_id").notNull(),mergedCounterpartyId:tM("merged_counterparty_id").notNull(),canonicalCompanyId:tM("canonical_company_id"),mergedCompanyId:tM("merged_company_id"),mergedCounterpartyName:tT("merged_counterparty_name"),mergedRowSnapshot:tT("merged_row_snapshot"),affectedFkSummary:eY("affected_fk_summary").notNull().default({}),dryRun:ef("dry_run").notNull().default(!1),mergedAt:tj("merged_at").notNull().defaultNow(),mergedBy:tM("merged_by")},e=>[ne("counterparty_merge_audit_entity_idx").on(e.entityId,e.mergedAt),ne("counterparty_merge_audit_canonical_idx").on(e.entityId,e.canonicalCounterpartyId),ne("counterparty_merge_audit_canonical_company_idx").on(e.entityId,e.canonicalCompanyId,e.mergedAt)]),t5("legal_party_merge_audit",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),canonicalPartyId:tM("canonical_party_id").notNull(),mergedPartyId:tM("merged_party_id").notNull(),mergedPartyName:tT("merged_party_name"),mergedRowSnapshot:tT("merged_row_snapshot"),affectedFkSummary:eY("affected_fk_summary").notNull().default({}),dryRun:ef("dry_run").notNull().default(!1),mergedAt:tj("merged_at").notNull().defaultNow(),mergedBy:tM("merged_by")},e=>[ne("legal_party_merge_audit_entity_idx").on(e.entityId,e.mergedAt),ne("legal_party_merge_audit_canonical_idx").on(e.entityId,e.canonicalPartyId)]);let lx=L("contact_wallet_verification_status",["unverified","verified"]),lA=t5("contact_wallets",{id:tM("id").primaryKey().defaultRandom(),contactId:tM("contact_id").notNull().references(()=>la.id,{onDelete:"cascade"}),walletAddress:tT("wallet_address").notNull(),stealthMetaAddress:tT("stealth_meta_address"),addressHmac:tT("address_hmac"),label:tT("label"),isPrimary:ef("is_primary").notNull().default(!0),verificationStatus:lx("wallet_verification_status").notNull().default("unverified"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("contact_wallets_contact_idx").on(e.contactId),nt("contact_wallets_contact_address_hmac_idx").on(e.contactId,e.addressHmac)]),lD=L("contact_bank_verification_status",["unverified","verified"]),lw=t5("contact_bank_accounts",{id:tM("id").primaryKey().defaultRandom(),contactId:tM("contact_id").notNull().references(()=>la.id,{onDelete:"cascade"}),bridgeExternalAccountId:tT("bridge_external_account_id"),bankRoutingNumber:tT("bank_routing_number"),bankAccountNumber:tT("bank_account_number"),bankAccountType:tT("bank_account_type"),bankAccountNonce:tT("bank_account_nonce"),bankAccountHmac:tT("bank_account_hmac"),label:tT("label"),isPrimary:ef("is_primary").notNull().default(!0),verificationStatus:lD("bank_verification_status").notNull().default("unverified"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("contact_bank_accounts_contact_idx").on(e.contactId),nt("contact_bank_accounts_contact_hmac_idx").on(e.contactId,e.bankAccountHmac),ne("contact_bank_accounts_hmac_idx").on(e.bankAccountHmac)]),lE=L("contact_invite_status",["sent","claimed","expired"]);t5("contact_invites",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),type:tT("type").notNull(),identifierHmac:tT("identifier_hmac").notNull(),token:tT("token").notNull().unique(),amount:td("amount",{precision:20,scale:8}),currency:tT("currency"),intent:tT("intent"),memo:tT("memo"),status:lE("status").notNull().default("sent"),claimedBy:tM("claimed_by"),expiresAt:tj("expires_at").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("contact_invite_entity_idx").on(e.entityId),ne("contact_invite_token_idx").on(e.token),ne("contact_invite_hmac_idx").on(e.entityId,e.identifierHmac)]),t5("resolve_audit_log",{id:tM("id").primaryKey().defaultRandom(),sessionId:tT("session_id").notNull(),identifierType:tT("identifier_type").notNull(),found:ef("found").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("resolve_audit_session_idx").on(e.sessionId),ne("resolve_audit_created_idx").on(e.createdAt)]);let lR=L("scheduled_payment_frequency",["ONE_TIME","WEEKLY","BIWEEKLY","MONTHLY","QUARTERLY"]),lk=L("scheduled_payment_status",["ACTIVE","PAUSED","COMPLETED","FAILED"]),lT=t5("scheduled_payments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),contactId:tM("contact_id").notNull().references(()=>la.id),contactWalletId:tM("contact_wallet_id").references(()=>lA.id),contactBankAccountId:tM("contact_bank_account_id").references(()=>lw.id),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USDC"),intent:tT("intent").notNull(),memo:tT("memo"),frequency:lR("frequency").notNull(),nextDueDate:eS("next_due_date").notNull(),lastExecutedAt:tj("last_executed_at"),dayOfMonth:eB("day_of_month"),dayOfWeek:eB("day_of_week"),totalExecuted:eB("total_executed").notNull().default(0),maxExecutions:eB("max_executions"),status:lk("status").notNull().default("ACTIVE"),sessionKeyId:tT("session_key_id"),autoSwapFromEth:ef("auto_swap_from_eth").notNull().default(!1),relatedBillId:tM("related_bill_id"),relatedInvoiceId:tM("related_invoice_id"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("sched_pay_entity_idx").on(e.entityId),ne("sched_pay_next_due_idx").on(e.nextDueDate),ne("sched_pay_status_idx").on(e.status)]),lS=L("scheduled_payment_execution_status",["SUCCESS","FAILED","PENDING"]);t5("scheduled_payment_executions",{id:tM("id").primaryKey().defaultRandom(),scheduledPaymentId:tM("scheduled_payment_id").notNull().references(()=>lT.id),executedAt:tj("executed_at").notNull().defaultNow(),amount:tT("amount").notNull(),status:lS("status").notNull(),txHash:tT("tx_hash"),bridgeTransferId:tT("bridge_transfer_id"),stagedTransactionId:tM("staged_transaction_id").references(()=>n4.id),errorMessage:tT("error_message"),createdAt:tj("created_at").notNull().defaultNow()},e=>
1[ne("sched_exec_payment_idx").on(e.scheduledPaymentId)]);let lC=t5("wallet_identities",{id:tM("id").primaryKey().defaultRandom(),credentialId:tT("credential_id").notNull().unique(),publicKey:tT("public_key").notNull(),displayName:tT("display_name").notNull(),email:tT("email"),emailVerifiedAt:tj("email_verified_at"),avatarUrl:tT("avatar_url"),counter:eB("counter").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("wi_credential_idx").on(e.credentialId)]);t5("email_verifications",{id:tM("id").primaryKey().defaultRandom(),identityId:tM("identity_id").notNull(),entityId:tM("entity_id"),email:tT("email").notNull(),codeHash:tT("code_hash").notNull(),expiresAt:tj("expires_at").notNull(),attempts:eB("attempts").notNull().default(0),verified:ef("verified").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ev_identity_idx").on(e.identityId),ne("ev_entity_idx").on(e.entityId),ne("ev_email_idx").on(e.email)]);let lP=L("wallet_status",["ACTIVE","FROZEN","CLOSED"]),lO=L("wallet_type",["TREASURY_PRIMARY","TREASURY_CHILD","MEMBER"]),lK=t5("wallets",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),address:tT("address").notNull().unique(),label:tT("label").notNull(),walletType:lO("wallet_type").notNull().default("MEMBER"),parentWalletId:tM("parent_wallet_id"),chainId:eB("chain_id").notNull().default(84532),status:lP("status").notNull().default("ACTIVE"),ownerPubkey:tT("owner_pubkey"),deployedAt:tj("deployed_at"),autoShieldEnabled:ef("auto_shield_enabled").notNull().default(!0),autoShieldMinUsdc:tT("auto_shield_min_usdc").notNull().default("0.10"),autoShieldMinEth:tT("auto_shield_min_eth").notNull().default("0.001"),autoShieldDailyLimitUsdc:tT("auto_shield_daily_limit_usdc"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("wallet_entity_idx").on(e.entityId),ne("wallet_parent_idx").on(e.parentWalletId),ne("wallet_type_idx").on(e.walletType),nt("wallet_address_idx").on(e.address)]),lL=L("confidential_event_type",["NOTE_CREATED","NOTE_NULLIFIED","PRIVATE_CONTRACT_CALL"]);t5("confidential_events",{id:tT("id").primaryKey(),eventType:lL("event_type").notNull(),txHash:tT("tx_hash").notNull(),blockNumber:er("block_number",{mode:"bigint"}).notNull(),blockTimestamp:er("block_timestamp",{mode:"bigint"}),logIndex:eB("log_index").notNull(),contractAddress:tT("contract_address").notNull(),commitment:tT("commitment"),leafIndex:er("leaf_index",{mode:"bigint"}),scanTag:tT("scan_tag"),ephemeralPubKey:tT("ephemeral_pub_key"),encryptedNote:tT("encrypted_note"),nullifierHash:tT("nullifier_hash"),targetContract:tT("target_contract"),inputToken:tT("input_token"),outputToken:tT("output_token"),chainId:eB("chain_id").notNull().default(84532),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ce_tx_hash_idx").on(e.txHash),ne("ce_block_number_idx").on(e.blockNumber),ne("ce_event_type_idx").on(e.eventType),ne("ce_commitment_idx").on(e.commitment),ne("ce_nullifier_hash_idx").on(e.nullifierHash),ne("ce_scan_tag_idx").on(e.scanTag)]);let lq=L("wallet_member_role",["OWNER","ADMIN","MEMBER","VIEWER"]);t5("wallet_members",{id:tM("id").primaryKey().defaultRandom(),walletId:tM("wallet_id").notNull().references(()=>lK.id),identityId:tM("identity_id").notNull().references(()=>lC.id),role:lq("role").notNull().default("MEMBER"),spendingLimit:tT("spending_limit"),spendingLimitPeriod:tT("spending_limit_period"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("wm_wallet_idx").on(e.walletId),ne("wm_identity_idx").on(e.identityId),nt("wm_wallet_identity_idx").on(e.walletId,e.identityId)]);let lj=L("wallet_edge_type",["TREASURY_TO_TREASURY","TREASURY_TO_MEMBER"]);t5("wallet_hierarchy_edges",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),parentWalletId:tM("parent_wallet_id").notNull().references(()=>lK.id),childWalletId:tM("child_wallet_id").notNull().references(()=>lK.id),edgeType:lj("edge_type").notNull(),isActive:ef("is_active").notNull().default(!0),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("wallet_edge_parent_child_unique_idx").on(e.parentWalletId,e.childWalletId),ne("wallet_edge_entity_idx").on(e.entityId),ne("wallet_edge_child_idx").on(e.childWalletId),ne("wallet_edge_active_idx").on(e.isActive)]),t5("wallet_delegation_policies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),parentWalletId:tM("parent_wallet_id").notNull().references(()=>lK.id),childWalletId:tM("child_wallet_id").notNull().references(()=>lK.id),perTxLimit:tT("per_tx_limit"),dailyLimit:tT("daily_limit"),monthlyLimit:tT("monthly_limit"),allowedCategories:eY("allowed_categories").$type(),metadata:eY("metadata").$type(),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("wallet_policy_parent_child_unique_idx").on(e.parentWalletId,e.childWalletId),ne("wallet_policy_entity_idx").on(e.entityId),ne("wallet_policy_child_idx").on(e.childWalletId),ne("wallet_policy_active_idx").on(e.isActive)]);let lU=L("webhook_inbox_status",["RECEIVED","PROCESSING","PROCESSED","FAILED"]);t5("webhook_inbox",{id:tM("id").primaryKey().defaultRandom(),source:tT("source").notNull(),eventKey:tT("event_key").notNull(),eventType:tT("event_type").notNull(),tenantId:tM("tenant_id"),entity
1Id:tM("entity_id"),payload:eY("payload").notNull(),status:lU("status").notNull().default("RECEIVED"),attempts:eB("attempts").notNull().default(0),nextAttemptAt:tj("next_attempt_at"),lastError:tT("last_error"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow(),processedAt:tj("processed_at")},e=>[nt("webhook_inbox_source_event_unique_idx").on(e.source,e.eventKey),ne("webhook_inbox_status_next_idx").on(e.status,e.nextAttemptAt),ne("webhook_inbox_type_idx").on(e.eventType),ne("webhook_inbox_entity_idx").on(e.entityId)]);let lB=L("trust_line_status",["PENDING","ACTIVE","SUSPENDED","CLOSED"]),lM=L("settlement_intent_status",["DRAFT","SUBMITTED","ROUTING","PROVING","SETTLED","FAILED"]),lF=t5("trust_lines",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),creditorWalletId:tM("creditor_wallet_id").notNull().references(()=>lK.id),debtorWalletId:tM("debtor_wallet_id").notNull().references(()=>lK.id),creditLimit:tT("credit_limit").notNull(),currentBalance:tT("current_balance").notNull().default("0"),currency:tT("currency").notNull().default("USD"),status:lB("status").notNull().default("PENDING"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("trust_line_creditor_debtor_idx").on(e.creditorWalletId,e.debtorWalletId),ne("trust_line_entity_idx").on(e.entityId),ne("trust_line_status_idx").on(e.status)]);t5("settlement_intents",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),trustLineId:tM("trust_line_id").notNull().references(()=>lF.id),amount:tT("amount").notNull(),currency:tT("currency").notNull().default("USD"),direction:tT("direction").notNull(),status:lM("status").notNull().default("DRAFT"),routePath:eY("route_path").$type(),proofCommitment:tT("proof_commitment"),proofNullifier:tT("proof_nullifier"),proofVerifiedAt:tj("proof_verified_at"),settledAt:tj("settled_at"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("settlement_intent_entity_idx").on(e.entityId),ne("settlement_intent_trust_line_idx").on(e.trustLineId),ne("settlement_intent_status_idx").on(e.status)]);let lV=L("billing_cycle_state",["OPEN","AUTH_PENDING","SETTLEMENT_PENDING","SETTLED","CLOSED"]);t5("billing_cycles",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),walletId:tM("wallet_id").notNull().references(()=>lK.id),cycleLabel:tT("cycle_label").notNull(),state:lV("state").notNull().default("OPEN"),openedAt:tj("opened_at").notNull().defaultNow(),closedAt:tj("closed_at"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("billing_cycle_entity_idx").on(e.entityId),ne("billing_cycle_wallet_idx").on(e.walletId),ne("billing_cycle_state_idx").on(e.state),nt("billing_cycle_wallet_label_unique_idx").on(e.walletId,e.cycleLabel)]);let lH=L("funding_account_status",["pending","active","suspended"]),l$=t5("funding_accounts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),bridgeCustomerId:tT("bridge_customer_id").notNull(),currency:tT("currency").notNull(),externalAccountId:tT("external_account_id"),virtualAccountId:tT("virtual_account_id"),virtualAccountDetails:eY("virtual_account_details"),liquidationAddress:tT("liquidation_address"),liquidationAddressId:tT("liquidation_address_id"),status:lH("status").notNull().default("pending"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fa_entity_idx").on(e.entityId),ne("fa_bridge_customer_idx").on(e.bridgeCustomerId),nt("fa_entity_currency_idx").on(e.entityId,e.currency)]),lG=L("treasury_bridge_transfer_status",["pending","settled","failed"]);t5("treasury_bridge_transfers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),bridgeTransferId:tT("bridge_transfer_id"),bridgeEventId:tT("bridge_event_id"),direction:tT("direction").notNull(),rampKind:tT("ramp_kind").notNull(),status:lG("status").notNull().default("pending"),grossAmount:tT("gross_amount").notNull(),netAmount:tT("net_amount"),bridgeFeeUsd:tT("bridge_fee_usd"),gasFeeUsd:tT("gas_fee_usd"),ledgerEventIdInitiated:tM("ledger_event_id_initiated"),ledgerEventIdSettled:tM("ledger_event_id_settled"),fundingAccountId:tM("funding_account_id").references(()=>l$.id),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("tbt_entity_idx").on(e.entityId),ne("tbt_bridge_transfer_idx").on(e.bridgeTransferId),nt("tbt_bridge_transfer_unique").on(e.bridgeTransferId)]);let lz=L("auto_shield_job_status",["queued","running","succeeded","failed","dead_letter"]);t5("auto_shield_jobs",{id:tM("id").primaryKey().defaultRandom(),walletAddress:tT("wallet_address").notNull(),token:tT("token").notNull(),amountRaw:tT("amount_raw").notNull(),status:lz("status").notNull().default("queued"),attempts:eB("attempts").notNull().default(0),idempotencyKey:tT("idempotency_key").notNull().unique(),triggerSource:tT("trigger_source").notNull(),chainId:eB("chain_id").notNull().default(84532),gasPaymentMethod:tT("gas_payment_method"),txHash:tT("tx_hash"),errorMessage:tT("error_message"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow(),completedAt:tj("completed_at")},e=>[ne("asj_status_idx").on(e.status),ne("asj_wallet_idx").on(e.walletAddress),nt("asj_idempotency_key_idx").on(e.idempotencyKey)]);let lQ=L("expense_report_status",["draft","submitted","under_review","approved","rejected","reimbursed","cancelled"]),lY=L("reimbursement_method",["payroll","bank_transfer","cash","corporate_card"]),lW=L("expense_report_payee_kind",["employee","contractor","shareholder"]),lJ=t5("expense_categories",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),code:tT("code"),parentId:tM("parent_id"),glAccountId:tM("gl_account_id").references(()=>nU.id),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("expense_categories_entity_idx").on(e.entityId)]),lX=t5("expense_reports",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),reportNumber:tT("report_number").notNull(),employeeUserId:tM("employee_user_id").notNull(),title:tT("title").notNull(),status:lQ("status").notNull().default("draft"),currency:tT("currency").notNull().default("USD"),totalAmount:td("total_amount",{precision:20,scale:2}).notNull().default("0"),approvedAmount:td("approved_amount",{precision:20,scale:2}),submittedAt:tj("submitted_at"),approvedBy:tM("approved_by"),approvedAt:tj("approved_at"),rejectedReason:tT("rejected_reason"),reimbursedAt:tj("reimbursed_at"),reimbursementMethod:lY("reimbursement_method"),notes:tT("notes"),metadata:eY("metadata").$type(),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),payeeKind:lW("payee_kind"),payeePartyId:tM("payee_party_id").references(()=>sg.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("expense_reports_entity_idx").on(e.entityId),ne("expense_reports_employee_idx").on(e.employeeUserId),ne("expense_reports_status_idx").on(e.entityId,e.status),ne("expense_reports_site_idx").on(e.entityId,e.siteId),ne("expense_reports_payee_party_idx").on(e.payeePartyId)]);t5("expense_lines",{id:tM("id").primaryKey().defaultRandom(),reportId:tM("report_id").notNull().references(()=>lX.id,{onDelete:"cascade"}),entityId:tM("entity_id").references(()=>nP.id,{onDelete:"cascade"}),date:eS("date").notNull(),categoryId:tM("category_id").references(()=>lJ.id),description:tT("description").notNull(),amount:td("amount",{precision:20,scale:2}).notNull(),currency:tT("currency").notNull().default("USD"),exchangeRate:td("exchange_rate",{precision:12,scale:6}).notNull().default("1"),baseAmount:td("base_amount",{precision:20,scale:2}).notNull(),merchantName:tT("merchant_name"),vendorId:tM("vendor_id").references(()=>dn.id,{onDelete:"set null"}),vendorInvoiceNumber:tT("vendor_invoice_number"),receiptNumber:tT("receipt_number"),documentFingerprintHmac:tT("document_fingerprint_hmac"),receiptUrl:tT("receipt_url"),isBillable:ef("is_billable").notNull().default(!1),taxRateId:tM("tax_rate_id").references(()=>d3.id),taxAmount:td("tax_amount",{precision:20,scale:2}).notNull().default("0"),glAccountId:tM("gl_account_id").references(()=>nU.id),notes:tT("notes"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("expense_lines_report_idx").on(e.reportId),ne("expense_lines_entity_idx").on(e.entityId),ne("expense_lines_doc_fingerprint_idx").on(e.entityId,e.documentFingerprintHmac),ne("expense_lines_category_idx").on(e.categoryId),ne("expense_lines_site_idx").on(e.siteId),ne("expense_lines_vendor_idx").on(e.entityId,e.vendorId)]),t5("expense_merchant_vendor_aliases",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),merchantNameHmac:tT("merchant_name_hmac").notNull(),vendorId:tM("vendor_id").notNull().references(()=>dn.id,{onDelete:"cascade"}),createdByIdentityId:tM("created_by_identity_id"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("expense_merchant_vendor_aliases_entity_hmac_uidx").on(e.entityId,e.merchantNameHmac),ne("expense_merchant_vendor_aliases_vendor_idx").on(e.entityId,e.vendorId)]);let lZ=L("purchase_order_status",["draft","pending_approval","approved","sent","partially_received","received","billed","cancelled"]),l0=t5("purchase_orders",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),poNumber:tT("po_number").notNull(),vendorId:tM("vendor_id").notNull().references(()=>dn.id),status:lZ("status").notNull().default("draft"),currency:tT("currency").notNull().default("USD"),subtotal:td("subtotal",{precision:20,scale:2}).notNull().default("0"),taxAmount:td("tax_amount",{precision:20,scale:2}).notNull().default("0"),total:td("total",{precision:20,scale:2}).notNull().default("0"),shippingCost:td("shipping_cost",{precision:20,scale:2}).notNull().default("0"),notes:tT("notes"),requestedBy:tM("requested_by"),approvedBy:tM("approved_by"),approvedAt:tj("approved_at"),sentAt:tj("sent_at"),expectedDeliveryDate:eS("expected_delivery_date"),paymentTerms:tT("payment_terms"),metadata:eY("metadata").$type(),billToAddressId:tM("bill_to_address_id").references(()=>lo.id,{onDelete:"set null"}),shipToAddressId:tM("ship_to_address_id").references(()=>lo.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("po_entity_idx").on(e.entityId),ne("po_vendor_idx").on(e.vendorId),ne("po_status_idx").on(e.entityId,e.status),ne("po_bill_to_address_idx").on(e.b
1illToAddressId),ne("po_ship_to_address_idx").on(e.shipToAddressId),nt("po_number_entity_idx").on(e.entityId,e.poNumber)]),l1=t5("purchase_order_lines",{id:tM("id").primaryKey().defaultRandom(),poId:tM("po_id").notNull().references(()=>l0.id,{onDelete:"cascade"}),lineNumber:eB("line_number").notNull().default(1),itemId:tM("item_id").references(()=>oL.id),description:tT("description").notNull(),quantity:td("quantity",{precision:20,scale:4}).notNull(),unitPrice:td("unit_price",{precision:20,scale:4}).notNull(),amount:td("amount",{precision:20,scale:2}).notNull(),receivedQty:td("received_qty",{precision:20,scale:4}).notNull().default("0"),billedQty:td("billed_qty",{precision:20,scale:4}).notNull().default("0"),taxRateId:tM("tax_rate_id").references(()=>d3.id),taxAmount:td("tax_amount",{precision:20,scale:2}).notNull().default("0"),glAccountId:tM("gl_account_id").references(()=>nU.id),deliveryDate:eS("delivery_date")},e=>[ne("po_lines_po_idx").on(e.poId),ne("po_lines_item_idx").on(e.itemId)]);t5("po_send_log",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),poId:tM("po_id").notNull().references(()=>l0.id,{onDelete:"cascade"}),connectionId:tM("connection_id").references(()=>ap.id,{onDelete:"set null"}),channel:tT("channel").notNull(),toEmail:tT("to_email").notNull(),deliveryMemo:tT("delivery_memo"),providerMessageId:tT("provider_message_id"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("po_send_log_po_idx").on(e.poId),ne("po_send_log_entity_idx").on(e.entityId)]);let l2=L("sales_quote_status",["draft","sent","accepted","rejected","expired","revised"]),l4=L("revenue_order_status",["draft","confirmed","in_progress","closed","cancelled"]),l6=L("sales_line_kind",["goods","service","subscription","fee","discount","bundle"]),l8=L("sales_fulfillment_profile",["ship","pickup","digital_delivery","activate_subscription","milestone_service","none"]),l5=t5("sales_quotes",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),quoteNumber:tT("quote_number").notNull(),customerId:tM("customer_id").references(()=>dn.id),status:l2("status").notNull().default("draft"),title:tT("title"),currency:tT("currency").notNull().default("USD"),subtotal:td("subtotal",{precision:20,scale:4}).notNull().default("0"),discountAmount:td("discount_amount",{precision:20,scale:4}).notNull().default("0"),taxAmount:td("tax_amount",{precision:20,scale:4}).notNull().default("0"),total:td("total",{precision:20,scale:4}).notNull().default("0"),validUntil:eS("valid_until"),sentAt:tj("sent_at"),acceptedAt:tj("accepted_at"),terms:tT("terms"),notes:tT("notes"),salesRepId:tM("sales_rep_id"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("sales_quotes_entity_idx").on(e.entityId),ne("sales_quotes_customer_idx").on(e.customerId),ne("sales_quotes_status_idx").on(e.entityId,e.status),nt("sales_quotes_entity_number_idx").on(e.entityId,e.quoteNumber)]);t5("sales_quote_lines",{id:tM("id").primaryKey().defaultRandom(),quoteId:tM("quote_id").notNull().references(()=>l5.id,{onDelete:"cascade"}),lineNumber:eB("line_number").notNull(),itemId:tM("item_id").references(()=>oL.id),description:tT("description"),quantity:td("quantity",{precision:20,scale:4}).notNull().default("1"),unitPrice:td("unit_price",{precision:20,scale:4}).notNull().default("0"),discountPercent:td("discount_percent",{precision:5,scale:2}).notNull().default("0"),amount:td("amount",{precision:20,scale:4}).notNull().default("0"),sequence:eB("sequence").notNull().default(0),lineKind:l6("line_kind").notNull().default("service"),fulfillmentProfile:l8("fulfillment_profile").notNull().default("none"),sourcingMethod:nr("sourcing_method").notNull().default("none"),parentLineId:tM("parent_line_id"),subscriptionPlanId:tM("subscription_plan_id").references(()=>rB.id,{onDelete:"set null"})},e=>[ne("sales_quote_lines_quote_idx").on(e.quoteId),ne("sales_quote_lines_parent_idx").on(e.parentLineId),ne("sales_quote_lines_sourcing_idx").on(e.sourcingMethod)]);let l3=t5("sales_orders",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),orderNumber:tT("order_number").notNull(),customerId:tM("customer_id").references(()=>dn.id),quoteId:tM("quote_id").references(()=>l5.id),projectId:tM("project_id").references(()=>op.id,{onDelete:"set null"}),status:l4("status").notNull().default("draft"),currency:tT("currency").notNull().default("USD"),subtotal:td("subtotal",{precision:20,scale:4}).notNull().default("0"),discountAmount:td("discount_amount",{precision:20,scale:4}).notNull().default("0"),taxAmount:td("tax_amount",{precision:20,scale:4}).notNull().default("0"),shippingAmount:td("shipping_amount",{precision:20,scale:4}).notNull().default("0"),total:td("total",{precision:20,scale:4}).notNull().default("0"),orderDate:eS("order_date").notNull(),requestedDeliveryDate:eS("requested_delivery_date"),shippingAddress:tT("shipping_address"),billToAddressId:tM("bill_to_address_id").references(()=>lo.id,{onDelete:"set null"}),shipToAddressId:tM("ship_to_address_id").references(()=>lo.id,{onDelete:"set null"}),paymentTerms:tT("payment_terms"),salesRepId:tM("sales_rep_id"),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("sales_orders_entity_idx").on(e.entityId),ne("sales_orders_customer_idx").on(e.customerId),ne("sales_orders_status_idx").on(e.entityId,e.status),ne("sales_orders_project_idx").on(e.projectId),ne("sales_orders_bill_to_address_idx").on(e.billToAddressId),ne("sales_orders_ship_to_address_idx").on(e.shipToAddressId),nt("sales_orders_entity_number_idx").on(e.entityId,e.orderNumber)]),l9=t5("sales_order_lines",{id:tM("id").primaryKey().defaultRandom(),orderId:tM("order_id").notNull().references(()=>l3.id,{onDelete:"cascade"}),lineNumber:eB("line_number").notNull(),itemId:tM("item_id").references(()=>oL.id),description:tT("description"),quantity:td("quantity",{precision:20,scale:4}).notNull().default("1"),unitPrice:td("unit_price",{precision:20,scale:4}).notNull().default("0"),discountPercent:td("discount_percent",{precision:5,scale:2}).notNull().default("0"),amount:td("amount",{precision:20,scale:4}).notNull().default("0"),shippedQty:td("shipped_qty",{precision:20,scale:4}).notNull().default("0"),invoicedQty:td("invoiced_qty",{precision:20,scale:4}).notNull().default("0"),lineKind:l6("line_kind").notNull().default("service"),fulfillmentProfile:l8("fulfillment_profile").notNull().default("none"),sourcingMethod:nr("sourcing_method").notNull().default("none"),dropshipPoLineId:tM("dropship_po_line_id").references(()=>l1.id),dropshipCostSnapshot:tT("dropship_cost_snapshot"),parentLineId:tM("parent_line_id"),subscriptionPlanId:tM("subscription_plan_id").references(()=>rB.id,{onDelete:"set null"})},e=>[ne("sales_order_lines_order_idx").on(e.orderId),ne("sales_order_lines_parent_idx").on(e.parentLineId),ne("sales_order_lines_sourcing_idx").on(e.sourcingMethod),ne("sales_order_lines_dropship_po_idx").on(e.dropshipPoLineId)]),l7=L("doc_signing_order",["parallel","sequential"]),re=t5("doc_folders",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),parentId:tM("parent_id"),color:tT("color"),icon:tT("icon"),isDefault:ef("is_default").notNull().default(!1),listMode:eY("list_mode"),sortOrder:eB("sort_order"),deletedAt:tj("deleted_at"),deletedBy:tM("deleted_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("doc_folders_entity_idx").on(e.entityId),ne("doc_folders_parent_idx").on(e.parentId)]),rt=L("doc_folder_access",["view","edit"]);t5("doc_folder_grants",{id:tM("id").primaryKey().defaultRandom(),folderId:tM("folder_id").notNull().references(()=>re.id,{onDelete:"cascade"}),userId:tM("user_id"),legalPartyId:tM("legal_party_id").references(()=>sg.id,{onDelete:"cascade"}),access:rt("access").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("doc_folder_grants_folder_idx").on(e.folderId),nt("doc_folder_grants_folder_user_idx").on(e.folderId,e.userId),nt("doc_folder_grants_folder_legal_party_idx").on(e.folderId,e.legalPartyId)]);let rn=t5("doc_templates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),documentId:tM("document_id").notNull().references(()=>
1a9.id,{onDelete:"cascade"}),defaultSigners:eY("default_signers"),defaultSignatureFields:eY("default_signature_fields"),defaultMessage:tT("default_message"),defaultDueDays:eB("default_due_days"),category:tT("category"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("doc_templates_entity_idx").on(e.entityId),ne("doc_templates_document_idx").on(e.documentId)]),rd=L("doc_signature_request_status",["draft","pending","partially_signed","completed","declined","expired","cancelled"]),ra=L("doc_signer_status",["pending","viewed","signed","declined"]),ri=t5("doc_signature_requests",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),documentId:tM("document_id").notNull().references(()=>a9.id,{onDelete:"cascade"}),templateId:tM("template_id").references(()=>rn.id,{onDelete:"set null"}),title:tT("title").notNull(),message:tT("message"),status:rd("status").notNull().default("draft"),requestedBy:tM("requested_by"),dueDate:eS("due_date"),completedAt:tj("completed_at"),contentHash:tT("content_hash"),completedHash:tT("completed_hash"),completedDocumentId:tM("completed_document_id").references(()=>a9.id,{onDelete:"set null"}),completionCertificateDocumentId:tM("completion_certificate_document_id").references(()=>a9.id,{onDelete:"set null"}),reminderIntervalDays:eB("reminder_interval_days").notNull().default(3),lastReminderAt:tj("last_reminder_at"),expiresAt:tj("expires_at"),signingOrder:l7("signing_order").notNull().default("parallel"),ccEmails:eY("cc_emails"),purpose:tT("purpose"),consumerRowId:tM("consumer_row_id"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("doc_sig_requests_entity_idx").on(e.entityId),ne("doc_sig_requests_document_idx").on(e.documentId),ne("doc_sig_requests_template_idx").on(e.templateId),ne("doc_sig_requests_purpose_idx").on(e.entityId,e.purpose),ne("doc_sig_requests_consumer_row_idx").on(e.purpose,e.consumerRowId)]),ro=t5("doc_signature_request_signers",{id:tM("id").primaryKey().defaultRandom(),requestId:tM("request_id").notNull().references(()=>ri.id,{onDelete:"cascade"}),signerEmail:tT("signer_email").notNull(),signerName:tT("signer_name").notNull(),signerUserId:tM("signer_user_id"),signerOrder:eB("signer_order").notNull().default(1),status:ra("status").notNull().default("pending"),signedAt:tj("signed_at"),declinedAt:tj("declined_at"),declineReason:tT("decline_reason"),signatureImageUrl:tT("signature_image_url"),ipAddress:tT("ip_address"),accessToken:tT("access_token"),tokenExpiresAt:tj("token_expires_at"),viewedAt:tj("viewed_at"),consentText:tT("consent_text"),consentAcceptedAt:tj("consent_accepted_at"),userAgent:tT("user_agent"),signatureType:tT("signature_type"),signatureData:tT("signature_data"),signingHash:tT("signing_hash"),contactId:tM("contact_id").references(()=>la.id,{onDelete:"set null"}),crmCompanyId:tM("crm_company_id").references(()=>i7.id,{onDelete:"set null"}),employeeId:tM("employee_id").references(()=>iM.id,{onDelete:"set null"}),legalPartyId:tM("legal_party_id").references(()=>sg.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("doc_sig_signers_request_idx").on(e.requestId),nt("doc_sig_signers_access_token_idx").on(e.accessToken),ne("doc_sig_signers_contact_idx").on(e.contactId),ne("doc_sig_signers_crm_company_idx").on(e.crmCompanyId),ne("doc_sig_signers_employee_idx").on(e.employeeId),ne("doc_sig_signers_legal_party_idx").on(e.legalPartyId)]);t5("doc_signature_fields",{id:tM("id").primaryKey().defaultRandom(),requestId:tM("request_id").notNull().references(()=>ri.id,{onDelete:"cascade"}),signerOrder:eB("signer_order").notNull(),fieldType:tT("field_type").notNull(),label:tT("label"),pageIndex:eB("page_index").notNull(),xPct:tI("x_pct").notNull(),yPct:tI("y_pct").notNull(),widthPct:tI("width_pct").notNull(),heightPct:tI("height_pct").notNull(),required:ef("required").notNull().default(!0),dateFormat:tT("date_format"),value:tT("value"),filledAt:tj("filled_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("doc_sig_fields_request_idx").on(e.requestId)]),t5("doc_signature_audit_log",{id:tM("id").primaryKey().defaultRandom(),requestId:tM("request_id").notNull().references(()=>
1ri.id,{onDelete:"cascade"}),action:tT("action").notNull(),actorEmail:tT("actor_email"),actorUserId:tM("actor_user_id"),ipAddress:tT("ip_address"),details:tT("details"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("doc_sig_audit_request_idx").on(e.requestId)]),t5("doc_signing_events",{id:tM("id").primaryKey().defaultRandom(),requestId:tM("request_id").notNull().references(()=>ri.id,{onDelete:"cascade"}),signerId:tM("signer_id").references(()=>ro.id,{onDelete:"set null"}),eventType:tT("event_type").notNull(),actorEmail:tT("actor_email"),ipAddress:tT("ip_address"),userAgent:tT("user_agent"),metadata:tT("metadata"),contentHash:tT("content_hash"),previousHash:tT("previous_hash"),sequenceNumber:eB("sequence_number").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("doc_signing_events_request_idx").on(e.requestId),ne("doc_signing_events_request_seq_idx").on(e.requestId,e.sequenceNumber)]);let rl=L("mfg_order_status",["draft","confirmed","in_progress","done","cancelled"]),rr=L("mfg_order_priority",["low","normal","high","urgent"]),rs=L("mfg_component_status",["pending","partially_issued","issued","returned"]),r_=L("mfg_operation_status",["pending","in_progress","done","skipped"]),ru=t5("mfg_work_centers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),code:tT("code"),description:tT("description"),costPerHour:td("cost_per_hour",{precision:20,scale:4}).notNull().default("0"),capacityPerDay:td("capacity_per_day",{precision:10,scale:2}).notNull().default("8"),isActive:ef("is_active").notNull().default(!0),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mfg_work_centers_entity_idx").on(e.entityId),ne("mfg_work_centers_entity_site_idx").on(e.entityId,e.siteId)]),rc=t5("mfg_boms",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),productItemId:tM("product_item_id").references(()=>oL.id),quantity:td("quantity",{precision:20,scale:4}).notNull().default("1"),unitOfMeasure:tT("unit_of_measure"),isActive:ef("is_active").notNull().default(!0),version:eB("version").notNull().default(1),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mfg_boms_entity_idx").on(e.entityId)]);t5("mfg_bom_lines",{id:tM("id").primaryKey().defaultRandom(),bomId:tM("bom_id").notNull().references(()=>rc.id,{onDelete:"cascade"}),componentItemId:tM("component_item_id").references(()=>oL.id),componentName:tT("component_name").notNull(),quantity:td("quantity",{precision:20,scale:4}).notNull().default("1"),unitOfMeasure:tT("unit_of_measure"),scrapPercent:td("scrap_percent",{precision:5,scale:2}).notNull().default("0"),sequence:eB("sequence").notNull().default(1),notes:tT("notes")},e=>[ne("mfg_bom_lines_bom_idx").on(e.bomId)]),t5("mfg_bom_operations",{id:tM("id").primaryKey().defaultRandom(),bomId:tM("bom_id").notNull().references(()=>rc.id,{onDelete:"cascade"}),workCenterId:tM("work_center_id").references(()=>ru.id),name:tT("name").notNull(),sequence:eB("sequence").notNull().default(1),estimatedDuration:eB("estimated_duration").notNull().default(60),laborCost:td("labor_cost",{precision:20,scale:4}),description:tT("description"),setupTime:eB("setup_time")},e=>[ne("mfg_bom_operations_bom_idx").on(e.bomId)]);let rp=t5("mfg_orders",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),orderNumber:tT("order_number").notNull(),bomId:tM("bom_id").references(()=>rc.id),productItemId:tM("product_item_id").references(()=>oL.id),productName:tT("product_name").notNull(),plannedQty:td("planned_qty",{precision:20,scale:4}).notNull().default("1"),producedQty:td("produced_qty",{precision:20,scale:4}).notNull().default("0"),scrapQty:td("scrap_qty",{precision:20,scale:4}).notNull().default("0"),status:rl("status").notNull().default("draft"),priority:rr("priority").notNull().default("normal"),scheduledStart:tj("scheduled_start"),scheduledDate:eS("scheduled_date"),scheduledEnd:tj("scheduled_end"),actualStart:tj("actual_start"),actualEnd:tj("actual_end"),notes:tT("notes"),eventId:tM("event_id"),consumptionJournalId:tM("consumption_journal_id"),laborJournalId:tM("labor_journal_id"),completionJournalId:tM("completion_journal_id"),subledgerBatchId:tM("subledger_batch_id"),createdBy:tM("created_by"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mfg_orders_entity_idx").on(e.entityId),ne("mfg_orders_status_idx").on(e.status),ne("mfg_orders_event_idx").on(e.eventId),ne("mfg_orders_entity_site_idx").on(e.entityId,e.siteId)]);t5("mfg_order_components",{id:tM("id").primaryKey().defaultRandom(),orderId:tM("order_id").notNull().references(()=>
1rp.id,{onDelete:"cascade"}),componentItemId:tM("component_item_id").references(()=>oL.id),componentName:tT("component_name").notNull(),requiredQty:td("required_qty",{precision:20,scale:4}).notNull(),issuedQty:td("issued_qty",{precision:20,scale:4}).notNull().default("0"),status:rs("status").notNull().default("pending")},e=>[ne("mfg_order_components_order_idx").on(e.orderId)]),t5("mfg_order_operations",{id:tM("id").primaryKey().defaultRandom(),orderId:tM("order_id").notNull().references(()=>rp.id,{onDelete:"cascade"}),workCenterId:tM("work_center_id").references(()=>ru.id),name:tT("name").notNull(),sequence:eB("sequence").notNull().default(1),estimatedDuration:eB("estimated_duration").notNull().default(60),actualDuration:eB("actual_duration"),status:r_("status").notNull().default("pending"),startedAt:tj("started_at"),completedAt:tj("completed_at"),description:tT("description"),notes:tT("notes")},e=>[ne("mfg_order_operations_order_idx").on(e.orderId)]);let ry=L("hd_ticket_status",["new","open","pending","on_hold","solved","closed"]),rm=L("hd_ticket_priority",["low","normal","high","urgent"]),rf=L("hd_ticket_channel",["email","portal","phone","chat","api","internal"]),rN=t5("hd_categories",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),parentId:tM("parent_id"),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("hd_categories_entity_idx").on(e.entityId)]),rI=t5("hd_tickets",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),ticketNumber:tT("ticket_number").notNull(),subject:tT("subject").notNull(),description:tT("description"),status:ry("status").notNull().default("new"),priority:rm("priority").notNull().default("normal"),channel:rf("channel").notNull().default("portal"),customerId:tM("customer_id").references(()=>dn.id),contactEmail:tT("contact_email"),contactName:tT("contact_name"),assignedTo:tM("assigned_to"),categoryId:tM("category_id").references(()=>rN.id),tags:eY("tags"),firstResponseAt:tj("first_response_at"),resolvedAt:tj("resolved_at"),closedAt:tj("closed_at"),satisfactionRating:eB("satisfaction_rating"),satisfactionComment:tT("satisfaction_comment"),billable:ef("billable").notNull().default(!1),projectId:tM("project_id").references(()=>op.id),workTaskId:tM("work_task_id").references(()=>ow.id,{onDelete:"set null"}),billableRateCents:tT("billable_rate_cents"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("hd_tickets_entity_idx").on(e.entityId),ne("hd_tickets_status_idx").on(e.status),ne("hd_tickets_assigned_idx").on(e.assignedTo),ne("hd_tickets_project_idx").on(e.projectId),ne("hd_tickets_work_task_idx").on(e.workTaskId)]),rg=L("hd_message_author_type",["customer","agent","system"]);t5("hd_ticket_messages",{id:tM("id").primaryKey().defaultRandom(),ticketId:tM("ticket_id").notNull().references(()=>rI.id,{onDelete:"cascade"}),authorType:rg("author_type").notNull().default("agent"),authorId:tM("author_id"),authorName:tT("author_name"),body:tT("body").notNull(),isInternal:ef("is_internal").notNull().default(!1),emailMessageId:tT("email_message_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("hd_ticket_messages_ticket_idx").on(e.ticketId),ne("hd_ticket_messages_email_message_id_idx").on(e.emailMessageId)]);let rb=L("hd_kb_article_status",["draft","published","archived"]),rh=t5("hd_kb_categories",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),slug:tT("slug").notNull(),description:tT("description"),sortOrder:eB("sort_order").notNull().default(0),isPublished:ef("is_published").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("hd_kb_categories_entity_idx").on(e.entityId)]);t5("hd_kb_articles",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),categoryId:tM("category_id").references(()=>rh.id),title:tT("title").notNull(),slug:tT("slug").notNull(),body:tT("body").notNull(),status:rb("status").notNull().default("draft"),authorId:tM("author_id"),viewCount:eB("view_count").notNull().default(0),helpfulCount:eB("helpful_count").notNull().default(0),notHelpfulCount:eB("not_helpful_count").notNull().default(0),publishedAt:tj("published_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("hd_kb_articles_entity_idx").on(e.entityId),ne("hd_kb_articles_category_idx").on(e.categoryId),ne("hd_kb_articles_status_idx").on(e.status)]);let rv=L("kb_visibility",["internal","help_center","marketing"]),rx=L("kb_page_status",["draft","published","archived"]),rA=L("kb_content_source_type",["kb_page","document","helpdesk_article"]),rD=t5("kb_spaces",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),slug:tT("slug").notNull(),name:tT("name").notNull(),description:tT("description"),icon:tT("icon"),defaultVisibility:rv("default_visibility").notNull().default("internal"),maxVisibility:rv("max_visibility").notNull().default("marketing"),sortOrder:eB("sort_order").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("kb_spaces_entity_idx").on(e.entityId),nt("kb_spaces_entity_slug_idx").on(e.entityId,e.slug)]),rw=t5("kb_pages",{id:tM("id").primaryKey().defaultRandom(),spaceId:tM("space_id").notNull().references(()=>rD.id,{onDelete:"cascade"}),parentPageId:tM("parent_page_id").references(()=>rw.id,{onDelete:"set null"}),slug:tT("slug").notNull(),title:tT("title").notNull(),bodyJson:tT("body_json").notNull().default(""),bodyMd:tT("body_md").notNull().default(""),visibility:rv("visibility").notNull().default("internal"),status:rx("status").notNull().default("draft"),seoNoindex:ef("seo_noindex").notNull().default(!1),publishedAt:tj("published_at"),currentRevisionId:tM("current_revision_id"),createdBy:tM("created_by"),updatedBy:tM("updated_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("kb_pages_space_idx").on(e.spaceId),ne("kb_pages_parent_idx").on(e.parentPageId),ne("kb_pages_visibility_status_idx").on(e.spaceId,e.visibility,e.status)]);t5("kb_page_revisions",{id:tM("id").primaryKey().defaultRandom(),pageId:tM("page_id").notNull().references(()=>rw.id,{onDelete:"cascade"}),bodyJson:tT("body_json").notNull().default(""),bodyMd:tT("body_md").notNull().default(""),summary:tT("summary"),authorId:tM("author_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("kb_page_revisions_page_idx").on(e.pageId)]),t5("kb_backlinks",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),sourcePageId:tM("source_page_id").notNull().references(()=>rw.id,{onDelete:"cascade"}),targetPageId:tM("target_page_id").notNull().references(()=>rw.id,{onDelete:"cascade"}),anchor:tT("anchor").notNull().default(""),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("kb_backlinks_entity_idx").on(e.entityId),ne("kb_backlinks_target_idx").on(e.targetPageId),nt("kb_backlinks_unique_triple").on(e.sourcePageId,e.targetPageId,e.anchor)]),t5("content_chunks",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),sourceType:rA("source_type").notNull(),sourceId:tM("source_id").notNull(),chunkIndex:eB("chunk_index").notNull(),chunkText:tT("chunk_text").notNull(),embedding:ni("embedding"),embeddingModel:tT("embedding_model"),tokenCount:eB("token_count").notNull().default(0),lastIndexedAt:tj("last_indexed_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("content_chunks_entity_idx").on(e.entityId),nt("content_chunks_source_chunk_uniq").on(e.entityId,e.sourceType,e.sourceId,e.chunkIndex)]);let rE=L("mktg_campaign_status",["draft","scheduled","sending","sent","cancelled"]),rR=L("mktg_list_member_status",["active","unsubscribed","bounced"]),rk=L("mktg_automation_status",["draft","active","paused","archived"]),rT=t5("mktg_lists",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),type:tT("type").notNull().default("static"),contactCount:eB("contact_count").notNull().default(0),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mktg_lists_entity_idx").on(e.entityId)]);t5("mktg_list_members",{id:tM("id").primaryKey().defaultRandom(),listId:tM("list_id").notNull().references(()=>rT.id,{onDelete:"cascade"}),contactId:tM("contact_id").references(()=>la.id,{onDelete:"set null"}),email:tT("email").notNull(),firstName:tT("first_name"),lastName:tT("last_name"),status:rR("status").notNull().default("active"),subscribedAt:tj("subscribed_at").notNull().defaultNow(),unsubscribedAt:tj("unsubscribed_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("mktg_list_members_list_idx").on(e.listId),ne("mktg_list_members_contact_idx").on(e.contactId),nt("mktg_list_members_list_email_uidx").on(e.listId,e.email)]);let rS=t5("mktg_email_templates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),subject:tT("subject").notNull(),bodyHtml:tT("body_html").notNull(),category:tT("category"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mktg_email_templates_entity_idx").on(e.entityId)]),rC=t5("mktg_campaigns",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),status:rE("status").notNull().default("draft"),templateId:tM("template_id").references(()=>rS.id),listId:tM("list_id").references(()=>rT.id),subject:tT("subject"),fromName:tT("from_name"),fromEmail:tT("from_email"),scheduledAt:tj("scheduled_at"),sentAt:tj("sent_at"),totalRecipients:eB("total_recipients").notNull().default(0),sentCount:eB("sent_count").notNull().default(0),openedCount:eB("opened_count").notNull().default(0),clickedCount:eB("clicked_count").notNull().default(0),bouncedCount:eB("bounced_count").notNull().default(0),budgetCents:tT("budget_cents"),spentCents:tT("spent_cents"),glAccountId:tM("gl_account_id"),eventId:tM("event_id"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mktg_campaigns_entity_idx").on(e.entityId),ne("mktg_campaigns_status_idx").on(e.status),ne("mktg_campaigns_event_idx").on(e.eventId)]),rP=t5("mktg_automations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),status:rk("status").notNull().default("draft"),triggerType:tT("trigger_type").notNull().default("manual_enroll"),triggerConfig:eY("trigger_config"),enrollmentCount:eB("enrollment_count").notNull().default(0),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mktg_automations_entity_idx").on(e.entityId),ne("mktg_automations_status_idx").on(e.status)]),rO=t5("mktg_automation_steps",{id:tM("id").primaryKey().defaultRandom(),automationId:tM("automation_id").notNull().references(()=>
1rP.id,{onDelete:"cascade"}),stepType:tT("step_type").notNull(),sequence:eB("sequence").notNull().default(0),config:eY("config"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("mktg_automation_steps_auto_idx").on(e.automationId)]),rK=L("mktg_automation_enrollment_status",["active","paused","completed","exited","failed"]),rL=L("mktg_automation_step_run_status",["pending","running","succeeded","failed","skipped"]),rq=t5("mktg_automation_enrollments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),automationId:tM("automation_id").notNull().references(()=>rP.id,{onDelete:"cascade"}),contactId:tM("contact_id").references(()=>la.id,{onDelete:"set null"}),email:tT("email").notNull(),emailHmac:tT("email_hmac").notNull(),firstName:tT("first_name"),lastName:tT("last_name"),status:rK("status").notNull().default("active"),currentStepId:tM("current_step_id").references(()=>rO.id,{onDelete:"set null"}),currentSequence:eB("current_sequence").notNull().default(0),nextRunAt:tj("next_run_at"),enrolledAt:tj("enrolled_at").notNull().defaultNow(),lastAdvancedAt:tj("last_advanced_at"),completedAt:tj("completed_at"),exitedAt:tj("exited_at"),exitReason:tT("exit_reason"),enrolledBy:tM("enrolled_by"),source:tT("source").notNull().default("manual"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("mktg_auto_enroll_entity_idx").on(e.entityId),ne("mktg_auto_enroll_automation_idx").on(e.automationId),ne("mktg_auto_enroll_contact_idx").on(e.contactId),ne("mktg_auto_enroll_due_idx").on(e.status,e.nextRunAt),nt("mktg_auto_enroll_active_contact_uidx").on(e.automationId,e.contactId).where(Y`${e.status} = 'active' AND ${e.contactId} IS NOT NULL`),nt("mktg_auto_enroll_active_email_uidx").on(e.automationId,e.emailHmac).where(Y`${e.status} = 'active'`)]);t5("mktg_automation_step_runs",{id:tM("id").primaryKey().defaultRandom(),enrollmentId:tM("enrollment_id").notNull().references(()=>rq.id,{onDelete:"cascade"}),stepId:tM("step_id").notNull().references(()=>rO.id,{onDelete:"cascade"}),attempt:eB("attempt").notNull().default(1),status:rL("status").notNull().default("pending"),startedAt:tj("started_at"),finishedAt:tj("finished_at"),errorMessage:tT("error_message"),result:eY("result"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("mktg_auto_step_runs_enrollment_idx").on(e.enrollmentId),ne("mktg_auto_step_runs_step_idx").on(e.stepId),nt("mktg_auto_step_runs_enrollment_step_uidx").on(e.enrollmentId,e.stepId)]);let rj=L("sub_billing_interval",["monthly","quarterly","annual"]),rU=L("sub_status",["trialing","active","past_due","paused","cancelled","expired"]),rB=t5("sub_plans",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),price:td("price",{precision:12,scale:2}).notNull(),currency:tT("currency").notNull().default("USD"),billingInterval:rj("billing_interval").notNull().default("monthly"),trialDays:eB("trial_days").notNull().default(0),features:eY("features"),isActive:ef("is_active").notNull().default(!0),sortOrder:eB("sort_order").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("sub_plans_entity_idx").on(e.entityId)]),rM=t5("sub_subscriptions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),planId:tM("plan_id").notNull().references(()=>rB.id),customerId:tM("customer_id").references(()=>dn.id),status:rU("status").notNull().default("active"),currentPeriodStart:tj("current_period_start"),currentPeriodEnd:tj("current_period_end"),trialEnd:tj("trial_end"),cancelledAt:tj("cancelled_at"),cancellationReason:tT("cancellation_reason"),quantity:td("quantity",{precision:20,scale:4}).notNull().default("1"),unitPrice:td("unit_price",{precision:20,scale:4}).notNull().default("0"),mrr:td("mrr",{precision:12,scale:2}),metadata:eY("metadata"),originatingSalesOrderId:tM("originating_sales_order_id").references(()=>l3.id,{onDelete:"set null"}),originatingSalesOrderLineId:tM("originating_sales_order_line_id").references(()=>l9.id,{onDelete:"set null"}),amendedFromSubscriptionId:tM("amended_from_subscription_id").references(()=>rM.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("sub_subscriptions_entity_idx").on(e.entityId),ne("sub_subscriptions_status_idx").on(e.status),ne("sub_subscriptions_customer_idx").on(e.customerId),ne("sub_subscriptions_orig_order_idx").on(e.originatingSalesOrderId),ne("sub_subscriptions_orig_line_idx").on(e.originatingSalesOrderLineId),ne("sub_subscriptions_amended_from_idx").on(e.amendedFromSubscriptionId)]),rF=L("sub_invoice_status",["draft","open","paid","void","uncollectible"]);t5("sub_invoices",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),subscriptionId:tM("subscription_id").notNull().references(()=>rM.id),invoiceNumber:tT("invoice_number").notNull(),status:rF("status").notNull().default("draft"),amount:td("amount",{precision:12,scale:2}).notNull(),currency:tT("currency").notNull().default("USD"),periodStart:tj("period_start"),peri
1odEnd:tj("period_end"),dueDate:tj("due_date"),paidAt:tj("paid_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("sub_invoices_entity_idx").on(e.entityId),ne("sub_invoices_sub_idx").on(e.subscriptionId)]);let rV=L("household_possession_status",["owned","loaned","sold","donated","lost","stolen","disposed"]),rH=L("household_possession_condition",["new","excellent","good","fair","poor"]);t5("household_possessions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),category:tT("category"),room:tT("room"),quantity:eB("quantity").notNull().default(1),manufacturer:tT("manufacturer"),model:tT("model"),serialNumber:tT("serial_number"),productUrl:tT("product_url"),acquiredFrom:tT("acquired_from"),purchaseDate:tj("purchase_date"),warrantyExpiry:tj("warranty_expiry"),purchasePrice:tT("purchase_price"),replacementValue:tT("replacement_value"),insuredValue:tT("insured_value"),insurerName:tT("insurer_name"),policyReference:tT("policy_reference"),condition:rH("condition"),status:rV("status").notNull().default("owned"),notes:tT("notes"),provenance:tT("provenance"),sourceStagedTransactionId:tM("source_staged_transaction_id"),sourceLedgerEventId:tM("source_ledger_event_id"),primaryImageDocumentId:tM("primary_image_document_id").references(()=>a9.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("household_possessions_entity_idx").on(e.entityId),ne("household_possessions_status_idx").on(e.entityId,e.status),ne("household_possessions_primary_image_idx").on(e.primaryImageDocumentId)]);let r$=L("maint_wo_status",["requested","scheduled","in_progress","completed","cancelled"]),rG=L("maint_wo_priority",["low","medium","high","critical"]),rz=t5("maint_equipment",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),serialNumber:tT("serial_number"),manufacturer:tT("manufacturer"),model:tT("model"),productUrl:tT("product_url"),location:tT("location"),status:tT("status").notNull().default("operational"),purchaseDate:tj("purchase_date"),warrantyExpiry:tj("warranty_expiry"),notes:tT("notes"),fixedAssetId:tM("fixed_asset_id").references(()=>av.id,{onDelete:"set null"}),primaryImageDocumentId:tM("primary_image_document_id").references(()=>a9.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("maint_equipment_entity_idx").on(e.entityId),ne("maint_equipment_primary_image_idx").on(e.primaryImageDocumentId),ne("maint_equipment_fixed_asset_idx").on(e.fixedAssetId)]),rQ=t5("maint_work_orders",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),orderNumber:tT("order_number").notNull(),equipmentId:tM("equipment_id").references(()=>rz.id),title:tT("title").notNull(),description:tT("description"),status:r$("status").notNull().default("requested"),priority:rG("priority").notNull().default("medium"),type:tT("type").notNull().default("corrective"),assignedTo:tM("assigned_to"),scheduledDate:tj("scheduled_date"),completedAt:tj("completed_at"),estimatedHours:td("estimated_hours",{precision:6,scale:2}),actualHours:td("actual_hours",{precision:6,scale:2}),cost:td("cost",{precision:12,scale:2}),notes:tT("notes"),capitalize:ef("capitalize").notNull().default(!1),capitalizedToAssetId:tM("capitalized_to_asset_id").references(()=>av.id),eventId:tM("event_id"),subledgerBatchId:tM("subledger_batch_id"),createdBy:tM("created_by"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("maint_wo_entity_idx").on(e.entityId),ne("maint_wo_status_idx").on(e.status),ne("maint_wo_equipment_idx").on(e.equipmentId),ne("maint_wo_event_idx").on(e.eventId),ne("maint_wo_entity_site_idx").on(e.entityId,e.siteId)]);t5("maint_schedules",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),equipmentId:tM("equipment_id").notNull().references(()=>rz.id),name:tT("name").notNull(),description:tT("description"),frequencyDays:eB("frequency_days").notNull(),lastPerformedAt:tj("last_performed_at"),nextDueAt:tj("next_due_at"),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("maint_schedules_entity_idx").on(e.entityId),ne("maint_schedules_equipment_idx").on(e.equipmentId)]);let rY=t5("bi_dashboards",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),layout:eY("layout"),isDefault:ef("is_default").notNull().default(!1),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("bi_dashboards_entity_idx").on(e.entityId)]);t5("bi_widgets",{id:tM("id").primaryKey().defaultRandom(),dashboardId:tM("dashboard_id").notNull().references(()=>
1rY.id,{onDelete:"cascade"}),title:tT("title").notNull(),widgetType:tT("widget_type").notNull(),dataSource:tT("data_source").notNull(),config:eY("config"),position:eY("position"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("bi_widgets_dashboard_idx").on(e.dashboardId)]),t5("bi_saved_reports",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),name:tT("name").notNull(),description:tT("description"),reportType:tT("report_type").notNull(),query:eY("query"),schedule:tT("schedule"),lastRunAt:tj("last_run_at"),createdBy:tM("created_by"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("bi_saved_reports_entity_idx").on(e.entityId)]),t5("cortex_proposals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),userId:tM("user_id").notNull(),toolName:tT("tool_name").notNull(),payload:eY("payload").notNull(),metadata:eY("metadata").$type().notNull().default({}),summary:tT("summary"),status:nD("status").notNull().default("pending"),expiresAt:tj("expires_at").notNull(),createdAt:tj("created_at").notNull().defaultNow(),executedAt:tj("executed_at"),executedBy:tM("executed_by"),rejectedAt:tj("rejected_at"),rejectedBy:tM("rejected_by")},e=>[ne("cortex_proposals_entity_idx").on(e.entityId),ne("cortex_proposals_status_idx").on(e.status),ne("cortex_proposals_expires_idx").on(e.expiresAt)]),t5("cortex_ephemeral_files",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),userId:tM("user_id").notNull(),blobUrl:tT("blob_url").notNull(),mimeType:tT("mime_type").notNull(),filename:tT("filename").notNull(),expiresAt:tj("expires_at").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cortex_ephemeral_files_entity_idx").on(e.entityId),ne("cortex_ephemeral_files_expires_idx").on(e.expiresAt),ne("cortex_ephemeral_files_user_idx").on(e.userId)]);let rW=t5("cortex_agents",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),slug:tT("slug").notNull(),name:tT("name").notNull(),title:tT("title"),systemPrompt:tT("system_prompt").notNull(),toolPolicy:eY("tool_policy").$type().notNull().default({}),visibility:nw("visibility").notNull().default("entity"),createdBy:tM("created_by"),archivedAt:tj("archived_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cortex_agents_entity_idx").on(e.entityId),nt("cortex_agents_entity_slug_uq").on(e.entityId,e.slug)]),rJ=t5("cortex_agent_delegations",{id:tM("id").primaryKey().defaultRandom(),agentId:tM("agent_id").notNull().references(()=>rW.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),grantedPermissions:eY("granted_permissions").notNull().$type().default([]),grantedBy:tM("granted_by").notNull(),expiresAt:tj("expires_at"),revokedAt:tj("revoked_at"),scheduleCron:tT("schedule_cron"),scheduleTimezone:tT("schedule_timezone").default("UTC"),runPrompt:tT("run_prompt"),lastRunAt:tj("last_run_at"),nextRunAt:tj("next_run_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cortex_agent_delegations_entity_idx").on(e.entityId),ne("cortex_agent_delegations_agent_idx").on(e.agentId),ne("cortex_agent_delegations_next_run_idx").on(e.nextRunAt)]);t5("cortex_agent_invocations",{id:tM("id").primaryKey().defaultRandom(),agentId:tM("agent_id").notNull().references(()=>rW.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),actorIdentityId:tM("actor_identity_id").notNull(),delegationId:tM("delegation_id").references(()=>rJ.id,{onDelete:"set null"}),sessionId:tT("session_id"),source:nE("source").notNull(),summary:tT("summary"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cortex_agent_invocations_entity_idx").on(e.entityId),ne("cortex_agent_invocations_agent_idx").on(e.agentId),ne("cortex_agent_invocations_actor_idx").on(e.actorIdentityId),ne("cortex_agent_invocations_created_idx").on(e.createdAt)]),t5("ai_automation_policies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").references(()=>
1nP.id,{onDelete:"cascade"}),appId:tT("app_id"),policy:eY("policy").notNull(),schemaVersion:eB("schema_version").notNull().default(1),updatedAt:tj("updated_at").notNull().defaultNow(),updatedBy:tM("updated_by")},e=>[ne("ai_automation_policies_entity_idx").on(e.entityId),nt("ai_automation_policies_scope_uq").on(Y`coalesce(${e.entityId}::text, '')`,Y`coalesce(${e.appId}, '')`)]),t5("ai_automation_policy_audit",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").references(()=>nP.id,{onDelete:"set null"}),appId:tT("app_id"),actorUserId:tM("actor_user_id").notNull(),action:tT("action").notNull(),previousPolicy:eY("previous_policy"),newPolicy:eY("new_policy").notNull(),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ai_automation_policy_audit_entity_idx").on(e.entityId),ne("ai_automation_policy_audit_created_idx").on(e.createdAt)]),t5("cortex_ai_settings",{id:tM("id").primaryKey(),allowedModelIds:eY("allowed_model_ids").$type(),defaultModelId:tT("default_model_id"),tenantMonthlyBudgetCents:eB("tenant_monthly_budget_cents"),userMonthlyBudgetCents:eB("user_monthly_budget_cents"),updatedAt:tj("updated_at").notNull().defaultNow(),updatedBy:tM("updated_by")}),t5("ledger_classify_previews",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),userId:tM("user_id").notNull(),expiresAt:tj("expires_at").notNull(),consumedAt:tj("consumed_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ledger_classify_previews_entity_user_idx").on(e.entityId,e.userId),ne("ledger_classify_previews_expires_idx").on(e.expiresAt)]);let rX=L("website_domain_status",["pending","active","disabled"]),rZ=t5("website_sites",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),draftVersion:eB("draft_version").notNull().default(1),publishedVersion:eB("published_version").notNull().default(0),draftContent:eY("draft_content").notNull().default({}),publishedContent:eY("published_content"),publishedAt:tj("published_at"),publicSiteConfig:eY("public_site_config").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow(),updatedBy:tM("updated_by")},e=>[nt("website_sites_entity_uq").on(e.entityId)]);t5("website_site_revisions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),publishedVersion:eB("published_version").notNull(),spec:eY("spec").notNull().default({}),createdAt:tj("created_at").notNull().defaultNow(),createdBy:tM("created_by")},e=>[ne("website_site_revisions_entity_idx").on(e.entityId),ne("website_site_revisions_entity_version_idx").on(e.entityId,e.publishedVersion)]);let r0=L("website_property_kind",["hosted","external"]),r1=L("website_device_class",["mobile","desktop","tablet"]),r2=L("website_event_type",["pageview","form_start","form_submit","cta_click"]),r4=L("website_submission_status",["processed","partial","failed"]),r6=L("website_property_cost_category",["hosting","domain","ads","agency","other"]),r8=t5("website_properties",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),kind:r0("kind").notNull(),hostname:tT("hostname").notNull(),websiteSiteId:tM("website_site_id").references(()=>rZ.id,{onDelete:"set null"}),trackingPublicKeyHash:tT("tracking_public_key_hash"),trackingKeyHint:tT("tracking_key_hint"),allowedOrigins:eY("allowed_origins").$type().notNull().default([]),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("website_properties_entity_idx").on(e.entityId),nt("website_properties_entity_hostname_uq").on(e.entityId,e.hostname),ne("website_properties_hostname_idx").on(e.hostname),ne("website_properties_key_hash_idx").on(e.trackingPublicKeyHash)]);t5("website_sessions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),propertyId:tM("property_id").notNull().references(()=>
1r8.id,{onDelete:"cascade"}),sessionKey:tT("session_key").notNull(),firstSeenAt:tj("first_seen_at").notNull().defaultNow(),lastSeenAt:tj("last_seen_at").notNull().defaultNow(),landingPath:tT("landing_path"),referrer:tT("referrer"),utm:eY("utm").$type(),deviceClass:r1("device_class")},e=>[ne("website_sessions_property_idx").on(e.propertyId),nt("website_sessions_property_key_uq").on(e.propertyId,e.sessionKey),ne("website_sessions_entity_last_seen_idx").on(e.entityId,e.lastSeenAt)]),t5("website_events",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),propertyId:tM("property_id").notNull().references(()=>r8.id,{onDelete:"cascade"}),sessionKey:tT("session_key"),occurredAt:tj("occurred_at").notNull().defaultNow(),eventType:r2("event_type").notNull(),path:tT("path"),formId:tT("form_id"),elementId:tT("element_id"),metadata:eY("metadata").$type()},e=>[ne("website_events_property_occurred_idx").on(e.propertyId,e.occurredAt),ne("website_events_entity_occurred_idx").on(e.entityId,e.occurredAt),ne("website_events_type_idx").on(e.propertyId,e.eventType)]),t5("website_submissions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),propertyId:tM("property_id").notNull().references(()=>r8.id,{onDelete:"cascade"}),sessionKey:tT("session_key"),formId:tT("form_id"),path:tT("path"),payload:tT("payload").notNull(),emailHmac:tT("email_hmac"),ipHmac:tT("ip_hmac"),crmLeadId:tM("crm_lead_id").references(()=>oi.id,{onDelete:"set null"}),crmContactId:tM("crm_contact_id").references(()=>la.id,{onDelete:"set null"}),hdTicketId:tM("hd_ticket_id").references(()=>rI.id,{onDelete:"set null"}),routingMode:tT("routing_mode"),status:r4("status").notNull().default("processed"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("website_submissions_property_idx").on(e.propertyId),ne("website_submissions_entity_created_idx").on(e.entityId,e.createdAt),ne("website_submissions_ip_hmac_idx").on(e.ipHmac,e.createdAt)]),t5("website_property_costs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),propertyId:tM("property_id").notNull().references(()=>r8.id,{onDelete:"cascade"}),periodStart:eS("period_start").notNull(),periodEnd:eS("period_end").notNull(),category:r6("category").notNull(),amountCents:eB("amount_cents").notNull(),currency:tT("currency").notNull().default("USD"),memo:tT("memo"),sourceRef:tT("source_ref"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("website_property_costs_property_idx").on(e.propertyId),ne("website_property_costs_entity_period_idx").on(e.entityId,e.periodStart,e.periodEnd)]),t5("website_daily_stats",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),propertyId:tM("property_id").notNull().references(()=>r8.id,{onDelete:"cascade"}),statDate:eS("stat_date").notNull(),sessions:eB("sessions").notNull().default(0),pageviews:eB("pageviews").notNull().default(0),formStarts:eB("form_starts").notNull().default(0),submits:eB("submits").notNull().default(0),crmLeads:eB("crm_leads").notNull().default(0),wonRevenueCents:eB("won_revenue_cents").notNull().default(0),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("website_daily_stats_property_date_uq").on(e.propertyId,e.statDate),ne("website_daily_stats_entity_date_idx").on(e.entityId,e.statDate)]),t5("website_domains",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),hostname:tT("hostname").notNull(),status:rX("status").notNull().default("pending"),verificationToken:tT("verification_token"),lastVerificationError:tT("last_verification_error"),verifiedAt:tj("verified_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("website_domains_hostname_uq").on(e.hostname),ne("website_domains_entity_idx").on(e.entityId)]),t5("subledger_running_totals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),ledgerId:tM("ledger_id").notNull().references(()=>nj.id),moduleKey:tT("module_key").notNull(),controlAccountRole:tT("control_account_role").notNull(),periodStart:eS("period_start").notNull(),periodEnd:eS("period_end").notNull(),runningTotalCents:tT("running_total_cents").notNull(),lastEventId:tM("last_event_id").references(()=>nB.id),lastUpdatedAt:tj("last_updated_at").notNull().defaultNow()},e=>[ne("srt_entity_module_idx").on(e.entityId,e.moduleKey),ne("srt_entity_ledger_idx").on(e.entityId,e.ledgerId),nt("srt_unique_idx").on(e.entityId,e.ledgerId,e.moduleKey,e.controlAccountRole,e.periodStart)]),t5("subledger_reconciliations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),ledgerId:tM("ledger_id").notNull().references(()=>nj.id),moduleKey:tT("module_key").notNull(),controlAccountRole:tT("control_account_role").notNull(),asOfDate:eS("as_of_date").notNull(),recomputedDetailSumCents:tT("recomputed_detail_sum_cents").notNull(),runningTotalCents:tT("running_total_cents").notNull(),controlBalanceCents:tT("control_balance_cents").notNull(),recomputeVsRunningVarianceCents:tT("recompute_vs_running_variance_cents").notNull(),detailVsControlVarianceCents:tT("detail_vs_control_variance_cents").notNull(),status:tT("status").notNull(),details:eY("details"),triggeredBy:tT("triggered_by").notNull(),triggeredByUserId:tM("triggered_by_user_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("srecon_entity_module_idx").on(e.entityId,e.moduleKey),ne("srecon_entity_ledger_module_idx").on(e.entityId,e.ledgerId,e.moduleKey),ne("srecon_status_idx").on(e.status),ne("srecon_created_idx").on(e.createdAt)]),t5("pending_postings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),moduleKey:tT("module_key").notNull(),eventType:tT("event_type").notNull(),payload:eY("payload").notNull(),dedupeKey:tT("dedupe_key").notNull(),incurredDate:eS("incurred_date").notNull(),status:tT("status").notNull().default("queued"),firedAt:tj("fired_at"),firedEventId:tM("fired_event_id").references(()=>nB.id),error:tT("error"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("pending_postings_entity_idx").on(e.entityId),ne("pending_postings_status_idx").on(e.status),nt("pending_postings_dedupe_idx").on(e.dedupeKey)]);let r5=L("vehicle_status",["active","retired","sold","leased"]),r3=L("vehicle_ownership",["owned","leased","employee_owned"]),r9=L("mileage_method",["standard_rate","actual_cost"]),r7=t5("vehicles",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),fixedAssetId:tM("fixed_asset_id").references(()=>av.id),name:tT("name").notNull(),make:tT("make"),model:tT("model"),year:eB("year"),vin:tT("vin"),licensePlate:tT("license_plate"),color:tT("color"),ownership:r3("ownership").notNull().default("owned"),status:r5("status").notNull().default("active"),mileageMethod:r9("mileage_method").notNull().default("standard_rate"),currentOdometer:tT("current_odometer"),fuelType:tT("fuel_type"),defaultDriverId:tM("default_driver_id").references(()=>ok.id),taxMethodLocked:ef("tax_method_locked").notNull().default(!1),notes:tT("notes"),homeSiteId:tM("home_site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("vehicles_entity_idx").on(e.entityId),ne("vehicles_fixed_asset_idx").on(e.fixedAssetId),ne("vehicles_status_idx").on(e.status),ne("vehicles_entity_home_site_idx").on(e.entityId,e.homeSiteId)]);t5("vehicle_mileage_logs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),vehicleId:tM("vehicle_id").notNull().references(()=>r7.id,{onDelete:"cascade"}),routeId:tM("route_id").references(()=>oE.id),driverId:tM("driver_id").references(()=>ok.id),logDate:eS("log_date").notNull(),startOdometer:tT("start_odometer"),endOdometer:tT("end_odometer"),milesDriven:tT("miles_driven").notNull(),businessPercent:tT("business_percent").notNull().default("100"),purpose:tT("purpose"),ratePerMileCents:eB("rate_per_mile_cents"),computedDeductionCents:tT("computed_deduction_cents"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("vehicle_mileage_logs_entity_idx").on(e.entityId),ne("vehicle_mileage_logs_vehicle_idx").on(e.vehicleId),ne("vehicle_mileage_logs_route_idx").on(e.routeId),ne("vehicle_mileage_logs_event_idx").on(e.eventId)]),t5("vehicle_fuel_logs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),vehicleId:tM("vehicle_id").notNull().references(()=>r7.id,{onDelete:"cascade"}),routeId:tM("route_id").references(()=>oE.id),driverId:tM("driver_id").references(()=>ok.id),logDate:eS("log_date").notNull(),gallons:tT("gallons"),totalCostCents:tT("total_cost_cents").notNull(),pricePerGallonCents:tT("price_per_gallon_cents"),odometer:tT("odometer"),vendorName:tT("vendor_name"),paymentMethod:tT("payment_method"),receiptDocumentId:tM("receipt_document_id"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("vehicle_fuel_logs_entity_idx").on(e.entityId),ne("vehicle_fuel_logs_vehicle_idx").on(e.vehicleId),ne("vehicle_fuel_logs_route_idx").on(e.routeId),ne("vehicle_fuel_logs_event_idx").on(e.eventId)]),t5("vehicle_toll_logs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),vehicleId:tM("vehicle_id").notNull().references(()=>r7.id,{onDelete:"cascade"}),routeId:tM("route_id").references(()=>oE.id),driverId:tM("driver_id").references(()=>ok.id),logDate:eS("log_date").notNull(),location:tT("location"),totalCostCents:tT("total_cost_cents").notNull(),paymentMethod:tT("payment_method"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("vehicle_toll_logs_entity_idx").on(e.entityId),ne("vehicle_toll_logs_vehicle_idx").on(e.vehicleId),ne("vehicle_toll_logs_event_idx").on(e.eventId)]),t5("vehicle_maintenance_logs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),vehicleId:tM("vehicle_id").notNull().references(()=>r7.id,{onDelete:"cascade"}),serviceDate:eS("service_date").notNull(),vendor:tT("vendor"),description:tT("description"),partsCostCents:tT("parts_cost_cents"),laborCostCents:tT("labor_cost_cents"),totalCostCents:tT("total_cost_cents").notNull(),capitalize:ef("capitalize").notNull().default(!1),capitalizedToAssetId:tM("capitalized_to_asset_id").references(()=>av.id),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id"),siteId:tM("site_id").references(()=>on.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("vehicle_maintenance_logs_entity_idx").on(e.entityId),ne("vehicle_maintenance_logs_vehicle_idx").on(e.vehicleId),ne("vehicle_maintenance_logs_event_idx").on(e.eventId),ne("vehicle_maintenance_logs_entity_site_idx").on(e.entityId,e.siteId)]),t5("vehicle_insurance_policies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),vehicleId:tM("vehicle_id").references(()=>r7.id,{onDelete:"cascade"}),policyNumber:tT("policy_number"),carrier:tT("carrier"),premiumCents:tT("premium_cents").notNull(),coverageType:tT("coverage_type"),startDate:eS("start_date").notNull(),endDate:eS("end_date").notNull(),eventId:tM("event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("vehicle_insurance_policies_entity_idx").on(e.entityId),ne("vehicle_insurance_policies_vehicle_idx").on(e.vehicleId)]),t5("mfg_overhead_pools",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),basis:tT("basis").notNull().default("labor_hours"),rateCents:eB("rate_cents").notNull().default(0),isActive:ef("is_active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("mfg_overhead_pools_entity_idx").on(e.entityId)]);let se=t5("project_cost_postings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),jobId:tM("job_id").notNull().references(()=>op.id,{onDelete:"cascade"}),postingDate:eS("posting_date").notNull(),category:tT("category").notNull(),amountCents:tT("amount_cents").notNull(),description:tT("description"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("project_cost_postings_entity_idx").on(e.entityId),ne("project_cost_postings_job_idx").on(e.jobId),ne("project_cost_postings_event_idx").on(e.eventId)]);t5("maint_wo_parts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),workOrderId:tM("work_order_id").notNull().references(()=>rQ.id,{onDelete:"cascade"}),inventoryItemId:tM("inventory_item_id").references(()=>oL.id),description:tT("description"),quantity:tT("quantity").notNull(),unitCostCents:tT("unit_cost_cents"),totalCostCents:tT("total_cost_cents").notNull(),eventId:tM("event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("maint_wo_parts_entity_idx").on(e.entityId),ne("maint_wo_parts_wo_idx").on(e.workOrderId),ne("maint_wo_parts_event_idx").on(e.eventId)]),t5("maint_wo_labor",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),workOrderId:tM("work_order_id").notNull().references(()=>rQ.id,{onDelete:"cascade"}),employeeId:tM("employee_id"),hours:tT("hours").notNull(),rateCents:tT("rate_cents"),totalCostCents:tT("total_cost_cents").notNull(),eventId:tM("event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("maint_wo_labor_entity_idx").on(e.entityId),ne("maint_wo_labor_wo_idx").on(e.workOrderId),ne("maint_wo_labor_event_idx").on(e.eventId)]);let st=t5("mktg_campaign_spend",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),campaignId:tM("campaign_id").notNull().references(()=>rC.id,{onDelete:"cascade"}),spendDate:eS("spend_date").notNull(),channel:tT("channel"),amountCents:tT("amount_cents").notNull(),vendorName:tT("vendor_name"),documentId:tM("document_id"),eventId:tM("event_id").references(()=>nB.id),subledgerBatchId:tM("subledger_batch_id"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("mktg_campaign_spend_entity_idx").on(e.entityId),ne("mktg_campaign_spend_campaign_idx").on(e.campaignId),ne("mktg_campaign_spend_event_idx").on(e.eventId)]),sn=L("ads_platform",["google_ads","meta_ads","linkedin_ads","x_ads"]),sd=L("ads_campaign_status",["active","paused","removed","draft","unknown"]),sa=L("ads_optimization_action_kind",["pause_campaign","resume_campaign","adjust_budget","shift_budget","recommendation"]),si=L("ads_optimization_action_status",["proposed","approved","applied","failed","rejected"]),so=L("ads_attribution_match_source",["utm","manual","platform"]),sl=t5("ads_accounts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),connectionId:tM("connection_id").notNull().references(()=>ap.id,{onDelete:"cascade"}),platform:sn("platform").notNull(),externalAccountId:tT("external_account_id").notNull(),name:tT("name").notNull(),currency:tT("currency").notNull().default("USD"),timezone:tT("timezone"),isActive:ef("is_active").notNull().default(!0),lastSyncAt:tj("last_sync_at"),lastSyncError:tT("last_sync_error"),metadata:eY("metadata").$type(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("ads_accounts_entity_idx").on(e.entityId),ne("ads_accounts_connection_idx").on(e.connectionId),nt("ads_accounts_entity_platform_external_uidx").on(e.entityId,e.platform,e.externalAccountId)]),sr=t5("ads_campaigns",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),accountId:tM("account_id").notNull().references(()=>sl.id,{onDelete:"cascade"}),platform:sn("platform").notNull(),externalCampaignId:tT("external_campaign_id").notNull(),name:tT("name").notNull(),status:sd("status").notNull().default("unknown"),objective:tT("objective"),utmCampaign:tT("utm_campaign"),landingUrl:tT("landing_url"),websitePropertyId:tM("website_property_id"),linkedMktgCampaignId:tM("linked_mktg_campaign_id").references(()=>rC.id,{onDelete:"set null"}),budgetCents:tT("budget_cents"),currency:tT("currency").notNull().default("USD"),notes:tT("notes"),metadata:eY("metadata").$type(),lastSyncedAt:tj("last_synced_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("ads_campaigns_entity_idx").on(e.entityId),ne("ads_campaigns_account_idx").on(e.accountId),ne("ads_campaigns_utm_idx").on(e.entityId,e.utmCampaign),nt("ads_campaigns_entity_platform_external_uidx").on(e.entityId,e.platform,e.externalCampaignId)]),ss=t5("ads_ad_groups",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),campaignId:tM("campaign_id").notNull().references(()=>sr.id,{onDelete:"cascade"}),externalAdGroupId:tT("external_ad_group_id").notNull(),name:tT("name").notNull(),status:sd("status").notNull().default("unknown"),budgetCents:tT("budget_cents"),metadata:eY("metadata").$type(),lastSyncedAt:tj("last_synced_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("ads_ad_groups_campaign_idx").on(e.campaignId),nt("ads_ad_groups_campaign_external_uidx").on(e.campaignId,e.externalAdGroupId)]);t5("ads_ads",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),adGroupId:tM("ad_group_id").notNull().references(()=>ss.id,{onDelete:"cascade"}),externalAdId:tT("external_ad_id").notNull(),name:tT("name").notNull(),status:sd("status").notNull().default("unknown"),creativeUrl:tT("creative_url"),headline:tT("headline"),metadata:eY("metadata").$type(),lastSyncedAt:tj("last_synced_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("ads_ads_ad_group_idx").on(e.adGroupId),nt("ads_ads_ad_group_external_uidx").on(e.adGroupId,e.externalAdId)]),t5("ads_daily_metrics",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),campaignId:tM("campaign_id").notNull().references(()=>sr.id,{onDelete:"cascade"}),metricDate:eS("metric_date").notNull(),spendCents:tT("spend_cents").notNull(),impressions:eB("impressions").notNull().default(0),clicks:eB("clicks").notNull().default(0),conversions:tT("conversions"),spendImportedAt:tj("spend_imported_at"),mktgSpendId:tM("mktg_spend_id").references(()=>st.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("ads_daily_metrics_entity_idx").on(e.entityId),ne("ads_daily_metrics_campaign_idx").on(e.campaignId),nt("ads_daily_metrics_campaign_date_uidx").on(e.campaignId,e.metricDate)]),t5("ads_attribution_links",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),adsCampaignId:tM("ads_campaign_id").notNull().references(()=>sr.id,{onDelete:"cascade"}),crmLeadId:tM("crm_lead_id").notNull().references(()=>oi.id,{onDelete:"cascade"}),salesOrderId:tM("sales_order_id"),matchSource:so("match_source").notNull().default("utm"),attributedValueCents:tT("attributed_value_cents"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ads_attribution_links_entity_idx").on(e.entityId),ne("ads_attribution_links_campaign_idx").on(e.adsCampaignId),ne("ads_attribution_links_lead_idx").on(e.crmLeadId),nt("ads_attribution_links_campaign_lead_uidx").on(e.adsCampaignId,e.crmLeadId)]),t5("ads_optimization_rules",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull().default("Default"),isActive:ef("is_active").notNull().default(!0),maxCpaCents:tT("max_cpa_cents"),minRoas:tT("min_roas"),dailyBudgetCapCents:tT("daily_budget_cap_cents"),autoPauseEnabled:ef("auto_pause_enabled").notNull().default(!1),requireApproval:ef("require_approval").notNull().default(!0),morningBriefEnabled:ef("morning_brief_enabled").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("ads_optimization_rules_entity_idx").on(e.entityId)]),t5("ads_optimization_actions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),adsCampaignId:tM("ads_campaign_id").references(()=>sr.id,{onDelete:"set null"}),actionKind:sa("action_kind").notNull(),status:si("status").notNull().default("proposed"),dryRun:ef("dry_run").notNull().default(!0),summary:tT("summary").notNull(),payload:eY("payload").$type(),errorMessage:tT("error_message"),createdBy:tM("created_by"),appliedAt:tj("applied_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("ads_optimization_actions_entity_idx").on(e.entityId),ne("ads_optimization_actions_campaign_idx").on(e.adsCampaignId)]),t5("ads_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>
1nP.id,{onDelete:"cascade"}),defaultUtmSource:tT("default_utm_source"),syncFrequency:a_("sync_frequency").notNull().default("DAILY"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()});let s_=L("legal_party_kind",["INDIVIDUAL","ORGANIZATION"]),su=L("governance_body_kind",["BOARD","COMMITTEE","MEMBERS_ASSEMBLY","PARTNERS_MEETING","TRUSTEES","INVESTMENT_COMMITTEE","LPAC","SOLE_OWNER"]),sc=L("governance_seat_kind",["DIRECTOR","CHAIR","OFFICER","MANAGER","MANAGING_MEMBER","MANAGING_PARTNER","TRUSTEE","SUCCESSOR_TRUSTEE","GP","LPAC_MEMBER","IC_MEMBER","OBSERVER"]),sp=L("governance_officer_title",["CEO","PRESIDENT","CFO","COO","CTO","SECRETARY","TREASURER","OTHER"]),sy=L("governance_holder_class",["COMMON","PREFERRED","LLC_UNIT","PROFITS_INTEREST","LP_INTEREST","GP_INTEREST","LLP_INTEREST","BENEFICIAL_INTEREST_INCOME","BENEFICIAL_INTEREST_REMAINDER","BENEFICIAL_INTEREST_BOTH","MEMBERSHIP_NONPROFIT"]),sm=L("governance_action_kind",["BOARD_RESOLUTION","WRITTEN_CONSENT","MEETING_MINUTES","AMENDMENT","ELECTION","APPOINTMENT","REMOVAL","RATIFICATION","INCORPORATION"]),sf=L("governance_action_status",["DRAFT","OPEN_FOR_VOTE","ADOPTED","REJECTED","WITHDRAWN","EXPIRED"]),sN=L("governance_vote",["YES","NO","ABSTAIN","NOT_VOTED"]),sI=L("governance_eligible_voter_scope",["BODY_SEATS","HOLDERS_OF_CLASS","ALL_HOLDERS","NAMED_PARTIES"]),sg=t5("legal_parties",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),kind:s_("kind").notNull(),displayName:tT("display_name").notNull(),legalName:tT("legal_name"),email:tT("email"),emailHmac:tT("email_hmac"),taxIdLast4:tT("tax_id_last4"),taxId:tT("tax_id"),taxIdHmac:tT("tax_id_hmac"),displayNameHmac:tT("display_name_hmac"),phone:tT("phone"),phoneHmac:tT("phone_hmac"),identityId:tM("identity_id"),globalRegistryId:tM("global_registry_id"),primaryAddressId:tM("primary_address_id").references(()=>lo.id,{onDelete:"set null"}),isActive:ef("is_active").notNull().default(!0),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("legal_parties_entity_idx").on(e.entityId),ne("legal_parties_global_registry_idx").on(e.globalRegistryId),ne("legal_parties_entity_email_hmac_idx").on(e.entityId,e.emailHmac),ne("legal_parties_entity_tax_id_hmac_idx").on(e.entityId,e.taxIdHmac),ne("legal_parties_entity_phone_hmac_idx").on(e.entityId,e.phoneHmac),ne("legal_parties_entity_name_hmac_idx").on(e.entityId,e.displayNameHmac),ne("legal_parties_identity_idx").on(e.identityId)]),sb=t5("governance_bodies",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),kind:su("kind").notNull(),name:tT("name").notNull(),description:tT("description"),parentBodyId:tM("parent_body_id").references(()=>sb.id,{onDelete:"cascade"}),quorumRule:eY("quorum_rule").$type().notNull().default({kind:"majority"}),supermajorityRule:eY("supermajority_rule").$type(),establishedAt:eS("established_at"),dissolvedAt:eS("dissolved_at"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_bodies_entity_idx").on(e.entityId),ne("governance_bodies_kind_idx").on(e.entityId,e.kind),ne("governance_bodies_parent_idx").on(e.parentBodyId)]),sh=t5("governance_seats",{id:tM("id").primaryKey().defaultRandom(),bodyId:tM("body_id").notNull().references(()=>sb.id,{onDelete:"cascade"}),partyId:tM("party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),kind:sc("kind").notNull(),officerTitle:sp("officer_title"),titleOverride:tT("title_override"),startDate:eS("start_date").notNull(),endDate:eS("end_date"),termLengthMonths:eB("term_length_months"),electedByActionId:tM("elected_by_action_id"),removedByActionId:tM("removed_by_action_id"),isVoting:ef("is_voting").notNull().default(!0),weight:td("weight",{precision:18,scale:6}).notNull().default("1"),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_seats_body_idx").on(e.bodyId),ne("governance_seats_party_idx").on(e.partyId),ne("governance_seats_kind_idx").on(e.bodyId,e.kind),ne("governance_seats_active_idx").on(e.bodyId,e.endDate)]),sv=t5("governance_holder_classes",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),holderClass:sy("holder_class").notNull(),name:tT("name").notNull(),votingMultiplier:td("voting_multiplier",{precision:18,scale:6}).notNull().default("1"),parameters:eY("parameters").$type(),liquidationPreference:tT("liquidation_preference"),liquidationPreferenceMultiple:tT("liquidation_preference_multiple"),participationCap:tT("participation_cap"),dividendRatePct:tT("dividend_rate_pct"),conversionRatio:tT("conversion_ratio"),antiDilutionType:tT("anti_dilution_type"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_holder_classes_entity_idx").on(e.entityId),nt("governance_holder_classes_entity_name_idx").on(e.entityId,e.name)]),sx=t5("governance_holders",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),partyId:tM("party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),holderClassId:tM("holder_class_id").references(()=>sv.id,{onDelete:"set null"}),units:tT("units"),percentage:tT("percentage"),legacyBeneficiaryId:tM("legacy_beneficiary_id"),legacyInvestorId:tM("legacy_investor_id"),acquiredDate:eS("acquired_date"),disposedDate:eS("disposed_date"),vesting:eY("vesting").$type(),isActive:ef("is_active").notNull().default(!0),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_holders_entity_idx").on(e.entityId),ne("governance_holders_party_idx").on(e.partyId),ne("governance_holders_class_idx").on(e.holderClassId),ne("governance_holders_legacy_beneficiary_idx").on(e.legacyBeneficiaryId),ne("governance_holders_legacy_investor_idx").on(e.legacyInvestorId),ne("governance_holders_active_idx").on(e.entityId,e.isActive)]),sA=t5("governance_actions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bodyId:tM("body_id").references(()=>sb.id,{onDelete:"set null"}),kind:sm("kind").notNull(),status:sf("status").notNull().default("DRAFT"),title:tT("title").notNull(),body:tT("body"),proposedAt:tj("proposed_at").notNull().defaultNow(),votingOpensAt:tj("voting_opens_at"),votingClosesAt:tj("voting_closes_at"),adoptedAt:tj("adopted_at"),requiredThreshold:eY("required_threshold").$type().notNull().default({kind:"majority"}),eligibleVoterScope:sI("eligible_voter_scope").notNull(),eligibleVoterParams:eY("eligible_voter_params").$type(),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),signatureRequestId:tM("signature_request_id").references(()=>ri.id,{onDelete:"set null"}),approvalRequestId:tM("approval_request_id"),createdBy:tM("created_by"),supersedesActionId:tM("supersedes_action_id").references(()=>sA.id,{onDelete:"set null"}),originIsHistorical:ef("origin_is_historical").notNull().default(!1),effectiveDate:eS("effective_date"),voidedAt:tj("voided_at"),voidedBy:tM("voided_by"),voidedReason:tT("voided_reason"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_actions_entity_idx").on(e.entityId),ne("governance_actions_status_idx").on(e.entityId,e.status),ne("governance_actions_body_idx").on(e.bodyId),ne("governance_actions_kind_idx").on(e.entityId,e.kind),ne("governance_actions_signature_request_idx").on(e.signatureRequestId),ne("governance_actions_supersedes_idx").on(e.supersedesActionId),ne("governance_actions_historical_idx").on(e.entityId,e.effectiveDate).where(Y`origin_is_historical = true`),ne("governance_actions_active_idx").on(e.entityId,e.status).where(Y`voided_at IS NULL`)]),sD=t5("governance_action_items",{id:tM("id").primaryKey().defaultRandom(),actionId:tM("action_id").notNull().references(()=>sA.id,{onDelete:"cascade"}),ordinal:eB("ordinal").notNull().default(1),title:tT("title").notNull(),body:tT("body"),itemType:tT("item_type").notNull().default("RESOLUTION_TEXT"),targetEntityRef:eY("target_entity_ref").$type(),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_action_items_action_idx").on(e.actionId),nt("governance_action_items_action_ordinal_idx").on(e.actionId,e.ordinal)]);t5("governance_votes",{id:tM("id").primaryKey().defaultRandom(),actionId:tM("action_id").notNull().references(()=>
1sA.id,{onDelete:"cascade"}),itemId:tM("item_id").references(()=>sD.id,{onDelete:"cascade"}),voterPartyId:tM("voter_party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),voterSeatId:tM("voter_seat_id").references(()=>sh.id,{onDelete:"set null"}),voterHolderId:tM("voter_holder_id").references(()=>sx.id,{onDelete:"set null"}),vote:sN("vote").notNull(),weight:td("weight",{precision:18,scale:6}).notNull().default("1"),signatureSignerId:tM("signature_signer_id").references(()=>ro.id,{onDelete:"set null"}),votedAt:tj("voted_at"),note:tT("note"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("governance_votes_action_idx").on(e.actionId),ne("governance_votes_party_idx").on(e.voterPartyId),ne("governance_votes_seat_idx").on(e.voterSeatId),ne("governance_votes_holder_idx").on(e.voterHolderId),ne("governance_votes_signature_signer_idx").on(e.signatureSignerId),nt("governance_votes_action_party_item_idx").on(e.actionId,e.voterPartyId,e.itemId)]);let sw=L("governance_meeting_status",["SCHEDULED","IN_PROGRESS","HELD","CANCELLED","ADJOURNED"]),sE=t5("governance_meetings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),bodyId:tM("body_id").notNull().references(()=>sb.id,{onDelete:"cascade"}),title:tT("title").notNull(),scheduledFor:tj("scheduled_for").notNull(),heldAt:tj("held_at"),location:tT("location"),status:sw("status").notNull().default("SCHEDULED"),agenda:tT("agenda"),notes:tT("notes"),quorumMet:ef("quorum_met"),minutesActionId:tM("minutes_action_id").references(()=>sA.id,{onDelete:"set null"}),createdBy:tM("created_by"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_meetings_entity_idx").on(e.entityId),ne("governance_meetings_body_idx").on(e.bodyId),ne("governance_meetings_status_idx").on(e.entityId,e.status),ne("governance_meetings_scheduled_idx").on(e.entityId,e.scheduledFor),ne("governance_meetings_minutes_action_idx").on(e.minutesActionId)]),sR=L("governance_attendee_role",["ATTENDEE","CHAIR","SECRETARY","GUEST"]);t5("governance_meeting_attendees",{id:tM("id").primaryKey().defaultRandom(),meetingId:tM("meeting_id").notNull().references(()=>sE.id,{onDelete:"cascade"}),partyId:tM("party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),role:sR("role").notNull().default("ATTENDEE"),present:ef("present").notNull().default(!1),arrivedAt:tj("arrived_at"),departedAt:tj("departed_at"),proxyForPartyId:tM("proxy_for_party_id").references(()=>sg.id,{onDelete:"set null"}),capacity:tT("capacity"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("governance_meeting_attendees_meeting_idx").on(e.meetingId),ne("governance_meeting_attendees_party_idx").on(e.partyId),ne("governance_meeting_attendees_proxy_idx").on(e.proxyForPartyId),nt("governance_meeting_attendees_meeting_party_idx").on(e.meetingId,e.partyId)]);let sk=L("compliance_jurisdiction_kind",["formation","foreign_qualification","payroll_only","sales_tax","other"]),sT=L("compliance_jurisdiction_status",["active","inactive"]),sS=L("compliance_obligation_status",["upcoming","due","overdue","filed","waived","superseded"]),sC=L("compliance_obligation_source",["tier1","tier2","tier3_license"]);t5("entity_compliance_profile",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),delawareAuthorizedShares:tT("delaware_authorized_shares"),delawareGrossAssets:tT("delaware_gross_assets"),registeredAgentPartyId:tM("registered_agent_party_id").references(()=>sg.id,{onDelete:"set null"}),accountCodeOverrides:eY("account_code_overrides").$type(),franchiseTaxFeeAccountId:tM("franchise_tax_fee_account_id").references(()=>nU.id,{onDelete:"set null"}),licensePermitFeeAccountId:tM("license_permit_fee_account_id").references(()=>nU.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("entity_compliance_profile_agent_idx").on(e.registeredAgentPartyId)]),t5("compliance_jurisdictions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),jurisdictionCode:tT("jurisdiction_code").notNull(),kind:sk("kind").notNull(),registeredAt:eS("registered_at"),registeredAgentPartyId:tM("registered_agent_party_id").references(()=>sg.id,{onDelete:"set null"}),status:sT("status").notNull().default("active"),notes:tT("notes"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("compliance_jurisdictions_entity_idx").on(e.entityId),nt("compliance_jurisdictions_entity_jurisdiction_idx").on(e.entityId,e.jurisdictionCode)]),t5("compliance_obligation_definitions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),code:tT("code").notNull(),label:tT("label").notNull(),jurisdiction:tT("jurisdiction").notNull(),appliesWhen:eY("applies_when").$type().notNull(),frequency:tT("frequency").notNull(),dueDateRule:eY("due_date_rule").$type().notNull(),inputsRequired:eY("inputs_required").$type(),feeFormula:tT("fee_formula"),defaultAccountCode:tT("default_account_code"),active:ef("active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("compliance_obligation_definitions_entity_idx").on(e.entityId),nt("compliance_obligation_definitions_entity_code_idx").on(e.entityId,e.code)]);let sP=t5("compliance_licenses",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),issuingAuthority:tT("issuing_authority"),jurisdictionCode:tT("jurisdiction_code").notNull(),issuedAt:eS("issued_at"),expiresAt:eS("expires_at").notNull(),notes:tT("notes"),active:ef("active").notNull().default(!0),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("compliance_licenses_entity_idx").on(e.entityId),ne("compliance_licenses_entity_expires_idx").on(e.entityId,e.expiresAt)]),sO=t5("compliance_obligations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),definitionCode:tT("definition_code").notNull(),source:sC("source").notNull(),licenseId:tM("license_id").references(()=>sP.id,{onDelete:"set null"}),periodKey:tT("period_key").notNull(),label:tT("label").notNull(),jurisdiction:tT("jurisdiction").notNull(),nextDueAt:eS("next_due_at").notNull(),status:sS("status").notNull().default("upcoming"),inputsSnapsh
1ot:tT("inputs_snapshot"),derivedAt:tj("derived_at").notNull().defaultNow(),lastFactsHash:tT("last_facts_hash").notNull(),lastReminderAt:tj("last_reminder_at"),waiveReason:tT("waive_reason"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("compliance_obligations_entity_idx").on(e.entityId),ne("compliance_obligations_entity_due_idx").on(e.entityId,e.nextDueAt),ne("compliance_obligations_entity_status_idx").on(e.entityId,e.status),nt("compliance_obligations_entity_code_period_idx").on(e.entityId,e.definitionCode,e.periodKey)]);t5("compliance_filings",{id:tM("id").primaryKey().defaultRandom(),obligationId:tM("obligation_id").notNull().references(()=>sO.id,{onDelete:"restrict"}),filedAt:eS("filed_at").notNull(),filedBy:tM("filed_by"),confirmationNumber:tT("confirmation_number"),feeAmount:tT("fee_amount"),journalEntryId:tM("journal_entry_id").references(()=>nV.id,{onDelete:"set null"}),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),governanceActionId:tM("governance_action_id").references(()=>sA.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("compliance_filings_obligation_idx").on(e.obligationId),ne("compliance_filings_journal_idx").on(e.journalEntryId)]);let sK=L("governance_filing_kind",["ARTICLES","BYLAWS","OPERATING_AGREEMENT","LPA","TRUST_INSTRUMENT","ANNUAL_REPORT","BOI_REPORT","CONFLICT_OF_INTEREST","DBA","IRS_DETERMINATION","OTHER"]),sL=L("governance_filing_status",["DRAFT","FILED","DUE","OVERDUE","NA"]);t5("governance_filings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),kind:sK("kind").notNull(),title:tT("title").notNull(),jurisdiction:tT("jurisdiction"),filedAt:eS("filed_at"),dueAt:eS("due_at"),periodCovered:tT("period_covered"),referenceNumber:tT("reference_number"),notes:tT("notes"),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),status:sL("status").notNull().default("DRAFT"),reminderDays:eB("reminder_days").notNull().default(30),lastReminderAt:tj("last_reminder_at"),recurrence:tT("recurrence"),createdBy:tM("created_by"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("governance_filings_entity_idx").on(e.entityId),ne("governance_filings_status_idx").on(e.entityId,e.status),ne("governance_filings_kind_idx").on(e.entityId,e.kind),ne("governance_filings_due_idx").on(e.entityId,e.dueAt),ne("governance_filings_document_idx").on(e.documentId)]),t5("hd_ticket_time_entries",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),ticketId:tM("ticket_id").notNull().references(()=>rI.id,{onDelete:"cascade"}),employeeId:tM("employee_id"),hours:tT("hours").notNull(),billable:ef("billable").notNull().default(!1),postedToProjectTimeEntryId:tM("posted_to_project_time_entry_id"),eventId:tM("event_id").references(()=>nB.id),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("hd_ticket_time_entries_entity_idx").on(e.entityId),ne("hd_ticket_time_entries_ticket_idx").on(e.ticketId),ne("hd_ticket_time_entries_event_idx").on(e.eventId)]);let sq=L("cap_table_security_kind",["COMMON","PREFERRED","OPTION","RSU","RSA","WARRANT","SAFE","CONVERTIBLE_NOTE","LLC_UNIT","PROFITS_INTEREST","FUND_LP_INTEREST","FUND_GP_INTEREST"]),sj=L("cap_table_issuance_lot_form",["BOOK_ENTRY","CERTIFICATED","MIXED"]),sU=L("cap_table_section_83b_status",["NOT_APPLICABLE","PENDING","FILED","NOT_FILED"]),sB=L("cap_table_share_certificate_status",["OUTSTANDING","CANCELLED","LOST","REPLACED","SURRENDERED_TO_BOOK_ENTRY"]),sM=t5("cap_table_securities",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),governanceHolderClassId:tM("governance_holder_class_id").references(()=>sv.id,{onDelete:"set null"}),kind:sq("kind").notNull(),name:tT("name").notNull(),parValueCents:tT("par_value_cents"),authorizedQty:tT("authorized_qty"),currency:tT("currency").notNull().default("USD"),authorizingActionId:tM("authorizing_action_id").references(()=>sA.id,{onDelete:"restrict"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_securities_entity_idx").on(e.entityId),ne("cap_table_securities_class_idx").on(e.governanceHolderClassId),ne("cap_table_securities_kind_idx").on(e.entityId,e.kind),ne("cap_table_securities_action_idx").on(e.authorizingActionId),nt("cap_table_securities_entity_name_idx").on(e.entityId,e.name)]);t5("cap_table_409a_valuations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),valuationDate:eS("valuation_date").notNull(),fmvPerShareCents:tT("fmv_per_share_cents").notNull(),methodology:tT("methodology"),source:tT("source"),expiresAt:eS("expires_at"),boardActionId:tM("board_action_id").references(()=>sA.id,{onDelete:"set null"}),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_409a_entity_idx").on(e.entityId),ne("cap_table_409a_date_idx").on(e.entityId,e.valuationDate),ne("cap_table_409a_action_idx").on(e.boardActionId)]),t5("cap_table_holdings",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"cascade"}),qtyVested:tT("qty_vested"),qtyUnvested:tT("qty_unvested"),qtyExercised:tT("qty_exercised"),recomputedAt:tj("recomputed_at").notNull().defaultNow(),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_holdings_entity_idx").on(e.entityId),ne("cap_table_holdings_holder_idx").on(e.governanceHolderId),ne("cap_table_holdings_security_idx").on(e.securityId),nt("cap_table_holdings_unique_idx").on(e.governanceHolderId,e.securityId)]);let sF=t5("cap_table_issuance_lots",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),qty:tT("qty").notNull(),pricePerShareCents:tT("price_per_share_cents"),proceedsCents:tT("proceeds_cents"),parPortionCents:tT("par_portion_cents"),apicPortionCents:tT("apic_portion_cents"),issueDate:eS("issue_date").notNull(),currency:tT("currency").notNull().default("USD"),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),vestingScheduleId:tM("vesting_schedule_id").references(()=>s$.id,{onDelete:"set null"}),vestingStartDate:eS("vesting_start_date"),equityPlanId:tM("equity_plan_id"),form:sj("form").notNull().default("BOOK_ENTRY"),section83bStatus:sU("section_83b_status").notNull().default("NOT_APPLICABLE"),section83bFiledDate:eS("section_83b_filed_date"),section83bDocumentId:tM("section_83b_document_id").references(()=>a9.id,{onDelete:"set null"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),voidedAt:tj("voided_at"),voidedBy:tM("voided_by"),voidedReason:tT("voided_reason"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_issuance_lots_entity_idx").on(e.entityId),ne("cap_table_issuance_lots_security_idx").on(e.securityId),ne("cap_table_issuance_lots_holder_idx").on(e.governanceHolderId),ne("cap_table_issuance_lots_action_idx").on(e.authorizingActionId),ne("cap_table_issuance_lots_event_idx").on(e.eventId),ne("cap_table_issuance_lots_vesting_schedule_idx").on(e.vestingScheduleId),ne("cap_table_issuance_lots_equity_plan_idx").on(e.equityPlanId),ne("cap_table_issuance_lots_date_idx").on(e.entityId,e.issueDate),ne("cap_table_issuance_lots_active_idx").on(e.entityId,e.issueDate).where(Y`voided_at IS NULL`)]);t5("cap_table_buybacks",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),fromGovernanceHolderId:tM("from_governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),qty:tT("qty").notNull(),cashPaidCents:tT("cash_paid_cents").notNull(),buybackDate:eS("buyback_date").notNull(),currency:tT("currency").notNull().default("USD"),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_buybacks_entity_idx").on(e.entityId),ne("cap_table_buybacks_security_idx").on(e.securityId),ne("cap_table_buybacks_holder_idx").on(e.fromGovernanceHolderId),ne("cap_table_buybacks_action_idx").on(e.authorizingActionId),ne("cap_table_buybacks_event_idx").on(e.eventId)]),t5("cap_table_capital_contributions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),amountCents:tT("amount_cents").notNull(),contributionDate:eS("contribution_date").notNull(),currency:tT("currency").notNull().default("USD"),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_capital_contributions_entity_idx").on(e.entityId),ne("cap_table_capital_contributions_holder_idx").on(e.governanceHolderId),ne("cap_table_capital_contributions_security_idx").on(e.securityId),ne("cap_table_capital_contributions_action_idx").on(e.authorizingActionId),ne("cap_table_capital_contributions_event_idx").on(e.eventId)]);let sV=L("cap_table_vesting_frequency",["MONTHLY","QUARTERLY","ANNUAL"]),sH=L("cap_table_acceleration_kind",["NONE","SINGLE_TRIGGER","DOUBLE_TRIGGER"]),s$=t5("cap_table_vesting_schedules",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),cliffMonths:tT("cliff_months").notNull(),totalMonths:tT("total_months").notNull(),frequency:sV("frequency").notNull().default("MONTHLY"),accelerationOnChangeOfControl:sH("acceleration_on_change_of_control").notNull().default("NONE"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_vesting_schedules_entity_idx").on(e.entityId),nt("cap_table_vesting_schedules_name_idx").on(e.entityId,e.name)]),sG=t5("cap_table_grants",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),grantNumber:tT("grant_number").notNull(),grantDate:eS("grant_date").notNull(),qty:tT("qty").notNull(),strikePriceCents:tT("strike_price_cents"),fmvAtGrantCents:tT("fmv_at_grant_cents"),fairValuePerOptionCents:tT("fair_value_per_option_cents"),vestingScheduleId:tM("vesting_schedule_id").references(()=>s$.id,{onDelete:"set null"}),vestingStartDate:eS("vesting_start_date"),expirationDate:eS("expiration_date"),iso:ef("iso").notNull().default(!1),equityPlanId:tM("equity_plan_id"),section83bStatus:sU("section_83b_status").notNull().default("NOT_APPLICABLE"),section83bFiledDate:eS("section_83b_filed_date"),section83bDocumentId:tM("section_83b_document_id").references(()=>a9.id,{onDelete:"set null"}),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),signatureRequestId:tM("signature_request_id").references(()=>ri.id,{onDelete:"set null"}),closed:ef("closed").notNull().default(!1),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_grants_entity_idx").on(e.entityId),ne("cap_table_grants_security_idx").on(e.securityId),ne("cap_table_grants_holder_idx").on(e.governanceHolderId),ne("cap_table_grants_action_idx").on(e.authorizingActionId),ne("cap_table_grants_vesting_schedule_idx").on(e.vestingScheduleId),ne("cap_table_grants_equity_plan_idx").on(e.equityPlanId),ne("cap_table_grants_grant_date_idx").on(e.entityId,e.grantDate),nt("cap_table_grants_entity_grant_number_uidx").on(e.entityId,e.grantNumber)]);t5("cap_table_vesting_events",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),grantId:tM("grant_id").notNull().references(()=>sG.id,{onDelete:"cascade"}),vestingDate:eS("vesting_date").notNull(),qtyVested:tT("qty_vested").notNull(),expenseAmountCents:tT("expense_amount_cents").notNull(),posted:ef("posted").notNull().default(!1),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_vesting_events_entity_idx").on(e.entityId),ne("cap_table_vesting_events_grant_idx").on(e.grantId),ne("cap_table_vesting_events_event_idx").on(e.eventId),nt("cap_table_vesting_events_grant_date_idx").on(e.grantId,e.vestingDate)]),t5("cap_table_issuance_vesting_events",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),issuanceLotId:tM("issuance_lot_id").notNull().references(()=>sF.id,{onDelete:"cascade"}),vestingDate:eS("vesting_date").notNull(),qtyVested:tT("qty_vested").notNull(),posted:ef("posted").notNull().default(!1),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_issuance_vesting_events_entity_idx").on(e.entityId),ne("cap_table_issuance_vesting_events_lot_idx").on(e.issuanceLotId),nt("cap_table_issuance_vesting_events_lot_date_idx").on(e.issuanceLotId,e.vestingDate)]);let sz=L("cap_table_grant_modification_kind",["REPRICE","ACCELERATE","EXTEND_EXERCISE_WINDOW","CANCEL"]);t5("cap_table_grant_modifications",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),grantId:tM("grant_id").notNull().references(()=>sG.id,{onDelete:"cascade"}),kind:sz("kind").notNull(),effectiveDate:eS("effective_date").notNull(),incrementalFairValueCents:tT("incremental_fair_value_cents").notNull(),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_grant_modifications_entity_idx").on(e.entityId),ne("cap_table_grant_modifications_grant_idx").on(e.grantId),ne("cap_table_grant_modifications_action_idx").on(e.authorizingActionId),ne("cap_table_grant_modifications_event_idx").on(e.eventId)]),t5("cap_table_exercises",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),grantId:tM("grant_id").notNull().references(()=>sG.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),exerciseDate:eS("exercise_date").notNull(),qty:tT("qty").notNull(),cashPaidCents:tT("cash_paid_cents").notNull(),fmvAtExerciseCents:tT("fmv_at_exercise_cents"),disqualifyingDisposition:ef("disqualifying_disposition").notNull().default(!1),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_exercises_entity_idx").on(e.entityId),ne("cap_table_exercises_grant_idx").on(e.grantId),ne("cap_table_exercises_holder_idx").on(e.governanceHolderId),ne("cap_table_exercises_event_idx").on(e.eventId),ne("cap_table_exercises_date_idx").on(e.entityId,e.exerciseDate)]),t5("cap_table_rsu_settlements",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),grantId:tM("grant_id").notNull().references(()=>sG.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),settlementDate:eS("settlement_date").notNull(),qty:tT("qty").notNull(),settlementAmountCents:tT("settlement_amount_cents"),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_rsu_settlements_entity_idx").on(e.entityId),ne("cap_table_rsu_settlements_grant_idx").on(e.grantId),ne("cap_table_rsu_settlements_holder_idx").on(e.governanceHolderId),ne("cap_table_rsu_settlements_event_idx").on(e.eventId)]),t5("cap_table_forfeitures",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),grantId:tM("grant_id").notNull().references(()=>sG.id,{onDelete:"restrict"}),forfeitureDate:eS("forfeiture_date").notNull(),qty:tT("qty").notNull(),reversalAmountCents:tT("reversal_amount_cents").notNull(),reason:tT("reason"),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_forfeitures_entity_idx").on(e.entityId),ne("cap_table_forfeitures_grant_idx").on(e.grantId),ne("cap_table_forfeitures_event_idx").on(e.eventId)]);let sQ=L("cap_table_safe_classification",["ASC_480_LIABILITY","EQUITY_TREATED"]),sY=t5("cap_table_convertible_terms",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"cascade"}),valuationCapCents:tT("valuation_cap_cents"),discountPct:tT("discount_pct"),mfn:ef("mfn").notNull().default(!1),interestRatePct:tT("interest_rate_pct"),maturityDate:eS("maturity_date"),principalCents:tT("principal_cents"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_convertible_terms_entity_idx").on(e.entityId),nt("cap_table_convertible_terms_security_idx").on(e.securityId)]),sW=t5("cap_table_safe_issuances",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),proceedsCents:tT("proceeds_cents").notNull(),issueDate:eS("issue_date").notNull(),currency:tT("currency").notNull().default("USD"),convertibleTermsId:tM("convertible_terms_id").references(()=>sY.id,{onDelete:"set null"}),liabilityClassification:sQ("liability_classification").notNull().default("ASC_480_LIABILITY"),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),draftDocumentId:tM("draft_document_id").references(()=>a9.id,{onDelete:"set null"}),signedDocumentId:tM("signed_document_id").references(()=>a9.id,{onDelete:"set null"}),signatureRequestId:tM("signature_request_id").references(()=>ri.id,{onDelete:"set null"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_safe_issuances_entity_idx").on(e.entityId),ne("cap_table_safe_issuances_security_idx").on(e.securityId),ne("cap_table_safe_issuances_holder_idx").on(e.governanceHolderId),ne("cap_table_safe_issuances_action_idx").on(e.authorizingActionId),ne("cap_table_safe_issuances_event_idx").on(e.eventId)]),sJ=t5("cap_table_note_issuances",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),proceedsCents:tT("proceeds_cents").notNull(),issueDate:eS("issue_date").notNull(),currency:tT("currency").notNull().default("USD"),convertibleTermsId:tM("convertible_terms_id").references(()=>sY.id,{onDelete:"set null"}),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),draftDocumentId:tM("draft_document_id").references(()=>a9.id,{onDelete:"set null"}),signedDocumentId:tM("signed_document_id").references(()=>a9.id,{onDelete:"set null"}),signatureRequestId:tM("signature_request_id").references(()=>ri.id,{onDelete:"set null"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_note_issuances_entity_idx").on(e.entityId),ne("cap_table_note_issuances_security_idx").on(e.securityId),ne("cap_table_note_issuances_holder_idx").on(e.governanceHolderId),ne("cap_table_note_issuances_action_idx").on(e.authorizingActionId),ne("cap_table_note_issuances_event_idx").on(e.eventId)]);t5("cap_table_note_interest_accruals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),noteIssuanceId:tM("note_issuance_id").notNull().references(()=>sJ.id,{onDelete:"cascade"}),accrualDate:eS("accrual_date").notNull(),interestAmountCents:tT("interest_amount_cents").notNull(),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cap_table_note_interest_entity_idx").on(e.entityId),ne("cap_table_note_interest_note_idx").on(e.noteIssuanceId),ne("cap_table_note_interest_event_idx").on(e.eventId),nt("cap_table_note_interest_unique_idx").on(e.noteIssuanceId,e.accrualDate)]),t5("cap_table_conversions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),safeIssuanceId:tM("safe_issuance_id").references(()=>sW.id,{onDelete:"restrict"}),noteIssuanceId:tM("note_issuance_id").references(()=>sJ.id,{onDelete:"restrict"}),outputSecurityId:tM("output_security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),conversionDate:eS("conversion_date").notNull(),ratio:tT("ratio").notNull(),fmvUsedCents:tT("fmv_used_cents"),parPortionCents:tT("par_portion_cents"),apicPortionCents:tT("apic_portion_cents"),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_conversions_entity_idx").on(e.entityId),ne("cap_table_conversions_safe_idx").on(e.safeIssuanceId),ne("cap_table_conversions_note_idx").on(e.noteIssuanceId),ne("cap_table_conversions_output_idx").on(e.outputSecurityId),ne("cap_table_conversions_holder_idx").on(e.governanceHolderId),ne("cap_table_conversions_action_idx").on(e.authorizingActionId),ne("cap_table_conversions_event_idx").on(e.eventId)]),t5("cap_table_dividend_accruals",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),accrualDate:eS("accrual_date").notNull(),totalAmountCents:tT("total_amount_cents").notNull(),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cap_table_dividend_accruals_entity_idx").on(e.entityId),ne("cap_table_dividend_accruals_security_idx").on(e.securityId),ne("cap_table_dividend_accruals_event_idx").on(e.eventId)]),t5("cap_table_equity_plans",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),adoptedDate:eS("adopted_date").notNull(),authorizingActionId:tM("authorizing_action_id").references(()=>sA.id,{onDelete:"restrict"}),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),authorizedQty:tT("authorized_qty").notNull(),status:tT("status").notNull().default("ACTIVE"),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_equity_plans_entity_idx").on(e.entityId),ne("cap_table_equity_plans_security_idx").on(e.securityId)]),t5("cap_table_share_certificates",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),certNumber:tT("cert_number").notNull(),status:sB("status").notNull().default("OUTSTANDING"),issuanceLotId:tM("issuance_lot_id").notNull().references(()=>sF.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),sharesRepresented:tT("shares_represented").notNull(),issueDate:eS("issue_date").notNull(),cancelledAt:tj("cancelled_at"),cancellationReason:tT("cancellation_reason"),replacementOfId:tM("replacement_of_id"),documentId:tM("document_id").references(()=>a9.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("cap_table_share_certificates_entity_number_uidx").on(e.entityId,e.certNumber),ne("cap_table_share_certificates_entity_idx").on(e.entityId),ne("cap_table_share_certificates_lot_idx").on(e.issuanceLotId),ne("cap_table_share_certificates_holder_idx").on(e.governanceHolderId),ne("cap_table_share_certificates_status_idx").on(e.entityId,e.status)]);let sX=L("cap_table_equity_distribution_kind",["CASH_DIVIDEND","SCORP_DISTRIBUTION"]),sZ=L("cap_table_equity_distribution_status",["DRAFT","ALLOCATED","PARTIALLY_PAID","PAID","VOID"]),s0=L("cap_table_equity_distribution_qty_basis",["VESTED_ONLY","OUTSTANDING"]),s1=L("cap_table_equity_distribution_alloc_payment_status",["UNPAID","PAID","WAIVED"]),s2=t5("cap_table_equity_distributions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),kind:sX("kind").notNull(),status:sZ("status").notNull().default("DRAFT"),declarationDate:eS("declaration_date").notNull(),recordDate:eS("record_date").notNull(),paymentDate:eS("payment_date"),totalAmountCents:tT("total_amount_cents").notNull(),perShareCents:tT("per_share_cents"),qtyBasis:s0("qty_basis").notNull().default("VESTED_ONLY"),allocationMethod:tT("allocation_method").notNull().default("PRO_RATA_OWNERSHIP"),authorizingActionId:tM("authorizing_action_id").references(()=>sA.id,{onDelete:"restrict"}),recordDateSnapshot:eY("record_date_snapshot"),declaredEventId:tM("declared_event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),voidedAt:tj("voided_at"),voidedByUserId:tM("voided_by_user_id"),voidReason:tT("void_reason"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_equity_distributions_entity_idx").on(e.entityId),ne("cap_table_equity_distributions_security_idx").on(e.securityId),ne("cap_table_equity_distributions_status_idx").on(e.entityId,e.status),ne("cap_table_equity_distributions_action_idx").on(e.authorizingActionId),ne("cap_table_equity_distributions_declared_event_idx").on(e.declaredEventId)]);t5("cap_table_equity_distribution_allocations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),distributionId:tM("distribution_id").notNull().references(()=>s2.id,{onDelete:"cascade"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),sharesOnRecordDate:tT("shares_on_record_date").notNull(),ownershipBps:tT("ownership_bps").notNull(),amountCents:tT("amount_cents").notNull(),paymentStatus:s1("payment_status").notNull().default("UNPAID"),paidAt:tj("paid_at"),paymentReference:tT("payment_reference"),paidEventId:tM("paid_event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_equity_distribution_allocs_entity_idx").on(e.entityId),ne("cap_table_equity_distribution_allocs_dist_idx").on(e.distributionId),ne("cap_table_equity_distribution_allocs_holder_idx").on(e.governanceHolderId),nt("cap_table_equity_distribution_allocs_dist_holder_uidx").on(e.distributionId,e.governanceHolderId),ne("cap_table_equity_distribution_allocs_paid_event_idx").on(e.paidEventId)]);let s4=L("cap_table_transfer_type",["SECONDARY","GIFT","INHERITANCE"]),s6=L("cap_table_s_corp_holder_category",["US_INDIVIDUAL","RESIDENT_ALIEN","ESTATE","BANKRUPTCY_ESTATE","GRANTOR_TRUST","TESTAMENTARY_TRUST","VOTING_TRUST","QSST","ESBT","TAX_EXEMPT_501C3","QUALIFIED_PLAN_401A","GRANDFATHERED_IRA","DISREGARDED_ENTITY","INELIGIBLE_PARTNERSHIP","INELIGIBLE_CORPORATION","INELIGIBLE_NRA","INELIGIBLE_OTHER","UNKNOWN"]),s8=L("cap_table_s_corp_residency",["US_CITIZEN","US_RESIDENT_ALIEN","NONRESIDENT_ALIEN","NOT_APPLICABLE","UNKNOWN"]),s5=L("cap_table_trust_election_status",["NOT_REQUIRED","FILED","MISSING","UNKNOWN"]),s3=L("cap_table_family_relationship",["SPOUSE","FORMER_SPOUSE","PARENT","CHILD"]),s9=L("cap_table_transfer_request_status",["PROPOSED","APPROVED","REJECTED","CANCELLED","APPLIED"]),s7=t5("cap_table_transfers",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),fromGovernanceHolderId:tM("from_governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),toGovernanceHolderId:tM("to_governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),transferDate:eS("transfer_date").notNull(),qty:tT("qty").notNull(),considerationCents:tT("consideration_cents"),transferType:s4("transfer_type").notNull(),boardConsentActionId:tM("board_consent_action_id").references(()=>sA.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_transfers_entity_idx").on(e.entityId),ne("cap_table_transfers_from_idx").on(e.fromGovernanceHolderId),ne("cap_table_transfers_to_i
1dx").on(e.toGovernanceHolderId),ne("cap_table_transfers_security_idx").on(e.securityId)]);t5("cap_table_holder_tax_profiles",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),partyId:tM("party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),holderCategory:s6("holder_category").notNull().default("UNKNOWN"),residency:s8("residency").notNull().default("UNKNOWN"),trustElectionStatus:s5("trust_election_status").notNull().default("UNKNOWN"),iraGrandfathered:ef("ira_grandfathered").notNull().default(!1),eligibilityClockStart:eS("eligibility_clock_start"),eligibilityClockKind:tT("eligibility_clock_kind"),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("cap_table_holder_tax_profiles_entity_party_uidx").on(e.entityId,e.partyId),ne("cap_table_holder_tax_profiles_entity_idx").on(e.entityId)]),t5("cap_table_family_links",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),partyId:tM("party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),relatedPartyId:tM("related_party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),relationship:s3("relationship").notNull(),effectiveFrom:eS("effective_from"),effectiveTo:eS("effective_to"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("cap_table_family_links_pair_rel_uidx").on(e.entityId,e.partyId,e.relatedPartyId,e.relationship),ne("cap_table_family_links_entity_idx").on(e.entityId),ne("cap_table_family_links_party_idx").on(e.partyId)]),t5("cap_table_transfer_requests",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),fromGovernanceHolderId:tM("from_governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),toGovernanceHolderId:tM("to_governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),transferDate:eS("transfer_date").notNull(),qty:tT("qty").notNull(),considerationCents:tT("consideration_cents"),transferType:s4("transfer_type").notNull(),boardConsentActionId:tM("board_consent_action_id").references(()=>sA.id,{onDelete:"set null"}),status:s9("status").notNull().default("PROPOSED"),eligibilitySnapshot:eY("eligibility_snapshot"),decidedByUserId:tM("decided_by_user_id"),decidedAt:tj("decided_at"),decisionNotes:tT("decision_notes"),appliedTransferId:tM("applied_transfer_id").references(()=>s7.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_transfer_requests_entity_idx").on(e.entityId),ne("cap_table_transfer_requests_status_idx").on(e.entityId,e.status)]);let _e=t5("cap_table_waterfall_scenarios",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),exitValueCents:tT("exit_value_cents").notNull(),scenario:eY("scenario").$type(),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_waterfall_scenarios_entity_idx").on(e.entityId),nt("cap_table_waterfall_scenarios_name_idx").on(e.entityId,e.name)]);t5("cap_table_waterfall_runs",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),scenarioId:tM("scenario_id").notNull().references(()=>_e.id,{onDelete:"cascade"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),payoutCents:tT("payout_cents").notNull(),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cap_table_waterfall_runs_entity_idx").on(e.entityId),ne("cap_table_waterfall_runs_scenario_idx").on(e.scenarioId),ne("cap_table_waterfall_runs_holder_idx").on(e.governanceHolderId)]);let _t=t5("cap_table_lp_commitments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),fundSecurityId:tM("fund_security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),commitmentCents:tT("commitment_cents").notNull(),calledCents:tT("called_cents"),distributedCents:tT("distributed_cents"),gpCarryPct:tT("gp_carry_pct"),closedAt:eS("closed_at"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_lp_commitments_entity_idx").on(e.entityId),ne("cap_table_lp_commitments_holder_idx").on(e.governanceHolderId),ne("cap_table_lp_commitments_fund_idx").on(e.fundSecurityId)]),_n=t5("cap_table_capital_calls",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),fundSecurityId:tM("fund_security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),callNumber:eB("call_number").notNull(),callDate:eS("call_date").notNull(),totalAmountCents:tT("total_amount_cents").notNull(),dueDate:eS("due_date"),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("cap_table_capital_calls_entity_idx").on(e.entityId),ne("cap_table_capital_calls_fund_idx").on(e.fundSecurityId),ne("cap_table_capital_calls_action_idx").on(e.authorizingActionId),nt("cap_table_capital_calls_number_idx").on(e.fundSecurityId,e.callNumber)]);t5("cap_table_capital_call_allocations",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),capitalCallId:tM("capital_call_id").notNull().references(()=>_n.id,{onDelete:"cascade"}),commitmentId:tM("commitment_id").notNull().references(()=>_t.id,{onDelete:"restrict"}),allocationCents:tT("allocation_cents").notNull(),fundedAt:eS("funded_at"),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cap_table_capital_call_allocations_entity_idx").on(e.entityId),ne("cap_table_capital_call_allocations_call_idx").on(e.capitalCallId),ne("cap_table_capital_call_allocations_commitment_idx").on(e.commitmentId),ne("cap_table_capital_call_allocations_event_idx").on(e.eventId)]);let _d=L("cap_table_distribution_kind",["RETURN_OF_CAPITAL","PROFIT","PREFERRED_DIVIDEND","LIQUIDATION"]);t5("cap_table_distributions",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),governanceHolderId:tM("governance_holder_id").notNull().references(()=>sx.id,{onDelete:"restrict"}),securityId:tM("security_id").notNull().references(()=>sM.id,{onDelete:"restrict"}),distributionDate:eS("distribution_date").notNull(),totalCents:tT("total_cents").notNull(),kind:_d("kind").notNull(),authorizingActionId:tM("authorizing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),eventId:tM("event_id").references(()=>nB.id,{onDelete:"set null"}),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("cap_table_distributions_entity_idx").on(e.entityId),ne("cap_table_distributions_holder_idx").on(e.governanceHolderId),ne("cap_table_distributions_security_idx").on(e.securityId),ne("cap_table_distributions_action_idx").on(e.authorizingActionId),ne("cap_table_distributions_event_idx").on(e.eventId)]);let _a=L("fundraising_round_type",["PRE_SEED","SEED","SERIES_A","SERIES_B","SERIES_C","SERIES_D_PLUS","BRIDGE","EXTENSION","LP_COMMITMENT_PERIOD","OTHER"]),_i=L("fundraising_round_status",["PLANNING","OPEN","CLOSING","CLOSED","CANCELED"]),_o=t5("fundraising_rounds",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),name:tT("name").notNull(),roundType:_a("round_type").notNull(),targetAmountCents:tT("target_amount_cents"),instrumentSecurityId:tM("instrument_security_id").references(()=>sM.id,{onDelete:"set null"}),status:_i("status").notNull().default("PLANNING"),targetCloseDate:eS("target_close_date"),leadInvestorPartyId:tM("lead_investor_party_id").references(()=>sg.id,{onDelete:"set null"}),boardAuthorizingActionId:tM("board_authorizing_action_id").references(()=>sA.id,{onDelete:"set null"}),depositAccountId:tM("deposit_account_id").references(()=>dN.id,{onDelete:"set null"}),openedAt:tj("opened_at"),closedAt:tj("closed_at"),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_rounds_entity_idx").on(e.entityId),ne("fundraising_rounds_status_idx").on(e.entityId,e.status),ne("fundraising_rounds_lead_idx").on(e.leadInvestorPartyId),ne("fundraising_rounds_action_idx").on(e.boardAuthorizingActionId)]),_l=L("fundraising_pipeline_stage_kind",["open","won","lost"]),_r=t5("fundraising_pipeline_stages",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),roundId:tM("round_id").notNull().references(()=>_o.id,{onDelete:"cascade"}),name:tT("name").notNull(),sortOrder:eB("sort_order").notNull().default(0),defaultProbabilityPct:eB("default_probability_pct").notNull().default(0),kind:_l("kind").notNull().default("open"),systemKey:tT("system_key"),colorKey:tT("color_key"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_pipeline_stages_entity_idx").on(e.entityId),ne("fundraising_pipeline_stages_round_idx").on(e.roundId),nt("fundraising_pipeline_stages_round_name_idx").on(e.roundId,e.name),nt("fundraising_pipeline_stages_round_system_key_idx").on(e.roundId,e.systemKey)]),_s=t5("fundraising_pipeline_entries",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),roundId:tM("round_id").notNull().references(()=>_o.id,{onDelete:"cascade"}),legalPartyId:tM("legal_party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),governanceHolderId:tM("governance_holder_id").references(()=>sx.id,{onDelete:"set null"}),currentStageId:tM("current_stage_id").references(()=>_r.id,{onDelete:"set null"}),primaryInvestorContactId:tM("primary_investor_contact_id").references(()=>_c.id,{onDelete:"set null"}),passedReason:tT("passed_reason"),passedAt:tj("passed_at"),targetAmountCents:tT("target_amount_cents"),committedAmountCents:tT("committed_amount_cents"),wiredAmountCents:tT("wired_amount_cents"),lastTouchAt:tj("last_touch_at"),ownerUserId:tM("owner_user_id"),notes:tT("notes"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_pipeline_entries_entity_idx").on(e.entityId),ne("fundraising_pipeline_entries_round_idx").on(e.roundId),ne("fundraising_pipeline_entries_party_idx").on(e.legalPartyId),ne("fundraising_pipeline_entries_stage_idx").on(e.currentStageId),ne("fundraising_pipeline_entries_owner_idx").on(e.ownerUserId),nt("fundraising_pipeline_entries_round_party_idx").on(e.roundId,e.legalPartyId)]),__=L("fundraising_activity_kind",["EMAIL","CALL","MEETING","NOTE","STAGE_CHANGE","SIGNATURE_REQUESTED","SIGNATURE_COMPLETED","SIGNATURE_DECLINED"]),_u=L("fundraising_investor_contact_status",["active","archived"]),_c=t5("fundraising_investor_contacts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),legalPartyId:tM("legal_party_id").notNull().references(()=>sg.id,{onDelete:"cascade"}),personPartyId:tM("person_party_id").references(()=>sg.id,{onDelete:"set null"}),displayName:tT("display_name"),firstName:tT("first_name"),lastName:tT("last_name"),email:tT("email"),phone:tT("phone"),jobTitle:tT("job_title"),department:tT("department"),linkedinUrl:tT("linkedin_url"),notes:tT("notes"),status:_u("status").notNull().default("active"),isPrimary:ef("is_primary").notNull().default(!1),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_investor_contacts_entity_idx").on(e.entityId),ne("fundraising_investor_contacts_party_idx").on(e.entityId,e.legalPartyId),ne("fundraising_investor_contacts_party_status_idx").on(e.legalPartyId,e.status),ne("fundraising_investor_contacts_person_party_idx").on(e.personPartyId)]);t5("fundraising_pipeline_entry_contacts",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),entryId:tM("entry_id").notNull().references(()=>_s.id,{onDelete:"cascade"}),investorContactId:tM("investor_contact_id").notNull().references(()=>_c.id,{onDelete:"cascade"}),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("fundraising_pipeline_entry_contacts_entity_idx").on(e.entityId),ne("fundraising_pipeline_entry_contacts_entry_idx").on(e.entryId),ne("fundraising_pipeline_entry_contacts_contact_idx").on(e.investorContactId),nt("fundraising_pipeline_entry_contacts_entry_contact_idx").on(e.entryId,e.investorContactId)]),t5("fundraising_pipeline_activities",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),entryId:tM("entry_id").notNull().references(()=>_s.id,{onDelete:"cascade"}),kind:__("kind").notNull(),payload:eY("payload").$type(),occurredAt:tj("occurred_at").notNull().defaultNow(),actorIdentityId:tM("actor_identity_id"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("fundraising_pipeline_activities_entity_idx").on(e.entityId),ne("fundraising_pipeline_activities_entry_idx").on(e.entryId),ne("fundraising_pipeline_activities_kind_idx").on(e.entryId,e.kind),ne("fundraising_pipeline_activities_occurred_idx").on(e.entityId,e.occurredAt)]);let _p=t5("fundraising_data_rooms",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),roundId:tM("round_id").notNull().references(()=>_o.id,{onDelete:"cascade"}),documentsFolderId:tM("documents_folder_id").notNull().references(()=>re.id,{onDelete:"restrict"}),defaultExpiresAt:tj("default_expires_at"),requireNda:ef("require_nda").notNull().default(!0),ndaTemplateDocumentId:tM("nda_template_document_id").references(()=>a9.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_data_rooms_entity_idx").on(e.entityId),nt("fundraising_data_rooms_round_idx").on(e.roundId),ne("fundraising_data_rooms_folder_idx").on(e.documentsFolderId)]),_y=L("fundraising_data_room_access",["READ","READ_WATERMARKED","NONE"]),_m=t5("fundraising_data_room_grants",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),dataRoomId:tM("data_room_id").notNull().references(()=>_p.id,{onDelete:"cascade"}),legalPartyId:tM("legal_party_id").notNull().references(()=>sg.id,{onDelete:"restrict"}),accessLevel:_y("access_level").notNull().default("READ_WATERMARKED"),ndaSignatureRequestId:tM("nda_signature_request_id").references(()=>ri.id,{onDelete:"set null"}),ndaCompletedAt:tj("nda_completed_at"),ndaSignedDocumentId:tM("nda_signed_document_id").references(()=>a9.id,{onDelete:"set null"}),effectiveAt:tj("effective_at"),expiresAt:tj("expires_at"),documentsFolderGrantId:tM("documents_folder_grant_id"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_data_room_grants_entity_idx").on(e.entityId),ne("fundraising_data_room_grants_room_idx").on(e.dataRoomId),ne("fundraising_data_room_grants_party_idx").on(e.legalPartyId),nt("fundraising_data_room_grants_unique_idx").on(e.dataRoomId,e.legalPartyId)]);t5("fundraising_data_room_invites",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),grantId:tM("grant_id").notNull().references(()=>_m.id,{onDelete:"cascade"}),tokenHash:tT("token_hash").notNull(),expiresAt:tj("expires_at").notNull(),revokedAt:tj("revoked_at"),createdByIdentityId:tM("created_by_identity_id"),lastOpenedAt:tj("last_opened_at"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("fundraising_data_room_invites_entity_idx").on(e.entityId),ne("fundraising_data_room_invites_grant_idx").on(e.grantId),nt("fundraising_data_room_invites_token_hash_unique").on(e.tokenHash)]);let _f=L("fundraising_term_sheet_status",["DRAFT","READY_TO_SEND","SENT","SIGNED","DECLINED","EXPIRED"]);t5("fundraising_term_sheets",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),entryId:tM("entry_id").notNull().references(()=>_s.id,{onDelete:"cascade"}),templateDocumentId:tM("template_document_id").references(()=>a9.id,{onDelete:"set null"}),draftDocumentId:tM("draft_document_id").notNull().references(()=>a9.id,{onDelete:"restrict"}),signatureRequestId:tM("signature_request_id").references(()=>ri.id,{onDelete:"set null"}),sentAt:tj("sent_at"),signedAt:tj("signed_at"),signedDocumentId:tM("signed_document_id").references(()=>a9.id,{onDelete:"set null"}),completionCertificateDocumentId:tM("completion_certificate_document_id").references(()=>a9.id,{onDelete:"set null"}),status:_f("status").notNull().default("DRAFT"),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_term_sheets_entity_idx").on(e.entityId),ne("fundraising_term_sheets_entry_idx").on(e.entryId),ne("fundraising_term_sheets_signature_idx").on(e.signatureRequestId),ne("fundraising_term_sheets_status_idx").on(e.entityId,e.status)]);let _N=L("fundraising_commitment_instrument",["SAFE","SPA"]),_I=L("fundraising_commitment_status",["SOFT","SIGNED_SPA","SIGNED_SAFE","WIRED","CANCELED"]);t5("fundraising_commitments",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),entryId:tM("entry_id").notNull().references(()=>_s.id,{onDelete:"cascade"}),instrumentType:_N("instrument_type").notNull().default("SPA"),amountCents:tT("amount_cents").notNull(),instrumentDraftDocId:tM("instrument_draft_doc_id").references(()=>a9.id,{onDelete:"set null"}),instrumentSignatureRequestId:tM("instrument_signature_request_id").references(()=>ri.id,{onDelete:"set null"}),instrumentSignedDocId:tM("instrument_signed_doc_id").references(()=>a9.id,{onDelete:"set null"}),instrumentCompletionCertificateDocId:tM("instrument_completion_certificate_doc_id").references(()=>a9.id,{onDelete:"set null"}),status:_I("status").notNull().default("SOFT"),wiredAt:tj("wired_at"),safeIssuanceId:tM("safe_issuance_id").references(()=>sW.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_commitments_entity_idx").on(e.entityId),ne("fundraising_commitments_entry_idx").on(e.entryId),ne("fundraising_commitments_status_idx").on(e.entityId,e.status),ne("fundraising_commitments_signature_idx").on(e.instrumentSignatureRequestId),ne("fundraising_commitments_safe_issuance_idx").on(e.safeIssuanceId)]),t5("fundraising_closes",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),roundId:tM("round_id").notNull().references(()=>_o.id,{onDelete:"cascade"}),closeNumber:eB("close_number").notNull(),closeDate:eS("close_date").notNull(),totalRaisedCents:tT("total_raised_cents").notNull(),closingActionId:tM("closing_action_id").notNull().references(()=>sA.id,{onDelete:"restrict"}),closingActionSignatureRequestId:tM("closing_action_signature_request_id").references(()=>ri.id,{onDelete:"set null"}),capTableIssuanceEventId:tM("cap_table_issuance_event_id").references(()=>nB.id,{onDelete:"set null"}),metadata:eY("metadata"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("fundraising_closes_entity_idx").on(e.entityId),ne("fundraising_closes_round_idx").on(e.roundId),ne("fundraising_closes_action_idx").on(e.closingActionId),nt("fundraising_closes_round_number_idx").on(e.roundId,e.closeNumber)]);let _g=L("strategy_goal_level",["company","team","individual"]),_b=L("strategy_methodology",["okr","bsc","mbo"]),_h=L("strategy_objective_status",["draft","active","completed","archived"]),_v=L("strategy_initiative_status",["planned","active","done","blocked"]),_x=L("strategy_kr_metric_type",["number","percent","currency","custom"]),_A=t5("strategy_objectives",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),parentObjectiveId:tM("parent_objective_id").references(()=>_A.id,{onDelete:"set null"}),title:tT("title").notNull(),description:tT("description"),level:_g("level").notNull().default("company"),methodology:_b("methodology").notNull().default("okr"),status:_h("status").notNull().default("draft"),boardVisible:ef("board_visible").notNull().default(!1),timeframeLabel:tT("timeframe_label"),ownerEmployeeId:tM("owner_employee_id").references(()=>iM.id,{onDelete:"set null"}),departmentId:tM("department_id").references(()=>iF.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("strategy_objectives_entity_idx").on(e.entityId),ne("strategy_objectives_parent_idx").on(e.parentObjectiveId),ne("strategy_objectives_owner_idx").on(e.ownerEmployeeId),ne("strategy_objectives_board_idx").on(e.entityId,e.boardVisible)]),_D=t5("strategy_key_results",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),objectiveId:tM("objective_id").notNull().references(()=>_A.id,{onDelete:"cascade"}),title:tT("title").notNull(),metricType:_x("metric_type").notNull().default("number"),targetValue:td("target_value",{precision:20,scale:6}),currentValue:td("current_value",{precision:20,scale:6}),unit:tT("unit"),weight:td("weight",{precision:10,scale:4}).notNull().default("1"),sortOrder:eB("sort_order").notNull().default(0),ownerEmployeeId:tM("owner_employee_id").references(()=>iM.id,{onDelete:"set null"}),deadline:eS("deadline"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("strategy_key_results_entity_idx").on(e.entityId),ne("strategy_key_results_objective_idx").on(e.objectiveId)]);t5("strategy_initiatives",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>
1nP.id,{onDelete:"cascade"}),keyResultId:tM("key_result_id").notNull().references(()=>_D.id,{onDelete:"cascade"}),title:tT("title").notNull(),description:tT("description"),status:_v("status").notNull().default("planned"),linkedJobId:tM("linked_job_id").references(()=>op.id,{onDelete:"set null"}),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("strategy_initiatives_entity_idx").on(e.entityId),ne("strategy_initiatives_kr_idx").on(e.keyResultId),ne("strategy_initiatives_job_idx").on(e.linkedJobId)]),t5("strategy_check_ins",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id,{onDelete:"cascade"}),keyResultId:tM("key_result_id").notNull().references(()=>_D.id,{onDelete:"cascade"}),periodStart:eS("period_start").notNull(),periodEnd:eS("period_end").notNull(),submittedByUserId:tM("submitted_by_user_id").notNull(),previousValue:td("previous_value",{precision:20,scale:6}),newValue:td("new_value",{precision:20,scale:6}),confidence:eB("confidence"),narrative:tT("narrative"),createdAt:tj("created_at").notNull().defaultNow()},e=>[ne("strategy_check_ins_entity_idx").on(e.entityId),ne("strategy_check_ins_kr_idx").on(e.keyResultId),ne("strategy_check_ins_created_idx").on(e.entityId,e.createdAt)]),t5("strategy_entity_settings",{entityId:tM("entity_id").primaryKey().references(()=>nP.id,{onDelete:"cascade"}),settings:eY("settings").$type().notNull().default({}),updatedAt:tj("updated_at").notNull().defaultNow()});let _w=L("broker_environment",["PAPER","LIVE"]),_E=L("broker_asset_class",["stock","etf","option","other"]),_R=L("broker_order_source",["user","luca","external"]),_k=L("broker_position_event_type",["assignment","exercise","expiration","option_trade","dividend","split","cash","other"]),_T=L("broker_position_event_status",["confirmed","pending","superseded"]),_S=t5("broker_connections",{id:tM("id").primaryKey().defaultRandom(),entityId:tM("entity_id").notNull().references(()=>nP.id),treasuryAccountId:tM("treasury_account_id").notNull().references(()=>n7.id),broker:tT("broker").notNull(),environment:_w("environment").notNull(),credentialKind:tT("credential_kind").notNull(),credentials:tT("credentials").notNull(),brokerAccountId:tT("broker_account_id").notNull(),brokerAccountNumber:tT("broker_account_number"),status:tT("status").notNull().default("active"),accountSnapshot:tT("account_snapshot"),syncState:eY("sync_state").$type().notNull().default({}),lastSyncedAt:tj("last_synced_at"),lastSyncError:tT("last_sync_error"),reconciliationStatus:tT("reconciliation_status"),reconciliation:tT("reconciliation"),reconciledAt:tj("reconciled_at"),paperLedgerState:tT("paper_ledger_state"),positionAlertConfig:tT("position_alert_config"),positionAlertState:tT("position_alert_state"),connectedByUserId:tM("connected_by_user_id"),disconnectedAt:tj("disconnected_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[ne("broker_connections_entity_idx").on(e.entityId),ne("broker_connections_treasury_idx").on(e.treasuryAccountId),nt("broker_connections_active_env_idx").on(e.entityId,e.broker,e.environment).where(Y`status = 'active'`)]),_C=t5("broker_instruments",{id:tM("id").primaryKey().defaultRandom(),symbol:tT("symbol").notNull(),assetClass:_E("asset_class").notNull(),name:tT("name"),occSymbol:tT("occ_symbol"),underlyingSymbol:tT("underlying_symbol"),expirationDate:eS("expiration_date"),strikePrice:tT("strike_price"),optionType:tT("option_type"),multiplier:eB("multiplier").notNull().default(1),exerciseStyle:tT("exercise_style"),brokerAssetId:tT("broker_asset_id"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("broker_instruments_symbol_idx").on(e.symbol),ne("broker_instruments_underlying_idx").on(e.underlyingSymbol,e.expirationDate)]),_P=t5("broker_orders",{id:tM("id").primaryKey().defaultRandom(),connectionId:tM("connection_id").notNull().references(()=>_S.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id),brokerOrderId:tT("broker_order_id").notNull(),clientOrderId:tT("client_order_id"),replacesBrokerOrderId:tT("replaces_broker_order_id"),replacedByBrokerOrderId:tT("replaced_by_broker_order_id"),instrumentId:tM("instrument_id").references(()=>_C.id),symbol:tT("symbol"),orderClass:tT("order_class"),side:tT("side"),positionIntent:tT("position_intent"),orderType:tT("order_type"),timeInForce:tT("time_in_force"),qty:tT("qty"),notional:tT("notional"),filledQty:tT("filled_qty"),filledAvgPrice:tT("filled_avg_price"),limitPrice:tT("limit_price"),stopPrice:tT("stop_price"),status:tT("status").notNull(),source:_R("source").notNull().default("external"),brokerCreatedAt:tj("broker_created_at"),submittedAt:tj("submitted_at"),filledAt:tj("filled_at"),canceledAt:tj("canceled_at"),expiredAt:tj("expired_at"),replacedAt:tj("replaced_at"),brokerUpdatedAt:tj("broker_updated_at"),raw:tT("raw"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("broker_orders_conn_order_idx").on(e.connectionId,e.brokerOrderId),ne("broker_orders_conn_created_idx").on(e.connectionId,e.brokerCreatedAt),ne("broker_orders_entity_idx").on(e.entityId)]);t5("broker_order_legs",{id:tM("id").primaryKey().defaultRandom(),orderId:tM("order_id").notNull().references(()=>
1_P.id,{onDelete:"cascade"}),connectionId:tM("connection_id").notNull().references(()=>_S.id,{onDelete:"cascade"}),brokerOrderId:tT("broker_order_id").notNull(),instrumentId:tM("instrument_id").references(()=>_C.id),symbol:tT("symbol").notNull(),side:tT("side"),positionIntent:tT("position_intent"),ratioQty:tT("ratio_qty"),qty:tT("qty"),filledQty:tT("filled_qty"),filledAvgPrice:tT("filled_avg_price"),status:tT("status"),raw:tT("raw"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("broker_order_legs_conn_order_idx").on(e.connectionId,e.brokerOrderId),ne("broker_order_legs_order_idx").on(e.orderId)]),t5("broker_fills",{id:tM("id").primaryKey().defaultRandom(),connectionId:tM("connection_id").notNull().references(()=>_S.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id),executionId:tT("execution_id").notNull(),brokerActivityId:tT("broker_activity_id"),brokerOrderId:tT("broker_order_id").notNull(),orderId:tM("order_id").references(()=>_P.id),instrumentId:tM("instrument_id").notNull().references(()=>_C.id),symbol:tT("symbol").notNull(),side:tT("side").notNull(),positionIntent:tT("position_intent"),qty:tT("qty").notNull(),price:tT("price").notNull(),fees:tT("fees"),executedAt:tj("executed_at").notNull(),source:tT("source").notNull().default("rest"),raw:tT("raw"),ledgerStatus:tT("ledger_status"),ledgerEventId:tM("ledger_event_id"),ledgerError:tT("ledger_error"),ledgerUpdatedAt:tj("ledger_updated_at"),createdAt:tj("created_at").notNull().defaultNow()},e=>[nt("broker_fills_conn_execution_idx").on(e.connectionId,e.executionId),ne("broker_fills_conn_executed_idx").on(e.connectionId,e.executedAt),ne("broker_fills_order_idx").on(e.orderId)]),t5("broker_position_events",{id:tM("id").primaryKey().defaultRandom(),connectionId:tM("connection_id").notNull().references(()=>_S.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id),brokerActivityId:tT("broker_activity_id").notNull(),activityType:tT("activity_type").notNull(),eventType:_k("event_type").notNull(),status:_T("status").notNull().default("confirmed"),instrumentId:tM("instrument_id").references(()=>_C.id),symbol:tT("symbol"),qty:tT("qty"),price:tT("price"),netAmount:tT("net_amount"),description:tT("description"),relatedActivityId:tT("related_activity_id"),occurredOn:eS("occurred_on").notNull(),occurredAt:tj("occurred_at"),raw:tT("raw"),ledgerStatus:tT("ledger_status"),ledgerEventId:tM("ledger_event_id"),ledgerError:tT("ledger_error"),ledgerUpdatedAt:tj("ledger_updated_at"),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("broker_position_events_conn_activity_idx").on(e.connectionId,e.brokerActivityId),ne("broker_position_events_conn_date_idx").on(e.connectionId,e.occurredOn),ne("broker_position_events_conn_status_idx").on(e.connectionId,e.status)]),t5("broker_positions",{id:tM("id").primaryKey().defaultRandom(),connectionId:tM("connection_id").notNull().references(()=>_S.id,{onDelete:"cascade"}),entityId:tM("entity_id").notNull().references(()=>nP.id),instrumentId:tM("instrument_id").notNull().references(()=>_C.id),symbol:tT("symbol").notNull(),qty:tT("qty").notNull(),avgEntryPrice:tT("avg_entry_price"),costBasis:tT("cost_basis"),marketValue:tT("market_value"),currentPrice:tT("current_price"),unrealizedPl:tT("unrealized_pl"),derivedQty:tT("derived_qty"),varianceQty:tT("variance_qty"),pendingConfirmation:ef("pending_confirmation").notNull().default(!1),lastSyncedAt:tj("last_synced_at").notNull().defaultNow(),createdAt:tj("created_at").notNull().defaultNow(),updatedAt:tj("updated_at").notNull().defaultNow()},e=>[nt("broker_positions_conn_instrument_idx").on(e.connectionId,e.instrumentId),ne("broker_positions_entity_idx").on(e.entityId)]),e.s(["accounts",0,nU,"books",0,nq,"companies",0,i7,"counterparties",0,dn,"dekKeyVersions",0,nK,"entities",0,nP,"inboundEmailMessages",0,oZ,"legalParties",0,sg,"lotDisposals",0,ak,"stagedTransactions",0,n4,"taxLots",0,aR,"washSaleAdjustments",0,aS],739788)}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.