jaz-clio 9.5.0 → 9.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.mjs CHANGED
@@ -427,7 +427,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
427
427
  `)?`"${e.replace(/"/g,'""')}"`:e}function UMe(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}function cHt(e,t){let r=t.map(i=>G$(i.header)).join(","),n=e.map(i=>t.map(o=>{let s=lHt(i,o.key);if(s==null||s==="")return"";let a=o.format?aHt(o.format(s)):UMe(s);return G$(a)}).join(","));return[r,...n].join(`
428
428
  `)}function lHt(e,t){let r=t.split("."),n=e;for(let i of r){if(n==null||typeof n!="object")return;n=n[i]}return n}function Ke(e,t,r,n){let i=Ch(r),o=e.totalElements??e.data.length;switch(i){case"json":console.log(_re({...e,totalElements:o},r));break;case"csv":console.log(cHt(e.data,t));break;case"yaml":console.log((0,Ire.stringify)({totalElements:o,totalPages:e.totalPages,truncated:e.truncated,...e.stats?{stats:e.stats}:{},data:e.data}).trimEnd());break;case"table":{console.log(S(`${n} (${e.data.length} of ${o}):
429
429
  `));let{items:s,overflow:a}=Cre(e.data);if(s.length===0){console.log(" No results found.");return}console.log(Gs(s,t)),a>0&&console.log(U(`
430
- ... and ${a.toLocaleString()} more (use --format json for full output)`));break}}}function NR(e,t){switch(Ch(t)){case"json":console.log(JSON.stringify(e,null,2));break;case"csv":{let n=Object.keys(e);console.log(n.map(G$).join(",")),console.log(n.map(i=>G$(UMe(e[i]))).join(","));break}case"yaml":console.log((0,Ire.stringify)(e).trimEnd());break;case"table":console.log(PMe(e));break}}var Ire,hr,Ht=J(()=>{"use strict";Be();fo();Ire=uo(OMe(),1);DC();mn();MMe();hr=class extends ct{constructor(t){super(t),this.name="CliValidationError"}}});var jMe={};$o(jMe,{displaySlice:()=>Cre,paginatedFetch:()=>st,paginatedJson:()=>_re});async function st(e,t,r){let n=r.defaultLimit??100;if(e.all&&e.offset!==void 0)throw new Error("--all and --offset cannot be used together");if(e.all){let d=(e.format?.toLowerCase()??(e.json?"json":"table"))==="table"?H1e(r.label):void 0,f=e.maxRows??qMe,p=await bf((y,b)=>t({limit:b,offset:y}),{pageSize:e.limit??200,maxItems:f,offsetMode:r.offsetMode,onProgress:d?(y,b)=>d.update(y,b):void 0});d?.clear();let{truncated:h}=p,{data:m}=p;m.length>f&&(m=m.slice(0,f),h=!0),h&&!Ka(e)&&console.error(Te(`Warning: dataset has ${p.totalElements.toLocaleString()} items \u2014 showing ${m.length.toLocaleString()} (max-rows: ${f.toLocaleString()})`));let A=e.limit??n,g=Math.ceil(p.totalElements/A);return{data:m,totalElements:p.totalElements,totalPages:g,truncated:h}}let i=e.limit??n,o=await t({limit:i,offset:e.offset??0}),s=o.data??[],a=(o.totalElements??0)>s.length;return{data:s,totalElements:o.totalElements??0,totalPages:o.totalPages??0,truncated:a}}function Cre(e,t=uHt){return e.length<=t?{items:e,overflow:0}:{items:e.slice(0,t),overflow:e.length-t}}function _re(e,t){let{totalElements:r,totalPages:n,truncated:i,data:o,stats:s}=e,a=s?{stats:s}:{};if(i){let c=t.maxRows??qMe;return JSON.stringify({totalElements:r,totalPages:n,truncated:i,_meta:{fetchedRows:o.length,maxRows:c},...a,data:o},null,2)}return JSON.stringify({totalElements:r,totalPages:n,truncated:i,...a,data:o},null,2)}var qMe,uHt,mn=J(()=>{"use strict";Be();JD();z1e();Ht();qMe=1e3,uHt=500});async function dHt(){if(!wre){let[e,t,r,n]=await Promise.all([Promise.resolve().then(()=>(nt(),GMe)),Promise.resolve().then(()=>(mn(),jMe)),Promise.resolve().then(()=>(Ht(),$Me)),Promise.resolve().then(()=>(gt(),INe))]);wre=e.apiAction,YMe=t.paginatedFetch,HMe=r.outputList,vre=n.parsePositiveInt,zMe=n.parseNonNegativeInt}}function Fe(e){let t=e.commandName??"search",r=e.positionalArg?` <${e.positionalArg}>`:"",n=e.parent.command(`${t}${r}`).description(`Search ${e.label.replace("Searching ","")}`);n.allowExcessArguments(!1);let i=new Map,o=_ee(e.fields);for(let[a,c,u,d]of o){let f=new lt(a,c),p=e.fields[d];u&&p?.op!=="multi"&&f.choices(u),n.addOption(f);let h=fHt(a);h!==d&&i.set(h,d)}e.defaults.supportsQuery&&n.option("--query <expression>",'Jaz search expression (e.g. "status:unpaid AND $500+", "customer:acme AND date:-30d"). Merged with --filter; --filter fields win on conflict.'),n.option("--filter <json>",e.defaults.filterDescription??"Raw API filter JSON (merged with flags; flags win on conflict)").addOption(e.defaults.sortFields?new lt("--sort <field>","Sort field name").choices([...e.defaults.sortFields]):new lt("--sort <field>","Sort field name")).addOption(new lt("--order <direction>","Sort direction").choices(["ASC","DESC"])).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON"),e.defaults.supportsPagination!==!1&&n.option("--limit <n>",`Max results (default ${e.defaults.defaultLimit})`).option("--offset <n>",uC(e.defaults.offsetMode)).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)"),e.defaults.supportsView&&n.addOption(new lt("--view <tier>","Payload tier: 'lean' = summary rows; 'full' (default) = complete records").choices(["lean","full"]));for(let[a,c]of Object.entries(e.extraParams??{})){let u=a.replace(/([A-Z])/g,"-$1").toLowerCase(),d=new lt(`--${u} <value>`,c.description??a);c.enum&&d.choices([...c.enum]),n.addOption(d)}if(e.pathParam&&e.pathParam!==e.positionalArg){let a=e.pathParam.replace(/([A-Z])/g,"-$1").toLowerCase();n.requiredOption(`--${a} <id>`,e.pathParamDescription??`${e.pathParam} (required)`)}let s=async(...a)=>{let c=e.positionalArg?a[0]:void 0,u=e.positionalArg?a[1]:a[0];c&&e.positionalArg&&(u[e.positionalArg]=c),await dHt(),await wre(async d=>{e.preProcess&&await e.preProcess(d,u),typeof u.limit=="string"&&(u.limit=vre(u.limit)),typeof u.offset=="string"&&(u.offset=zMe(u.offset)),typeof u.maxRows=="string"&&(u.maxRows=vre(u.maxRows));let f={...u};for(let[T,D]of i)f[T]!==void 0&&(f[D]=f[T]);let p;if(typeof u.filter=="string")try{p=JSON.parse(u.filter)}catch{throw new Error(`Invalid --filter JSON: ${u.filter}`)}let h=e.baseFilter?p?{...e.baseFilter,...p}:e.baseFilter:p,m=YD(f,e.fields,h),A;if(c&&e.positionalFilter){let T=e.positionalFilter(c);A=m?{...T,...m}:T}else A=m;let g={sortBy:[u.sort??e.defaults.sortBy],order:u.order??e.defaults.sortOrder},y=e.defaults.supportsQuery?u.query:void 0,b=e.defaults.supportsView?u.view:void 0,E={};for(let[T,D]of Object.entries(e.extraParams??{})){let k=u[T];typeof k=="string"&&(E[T]=D.type==="array"?k.split(",").map(F=>F.trim()):k)}let C=e.pathParam?({limit:T,offset:D})=>e.fetcher(d,u[e.pathParam],{filter:A,sort:g,limit:T,offset:D,query:y,view:b,...E}):({limit:T,offset:D})=>e.fetcher(d,{filter:A,sort:g,limit:T,offset:D,query:y,view:b,...E}),w=await YMe(u,C,{label:e.label,defaultLimit:e.defaults.defaultLimit,offsetMode:e.defaults.offsetMode});HMe(w,e.columns,u,e.label.replace("Searching ",""))})(u)};return n.action(s),n}function fHt(e){return e.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(r,n)=>n.toUpperCase())}var wre,YMe,HMe,vre,zMe,JMe=J(()=>{"use strict";jn();zD();ch()});var RC,TC,BR,OR,VMe=J(()=>{"use strict";zo();RC={reference:{path:"reference",op:"contains",type:"string",description:"Invoice reference number"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:aLe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact/customer name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:LU},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},TC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},BR=RC,OR=TC});var WMe,FR,LR,xC,QR,_h,wh,KMe=J(()=>{"use strict";zo();WMe={reference:{path:"reference",op:"contains",type:"string",description:"Order reference number"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},FR={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:kLe},...WMe},LR={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:NLe},...WMe},xC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},QR=xC,_h={name:{path:"name",op:"contains",type:"string",description:"Line item text/description"},reference:{path:"reference",op:"contains",type:"string",description:"Parent order reference"},orderId:{path:"btResourceId",op:"eq",type:"string",description:"Parent order resourceId"},contactName:{path:"contactName",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},status:{path:"status",op:"eq",type:"string",description:"Line item status"},account:{path:"organizationAccountName",op:"contains",type:"string",description:"Chart-of-account name on the line"},taxProfile:{path:"taxProfileName",op:"contains",type:"string",description:"Tax profile name on the line"},isOpen:{path:"isOpen",op:"boolean",type:"boolean",description:"Only open (unfulfilled) lines"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"totalItemAmount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"totalItemAmount",op:"lte",type:"number",description:"Maximum line amount"}},wh={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var vh,kC,PR,XMe=J(()=>{"use strict";zo();vh={reference:{path:"reference",op:"contains",type:"string",description:"Credit note reference"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:cLe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:LU},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},kC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},PR=kC});var MR,UR,ZMe=J(()=>{"use strict";zo();MR={reference:{path:"reference",op:"contains",type:"string",description:"Journal reference"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:lLe},type:{path:"type",op:"multi",type:"string",description:"Journal type",enum:uLe},templateType:{path:"templateType",op:"multi",type:"string",description:"Template type",enum:dLe},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},internalNotes:{path:"internalNotes",op:"contains",type:"string",description:"Search internal notes"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},UR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var $R,qR,eUe=J(()=>{"use strict";zo();$R={name:{path:"name",op:"contains",type:"string",description:"Contact name"},email:{path:"email",op:"contains",type:"string",description:"Email address"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:FU},isCustomer:{path:"customer",op:"boolean",type:"boolean",description:"Filter to customers only",cliFlag:"--customer"},isSupplier:{path:"supplier",op:"boolean",type:"boolean",description:"Filter to suppliers only",cliFlag:"--supplier"},taxId:{path:"taxId",op:"contains",type:"string",description:"Tax ID"}},qR={sortBy:"name",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var _f,wf,Sre,jR,YR,tUe=J(()=>{"use strict";zo();_f={type:{path:"businessTransactionType",op:"multi",type:"string",description:"Transaction type",enum:yLe},direction:{path:"direction",op:"eq",type:"string",description:"Direction (PAYIN or PAYOUT)",enum:ALe},status:{path:"businessTransactionStatus",op:"multi",type:"string",description:"Status",enum:ELe},reference:{path:"businessTransactionReference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},businessTransactionType:{path:"businessTransactionType",op:"multi",type:"string",description:"(alias for type)"}},wf={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0},Sre={magicSort:{type:"object",description:"Rank by match quality to a bank entry: {bankStatementEntryResourceId, magicSort:true}."},transactionType:{type:"string",enum:[...gLe],description:"Scope. Default ALL_CASHFLOWS."}},jR={resourceId:{path:"resourceId",op:"eq",type:"string",description:"One unapplied payment (the read-back for its hash)",cliFlag:"--id <resourceId>"},type:{path:"type",op:"eq",type:"string",description:"AR = received, AP = paid",enum:["AR","AP"]},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},YR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20}});var HR,zR,rUe=J(()=>{"use strict";zo();HR={status:{path:"status",op:"multi",type:"string",description:"Status",enum:mLe},description:{path:"description",op:"contains",type:"string",description:"Description"},payer:{path:"extContactName",op:"contains",type:"string",description:"Payer/payee name"},reference:{path:"extReference",op:"contains",type:"string",description:"Bank reference",cliFlag:"--ref <reference>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"netAmount",op:"gte",type:"number",description:"Minimum net amount"},maxAmount:{path:"netAmount",op:"lte",type:"number",description:"Maximum net amount"}},zR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var JR,GR,nUe=J(()=>{"use strict";zo();JR={status:{path:"status",op:"multi",type:"string",description:"Status",enum:fLe},itemCategory:{path:"itemCategory",op:"eq",type:"string",description:"Category",enum:hLe},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale items only",cliFlag:"--sale"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase items only",cliFlag:"--purchase"}},GR={sortBy:"internalName",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var VR,WR,KR,XR,ZR,eT,iUe=J(()=>{"use strict";zo();ch();VR={name:{path:"name",op:"contains",type:"string",description:"Asset name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:bLe},category:{path:"category",op:"eq",type:"string",description:"Category",enum:Eee},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Asset type name"},startDate:{path:"purchaseDate",op:"gte",type:"string",description:"Purchase date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"purchaseDate",op:"lte",type:"string",description:"Purchase date to (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"purchaseAmount",op:"gte",type:"number",description:"Minimum purchase amount"},maxAmount:{path:"purchaseAmount",op:"lte",type:"number",description:"Maximum purchase amount"}},WR={sortBy:"name",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0,filterDescription:ah("resourceId, typeCode, currencyCode, depreciationEndDate, disposalValueDate, bookValueAmount, assetDisposalGainLossAmount")},KR={reference:{path:"reference",op:"contains",type:"string",description:"Source bill or journal reference",cliFlag:"--ref <reference>"},contactName:{path:"contactName",op:"contains",type:"string",description:"Supplier name"},documentType:{path:"documentType",op:"eq",type:"string",description:"PURCHASE (bill) or a journal type"},accountName:{path:"accountName",op:"contains",type:"string",description:"Fixed Asset account name"},lineDescription:{path:"description",op:"contains",type:"string",description:"Line description"},minAmount:{path:"amount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"amount",op:"lte",type:"number",description:"Maximum line amount"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Document date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Document date to (YYYY-MM-DD)",cliFlag:"--to <date>"}},XR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20},ZR={categoryCode:{path:"categoryCode",op:"eq",type:"string",description:"Asset category",enum:Eee,cliFlag:"--category <cat>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Asset type name"}},eT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50}});var tT,rT,nT,iT,oT,sT,aT,cT,lT,uT,oUe=J(()=>{"use strict";zo();ch();tT={name:{path:"name",op:"contains",type:"string",description:"Deferral name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Stored status",enum:ILe},category:{path:"category",op:"eq",type:"string",description:"Category",enum:QU},typeName:{path:"typeName",op:"contains",type:"string",description:"Deferral type name"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},minAmount:{path:"deferralAmount",op:"gte",type:"number",description:"Minimum deferral amount"},maxAmount:{path:"deferralAmount",op:"lte",type:"number",description:"Maximum deferral amount"}},rT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0,sortFields:CLe,filterDescription:ah("resourceId, typeCode, currencyCode, sourceDate, amortizationStartDate, amortizationEndDate, closedOutDate")},nT={viewStatus:{type:"string",enum:["ACTIVE","DRAFT","COMPLETED","FULLY_AMORTIZED","CLOSED_OUT"],description:"Status as at endDate. COMPLETED = FULLY_AMORTIZED or CLOSED_OUT."},endDate:{type:"string",description:"As-at date (YYYY-MM-DD) the figures and statuses are worked out at. Default today."}},iT={reference:{path:"reference",op:"contains",type:"string",description:"Source bill, invoice or journal reference",cliFlag:"--ref <reference>"},contactName:{path:"contactName",op:"contains",type:"string",description:"Supplier or customer name"},documentType:{path:"documentType",op:"eq",type:"string",description:"PURCHASE (bill), SALE (invoice) or a journal type"},category:{path:"category",op:"eq",type:"string",description:"Category",enum:QU,cliFlag:"--category <cat>"},accountName:{path:"accountName",op:"contains",type:"string",description:"Deferral account name"},lineDescription:{path:"description",op:"contains",type:"string",description:"Line description"},minAmount:{path:"amount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"amount",op:"lte",type:"number",description:"Maximum line amount"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Document date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Document date to (YYYY-MM-DD)",cliFlag:"--to <date>"}},oT={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,sortFields:["valueDate","reference","contactName","documentType"]},sT={categoryCode:{path:"categoryCode",op:"eq",type:"string",description:"Category (the same typeCode exists in both, so always set it)",enum:QU,cliFlag:"--category <cat>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Deferral type name"}},aT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50,sortFields:["resourceId","typeName","typeCode","categoryCode"]},cT={accountName:{path:"accountName",op:"contains",type:"string",description:"Account name"},accountCode:{path:"accountCode",op:"contains",type:"string",description:"Account code"},accountType:{path:"accountType",op:"eq",type:"string",description:"Account type",enum:["Current Asset","Current Liability"]}},lT={sortBy:"accountCode",sortOrder:"ASC",defaultLimit:50,sortFields:["accountName","accountCode","accountType","accountResourceId"]},uT={searchTerms:{type:"array",items:{type:"string"},description:"Words matched against name, code, type and description (max 20). Omit to list all."}}});var dT,pHt,fT,pT,hT,mT,sUe=J(()=>{"use strict";zo();ch();dT={name:{path:"name",op:"contains",type:"string",description:"Lease name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Stored status",enum:SLe},typeCode:{path:"typeCode",op:"eq",type:"string",description:"Lease type code (e.g. OFFICE, HIRE_PURCHASE)"},typeName:{path:"typeName",op:"contains",type:"string",description:"Lease type name"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Lessor contact resourceId"},paymentTiming:{path:"paymentTiming",op:"eq",type:"string",description:"Payment timing",enum:sh},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},commencementFrom:{path:"commencementDate",op:"gte",type:"string",description:"Commencement date from (YYYY-MM-DD)",cliFlag:"--from <date>"},commencementTo:{path:"commencementDate",op:"lte",type:"string",description:"Commencement date to (YYYY-MM-DD)",cliFlag:"--to <date>"}},pHt=["resourceId","name","reference","typeName","commencementDate","endDate","leaseLiabilityAmount","rouAssetAmount","leaseLiabilityRemaining","currentPortion","nonCurrentPortion","accumulatedDepreciation","rouNetBookValue","interestToDate","createdAt"],fT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20,sortFields:pHt,filterDescription:ah("resourceId, currencyCode, leaseTerm, endDate, closedOutDate, leaseLiabilityAmount")},pT={viewStatus:{type:"string",enum:[...DLe],description:"Register tab. COMPLETED is ended, closed out or terminated; ACTIVE also lists lease exemptions until their end date."},endDate:{type:"string",description:"As-at date (YYYY-MM-DD) of liability, right-of-use and view status. Default today. Leases starting after it are left out."}},hT={typeCode:{path:"typeCode",op:"eq",type:"string",description:"Type code"},typeName:{path:"typeName",op:"contains",type:"string",description:"Type name"}},mT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50}});var AT,hHt,gT,yT,ET,bT,aUe=J(()=>{"use strict";zo();ch();AT={name:{path:"name",op:"contains",type:"string",description:"Loan name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Stored status (the as-at status is viewStatus)",enum:_Le},kind:{path:"kind",op:"eq",type:"string",description:"TERM (repayment schedule) or ON_DEMAND (overdraft, revolving, director loan account)",enum:wLe},typeCode:{path:"typeCode",op:"eq",type:"string",description:"Loan type code (BANK, DIRECTOR, MORTGAGE...); see search_loan_types",cliFlag:"--type-code <code>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Loan type name"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Lender contact resourceId",cliFlag:"--contact <id>"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},startDate:{path:"drawdownDate",op:"gte",type:"string",description:"Drawdown date from (YYYY-MM-DD)",cliFlag:"--from <date>"},drawnTo:{path:"drawdownDate",op:"lte",type:"string",description:"Drawdown date to (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"principalAmount",op:"gte",type:"number",description:"Minimum principal"},maxAmount:{path:"principalAmount",op:"lte",type:"number",description:"Maximum principal"}},hHt=["createdAt","resourceId","name","reference","kind","typeName","drawdownDate","endDate","principalAmount","outstandingPrincipal","annualInterestRate","loanTerm"],gT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20,supportsQuery:!1,sortFields:hHt,filterDescription:ah("resourceId, currencyCode, loanTerm, endDate, closedOutDate, annualInterestRate")},yT={viewStatus:{type:"string",enum:[...vLe],description:"Status as at endDate: REPAID, SETTLED and CLOSED_OUT are derived, INACTIVE = any of those three. Figures on every row are as at endDate."},endDate:{type:"string",description:"As-at date (YYYY-MM-DD, default today); loans starting after it are left out"}},ET={typeName:{path:"typeName",op:"contains",type:"string",description:"Loan type name"},typeCode:{path:"typeCode",op:"eq",type:"string",description:"Loan type code",cliFlag:"--type-code <code>"}},bT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50,supportsQuery:!1}});var IT,CT,cUe=J(()=>{"use strict";zo();IT={type:{path:"businessTransactionType",op:"eq",type:"string",description:"Transaction type (SALE, PURCHASE, JOURNAL_MANUAL)"},status:{path:"status",op:"multi",type:"string",description:"Scheduler status",enum:RLe},subscriptionStatus:{path:"subscriptionStatus",op:"multi",type:"string",description:"Subscription status",enum:TLe},schedulerType:{path:"schedulerType",op:"eq",type:"string",description:"Scheduler type"},interval:{path:"interval",op:"eq",type:"string",description:"Interval",enum:xLe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"}},CT={sortBy:"nextScheduleDate",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0}});var _T,wT,lUe=J(()=>{"use strict";zo();_T={id:{path:"resourceId",op:"eq",type:"string",description:"Job ID (the jobId returned from bulk operations)",cliFlag:"--id"},status:{path:"status",op:"multi",type:"string",description:"Job status",enum:QLe},type:{path:"jobType",op:"eq",type:"string",description:"Job type (e.g. UPSERT_CONTACTS, UPSERT_ITEMS, PROCESS_BANK_STATEMENT_FILES)",cliFlag:"--type"},fileName:{path:"fileName",op:"contains",type:"string",description:"File name (file-based jobs only)",cliFlag:"--file-name"},from:{path:"createdAt",op:"gte",type:"string",description:"On/after (ISO date)",cliFlag:"--from"},to:{path:"createdAt",op:"lte",type:"string",description:"On/before (ISO date)",cliFlag:"--to"}},wT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20}});var vT,qg,uUe=J(()=>{"use strict";vT={name:{path:"name",op:"plain",type:"string",description:"Purchase item name"},reference:{path:"reference",op:"plain",type:"string",description:"Reference name"},currencyCode:{path:"currencyCode",op:"plain",type:"string",description:"Currency code (ISO 4217)"}},qg={sortBy:"name",sortOrder:"ASC",defaultLimit:20,offsetMode:"row"}});var ST,DT,dUe=J(()=>{"use strict";ST={formType:{path:"formType",op:"eq",type:"string",description:"Form code, e.g. 2550Q"},lifecycleStatus:{path:"lifecycleStatus",op:"multi",type:"string",description:"Status, comma-separated (e.g. READY_TO_FILE)"},periodYear:{path:"periodYear",op:"eq",type:"number",description:"Period year"},dueFrom:{path:"filingDueDate",op:"gte",type:"string",description:"Due on/after (YYYY-MM-DD)"},dueTo:{path:"filingDueDate",op:"lte",type:"string",description:"Due on/before (YYYY-MM-DD)"}},DT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20}});function pUe(e){return typeof e=="string"&&ws.includes(e)}var ws,RT,Sh,V$,ju,jg,Yg,fUe,NC,Hg,Yu=J(()=>{"use strict";ws=["PROFIT_AND_LOSS","BALANCE_SHEET","CASHFLOW","EQUITY_MOVEMENT","TRIAL_BALANCE","GENERAL_LEDGER","VAT_LEDGER","CASH_BALANCE","AGED_RECEIVABLES_SUMMARY","AGED_RECEIVABLES_DETAILS","AGED_PAYABLES_SUMMARY","AGED_PAYABLES_DETAILS","REPORT_PACK"],RT=["IAS_1","IFRS_18","GAAP","IND_AS","IFRS_SME"],Sh=["IAS_1","IFRS_18"],V$=["FINANCIAL","ACCOUNTING","OPERATIONAL","REPORT_PACK"],ju={PROFIT_AND_LOSS:{label:"Profit and loss",category:"FINANCIAL",exportType:"profit-and-loss",takesFramework:!0,frameworkChangesDefault:!0,periodKind:"range",snapshotsChartOfAccounts:!0,hasRows:!0},BALANCE_SHEET:{label:"Balance sheet",category:"FINANCIAL",exportType:"balance-sheet",takesFramework:!0,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!0,hasRows:!0},CASHFLOW:{label:"Cashflow statement",category:"FINANCIAL",exportType:"cashflow",takesFramework:!0,frameworkChangesDefault:!0,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!0},EQUITY_MOVEMENT:{label:"Statement of changes in equity",category:"FINANCIAL",exportType:"equity-movement",takesFramework:!0,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1},TRIAL_BALANCE:{label:"Trial balance",category:"ACCOUNTING",exportType:"trial-balance",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},GENERAL_LEDGER:{label:"General ledger",category:"ACCOUNTING",exportType:"general-ledger",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1},VAT_LEDGER:{label:"Tax (GST/VAT) ledger",category:"ACCOUNTING",exportType:"tax-ledger",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1},CASH_BALANCE:{label:"Cash balance",category:"OPERATIONAL",exportType:"cash-balance",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_RECEIVABLES_SUMMARY:{label:"Aged receivables (summary)",category:"OPERATIONAL",exportType:"ar-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_RECEIVABLES_DETAILS:{label:"Aged receivables (details)",category:"OPERATIONAL",exportType:"ar-details-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_PAYABLES_SUMMARY:{label:"Aged payables (summary)",category:"OPERATIONAL",exportType:"ap-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_PAYABLES_DETAILS:{label:"Aged payables (details)",category:"OPERATIONAL",exportType:"ap-details-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},REPORT_PACK:{label:"Report pack (several reports in one document)",category:"REPORT_PACK",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1}},jg=ws.filter(e=>e!=="REPORT_PACK"),Yg=ws.filter(e=>ju[e].takesFramework),fUe=ws.filter(e=>ju[e].frameworkChangesDefault),NC=ws.filter(e=>ju[e].hasRows),Hg=new Map(jg.flatMap(e=>{let t=ju[e].exportType;return t?[[t,e]]:[]}))});function W$(e){if(!Array.isArray(e))throw new ue(`expected a list of strings, got ${JSON.stringify(e)}.`);return e.map(String)}function AHt(e,t,r){let n=mHt.has(r),i=a=>n?typeof a=="string"?a.toLowerCase():Array.isArray(a)?a.map(i):a:a,o=e==null?void 0:i(String(e)),s=typeof t=="object"&&t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).map(([a,c])=>[a,i(c)])):i(t);if(typeof s=="string")return o===s;if(!s||typeof s!="object"||Array.isArray(s))throw new ue(`filter.${r} must be a string or an object of operators (${Object.keys(TT).join(", ")}, isNull).`);return Object.entries(s).every(([a,c])=>{if(a==="isNull")return c===!0||c==="true"?o===void 0||o==="":o!==void 0&&o!=="";let u=TT[a];if(!u)throw new ue(`filter.${r}.${a} is not an operator. Use one of: ${Object.keys(TT).join(", ")}, isNull.`);return o!==void 0&&u(o,c)})}function gHt(e,t,r){let n=typeof t=="boolean"?t:t?.eq;if(typeof n!="boolean")throw new ue(`filter.${r} must be true, false, or {"eq": true|false}.`);return e===!0===n}function Dre(e){if(e){if(typeof e!="object"||Array.isArray(e))throw new ue("filter must be an object of fields.");for(let[t,r]of Object.entries(e)){if(r==null)continue;if(t==="and"||t==="or"){for(let s of Array.isArray(r)?r:[r])Dre(s);continue}if(!xT.includes(t))throw new ue(`filter: "${t}" is not a report template field. Use: ${xT.join(", ")}.`);let n=EHt[t];if(!n)continue;let o=(typeof r=="string"?[r]:Array.isArray(r)?r:typeof r=="object"?Object.entries(r).filter(([s])=>yHt.has(s)).flatMap(([,s])=>Array.isArray(s)?s:[s]):[r]).filter(s=>!n.includes(String(s)));if(o.length>0)throw new ue(`filter.${t}: ${o.map(s=>JSON.stringify(s)).join(", ")} is not a value it takes. Use: ${n.join(", ")}.`)}}}function X$(e,t){return t?Object.entries(t).every(([r,n])=>{if(n==null)return!0;switch(r){case"resourceId":case"templateName":case"reportType":case"reportCategory":return AHt(e[r],n,r);case"reportTypes":return W$(n).includes(String(e.reportType));case"isDefault":return gHt(e.isDefault,n,r);case"and":return(Array.isArray(n)?n:[n]).every(i=>X$(e,i));case"or":return(Array.isArray(n)?n:[n]).some(i=>X$(e,i));default:throw new ue(`filter: "${r}" is not a report template field. Use: ${xT.join(", ")}.`)}}):!0}function hUe(e,t=["reportType"],r="ASC"){for(let o of t)if(!K$.includes(o))throw new ue(`sortBy "${o}" is not sortable. Use one of: ${K$.join(", ")}.`);let n=[...t,"templateName","resourceId"],i=r==="DESC"?-1:1;return[...e].sort((o,s)=>{for(let a of n){let c=String(o[a]??""),u=String(s[a]??"");if(c!==u)return(c<u?-1:1)*(t.includes(a)?i:1)}return 0})}var xT,K$,TT,mHt,yHt,EHt,Rre=J(()=>{"use strict";ot();Yu();xT=["resourceId","templateName","reportType","reportTypes","reportCategory","isDefault","and","or"],K$=["reportType","templateName","isDefault","resourceId"],TT={eq:(e,t)=>e===String(t),neq:(e,t)=>e!==String(t),in:(e,t)=>W$(t).includes(e),contains:(e,t)=>e.toLowerCase().includes(String(t).toLowerCase()),notContains:(e,t)=>!e.toLowerCase().includes(String(t).toLowerCase()),likeIn:(e,t)=>W$(t).some(r=>e.toLowerCase().includes(r.toLowerCase())),reg:(e,t)=>W$(t).some(r=>e.toLowerCase().includes(r.toLowerCase())),startWith:(e,t)=>e.startsWith(String(t)),notStartWith:(e,t)=>!e.startsWith(String(t)),endWith:(e,t)=>e.endsWith(String(t))};mHt=new Set(["resourceId"]);yHt=new Set(["eq","neq","in"]),EHt={reportType:ws,reportTypes:ws,reportCategory:V$}});var kT,NT,BT,OT,mUe=J(()=>{"use strict";Yu();Rre();kT={catalogName:{path:"catalogName",op:"contains",type:"string",description:"Catalog name"},description:{path:"description",op:"contains",type:"string",description:"Catalog item description"},status:{path:"status",op:"multi",type:"string",description:"Record status (e.g. ACTIVE, INACTIVE)"},contactGroupResourceId:{path:"contactGroupResourceId",op:"eq",type:"string",description:"Contact group resourceId"}},NT={sortBy:"catalogName",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},BT={templateName:{path:"templateName",op:"contains",type:"string",description:"Name contains",cliFlag:"--name"},reportType:{path:"reportType",op:"plain",type:"string",description:"Report type",enum:ws,cliFlag:"--type"},reportCategory:{path:"reportCategory",op:"eq",type:"string",description:"Category",enum:V$,cliFlag:"--category"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Defaults only",cliFlag:"--default"}},OT={sortBy:"reportType",sortOrder:"ASC",defaultLimit:20,supportsPagination:!1,sortFields:K$,filterDescription:`Raw filter JSON. Fields: ${xT.filter(e=>e!=="and"&&e!=="or").join(", ")}, combined with and/or. String ops: ${Object.keys(TT).join(", ")}, isNull. isDefault: {"eq": true}.`}});async function Z$(e,t){return e.search("/api/v1/claims/search",t)}async function FT(e,t){return e.get(`/api/v1/claims/${t}`)}async function e2(e,t){return e.post("/api/v1/claims",t,AP)}async function t2(e,t,r){return e.put(`/api/v1/claims/${t}`,r)}async function r2(e,t){return e.delete(`/api/v1/claims/${t}`)}async function n2(e,t,r){return e.delete(`/api/v1/claims/${t}/attachments/${r}`)}async function i2(e,t){return e.post(`/api/v1/claims/${t}/submit`,{})}async function o2(e,t){return e.post(`/api/v1/claims/${t}/approve`,{})}async function s2(e,t,r){return e.post(`/api/v1/claims/${t}/reject`,{rejectionReason:r})}async function a2(e,t,r){return e.post(`/api/v1/claims/${t}/cancel`,{cancellationReason:r})}async function c2(e,t){return e.post(`/api/v1/claims/${t}/unpost`,{})}function LT(e){mt(e,"resourceIds",500,"claims")}async function l2(e,t){return LT(t),e.post("/api/v1/claims/bulk/submit",{resourceIds:t})}async function u2(e,t){return LT(t),e.post("/api/v1/claims/bulk/approve",{resourceIds:t})}async function d2(e,t){return LT(t),e.post("/api/v1/claims/bulk/delete",{resourceIds:t})}async function f2(e,t,r){return LT(t),e.post("/api/v1/claims/bulk/reject",{resourceIds:t,rejectionReason:r})}async function p2(e,t,r){return LT(t),e.post("/api/v1/claims/bulk/cancel",{resourceIds:t,cancellationReason:r})}async function h2(e){let t=await e.get("/api/v1/claims/tracking-tags");return Array.isArray(t)?t:t?.data??[]}async function m2(e){let t=await e.get("/api/v1/claims/custom-field-values");return Array.isArray(t)?t:t?.data??[]}var AUe,A2=J(()=>{"use strict";an();tr();AUe=["DRAFT","SUBMITTED","APPROVED","CONVERTED","REJECTED","CANCELLED"]});var QT,PT,bHt,IHt,MT,UT,$T,qT,jT,YT,HT,zT,gUe=J(()=>{"use strict";uD();pD();A2();QT={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:AUe},employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Vendor contact resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Approver user resourceId"},reference:{path:"reference",op:"contains",type:"string",description:"Claim reference"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (ISO 4217)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Value date on/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Value date on/before (YYYY-MM-DD)",cliFlag:"--to <date>"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},PT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20},bHt=["RECORDED","COMPLETED","CANCELLED","IN_PROGRESS","ACTION_NEEDED"],IHt=["DIRECT_ENTRY","DISBURSEMENT","REIMBURSEMENT_PAYOUT","ADVANCE"],MT={employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},employeeName:{path:"employeeName",op:"contains",type:"string",description:"Employee name"},reference:{path:"reference",op:"contains",type:"string",description:"Payout reference"},payoutStatus:{path:"payoutStatus",op:"multi",type:"string",description:"Payout status (comma-separated)",enum:bHt},payoutType:{path:"payoutType",op:"multi",type:"string",description:"Payout type (comma-separated): DIRECT_ENTRY (books-only DCE), DISBURSEMENT (gateway direct-debit-backed), REIMBURSEMENT_PAYOUT, ADVANCE",enum:IHt}},UT={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,offsetMode:"row"},$T={name:{path:"name",op:"contains",type:"string",description:"Claim type name"},expenseAccountResourceId:{path:"expenseAccountResourceId",op:"eq",type:"string",description:"Default expense account resourceId"},taxProfileResourceId:{path:"taxProfileResourceId",op:"eq",type:"string",description:"Default tax profile resourceId"}},qT={sortBy:"name",sortOrder:"ASC",defaultLimit:100},jT={name:{path:"name",op:"contains",type:"string",description:"Claim profile name"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Default approver user resourceId"},minClaimAmount:{path:"minClaimAmount",op:"gte",type:"number",description:"Minimum claim total (>=)"},maxClaimAmount:{path:"maxClaimAmount",op:"lte",type:"number",description:"Maximum claim total (<=)"},maxPerPeriodAmount:{path:"maxPerPeriodAmount",op:"lte",type:"number",description:"Per-period spend cap (<=)"},perPeriod:{path:"perPeriod",op:"eq",type:"string",description:"Per-period window",enum:cD},employeeBalanceAccountResourceId:{path:"employeeBalanceAccountResourceId",op:"eq",type:"string",description:"Employee balance (liability) account resourceId"}},YT={sortBy:"name",sortOrder:"ASC",defaultLimit:100},HT={name:{path:"name",op:"contains",type:"string",description:"Posting rule name"},outerAxis:{path:"outerAxis",op:"eq",type:"string",description:"Outer grouping axis",enum:dD},innerAxis:{path:"innerAxis",op:"eq",type:"string",description:"Inner line-aggregation axis",enum:fD},defaultBankAccountResourceId:{path:"defaultBankAccountResourceId",op:"eq",type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{path:"defaultIncludeReimbursementPayout",op:"boolean",type:"boolean",description:"Creates reimbursement DCE by default"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default rule"}},zT={sortBy:"name",sortOrder:"ASC",defaultLimit:100}});var JT,GT,VT,WT,yUe=J(()=>{"use strict";gD();JT={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},userResourceId:{path:"userResourceId",op:"eq",type:"string",description:"Bound login user resourceId"},managerEmployeeResourceId:{path:"managerEmployeeResourceId",op:"eq",type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"}},GT={sortBy:"name",sortOrder:"ASC",defaultLimit:50},VT={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},employmentType:{path:"employmentType",op:"eq",type:"string",description:"Employment type",enum:Ig},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"}},WT={sortBy:"name",sortOrder:"ASC",defaultLimit:50}});var KT,XT,ZT,ex,tx,rx,nx,ix,ox,sx,ax,cx,lx,ux,Tre,dx,fx,px,hx,EUe=J(()=>{"use strict";zo();KT={name:{path:"name",op:"contains",type:"string",description:"Account name"},code:{path:"code",op:"contains",type:"string",description:"Account code"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:pLe},accountClass:{path:"accountClass",op:"eq",type:"string",description:"Account class",enum:BLe},accountType:{path:"accountType",op:"eq",type:"string",description:"Account type",enum:PU},controlFlag:{path:"controlFlag",op:"boolean",type:"boolean",description:"Control flag (system accounts)"}},XT={sortBy:"code",sortOrder:"ASC",defaultLimit:100,supportsQuery:!1},ZT={query:{path:"tagName",op:"contains",type:"string",description:"Tag name"}},ex={sortBy:"tagName",sortOrder:"ASC",defaultLimit:100},tx={name:{path:"name",op:"contains",type:"string",description:"Tax profile name",cliFlag:"--name <name>"},taxTypeCode:{path:"taxTypeCode",op:"contains",type:"string",description:"Tax type code"},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale profiles"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase profiles"},appliesToSaleCreditNote:{path:"appliesToSaleCreditNote",op:"boolean",type:"boolean",description:"Filter to sale CN profiles"},appliesToPurchaseCreditNote:{path:"appliesToPurchaseCreditNote",op:"boolean",type:"boolean",description:"Filter to purchase CN profiles"}},rx={sortBy:"name",sortOrder:"ASC",defaultLimit:100,supportsQuery:!0},nx={title:{path:"title",op:"contains",type:"string",description:"Capsule title"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:LLe}},ix={sortBy:"title",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},ox={query:{path:"customFieldName",op:"contains",type:"string",description:"Custom field name",cliFlag:"--name <name>"},datatypeCode:{path:"datatypeCode",op:"eq",type:"string",description:"Data type",enum:OLe,cliFlag:"--type <type>"},customFieldName:{path:"customFieldName",op:"contains",type:"string",description:"(alias for query)"}},sx={sortBy:"customFieldName",sortOrder:"ASC",defaultLimit:100},ax={query:{path:"name",op:"contains",type:"string",description:"Group name"}},cx={sortBy:"name",sortOrder:"ASC",defaultLimit:100},lx={firstName:{path:"user.firstName",op:"contains",type:"string",description:"User first name"},lastName:{path:"user.lastName",op:"contains",type:"string",description:"User last name"},email:{path:"user.email",op:"contains",type:"string",description:"Email"},userType:{path:"userType",op:"eq",type:"string",description:"Access tier",enum:FLe},status:{path:"status",op:"multi",type:"string",description:"Status",enum:FU}},ux={sortBy:"user.FirstName",sortOrder:"ASC",defaultLimit:50},Tre=e=>({or:{user:{firstName:{contains:e}},or:{user:{lastName:{contains:e}}}}}),dx={query:{path:"name",op:"contains",type:"string",description:"Rule name"},account:{path:"appliesToReconciliationAccount",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"}},fx={sortBy:"name",sortOrder:"ASC",defaultLimit:100},px={query:{path:"type",op:"contains",type:"string",description:"Classifier type"}},hx={sortBy:"type",sortOrder:"ASC",defaultLimit:100}});var zt=J(()=>{"use strict";zo();ch();zD();JMe();VMe();KMe();XMe();ZMe();eUe();tUe();rUe();nUe();iUe();oUe();sUe();aUe();cUe();lUe();uUe();dUe();mUe();gUe();yUe();EUe()});async function g2(e,t){return e.list("/api/v1/modules",t)}async function y2(e,t){return e.get(`/api/v1/modules/${encodeURIComponent(t)}`)}var xre=J(()=>{"use strict"});async function E2(e,t){return e.list("/api/v1/purchase-items",t)}async function b2(e,t){return e.get(`/api/v1/purchase-items/${encodeURIComponent(t)}`)}async function I2(e,t){return e.search("/api/v1/purchase-items/search",t)}var kre=J(()=>{"use strict"});async function C2(e,t){return e.list("/api/v1/invoices",t)}async function Eo(e,t){let r=await e.get(`/api/v1/invoices/${t}`);return"data"in r&&typeof r.data=="object"?r:{data:r}}async function BC(e,t){return e.search("/api/v1/invoices/search",t)}async function mx(e,t){return e.post("/api/v1/invoices",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function _2(e,t,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(Fu)}:r;return e.put(`/api/v1/invoices/${t}`,n)}async function w2(e,t,r){return e.delete(`/api/v1/invoices/${t}`,r)}async function Ax(e,t,r){return e.post(`/api/v1/invoices/${t}/payments`,{...r,currency:Wt(r.currency),saveAsDraft:r.saveAsDraft??!0},dP)}async function gx(e,t){return e.post("/api/v1/scheduled/invoices",{...t,invoice:{...t.invoice,currency:Wt(t.invoice?.currency)}},Jp)}async function v2(e,t,r){return e.post(`/api/v1/invoices/${t}/credits`,{credits:r},fP)}async function yx(e,t,r){return e.put(`/api/v1/invoices/${t}`,{...r,resourceId:t,saveAsDraft:!1})}async function S2(e,t){return e.get(`/api/v1/invoices/${t}/download`)}async function Ex(e,t){let r=await e.get(`/api/v1/invoices/${t}/payments`);return{data:Array.isArray(r)?r:r.data??[]}}async function D2(e,t){let r=await e.get(`/api/v1/invoices/${t}/credits`);return{data:Array.isArray(r)?r:r.data??[]}}async function R2(e,t,r){await e.delete(`/api/v1/invoices/${t}/credits/${r}`)}async function T2(e,t){return En(e,"/api/v1/invoices/bulk-upsert","invoices",t)}async function x2(e,t){return En(e,"/api/v1/invoices/line-items/bulk-upsert","invoices",Gp(t))}var zg=J(()=>{"use strict";tr();Vp();an();ot()});async function bUe(e,t,r){return e.list(`/api/v1/${Ml[t]}`,r)}async function Ul(e,t,r){return e.get(`/api/v1/${Ml[t]}/${r}`)}async function k2(e,t,r){return e.search(`/api/v1/${Ml[t]}/search`,r)}async function N2(e,t,r){return e.search(`/api/v1/${Ml[t]}/line-items/search`,r)}async function bx(e,t){return e.post("/api/v1/sale-quotes",{...t,currency:Wt(t.currency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function Ix(e,t){return e.post("/api/v1/sale-orders",{...t,currency:Wt(t.currency)},Wi)}async function B2(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/${r}/convert-to-invoice`,n,uP)}async function O2(e,t,r,n){return e.put(`/api/v1/${Ml[t]}/${r}`,n)}async function F2(e,t,r){await e.delete(`/api/v1/${Ml[t]}/${r}`)}async function L2(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/${r}/void`,n?{internalNotes:n}:{})}async function Q2(e,t){return e.post(`/api/v1/sale-quotes/${t}/accept`,{})}async function P2(e,t){return e.post(`/api/v1/sale-orders/${t}/confirm`,{})}async function IUe(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/${r}/fast-fix`,{attributes:n})}async function CUe(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function _Ue(e,t){return e.post("/api/v1/sale-quotes/bulk-accept",{resourceIds:t})}async function wUe(e,t){return e.post("/api/v1/sale-orders/bulk-confirm",{resourceIds:t})}async function vUe(e,t,r){return e.post(`/api/v1/${Ml[t]}/bulk-delete`,{resourceIds:r})}async function SUe(e,t){return e.post("/api/v1/sale-orders/line-items/bulk-upsert",{saleOrders:t},SI)}var Ml,Nre=J(()=>{"use strict";tr();ot();Ml={SALE_QUOTE:"sale-quotes",SALE_ORDER:"sale-orders"}});async function DUe(e,t,r){return e.list(`/api/v1/${$l[t]}`,r)}async function ql(e,t,r){return e.get(`/api/v1/${$l[t]}/${r}`)}async function M2(e,t,r){return e.search(`/api/v1/${$l[t]}/search`,r)}async function U2(e,t,r){return e.search(`/api/v1/${$l[t]}/line-items/search`,r)}async function Cx(e,t){return e.post("/api/v1/purchase-requests",{...t,currency:Wt(t.currency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function _x(e,t){return e.post("/api/v1/purchase-orders",{...t,currency:Wt(t.currency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function $2(e,t,r,n){return e.post(`/api/v1/${$l[t]}/${r}/convert-to-bill`,n,uP)}async function q2(e,t,r,n){return e.put(`/api/v1/${$l[t]}/${r}`,n)}async function j2(e,t,r){await e.delete(`/api/v1/${$l[t]}/${r}`)}async function Y2(e,t,r,n){return e.post(`/api/v1/${$l[t]}/${r}/void`,n?{internalNotes:n}:{})}async function H2(e,t){return e.post(`/api/v1/purchase-requests/${t}/accept`,{})}async function z2(e,t){return e.post(`/api/v1/purchase-orders/${t}/confirm`,{})}async function RUe(e,t,r,n){return e.post(`/api/v1/${$l[t]}/${r}/fast-fix`,{attributes:n})}async function TUe(e,t,r,n){return e.post(`/api/v1/${$l[t]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function xUe(e,t){return e.post("/api/v1/purchase-requests/bulk-accept",{resourceIds:t})}async function kUe(e,t){return e.post("/api/v1/purchase-orders/bulk-confirm",{resourceIds:t})}async function NUe(e,t,r){return e.post(`/api/v1/${$l[t]}/bulk-delete`,{resourceIds:r})}async function BUe(e,t){return e.post("/api/v1/purchase-orders/line-items/bulk-upsert",{purchaseOrders:t},SI)}var $l,Bre=J(()=>{"use strict";tr();ot();$l={PURCHASE_REQUEST:"purchase-requests",PURCHASE_ORDER:"purchase-orders"}});function Ore(e,t){return Object.keys(vf).filter(r=>r!==e&&t[vf[r]]!==void 0).map(r=>vf[r])}function CHt(e){let t=Array.isArray(e?.lineItems)?e.lineItems:[],r=[];for(let n of t){let i=n;typeof i?.resourceId!="string"||i.resourceId===""||r.push({resourceId:i.resourceId,...typeof i.name=="string"&&{name:i.name}})}return r}function _Ht(e,t,r,n){let i=CHt(r);if(i.length===0)return;let o=LUe[e],s=new Set(t.map(c=>c?.resourceId).filter(c=>typeof c=="string"&&c!=="").map(OUe));if(s.size===0)return n.appendLines===!0?void 0:{code:"append_would_duplicate",message:`None of the ${t.length} lineItems carries a resourceId, so the API would ADD them beside the ${i.length} line(s) already on this ${o}: an update never replaces lines. To edit lines, send every stored line with its resourceId (set deleted:true on a line to remove it; a line without a resourceId is added). Stored lines: ${FUe(i)}. To add these lines on purpose, set ${n.appendOptIn}.`,storedLines:i};let a=i.filter(c=>!s.has(OUe(c.resourceId)));if(a.length!==0)return{code:"lines_not_sent",message:`lineItems must include every line already on this ${o} once any line names a resourceId, or the API refuses the update. ${a.length} not sent: ${FUe(a)}. Send each with its resourceId, and deleted:true to remove it.`,storedLines:i,missing:a}}async function Fre(e,t,r,n){if(!Array.isArray(t)||t.length===0)return;let i=(await r()).data;return _Ht(e,t,i,n)}async function QUe(e,t,r,n){let i=Ore(e,t);if(i.length>0)throw ut(new ue(`${i.join(", ")} does not apply to a ${LUe[e]}; its flag is ${vf[e]}.`));let o=await Fre(e,t.lineItems,r,n);if(o)throw ut(new ue(o.message))}var LUe,vf,OUe,FUe,Lre=J(()=>{"use strict";ot();LUe={SALE_QUOTE:"sale quote",SALE_ORDER:"sale order",PURCHASE_REQUEST:"purchase request",PURCHASE_ORDER:"purchase order"},vf={SALE_QUOTE:"isDraftToActiveSaleQuote",SALE_ORDER:"isPendingToActiveSaleOrder",PURCHASE_REQUEST:"isDraftToActivePurchaseRequest",PURCHASE_ORDER:"isPendingToActivePurchaseOrder"};OUe=e=>e.trim().toLowerCase();FUe=e=>e.map(t=>t.name?`${t.resourceId} ("${t.name}")`:t.resourceId).join(", ")});async function J2(e,t){return e.list("/api/v1/journals",t)}async function wx(e,t){return e.search("/api/v1/journals/search",t)}async function vx(e,t){return e.post("/api/v1/journals",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function G2(e,t,r){return e.delete(`/api/v1/journals/${t}`,r)}async function vs(e,t){return e.get(`/api/v1/journals/${t}`)}async function OC(e,t,r,n){let i=await PUe(e,t,r,n);return e.put(`/api/v1/journals/${t}`,{...i,currency:Wt(r.currency),taxCurrency:Wt(r.taxCurrency)})}async function PUe(e,t,r,n){xM(r);let i={...r};if(typeof i.taxVatApplicable!="boolean"&&i.journalEntries?.some(s=>!!s?.taxProfileResourceId)&&(i.taxVatApplicable=!0),typeof i.taxVatApplicable=="boolean"&&typeof i.taxInclusion=="boolean")return i;let o=n;if(!o)try{o=(await vs(e,t)).data}catch(s){let a=s instanceof Error?s:new Error(String(s));throw a.message=`Could not read journal ${t} to keep its tax settings, so nothing was changed (retry, or pass taxVatApplicable and taxInclusion explicitly). ${a.message}`,ut(a)}return typeof i.taxVatApplicable!="boolean"&&typeof o?.taxVatApplicable=="boolean"&&(i.taxVatApplicable=o.taxVatApplicable),typeof i.taxInclusion!="boolean"&&typeof o?.taxInclusion=="boolean"&&(i.taxInclusion=o.taxInclusion),i}async function MUe(e,t,r,n){let i=await PUe(e,t,r,n);return e.put(`/api/v1/journals/${t}`,{...i,resourceId:t,saveAsDraft:!1})}async function Sx(e,t){return e.post("/api/v1/scheduled/journals",t,Jp)}async function V2(e,t){return En(e,"/api/v1/journals/bulk-upsert","journals",t)}async function UUe(e,t){return Zi(t,"resourceId","Pass the journal resourceId."),e.get(`/api/v1/journals/${encodeURIComponent(t)}/download`)}var Jg=J(()=>{"use strict";tr();an();ot()});async function Gg(e,t){return e.get(`/api/v1/deferrals/${t}`)}async function X2(e,t){return e.search("/api/v1/deferrals/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function Z2(e,t){return e.post("/api/v1/deferrals",{...t,saveAsDraft:t.saveAsDraft??!0},Pke)}async function eq(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ut(new ue(`The body names deferral ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`));let o={reference:r.reference??(n??(await Gg(e,t)).data).reference};for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=t,e.put(`/api/v1/deferrals/${t}`,o,mP)}async function tq(e,t){return e.delete(`/api/v1/deferrals/${t}`)}async function rq(e,t,r){return e.post(`/api/v1/close-out/deferrals/${t}`,{closeOutDate:r,resourceId:t},mP)}async function nq(e,t){return e.post(`/api/v1/reopen/deferrals/${t}`,{},mP)}async function iq(e,t){return e.get("/api/v1/deferrals/totals",t)}async function oq(e,t,r){return e.get(`/api/v1/deferrals/${t}/schedule`,{viewDate:r})}async function sq(e,t){return e.search("/api/v1/deferrals/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function aq(e,t){return e.search("/api/v1/deferral-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function cq(e,t){return e.search("/api/v1/deferral-accounts/search",{...t,searchTerms:t.searchTerms??[],sort:t.sort??{sortBy:["accountCode"],order:"ASC"}})}async function lq(e,t){return e.put("/api/v1/deferral-accounts",{accounts:t},Mke)}async function uq(e,t){return e.post("/api/v1/deferrals/preview-custom-schedule",t,et)}async function dq(e,t){return mt(t,"deferrals",500,"deferrals"),jo(t,$Ue),En(e,"/api/v1/deferrals/bulk-upsert","deferrals",t)}async function fq(e,t){return mt(t,"deferrals",500,"deferrals"),jo(t,$Ue),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`deferrals[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that deferral. Bulk update does not take tags: change them with update_deferral (clio deferrals update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/deferrals/bulk-update","deferrals",t)}var W2,K2,$Ue,pq,hq=J(()=>{"use strict";an();ot();tr();W2=["PREPAID_EXPENSE","DEFERRED_REVENUE"],K2=["STRAIGHT_LINE","CUSTOM_SCHEDULE"];$Ue=["amortizationStartDate"];pq={deferralCategory:["in"],deferralType:["in"],deferralStatus:["in"],deferralAccount:{resourceId:["in"]},deferralAmount:["gte","lte"],deferralReference:["contains"],deferralName:["contains"]}});function jUe(e){return Array.isArray(e)?`with ${e.join(" / ")}`:e===mq?"with an operator":`with ${Object.keys(e).join(", ")}`}function HUe(e,t,r,n){let i=s=>ut(new ue(`${e} filter.${n}: ${s} The API ignores it and would return an unfiltered report. Nothing was sent.`));if(!YUe(t))throw i(`expected an object ${jUe(r)}.`);let o=Object.keys(t);if(o.length===0)throw i(`the expression is empty, so it filters nothing; give ${jUe(r).replace(/^with /,"")} or drop the field.`);if(r!==mq)for(let s of o)if(Array.isArray(r)){if(!r.includes(s))throw i(`operator "${s}" is not read; it reads ${r.join(" / ")}.`)}else if(s in r)HUe(e,t[s],r[s],`${n}.${s}`);else throw i(`"${s}" is not a supported field; supported: ${Object.keys(r).join(", ")}.`)}function Rx(e,t){let{filter:r}=t;if(r===void 0)return;let n=wHt[e];if(!YUe(r))throw ut(new ue(`${e} filter must be an object keyed by field; supported: ${Object.keys(n).join(", ")}. Nothing was sent.`));for(let[i,o]of Object.entries(r)){let s=n[i];if(!s)throw ut(new ue(`${e} filter.${i} is not a supported field; supported: ${Object.keys(n).join(", ")}. The API ignores it and would return an unfiltered report. Nothing was sent.`));HUe(e,o,s,i)}if(Object.keys(r).length>0&&!(t.primarySnapshotStartDate&&t.primarySnapshotEndDate))throw ut(new ue(`${e} filter needs the period it filters over: send both primarySnapshotStartDate and primarySnapshotEndDate. Nothing was sent.`))}var mq,qUe,Dx,wHt,YUe,zUe=J(()=>{"use strict";ot();hq();mq="expression",qUe=(...e)=>Object.fromEntries(e.map(t=>[t,mq])),Dx={loanAccount:{resourceId:["in"]},loanBalance:["gte","lte"],loanReference:["contains"],loanName:["contains"],loanType:["in"],loanStatus:["in"]},wHt={"deferrals-summary":pq,"fixed-assets-summary":qUe("assetAccount","assetName","assetReference","netBookValueAmount","purchaseValueAmount","assetStatus","assetType","assetCategory","assetDepreciationMethod"),"leases-summary":{leaseAccount:{resourceId:mq},...qUe("leaseLiability","leaseReference","leaseName","leaseType","leaseStatus")},"loans-summary":Dx,"loans-roll-forward":Dx,"loans-related-party":Dx,"loans-interest":Dx,"loans-maturity-analysis":Dx},YUe=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});async function Aq(e,t){return e.post("/api/v1/generate-reports/trial-balance",t,et)}async function gq(e,t){return e.post("/api/v1/generate-reports/balance-sheet",t,et)}async function yq(e,t){return e.post("/api/v1/generate-reports/profit-and-loss",t,et)}async function Eq(e,t){return e.post("/api/v1/generate-reports/cashflow",t,et)}async function bq(e,t){return e.post("/api/v1/generate-reports/ar-summary-report",t,et)}async function Iq(e,t){return e.post("/api/v1/generate-reports/ap-summary-report",t,et)}function Tx(e,t){let{root:r,rows:n}=vHt[t],i=e.data?.[r]??{},o=Array.isArray(i[n])?i[n]:[],s={current:0,lessThanOneMonth:0,oneMonth:0,twoMonths:0,threeMonths:0,older:0,total:0};for(let u of o)s.current+=u.currentIso??0,s.lessThanOneMonth+=u.lessThanOneMonthIso??0,s.oneMonth+=u.oneMonthIso??0,s.twoMonths+=u.twoMonthsIso??0,s.threeMonths+=u.threeMonthsIso??0,s.older+=u.olderIso??0,s.total+=u.balanceIso??0;let a=u=>Math.round(u*100)/100,c=i.startDate;return{reportType:t==="receivables"?"AGED_RECEIVABLES":"AGED_PAYABLES",organizationName:i.organizationName,asAt:typeof c=="number"?new Date(c).toISOString().slice(0,10):void 0,currencyCode:i.currencyCode,currencySymbol:i.currencySymbol,buckets:{current:a(s.current),lessThanOneMonth:a(s.lessThanOneMonth),oneMonth:a(s.oneMonth),twoMonths:a(s.twoMonths),threeMonths:a(s.threeMonths),older:a(s.older)},totalOutstanding:a(s.total),contactCount:o.length}}async function Cq(e,t){return e.post("/api/v1/generate-reports/cash-balance",t,et)}function xx(e){if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<1||e>Vg))throw new ct(`limit must be a whole number from 1 to ${Vg} (got ${String(e)}).`)}function SHt(e){let t=[];for(let r=0;r<e.length;r+=Hu)t.push(e.slice(r,r+Hu));return t}function DHt(e){let{accountResourceIds:t,...r}=e;return t&&t.length>0?{...r,filter:{account:{resourceId:{in:t}}}}:r}async function kx(e,t){return e.post("/api/v1/generate-reports/general-ledger",DHt(t),et)}async function GUe(e,t,r=Vg,n){xx(r);let i=t.accountResourceIds??[];if(i.length<=Hu)return JUe(e,t,r,n);let o,s=SHt(i);for(let[a,c]of s.entries()){let u=o?.data.searchGeneralLedgersReport?.data?.length??0,d=n===void 0?void 0:n-u,f=await JUe(e,{...t,accountResourceIds:c},r,d);if(!o)o=f;else{let p=o.data.searchGeneralLedgersReport??{},h=f.data.searchGeneralLedgersReport??{};o.data.searchGeneralLedgersReport={...p,data:[...p.data??[],...h.data??[]],totalElements:(p.totalElements??0)+(h.totalElements??0),totalPages:(p.totalPages??0)+(h.totalPages??0)},o.truncated=o.truncated||f.truncated}if(n!==void 0&&(o.data.searchGeneralLedgersReport?.data?.length??0)>=n&&a<s.length-1){o.truncated=!0;break}}return o}async function JUe(e,t,r,n){let i,o=await bf(async(a,c)=>{let u=await kx(e,{...t,limit:c,offset:a});a===0&&(i=u);let d=u.data?.searchGeneralLedgersReport??{};return{data:d.data??[],totalElements:d.totalElements??0,totalPages:d.totalPages??0}},{pageSize:r,offsetMode:"row",maxItems:n}),s=i?.data?.searchGeneralLedgersReport??{};return{data:{...i?.data,searchGeneralLedgersReport:{...s,data:o.data}},truncated:o.truncated}}async function _q(e,t){return e.post("/api/v1/generate-reports/vat-ledger",t,et)}async function wq(e,t){return e.post("/api/v1/generate-reports/equity-movement",t,et)}async function vq(e,t){return e.post("/api/v1/generate-reports/bank-balance-summary",t,et)}async function Sq(e,t){return e.post("/api/v1/generate-reports/bank-reconciliation-summary",t,et)}async function Dq(e,t){return e.post("/api/v1/generate-reports/bank-reconciliation-details",t,et)}async function Rq(e,t){return Rx("fixed-assets-summary",t),e.post("/api/v1/generate-reports/fixed-assets-summary",t,et)}async function Tq(e,t){return e.post("/api/v1/generate-reports/fixed-assets-recon-summary",t,et)}async function xq(e,t){return Rx("deferrals-summary",t),e.post("/api/v1/generate-reports/deferrals-summary",t,et)}async function kq(e,t){return e.post("/api/v1/generate-reports/deferrals-recon-summary",t,et)}async function VUe(e,t){return Rx("leases-summary",t),e.post("/api/v1/generate-reports/leases-summary",t,et)}async function WUe(e,t){return e.post("/api/v1/generate-reports/leases-recon-summary",t,et)}async function Nx(e,t,r){let n=RHt[t];return t!=="loans-recon-summary"&&Rx(t,r),e.post(n,r,et)}async function Nq(e,t){return e.post("/api/v1/generate-reports/ar-report",t,et)}async function Bq(e,t){return e.post("/api/v1/generate-reports/ap-report",t,et)}async function Oq(e){return e.get("/api/v1/ledger/highlights")}var vHt,FC,Vg,Hu,RHt,Qre=J(()=>{"use strict";JD();fo();zUe();tr();vHt={receivables:{root:"generateAgedReceivablesReportGroupByContact",rows:"customerSummary"},payables:{root:"generateAgedPayablesReportGroupByContact",rows:"supplierSummary"}};FC=["ACCOUNT","CONTACT","TRANSACTION","RELATIONSHIP","CAPSULE"],Vg=1e3,Hu=100;RHt={"loans-summary":"/api/v1/generate-reports/loans-summary","loans-roll-forward":"/api/v1/generate-reports/loans-roll-forward","loans-related-party":"/api/v1/generate-reports/loans-related-party","loans-interest":"/api/v1/generate-reports/loans-interest","loans-maturity-analysis":"/api/v1/generate-reports/loans-maturity-analysis","loans-recon-summary":"/api/v1/generate-reports/loans-recon-summary"}});async function Fq(e,t){return e.list("/api/v1/catalogs",t)}async function Lq(e,t){return e.get(`/api/v1/catalogs/${encodeURIComponent(t)}`)}async function Qq(e,t){return e.search("/api/v1/catalogs/search",t)}async function Pq(e,t){return e.post("/api/v1/catalogs",t)}async function Mq(e,t,r){return e.put(`/api/v1/catalogs/${encodeURIComponent(t)}`,r)}async function Uq(e,t){await e.delete(`/api/v1/catalogs/${encodeURIComponent(t)}`)}var Pre=J(()=>{"use strict"});import{isDeepStrictEqual as THt}from"node:util";function Fx(e,t="templateConfiguration"){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{throw new ue(`${t} is not valid JSON. Pass the layout as an object, or as a JSON string of one.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new ue(`${t} must be a JSON object (the layout), got ${Array.isArray(r)?"an array":typeof r}.`);let{[jq]:n,...i}=r;return i}function Hq(e){let{[jq]:t,...r}=e;return JSON.stringify(r)}function e$e(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,JSON.stringify(r??null).length]))}function jre(e,t){let r=t.filter(n=>!(n in e));if(r.length>0)throw new ue(`This layout has no ${r.map(n=>`"${n}"`).join(", ")}. Its keys are: ${Object.keys(e).join(", ")}.`);return Object.fromEntries(t.map(n=>[n,e[n]]))}function Yre(e){let t=Ox(e.rowConfigs);if(!t)return;let r=n=>n.filter(i=>i&&typeof i=="object").map(i=>{let o=i.formulaConfig?.formula,s=Ox(i.children);return{id:String(i.id),...typeof i.name=="string"?{name:i.name}:{},...typeof i.rowType=="string"?{rowType:i.rowType}:{},...typeof o=="string"&&o!==""?{formula:o}:{},...s&&s.length>0?{children:r(s)}:{}}});return r(t)}function t$e(e,t){return Bx(e,t).row}function kHt(e){return"path"in e?e.path.join("."):e.field?`row "${e.rowId}".${e.field}`:`row "${e.rowId}"`}function n$e(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(r$e.has(r))throw new ue(`${t} contains the key "${r}", which is not allowed.`);n$e(e[r],t)}}function Hre(e,t,r){if(!Array.isArray(t)||t.length===0)throw new ue("edits must be a non-empty array of changes.");let n=structuredClone(e),i=[];t.forEach((s,a)=>{let c=`edits[${a}]`,u=NHt(s,c);try{i.push(...BHt(n,u))}catch(d){throw d instanceof ue?new ue(`${c} (${u.op}): ${d.message}`):d}});let o=zq(e,n,r);if(o.length>0)throw new ue(`Nothing was saved. The edits would introduce: ${o.join("; ")}.`);return{configuration:n,touched:i}}function NHt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ue(`${t} must be an object with an "op".`);let r=e;if(!LC.includes(r.op))throw new ue(`${t}.op must be one of ${LC.join(", ")} (got ${JSON.stringify(r.op)}).`);let n=(i,o)=>{let s=r[i];if(!(o==="string"?typeof s=="string"&&s!=="":!!s&&typeof s=="object"&&!Array.isArray(s)))throw new ue(`${t} (${r.op}) needs "${i}" (${o==="string"?"a non-empty string":"an object"}).`)};switch(r.op){case"set":case"insert":if(n("path","string"),!("value"in r))throw new ue(`${t} (${r.op}) needs "value".`);break;case"remove":n("path","string");break;case"updateRow":n("rowId","string"),n("fields","object");break;case"addRow":n("row","object");break;case"removeRow":n("rowId","string");break;case"moveRow":n("rowId","string");break}if("index"in r&&r.index!==void 0&&!(Number.isInteger(r.index)&&r.index>=0))throw new ue(`${t} (${r.op}): index must be a whole number, 0 or more.`);for(let i of["value","fields","row"])i in r&&n$e(r[i],`${t} (${r.op}) ${i}`);return r}function BHt(e,t){switch(t.op){case"set":{let r=Mre(t.path),{container:n,key:i}=Ure(e,r,"set"),o=Array.isArray(n)?i==="-"?n.length:qq(i,n.length,!0):void 0,s=Array.isArray(n)?n[o]:n[i],a=t.fromText&&typeof t.value=="string"?FHt(t.value,s,$q(r)):structuredClone(t.value);return OHt(s,a,$q(r)),Array.isArray(n)?(n[o]=a,[{path:[...r.slice(0,-1),String(o)]}]):(n[i]=a,[{path:r}])}case"insert":{let r=Mre(t.path),{container:n,key:i}=Ure(e,r,"set");if(!Array.isArray(n))throw new ue(`insert adds to a list, and "${$q(r.slice(0,-1))||"(the layout)"}" is not one. Use set to change a key.`);let o=i==="-"?n.length:qq(i,n.length,!0);return n.splice(o,0,structuredClone(t.value)),[{path:[...r.slice(0,-1),String(o)]}]}case"remove":{let r=Mre(t.path),{container:n,key:i}=Ure(e,r,"remove");if(Array.isArray(n))return n.splice(qq(i,n.length,!1),1),[];if(!Object.hasOwn(n,i))throw new ue(`nothing at "${t.path}" to remove.`);return delete n[i],[{path:r,removed:!0}]}case"updateRow":{let r=Bx(e,t.rowId);for(let n of Object.keys(t.fields)){let i=xHt[n];if(i)throw new ue(`"${n}" cannot be set with updateRow: ${i}.`)}return Object.assign(r.row,structuredClone(t.fields)),Object.keys(t.fields).map(n=>({rowId:t.rowId,field:n}))}case"addRow":{let r=structuredClone(t.row);if(typeof r.id!="string"||r.id==="")throw new ue('the new row needs a string "id", unique in this layout.');if(typeof r.rowType!="string")throw new ue(`the new row needs a "rowType" (${i$e.join(", ")}).`);if(jl(e).some(i=>i.row.id===r.id))throw new ue(`a row with id "${r.id}" already exists.`);let n=XUe(e,t.parentId??null);return r.parentId=t.parentId??null,n.splice(KUe(t.index,n.length),0,r),[{rowId:r.id}]}case"removeRow":{let r=Bx(e,t.rowId),n=new Set(jl({rowConfigs:[r.row]}).map(o=>o.row.id)),i=o$e(e).filter(o=>!n.has(o.rowId)&&o.refs.some(s=>n.has(s)));if(i.length>0)throw new ue(`row "${t.rowId}" is used in the formula of ${i.map(o=>`"${o.rowId}"`).join(", ")}. A formula that names a missing row silently counts it as 0, so update or remove those rows first.`);return r.siblings.splice(r.index,1),[]}case"moveRow":{let r=Bx(e,t.rowId),n=t.parentId??null;if(n!==null&&new Set(jl({rowConfigs:[r.row]}).map(s=>s.row.id)).has(n))throw new ue(`row "${t.rowId}" cannot move inside itself or its own child "${n}".`);r.siblings.splice(r.index,1);let i=XUe(e,n);return r.row.parentId=n,i.splice(KUe(t.index,i.length),0,r.row),[{rowId:t.rowId}]}}}function Yq(e){if(e==null)return"empty";if(Array.isArray(e))return"list";switch(typeof e){case"string":return"text";case"number":return"number";case"boolean":return"true/false";default:return"object"}}function OHt(e,t,r){let n=Yq(e),i=Yq(t);if(n==="empty"||n===i)return;let o=n==="text"&&i==="empty"?' To clear text, set "" instead.':"";throw new ue(`"${r}" holds ${n==="list"||n==="object"?`a ${n}`:n}; got ${i==="list"||i==="object"?`a ${i}`:i}.${o}`)}function FHt(e,t,r){switch(Yq(t)){case"text":return e;case"number":{let n=Number(e);if(e.trim()===""||!Number.isFinite(n))throw new ue(`"${r}" is a number; "${e}" is not one.`);return n}case"true/false":if(e==="true"||e==="false")return e==="true";throw new ue(`"${r}" is true or false; got "${e}".`);case"list":case"object":try{return JSON.parse(e)}catch{throw new ue(`"${r}" holds a ${Yq(t)}; pass it as JSON.`)}default:try{return JSON.parse(e)}catch{return e}}}function Mre(e){let t=e.startsWith("/")?e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")):e.split(".");if(t.length===0||t.some(n=>n===""))throw new ue(`"${e}" is not a path. Use dotted keys like "pdfTitleConfigs.title", or a JSON Pointer like "/pdfTitleConfigs/title".`);let r=t.find(n=>r$e.has(n));if(r)throw new ue(`"${e}" uses "${r}", which is not a layout key.`);if(t[0]===jq)throw new ue(`${jq} is written by the server on every save and cannot be edited.`);return t}function $q(e){return e.join(".")}function Ure(e,t,r){let n=e;for(let i=0;i<t.length-1;i++){let o=t[i],s=Array.isArray(n)?n[qq(o,n.length,!1)]:n&&typeof n=="object"?n[o]:void 0;if(!s||typeof s!="object"){let a=$q(t.slice(0,i+1)),c=n&&typeof n=="object"&&!Array.isArray(n)?` Keys here: ${Object.keys(n).join(", ")||"(none)"}.`:"";throw new ue(`"${a}" does not exist or is not an object or list, so nothing can be ${r==="set"?"set":"removed"} under it.${c}`)}n=s}return{container:n,key:t[t.length-1]}}function qq(e,t,r){let n=Number(e),i=r?t:t-1;if(!Number.isInteger(n)||n<0||n>i)throw i<0?new ue(`the list is empty, so there is no position "${e}"${r?'; use "-" to append':""}.`):new ue(`"${e}" is not a valid position in a list of ${t} (use 0-${i}${r?', or "-" to append':""}).`);return n}function KUe(e,t){if(e===void 0)return t;if(e>t)throw new ue(`index ${e} is past the end: there are ${t+1} positions (0-${t}).`);return e}function Ox(e){return Array.isArray(e)?e:void 0}function jl(e){let t=[],r=i=>{i.forEach((o,s)=>{if(!o||typeof o!="object")return;t.push({row:o,siblings:i,index:s});let a=Ox(o.children);a&&r(a)})},n=Ox(e.rowConfigs);return n&&r(n),t}function Bx(e,t){if(jl(e).length===0)throw new ue(`this layout has no rows (only ${NC.join(", ")} templates have them).`);let r=jl(e).find(n=>n.row.id===t);if(!r){let n=jl(e).map(i=>i.row.id).filter(i=>typeof i=="string").slice(0,40);throw new ue(`no row "${t}". Row ids here: ${n.join(", ")}${n.length===40?", ...":""}.`)}return r}function XUe(e,t){if(t===null){if(!Ox(e.rowConfigs))throw new ue("this layout has no rows to add to.");return e.rowConfigs}let r=Bx(e,t).row;return Array.isArray(r.children)||(r.children=[]),r.children}function MHt(e){return[...e.matchAll(PHt)].map(t=>(t[1]??t[2]??t[3]).trim()).filter(Boolean)}function o$e(e){return jl(e).flatMap(({row:t})=>{let r=t.formulaConfig?.formula;return typeof r=="string"&&r.trim()!==""?[{rowId:String(t.id),refs:MHt(r)}]:[]})}function Wg(e,t){return t.split(".").reduce((r,n)=>r&&typeof r=="object"?r[n]:void 0,e)}function Kg(e,t,r,n){r!=null&&(typeof r!="string"||!n.includes(r))&&e.push(`${t} = ${JSON.stringify(r)} (allowed: ${n.join(", ")})`)}function ZUe(e,t){let r=[];for(let[c,u]of Object.entries(jHt))Kg(r,c,Wg(e,c),u);let n=ju[t].periodKind==="point"?qHt:$Ht;Kg(r,"basePeriodConfig.periodType",Wg(e,"basePeriodConfig.periodType"),n);for(let c of["startDate","endDate"]){let u=Wg(e,`basePeriodConfig.${c}`);u!=null&&!(Number.isInteger(u)&&u>=0)&&r.push(`basePeriodConfig.${c} = ${JSON.stringify(u)} (a date in epoch milliseconds, a whole number)`)}let i=Wg(e,"basePeriodConfig.startDate"),o=Wg(e,"basePeriodConfig.endDate");if(typeof i=="number"&&typeof o=="number"&&i>o&&r.push("basePeriodConfig.startDate is after endDate"),Wg(e,"basePeriodConfig.periodType")==="custom"){let c=ju[t].periodKind==="point"?["endDate"]:["startDate","endDate"];for(let u of c)typeof Wg(e,`basePeriodConfig.${u}`)!="number"&&r.push(`basePeriodConfig.${u} must be a date in epoch milliseconds when periodType is custom`)}Array.isArray(e.columnConfigs)&&e.columnConfigs.forEach((c,u)=>Kg(r,`columnConfigs.${u}.type`,c?.type,YHt)),Array.isArray(e.includedComponents)&&e.includedComponents.forEach((c,u)=>{Kg(r,`includedComponents.${u}.type`,c?.type,HHt)});let s=jl(e),a=new Map;for(let{row:c}of s){let u=String(c.id);a.set(u,(a.get(u)??0)+1);let d=`row "${u}"`;Kg(r,`${d}.rowType`,c.rowType,i$e),Array.isArray(c.actionCriteria)&&c.actionCriteria.forEach(f=>{Kg(r,`${d}.actionCriteria.criteriaVariable`,f?.criteriaVariable,LHt),Kg(r,`${d}.actionCriteria.criteriaCondition`,f?.criteriaCondition,QHt)})}for(let[c,u]of a)u>1&&r.push(`row id "${c}" is used ${u} times`);for(let c of o$e(e))for(let u of c.refs)a.has(u)||r.push(`the formula of row "${c.rowId}" names "${u}", which is not a row (it would count as 0)`);return r}function zq(e,t,r,n={}){let i=new Set(ZUe(e,r)),o=ZUe(t,r).filter(c=>!i.has(c));if(n.engineRows===!1)return o;let s=new Set(jl(e).map(c=>c.row.id)),a=new Set(jl(t).map(c=>c.row.id));for(let c of UHt[r]??[])s.has(c)&&!a.has(c)&&o.push(`row "${c}" was removed, and the report engine reads it by id (totals, tax section or PDF footer)`);return o}function $re(e,t){if("rowId"in t){let r=jl(e).find(n=>n.row.id===t.rowId);return r?t.field?r.row[t.field]:r.row.id:void 0}return t.path.reduce((r,n)=>r&&typeof r=="object"?r[n]:void 0,e)}function qre(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,n)=>qre(r,t[n]));if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let r=e,n=t;return Object.keys(r).every(i=>qre(r[i],n[i]))&&Object.keys(n).every(i=>i in r||s$e(n[i]))}return THt(e,t)}function a$e(e,t,r){return r.filter(n=>"removed"in n&&n.removed?!s$e($re(t,n)):!qre($re(e,n),$re(t,n))).map(kHt)}function Lx(e){return(Array.isArray(e.includedComponents)?e.includedComponents:[]).filter(r=>r?.type==="TEMPLATE").map((r,n)=>({templateResourceId:String(r.templateConfig?.templateResourceId??r.id??""),templateOrder:n+1}))}function zre(e,t){let r=Array.isArray(e.includedComponents)?e.includedComponents:[],n=new Map(r.filter(c=>c?.type==="TEMPLATE").map(c=>[String(c.templateConfig?.templateResourceId??c.id),c])),i=t.map(c=>{let u=n.get(c.templateResourceId);return{...u??{},id:u?.id??c.templateResourceId,type:"TEMPLATE",templateConfig:{...u?.templateConfig??{},reportType:c.reportType,templateName:c.templateName,templateResourceId:c.templateResourceId}}}),o=r.flatMap((c,u)=>c?.type==="TEMPLATE"?[u]:[]),s=[],a=0;if(r.forEach((c,u)=>{if(c?.type!=="TEMPLATE"?s.push(c):a<i.length&&s.push(i[a++]),u===o[o.length-1])for(;a<i.length;)s.push(i[a++])}),a<i.length){let c=s.findIndex(u=>u?.type==="SIGNATURE_PAGE"||u?.type==="APPENDIX");s.splice(c>=0?c:s.length,0,...i.slice(a))}return{...e,includedComponents:s}}function Jre(e="CUSTOM"){return{reportPackType:e,templateFont:"Inter",decorator:"FIRST_PAGE_ONLY",isUppercase:!1,enablePageNumber:!0,roundedValuesMode:"AS_PER_TEMPLATE",basePeriodConfig:{periodType:"this_month"},includedComponents:[]}}var jq,LC,xHt,r$e,i$e,LHt,QHt,PHt,UHt,$Ht,qHt,jHt,YHt,HHt,s$e,Jq=J(()=>{"use strict";ot();Yu();jq="coaSnapshot";LC=["set","insert","remove","updateRow","addRow","removeRow","moveRow"],xHt={id:"a row id cannot change: removeRow it and addRow a new one",children:"use addRow / removeRow / moveRow on the child rows",parentId:"use moveRow"};r$e=new Set(["__proto__","constructor","prototype"]);i$e=["GROUP","SECTION","TOTAL","COMBINE_ACCOUNT","TEXT","ROW","GROUP_TOTAL"],LHt=["ACCOUNT_TYPE","ACCOUNT_CODE","ACCOUNT_NAME","ACCOUNT_CLASS"],QHt=["IS","IS_NOT","IS_IN","IS_NOT_IN","CONTAINS","DOES_NOT_CONTAIN","STARTS_WITH","ENDS_WITH"];PHt=/GT\(\s*([^)]*?)\s*\)|([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})|([^+\-\s()]+)/gi;UHt={PROFIT_AND_LOSS:["TOTAL_NET_PROFIT","TOTAL_NET_PROFIT_BEFORE_TAX","TOTAL_NET_PROFIT_AFTER_TAX","TOTAL_GROSS_PROFIT","TOTAL_OPERATING_PROFIT","TOTAL_OTHER_PROFIT","TOTAL_PBFIT","TOTAL_PROFIT_BEFORE_INCOME_TAX","TOTAL_PROFIT"],BALANCE_SHEET:["TOTAL_ASSETS","TOTAL_LIABILITIES_AND_EQUITY"],CASHFLOW:["NET_CASHFLOW","CASH_SUMMARY_BEGINNING_CASH_BALANCE","CASH_SUMMARY_NET_INCREASE_IN_CASH","CASH_SUMMARY_ENDING_CASH_BALANCE"]},$Ht=["this_month","last_month","this_quarter","last_quarter","this_year","last_year","this_week","this_financial_year","last_financial_year","previous_financial_year","this_financial_quarter","this_financial_year_this_quarter","last_financial_quarter","previous_financial_quarter","this_financial_year_last_quarter","custom"],qHt=["today","end_of_this_month","end_of_last_month","end_of_last_quarter","end_of_last_financial_quarter","end_of_last_financial_year","custom"],jHt={colorTheme:["default","calm","bold","trust","social","ivory","gold","peach"],margins:["default","compact","comfortable"],fontSize:["default","smaller","larger"],templateFont:["Inter","LatoFont","Roboto","Figtree","SourceSans3"],templateStyle:["REPORT_TEMPLATE_CLASSIC","REPORT_TEMPLATE_BALANCED","REPORT_TEMPLATE_MODERN","REPORT_TEMPLATE_UNIFORM"],lineBreak:["L0","L1","L2","L3"],"pdfTitleConfigs.layout":["left_aligned","center_aligned"],"pdfTitleConfigs.headline":["HEADLINE_COMPANY_NAME","HEADLINE_REPORT_TITLE"],"sortConfigs.type":["FIXED","CUSTOM"],"sortConfigs.primarySortBy":["CODE_ASC","CODE_DESC","NAME_ASC","NAME_DESC","AMOUNT_ASC","AMOUNT_DESC"],"sortConfigs.secondarySortBy":["CODE_ASC","CODE_DESC","NAME_ASC","NAME_DESC","AMOUNT_ASC","AMOUNT_DESC"],reportPackType:["ACCOUNTING","FINANCIALS","MANAGEMENT","PAYABLES","RECEIVABLES","CUSTOM"],decorator:["FIRST_PAGE_ONLY","ALL_PAGES","NO_DECORATOR"],roundedValuesMode:["AS_PER_TEMPLATE","ROUNDED_VALUES","EXACT_VALUES"]},YHt=["COMPARE","YEAR_TO_DATE","VARIANCE","ACCOUNT_CODE","TOTAL","MONTH_TO_DATE","CURRENT_PERIOD"],HHt=["COVER_PAGE","TABLE_OF_CONTENTS","TEMPLATE","SIGNATURE_PAGE","APPENDIX"];s$e=e=>e==null||e===""});import{isDeepStrictEqual as zHt}from"node:util";function QC(e){return e.templateConfiguration===void 0||e.templateConfiguration===null||e.templateConfiguration===""?{}:Fx(e.templateConfiguration)}function GHt(e){try{return QC(e)}catch{return{}}}function Qx(e){let t=0;try{t=Hq(QC(e)).length}catch{t=typeof e.templateConfiguration=="string"?e.templateConfiguration.length:0}return{resourceId:e.resourceId,templateName:e.templateName??"",reportType:e.reportType??"",...e.reportCategory?{reportCategory:e.reportCategory}:{},isDefault:e.isDefault===!0,...e.reportPackType?{reportPackType:e.reportPackType}:{},...Array.isArray(e.packTemplates)&&e.packTemplates.length>0?{packTemplates:e.packTemplates.map((r,n)=>({templateResourceId:r.templateResourceId,...r.templateName?{templateName:r.templateName}:{},...r.reportType?{reportType:r.reportType}:{},templateOrder:r.templateOrder??n+1}))}:{},configurationChars:t}}async function Sf(e){let t=await e.list("/api/v1/organization-report-template"),{reportTemplates:r,...n}=t;return Array.isArray(r)&&r.length>0&&(!t.data||t.data.length===0)?{...n,data:r,totalElements:r.length,totalPages:1}:{...n,data:Array.isArray(t.data)?t.data:[],totalElements:t.totalElements??0,totalPages:t.totalPages??0}}async function Gq(e,t){let r=await Sf(e);return{...r,data:r.data.map(Qx)}}async function Vq(e,t){Dre(t.filter);let{data:r}=await Sf(e),n=hUe(r.filter(i=>X$(i,t.filter)),t.sort?.sortBy,t.sort?.order).map(Qx);return{data:n,totalElements:n.length,totalPages:1}}async function Gre(e,t){return e.get(`/api/v1/organization-report-template/${encodeURIComponent(t)}`)}function Dh(e){return e.trim().toLowerCase().replace(/ /g,"_")}async function Df(e,t,r={}){let n=String(t??"").trim();if(!n)throw new ue("Name the template: its resourceId or its exact name.");if(vc.test(n)){let u=r.rows?r.rows.find(d=>d.resourceId.toLowerCase()===n.toLowerCase()):(await Gre(e,n))?.data;if(!u)throw new ue(`No report template ${n} in this organization. ${l$e}`);if(r.reportType&&u.reportType!==r.reportType)throw u$e(u,r.reportType,r.rows??(await Sf(e)).data);return u}let i=r.rows??(await Sf(e)).data,o=r.reportType?i.filter(u=>u.reportType===r.reportType):i,s=o.filter(u=>u.templateName===n),a=s.length>0?s:o.filter(u=>Dh(u.templateName??"")===Dh(n));if(a.length===1)return a[0];if(a.length>1)throw new ue(`"${n}" names ${a.length} templates: ${a.map(u=>`${u.reportType} "${u.templateName}" (${u.resourceId})`).join(", ")}. Pass the resourceId of the one you mean.`);if(r.reportType){let u=i.find(d=>Dh(d.templateName??"")===Dh(n));if(u)throw u$e(u,r.reportType,i)}let c=gf(n,[...o],u=>u.templateName??"",{threshold:.35,limit:3}).map(u=>`${u.item.reportType} "${u.item.templateName}"`);throw new ue(`No ${r.reportType?`${r.reportType} `:""}report template named "${n}".`+(c.length>0?` Did you mean: ${c.join(", ")}?`:` ${l$e}`))}function u$e(e,t,r){let n=r.filter(i=>i.reportType===t).map(i=>`"${i.templateName}"`);return new ue(`"${e.templateName}" is a ${e.reportType} template; this needs a ${t} template (this organization has: ${n.join(", ")||"none"}).`)}function VHt(e){if(!(e==null||e==="")){if(Array.isArray(e))return e.map(String);if(typeof e=="string"){let t=e.trim();if(t.startsWith("["))try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(String)}catch{}return t.split(",").map(r=>r.trim()).filter(Boolean)}throw new ue('keys must be a list of top-level layout key names, e.g. ["pdfTitleConfigs", "columnConfigs"].')}}async function Wq(e,t,r={}){let n=VHt(r.keys);if(r.row!==void 0&&typeof r.row!="string")throw new ue("row must be a row id (text).");let i=await Df(e,t),o=QC(i),s=Qx(i);if(r.row!==void 0&&(s.row=t$e(o,r.row),!n?.length))return s;if(n?.includes(d$e)){let a=Yre(o);if(!a)throw new ue(`This layout has no rows (only ${NC.join(", ")} templates have them).`);let c=n.filter(u=>u!==d$e);return c.length>0&&(s.templateConfiguration=jre(o,c)),s.rowOutline=f$e(a,c$e-JSON.stringify(s).length),s}if(n&&n.length>0)s.templateConfiguration=jre(o,n);else if(r.whole||s.configurationChars<=JHt)s.templateConfiguration=o;else{s.configurationKeys=e$e(o);let a=Yre(o);a&&(s.rowOutline=f$e(a,c$e-JSON.stringify(s).length))}return s}function f$e(e,t){if(JSON.stringify(e).length<=t)return e;let r=e.map(({children:n,...i})=>({...i,...n?{childCount:n.length}:{}}));return JSON.stringify(r).length<=t?r:void 0}async function PC(e,t,r){p$e(t,{allowPack:!1});let n=ju[t];h$e(r,t);let i=r!==void 0&&n.frameworkChangesDefault?r:void 0,o=await Px(()=>e.get("/api/v1/organization-report-template/default-configuration",{reportType:t,...i?{framework:i}:{}}),{reportType:t,framework:r,verb:"default"});return{reportType:t,...i?{framework:i}:{},templateConfiguration:Fx(o?.data?.templateConfiguration??"")}}async function Kq(e,t){let r=t.reportType;p$e(r,{allowPack:!0});let n=m$e(t.templateName);h$e(t.framework,r);let i=r==="REPORT_PACK";if(!i&&t.packTemplates!==void 0)throw new ue(`${Ss.packTemplates} is for REPORT_PACK templates only.`);let o=(await Sf(e)).data;A$e(o,r,n);let s=t.templateConfiguration!==void 0?Fx(t.templateConfiguration):void 0;s&&!i&&await KHt(e,s,r,t.framework),i&&(s??=Jre());let a=[];if(t.edits!==void 0){s??=(await PC(e,r,t.framework)).templateConfiguration;let f=s;({configuration:s,touched:a}=Hre(s,t.edits,r)),i&&y$e(f,s)}let c;if(i){let f=await g$e(e,o,t.packTemplates,s);s=zre(s??Jre(),f),c=f.map((p,h)=>({templateResourceId:p.templateResourceId,templateOrder:h+1}))}let d=(await Px(()=>e.post("/api/v1/organization-report-template",{templateName:n,reportType:r,...t.framework?{framework:t.framework}:{},...s?{templateConfiguration:Hq(s)}:{},...c?{packTemplates:c}:{}},aZ),{reportType:r,framework:t.framework,templateName:n,verb:"create"}))?.data?.resourceId;if(!d)throw new Error("The template was created but the API returned no resourceId. List the templates to find it.");return Vre(e,d,s,a)}async function Xq(e,t,r){if(r.templateName===void 0&&r.templateConfiguration===void 0&&r.edits===void 0&&r.packTemplates===void 0)throw new ue(`Nothing to change: pass ${Ss.templateName}, ${Ss.templateConfiguration}, ${Ss.edits}, or ${Ss.packTemplates}.`);let n=(await Sf(e)).data,i=await Df(e,t,{rows:n}),o=i.reportType,s=o==="REPORT_PACK";if(!s&&r.packTemplates!==void 0)throw new ue(`${Ss.packTemplates} is for REPORT_PACK templates only; "${i.templateName}" is ${o}.`);let a=r.templateName!==void 0?m$e(r.templateName):void 0;a!==void 0&&Dh(a)!==Dh(i.templateName??"")&&A$e(n,o,a);let c=r.templateConfiguration!==void 0||r.edits!==void 0||r.packTemplates!==void 0,u,d,f=[],p=async h=>{let m=QC(h),A=m,g=[];if(r.templateConfiguration!==void 0&&(A=Fx(r.templateConfiguration),WHt(m,A,o)),s&&r.packTemplates===void 0&&XHt(h,m),r.edits!==void 0){let b=A;({configuration:A,touched:g}=Hre(A,r.edits,o)),s&&y$e(b,A)}let y;if(s){let b=await g$e(e,n,r.packTemplates,A);A=zre(A,b),y=b.map((E,C)=>({templateResourceId:E.templateResourceId,templateOrder:C+1}))}return{stored:m,next:A,places:g,pack:y}};if(c){let h=await p(i);if(r.edits!==void 0&&r.templateConfiguration===void 0){let m=(await Gre(e,i.resourceId))?.data;m&&!zHt(QC(m),h.stored)&&(h=await p(m))}u=h.next,f=h.places,d=h.pack}return await Px(()=>e.put(`/api/v1/organization-report-template/${encodeURIComponent(i.resourceId)}`,{...a!==void 0?{templateName:a}:{},...u?{templateConfiguration:Hq(u)}:{},...d?{packTemplates:d}:{}}),{reportType:o,templateName:a,verb:"update"}),Vre(e,i.resourceId,u,f)}async function Zq(e,t){let r=(await Sf(e)).data,n=await Df(e,t,{rows:r}),i=r.find(s=>s.reportType===n.reportType&&s.isDefault===!0&&s.resourceId!==n.resourceId);return n.isDefault===!0?{resourceId:n.resourceId,template:Qx(n),alreadyDefault:!0}:(await Px(()=>e.post(`/api/v1/organization-report-template/${encodeURIComponent(n.resourceId)}/set-default`,void 0),{reportType:n.reportType}),{...await Vre(e,n.resourceId,void 0,[]),previousDefault:i?{resourceId:i.resourceId,templateName:i.templateName}:null})}async function ej(e,t){let r=(await Sf(e)).data,n=await Df(e,t,{rows:r}),i=n.reportType==="REPORT_PACK";if(!i&&n.isDefault===!0){let d=r.filter(f=>f.reportType===n.reportType&&f.resourceId!==n.resourceId);throw new ue(`"${n.templateName}" is the default ${n.reportType} template, so it cannot be deleted. `+(d.length>0?`Make another one the default first (set_default_organization_report_template; CLI: clio report-templates set-default), e.g. ${d.slice(0,3).map(f=>`"${f.templateName}"`).join(", ")}.`:`It is the only ${n.reportType} template; create another and make it the default first.`))}let o=r.filter(d=>d.reportType==="REPORT_PACK"&&d.resourceId!==n.resourceId),s=d=>new Set([...Lx(GHt(d)).map(f=>f.templateResourceId),...(d.packTemplates??[]).map(f=>f.templateResourceId)]),a=o.filter(d=>s(d).has(n.resourceId)),c=a.filter(d=>s(d).size===1);if(c.length>0)throw new ue(`"${n.templateName}" is the only report in the pack${c.length>1?"s":""} ${c.map(d=>`"${d.templateName}"`).join(", ")}, and deleting it would leave an empty pack. Add another report to the pack first, or delete the pack.`);await Px(()=>e.delete(`/api/v1/organization-report-template/${encodeURIComponent(n.resourceId)}`,aZ),{reportType:n.reportType});let u={resourceId:n.resourceId,deleted:!0,templateName:n.templateName,reportType:n.reportType};if(a.length>0&&(u.removedFromPacks=a.map(d=>({resourceId:d.resourceId,templateName:d.templateName}))),i&&n.isDefault===!0)try{let f=(await Sf(e)).data.find(p=>p.reportType==="REPORT_PACK"&&p.isDefault===!0);u.newDefault=f?{resourceId:f.resourceId,templateName:f.templateName}:null}catch(d){return{partialFailures:[`The pack was deleted, but the new default pack could not be read: ${d.message}`],...u}}return u}function p$e(e,t){if(!pUe(e)||!t.allowPack&&e==="REPORT_PACK"){let r=t.allowPack?ws:jg;throw new ue(`reportType must be one of ${r.join(", ")} (got ${JSON.stringify(e)}).`)}}function h$e(e,t){if(e!==void 0){if(!ju[t].takesFramework)throw new ue(`${Ss.framework} applies only to ${Yg.join(", ")} templates.`);if(!RT.includes(e))throw new ue(`framework must be one of ${RT.join(", ")} (got ${JSON.stringify(e)}).`)}}function WHt(e,t,r){let n=Object.keys(e).filter(o=>!(o in t));if(n.length>0)throw new ue(`Nothing was saved. The replacement layout leaves out ${n.join(", ")}, which the stored layout has. Send the whole layout (read it with get_organization_report_template; CLI: get --config-out), or change part of it with ${Ss.edits}.`);let i=zq(e,t,r);if(i.length>0)throw new ue(`Nothing was saved. The replacement layout would introduce: ${i.join("; ")}.`)}function m$e(e){let t=typeof e=="string"?e.trim():"";if(!t)throw new ue("templateName must have at least one visible character.");let r=[...t].length;if(r>255)throw new ue(`templateName is ${r} characters; the limit is 255.`);return t}async function KHt(e,t,r,n){let i=n===void 0||Sh.includes(n),o=(await PC(e,r,i?n:void 0)).templateConfiguration,s=Object.keys(o).filter(c=>!(c in t));if(s.length>0)throw new ue(`Nothing was saved. A ${r} layout needs ${s.join(", ")}, and this one leaves ${s.length===1?"it":"them"} out. Start from a whole layout (get_default_organization_report_template_configuration, or an existing ${r} template), or create without ${Ss.templateConfiguration} and use ${Ss.edits}.`);let a=zq(o,t,r,{engineRows:!1});if(a.length>0)throw new ue(`Nothing was saved. The layout has: ${a.join("; ")}.`)}function XHt(e,t){let r=Lx(t).map(o=>o.templateResourceId),n=[...e.packTemplates??[]].sort((o,s)=>(o.templateOrder??0)-(s.templateOrder??0)).map(o=>o.templateResourceId);if(n.length===0||r.join()===n.join())return;let i=o=>e.packTemplates?.find(s=>s.templateResourceId===o)?.templateName??o;throw new ue(`Nothing was saved. This pack's two records of its reports disagree: its layout shows ${r.map(i).join(", ")||"none"}, its report list shows ${n.map(i).join(", ")}. Pass ${Ss.packTemplates} with the reports it should hold, and both are rewritten from it.`)}function A$e(e,t,r){let n=e.find(i=>i.reportType===t&&Dh(i.templateName??"")===Dh(r));if(n)throw new ue(`A ${t} template named "${n.templateName}" already exists (${n.resourceId}). Names are unique per report type, ignoring case and treating spaces and underscores alike. Pick another name, or update that template.`)}async function g$e(e,t,r,n){let i;if(r!==void 0){if(!Array.isArray(r)||r.length===0)throw new ue(`${Ss.packTemplates} must list at least one report (a template resourceId or name).`);if(r.length>100)throw new ue(`${Ss.packTemplates} lists ${r.length} reports; the limit is 100.`);let s=r.map((c,u)=>{if(typeof c=="string")return{ref:c,order:u+1};if(c&&typeof c=="object"&&typeof c.templateResourceId=="string")return{ref:c.templateResourceId,order:c.templateOrder??u+1};throw new ue(`packTemplates[${u}] must be a template resourceId or name.`)}),a=s.map(c=>c.order);if(new Set(a).size!==a.length)throw new ue("packTemplates has two reports at the same templateOrder.");i=[...s].sort((c,u)=>c.order-u.order).map(c=>c.ref)}else if(i=Lx(n??{}).map(s=>s.templateResourceId),i.length===0)throw new ue(`A report pack needs at least one report: pass ${Ss.packTemplates}, template names or resourceIds in order.`);let o=[];for(let s of i){let a=await Df(e,s,{rows:t});if(a.reportType==="REPORT_PACK")throw new ue(`"${a.templateName}" is itself a pack; packs cannot contain packs.`);if(o.some(c=>c.templateResourceId===a.resourceId))throw new ue(`"${a.templateName}" is listed twice in the pack.`);o.push({templateResourceId:a.resourceId,templateName:a.templateName??"",reportType:a.reportType??""})}return o}function y$e(e,t){let r=s=>Lx(s).map(a=>a.templateResourceId),n=r(e),i=r(t);if(n.join()===i.join())return;let o=n.filter(s=>!i.includes(s));throw new ue(`Nothing was saved. These edits change which reports the pack holds${o.length?` (they would drop ${o.length} of them)`:""}. Change the reports with ${Ss.packTemplates}; use edits for the cover page, contents, signature and styling, and insert (not set) to add a component to includedComponents.`)}async function Vre(e,t,r,n){let i;try{i=await ZHt(e,t)}catch(s){return{partialFailures:[`Saved, but reading it back failed: ${s.message}`],resourceId:t}}if(!i)return{partialFailures:["Saved, but reading it back returned nothing."],resourceId:t};let o={resourceId:t,template:Qx(i)};if(r&&n.length>0){let s=a$e(r,QC(i),n);s.length>0&&(o.notSaved=s)}return o}async function ZHt(e,t){let r=[250,500,1e3];for(let n=0;;n++)try{return(await Gre(e,t))?.data}catch(i){if(!(i instanceof gr)||i.status!==404||n>=r.length)throw i;await new Promise(o=>setTimeout(o,r[n]))}}async function Px(e,t){try{return await e()}catch(r){throw ezt(r,t),r}}function ezt(e,t){if(!(e instanceof gr)||!e.endpoint.startsWith("/api/v1/organization-report-template")||e.refusal)return;let r=e.body?.error?.error_type;if(typeof r=="string")switch(r){case"NO_TEMPLATE_FOUND":e.refusal={code:r,hint:`There is no system default ${t.reportType??""} layout${t.framework?` for ${t.framework}`:""}: defaults exist for ${Sh.join(" and ")} only. `+(t.verb==="create"?`Use one of those, or pass ${Ss.templateConfiguration} with a whole layout, for example an existing template's.`:"Use one of those, or start from an existing template's layout (get_organization_report_template; CLI: get --config-out) and create with it."),repairTool:"list_organization_report_templates"};return;case"DUPLICATE_REPORT_TEMPLATE_EXISTS":e.refusal={code:r,hint:`A ${t.reportType??""} template named "${t.templateName??""}" already exists. Names are unique per report type, ignoring case and treating spaces and underscores alike. Pick another name.`,repairTool:"search_organization_report_templates"};return;case"CANNOT_DELETE_REPORT_TEMPLATE":e.refusal={code:r,hint:"Upstream refuses to delete the default template of a report type, and the only template of one. Make another template the default first.",repairTool:"list_organization_report_templates"};return;case"TEMPLATE_NOT_FOUND":case"DUPLICATE_TEMPLATE_ORDER":e.refusal={code:r,hint:"A report pack lists a template that does not exist, or two at the same position. List the templates and pass packTemplates again.",repairTool:"list_organization_report_templates"};return}}var JHt,c$e,l$e,Ss,d$e,Mx=J(()=>{"use strict";Ki();ot();tr();Tg();Yu();Jq();Rre();JHt=15e3,c$e=19500;l$e="List them with list_organization_report_templates (CLI: clio report-templates list).",Ss={templateName:"templateName (CLI --name)",templateConfiguration:"templateConfiguration (CLI --config-file)",edits:"edits (CLI --set / --remove / --edits)",packTemplates:"packTemplates (CLI --report)",framework:"framework (CLI --framework)"};d$e="rowOutline"});function w$e(e){return e.edits}var Rh,tj,E$e,b$e,I$e,C$e,_$e,v$e,S$e=J(()=>{"use strict";zt();Mx();Yu();Jq();Rh="report_templates",tj={type:"string",description:"The template: its resourceId or exact name."},E$e={type:"string",enum:[...ws],description:"REPORT_PACK bundles several reports in one document."},b$e={type:"string",enum:[...RT],description:`${Yg.join(", ")} only (default IAS_1). Starting layouts exist for ${Sh.join(" and ")}.`},I$e={type:"object",description:"The whole layout. Prefer edits to change part of it."},C$e={type:"array",description:'Layout changes, in order, all or nothing. set {path, value}, insert {path, value} into a list, remove {path}; path dotted like "pdfTitleConfigs.title". Rows by id: updateRow {rowId, fields}, addRow {row, parentId?, index?}, removeRow {rowId}, moveRow {rowId, parentId?, index?}.',items:{type:"object",properties:{op:{type:"string",enum:[...LC],description:"The change."},path:{type:"string"},rowId:{type:"string"},fields:{type:"object"},row:{type:"object"},parentId:{type:"string"},index:{type:"number"}},required:["op"]}},_$e={type:"array",items:{type:"string"},description:"REPORT_PACK: its reports in order, each a resourceId or name."};v$e=[{name:"list_organization_report_templates",description:"List every report template (no layouts): reportType, isDefault (one per type), a pack's reports. Read one with get_organization_report_template.",params:{},required:[],group:Rh,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"list report templates layouts packs default",execute:async e=>Gq(e.client)},{name:"get_organization_report_template",description:"Read a report template and its layout (templateConfiguration). Too large to return whole: configurationKeys (key sizes) and rowOutline come back; ask for keys or one row.",params:{template:tj,keys:{type:"array",items:{type:"string"},description:'Only these top-level layout keys; "rowOutline" gives the row outline.'},row:{type:"string",description:"One row in full, by id."}},required:["template"],group:Rh,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"get read report template layout configuration",execute:async(e,t)=>Wq(e.client,t.template,{keys:t.keys,row:t.row})},Nt({name:"search_organization_report_templates",description:"Find report templates by name, report type, category or default flag.",group:Rh,fields:BT,defaults:OT,fetcher:Vq,searchHint:"find report templates by name type category default"}),{name:"get_default_organization_report_template_configuration",description:"The default layout a new template of this report type starts from.",params:{reportType:{...E$e,enum:[...jg],description:"Packs have none."},framework:b$e},required:["reportType"],group:Rh,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"default system report template layout starting point",execute:async(e,t)=>PC(e.client,t.reportType,t.framework)},{name:"create_organization_report_template",description:"Create a report template from the default layout (or templateConfiguration), with edits applied. A pack needs packTemplates. Not made the default; names are unique per report type.",params:{templateName:{type:"string",description:"Unique within its report type."},reportType:E$e,framework:b$e,templateConfiguration:I$e,edits:C$e,packTemplates:_$e},required:["templateName","reportType"],group:Rh,readOnly:!1,searchHint:"create new report template custom layout pack",execute:async(e,t)=>Kq(e.client,{templateName:t.templateName,reportType:t.reportType,framework:t.framework,templateConfiguration:t.templateConfiguration,edits:w$e(t),packTemplates:t.packTemplates})},{name:"update_organization_report_template",description:"Rename a report template, change its layout (edits or templateConfiguration), or a pack's reports (packTemplates).",params:{template:tj,templateName:{type:"string",description:"New name."},templateConfiguration:I$e,edits:C$e,packTemplates:_$e},required:["template"],group:Rh,readOnly:!1,isDestructive:!0,searchHint:"update edit rename report template layout title rows columns",execute:async(e,t)=>Xq(e.client,t.template,{templateName:t.templateName,templateConfiguration:t.templateConfiguration,edits:w$e(t),packTemplates:t.packTemplates})},{name:"set_default_organization_report_template",description:"Make a template its report type's default: every export and dashboard view of it then uses it, org-wide. Answers with previousDefault.",params:{template:tj},required:["template"],group:Rh,readOnly:!1,isDestructive:!0,searchHint:"set default report template",execute:async(e,t)=>Zq(e.client,t.template)},{name:"delete_organization_report_template",description:"Delete a report template (also removed from packs). Refused for a type's default and a pack's last report.",params:{template:tj},required:["template"],group:Rh,readOnly:!1,isDestructive:!0,searchHint:"delete remove report template",execute:async(e,t)=>ej(e.client,t.template)}]});async function rj(e,t){return e.list("/api/v1/customer-credit-notes",t)}async function Vs(e,t){return e.get(`/api/v1/customer-credit-notes/${t}`)}async function Ux(e,t){return e.search("/api/v1/customer-credit-notes/search",t)}async function $x(e,t){return e.post("/api/v1/customer-credit-notes",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function nj(e,t,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(Fu)}:r;return e.put(`/api/v1/customer-credit-notes/${t}`,n)}async function qx(e,t,r){return e.put(`/api/v1/customer-credit-notes/${t}`,{...r,resourceId:t,saveAsDraft:!1})}async function ij(e,t,r){return e.delete(`/api/v1/customer-credit-notes/${t}`,r)}async function jx(e,t,r){return e.post(`/api/v1/customer-credit-notes/${t}/refunds`,{...r,currency:Wt(r.currency),saveAsDraft:r.saveAsDraft??!0},pP)}async function Yx(e,t){return e.get(`/api/v1/customer-credit-notes/${t}/refunds`)}async function oj(e,t){return e.get(`/api/v1/customer-credit-notes/${t}/download`)}async function sj(e,t){return En(e,"/api/v1/customer-credit-notes/bulk-upsert","customerCreditNotes",Gp(t))}var Hx=J(()=>{"use strict";tr();Vp();an();ot()});async function aj(e,t){return e.list("/api/v1/supplier-credit-notes",t)}async function Ws(e,t){return e.get(`/api/v1/supplier-credit-notes/${t}`)}async function zx(e,t){return e.search("/api/v1/supplier-credit-notes/search",t)}async function Jx(e,t){return e.post("/api/v1/supplier-credit-notes",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function cj(e,t,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(Fu)}:r;return e.put(`/api/v1/supplier-credit-notes/${t}`,n)}async function Gx(e,t,r){return e.put(`/api/v1/supplier-credit-notes/${t}`,{...r,resourceId:t,saveAsDraft:!1})}async function lj(e,t,r){return e.delete(`/api/v1/supplier-credit-notes/${t}`,r)}async function uj(e,t){return e.get(`/api/v1/supplier-credit-notes/${t}/download`)}async function Vx(e,t,r){return e.post(`/api/v1/supplier-credit-notes/${t}/refunds`,{...r,currency:Wt(r.currency),saveAsDraft:r.saveAsDraft??!0},pP)}async function Wx(e,t){return e.get(`/api/v1/supplier-credit-notes/${t}/refunds`)}async function dj(e,t){return En(e,"/api/v1/supplier-credit-notes/bulk-upsert","supplierCreditNotes",Gp(t))}var Kx=J(()=>{"use strict";tr();Vp();an();ot()});async function Xx(e){return e.get("/api/v1/organization/currencies")}async function fj(e,t){return e.post("/api/v1/organization/currencies",{currencies:t})}async function pj(e,t,r){return e.list(`/api/v1/organization/currencies/${t}/rates`,r)}function D$e(e){_Z(e.rate,"rate");let t=CZ(e.rateDirection);return{...e,rateDirection:t}}async function hj(e,t,r){return e.post(`/api/v1/organization/currencies/${t}/rates`,D$e(r))}async function mj(e,t,r,n){return e.put(`/api/v1/organization/currencies/${t}/rates/${r}`,D$e(n))}async function Aj(e,t){return e.post("/api/v1/organization/currencies/rates/bulk-upsert",{rates:t})}var gj=J(()=>{"use strict";ot()});var R$e=I((Wre,Kre)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Kre=="object"&&typeof Wre<"u"?Kre.exports=t():e.Papa=t()})(Wre,function e(){"use strict";var t=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof t<"u"?t:{}})();function r(){var R=t.URL||t.webkitURL||null,O=e.toString();return a.BLOB_URL||(a.BLOB_URL=R.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",O,")();"],{type:"text/javascript"})))}var n=!t.document&&!!t.postMessage,i=t.IS_PAPA_WORKER||!1,o={},s=0,a={};if(a.parse=u,a.unparse=d,a.RECORD_SEP="",a.UNIT_SEP="",a.BYTE_ORDER_MARK="\uFEFF",a.BAD_DELIMITERS=["\r",`
430
+ ... and ${a.toLocaleString()} more (use --format json for full output)`));break}}}function NR(e,t){switch(Ch(t)){case"json":console.log(JSON.stringify(e,null,2));break;case"csv":{let n=Object.keys(e);console.log(n.map(G$).join(",")),console.log(n.map(i=>G$(UMe(e[i]))).join(","));break}case"yaml":console.log((0,Ire.stringify)(e).trimEnd());break;case"table":console.log(PMe(e));break}}var Ire,hr,Ht=J(()=>{"use strict";Be();fo();Ire=uo(OMe(),1);DC();mn();MMe();hr=class extends ct{constructor(t){super(t),this.name="CliValidationError"}}});var jMe={};$o(jMe,{displaySlice:()=>Cre,paginatedFetch:()=>st,paginatedJson:()=>_re});async function st(e,t,r){let n=r.defaultLimit??100;if(e.all&&e.offset!==void 0)throw new Error("--all and --offset cannot be used together");if(e.all){let d=(e.format?.toLowerCase()??(e.json?"json":"table"))==="table"?H1e(r.label):void 0,f=e.maxRows??qMe,p=await bf((y,b)=>t({limit:b,offset:y}),{pageSize:e.limit??200,maxItems:f,offsetMode:r.offsetMode,onProgress:d?(y,b)=>d.update(y,b):void 0});d?.clear();let{truncated:h}=p,{data:m}=p;m.length>f&&(m=m.slice(0,f),h=!0),h&&!Ka(e)&&console.error(Te(`Warning: dataset has ${p.totalElements.toLocaleString()} items \u2014 showing ${m.length.toLocaleString()} (max-rows: ${f.toLocaleString()})`));let A=e.limit??n,g=Math.ceil(p.totalElements/A);return{data:m,totalElements:p.totalElements,totalPages:g,truncated:h}}let i=e.limit??n,o=await t({limit:i,offset:e.offset??0}),s=o.data??[],a=(o.totalElements??0)>s.length;return{data:s,totalElements:o.totalElements??0,totalPages:o.totalPages??0,truncated:a}}function Cre(e,t=uHt){return e.length<=t?{items:e,overflow:0}:{items:e.slice(0,t),overflow:e.length-t}}function _re(e,t){let{totalElements:r,totalPages:n,truncated:i,data:o,stats:s}=e,a=s?{stats:s}:{};if(i){let c=t.maxRows??qMe;return JSON.stringify({totalElements:r,totalPages:n,truncated:i,_meta:{fetchedRows:o.length,maxRows:c},...a,data:o},null,2)}return JSON.stringify({totalElements:r,totalPages:n,truncated:i,...a,data:o},null,2)}var qMe,uHt,mn=J(()=>{"use strict";Be();JD();z1e();Ht();qMe=1e3,uHt=500});async function dHt(){if(!wre){let[e,t,r,n]=await Promise.all([Promise.resolve().then(()=>(nt(),GMe)),Promise.resolve().then(()=>(mn(),jMe)),Promise.resolve().then(()=>(Ht(),$Me)),Promise.resolve().then(()=>(gt(),INe))]);wre=e.apiAction,YMe=t.paginatedFetch,HMe=r.outputList,vre=n.parsePositiveInt,zMe=n.parseNonNegativeInt}}function Fe(e){let t=e.commandName??"search",r=e.positionalArg?` <${e.positionalArg}>`:"",n=e.parent.command(`${t}${r}`).description(`Search ${e.label.replace("Searching ","")}`);n.allowExcessArguments(!1);let i=new Map,o=_ee(e.fields);for(let[a,c,u,d]of o){let f=new lt(a,c),p=e.fields[d];u&&p?.op!=="multi"&&f.choices(u),n.addOption(f);let h=fHt(a);h!==d&&i.set(h,d)}e.defaults.supportsQuery&&n.option("--query <expression>",'Jaz search expression (e.g. "status:unpaid AND $500+", "customer:acme AND date:-30d"). Merged with --filter; --filter fields win on conflict.'),n.option("--filter <json>",e.defaults.filterDescription??"Raw API filter JSON (merged with flags; flags win on conflict)").addOption(e.defaults.sortFields?new lt("--sort <field>","Sort field name").choices([...e.defaults.sortFields]):new lt("--sort <field>","Sort field name")).addOption(new lt("--order <direction>","Sort direction").choices(["ASC","DESC"])).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON"),e.defaults.supportsPagination!==!1&&n.option("--limit <n>",`Max results (default ${e.defaults.defaultLimit})`).option("--offset <n>",uC(e.defaults.offsetMode)).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)"),e.defaults.supportsView&&n.addOption(new lt("--view <tier>","Payload tier: 'lean' = summary rows; 'full' (default) = complete records").choices(["lean","full"]));for(let[a,c]of Object.entries(e.extraParams??{})){let u=a.replace(/([A-Z])/g,"-$1").toLowerCase(),d=new lt(`--${u} <value>`,c.description??a);c.enum&&d.choices([...c.enum]),n.addOption(d)}if(e.pathParam&&e.pathParam!==e.positionalArg){let a=e.pathParam.replace(/([A-Z])/g,"-$1").toLowerCase();n.requiredOption(`--${a} <id>`,e.pathParamDescription??`${e.pathParam} (required)`)}let s=async(...a)=>{let c=e.positionalArg?a[0]:void 0,u=e.positionalArg?a[1]:a[0];c&&e.positionalArg&&(u[e.positionalArg]=c),await dHt(),await wre(async d=>{e.preProcess&&await e.preProcess(d,u),typeof u.limit=="string"&&(u.limit=vre(u.limit)),typeof u.offset=="string"&&(u.offset=zMe(u.offset)),typeof u.maxRows=="string"&&(u.maxRows=vre(u.maxRows));let f={...u};for(let[T,D]of i)f[T]!==void 0&&(f[D]=f[T]);let p;if(typeof u.filter=="string")try{p=JSON.parse(u.filter)}catch{throw new Error(`Invalid --filter JSON: ${u.filter}`)}let h=e.baseFilter?p?{...e.baseFilter,...p}:e.baseFilter:p,m=YD(f,e.fields,h),A;if(c&&e.positionalFilter){let T=e.positionalFilter(c);A=m?{...T,...m}:T}else A=m;let g={sortBy:[u.sort??e.defaults.sortBy],order:u.order??e.defaults.sortOrder},y=e.defaults.supportsQuery?u.query:void 0,b=e.defaults.supportsView?u.view:void 0,E={};for(let[T,D]of Object.entries(e.extraParams??{})){let k=u[T];typeof k=="string"&&(E[T]=D.type==="array"?k.split(",").map(F=>F.trim()):k)}let C=e.pathParam?({limit:T,offset:D})=>e.fetcher(d,u[e.pathParam],{filter:A,sort:g,limit:T,offset:D,query:y,view:b,...E}):({limit:T,offset:D})=>e.fetcher(d,{filter:A,sort:g,limit:T,offset:D,query:y,view:b,...E}),w=await YMe(u,C,{label:e.label,defaultLimit:e.defaults.defaultLimit,offsetMode:e.defaults.offsetMode});HMe(w,e.columns,u,e.label.replace("Searching ",""))})(u)};return n.action(s),n}function fHt(e){return e.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(r,n)=>n.toUpperCase())}var wre,YMe,HMe,vre,zMe,JMe=J(()=>{"use strict";jn();zD();ch()});var RC,TC,BR,OR,VMe=J(()=>{"use strict";zo();RC={reference:{path:"reference",op:"contains",type:"string",description:"Invoice reference number"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:aLe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact/customer name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:LU},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},TC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},BR=RC,OR=TC});var WMe,FR,LR,xC,QR,_h,wh,KMe=J(()=>{"use strict";zo();WMe={reference:{path:"reference",op:"contains",type:"string",description:"Order reference number"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},dueDateFrom:{path:"dueDate",op:"gte",type:"string",description:"Due date from (YYYY-MM-DD)"},dueDateTo:{path:"dueDate",op:"lte",type:"string",description:"Due date to (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},FR={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:kLe},...WMe},LR={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:NLe},...WMe},xC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},QR=xC,_h={name:{path:"name",op:"contains",type:"string",description:"Line item text/description"},reference:{path:"reference",op:"contains",type:"string",description:"Parent order reference"},orderId:{path:"btResourceId",op:"eq",type:"string",description:"Parent order resourceId"},contactName:{path:"contactName",op:"contains",type:"string",description:"Contact (customer/supplier) name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (e.g., SGD, USD)"},status:{path:"status",op:"eq",type:"string",description:"Line item status"},account:{path:"organizationAccountName",op:"contains",type:"string",description:"Chart-of-account name on the line"},taxProfile:{path:"taxProfileName",op:"contains",type:"string",description:"Tax profile name on the line"},isOpen:{path:"isOpen",op:"boolean",type:"boolean",description:"Only open (unfulfilled) lines"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On/before (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"totalItemAmount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"totalItemAmount",op:"lte",type:"number",description:"Maximum line amount"}},wh={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var vh,kC,PR,XMe=J(()=>{"use strict";zo();vh={reference:{path:"reference",op:"contains",type:"string",description:"Credit note reference"},status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:cLe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},contactId:{path:"contactResourceId",op:"eq",type:"string",description:"Contact resourceId"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"},approvalStatus:{path:"approvalStatus",op:"multi",type:"string",description:"Approval status",enum:LU},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},kC={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0},PR=kC});var MR,UR,ZMe=J(()=>{"use strict";zo();MR={reference:{path:"reference",op:"contains",type:"string",description:"Journal reference"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:lLe},type:{path:"type",op:"multi",type:"string",description:"Journal type",enum:uLe},templateType:{path:"templateType",op:"multi",type:"string",description:"Template type",enum:dLe},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},internalNotes:{path:"internalNotes",op:"contains",type:"string",description:"Search internal notes"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},UR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var $R,qR,eUe=J(()=>{"use strict";zo();$R={name:{path:"name",op:"contains",type:"string",description:"Contact name"},email:{path:"email",op:"contains",type:"string",description:"Email address"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:FU},isCustomer:{path:"customer",op:"boolean",type:"boolean",description:"Filter to customers only",cliFlag:"--customer"},isSupplier:{path:"supplier",op:"boolean",type:"boolean",description:"Filter to suppliers only",cliFlag:"--supplier"},taxId:{path:"taxId",op:"contains",type:"string",description:"Tax ID"}},qR={sortBy:"name",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var _f,wf,Sre,jR,YR,tUe=J(()=>{"use strict";zo();_f={type:{path:"businessTransactionType",op:"multi",type:"string",description:"Transaction type",enum:yLe},direction:{path:"direction",op:"eq",type:"string",description:"Direction (PAYIN or PAYOUT)",enum:ALe},status:{path:"businessTransactionStatus",op:"multi",type:"string",description:"Status",enum:ELe},reference:{path:"businessTransactionReference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},businessTransactionType:{path:"businessTransactionType",op:"multi",type:"string",description:"(alias for type)"}},wf={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0},Sre={magicSort:{type:"object",description:"Rank by match quality to a bank entry: {bankStatementEntryResourceId, magicSort:true}."},transactionType:{type:"string",enum:[...gLe],description:"Scope. Default ALL_CASHFLOWS."}},jR={resourceId:{path:"resourceId",op:"eq",type:"string",description:"One unapplied payment (the read-back for its hash)",cliFlag:"--id <resourceId>"},type:{path:"type",op:"eq",type:"string",description:"AR = received, AP = paid",enum:["AR","AP"]},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},accountId:{path:"organizationAccountResourceId",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"}},YR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20}});var HR,zR,rUe=J(()=>{"use strict";zo();HR={status:{path:"status",op:"multi",type:"string",description:"Status",enum:mLe},description:{path:"description",op:"contains",type:"string",description:"Description"},payer:{path:"extContactName",op:"contains",type:"string",description:"Payer/payee name"},reference:{path:"extReference",op:"contains",type:"string",description:"Bank reference",cliFlag:"--ref <reference>"},startDate:{path:"valueDate",op:"gte",type:"string",description:"On or after this date (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"On or before this date (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"netAmount",op:"gte",type:"number",description:"Minimum net amount"},maxAmount:{path:"netAmount",op:"lte",type:"number",description:"Maximum net amount"}},zR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0}});var JR,GR,nUe=J(()=>{"use strict";zo();JR={status:{path:"status",op:"multi",type:"string",description:"Status",enum:fLe},itemCategory:{path:"itemCategory",op:"eq",type:"string",description:"Category",enum:hLe},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale items only",cliFlag:"--sale"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase items only",cliFlag:"--purchase"}},GR={sortBy:"internalName",sortOrder:"ASC",defaultLimit:20,leanDefaultLimit:50,supportsQuery:!0,supportsView:!0}});var VR,WR,KR,XR,ZR,eT,iUe=J(()=>{"use strict";zo();ch();VR={name:{path:"name",op:"contains",type:"string",description:"Asset name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:bLe},category:{path:"category",op:"eq",type:"string",description:"Category",enum:Eee},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Asset type name"},startDate:{path:"purchaseDate",op:"gte",type:"string",description:"Purchase date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"purchaseDate",op:"lte",type:"string",description:"Purchase date to (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"purchaseAmount",op:"gte",type:"number",description:"Minimum purchase amount"},maxAmount:{path:"purchaseAmount",op:"lte",type:"number",description:"Maximum purchase amount"}},WR={sortBy:"name",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0,filterDescription:ah("resourceId, typeCode, currencyCode, depreciationEndDate, disposalValueDate, bookValueAmount, assetDisposalGainLossAmount")},KR={reference:{path:"reference",op:"contains",type:"string",description:"Source bill or journal reference",cliFlag:"--ref <reference>"},contactName:{path:"contactName",op:"contains",type:"string",description:"Supplier name"},documentType:{path:"documentType",op:"eq",type:"string",description:"PURCHASE (bill) or a journal type"},accountName:{path:"accountName",op:"contains",type:"string",description:"Fixed Asset account name"},lineDescription:{path:"description",op:"contains",type:"string",description:"Line description"},minAmount:{path:"amount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"amount",op:"lte",type:"number",description:"Maximum line amount"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Document date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Document date to (YYYY-MM-DD)",cliFlag:"--to <date>"}},XR={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20},ZR={categoryCode:{path:"categoryCode",op:"eq",type:"string",description:"Asset category",enum:Eee,cliFlag:"--category <cat>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Asset type name"}},eT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50}});var tT,rT,nT,iT,oT,sT,aT,cT,lT,uT,oUe=J(()=>{"use strict";zo();ch();tT={name:{path:"name",op:"contains",type:"string",description:"Deferral name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Stored status",enum:ILe},category:{path:"category",op:"eq",type:"string",description:"Category",enum:QU},typeName:{path:"typeName",op:"contains",type:"string",description:"Deferral type name"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},minAmount:{path:"deferralAmount",op:"gte",type:"number",description:"Minimum deferral amount"},maxAmount:{path:"deferralAmount",op:"lte",type:"number",description:"Maximum deferral amount"}},rT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20,supportsQuery:!0,sortFields:CLe,filterDescription:ah("resourceId, typeCode, currencyCode, sourceDate, amortizationStartDate, amortizationEndDate, closedOutDate")},nT={viewStatus:{type:"string",enum:["ACTIVE","DRAFT","COMPLETED","FULLY_AMORTIZED","CLOSED_OUT"],description:"Status as at endDate. COMPLETED = FULLY_AMORTIZED or CLOSED_OUT."},endDate:{type:"string",description:"As-at date (YYYY-MM-DD) the figures and statuses are worked out at. Default today."}},iT={reference:{path:"reference",op:"contains",type:"string",description:"Source bill, invoice or journal reference",cliFlag:"--ref <reference>"},contactName:{path:"contactName",op:"contains",type:"string",description:"Supplier or customer name"},documentType:{path:"documentType",op:"eq",type:"string",description:"PURCHASE (bill), SALE (invoice) or a journal type"},category:{path:"category",op:"eq",type:"string",description:"Category",enum:QU,cliFlag:"--category <cat>"},accountName:{path:"accountName",op:"contains",type:"string",description:"Deferral account name"},lineDescription:{path:"description",op:"contains",type:"string",description:"Line description"},minAmount:{path:"amount",op:"gte",type:"number",description:"Minimum line amount"},maxAmount:{path:"amount",op:"lte",type:"number",description:"Maximum line amount"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Document date from (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Document date to (YYYY-MM-DD)",cliFlag:"--to <date>"}},oT={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,sortFields:["valueDate","reference","contactName","documentType"]},sT={categoryCode:{path:"categoryCode",op:"eq",type:"string",description:"Category (the same typeCode exists in both, so always set it)",enum:QU,cliFlag:"--category <cat>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Deferral type name"}},aT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50,sortFields:["resourceId","typeName","typeCode","categoryCode"]},cT={accountName:{path:"accountName",op:"contains",type:"string",description:"Account name"},accountCode:{path:"accountCode",op:"contains",type:"string",description:"Account code"},accountType:{path:"accountType",op:"eq",type:"string",description:"Account type",enum:["Current Asset","Current Liability"]}},lT={sortBy:"accountCode",sortOrder:"ASC",defaultLimit:50,sortFields:["accountName","accountCode","accountType","accountResourceId"]},uT={searchTerms:{type:"array",items:{type:"string"},description:"Words matched against name, code, type and description (max 20). Omit to list all."}}});var dT,pHt,fT,pT,hT,mT,sUe=J(()=>{"use strict";zo();ch();dT={name:{path:"name",op:"contains",type:"string",description:"Lease name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Stored status",enum:SLe},typeCode:{path:"typeCode",op:"eq",type:"string",description:"Lease type code (e.g. OFFICE, HIRE_PURCHASE)"},typeName:{path:"typeName",op:"contains",type:"string",description:"Lease type name"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Lessor contact resourceId"},paymentTiming:{path:"paymentTiming",op:"eq",type:"string",description:"Payment timing",enum:sh},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},commencementFrom:{path:"commencementDate",op:"gte",type:"string",description:"Commencement date from (YYYY-MM-DD)",cliFlag:"--from <date>"},commencementTo:{path:"commencementDate",op:"lte",type:"string",description:"Commencement date to (YYYY-MM-DD)",cliFlag:"--to <date>"}},pHt=["resourceId","name","reference","typeName","commencementDate","endDate","leaseLiabilityAmount","rouAssetAmount","leaseLiabilityRemaining","currentPortion","nonCurrentPortion","accumulatedDepreciation","rouNetBookValue","interestToDate","createdAt"],fT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20,sortFields:pHt,filterDescription:ah("resourceId, currencyCode, leaseTerm, endDate, closedOutDate, leaseLiabilityAmount")},pT={viewStatus:{type:"string",enum:[...DLe],description:"Register tab. COMPLETED is ended, closed out or terminated; ACTIVE also lists lease exemptions until their end date."},endDate:{type:"string",description:"As-at date (YYYY-MM-DD) of liability, right-of-use and view status. Default today. Leases starting after it are left out."}},hT={typeCode:{path:"typeCode",op:"eq",type:"string",description:"Type code"},typeName:{path:"typeName",op:"contains",type:"string",description:"Type name"}},mT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50}});var AT,hHt,gT,yT,ET,bT,aUe=J(()=>{"use strict";zo();ch();AT={name:{path:"name",op:"contains",type:"string",description:"Loan name"},reference:{path:"reference",op:"contains",type:"string",description:"Reference",cliFlag:"--ref <reference>"},status:{path:"status",op:"multi",type:"string",description:"Stored status (the as-at status is viewStatus)",enum:_Le},kind:{path:"kind",op:"eq",type:"string",description:"TERM (repayment schedule) or ON_DEMAND (director, shareholder, related-party or intercompany account)",enum:wLe},typeCode:{path:"typeCode",op:"eq",type:"string",description:"Loan type code (BANK, DIRECTOR, MORTGAGE...); see search_loan_types",cliFlag:"--type-code <code>"},typeName:{path:"typeName",op:"contains",type:"string",description:"Loan type name"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Lender contact resourceId",cliFlag:"--contact <id>"},tag:{path:"tags",op:"contains",type:"string",description:"Tag name",cliFlag:"--tag <name>"},startDate:{path:"drawdownDate",op:"gte",type:"string",description:"Drawdown date from (YYYY-MM-DD)",cliFlag:"--from <date>"},drawnTo:{path:"drawdownDate",op:"lte",type:"string",description:"Drawdown date to (YYYY-MM-DD)",cliFlag:"--to <date>"},minAmount:{path:"principalAmount",op:"gte",type:"number",description:"Minimum principal"},maxAmount:{path:"principalAmount",op:"lte",type:"number",description:"Maximum principal"}},hHt=["createdAt","resourceId","name","reference","kind","typeName","drawdownDate","endDate","principalAmount","outstandingPrincipal","annualInterestRate","loanTerm"],gT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20,supportsQuery:!1,sortFields:hHt,filterDescription:ah("resourceId, currencyCode, loanTerm, endDate, closedOutDate, annualInterestRate")},yT={viewStatus:{type:"string",enum:[...vLe],description:"Status as at endDate: REPAID, SETTLED and CLOSED_OUT are derived, INACTIVE = any of those three. Figures on every row are as at endDate."},endDate:{type:"string",description:"As-at date (YYYY-MM-DD, default today); loans starting after it are left out"}},ET={typeName:{path:"typeName",op:"contains",type:"string",description:"Loan type name"},typeCode:{path:"typeCode",op:"eq",type:"string",description:"Loan type code",cliFlag:"--type-code <code>"}},bT={sortBy:"typeName",sortOrder:"ASC",defaultLimit:50,supportsQuery:!1}});var IT,CT,cUe=J(()=>{"use strict";zo();IT={type:{path:"businessTransactionType",op:"eq",type:"string",description:"Transaction type (SALE, PURCHASE, JOURNAL_MANUAL)"},status:{path:"status",op:"multi",type:"string",description:"Scheduler status",enum:RLe},subscriptionStatus:{path:"subscriptionStatus",op:"multi",type:"string",description:"Subscription status",enum:TLe},schedulerType:{path:"schedulerType",op:"eq",type:"string",description:"Scheduler type"},interval:{path:"interval",op:"eq",type:"string",description:"Interval",enum:xLe},contactName:{path:"contact.name",op:"contains",type:"string",description:"Contact name"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code"}},CT={sortBy:"nextScheduleDate",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0}});var _T,wT,lUe=J(()=>{"use strict";zo();_T={id:{path:"resourceId",op:"eq",type:"string",description:"Job ID (the jobId returned from bulk operations)",cliFlag:"--id"},status:{path:"status",op:"multi",type:"string",description:"Job status",enum:QLe},type:{path:"jobType",op:"eq",type:"string",description:"Job type (e.g. UPSERT_CONTACTS, UPSERT_ITEMS, PROCESS_BANK_STATEMENT_FILES)",cliFlag:"--type"},fileName:{path:"fileName",op:"contains",type:"string",description:"File name (file-based jobs only)",cliFlag:"--file-name"},from:{path:"createdAt",op:"gte",type:"string",description:"On/after (ISO date)",cliFlag:"--from"},to:{path:"createdAt",op:"lte",type:"string",description:"On/before (ISO date)",cliFlag:"--to"}},wT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20}});var vT,qg,uUe=J(()=>{"use strict";vT={name:{path:"name",op:"plain",type:"string",description:"Purchase item name"},reference:{path:"reference",op:"plain",type:"string",description:"Reference name"},currencyCode:{path:"currencyCode",op:"plain",type:"string",description:"Currency code (ISO 4217)"}},qg={sortBy:"name",sortOrder:"ASC",defaultLimit:20,offsetMode:"row"}});var ST,DT,dUe=J(()=>{"use strict";ST={formType:{path:"formType",op:"eq",type:"string",description:"Form code, e.g. 2550Q"},lifecycleStatus:{path:"lifecycleStatus",op:"multi",type:"string",description:"Status, comma-separated (e.g. READY_TO_FILE)"},periodYear:{path:"periodYear",op:"eq",type:"number",description:"Period year"},dueFrom:{path:"filingDueDate",op:"gte",type:"string",description:"Due on/after (YYYY-MM-DD)"},dueTo:{path:"filingDueDate",op:"lte",type:"string",description:"Due on/before (YYYY-MM-DD)"}},DT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20}});function pUe(e){return typeof e=="string"&&ws.includes(e)}var ws,RT,Sh,V$,ju,jg,Yg,fUe,NC,Hg,Yu=J(()=>{"use strict";ws=["PROFIT_AND_LOSS","BALANCE_SHEET","CASHFLOW","EQUITY_MOVEMENT","TRIAL_BALANCE","GENERAL_LEDGER","VAT_LEDGER","CASH_BALANCE","AGED_RECEIVABLES_SUMMARY","AGED_RECEIVABLES_DETAILS","AGED_PAYABLES_SUMMARY","AGED_PAYABLES_DETAILS","REPORT_PACK"],RT=["IAS_1","IFRS_18","GAAP","IND_AS","IFRS_SME"],Sh=["IAS_1","IFRS_18"],V$=["FINANCIAL","ACCOUNTING","OPERATIONAL","REPORT_PACK"],ju={PROFIT_AND_LOSS:{label:"Profit and loss",category:"FINANCIAL",exportType:"profit-and-loss",takesFramework:!0,frameworkChangesDefault:!0,periodKind:"range",snapshotsChartOfAccounts:!0,hasRows:!0},BALANCE_SHEET:{label:"Balance sheet",category:"FINANCIAL",exportType:"balance-sheet",takesFramework:!0,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!0,hasRows:!0},CASHFLOW:{label:"Cashflow statement",category:"FINANCIAL",exportType:"cashflow",takesFramework:!0,frameworkChangesDefault:!0,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!0},EQUITY_MOVEMENT:{label:"Statement of changes in equity",category:"FINANCIAL",exportType:"equity-movement",takesFramework:!0,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1},TRIAL_BALANCE:{label:"Trial balance",category:"ACCOUNTING",exportType:"trial-balance",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},GENERAL_LEDGER:{label:"General ledger",category:"ACCOUNTING",exportType:"general-ledger",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1},VAT_LEDGER:{label:"Tax (GST/VAT) ledger",category:"ACCOUNTING",exportType:"tax-ledger",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1},CASH_BALANCE:{label:"Cash balance",category:"OPERATIONAL",exportType:"cash-balance",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_RECEIVABLES_SUMMARY:{label:"Aged receivables (summary)",category:"OPERATIONAL",exportType:"ar-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_RECEIVABLES_DETAILS:{label:"Aged receivables (details)",category:"OPERATIONAL",exportType:"ar-details-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_PAYABLES_SUMMARY:{label:"Aged payables (summary)",category:"OPERATIONAL",exportType:"ap-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},AGED_PAYABLES_DETAILS:{label:"Aged payables (details)",category:"OPERATIONAL",exportType:"ap-details-report",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"point",snapshotsChartOfAccounts:!1,hasRows:!1},REPORT_PACK:{label:"Report pack (several reports in one document)",category:"REPORT_PACK",takesFramework:!1,frameworkChangesDefault:!1,periodKind:"range",snapshotsChartOfAccounts:!1,hasRows:!1}},jg=ws.filter(e=>e!=="REPORT_PACK"),Yg=ws.filter(e=>ju[e].takesFramework),fUe=ws.filter(e=>ju[e].frameworkChangesDefault),NC=ws.filter(e=>ju[e].hasRows),Hg=new Map(jg.flatMap(e=>{let t=ju[e].exportType;return t?[[t,e]]:[]}))});function W$(e){if(!Array.isArray(e))throw new ue(`expected a list of strings, got ${JSON.stringify(e)}.`);return e.map(String)}function AHt(e,t,r){let n=mHt.has(r),i=a=>n?typeof a=="string"?a.toLowerCase():Array.isArray(a)?a.map(i):a:a,o=e==null?void 0:i(String(e)),s=typeof t=="object"&&t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).map(([a,c])=>[a,i(c)])):i(t);if(typeof s=="string")return o===s;if(!s||typeof s!="object"||Array.isArray(s))throw new ue(`filter.${r} must be a string or an object of operators (${Object.keys(TT).join(", ")}, isNull).`);return Object.entries(s).every(([a,c])=>{if(a==="isNull")return c===!0||c==="true"?o===void 0||o==="":o!==void 0&&o!=="";let u=TT[a];if(!u)throw new ue(`filter.${r}.${a} is not an operator. Use one of: ${Object.keys(TT).join(", ")}, isNull.`);return o!==void 0&&u(o,c)})}function gHt(e,t,r){let n=typeof t=="boolean"?t:t?.eq;if(typeof n!="boolean")throw new ue(`filter.${r} must be true, false, or {"eq": true|false}.`);return e===!0===n}function Dre(e){if(e){if(typeof e!="object"||Array.isArray(e))throw new ue("filter must be an object of fields.");for(let[t,r]of Object.entries(e)){if(r==null)continue;if(t==="and"||t==="or"){for(let s of Array.isArray(r)?r:[r])Dre(s);continue}if(!xT.includes(t))throw new ue(`filter: "${t}" is not a report template field. Use: ${xT.join(", ")}.`);let n=EHt[t];if(!n)continue;let o=(typeof r=="string"?[r]:Array.isArray(r)?r:typeof r=="object"?Object.entries(r).filter(([s])=>yHt.has(s)).flatMap(([,s])=>Array.isArray(s)?s:[s]):[r]).filter(s=>!n.includes(String(s)));if(o.length>0)throw new ue(`filter.${t}: ${o.map(s=>JSON.stringify(s)).join(", ")} is not a value it takes. Use: ${n.join(", ")}.`)}}}function X$(e,t){return t?Object.entries(t).every(([r,n])=>{if(n==null)return!0;switch(r){case"resourceId":case"templateName":case"reportType":case"reportCategory":return AHt(e[r],n,r);case"reportTypes":return W$(n).includes(String(e.reportType));case"isDefault":return gHt(e.isDefault,n,r);case"and":return(Array.isArray(n)?n:[n]).every(i=>X$(e,i));case"or":return(Array.isArray(n)?n:[n]).some(i=>X$(e,i));default:throw new ue(`filter: "${r}" is not a report template field. Use: ${xT.join(", ")}.`)}}):!0}function hUe(e,t=["reportType"],r="ASC"){for(let o of t)if(!K$.includes(o))throw new ue(`sortBy "${o}" is not sortable. Use one of: ${K$.join(", ")}.`);let n=[...t,"templateName","resourceId"],i=r==="DESC"?-1:1;return[...e].sort((o,s)=>{for(let a of n){let c=String(o[a]??""),u=String(s[a]??"");if(c!==u)return(c<u?-1:1)*(t.includes(a)?i:1)}return 0})}var xT,K$,TT,mHt,yHt,EHt,Rre=J(()=>{"use strict";ot();Yu();xT=["resourceId","templateName","reportType","reportTypes","reportCategory","isDefault","and","or"],K$=["reportType","templateName","isDefault","resourceId"],TT={eq:(e,t)=>e===String(t),neq:(e,t)=>e!==String(t),in:(e,t)=>W$(t).includes(e),contains:(e,t)=>e.toLowerCase().includes(String(t).toLowerCase()),notContains:(e,t)=>!e.toLowerCase().includes(String(t).toLowerCase()),likeIn:(e,t)=>W$(t).some(r=>e.toLowerCase().includes(r.toLowerCase())),reg:(e,t)=>W$(t).some(r=>e.toLowerCase().includes(r.toLowerCase())),startWith:(e,t)=>e.startsWith(String(t)),notStartWith:(e,t)=>!e.startsWith(String(t)),endWith:(e,t)=>e.endsWith(String(t))};mHt=new Set(["resourceId"]);yHt=new Set(["eq","neq","in"]),EHt={reportType:ws,reportTypes:ws,reportCategory:V$}});var kT,NT,BT,OT,mUe=J(()=>{"use strict";Yu();Rre();kT={catalogName:{path:"catalogName",op:"contains",type:"string",description:"Catalog name"},description:{path:"description",op:"contains",type:"string",description:"Catalog item description"},status:{path:"status",op:"multi",type:"string",description:"Record status (e.g. ACTIVE, INACTIVE)"},contactGroupResourceId:{path:"contactGroupResourceId",op:"eq",type:"string",description:"Contact group resourceId"}},NT={sortBy:"catalogName",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},BT={templateName:{path:"templateName",op:"contains",type:"string",description:"Name contains",cliFlag:"--name"},reportType:{path:"reportType",op:"plain",type:"string",description:"Report type",enum:ws,cliFlag:"--type"},reportCategory:{path:"reportCategory",op:"eq",type:"string",description:"Category",enum:V$,cliFlag:"--category"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Defaults only",cliFlag:"--default"}},OT={sortBy:"reportType",sortOrder:"ASC",defaultLimit:20,supportsPagination:!1,sortFields:K$,filterDescription:`Raw filter JSON. Fields: ${xT.filter(e=>e!=="and"&&e!=="or").join(", ")}, combined with and/or. String ops: ${Object.keys(TT).join(", ")}, isNull. isDefault: {"eq": true}.`}});async function Z$(e,t){return e.search("/api/v1/claims/search",t)}async function FT(e,t){return e.get(`/api/v1/claims/${t}`)}async function e2(e,t){return e.post("/api/v1/claims",t,AP)}async function t2(e,t,r){return e.put(`/api/v1/claims/${t}`,r)}async function r2(e,t){return e.delete(`/api/v1/claims/${t}`)}async function n2(e,t,r){return e.delete(`/api/v1/claims/${t}/attachments/${r}`)}async function i2(e,t){return e.post(`/api/v1/claims/${t}/submit`,{})}async function o2(e,t){return e.post(`/api/v1/claims/${t}/approve`,{})}async function s2(e,t,r){return e.post(`/api/v1/claims/${t}/reject`,{rejectionReason:r})}async function a2(e,t,r){return e.post(`/api/v1/claims/${t}/cancel`,{cancellationReason:r})}async function c2(e,t){return e.post(`/api/v1/claims/${t}/unpost`,{})}function LT(e){mt(e,"resourceIds",500,"claims")}async function l2(e,t){return LT(t),e.post("/api/v1/claims/bulk/submit",{resourceIds:t})}async function u2(e,t){return LT(t),e.post("/api/v1/claims/bulk/approve",{resourceIds:t})}async function d2(e,t){return LT(t),e.post("/api/v1/claims/bulk/delete",{resourceIds:t})}async function f2(e,t,r){return LT(t),e.post("/api/v1/claims/bulk/reject",{resourceIds:t,rejectionReason:r})}async function p2(e,t,r){return LT(t),e.post("/api/v1/claims/bulk/cancel",{resourceIds:t,cancellationReason:r})}async function h2(e){let t=await e.get("/api/v1/claims/tracking-tags");return Array.isArray(t)?t:t?.data??[]}async function m2(e){let t=await e.get("/api/v1/claims/custom-field-values");return Array.isArray(t)?t:t?.data??[]}var AUe,A2=J(()=>{"use strict";an();tr();AUe=["DRAFT","SUBMITTED","APPROVED","CONVERTED","REJECTED","CANCELLED"]});var QT,PT,bHt,IHt,MT,UT,$T,qT,jT,YT,HT,zT,gUe=J(()=>{"use strict";uD();pD();A2();QT={status:{path:"status",op:"multi",type:"string",description:"Status (comma-separated for OR)",enum:AUe},employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},contactResourceId:{path:"contactResourceId",op:"eq",type:"string",description:"Vendor contact resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Approver user resourceId"},reference:{path:"reference",op:"contains",type:"string",description:"Claim reference"},currencyCode:{path:"currencyCode",op:"eq",type:"string",description:"Currency code (ISO 4217)"},startDate:{path:"valueDate",op:"gte",type:"string",description:"Value date on/after (YYYY-MM-DD)",cliFlag:"--from <date>"},endDate:{path:"valueDate",op:"lte",type:"string",description:"Value date on/before (YYYY-MM-DD)",cliFlag:"--to <date>"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"},minAmount:{path:"totalAmount",op:"gte",type:"number",description:"Minimum total amount"},maxAmount:{path:"totalAmount",op:"lte",type:"number",description:"Maximum total amount"}},PT={sortBy:"createdAt",sortOrder:"DESC",defaultLimit:20},bHt=["RECORDED","COMPLETED","CANCELLED","IN_PROGRESS","ACTION_NEEDED"],IHt=["DIRECT_ENTRY","DISBURSEMENT","REIMBURSEMENT_PAYOUT","ADVANCE"],MT={employeeResourceId:{path:"employeeResourceId",op:"eq",type:"string",description:"Employee resourceId"},employeeName:{path:"employeeName",op:"contains",type:"string",description:"Employee name"},reference:{path:"reference",op:"contains",type:"string",description:"Payout reference"},payoutStatus:{path:"payoutStatus",op:"multi",type:"string",description:"Payout status (comma-separated)",enum:bHt},payoutType:{path:"payoutType",op:"multi",type:"string",description:"Payout type (comma-separated): DIRECT_ENTRY (books-only DCE), DISBURSEMENT (gateway direct-debit-backed), REIMBURSEMENT_PAYOUT, ADVANCE",enum:IHt}},UT={sortBy:"valueDate",sortOrder:"DESC",defaultLimit:20,offsetMode:"row"},$T={name:{path:"name",op:"contains",type:"string",description:"Claim type name"},expenseAccountResourceId:{path:"expenseAccountResourceId",op:"eq",type:"string",description:"Default expense account resourceId"},taxProfileResourceId:{path:"taxProfileResourceId",op:"eq",type:"string",description:"Default tax profile resourceId"}},qT={sortBy:"name",sortOrder:"ASC",defaultLimit:100},jT={name:{path:"name",op:"contains",type:"string",description:"Claim profile name"},approverUserResourceId:{path:"approverUserResourceId",op:"eq",type:"string",description:"Default approver user resourceId"},minClaimAmount:{path:"minClaimAmount",op:"gte",type:"number",description:"Minimum claim total (>=)"},maxClaimAmount:{path:"maxClaimAmount",op:"lte",type:"number",description:"Maximum claim total (<=)"},maxPerPeriodAmount:{path:"maxPerPeriodAmount",op:"lte",type:"number",description:"Per-period spend cap (<=)"},perPeriod:{path:"perPeriod",op:"eq",type:"string",description:"Per-period window",enum:cD},employeeBalanceAccountResourceId:{path:"employeeBalanceAccountResourceId",op:"eq",type:"string",description:"Employee balance (liability) account resourceId"}},YT={sortBy:"name",sortOrder:"ASC",defaultLimit:100},HT={name:{path:"name",op:"contains",type:"string",description:"Posting rule name"},outerAxis:{path:"outerAxis",op:"eq",type:"string",description:"Outer grouping axis",enum:dD},innerAxis:{path:"innerAxis",op:"eq",type:"string",description:"Inner line-aggregation axis",enum:fD},defaultBankAccountResourceId:{path:"defaultBankAccountResourceId",op:"eq",type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{path:"defaultIncludeReimbursementPayout",op:"boolean",type:"boolean",description:"Creates reimbursement DCE by default"},isDefault:{path:"isDefault",op:"boolean",type:"boolean",description:"Org default rule"}},zT={sortBy:"name",sortOrder:"ASC",defaultLimit:100}});var JT,GT,VT,WT,yUe=J(()=>{"use strict";gD();JT={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},userResourceId:{path:"userResourceId",op:"eq",type:"string",description:"Bound login user resourceId"},managerEmployeeResourceId:{path:"managerEmployeeResourceId",op:"eq",type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{path:"claimProfileResourceId",op:"eq",type:"string",description:"Claim profile resourceId"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"},createdFrom:{path:"createdAt",op:"gte",type:"string",description:"Created on/after (YYYY-MM-DD)"},createdTo:{path:"createdAt",op:"lte",type:"string",description:"Created on/before (YYYY-MM-DD)"}},GT={sortBy:"name",sortOrder:"ASC",defaultLimit:50},VT={name:{path:"name",op:"contains",type:"string",description:"Employee name"},email:{path:"email",op:"contains",type:"string",description:"Work email"},phone:{path:"phone",op:"contains",type:"string",description:"Phone"},currency:{path:"currency",op:"eq",type:"string",description:"Balance currency (ISO 4217)"},employmentType:{path:"employmentType",op:"eq",type:"string",description:"Employment type",enum:Ig},active:{path:"active",op:"boolean",type:"boolean",description:"Active employees only"}},WT={sortBy:"name",sortOrder:"ASC",defaultLimit:50}});var KT,XT,ZT,ex,tx,rx,nx,ix,ox,sx,ax,cx,lx,ux,Tre,dx,fx,px,hx,EUe=J(()=>{"use strict";zo();KT={name:{path:"name",op:"contains",type:"string",description:"Account name"},code:{path:"code",op:"contains",type:"string",description:"Account code"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:pLe},accountClass:{path:"accountClass",op:"eq",type:"string",description:"Account class",enum:BLe},accountType:{path:"accountType",op:"eq",type:"string",description:"Account type",enum:PU},controlFlag:{path:"controlFlag",op:"boolean",type:"boolean",description:"Control flag (system accounts)"}},XT={sortBy:"code",sortOrder:"ASC",defaultLimit:100,supportsQuery:!1},ZT={query:{path:"tagName",op:"contains",type:"string",description:"Tag name"}},ex={sortBy:"tagName",sortOrder:"ASC",defaultLimit:100},tx={name:{path:"name",op:"contains",type:"string",description:"Tax profile name",cliFlag:"--name <name>"},taxTypeCode:{path:"taxTypeCode",op:"contains",type:"string",description:"Tax type code"},appliesToSale:{path:"appliesToSale",op:"boolean",type:"boolean",description:"Filter to sale profiles"},appliesToPurchase:{path:"appliesToPurchase",op:"boolean",type:"boolean",description:"Filter to purchase profiles"},appliesToSaleCreditNote:{path:"appliesToSaleCreditNote",op:"boolean",type:"boolean",description:"Filter to sale CN profiles"},appliesToPurchaseCreditNote:{path:"appliesToPurchaseCreditNote",op:"boolean",type:"boolean",description:"Filter to purchase CN profiles"}},rx={sortBy:"name",sortOrder:"ASC",defaultLimit:100,supportsQuery:!0},nx={title:{path:"title",op:"contains",type:"string",description:"Capsule title"},status:{path:"status",op:"multi",type:"string",description:"Status",enum:LLe}},ix={sortBy:"title",sortOrder:"ASC",defaultLimit:20,supportsQuery:!0},ox={query:{path:"customFieldName",op:"contains",type:"string",description:"Custom field name",cliFlag:"--name <name>"},datatypeCode:{path:"datatypeCode",op:"eq",type:"string",description:"Data type",enum:OLe,cliFlag:"--type <type>"},customFieldName:{path:"customFieldName",op:"contains",type:"string",description:"(alias for query)"}},sx={sortBy:"customFieldName",sortOrder:"ASC",defaultLimit:100},ax={query:{path:"name",op:"contains",type:"string",description:"Group name"}},cx={sortBy:"name",sortOrder:"ASC",defaultLimit:100},lx={firstName:{path:"user.firstName",op:"contains",type:"string",description:"User first name"},lastName:{path:"user.lastName",op:"contains",type:"string",description:"User last name"},email:{path:"user.email",op:"contains",type:"string",description:"Email"},userType:{path:"userType",op:"eq",type:"string",description:"Access tier",enum:FLe},status:{path:"status",op:"multi",type:"string",description:"Status",enum:FU}},ux={sortBy:"user.FirstName",sortOrder:"ASC",defaultLimit:50},Tre=e=>({or:{user:{firstName:{contains:e}},or:{user:{lastName:{contains:e}}}}}),dx={query:{path:"name",op:"contains",type:"string",description:"Rule name"},account:{path:"appliesToReconciliationAccount",op:"eq",type:"string",description:"Bank account resourceId",cliFlag:"--account <id>"}},fx={sortBy:"name",sortOrder:"ASC",defaultLimit:100},px={query:{path:"type",op:"contains",type:"string",description:"Classifier type"}},hx={sortBy:"type",sortOrder:"ASC",defaultLimit:100}});var zt=J(()=>{"use strict";zo();ch();zD();JMe();VMe();KMe();XMe();ZMe();eUe();tUe();rUe();nUe();iUe();oUe();sUe();aUe();cUe();lUe();uUe();dUe();mUe();gUe();yUe();EUe()});async function g2(e,t){return e.list("/api/v1/modules",t)}async function y2(e,t){return e.get(`/api/v1/modules/${encodeURIComponent(t)}`)}var xre=J(()=>{"use strict"});async function E2(e,t){return e.list("/api/v1/purchase-items",t)}async function b2(e,t){return e.get(`/api/v1/purchase-items/${encodeURIComponent(t)}`)}async function I2(e,t){return e.search("/api/v1/purchase-items/search",t)}var kre=J(()=>{"use strict"});async function C2(e,t){return e.list("/api/v1/invoices",t)}async function Eo(e,t){let r=await e.get(`/api/v1/invoices/${t}`);return"data"in r&&typeof r.data=="object"?r:{data:r}}async function BC(e,t){return e.search("/api/v1/invoices/search",t)}async function mx(e,t){return e.post("/api/v1/invoices",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function _2(e,t,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(Fu)}:r;return e.put(`/api/v1/invoices/${t}`,n)}async function w2(e,t,r){return e.delete(`/api/v1/invoices/${t}`,r)}async function Ax(e,t,r){return e.post(`/api/v1/invoices/${t}/payments`,{...r,currency:Wt(r.currency),saveAsDraft:r.saveAsDraft??!0},dP)}async function gx(e,t){return e.post("/api/v1/scheduled/invoices",{...t,invoice:{...t.invoice,currency:Wt(t.invoice?.currency)}},Jp)}async function v2(e,t,r){return e.post(`/api/v1/invoices/${t}/credits`,{credits:r},fP)}async function yx(e,t,r){return e.put(`/api/v1/invoices/${t}`,{...r,resourceId:t,saveAsDraft:!1})}async function S2(e,t){return e.get(`/api/v1/invoices/${t}/download`)}async function Ex(e,t){let r=await e.get(`/api/v1/invoices/${t}/payments`);return{data:Array.isArray(r)?r:r.data??[]}}async function D2(e,t){let r=await e.get(`/api/v1/invoices/${t}/credits`);return{data:Array.isArray(r)?r:r.data??[]}}async function R2(e,t,r){await e.delete(`/api/v1/invoices/${t}/credits/${r}`)}async function T2(e,t){return En(e,"/api/v1/invoices/bulk-upsert","invoices",t)}async function x2(e,t){return En(e,"/api/v1/invoices/line-items/bulk-upsert","invoices",Gp(t))}var zg=J(()=>{"use strict";tr();Vp();an();ot()});async function bUe(e,t,r){return e.list(`/api/v1/${Ml[t]}`,r)}async function Ul(e,t,r){return e.get(`/api/v1/${Ml[t]}/${r}`)}async function k2(e,t,r){return e.search(`/api/v1/${Ml[t]}/search`,r)}async function N2(e,t,r){return e.search(`/api/v1/${Ml[t]}/line-items/search`,r)}async function bx(e,t){return e.post("/api/v1/sale-quotes",{...t,currency:Wt(t.currency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function Ix(e,t){return e.post("/api/v1/sale-orders",{...t,currency:Wt(t.currency)},Wi)}async function B2(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/${r}/convert-to-invoice`,n,uP)}async function O2(e,t,r,n){return e.put(`/api/v1/${Ml[t]}/${r}`,n)}async function F2(e,t,r){await e.delete(`/api/v1/${Ml[t]}/${r}`)}async function L2(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/${r}/void`,n?{internalNotes:n}:{})}async function Q2(e,t){return e.post(`/api/v1/sale-quotes/${t}/accept`,{})}async function P2(e,t){return e.post(`/api/v1/sale-orders/${t}/confirm`,{})}async function IUe(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/${r}/fast-fix`,{attributes:n})}async function CUe(e,t,r,n){return e.post(`/api/v1/${Ml[t]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function _Ue(e,t){return e.post("/api/v1/sale-quotes/bulk-accept",{resourceIds:t})}async function wUe(e,t){return e.post("/api/v1/sale-orders/bulk-confirm",{resourceIds:t})}async function vUe(e,t,r){return e.post(`/api/v1/${Ml[t]}/bulk-delete`,{resourceIds:r})}async function SUe(e,t){return e.post("/api/v1/sale-orders/line-items/bulk-upsert",{saleOrders:t},SI)}var Ml,Nre=J(()=>{"use strict";tr();ot();Ml={SALE_QUOTE:"sale-quotes",SALE_ORDER:"sale-orders"}});async function DUe(e,t,r){return e.list(`/api/v1/${$l[t]}`,r)}async function ql(e,t,r){return e.get(`/api/v1/${$l[t]}/${r}`)}async function M2(e,t,r){return e.search(`/api/v1/${$l[t]}/search`,r)}async function U2(e,t,r){return e.search(`/api/v1/${$l[t]}/line-items/search`,r)}async function Cx(e,t){return e.post("/api/v1/purchase-requests",{...t,currency:Wt(t.currency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function _x(e,t){return e.post("/api/v1/purchase-orders",{...t,currency:Wt(t.currency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function $2(e,t,r,n){return e.post(`/api/v1/${$l[t]}/${r}/convert-to-bill`,n,uP)}async function q2(e,t,r,n){return e.put(`/api/v1/${$l[t]}/${r}`,n)}async function j2(e,t,r){await e.delete(`/api/v1/${$l[t]}/${r}`)}async function Y2(e,t,r,n){return e.post(`/api/v1/${$l[t]}/${r}/void`,n?{internalNotes:n}:{})}async function H2(e,t){return e.post(`/api/v1/purchase-requests/${t}/accept`,{})}async function z2(e,t){return e.post(`/api/v1/purchase-orders/${t}/confirm`,{})}async function RUe(e,t,r,n){return e.post(`/api/v1/${$l[t]}/${r}/fast-fix`,{attributes:n})}async function TUe(e,t,r,n){return e.post(`/api/v1/${$l[t]}/bulk-void`,{resourceIds:r,...n?{internalNotes:n}:{}})}async function xUe(e,t){return e.post("/api/v1/purchase-requests/bulk-accept",{resourceIds:t})}async function kUe(e,t){return e.post("/api/v1/purchase-orders/bulk-confirm",{resourceIds:t})}async function NUe(e,t,r){return e.post(`/api/v1/${$l[t]}/bulk-delete`,{resourceIds:r})}async function BUe(e,t){return e.post("/api/v1/purchase-orders/line-items/bulk-upsert",{purchaseOrders:t},SI)}var $l,Bre=J(()=>{"use strict";tr();ot();$l={PURCHASE_REQUEST:"purchase-requests",PURCHASE_ORDER:"purchase-orders"}});function Ore(e,t){return Object.keys(vf).filter(r=>r!==e&&t[vf[r]]!==void 0).map(r=>vf[r])}function CHt(e){let t=Array.isArray(e?.lineItems)?e.lineItems:[],r=[];for(let n of t){let i=n;typeof i?.resourceId!="string"||i.resourceId===""||r.push({resourceId:i.resourceId,...typeof i.name=="string"&&{name:i.name}})}return r}function _Ht(e,t,r,n){let i=CHt(r);if(i.length===0)return;let o=LUe[e],s=new Set(t.map(c=>c?.resourceId).filter(c=>typeof c=="string"&&c!=="").map(OUe));if(s.size===0)return n.appendLines===!0?void 0:{code:"append_would_duplicate",message:`None of the ${t.length} lineItems carries a resourceId, so the API would ADD them beside the ${i.length} line(s) already on this ${o}: an update never replaces lines. To edit lines, send every stored line with its resourceId (set deleted:true on a line to remove it; a line without a resourceId is added). Stored lines: ${FUe(i)}. To add these lines on purpose, set ${n.appendOptIn}.`,storedLines:i};let a=i.filter(c=>!s.has(OUe(c.resourceId)));if(a.length!==0)return{code:"lines_not_sent",message:`lineItems must include every line already on this ${o} once any line names a resourceId, or the API refuses the update. ${a.length} not sent: ${FUe(a)}. Send each with its resourceId, and deleted:true to remove it.`,storedLines:i,missing:a}}async function Fre(e,t,r,n){if(!Array.isArray(t)||t.length===0)return;let i=(await r()).data;return _Ht(e,t,i,n)}async function QUe(e,t,r,n){let i=Ore(e,t);if(i.length>0)throw ut(new ue(`${i.join(", ")} does not apply to a ${LUe[e]}; its flag is ${vf[e]}.`));let o=await Fre(e,t.lineItems,r,n);if(o)throw ut(new ue(o.message))}var LUe,vf,OUe,FUe,Lre=J(()=>{"use strict";ot();LUe={SALE_QUOTE:"sale quote",SALE_ORDER:"sale order",PURCHASE_REQUEST:"purchase request",PURCHASE_ORDER:"purchase order"},vf={SALE_QUOTE:"isDraftToActiveSaleQuote",SALE_ORDER:"isPendingToActiveSaleOrder",PURCHASE_REQUEST:"isDraftToActivePurchaseRequest",PURCHASE_ORDER:"isPendingToActivePurchaseOrder"};OUe=e=>e.trim().toLowerCase();FUe=e=>e.map(t=>t.name?`${t.resourceId} ("${t.name}")`:t.resourceId).join(", ")});async function J2(e,t){return e.list("/api/v1/journals",t)}async function wx(e,t){return e.search("/api/v1/journals/search",t)}async function vx(e,t){return e.post("/api/v1/journals",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function G2(e,t,r){return e.delete(`/api/v1/journals/${t}`,r)}async function vs(e,t){return e.get(`/api/v1/journals/${t}`)}async function OC(e,t,r,n){let i=await PUe(e,t,r,n);return e.put(`/api/v1/journals/${t}`,{...i,currency:Wt(r.currency),taxCurrency:Wt(r.taxCurrency)})}async function PUe(e,t,r,n){xM(r);let i={...r};if(typeof i.taxVatApplicable!="boolean"&&i.journalEntries?.some(s=>!!s?.taxProfileResourceId)&&(i.taxVatApplicable=!0),typeof i.taxVatApplicable=="boolean"&&typeof i.taxInclusion=="boolean")return i;let o=n;if(!o)try{o=(await vs(e,t)).data}catch(s){let a=s instanceof Error?s:new Error(String(s));throw a.message=`Could not read journal ${t} to keep its tax settings, so nothing was changed (retry, or pass taxVatApplicable and taxInclusion explicitly). ${a.message}`,ut(a)}return typeof i.taxVatApplicable!="boolean"&&typeof o?.taxVatApplicable=="boolean"&&(i.taxVatApplicable=o.taxVatApplicable),typeof i.taxInclusion!="boolean"&&typeof o?.taxInclusion=="boolean"&&(i.taxInclusion=o.taxInclusion),i}async function MUe(e,t,r,n){let i=await PUe(e,t,r,n);return e.put(`/api/v1/journals/${t}`,{...i,resourceId:t,saveAsDraft:!1})}async function Sx(e,t){return e.post("/api/v1/scheduled/journals",t,Jp)}async function V2(e,t){return En(e,"/api/v1/journals/bulk-upsert","journals",t)}async function UUe(e,t){return Zi(t,"resourceId","Pass the journal resourceId."),e.get(`/api/v1/journals/${encodeURIComponent(t)}/download`)}var Jg=J(()=>{"use strict";tr();an();ot()});async function Gg(e,t){return e.get(`/api/v1/deferrals/${t}`)}async function X2(e,t){return e.search("/api/v1/deferrals/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function Z2(e,t){return e.post("/api/v1/deferrals",{...t,saveAsDraft:t.saveAsDraft??!0},Pke)}async function eq(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ut(new ue(`The body names deferral ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`));let o={reference:r.reference??(n??(await Gg(e,t)).data).reference};for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=t,e.put(`/api/v1/deferrals/${t}`,o,mP)}async function tq(e,t){return e.delete(`/api/v1/deferrals/${t}`)}async function rq(e,t,r){return e.post(`/api/v1/close-out/deferrals/${t}`,{closeOutDate:r,resourceId:t},mP)}async function nq(e,t){return e.post(`/api/v1/reopen/deferrals/${t}`,{},mP)}async function iq(e,t){return e.get("/api/v1/deferrals/totals",t)}async function oq(e,t,r){return e.get(`/api/v1/deferrals/${t}/schedule`,{viewDate:r})}async function sq(e,t){return e.search("/api/v1/deferrals/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function aq(e,t){return e.search("/api/v1/deferral-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function cq(e,t){return e.search("/api/v1/deferral-accounts/search",{...t,searchTerms:t.searchTerms??[],sort:t.sort??{sortBy:["accountCode"],order:"ASC"}})}async function lq(e,t){return e.put("/api/v1/deferral-accounts",{accounts:t},Mke)}async function uq(e,t){return e.post("/api/v1/deferrals/preview-custom-schedule",t,et)}async function dq(e,t){return mt(t,"deferrals",500,"deferrals"),jo(t,$Ue),En(e,"/api/v1/deferrals/bulk-upsert","deferrals",t)}async function fq(e,t){return mt(t,"deferrals",500,"deferrals"),jo(t,$Ue),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`deferrals[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that deferral. Bulk update does not take tags: change them with update_deferral (clio deferrals update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/deferrals/bulk-update","deferrals",t)}var W2,K2,$Ue,pq,hq=J(()=>{"use strict";an();ot();tr();W2=["PREPAID_EXPENSE","DEFERRED_REVENUE"],K2=["STRAIGHT_LINE","CUSTOM_SCHEDULE"];$Ue=["amortizationStartDate"];pq={deferralCategory:["in"],deferralType:["in"],deferralStatus:["in"],deferralAccount:{resourceId:["in"]},deferralAmount:["gte","lte"],deferralReference:["contains"],deferralName:["contains"]}});function jUe(e){return Array.isArray(e)?`with ${e.join(" / ")}`:e===mq?"with an operator":`with ${Object.keys(e).join(", ")}`}function HUe(e,t,r,n){let i=s=>ut(new ue(`${e} filter.${n}: ${s} The API ignores it and would return an unfiltered report. Nothing was sent.`));if(!YUe(t))throw i(`expected an object ${jUe(r)}.`);let o=Object.keys(t);if(o.length===0)throw i(`the expression is empty, so it filters nothing; give ${jUe(r).replace(/^with /,"")} or drop the field.`);if(r!==mq)for(let s of o)if(Array.isArray(r)){if(!r.includes(s))throw i(`operator "${s}" is not read; it reads ${r.join(" / ")}.`)}else if(s in r)HUe(e,t[s],r[s],`${n}.${s}`);else throw i(`"${s}" is not a supported field; supported: ${Object.keys(r).join(", ")}.`)}function Rx(e,t){let{filter:r}=t;if(r===void 0)return;let n=wHt[e];if(!YUe(r))throw ut(new ue(`${e} filter must be an object keyed by field; supported: ${Object.keys(n).join(", ")}. Nothing was sent.`));for(let[i,o]of Object.entries(r)){let s=n[i];if(!s)throw ut(new ue(`${e} filter.${i} is not a supported field; supported: ${Object.keys(n).join(", ")}. The API ignores it and would return an unfiltered report. Nothing was sent.`));HUe(e,o,s,i)}if(Object.keys(r).length>0&&!(t.primarySnapshotStartDate&&t.primarySnapshotEndDate))throw ut(new ue(`${e} filter needs the period it filters over: send both primarySnapshotStartDate and primarySnapshotEndDate. Nothing was sent.`))}var mq,qUe,Dx,wHt,YUe,zUe=J(()=>{"use strict";ot();hq();mq="expression",qUe=(...e)=>Object.fromEntries(e.map(t=>[t,mq])),Dx={loanAccount:{resourceId:["in"]},loanBalance:["gte","lte"],loanReference:["contains"],loanName:["contains"],loanType:["in"],loanStatus:["in"]},wHt={"deferrals-summary":pq,"fixed-assets-summary":qUe("assetAccount","assetName","assetReference","netBookValueAmount","purchaseValueAmount","assetStatus","assetType","assetCategory","assetDepreciationMethod"),"leases-summary":{leaseAccount:{resourceId:mq},...qUe("leaseLiability","leaseReference","leaseName","leaseType","leaseStatus")},"loans-summary":Dx,"loans-roll-forward":Dx,"loans-related-party":Dx,"loans-interest":Dx,"loans-maturity-analysis":Dx},YUe=e=>!!e&&typeof e=="object"&&!Array.isArray(e)});async function Aq(e,t){return e.post("/api/v1/generate-reports/trial-balance",t,et)}async function gq(e,t){return e.post("/api/v1/generate-reports/balance-sheet",t,et)}async function yq(e,t){return e.post("/api/v1/generate-reports/profit-and-loss",t,et)}async function Eq(e,t){return e.post("/api/v1/generate-reports/cashflow",t,et)}async function bq(e,t){return e.post("/api/v1/generate-reports/ar-summary-report",t,et)}async function Iq(e,t){return e.post("/api/v1/generate-reports/ap-summary-report",t,et)}function Tx(e,t){let{root:r,rows:n}=vHt[t],i=e.data?.[r]??{},o=Array.isArray(i[n])?i[n]:[],s={current:0,lessThanOneMonth:0,oneMonth:0,twoMonths:0,threeMonths:0,older:0,total:0};for(let u of o)s.current+=u.currentIso??0,s.lessThanOneMonth+=u.lessThanOneMonthIso??0,s.oneMonth+=u.oneMonthIso??0,s.twoMonths+=u.twoMonthsIso??0,s.threeMonths+=u.threeMonthsIso??0,s.older+=u.olderIso??0,s.total+=u.balanceIso??0;let a=u=>Math.round(u*100)/100,c=i.startDate;return{reportType:t==="receivables"?"AGED_RECEIVABLES":"AGED_PAYABLES",organizationName:i.organizationName,asAt:typeof c=="number"?new Date(c).toISOString().slice(0,10):void 0,currencyCode:i.currencyCode,currencySymbol:i.currencySymbol,buckets:{current:a(s.current),lessThanOneMonth:a(s.lessThanOneMonth),oneMonth:a(s.oneMonth),twoMonths:a(s.twoMonths),threeMonths:a(s.threeMonths),older:a(s.older)},totalOutstanding:a(s.total),contactCount:o.length}}async function Cq(e,t){return e.post("/api/v1/generate-reports/cash-balance",t,et)}function xx(e){if(e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<1||e>Vg))throw new ct(`limit must be a whole number from 1 to ${Vg} (got ${String(e)}).`)}function SHt(e){let t=[];for(let r=0;r<e.length;r+=Hu)t.push(e.slice(r,r+Hu));return t}function DHt(e){let{accountResourceIds:t,...r}=e;return t&&t.length>0?{...r,filter:{account:{resourceId:{in:t}}}}:r}async function kx(e,t){return e.post("/api/v1/generate-reports/general-ledger",DHt(t),et)}async function GUe(e,t,r=Vg,n){xx(r);let i=t.accountResourceIds??[];if(i.length<=Hu)return JUe(e,t,r,n);let o,s=SHt(i);for(let[a,c]of s.entries()){let u=o?.data.searchGeneralLedgersReport?.data?.length??0,d=n===void 0?void 0:n-u,f=await JUe(e,{...t,accountResourceIds:c},r,d);if(!o)o=f;else{let p=o.data.searchGeneralLedgersReport??{},h=f.data.searchGeneralLedgersReport??{};o.data.searchGeneralLedgersReport={...p,data:[...p.data??[],...h.data??[]],totalElements:(p.totalElements??0)+(h.totalElements??0),totalPages:(p.totalPages??0)+(h.totalPages??0)},o.truncated=o.truncated||f.truncated}if(n!==void 0&&(o.data.searchGeneralLedgersReport?.data?.length??0)>=n&&a<s.length-1){o.truncated=!0;break}}return o}async function JUe(e,t,r,n){let i,o=await bf(async(a,c)=>{let u=await kx(e,{...t,limit:c,offset:a});a===0&&(i=u);let d=u.data?.searchGeneralLedgersReport??{};return{data:d.data??[],totalElements:d.totalElements??0,totalPages:d.totalPages??0}},{pageSize:r,offsetMode:"row",maxItems:n}),s=i?.data?.searchGeneralLedgersReport??{};return{data:{...i?.data,searchGeneralLedgersReport:{...s,data:o.data}},truncated:o.truncated}}async function _q(e,t){return e.post("/api/v1/generate-reports/vat-ledger",t,et)}async function wq(e,t){return e.post("/api/v1/generate-reports/equity-movement",t,et)}async function vq(e,t){return e.post("/api/v1/generate-reports/bank-balance-summary",t,et)}async function Sq(e,t){return e.post("/api/v1/generate-reports/bank-reconciliation-summary",t,et)}async function Dq(e,t){return e.post("/api/v1/generate-reports/bank-reconciliation-details",t,et)}async function Rq(e,t){return Rx("fixed-assets-summary",t),e.post("/api/v1/generate-reports/fixed-assets-summary",t,et)}async function Tq(e,t){return e.post("/api/v1/generate-reports/fixed-assets-recon-summary",t,et)}async function xq(e,t){return Rx("deferrals-summary",t),e.post("/api/v1/generate-reports/deferrals-summary",t,et)}async function kq(e,t){return e.post("/api/v1/generate-reports/deferrals-recon-summary",t,et)}async function VUe(e,t){return Rx("leases-summary",t),e.post("/api/v1/generate-reports/leases-summary",t,et)}async function WUe(e,t){return e.post("/api/v1/generate-reports/leases-recon-summary",t,et)}async function Nx(e,t,r){let n=RHt[t];return t!=="loans-recon-summary"&&Rx(t,r),e.post(n,r,et)}async function Nq(e,t){return e.post("/api/v1/generate-reports/ar-report",t,et)}async function Bq(e,t){return e.post("/api/v1/generate-reports/ap-report",t,et)}async function Oq(e){return e.get("/api/v1/ledger/highlights")}var vHt,FC,Vg,Hu,RHt,Qre=J(()=>{"use strict";JD();fo();zUe();tr();vHt={receivables:{root:"generateAgedReceivablesReportGroupByContact",rows:"customerSummary"},payables:{root:"generateAgedPayablesReportGroupByContact",rows:"supplierSummary"}};FC=["ACCOUNT","CONTACT","TRANSACTION","RELATIONSHIP","CAPSULE"],Vg=1e3,Hu=100;RHt={"loans-summary":"/api/v1/generate-reports/loans-summary","loans-roll-forward":"/api/v1/generate-reports/loans-roll-forward","loans-related-party":"/api/v1/generate-reports/loans-related-party","loans-interest":"/api/v1/generate-reports/loans-interest","loans-maturity-analysis":"/api/v1/generate-reports/loans-maturity-analysis","loans-recon-summary":"/api/v1/generate-reports/loans-recon-summary"}});async function Fq(e,t){return e.list("/api/v1/catalogs",t)}async function Lq(e,t){return e.get(`/api/v1/catalogs/${encodeURIComponent(t)}`)}async function Qq(e,t){return e.search("/api/v1/catalogs/search",t)}async function Pq(e,t){return e.post("/api/v1/catalogs",t)}async function Mq(e,t,r){return e.put(`/api/v1/catalogs/${encodeURIComponent(t)}`,r)}async function Uq(e,t){await e.delete(`/api/v1/catalogs/${encodeURIComponent(t)}`)}var Pre=J(()=>{"use strict"});import{isDeepStrictEqual as THt}from"node:util";function Fx(e,t="templateConfiguration"){let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{throw new ue(`${t} is not valid JSON. Pass the layout as an object, or as a JSON string of one.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new ue(`${t} must be a JSON object (the layout), got ${Array.isArray(r)?"an array":typeof r}.`);let{[jq]:n,...i}=r;return i}function Hq(e){let{[jq]:t,...r}=e;return JSON.stringify(r)}function e$e(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,JSON.stringify(r??null).length]))}function jre(e,t){let r=t.filter(n=>!(n in e));if(r.length>0)throw new ue(`This layout has no ${r.map(n=>`"${n}"`).join(", ")}. Its keys are: ${Object.keys(e).join(", ")}.`);return Object.fromEntries(t.map(n=>[n,e[n]]))}function Yre(e){let t=Ox(e.rowConfigs);if(!t)return;let r=n=>n.filter(i=>i&&typeof i=="object").map(i=>{let o=i.formulaConfig?.formula,s=Ox(i.children);return{id:String(i.id),...typeof i.name=="string"?{name:i.name}:{},...typeof i.rowType=="string"?{rowType:i.rowType}:{},...typeof o=="string"&&o!==""?{formula:o}:{},...s&&s.length>0?{children:r(s)}:{}}});return r(t)}function t$e(e,t){return Bx(e,t).row}function kHt(e){return"path"in e?e.path.join("."):e.field?`row "${e.rowId}".${e.field}`:`row "${e.rowId}"`}function n$e(e,t){if(!(!e||typeof e!="object"))for(let r of Object.keys(e)){if(r$e.has(r))throw new ue(`${t} contains the key "${r}", which is not allowed.`);n$e(e[r],t)}}function Hre(e,t,r){if(!Array.isArray(t)||t.length===0)throw new ue("edits must be a non-empty array of changes.");let n=structuredClone(e),i=[];t.forEach((s,a)=>{let c=`edits[${a}]`,u=NHt(s,c);try{i.push(...BHt(n,u))}catch(d){throw d instanceof ue?new ue(`${c} (${u.op}): ${d.message}`):d}});let o=zq(e,n,r);if(o.length>0)throw new ue(`Nothing was saved. The edits would introduce: ${o.join("; ")}.`);return{configuration:n,touched:i}}function NHt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new ue(`${t} must be an object with an "op".`);let r=e;if(!LC.includes(r.op))throw new ue(`${t}.op must be one of ${LC.join(", ")} (got ${JSON.stringify(r.op)}).`);let n=(i,o)=>{let s=r[i];if(!(o==="string"?typeof s=="string"&&s!=="":!!s&&typeof s=="object"&&!Array.isArray(s)))throw new ue(`${t} (${r.op}) needs "${i}" (${o==="string"?"a non-empty string":"an object"}).`)};switch(r.op){case"set":case"insert":if(n("path","string"),!("value"in r))throw new ue(`${t} (${r.op}) needs "value".`);break;case"remove":n("path","string");break;case"updateRow":n("rowId","string"),n("fields","object");break;case"addRow":n("row","object");break;case"removeRow":n("rowId","string");break;case"moveRow":n("rowId","string");break}if("index"in r&&r.index!==void 0&&!(Number.isInteger(r.index)&&r.index>=0))throw new ue(`${t} (${r.op}): index must be a whole number, 0 or more.`);for(let i of["value","fields","row"])i in r&&n$e(r[i],`${t} (${r.op}) ${i}`);return r}function BHt(e,t){switch(t.op){case"set":{let r=Mre(t.path),{container:n,key:i}=Ure(e,r,"set"),o=Array.isArray(n)?i==="-"?n.length:qq(i,n.length,!0):void 0,s=Array.isArray(n)?n[o]:n[i],a=t.fromText&&typeof t.value=="string"?FHt(t.value,s,$q(r)):structuredClone(t.value);return OHt(s,a,$q(r)),Array.isArray(n)?(n[o]=a,[{path:[...r.slice(0,-1),String(o)]}]):(n[i]=a,[{path:r}])}case"insert":{let r=Mre(t.path),{container:n,key:i}=Ure(e,r,"set");if(!Array.isArray(n))throw new ue(`insert adds to a list, and "${$q(r.slice(0,-1))||"(the layout)"}" is not one. Use set to change a key.`);let o=i==="-"?n.length:qq(i,n.length,!0);return n.splice(o,0,structuredClone(t.value)),[{path:[...r.slice(0,-1),String(o)]}]}case"remove":{let r=Mre(t.path),{container:n,key:i}=Ure(e,r,"remove");if(Array.isArray(n))return n.splice(qq(i,n.length,!1),1),[];if(!Object.hasOwn(n,i))throw new ue(`nothing at "${t.path}" to remove.`);return delete n[i],[{path:r,removed:!0}]}case"updateRow":{let r=Bx(e,t.rowId);for(let n of Object.keys(t.fields)){let i=xHt[n];if(i)throw new ue(`"${n}" cannot be set with updateRow: ${i}.`)}return Object.assign(r.row,structuredClone(t.fields)),Object.keys(t.fields).map(n=>({rowId:t.rowId,field:n}))}case"addRow":{let r=structuredClone(t.row);if(typeof r.id!="string"||r.id==="")throw new ue('the new row needs a string "id", unique in this layout.');if(typeof r.rowType!="string")throw new ue(`the new row needs a "rowType" (${i$e.join(", ")}).`);if(jl(e).some(i=>i.row.id===r.id))throw new ue(`a row with id "${r.id}" already exists.`);let n=XUe(e,t.parentId??null);return r.parentId=t.parentId??null,n.splice(KUe(t.index,n.length),0,r),[{rowId:r.id}]}case"removeRow":{let r=Bx(e,t.rowId),n=new Set(jl({rowConfigs:[r.row]}).map(o=>o.row.id)),i=o$e(e).filter(o=>!n.has(o.rowId)&&o.refs.some(s=>n.has(s)));if(i.length>0)throw new ue(`row "${t.rowId}" is used in the formula of ${i.map(o=>`"${o.rowId}"`).join(", ")}. A formula that names a missing row silently counts it as 0, so update or remove those rows first.`);return r.siblings.splice(r.index,1),[]}case"moveRow":{let r=Bx(e,t.rowId),n=t.parentId??null;if(n!==null&&new Set(jl({rowConfigs:[r.row]}).map(s=>s.row.id)).has(n))throw new ue(`row "${t.rowId}" cannot move inside itself or its own child "${n}".`);r.siblings.splice(r.index,1);let i=XUe(e,n);return r.row.parentId=n,i.splice(KUe(t.index,i.length),0,r.row),[{rowId:t.rowId}]}}}function Yq(e){if(e==null)return"empty";if(Array.isArray(e))return"list";switch(typeof e){case"string":return"text";case"number":return"number";case"boolean":return"true/false";default:return"object"}}function OHt(e,t,r){let n=Yq(e),i=Yq(t);if(n==="empty"||n===i)return;let o=n==="text"&&i==="empty"?' To clear text, set "" instead.':"";throw new ue(`"${r}" holds ${n==="list"||n==="object"?`a ${n}`:n}; got ${i==="list"||i==="object"?`a ${i}`:i}.${o}`)}function FHt(e,t,r){switch(Yq(t)){case"text":return e;case"number":{let n=Number(e);if(e.trim()===""||!Number.isFinite(n))throw new ue(`"${r}" is a number; "${e}" is not one.`);return n}case"true/false":if(e==="true"||e==="false")return e==="true";throw new ue(`"${r}" is true or false; got "${e}".`);case"list":case"object":try{return JSON.parse(e)}catch{throw new ue(`"${r}" holds a ${Yq(t)}; pass it as JSON.`)}default:try{return JSON.parse(e)}catch{return e}}}function Mre(e){let t=e.startsWith("/")?e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")):e.split(".");if(t.length===0||t.some(n=>n===""))throw new ue(`"${e}" is not a path. Use dotted keys like "pdfTitleConfigs.title", or a JSON Pointer like "/pdfTitleConfigs/title".`);let r=t.find(n=>r$e.has(n));if(r)throw new ue(`"${e}" uses "${r}", which is not a layout key.`);if(t[0]===jq)throw new ue(`${jq} is written by the server on every save and cannot be edited.`);return t}function $q(e){return e.join(".")}function Ure(e,t,r){let n=e;for(let i=0;i<t.length-1;i++){let o=t[i],s=Array.isArray(n)?n[qq(o,n.length,!1)]:n&&typeof n=="object"?n[o]:void 0;if(!s||typeof s!="object"){let a=$q(t.slice(0,i+1)),c=n&&typeof n=="object"&&!Array.isArray(n)?` Keys here: ${Object.keys(n).join(", ")||"(none)"}.`:"";throw new ue(`"${a}" does not exist or is not an object or list, so nothing can be ${r==="set"?"set":"removed"} under it.${c}`)}n=s}return{container:n,key:t[t.length-1]}}function qq(e,t,r){let n=Number(e),i=r?t:t-1;if(!Number.isInteger(n)||n<0||n>i)throw i<0?new ue(`the list is empty, so there is no position "${e}"${r?'; use "-" to append':""}.`):new ue(`"${e}" is not a valid position in a list of ${t} (use 0-${i}${r?', or "-" to append':""}).`);return n}function KUe(e,t){if(e===void 0)return t;if(e>t)throw new ue(`index ${e} is past the end: there are ${t+1} positions (0-${t}).`);return e}function Ox(e){return Array.isArray(e)?e:void 0}function jl(e){let t=[],r=i=>{i.forEach((o,s)=>{if(!o||typeof o!="object")return;t.push({row:o,siblings:i,index:s});let a=Ox(o.children);a&&r(a)})},n=Ox(e.rowConfigs);return n&&r(n),t}function Bx(e,t){if(jl(e).length===0)throw new ue(`this layout has no rows (only ${NC.join(", ")} templates have them).`);let r=jl(e).find(n=>n.row.id===t);if(!r){let n=jl(e).map(i=>i.row.id).filter(i=>typeof i=="string").slice(0,40);throw new ue(`no row "${t}". Row ids here: ${n.join(", ")}${n.length===40?", ...":""}.`)}return r}function XUe(e,t){if(t===null){if(!Ox(e.rowConfigs))throw new ue("this layout has no rows to add to.");return e.rowConfigs}let r=Bx(e,t).row;return Array.isArray(r.children)||(r.children=[]),r.children}function MHt(e){return[...e.matchAll(PHt)].map(t=>(t[1]??t[2]??t[3]).trim()).filter(Boolean)}function o$e(e){return jl(e).flatMap(({row:t})=>{let r=t.formulaConfig?.formula;return typeof r=="string"&&r.trim()!==""?[{rowId:String(t.id),refs:MHt(r)}]:[]})}function Wg(e,t){return t.split(".").reduce((r,n)=>r&&typeof r=="object"?r[n]:void 0,e)}function Kg(e,t,r,n){r!=null&&(typeof r!="string"||!n.includes(r))&&e.push(`${t} = ${JSON.stringify(r)} (allowed: ${n.join(", ")})`)}function ZUe(e,t){let r=[];for(let[c,u]of Object.entries(jHt))Kg(r,c,Wg(e,c),u);let n=ju[t].periodKind==="point"?qHt:$Ht;Kg(r,"basePeriodConfig.periodType",Wg(e,"basePeriodConfig.periodType"),n);for(let c of["startDate","endDate"]){let u=Wg(e,`basePeriodConfig.${c}`);u!=null&&!(Number.isInteger(u)&&u>=0)&&r.push(`basePeriodConfig.${c} = ${JSON.stringify(u)} (a date in epoch milliseconds, a whole number)`)}let i=Wg(e,"basePeriodConfig.startDate"),o=Wg(e,"basePeriodConfig.endDate");if(typeof i=="number"&&typeof o=="number"&&i>o&&r.push("basePeriodConfig.startDate is after endDate"),Wg(e,"basePeriodConfig.periodType")==="custom"){let c=ju[t].periodKind==="point"?["endDate"]:["startDate","endDate"];for(let u of c)typeof Wg(e,`basePeriodConfig.${u}`)!="number"&&r.push(`basePeriodConfig.${u} must be a date in epoch milliseconds when periodType is custom`)}Array.isArray(e.columnConfigs)&&e.columnConfigs.forEach((c,u)=>Kg(r,`columnConfigs.${u}.type`,c?.type,YHt)),Array.isArray(e.includedComponents)&&e.includedComponents.forEach((c,u)=>{Kg(r,`includedComponents.${u}.type`,c?.type,HHt)});let s=jl(e),a=new Map;for(let{row:c}of s){let u=String(c.id);a.set(u,(a.get(u)??0)+1);let d=`row "${u}"`;Kg(r,`${d}.rowType`,c.rowType,i$e),Array.isArray(c.actionCriteria)&&c.actionCriteria.forEach(f=>{Kg(r,`${d}.actionCriteria.criteriaVariable`,f?.criteriaVariable,LHt),Kg(r,`${d}.actionCriteria.criteriaCondition`,f?.criteriaCondition,QHt)})}for(let[c,u]of a)u>1&&r.push(`row id "${c}" is used ${u} times`);for(let c of o$e(e))for(let u of c.refs)a.has(u)||r.push(`the formula of row "${c.rowId}" names "${u}", which is not a row (it would count as 0)`);return r}function zq(e,t,r,n={}){let i=new Set(ZUe(e,r)),o=ZUe(t,r).filter(c=>!i.has(c));if(n.engineRows===!1)return o;let s=new Set(jl(e).map(c=>c.row.id)),a=new Set(jl(t).map(c=>c.row.id));for(let c of UHt[r]??[])s.has(c)&&!a.has(c)&&o.push(`row "${c}" was removed, and the report engine reads it by id (totals, tax section or PDF footer)`);return o}function $re(e,t){if("rowId"in t){let r=jl(e).find(n=>n.row.id===t.rowId);return r?t.field?r.row[t.field]:r.row.id:void 0}return t.path.reduce((r,n)=>r&&typeof r=="object"?r[n]:void 0,e)}function qre(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,n)=>qre(r,t[n]));if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let r=e,n=t;return Object.keys(r).every(i=>qre(r[i],n[i]))&&Object.keys(n).every(i=>i in r||s$e(n[i]))}return THt(e,t)}function a$e(e,t,r){return r.filter(n=>"removed"in n&&n.removed?!s$e($re(t,n)):!qre($re(e,n),$re(t,n))).map(kHt)}function Lx(e){return(Array.isArray(e.includedComponents)?e.includedComponents:[]).filter(r=>r?.type==="TEMPLATE").map((r,n)=>({templateResourceId:String(r.templateConfig?.templateResourceId??r.id??""),templateOrder:n+1}))}function zre(e,t){let r=Array.isArray(e.includedComponents)?e.includedComponents:[],n=new Map(r.filter(c=>c?.type==="TEMPLATE").map(c=>[String(c.templateConfig?.templateResourceId??c.id),c])),i=t.map(c=>{let u=n.get(c.templateResourceId);return{...u??{},id:u?.id??c.templateResourceId,type:"TEMPLATE",templateConfig:{...u?.templateConfig??{},reportType:c.reportType,templateName:c.templateName,templateResourceId:c.templateResourceId}}}),o=r.flatMap((c,u)=>c?.type==="TEMPLATE"?[u]:[]),s=[],a=0;if(r.forEach((c,u)=>{if(c?.type!=="TEMPLATE"?s.push(c):a<i.length&&s.push(i[a++]),u===o[o.length-1])for(;a<i.length;)s.push(i[a++])}),a<i.length){let c=s.findIndex(u=>u?.type==="SIGNATURE_PAGE"||u?.type==="APPENDIX");s.splice(c>=0?c:s.length,0,...i.slice(a))}return{...e,includedComponents:s}}function Jre(e="CUSTOM"){return{reportPackType:e,templateFont:"Inter",decorator:"FIRST_PAGE_ONLY",isUppercase:!1,enablePageNumber:!0,roundedValuesMode:"AS_PER_TEMPLATE",basePeriodConfig:{periodType:"this_month"},includedComponents:[]}}var jq,LC,xHt,r$e,i$e,LHt,QHt,PHt,UHt,$Ht,qHt,jHt,YHt,HHt,s$e,Jq=J(()=>{"use strict";ot();Yu();jq="coaSnapshot";LC=["set","insert","remove","updateRow","addRow","removeRow","moveRow"],xHt={id:"a row id cannot change: removeRow it and addRow a new one",children:"use addRow / removeRow / moveRow on the child rows",parentId:"use moveRow"};r$e=new Set(["__proto__","constructor","prototype"]);i$e=["GROUP","SECTION","TOTAL","COMBINE_ACCOUNT","TEXT","ROW","GROUP_TOTAL"],LHt=["ACCOUNT_TYPE","ACCOUNT_CODE","ACCOUNT_NAME","ACCOUNT_CLASS"],QHt=["IS","IS_NOT","IS_IN","IS_NOT_IN","CONTAINS","DOES_NOT_CONTAIN","STARTS_WITH","ENDS_WITH"];PHt=/GT\(\s*([^)]*?)\s*\)|([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})|([^+\-\s()]+)/gi;UHt={PROFIT_AND_LOSS:["TOTAL_NET_PROFIT","TOTAL_NET_PROFIT_BEFORE_TAX","TOTAL_NET_PROFIT_AFTER_TAX","TOTAL_GROSS_PROFIT","TOTAL_OPERATING_PROFIT","TOTAL_OTHER_PROFIT","TOTAL_PBFIT","TOTAL_PROFIT_BEFORE_INCOME_TAX","TOTAL_PROFIT"],BALANCE_SHEET:["TOTAL_ASSETS","TOTAL_LIABILITIES_AND_EQUITY"],CASHFLOW:["NET_CASHFLOW","CASH_SUMMARY_BEGINNING_CASH_BALANCE","CASH_SUMMARY_NET_INCREASE_IN_CASH","CASH_SUMMARY_ENDING_CASH_BALANCE"]},$Ht=["this_month","last_month","this_quarter","last_quarter","this_year","last_year","this_week","this_financial_year","last_financial_year","previous_financial_year","this_financial_quarter","this_financial_year_this_quarter","last_financial_quarter","previous_financial_quarter","this_financial_year_last_quarter","custom"],qHt=["today","end_of_this_month","end_of_last_month","end_of_last_quarter","end_of_last_financial_quarter","end_of_last_financial_year","custom"],jHt={colorTheme:["default","calm","bold","trust","social","ivory","gold","peach"],margins:["default","compact","comfortable"],fontSize:["default","smaller","larger"],templateFont:["Inter","LatoFont","Roboto","Figtree","SourceSans3"],templateStyle:["REPORT_TEMPLATE_CLASSIC","REPORT_TEMPLATE_BALANCED","REPORT_TEMPLATE_MODERN","REPORT_TEMPLATE_UNIFORM"],lineBreak:["L0","L1","L2","L3"],"pdfTitleConfigs.layout":["left_aligned","center_aligned"],"pdfTitleConfigs.headline":["HEADLINE_COMPANY_NAME","HEADLINE_REPORT_TITLE"],"sortConfigs.type":["FIXED","CUSTOM"],"sortConfigs.primarySortBy":["CODE_ASC","CODE_DESC","NAME_ASC","NAME_DESC","AMOUNT_ASC","AMOUNT_DESC"],"sortConfigs.secondarySortBy":["CODE_ASC","CODE_DESC","NAME_ASC","NAME_DESC","AMOUNT_ASC","AMOUNT_DESC"],reportPackType:["ACCOUNTING","FINANCIALS","MANAGEMENT","PAYABLES","RECEIVABLES","CUSTOM"],decorator:["FIRST_PAGE_ONLY","ALL_PAGES","NO_DECORATOR"],roundedValuesMode:["AS_PER_TEMPLATE","ROUNDED_VALUES","EXACT_VALUES"]},YHt=["COMPARE","YEAR_TO_DATE","VARIANCE","ACCOUNT_CODE","TOTAL","MONTH_TO_DATE","CURRENT_PERIOD"],HHt=["COVER_PAGE","TABLE_OF_CONTENTS","TEMPLATE","SIGNATURE_PAGE","APPENDIX"];s$e=e=>e==null||e===""});import{isDeepStrictEqual as zHt}from"node:util";function QC(e){return e.templateConfiguration===void 0||e.templateConfiguration===null||e.templateConfiguration===""?{}:Fx(e.templateConfiguration)}function GHt(e){try{return QC(e)}catch{return{}}}function Qx(e){let t=0;try{t=Hq(QC(e)).length}catch{t=typeof e.templateConfiguration=="string"?e.templateConfiguration.length:0}return{resourceId:e.resourceId,templateName:e.templateName??"",reportType:e.reportType??"",...e.reportCategory?{reportCategory:e.reportCategory}:{},isDefault:e.isDefault===!0,...e.reportPackType?{reportPackType:e.reportPackType}:{},...Array.isArray(e.packTemplates)&&e.packTemplates.length>0?{packTemplates:e.packTemplates.map((r,n)=>({templateResourceId:r.templateResourceId,...r.templateName?{templateName:r.templateName}:{},...r.reportType?{reportType:r.reportType}:{},templateOrder:r.templateOrder??n+1}))}:{},configurationChars:t}}async function Sf(e){let t=await e.list("/api/v1/organization-report-template"),{reportTemplates:r,...n}=t;return Array.isArray(r)&&r.length>0&&(!t.data||t.data.length===0)?{...n,data:r,totalElements:r.length,totalPages:1}:{...n,data:Array.isArray(t.data)?t.data:[],totalElements:t.totalElements??0,totalPages:t.totalPages??0}}async function Gq(e,t){let r=await Sf(e);return{...r,data:r.data.map(Qx)}}async function Vq(e,t){Dre(t.filter);let{data:r}=await Sf(e),n=hUe(r.filter(i=>X$(i,t.filter)),t.sort?.sortBy,t.sort?.order).map(Qx);return{data:n,totalElements:n.length,totalPages:1}}async function Gre(e,t){return e.get(`/api/v1/organization-report-template/${encodeURIComponent(t)}`)}function Dh(e){return e.trim().toLowerCase().replace(/ /g,"_")}async function Df(e,t,r={}){let n=String(t??"").trim();if(!n)throw new ue("Name the template: its resourceId or its exact name.");if(vc.test(n)){let u=r.rows?r.rows.find(d=>d.resourceId.toLowerCase()===n.toLowerCase()):(await Gre(e,n))?.data;if(!u)throw new ue(`No report template ${n} in this organization. ${l$e}`);if(r.reportType&&u.reportType!==r.reportType)throw u$e(u,r.reportType,r.rows??(await Sf(e)).data);return u}let i=r.rows??(await Sf(e)).data,o=r.reportType?i.filter(u=>u.reportType===r.reportType):i,s=o.filter(u=>u.templateName===n),a=s.length>0?s:o.filter(u=>Dh(u.templateName??"")===Dh(n));if(a.length===1)return a[0];if(a.length>1)throw new ue(`"${n}" names ${a.length} templates: ${a.map(u=>`${u.reportType} "${u.templateName}" (${u.resourceId})`).join(", ")}. Pass the resourceId of the one you mean.`);if(r.reportType){let u=i.find(d=>Dh(d.templateName??"")===Dh(n));if(u)throw u$e(u,r.reportType,i)}let c=gf(n,[...o],u=>u.templateName??"",{threshold:.35,limit:3}).map(u=>`${u.item.reportType} "${u.item.templateName}"`);throw new ue(`No ${r.reportType?`${r.reportType} `:""}report template named "${n}".`+(c.length>0?` Did you mean: ${c.join(", ")}?`:` ${l$e}`))}function u$e(e,t,r){let n=r.filter(i=>i.reportType===t).map(i=>`"${i.templateName}"`);return new ue(`"${e.templateName}" is a ${e.reportType} template; this needs a ${t} template (this organization has: ${n.join(", ")||"none"}).`)}function VHt(e){if(!(e==null||e==="")){if(Array.isArray(e))return e.map(String);if(typeof e=="string"){let t=e.trim();if(t.startsWith("["))try{let r=JSON.parse(t);if(Array.isArray(r))return r.map(String)}catch{}return t.split(",").map(r=>r.trim()).filter(Boolean)}throw new ue('keys must be a list of top-level layout key names, e.g. ["pdfTitleConfigs", "columnConfigs"].')}}async function Wq(e,t,r={}){let n=VHt(r.keys);if(r.row!==void 0&&typeof r.row!="string")throw new ue("row must be a row id (text).");let i=await Df(e,t),o=QC(i),s=Qx(i);if(r.row!==void 0&&(s.row=t$e(o,r.row),!n?.length))return s;if(n?.includes(d$e)){let a=Yre(o);if(!a)throw new ue(`This layout has no rows (only ${NC.join(", ")} templates have them).`);let c=n.filter(u=>u!==d$e);return c.length>0&&(s.templateConfiguration=jre(o,c)),s.rowOutline=f$e(a,c$e-JSON.stringify(s).length),s}if(n&&n.length>0)s.templateConfiguration=jre(o,n);else if(r.whole||s.configurationChars<=JHt)s.templateConfiguration=o;else{s.configurationKeys=e$e(o);let a=Yre(o);a&&(s.rowOutline=f$e(a,c$e-JSON.stringify(s).length))}return s}function f$e(e,t){if(JSON.stringify(e).length<=t)return e;let r=e.map(({children:n,...i})=>({...i,...n?{childCount:n.length}:{}}));return JSON.stringify(r).length<=t?r:void 0}async function PC(e,t,r){p$e(t,{allowPack:!1});let n=ju[t];h$e(r,t);let i=r!==void 0&&n.frameworkChangesDefault?r:void 0,o=await Px(()=>e.get("/api/v1/organization-report-template/default-configuration",{reportType:t,...i?{framework:i}:{}}),{reportType:t,framework:r,verb:"default"});return{reportType:t,...i?{framework:i}:{},templateConfiguration:Fx(o?.data?.templateConfiguration??"")}}async function Kq(e,t){let r=t.reportType;p$e(r,{allowPack:!0});let n=m$e(t.templateName);h$e(t.framework,r);let i=r==="REPORT_PACK";if(!i&&t.packTemplates!==void 0)throw new ue(`${Ss.packTemplates} is for REPORT_PACK templates only.`);let o=(await Sf(e)).data;A$e(o,r,n);let s=t.templateConfiguration!==void 0?Fx(t.templateConfiguration):void 0;s&&!i&&await KHt(e,s,r,t.framework),i&&(s??=Jre());let a=[];if(t.edits!==void 0){s??=(await PC(e,r,t.framework)).templateConfiguration;let f=s;({configuration:s,touched:a}=Hre(s,t.edits,r)),i&&y$e(f,s)}let c;if(i){let f=await g$e(e,o,t.packTemplates,s);s=zre(s??Jre(),f),c=f.map((p,h)=>({templateResourceId:p.templateResourceId,templateOrder:h+1}))}let d=(await Px(()=>e.post("/api/v1/organization-report-template",{templateName:n,reportType:r,...t.framework?{framework:t.framework}:{},...s?{templateConfiguration:Hq(s)}:{},...c?{packTemplates:c}:{}},aZ),{reportType:r,framework:t.framework,templateName:n,verb:"create"}))?.data?.resourceId;if(!d)throw new Error("The template was created but the API returned no resourceId. List the templates to find it.");return Vre(e,d,s,a)}async function Xq(e,t,r){if(r.templateName===void 0&&r.templateConfiguration===void 0&&r.edits===void 0&&r.packTemplates===void 0)throw new ue(`Nothing to change: pass ${Ss.templateName}, ${Ss.templateConfiguration}, ${Ss.edits}, or ${Ss.packTemplates}.`);let n=(await Sf(e)).data,i=await Df(e,t,{rows:n}),o=i.reportType,s=o==="REPORT_PACK";if(!s&&r.packTemplates!==void 0)throw new ue(`${Ss.packTemplates} is for REPORT_PACK templates only; "${i.templateName}" is ${o}.`);let a=r.templateName!==void 0?m$e(r.templateName):void 0;a!==void 0&&Dh(a)!==Dh(i.templateName??"")&&A$e(n,o,a);let c=r.templateConfiguration!==void 0||r.edits!==void 0||r.packTemplates!==void 0,u,d,f=[],p=async h=>{let m=QC(h),A=m,g=[];if(r.templateConfiguration!==void 0&&(A=Fx(r.templateConfiguration),WHt(m,A,o)),s&&r.packTemplates===void 0&&XHt(h,m),r.edits!==void 0){let b=A;({configuration:A,touched:g}=Hre(A,r.edits,o)),s&&y$e(b,A)}let y;if(s){let b=await g$e(e,n,r.packTemplates,A);A=zre(A,b),y=b.map((E,C)=>({templateResourceId:E.templateResourceId,templateOrder:C+1}))}return{stored:m,next:A,places:g,pack:y}};if(c){let h=await p(i);if(r.edits!==void 0&&r.templateConfiguration===void 0){let m=(await Gre(e,i.resourceId))?.data;m&&!zHt(QC(m),h.stored)&&(h=await p(m))}u=h.next,f=h.places,d=h.pack}return await Px(()=>e.put(`/api/v1/organization-report-template/${encodeURIComponent(i.resourceId)}`,{...a!==void 0?{templateName:a}:{},...u?{templateConfiguration:Hq(u)}:{},...d?{packTemplates:d}:{}}),{reportType:o,templateName:a,verb:"update"}),Vre(e,i.resourceId,u,f)}async function Zq(e,t){let r=(await Sf(e)).data,n=await Df(e,t,{rows:r}),i=r.find(s=>s.reportType===n.reportType&&s.isDefault===!0&&s.resourceId!==n.resourceId);return n.isDefault===!0?{resourceId:n.resourceId,template:Qx(n),alreadyDefault:!0}:(await Px(()=>e.post(`/api/v1/organization-report-template/${encodeURIComponent(n.resourceId)}/set-default`,void 0),{reportType:n.reportType}),{...await Vre(e,n.resourceId,void 0,[]),previousDefault:i?{resourceId:i.resourceId,templateName:i.templateName}:null})}async function ej(e,t){let r=(await Sf(e)).data,n=await Df(e,t,{rows:r}),i=n.reportType==="REPORT_PACK";if(!i&&n.isDefault===!0){let d=r.filter(f=>f.reportType===n.reportType&&f.resourceId!==n.resourceId);throw new ue(`"${n.templateName}" is the default ${n.reportType} template, so it cannot be deleted. `+(d.length>0?`Make another one the default first (set_default_organization_report_template; CLI: clio report-templates set-default), e.g. ${d.slice(0,3).map(f=>`"${f.templateName}"`).join(", ")}.`:`It is the only ${n.reportType} template; create another and make it the default first.`))}let o=r.filter(d=>d.reportType==="REPORT_PACK"&&d.resourceId!==n.resourceId),s=d=>new Set([...Lx(GHt(d)).map(f=>f.templateResourceId),...(d.packTemplates??[]).map(f=>f.templateResourceId)]),a=o.filter(d=>s(d).has(n.resourceId)),c=a.filter(d=>s(d).size===1);if(c.length>0)throw new ue(`"${n.templateName}" is the only report in the pack${c.length>1?"s":""} ${c.map(d=>`"${d.templateName}"`).join(", ")}, and deleting it would leave an empty pack. Add another report to the pack first, or delete the pack.`);await Px(()=>e.delete(`/api/v1/organization-report-template/${encodeURIComponent(n.resourceId)}`,aZ),{reportType:n.reportType});let u={resourceId:n.resourceId,deleted:!0,templateName:n.templateName,reportType:n.reportType};if(a.length>0&&(u.removedFromPacks=a.map(d=>({resourceId:d.resourceId,templateName:d.templateName}))),i&&n.isDefault===!0)try{let f=(await Sf(e)).data.find(p=>p.reportType==="REPORT_PACK"&&p.isDefault===!0);u.newDefault=f?{resourceId:f.resourceId,templateName:f.templateName}:null}catch(d){return{partialFailures:[`The pack was deleted, but the new default pack could not be read: ${d.message}`],...u}}return u}function p$e(e,t){if(!pUe(e)||!t.allowPack&&e==="REPORT_PACK"){let r=t.allowPack?ws:jg;throw new ue(`reportType must be one of ${r.join(", ")} (got ${JSON.stringify(e)}).`)}}function h$e(e,t){if(e!==void 0){if(!ju[t].takesFramework)throw new ue(`${Ss.framework} applies only to ${Yg.join(", ")} templates.`);if(!RT.includes(e))throw new ue(`framework must be one of ${RT.join(", ")} (got ${JSON.stringify(e)}).`)}}function WHt(e,t,r){let n=Object.keys(e).filter(o=>!(o in t));if(n.length>0)throw new ue(`Nothing was saved. The replacement layout leaves out ${n.join(", ")}, which the stored layout has. Send the whole layout (read it with get_organization_report_template; CLI: get --config-out), or change part of it with ${Ss.edits}.`);let i=zq(e,t,r);if(i.length>0)throw new ue(`Nothing was saved. The replacement layout would introduce: ${i.join("; ")}.`)}function m$e(e){let t=typeof e=="string"?e.trim():"";if(!t)throw new ue("templateName must have at least one visible character.");let r=[...t].length;if(r>255)throw new ue(`templateName is ${r} characters; the limit is 255.`);return t}async function KHt(e,t,r,n){let i=n===void 0||Sh.includes(n),o=(await PC(e,r,i?n:void 0)).templateConfiguration,s=Object.keys(o).filter(c=>!(c in t));if(s.length>0)throw new ue(`Nothing was saved. A ${r} layout needs ${s.join(", ")}, and this one leaves ${s.length===1?"it":"them"} out. Start from a whole layout (get_default_organization_report_template_configuration, or an existing ${r} template), or create without ${Ss.templateConfiguration} and use ${Ss.edits}.`);let a=zq(o,t,r,{engineRows:!1});if(a.length>0)throw new ue(`Nothing was saved. The layout has: ${a.join("; ")}.`)}function XHt(e,t){let r=Lx(t).map(o=>o.templateResourceId),n=[...e.packTemplates??[]].sort((o,s)=>(o.templateOrder??0)-(s.templateOrder??0)).map(o=>o.templateResourceId);if(n.length===0||r.join()===n.join())return;let i=o=>e.packTemplates?.find(s=>s.templateResourceId===o)?.templateName??o;throw new ue(`Nothing was saved. This pack's two records of its reports disagree: its layout shows ${r.map(i).join(", ")||"none"}, its report list shows ${n.map(i).join(", ")}. Pass ${Ss.packTemplates} with the reports it should hold, and both are rewritten from it.`)}function A$e(e,t,r){let n=e.find(i=>i.reportType===t&&Dh(i.templateName??"")===Dh(r));if(n)throw new ue(`A ${t} template named "${n.templateName}" already exists (${n.resourceId}). Names are unique per report type, ignoring case and treating spaces and underscores alike. Pick another name, or update that template.`)}async function g$e(e,t,r,n){let i;if(r!==void 0){if(!Array.isArray(r)||r.length===0)throw new ue(`${Ss.packTemplates} must list at least one report (a template resourceId or name).`);if(r.length>100)throw new ue(`${Ss.packTemplates} lists ${r.length} reports; the limit is 100.`);let s=r.map((c,u)=>{if(typeof c=="string")return{ref:c,order:u+1};if(c&&typeof c=="object"&&typeof c.templateResourceId=="string")return{ref:c.templateResourceId,order:c.templateOrder??u+1};throw new ue(`packTemplates[${u}] must be a template resourceId or name.`)}),a=s.map(c=>c.order);if(new Set(a).size!==a.length)throw new ue("packTemplates has two reports at the same templateOrder.");i=[...s].sort((c,u)=>c.order-u.order).map(c=>c.ref)}else if(i=Lx(n??{}).map(s=>s.templateResourceId),i.length===0)throw new ue(`A report pack needs at least one report: pass ${Ss.packTemplates}, template names or resourceIds in order.`);let o=[];for(let s of i){let a=await Df(e,s,{rows:t});if(a.reportType==="REPORT_PACK")throw new ue(`"${a.templateName}" is itself a pack; packs cannot contain packs.`);if(o.some(c=>c.templateResourceId===a.resourceId))throw new ue(`"${a.templateName}" is listed twice in the pack.`);o.push({templateResourceId:a.resourceId,templateName:a.templateName??"",reportType:a.reportType??""})}return o}function y$e(e,t){let r=s=>Lx(s).map(a=>a.templateResourceId),n=r(e),i=r(t);if(n.join()===i.join())return;let o=n.filter(s=>!i.includes(s));throw new ue(`Nothing was saved. These edits change which reports the pack holds${o.length?` (they would drop ${o.length} of them)`:""}. Change the reports with ${Ss.packTemplates}; use edits for the cover page, contents, signature and styling, and insert (not set) to add a component to includedComponents.`)}async function Vre(e,t,r,n){let i;try{i=await ZHt(e,t)}catch(s){return{partialFailures:[`Saved, but reading it back failed: ${s.message}`],resourceId:t}}if(!i)return{partialFailures:["Saved, but reading it back returned nothing."],resourceId:t};let o={resourceId:t,template:Qx(i)};if(r&&n.length>0){let s=a$e(r,QC(i),n);s.length>0&&(o.notSaved=s)}return o}async function ZHt(e,t){let r=[250,500,1e3];for(let n=0;;n++)try{return(await Gre(e,t))?.data}catch(i){if(!(i instanceof gr)||i.status!==404||n>=r.length)throw i;await new Promise(o=>setTimeout(o,r[n]))}}async function Px(e,t){try{return await e()}catch(r){throw ezt(r,t),r}}function ezt(e,t){if(!(e instanceof gr)||!e.endpoint.startsWith("/api/v1/organization-report-template")||e.refusal)return;let r=e.body?.error?.error_type;if(typeof r=="string")switch(r){case"NO_TEMPLATE_FOUND":e.refusal={code:r,hint:`There is no system default ${t.reportType??""} layout${t.framework?` for ${t.framework}`:""}: defaults exist for ${Sh.join(" and ")} only. `+(t.verb==="create"?`Use one of those, or pass ${Ss.templateConfiguration} with a whole layout, for example an existing template's.`:"Use one of those, or start from an existing template's layout (get_organization_report_template; CLI: get --config-out) and create with it."),repairTool:"list_organization_report_templates"};return;case"DUPLICATE_REPORT_TEMPLATE_EXISTS":e.refusal={code:r,hint:`A ${t.reportType??""} template named "${t.templateName??""}" already exists. Names are unique per report type, ignoring case and treating spaces and underscores alike. Pick another name.`,repairTool:"search_organization_report_templates"};return;case"CANNOT_DELETE_REPORT_TEMPLATE":e.refusal={code:r,hint:"Upstream refuses to delete the default template of a report type, and the only template of one. Make another template the default first.",repairTool:"list_organization_report_templates"};return;case"TEMPLATE_NOT_FOUND":case"DUPLICATE_TEMPLATE_ORDER":e.refusal={code:r,hint:"A report pack lists a template that does not exist, or two at the same position. List the templates and pass packTemplates again.",repairTool:"list_organization_report_templates"};return}}var JHt,c$e,l$e,Ss,d$e,Mx=J(()=>{"use strict";Ki();ot();tr();Tg();Yu();Jq();Rre();JHt=15e3,c$e=19500;l$e="List them with list_organization_report_templates (CLI: clio report-templates list).",Ss={templateName:"templateName (CLI --name)",templateConfiguration:"templateConfiguration (CLI --config-file)",edits:"edits (CLI --set / --remove / --edits)",packTemplates:"packTemplates (CLI --report)",framework:"framework (CLI --framework)"};d$e="rowOutline"});function w$e(e){return e.edits}var Rh,tj,E$e,b$e,I$e,C$e,_$e,v$e,S$e=J(()=>{"use strict";zt();Mx();Yu();Jq();Rh="report_templates",tj={type:"string",description:"The template: its resourceId or exact name."},E$e={type:"string",enum:[...ws],description:"REPORT_PACK bundles several reports in one document."},b$e={type:"string",enum:[...RT],description:`${Yg.join(", ")} only (default IAS_1). Starting layouts exist for ${Sh.join(" and ")}.`},I$e={type:"object",description:"The whole layout. Prefer edits to change part of it."},C$e={type:"array",description:'Layout changes, in order, all or nothing. set {path, value}, insert {path, value} into a list, remove {path}; path dotted like "pdfTitleConfigs.title". Rows by id: updateRow {rowId, fields}, addRow {row, parentId?, index?}, removeRow {rowId}, moveRow {rowId, parentId?, index?}.',items:{type:"object",properties:{op:{type:"string",enum:[...LC],description:"The change."},path:{type:"string"},rowId:{type:"string"},fields:{type:"object"},row:{type:"object"},parentId:{type:"string"},index:{type:"number"}},required:["op"]}},_$e={type:"array",items:{type:"string"},description:"REPORT_PACK: its reports in order, each a resourceId or name."};v$e=[{name:"list_organization_report_templates",description:"List every report template (no layouts): reportType, isDefault (one per type), a pack's reports. Read one with get_organization_report_template.",params:{},required:[],group:Rh,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"list report templates layouts packs default",execute:async e=>Gq(e.client)},{name:"get_organization_report_template",description:"Read a report template and its layout (templateConfiguration). Too large to return whole: configurationKeys (key sizes) and rowOutline come back; ask for keys or one row.",params:{template:tj,keys:{type:"array",items:{type:"string"},description:'Only these top-level layout keys; "rowOutline" gives the row outline.'},row:{type:"string",description:"One row in full, by id."}},required:["template"],group:Rh,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"get read report template layout configuration",execute:async(e,t)=>Wq(e.client,t.template,{keys:t.keys,row:t.row})},Nt({name:"search_organization_report_templates",description:"Find report templates by name, report type, category or default flag.",group:Rh,fields:BT,defaults:OT,fetcher:Vq,searchHint:"find report templates by name type category default"}),{name:"get_default_organization_report_template_configuration",description:"The default layout a new template of this report type starts from.",params:{reportType:{...E$e,enum:[...jg],description:"Packs have none."},framework:b$e},required:["reportType"],group:Rh,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"default system report template layout starting point",execute:async(e,t)=>PC(e.client,t.reportType,t.framework)},{name:"create_organization_report_template",description:"Create a report template from the default layout (or templateConfiguration), with edits applied. A pack needs packTemplates. Not made the default; names are unique per report type.",params:{templateName:{type:"string",description:"Unique within its report type."},reportType:E$e,framework:b$e,templateConfiguration:I$e,edits:C$e,packTemplates:_$e},required:["templateName","reportType"],group:Rh,readOnly:!1,searchHint:"create new report template custom layout pack",execute:async(e,t)=>Kq(e.client,{templateName:t.templateName,reportType:t.reportType,framework:t.framework,templateConfiguration:t.templateConfiguration,edits:w$e(t),packTemplates:t.packTemplates})},{name:"update_organization_report_template",description:"Rename a report template, change its layout (edits or templateConfiguration), or a pack's reports (packTemplates).",params:{template:tj,templateName:{type:"string",description:"New name."},templateConfiguration:I$e,edits:C$e,packTemplates:_$e},required:["template"],group:Rh,readOnly:!1,isDestructive:!0,searchHint:"update edit rename report template layout title rows columns",execute:async(e,t)=>Xq(e.client,t.template,{templateName:t.templateName,templateConfiguration:t.templateConfiguration,edits:w$e(t),packTemplates:t.packTemplates})},{name:"set_default_organization_report_template",description:"Make a template its report type's default: every export and dashboard view of it then uses it, org-wide. Answers with previousDefault.",params:{template:tj},required:["template"],group:Rh,readOnly:!1,isDestructive:!0,searchHint:"set default report template",execute:async(e,t)=>Zq(e.client,t.template)},{name:"delete_organization_report_template",description:"Delete a report template (also removed from packs). Refused for a type's default and a pack's last report.",params:{template:tj},required:["template"],group:Rh,readOnly:!1,isDestructive:!0,searchHint:"delete remove report template",execute:async(e,t)=>ej(e.client,t.template)}]});async function rj(e,t){return e.list("/api/v1/customer-credit-notes",t)}async function Vs(e,t){return e.get(`/api/v1/customer-credit-notes/${t}`)}async function Ux(e,t){return e.search("/api/v1/customer-credit-notes/search",t)}async function $x(e,t){return e.post("/api/v1/customer-credit-notes",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function nj(e,t,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(Fu)}:r;return e.put(`/api/v1/customer-credit-notes/${t}`,n)}async function qx(e,t,r){return e.put(`/api/v1/customer-credit-notes/${t}`,{...r,resourceId:t,saveAsDraft:!1})}async function ij(e,t,r){return e.delete(`/api/v1/customer-credit-notes/${t}`,r)}async function jx(e,t,r){return e.post(`/api/v1/customer-credit-notes/${t}/refunds`,{...r,currency:Wt(r.currency),saveAsDraft:r.saveAsDraft??!0},pP)}async function Yx(e,t){return e.get(`/api/v1/customer-credit-notes/${t}/refunds`)}async function oj(e,t){return e.get(`/api/v1/customer-credit-notes/${t}/download`)}async function sj(e,t){return En(e,"/api/v1/customer-credit-notes/bulk-upsert","customerCreditNotes",Gp(t))}var Hx=J(()=>{"use strict";tr();Vp();an();ot()});async function aj(e,t){return e.list("/api/v1/supplier-credit-notes",t)}async function Ws(e,t){return e.get(`/api/v1/supplier-credit-notes/${t}`)}async function zx(e,t){return e.search("/api/v1/supplier-credit-notes/search",t)}async function Jx(e,t){return e.post("/api/v1/supplier-credit-notes",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency),saveAsDraft:t.saveAsDraft??!0},Wi)}async function cj(e,t,r){let n=r.lineItems?{...r,lineItems:r.lineItems.map(Fu)}:r;return e.put(`/api/v1/supplier-credit-notes/${t}`,n)}async function Gx(e,t,r){return e.put(`/api/v1/supplier-credit-notes/${t}`,{...r,resourceId:t,saveAsDraft:!1})}async function lj(e,t,r){return e.delete(`/api/v1/supplier-credit-notes/${t}`,r)}async function uj(e,t){return e.get(`/api/v1/supplier-credit-notes/${t}/download`)}async function Vx(e,t,r){return e.post(`/api/v1/supplier-credit-notes/${t}/refunds`,{...r,currency:Wt(r.currency),saveAsDraft:r.saveAsDraft??!0},pP)}async function Wx(e,t){return e.get(`/api/v1/supplier-credit-notes/${t}/refunds`)}async function dj(e,t){return En(e,"/api/v1/supplier-credit-notes/bulk-upsert","supplierCreditNotes",Gp(t))}var Kx=J(()=>{"use strict";tr();Vp();an();ot()});async function Xx(e){return e.get("/api/v1/organization/currencies")}async function fj(e,t){return e.post("/api/v1/organization/currencies",{currencies:t})}async function pj(e,t,r){return e.list(`/api/v1/organization/currencies/${t}/rates`,r)}function D$e(e){_Z(e.rate,"rate");let t=CZ(e.rateDirection);return{...e,rateDirection:t}}async function hj(e,t,r){return e.post(`/api/v1/organization/currencies/${t}/rates`,D$e(r))}async function mj(e,t,r,n){return e.put(`/api/v1/organization/currencies/${t}/rates/${r}`,D$e(n))}async function Aj(e,t){return e.post("/api/v1/organization/currencies/rates/bulk-upsert",{rates:t})}var gj=J(()=>{"use strict";ot()});var R$e=I((Wre,Kre)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Kre=="object"&&typeof Wre<"u"?Kre.exports=t():e.Papa=t()})(Wre,function e(){"use strict";var t=(function(){return typeof self<"u"?self:typeof window<"u"?window:typeof t<"u"?t:{}})();function r(){var R=t.URL||t.webkitURL||null,O=e.toString();return a.BLOB_URL||(a.BLOB_URL=R.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",O,")();"],{type:"text/javascript"})))}var n=!t.document&&!!t.postMessage,i=t.IS_PAPA_WORKER||!1,o={},s=0,a={};if(a.parse=u,a.unparse=d,a.RECORD_SEP="",a.UNIT_SEP="",a.BYTE_ORDER_MARK="\uFEFF",a.BAD_DELIMITERS=["\r",`
431
431
  `,'"',a.BYTE_ORDER_MARK],a.WORKERS_SUPPORTED=!n&&!!t.Worker,a.NODE_STREAM_INPUT=1,a.LocalChunkSize=1024*1024*10,a.RemoteChunkSize=1024*1024*5,a.DefaultDelimiter=",",a.Parser=E,a.ParserHandle=y,a.NetworkStreamer=p,a.FileStreamer=h,a.StringStreamer=m,a.ReadableStreamStreamer=A,typeof PAPA_BROWSER_CONTEXT>"u"&&(a.DuplexStreamStreamer=g),t.jQuery){var c=t.jQuery;c.fn.parse=function(R){var O=R.config||{},M=[];return this.each(function(V){var X=c(this).prop("tagName").toUpperCase()==="INPUT"&&c(this).attr("type").toLowerCase()==="file"&&t.FileReader;if(!X||!this.files||this.files.length===0)return!0;for(var oe=0;oe<this.files.length;oe++)M.push({file:this.files[oe],inputElem:this,instanceConfig:c.extend({},O)})}),W(),this;function W(){if(M.length===0){j(R.complete)&&R.complete();return}var V=M[0];if(j(R.before)){var X=R.before(V.file,V.inputElem);if(typeof X=="object")if(X.action==="abort"){B("AbortError",V.file,V.inputElem,X.reason);return}else if(X.action==="skip"){Y();return}else typeof X.config=="object"&&(V.instanceConfig=c.extend(V.instanceConfig,X.config));else if(X==="skip"){Y();return}}var oe=V.instanceConfig.complete;V.instanceConfig.complete=function(Ee){j(oe)&&oe(Ee,V.file,V.inputElem),Y()},a.parse(V.file,V.instanceConfig)}function B(V,X,oe,Ee){j(R.error)&&R.error({name:V},X,oe,Ee)}function Y(){M.splice(0,1),W()}}}i&&(t.onmessage=k);function u(R,O){O=O||{};var M=O.dynamicTyping||!1;if(j(M)&&(O.dynamicTypingFunction=M,M={}),O.dynamicTyping=M,O.transform=j(O.transform)?O.transform:!1,O.worker&&a.WORKERS_SUPPORTED){var W=C();W.userStep=O.step,W.userChunk=O.chunk,W.userComplete=O.complete,W.userError=O.error,O.step=j(O.step),O.chunk=j(O.chunk),O.complete=j(O.complete),O.error=j(O.error),delete O.worker,W.postMessage({input:R,config:O,workerId:W.id});return}var B=null;if(R===a.NODE_STREAM_INPUT&&typeof PAPA_BROWSER_CONTEXT>"u")return B=new g(O),B.getStream();return typeof R=="string"?(R=Y(R),O.download?B=new p(O):B=new m(O)):R.readable===!0&&j(R.read)&&j(R.on)?B=new A(O):(t.File&&R instanceof File||R instanceof Object)&&(B=new h(O)),B.stream(R);function Y(V){return V.charCodeAt(0)===65279?V.slice(1):V}}function d(R,O){var M=!1,W=!0,B=",",Y=`\r
432
432
  `,V='"',X=V+V,oe=!1,Ee=null,ke=!1;yt();var ve=new RegExp(b(V),"g");if(typeof R=="string"&&(R=JSON.parse(R)),Array.isArray(R)){if(!R.length||Array.isArray(R[0]))return Ne(null,R,oe);if(typeof R[0]=="object")return Ne(Ee||Object.keys(R[0]),R,oe)}else if(typeof R=="object")return typeof R.data=="string"&&(R.data=JSON.parse(R.data)),Array.isArray(R.data)&&(R.fields||(R.fields=R.meta&&R.meta.fields||Ee),R.fields||(R.fields=Array.isArray(R.data[0])?R.fields:typeof R.data[0]=="object"?Object.keys(R.data[0]):[]),!Array.isArray(R.data[0])&&typeof R.data[0]!="object"&&(R.data=[R.data])),Ne(R.fields||[],R.data||[],oe);throw new Error("Unable to serialize unrecognized input");function yt(){if(typeof O=="object"){if(typeof O.delimiter=="string"&&!a.BAD_DELIMITERS.filter(function(le){return O.delimiter.indexOf(le)!==-1}).length&&(B=O.delimiter),(typeof O.quotes=="boolean"||typeof O.quotes=="function"||Array.isArray(O.quotes))&&(M=O.quotes),(typeof O.skipEmptyLines=="boolean"||typeof O.skipEmptyLines=="string")&&(oe=O.skipEmptyLines),typeof O.newline=="string"&&(Y=O.newline),typeof O.quoteChar=="string"&&(V=O.quoteChar),typeof O.header=="boolean"&&(W=O.header),Array.isArray(O.columns)){if(O.columns.length===0)throw new Error("Option columns is empty");Ee=O.columns}O.escapeChar!==void 0&&(X=O.escapeChar+V),O.escapeFormulae instanceof RegExp?ke=O.escapeFormulae:typeof O.escapeFormulae=="boolean"&&O.escapeFormulae&&(ke=/^[=+\-@\t\r].*$/)}}function Ne(le,we,Le){var ze="";typeof le=="string"&&(le=JSON.parse(le)),typeof we=="string"&&(we=JSON.parse(we));var Yt=Array.isArray(le)&&le.length>0,Mt=!Array.isArray(we[0]);if(Yt&&W){for(var pr=0;pr<le.length;pr++)pr>0&&(ze+=B),ze+=Ue(le[pr],pr);we.length>0&&(ze+=Y)}for(var Ve=0;Ve<we.length;Ve++){var je=Yt?le.length:we[Ve].length,wt=!1,$e=Yt?Object.keys(we[Ve]).length===0:we[Ve].length===0;if(Le&&!Yt&&(wt=Le==="greedy"?we[Ve].join("").trim()==="":we[Ve].length===1&&we[Ve][0].length===0),Le==="greedy"&&Yt){for(var Xe=[],rt=0;rt<je;rt++){var Ze=Mt?le[rt]:rt;Xe.push(we[Ve][Ze])}wt=Xe.join("").trim()===""}if(!wt){for(var ae=0;ae<je;ae++){ae>0&&!$e&&(ze+=B);var ee=Yt&&Mt?le[ae]:ae;ze+=Ue(we[Ve][ee],ae)}Ve<we.length-1&&(!Le||je>0&&!$e)&&(ze+=Y)}}return ze}function Ue(le,we){if(typeof le>"u"||le===null)return"";if(le.constructor===Date)return JSON.stringify(le).slice(1,25);var Le=!1;ke&&typeof le=="string"&&ke.test(le)&&(le="'"+le,Le=!0);var ze=le.toString().replace(ve,X);return Le=Le||M===!0||typeof M=="function"&&M(le,we)||Array.isArray(M)&&M[we]||Ae(ze,a.BAD_DELIMITERS)||ze.indexOf(B)>-1||ze.charAt(0)===" "||ze.charAt(ze.length-1)===" ",Le?V+ze+V:ze}function Ae(le,we){for(var Le=0;Le<we.length;Le++)if(le.indexOf(we[Le])>-1)return!0;return!1}}function f(R){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},O.call(this,R),this.parseChunk=function(M,W){let B=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&B>0){let ke=this._config.newline;if(!ke){let yt=this._config.quoteChar||'"';ke=this._handle.guessLineEndings(M,yt)}M=[...M.split(ke).slice(B)].join(ke)}if(this.isFirstChunk&&j(this._config.beforeFirstChunk)){var Y=this._config.beforeFirstChunk(M);Y!==void 0&&(M=Y)}this.isFirstChunk=!1,this._halted=!1;var V=this._partialLine+M;this._partialLine="";var X=this._handle.parse(V,this._baseIndex,!this._finished);if(this._handle.paused()||this._handle.aborted()){this._halted=!0;return}var oe=X.meta.cursor;this._finished||(this._partialLine=V.substring(oe-this._baseIndex),this._baseIndex=oe),X&&X.data&&(this._rowCount+=X.data.length);var Ee=this._finished||this._config.preview&&this._rowCount>=this._config.preview;if(i)t.postMessage({results:X,workerId:a.WORKER_ID,finished:Ee});else if(j(this._config.chunk)&&!W){if(this._config.chunk(X,this._handle),this._handle.paused()||this._handle.aborted()){this._halted=!0;return}X=void 0,this._completeResults=void 0}return!this._config.step&&!this._config.chunk&&(this._completeResults.data=this._completeResults.data.concat(X.data),this._completeResults.errors=this._completeResults.errors.concat(X.errors),this._completeResults.meta=X.meta),!this._completed&&Ee&&j(this._config.complete)&&(!X||!X.meta.aborted)&&(this._config.complete(this._completeResults,this._input),this._completed=!0),!Ee&&(!X||!X.meta.paused)&&this._nextChunk(),X},this._sendError=function(M){j(this._config.error)?this._config.error(M):i&&this._config.error&&t.postMessage({workerId:a.WORKER_ID,error:M,finished:!1})};function O(M){var W=F(M);W.chunkSize=parseInt(W.chunkSize),!M.step&&!M.chunk&&(W.chunkSize=null),this._handle=new y(W),this._handle.streamer=this,this._config=W}}function p(R){R=R||{},R.chunkSize||(R.chunkSize=a.RemoteChunkSize),f.call(this,R);var O;n?this._nextChunk=function(){this._readChunk(),this._chunkLoaded()}:this._nextChunk=function(){this._readChunk()},this.stream=function(W){this._input=W,this._nextChunk()},this._readChunk=function(){if(this._finished){this._chunkLoaded();return}if(O=new XMLHttpRequest,this._config.withCredentials&&(O.withCredentials=this._config.withCredentials),n||(O.onload=G(this._chunkLoaded,this),O.onerror=G(this._chunkError,this)),O.open(this._config.downloadRequestBody?"POST":"GET",this._input,!n),this._config.downloadRequestHeaders){var W=this._config.downloadRequestHeaders;for(var B in W)O.setRequestHeader(B,W[B])}if(this._config.chunkSize){var Y=this._start+this._config.chunkSize-1;O.setRequestHeader("Range","bytes="+this._start+"-"+Y)}try{O.send(this._config.downloadRequestBody)}catch(V){this._chunkError(V.message)}n&&O.status===0&&this._chunkError()},this._chunkLoaded=function(){if(O.readyState===4){if(O.status<200||O.status>=400){this._chunkError();return}this._start+=this._config.chunkSize?this._config.chunkSize:O.responseText.length,this._finished=!this._config.chunkSize||this._start>=M(O),this.parseChunk(O.responseText)}},this._chunkError=function(W){var B=O.statusText||W;this._sendError(new Error(B))};function M(W){var B=W.getResponseHeader("Content-Range");return B===null?-1:parseInt(B.substring(B.lastIndexOf("/")+1))}}p.prototype=Object.create(f.prototype),p.prototype.constructor=p;function h(R){R=R||{},R.chunkSize||(R.chunkSize=a.LocalChunkSize),f.call(this,R);var O,M,W=typeof FileReader<"u";this.stream=function(B){this._input=B,M=B.slice||B.webkitSlice||B.mozSlice,W?(O=new FileReader,O.onload=G(this._chunkLoaded,this),O.onerror=G(this._chunkError,this)):O=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){!this._finished&&(!this._config.preview||this._rowCount<this._config.preview)&&this._readChunk()},this._readChunk=function(){var B=this._input;if(this._config.chunkSize){var Y=Math.min(this._start+this._config.chunkSize,this._input.size);B=M.call(B,this._start,Y)}var V=O.readAsText(B,this._config.encoding);W||this._chunkLoaded({target:{result:V}})},this._chunkLoaded=function(B){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(B.target.result)},this._chunkError=function(){this._sendError(O.error)}}h.prototype=Object.create(f.prototype),h.prototype.constructor=h;function m(R){R=R||{},f.call(this,R);var O;this.stream=function(M){return O=M,this._nextChunk()},this._nextChunk=function(){if(!this._finished){var M=this._config.chunkSize,W;return M?(W=O.substring(0,M),O=O.substring(M)):(W=O,O=""),this._finished=!O,this.parseChunk(W)}}}m.prototype=Object.create(m.prototype),m.prototype.constructor=m;function A(R){R=R||{},f.call(this,R);var O=[],M=!0,W=!1;this.pause=function(){f.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){f.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(B){this._input=B,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){W&&O.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),O.length?this.parseChunk(O.shift()):M=!0},this._streamData=G(function(B){try{O.push(typeof B=="string"?B:B.toString(this._config.encoding)),M&&(M=!1,this._checkIsFinished(),this.parseChunk(O.shift()))}catch(Y){this._streamError(Y)}},this),this._streamError=G(function(B){this._streamCleanUp(),this._sendError(B)},this),this._streamEnd=G(function(){this._streamCleanUp(),W=!0,this._streamData("")},this),this._streamCleanUp=G(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}A.prototype=Object.create(f.prototype),A.prototype.constructor=A;function g(R){var O=z("stream").Duplex,M=F(R),W=!0,B=!1,Y=[],V=null;this._onCsvData=function(X){var oe=X.data;!V.push(oe)&&!this._handle.paused()&&this._handle.pause()},this._onCsvComplete=function(){V.push(null)},M.step=G(this._onCsvData,this),M.complete=G(this._onCsvComplete,this),f.call(this,M),this._nextChunk=function(){B&&Y.length===1&&(this._finished=!0),Y.length?Y.shift()():W=!0},this._addToParseQueue=function(X,oe){Y.push(G(function(){if(this.parseChunk(typeof X=="string"?X:X.toString(M.encoding)),j(oe))return oe()},this)),W&&(W=!1,this._nextChunk())},this._onRead=function(){this._handle.paused()&&this._handle.resume()},this._onWrite=function(X,oe,Ee){this._addToParseQueue(X,Ee)},this._onWriteComplete=function(){B=!0,this._addToParseQueue("")},this.getStream=function(){return V},V=new O({readableObjectMode:!0,decodeStrings:!1,read:G(this._onRead,this),write:G(this._onWrite,this)}),V.once("finish",G(this._onWriteComplete,this))}typeof PAPA_BROWSER_CONTEXT>"u"&&(g.prototype=Object.create(f.prototype),g.prototype.constructor=g);function y(R){var O=Math.pow(2,53),M=-O,W=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,B=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Y=this,V=0,X=0,oe,Ee,ke=!1,ve=!1,yt,Ne=[],Ue={data:[],errors:[],meta:{}};if(j(R.step)){var Ae=R.step;R.step=function($e){if(Ue=$e,ze())Le();else{if(Le(),Ue.data.length===0)return;V+=$e.data.length,R.preview&&V>R.preview?Ee.abort():(Ue.data=Ue.data[0],Ae(Ue,Y))}}}this.parse=function($e,Xe,rt){var Ze=R.quoteChar||'"';if(R.newline||(R.newline=this.guessLineEndings($e,Ze)),yt=!1,R.delimiter)j(R.delimiter)&&(R.delimiter=R.delimiter($e),Ue.meta.delimiter=R.delimiter);else{var ae=je($e,R.newline,R.skipEmptyLines,R.comments,R.delimitersToGuess);ae.successful?R.delimiter=ae.bestDelimiter:(yt=!0,R.delimiter=a.DefaultDelimiter),Ue.meta.delimiter=R.delimiter}var ee=F(R);return R.preview&&R.header&&ee.preview++,oe=$e,Ee=new E(ee),Ue=Ee.parse(oe,Xe,rt),Le(),ke?{meta:{paused:!0}}:Ue||{meta:{paused:!1}}},this.paused=function(){return ke},this.pause=function(){ke=!0,Ee.abort(),oe=j(R.chunk)?"":oe.substring(Ee.getCharIndex())},this.resume=function(){Y.streamer._halted?(ke=!1,Y.streamer.parseChunk(oe,!0)):setTimeout(Y.resume,3)},this.aborted=function(){return ve},this.abort=function(){ve=!0,Ee.abort(),Ue.meta.aborted=!0,j(R.complete)&&R.complete(Ue),oe=""},this.guessLineEndings=function($e,Xe){$e=$e.substring(0,1024*1024);var rt=new RegExp(b(Xe)+"([^]*?)"+b(Xe),"gm");$e=$e.replace(rt,"");var Ze=$e.split("\r"),ae=$e.split(`
433
433
  `),ee=ae.length>1&&ae[0].length<Ze[0].length;if(Ze.length===1||ee)return`
@@ -659,7 +659,7 @@ actual: `+e._bytesWritten),FG.prototype._finish.call(e)}});var fme=I((nrn,zit)=>
659
659
  Unsupported type: `+e.type,"ENOTSUP");e._finish()})};Zc.prototype._stat=function(e){var t=this,r=t.props,n=r.follow?"stat":"lstat",i=t._proxy||t;e?o(null,e):Xc[n](t._path,o);function o(s,a){if(t.filter&&!t.filter.call(i,i,a)){t._aborted=!0,t.emit("end"),t.emit("close");return}if(s||!a)return pme(t);t._old=a;var c=Vit(a);if(c!==t.type||t.type==="File"&&a.nlink>1)return oCr(t._path,function(u){if(u)return t.error(u);t._old=null,pme(t)});pme(t)}};function pme(e){sCr(OB.dirname(e._path),Zc.dirmode,function(t,r){return t?e.error(t):(e._madeDir=r,e._create())})}function Kit(e,t,r,n,i){var o=t.mode,s=t.follow||e.type!=="SymbolicLink"?"chmod":"lchmod";if(!Xc[s]||typeof o!="number")return i();var a=r.mode&parseInt("0777",8);if(o=o&parseInt("0777",8),o===a)return i();Xc[s](n,o,i)}function Xit(e,t,r,n,i){if(process.platform==="win32"||!process.getuid||process.getuid()!==0||typeof t.uid!="number"&&typeof t.gid!="number"||r.uid===t.uid&&r.gid===t.gid)return i();var o=e.props.follow||e.type!=="SymbolicLink"?"chown":"lchown";if(!Xc[o])return i();typeof t.uid!="number"&&(t.uid=r.uid),typeof t.gid!="number"&&(t.gid=r.gid),Xc[o](n,t.uid,t.gid,i)}function Zit(e,t,r,n,i){if(!Xc.utimes||process.platform==="win32")return i();var o=t.follow||e.type!=="SymbolicLink"?"utimes":"lutimes";if(o==="lutimes"&&!Xc[o]&&(o="utimes"),!Xc[o])return i();var s=r.atime,a=r.mtime,c=t.atime,u=t.mtime;if(c===void 0&&(c=s),u===void 0&&(u=a),Jit(c)||(c=new Date(c)),Jit(u)||(c=new Date(u)),c.getTime()===s.getTime()&&u.getTime()===a.getTime())return i();Xc[o](n,c,u,i)}Zc.prototype._finish=function(){var e=this;if(e._finishing)return;e._finishing=!0;var t=0,r=null,n=!1;if(e._old)e._old.atime=new Date(0),e._old.mtime=new Date(0),o(e._old);else{var i=e.props.follow?"stat":"lstat";Xc[i](e._path,function(a,c){if(a)if(a.code==="ENOENT"&&(e.type==="Link"||e.type==="SymbolicLink")&&process.platform==="win32"){e.ready=!0,e.emit("ready"),e.emit("end"),e.emit("close"),e.end=e._finish=function(){};return}else return e.error(a);o(e._old=c)})}return;function o(a){t+=3,Kit(e,e.props,a,e._path,s("chmod")),Xit(e,e.props,a,e._path,s("chown")),Zit(e,e.props,a,e._path,s("utimes"))}function s(a){return function(c){if(r)return;if(c)return c.fstream_finish_call=a,e.error(r=c);if(--t>0||n)return;if(n=!0,e._madeDir)eot(e,e._path,u);else return u();function u(d){if(d)return d.fstream_finish_call="setupMadeDir",e.error(d);e.emit("end"),e.emit("close")}}}};function eot(e,t,r){var n=e._madeDir,i=OB.dirname(t);dCr(e,i,function(o){if(o)return r(o);if(i===n)return r();eot(e,i,r)})}function dCr(e,t,r){var n={};Object.keys(e.props).forEach(function(a){n[a]=e.props[a],a==="mode"&&e.type!=="Directory"&&(n[a]=n[a]|parseInt("0111",8))});var i=3,o=null;Xc.stat(t,function(a,c){if(a)return r(o=a);Kit(e,n,c,t,s),Xit(e,n,c,t,s),Zit(e,n,c,t,s)});function s(a){if(!o){if(a)return r(o=a);if(--i===0)return r()}}}Zc.prototype.pipe=function(){this.error("Can't pipe from writable stream")};Zc.prototype.add=function(){this.error("Can't add to non-Directory type")};Zc.prototype.write=function(){return!0};function fCr(e){return Object.prototype.toString.call(e)}function Jit(e){return typeof e=="object"&&fCr(e)==="[object Date]"}});var hme=I(Mr=>{Mr.Abstract=RG();Mr.Reader=AE();Mr.Writer=Yw();Mr.File={Reader:Khe(),Writer:ume()};Mr.Dir={Reader:Whe(),Writer:cme()};Mr.Link={Reader:Ghe(),Writer:lme()};Mr.Proxy={Reader:Zhe(),Writer:fme()};Mr.Reader.Dir=Mr.DirReader=Mr.Dir.Reader;Mr.Reader.File=Mr.FileReader=Mr.File.Reader;Mr.Reader.Link=Mr.LinkReader=Mr.Link.Reader;Mr.Reader.Proxy=Mr.ProxyReader=Mr.Proxy.Reader;Mr.Writer.Dir=Mr.DirWriter=Mr.Dir.Writer;Mr.Writer.File=Mr.FileWriter=Mr.File.Writer;Mr.Writer.Link=Mr.LinkWriter=Mr.Link.Writer;Mr.Writer.Proxy=Mr.ProxyWriter=Mr.Proxy.Writer;Mr.collect=BG()});var not=I((srn,rot)=>{rot.exports=yCr;var pCr=DG(),hCr=hme().Writer,mme=z("path"),mCr=z("stream"),ACr=Hhe(),gCr=Jm();function yCr(e){e.path=mme.resolve(mme.normalize(e.path));var t=new pCr(e),r=new mCr.Writable({objectMode:!0});r._write=function(i,o,s){if(i.type=="Directory")return s();var a=mme.join(e.path,i.path);if(a.indexOf(e.path)!=0)return s();let c=e.getWriter?e.getWriter({path:a}):hCr({path:a});i.pipe(c).on("error",s).on("close",s)};var n=ACr(t,r);return t.once("crx-header",function(i){n.crxHeader=i}),t.pipe(r).on("finish",function(){n.emit("close")}),n.promise=function(){return new gCr(function(i,o){n.on("close",i),n.on("error",o)})},n}});var iot=I((arn,LG)=>{var _o=(function(e){"use strict";var t=1e7,r=7,n=9007199254740992,i=p(n),o="0123456789abcdefghijklmnopqrstuvwxyz",s=typeof BigInt=="function";function a(v,x,P,H){return typeof v>"u"?a[0]:typeof x<"u"?+x==10&&!P?ae(v):Ve(v,x,P,H):ae(v)}function c(v,x){this.value=v,this.sign=x,this.isSmall=!1}c.prototype=Object.create(a.prototype);function u(v){this.value=v,this.sign=v<0,this.isSmall=!0}u.prototype=Object.create(a.prototype);function d(v){this.value=v}d.prototype=Object.create(a.prototype);function f(v){return-n<v&&v<n}function p(v){return v<1e7?[v]:v<1e14?[v%1e7,Math.floor(v/1e7)]:[v%1e7,Math.floor(v/1e7)%1e7,Math.floor(v/1e14)]}function h(v){m(v);var x=v.length;if(x<4&&V(v,i)<0)switch(x){case 0:return 0;case 1:return v[0];case 2:return v[0]+v[1]*t;default:return v[0]+(v[1]+v[2]*t)*t}return v}function m(v){for(var x=v.length;v[--x]===0;);v.length=x+1}function A(v){for(var x=new Array(v),P=-1;++P<v;)x[P]=0;return x}function g(v){return v>0?Math.floor(v):Math.ceil(v)}function y(v,x){var P=v.length,H=x.length,ie=new Array(P),re=0,se=t,ce,ge;for(ge=0;ge<H;ge++)ce=v[ge]+x[ge]+re,re=ce>=se?1:0,ie[ge]=ce-re*se;for(;ge<P;)ce=v[ge]+re,re=ce===se?1:0,ie[ge++]=ce-re*se;return re>0&&ie.push(re),ie}function b(v,x){return v.length>=x.length?y(v,x):y(x,v)}function E(v,x){var P=v.length,H=new Array(P),ie=t,re,se;for(se=0;se<P;se++)re=v[se]-ie+x,x=Math.floor(re/ie),H[se]=re-x*ie,x+=1;for(;x>0;)H[se++]=x%ie,x=Math.floor(x/ie);return H}c.prototype.add=function(v){var x=ae(v);if(this.sign!==x.sign)return this.subtract(x.negate());var P=this.value,H=x.value;return x.isSmall?new c(E(P,Math.abs(H)),this.sign):new c(b(P,H),this.sign)},c.prototype.plus=c.prototype.add,u.prototype.add=function(v){var x=ae(v),P=this.value;if(P<0!==x.sign)return this.subtract(x.negate());var H=x.value;if(x.isSmall){if(f(P+H))return new u(P+H);H=p(Math.abs(H))}return new c(E(H,Math.abs(P)),P<0)},u.prototype.plus=u.prototype.add,d.prototype.add=function(v){return new d(this.value+ae(v).value)},d.prototype.plus=d.prototype.add;function C(v,x){var P=v.length,H=x.length,ie=new Array(P),re=0,se=t,ce,ge;for(ce=0;ce<H;ce++)ge=v[ce]-re-x[ce],ge<0?(ge+=se,re=1):re=0,ie[ce]=ge;for(ce=H;ce<P;ce++){if(ge=v[ce]-re,ge<0)ge+=se;else{ie[ce++]=ge;break}ie[ce]=ge}for(;ce<P;ce++)ie[ce]=v[ce];return m(ie),ie}function w(v,x,P){var H;return V(v,x)>=0?H=C(v,x):(H=C(x,v),P=!P),H=h(H),typeof H=="number"?(P&&(H=-H),new u(H)):new c(H,P)}function T(v,x,P){var H=v.length,ie=new Array(H),re=-x,se=t,ce,ge;for(ce=0;ce<H;ce++)ge=v[ce]+re,re=Math.floor(ge/se),ge%=se,ie[ce]=ge<0?ge+se:ge;return ie=h(ie),typeof ie=="number"?(P&&(ie=-ie),new u(ie)):new c(ie,P)}c.prototype.subtract=function(v){var x=ae(v);if(this.sign!==x.sign)return this.add(x.negate());var P=this.value,H=x.value;return x.isSmall?T(P,Math.abs(H),this.sign):w(P,H,this.sign)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(v){var x=ae(v),P=this.value;if(P<0!==x.sign)return this.add(x.negate());var H=x.value;return x.isSmall?new u(P-H):T(H,Math.abs(P),P>=0)},u.prototype.minus=u.prototype.subtract,d.prototype.subtract=function(v){return new d(this.value-ae(v).value)},d.prototype.minus=d.prototype.subtract,c.prototype.negate=function(){return new c(this.value,!this.sign)},u.prototype.negate=function(){var v=this.sign,x=new u(-this.value);return x.sign=!v,x},d.prototype.negate=function(){return new d(-this.value)},c.prototype.abs=function(){return new c(this.value,!1)},u.prototype.abs=function(){return new u(Math.abs(this.value))},d.prototype.abs=function(){return new d(this.value>=0?this.value:-this.value)};function D(v,x){var P=v.length,H=x.length,ie=P+H,re=A(ie),se=t,ce,ge,Pe,Je,dt;for(Pe=0;Pe<P;++Pe){Je=v[Pe];for(var Zt=0;Zt<H;++Zt)dt=x[Zt],ce=Je*dt+re[Pe+Zt],ge=Math.floor(ce/se),re[Pe+Zt]=ce-ge*se,re[Pe+Zt+1]+=ge}return m(re),re}function k(v,x){var P=v.length,H=new Array(P),ie=t,re=0,se,ce;for(ce=0;ce<P;ce++)se=v[ce]*x+re,re=Math.floor(se/ie),H[ce]=se-re*ie;for(;re>0;)H[ce++]=re%ie,re=Math.floor(re/ie);return H}function F(v,x){for(var P=[];x-- >0;)P.push(0);return P.concat(v)}function G(v,x){var P=Math.max(v.length,x.length);if(P<=30)return D(v,x);P=Math.ceil(P/2);var H=v.slice(P),ie=v.slice(0,P),re=x.slice(P),se=x.slice(0,P),ce=G(ie,se),ge=G(H,re),Pe=G(b(ie,H),b(se,re)),Je=b(b(ce,F(C(C(Pe,ce),ge),P)),F(ge,2*P));return m(Je),Je}function j(v,x){return-.012*v-.012*x+15e-6*v*x>0}c.prototype.multiply=function(v){var x=ae(v),P=this.value,H=x.value,ie=this.sign!==x.sign,re;if(x.isSmall){if(H===0)return a[0];if(H===1)return this;if(H===-1)return this.negate();if(re=Math.abs(H),re<t)return new c(k(P,re),ie);H=p(re)}return j(P.length,H.length)?new c(G(P,H),ie):new c(D(P,H),ie)},c.prototype.times=c.prototype.multiply;function R(v,x,P){return v<t?new c(k(x,v),P):new c(D(x,p(v)),P)}u.prototype._multiplyBySmall=function(v){return f(v.value*this.value)?new u(v.value*this.value):R(Math.abs(v.value),p(Math.abs(this.value)),this.sign!==v.sign)},c.prototype._multiplyBySmall=function(v){return v.value===0?a[0]:v.value===1?this:v.value===-1?this.negate():R(Math.abs(v.value),this.value,this.sign!==v.sign)},u.prototype.multiply=function(v){return ae(v)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,d.prototype.multiply=function(v){return new d(this.value*ae(v).value)},d.prototype.times=d.prototype.multiply;function O(v){var x=v.length,P=A(x+x),H=t,ie,re,se,ce,ge;for(se=0;se<x;se++){ce=v[se],re=0-ce*ce;for(var Pe=se;Pe<x;Pe++)ge=v[Pe],ie=2*(ce*ge)+P[se+Pe]+re,re=Math.floor(ie/H),P[se+Pe]=ie-re*H;P[se+x]=re}return m(P),P}c.prototype.square=function(){return new c(O(this.value),!1)},u.prototype.square=function(){var v=this.value*this.value;return f(v)?new u(v):new c(O(p(Math.abs(this.value))),!1)},d.prototype.square=function(v){return new d(this.value*this.value)};function M(v,x){var P=v.length,H=x.length,ie=t,re=A(x.length),se=x[H-1],ce=Math.ceil(ie/(2*se)),ge=k(v,ce),Pe=k(x,ce),Je,dt,Zt,_n,ci,lo,ul;for(ge.length<=P&&ge.push(0),Pe.push(0),se=Pe[H-1],dt=P-H;dt>=0;dt--){for(Je=ie-1,ge[dt+H]!==se&&(Je=Math.floor((ge[dt+H]*ie+ge[dt+H-1])/se)),Zt=0,_n=0,lo=Pe.length,ci=0;ci<lo;ci++)Zt+=Je*Pe[ci],ul=Math.floor(Zt/ie),_n+=ge[dt+ci]-(Zt-ul*ie),Zt=ul,_n<0?(ge[dt+ci]=_n+ie,_n=-1):(ge[dt+ci]=_n,_n=0);for(;_n!==0;){for(Je-=1,Zt=0,ci=0;ci<lo;ci++)Zt+=ge[dt+ci]-ie+Pe[ci],Zt<0?(ge[dt+ci]=Zt+ie,Zt=0):(ge[dt+ci]=Zt,Zt=1);_n+=Zt}re[dt]=Je}return ge=B(ge,ce)[0],[h(re),h(ge)]}function W(v,x){for(var P=v.length,H=x.length,ie=[],re=[],se=t,ce,ge,Pe,Je,dt;P;){if(re.unshift(v[--P]),m(re),V(re,x)<0){ie.push(0);continue}ge=re.length,Pe=re[ge-1]*se+re[ge-2],Je=x[H-1]*se+x[H-2],ge>H&&(Pe=(Pe+1)*se),ce=Math.ceil(Pe/Je);do{if(dt=k(x,ce),V(dt,re)<=0)break;ce--}while(ce);ie.push(ce),re=C(re,dt)}return ie.reverse(),[h(ie),h(re)]}function B(v,x){var P=v.length,H=A(P),ie=t,re,se,ce,ge;for(ce=0,re=P-1;re>=0;--re)ge=ce*ie+v[re],se=g(ge/x),ce=ge-se*x,H[re]=se|0;return[H,ce|0]}function Y(v,x){var P,H=ae(x);if(s)return[new d(v.value/H.value),new d(v.value%H.value)];var ie=v.value,re=H.value,se;if(re===0)throw new Error("Cannot divide by zero");if(v.isSmall)return H.isSmall?[new u(g(ie/re)),new u(ie%re)]:[a[0],v];if(H.isSmall){if(re===1)return[v,a[0]];if(re==-1)return[v.negate(),a[0]];var ce=Math.abs(re);if(ce<t){P=B(ie,ce),se=h(P[0]);var ge=P[1];return v.sign&&(ge=-ge),typeof se=="number"?(v.sign!==H.sign&&(se=-se),[new u(se),new u(ge)]):[new c(se,v.sign!==H.sign),new u(ge)]}re=p(ce)}var Pe=V(ie,re);if(Pe===-1)return[a[0],v];if(Pe===0)return[a[v.sign===H.sign?1:-1],a[0]];ie.length+re.length<=200?P=M(ie,re):P=W(ie,re),se=P[0];var Je=v.sign!==H.sign,dt=P[1],Zt=v.sign;return typeof se=="number"?(Je&&(se=-se),se=new u(se)):se=new c(se,Je),typeof dt=="number"?(Zt&&(dt=-dt),dt=new u(dt)):dt=new c(dt,Zt),[se,dt]}c.prototype.divmod=function(v){var x=Y(this,v);return{quotient:x[0],remainder:x[1]}},d.prototype.divmod=u.prototype.divmod=c.prototype.divmod,c.prototype.divide=function(v){return Y(this,v)[0]},d.prototype.over=d.prototype.divide=function(v){return new d(this.value/ae(v).value)},u.prototype.over=u.prototype.divide=c.prototype.over=c.prototype.divide,c.prototype.mod=function(v){return Y(this,v)[1]},d.prototype.mod=d.prototype.remainder=function(v){return new d(this.value%ae(v).value)},u.prototype.remainder=u.prototype.mod=c.prototype.remainder=c.prototype.mod,c.prototype.pow=function(v){var x=ae(v),P=this.value,H=x.value,ie,re,se;if(H===0)return a[1];if(P===0)return a[0];if(P===1)return a[1];if(P===-1)return x.isEven()?a[1]:a[-1];if(x.sign)return a[0];if(!x.isSmall)throw new Error("The exponent "+x.toString()+" is too large.");if(this.isSmall&&f(ie=Math.pow(P,H)))return new u(g(ie));for(re=this,se=a[1];H&!0&&(se=se.times(re),--H),H!==0;)H/=2,re=re.square();return se},u.prototype.pow=c.prototype.pow,d.prototype.pow=function(v){var x=ae(v),P=this.value,H=x.value,ie=BigInt(0),re=BigInt(1),se=BigInt(2);if(H===ie)return a[1];if(P===ie)return a[0];if(P===re)return a[1];if(P===BigInt(-1))return x.isEven()?a[1]:a[-1];if(x.isNegative())return new d(ie);for(var ce=this,ge=a[1];(H&re)===re&&(ge=ge.times(ce),--H),H!==ie;)H/=se,ce=ce.square();return ge},c.prototype.modPow=function(v,x){if(v=ae(v),x=ae(x),x.isZero())throw new Error("Cannot take modPow with modulus 0");var P=a[1],H=this.mod(x);for(v.isNegative()&&(v=v.multiply(a[-1]),H=H.modInv(x));v.isPositive();){if(H.isZero())return a[0];v.isOdd()&&(P=P.multiply(H).mod(x)),v=v.divide(2),H=H.square().mod(x)}return P},d.prototype.modPow=u.prototype.modPow=c.prototype.modPow;function V(v,x){if(v.length!==x.length)return v.length>x.length?1:-1;for(var P=v.length-1;P>=0;P--)if(v[P]!==x[P])return v[P]>x[P]?1:-1;return 0}c.prototype.compareAbs=function(v){var x=ae(v),P=this.value,H=x.value;return x.isSmall?1:V(P,H)},u.prototype.compareAbs=function(v){var x=ae(v),P=Math.abs(this.value),H=x.value;return x.isSmall?(H=Math.abs(H),P===H?0:P>H?1:-1):-1},d.prototype.compareAbs=function(v){var x=this.value,P=ae(v).value;return x=x>=0?x:-x,P=P>=0?P:-P,x===P?0:x>P?1:-1},c.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),P=this.value,H=x.value;return this.sign!==x.sign?x.sign?1:-1:x.isSmall?this.sign?-1:1:V(P,H)*(this.sign?-1:1)},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),P=this.value,H=x.value;return x.isSmall?P==H?0:P>H?1:-1:P<0!==x.sign?P<0?-1:1:P<0?1:-1},u.prototype.compareTo=u.prototype.compare,d.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=this.value,P=ae(v).value;return x===P?0:x>P?1:-1},d.prototype.compareTo=d.prototype.compare,c.prototype.equals=function(v){return this.compare(v)===0},d.prototype.eq=d.prototype.equals=u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals,c.prototype.notEquals=function(v){return this.compare(v)!==0},d.prototype.neq=d.prototype.notEquals=u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals,c.prototype.greater=function(v){return this.compare(v)>0},d.prototype.gt=d.prototype.greater=u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater,c.prototype.lesser=function(v){return this.compare(v)<0},d.prototype.lt=d.prototype.lesser=u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser,c.prototype.greaterOrEquals=function(v){return this.compare(v)>=0},d.prototype.geq=d.prototype.greaterOrEquals=u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals,c.prototype.lesserOrEquals=function(v){return this.compare(v)<=0},d.prototype.leq=d.prototype.lesserOrEquals=u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals,c.prototype.isEven=function(){return(this.value[0]&1)===0},u.prototype.isEven=function(){return(this.value&1)===0},d.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},c.prototype.isOdd=function(){return(this.value[0]&1)===1},u.prototype.isOdd=function(){return(this.value&1)===1},d.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},c.prototype.isPositive=function(){return!this.sign},u.prototype.isPositive=function(){return this.value>0},d.prototype.isPositive=u.prototype.isPositive,c.prototype.isNegative=function(){return this.sign},u.prototype.isNegative=function(){return this.value<0},d.prototype.isNegative=u.prototype.isNegative,c.prototype.isUnit=function(){return!1},u.prototype.isUnit=function(){return Math.abs(this.value)===1},d.prototype.isUnit=function(){return this.abs().value===BigInt(1)},c.prototype.isZero=function(){return!1},u.prototype.isZero=function(){return this.value===0},d.prototype.isZero=function(){return this.value===BigInt(0)},c.prototype.isDivisibleBy=function(v){var x=ae(v);return x.isZero()?!1:x.isUnit()?!0:x.compareAbs(2)===0?this.isEven():this.mod(x).isZero()},d.prototype.isDivisibleBy=u.prototype.isDivisibleBy=c.prototype.isDivisibleBy;function X(v){var x=v.abs();if(x.isUnit())return!1;if(x.equals(2)||x.equals(3)||x.equals(5))return!0;if(x.isEven()||x.isDivisibleBy(3)||x.isDivisibleBy(5))return!1;if(x.lesser(49))return!0}function oe(v,x){for(var P=v.prev(),H=P,ie=0,re,se,ce,ge;H.isEven();)H=H.divide(2),ie++;e:for(ce=0;ce<x.length;ce++)if(!v.lesser(x[ce])&&(ge=_o(x[ce]).modPow(H,v),!(ge.isUnit()||ge.equals(P)))){for(re=ie-1;re!=0;re--){if(ge=ge.square().mod(v),ge.isUnit())return!1;if(ge.equals(P))continue e}return!1}return!0}c.prototype.isPrime=function(v){var x=X(this);if(x!==e)return x;var P=this.abs(),H=P.bitLength();if(H<=64)return oe(P,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var ie=Math.log(2)*H.toJSNumber(),re=Math.ceil(v===!0?2*Math.pow(ie,2):ie),se=[],ce=0;ce<re;ce++)se.push(_o(ce+2));return oe(P,se)},d.prototype.isPrime=u.prototype.isPrime=c.prototype.isPrime,c.prototype.isProbablePrime=function(v,x){var P=X(this);if(P!==e)return P;for(var H=this.abs(),ie=v===e?5:v,re=[],se=0;se<ie;se++)re.push(_o.randBetween(2,H.minus(2),x));return oe(H,re)},d.prototype.isProbablePrime=u.prototype.isProbablePrime=c.prototype.isProbablePrime,c.prototype.modInv=function(v){for(var x=_o.zero,P=_o.one,H=ae(v),ie=this.abs(),re,se,ce;!ie.isZero();)re=H.divide(ie),se=x,ce=H,x=P,H=ie,P=se.subtract(re.multiply(P)),ie=ce.subtract(re.multiply(ie));if(!H.isUnit())throw new Error(this.toString()+" and "+v.toString()+" are not co-prime");return x.compare(0)===-1&&(x=x.add(v)),this.isNegative()?x.negate():x},d.prototype.modInv=u.prototype.modInv=c.prototype.modInv,c.prototype.next=function(){var v=this.value;return this.sign?T(v,1,this.sign):new c(E(v,1),this.sign)},u.prototype.next=function(){var v=this.value;return v+1<n?new u(v+1):new c(i,!1)},d.prototype.next=function(){return new d(this.value+BigInt(1))},c.prototype.prev=function(){var v=this.value;return this.sign?new c(E(v,1),!0):T(v,1,this.sign)},u.prototype.prev=function(){var v=this.value;return v-1>-n?new u(v-1):new c(i,!0)},d.prototype.prev=function(){return new d(this.value-BigInt(1))};for(var Ee=[1];2*Ee[Ee.length-1]<=t;)Ee.push(2*Ee[Ee.length-1]);var ke=Ee.length,ve=Ee[ke-1];function yt(v){return Math.abs(v)<=t}c.prototype.shiftLeft=function(v){var x=ae(v).toJSNumber();if(!yt(x))throw new Error(String(x)+" is too large for shifting.");if(x<0)return this.shiftRight(-x);var P=this;if(P.isZero())return P;for(;x>=ke;)P=P.multiply(ve),x-=ke-1;return P.multiply(Ee[x])},d.prototype.shiftLeft=u.prototype.shiftLeft=c.prototype.shiftLeft,c.prototype.shiftRight=function(v){var x,P=ae(v).toJSNumber();if(!yt(P))throw new Error(String(P)+" is too large for shifting.");if(P<0)return this.shiftLeft(-P);for(var H=this;P>=ke;){if(H.isZero()||H.isNegative()&&H.isUnit())return H;x=Y(H,ve),H=x[1].isNegative()?x[0].prev():x[0],P-=ke-1}return x=Y(H,Ee[P]),x[1].isNegative()?x[0].prev():x[0]},d.prototype.shiftRight=u.prototype.shiftRight=c.prototype.shiftRight;function Ne(v,x,P){x=ae(x);for(var H=v.isNegative(),ie=x.isNegative(),re=H?v.not():v,se=ie?x.not():x,ce=0,ge=0,Pe=null,Je=null,dt=[];!re.isZero()||!se.isZero();)Pe=Y(re,ve),ce=Pe[1].toJSNumber(),H&&(ce=ve-1-ce),Je=Y(se,ve),ge=Je[1].toJSNumber(),ie&&(ge=ve-1-ge),re=Pe[0],se=Je[0],dt.push(P(ce,ge));for(var Zt=P(H?1:0,ie?1:0)!==0?_o(-1):_o(0),_n=dt.length-1;_n>=0;_n-=1)Zt=Zt.multiply(ve).add(_o(dt[_n]));return Zt}c.prototype.not=function(){return this.negate().prev()},d.prototype.not=u.prototype.not=c.prototype.not,c.prototype.and=function(v){return Ne(this,v,function(x,P){return x&P})},d.prototype.and=u.prototype.and=c.prototype.and,c.prototype.or=function(v){return Ne(this,v,function(x,P){return x|P})},d.prototype.or=u.prototype.or=c.prototype.or,c.prototype.xor=function(v){return Ne(this,v,function(x,P){return x^P})},d.prototype.xor=u.prototype.xor=c.prototype.xor;var Ue=1<<30,Ae=(t&-t)*(t&-t)|Ue;function le(v){var x=v.value,P=typeof x=="number"?x|Ue:typeof x=="bigint"?x|BigInt(Ue):x[0]+x[1]*t|Ae;return P&-P}function we(v,x){if(x.compareTo(v)<=0){var P=we(v,x.square(x)),H=P.p,ie=P.e,re=H.multiply(x);return re.compareTo(v)<=0?{p:re,e:ie*2+1}:{p:H,e:ie*2}}return{p:_o(1),e:0}}c.prototype.bitLength=function(){var v=this;return v.compareTo(_o(0))<0&&(v=v.negate().subtract(_o(1))),v.compareTo(_o(0))===0?_o(0):_o(we(v,_o(2)).e).add(_o(1))},d.prototype.bitLength=u.prototype.bitLength=c.prototype.bitLength;function Le(v,x){return v=ae(v),x=ae(x),v.greater(x)?v:x}function ze(v,x){return v=ae(v),x=ae(x),v.lesser(x)?v:x}function Yt(v,x){if(v=ae(v).abs(),x=ae(x).abs(),v.equals(x))return v;if(v.isZero())return x;if(x.isZero())return v;for(var P=a[1],H,ie;v.isEven()&&x.isEven();)H=ze(le(v),le(x)),v=v.divide(H),x=x.divide(H),P=P.multiply(H);for(;v.isEven();)v=v.divide(le(v));do{for(;x.isEven();)x=x.divide(le(x));v.greater(x)&&(ie=x,x=v,v=ie),x=x.subtract(v)}while(!x.isZero());return P.isUnit()?v:v.multiply(P)}function Mt(v,x){return v=ae(v).abs(),x=ae(x).abs(),v.divide(Yt(v,x)).multiply(x)}function pr(v,x,P){v=ae(v),x=ae(x);var H=P||Math.random,ie=ze(v,x),re=Le(v,x),se=re.subtract(ie).add(1);if(se.isSmall)return ie.add(Math.floor(H()*se));for(var ce=$e(se,t).value,ge=[],Pe=!0,Je=0;Je<ce.length;Je++){var dt=Pe?ce[Je]+(Je+1<ce.length?ce[Je+1]/t:0):t,Zt=g(H()*dt);ge.push(Zt),Zt<ce[Je]&&(Pe=!1)}return ie.add(a.fromArray(ge,t,!1))}var Ve=function(v,x,P,H){P=P||o,v=String(v),H||(v=v.toLowerCase(),P=P.toLowerCase());var ie=v.length,re,se=Math.abs(x),ce={};for(re=0;re<P.length;re++)ce[P[re]]=re;for(re=0;re<ie;re++){var ge=v[re];if(ge!=="-"&&ge in ce&&ce[ge]>=se){if(ge==="1"&&se===1)continue;throw new Error(ge+" is not a valid digit in base "+x+".")}}x=ae(x);var Pe=[],Je=v[0]==="-";for(re=Je?1:0;re<v.length;re++){var ge=v[re];if(ge in ce)Pe.push(ae(ce[ge]));else if(ge==="<"){var dt=re;do re++;while(v[re]!==">"&&re<v.length);Pe.push(ae(v.slice(dt+1,re)))}else throw new Error(ge+" is not a valid character")}return je(Pe,x,Je)};function je(v,x,P){var H=a[0],ie=a[1],re;for(re=v.length-1;re>=0;re--)H=H.add(v[re].times(ie)),ie=ie.times(x);return P?H.negate():H}function wt(v,x){return x=x||o,v<x.length?x[v]:"<"+v+">"}function $e(v,x){if(x=_o(x),x.isZero()){if(v.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(x.equals(-1)){if(v.isZero())return{value:[0],isNegative:!1};if(v.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-v.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var P=Array.apply(null,Array(v.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return P.unshift([1]),{value:[].concat.apply([],P),isNegative:!1}}var H=!1;if(v.isNegative()&&x.isPositive()&&(H=!0,v=v.abs()),x.isUnit())return v.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(v.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:H};for(var ie=[],re=v,se;re.isNegative()||re.compareAbs(x)>=0;){se=re.divmod(x),re=se.quotient;var ce=se.remainder;ce.isNegative()&&(ce=x.minus(ce).abs(),re=re.next()),ie.push(ce.toJSNumber())}return ie.push(re.toJSNumber()),{value:ie.reverse(),isNegative:H}}function Xe(v,x,P){var H=$e(v,x);return(H.isNegative?"-":"")+H.value.map(function(ie){return wt(ie,P)}).join("")}c.prototype.toArray=function(v){return $e(this,v)},u.prototype.toArray=function(v){return $e(this,v)},d.prototype.toArray=function(v){return $e(this,v)},c.prototype.toString=function(v,x){if(v===e&&(v=10),v!==10||x)return Xe(this,v,x);for(var P=this.value,H=P.length,ie=String(P[--H]),re="0000000",se;--H>=0;)se=String(P[H]),ie+=re.slice(se.length)+se;var ce=this.sign?"-":"";return ce+ie},u.prototype.toString=function(v,x){return v===e&&(v=10),v!=10||x?Xe(this,v,x):String(this.value)},d.prototype.toString=u.prototype.toString,d.prototype.toJSON=c.prototype.toJSON=u.prototype.toJSON=function(){return this.toString()},c.prototype.valueOf=function(){return parseInt(this.toString(),10)},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=function(){return this.value},u.prototype.toJSNumber=u.prototype.valueOf,d.prototype.valueOf=d.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};function rt(v){if(f(+v)){var x=+v;if(x===g(x))return s?new d(BigInt(x)):new u(x);throw new Error("Invalid integer: "+v)}var P=v[0]==="-";P&&(v=v.slice(1));var H=v.split(/e/i);if(H.length>2)throw new Error("Invalid integer: "+H.join("e"));if(H.length===2){var ie=H[1];if(ie[0]==="+"&&(ie=ie.slice(1)),ie=+ie,ie!==g(ie)||!f(ie))throw new Error("Invalid integer: "+ie+" is not a valid exponent.");var re=H[0],se=re.indexOf(".");if(se>=0&&(ie-=re.length-se-1,re=re.slice(0,se)+re.slice(se+1)),ie<0)throw new Error("Cannot include negative exponent part for integers");re+=new Array(ie+1).join("0"),v=re}var ce=/^([0-9][0-9]*)$/.test(v);if(!ce)throw new Error("Invalid integer: "+v);if(s)return new d(BigInt(P?"-"+v:v));for(var ge=[],Pe=v.length,Je=r,dt=Pe-Je;Pe>0;)ge.push(+v.slice(dt,Pe)),dt-=Je,dt<0&&(dt=0),Pe-=Je;return m(ge),new c(ge,P)}function Ze(v){if(s)return new d(BigInt(v));if(f(v)){if(v!==g(v))throw new Error(v+" is not an integer.");return new u(v)}return rt(v.toString())}function ae(v){return typeof v=="number"?Ze(v):typeof v=="string"?rt(v):typeof v=="bigint"?new d(v):v}for(var ee=0;ee<1e3;ee++)a[ee]=ae(ee),ee>0&&(a[-ee]=ae(-ee));return a.one=a[1],a.zero=a[0],a.minusOne=a[-1],a.max=Le,a.min=ze,a.gcd=Yt,a.lcm=Mt,a.isInstance=function(v){return v instanceof c||v instanceof u||v instanceof d},a.randBetween=pr,a.fromArray=function(v,x,P){return je(v.map(ae),ae(x||10),P)},a})();typeof LG<"u"&&LG.hasOwnProperty("exports")&&(LG.exports=_o);typeof define=="function"&&define.amd&&define(function(){return _o})});var aot=I((crn,sot)=>{var Xm=iot(),QG=z("stream");(!QG.Writable||!QG.Writable.prototype.destroy)&&(QG=Ia());var PG;function ECr(){var e=3988292384,t,r,n;for(PG=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=t&1?e^t>>>1:t=t>>>1;PG[r]=t>>>0}}function oot(e,t){return PG||ECr(),e.charCodeAt&&(e=e.charCodeAt(0)),Xm(t).shiftRight(8).and(16777215).xor(PG[Xm(t).xor(e).and(255)]).value}function Hw(){if(!(this instanceof Hw))return new Hw;this.key0=305419896,this.key1=591751049,this.key2=878082192}Hw.prototype.update=function(e){this.key0=oot(e,this.key0),this.key1=Xm(this.key0).and(255).and(4294967295).add(this.key1),this.key1=Xm(this.key1).multiply(134775813).add(1).and(4294967295).value,this.key2=oot(Xm(this.key1).shiftRight(24).and(255),this.key2)};Hw.prototype.decryptByte=function(e){var t=Xm(this.key2).or(2);return e=e^Xm(t).multiply(Xm(t^1)).shiftRight(8).and(255),this.update(e),e};Hw.prototype.stream=function(){var e=QG.Transform(),t=this;return e._transform=function(r,n,i){for(var o=0;o<r.length;o++)r[o]=t.decryptByte(r[o]);this.push(r),i()},e};sot.exports=Hw});var lot=I((lrn,cot)=>{var bCr=Jm(),ICr=aot(),CCr=CG(),FB=z("stream"),_Cr=IB(),wCr=z("zlib"),vCr=vG(),SCr=Mw(),DCr=SG();(!FB.Writable||!FB.Writable.prototype.destroy)&&(FB=Ia());cot.exports=function(t,r,n,i){var o=CCr(),s=FB.PassThrough(),a=t.stream(r);return a.pipe(o).on("error",function(c){s.emit("error",c)}),s.vars=o.pull(30).then(function(c){var u=_Cr.parse(c).word32lu("signature").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;return u.lastModifiedDateTime=DCr(u.lastModifiedDate,u.lastModifiedTime),o.pull(u.fileNameLength).then(function(d){return u.fileName=d.toString("utf8"),o.pull(u.extraFieldLength)}).then(function(d){var f;return u.extra=vCr(d,u),i&&i.compressedSize&&(u=i),u.flags&1&&(f=o.pull(12).then(function(p){if(!n)throw new Error("MISSING_PASSWORD");var h=ICr();String(n).split("").forEach(function(g){h.update(g)});for(var m=0;m<p.length;m++)p[m]=h.decryptByte(p[m]);u.decrypt=h,u.compressedSize-=12;var A=u.flags&8?u.lastModifiedTime>>8&255:u.crc32>>24&255;if(p[11]!==A)throw new Error("BAD_PASSWORD");return u})),bCr.resolve(f).then(function(){return s.emit("vars",u),u})})}),s.vars.then(function(c){var u=!(c.flags&8)||c.compressedSize>0,d,f=c.compressionMethod?wCr.createInflateRaw():FB.PassThrough();u?(s.size=c.uncompressedSize,d=c.compressedSize):(d=SCr.alloc(4),d.writeUInt32LE(134695760,0));var p=o.stream(d);c.decrypt&&(p=p.pipe(c.decrypt.stream())),p.pipe(f).on("error",function(h){s.emit("error",h)}).pipe(s).on("finish",function(){a.destroy?a.destroy():a.abort?a.abort():a.close?a.close():a.push?a.push():console.log("warning - unable to close stream")})}).catch(function(c){s.emit("error",c)}),s}});var fot=I((urn,dot)=>{var PB=IB(),QB=CG(),RCr=lot(),LB=Jm(),TCr=wG(),xCr=vG(),kCr=Mw(),Ame=z("path"),NCr=hme().Writer,BCr=SG(),uot=kCr.alloc(4);uot.writeUInt32LE(101010256,0);function OCr(e){var t=e.stream(0).pipe(QB());return t.pull(4).then(function(r){var n=r.readUInt32LE(0);if(n===875721283){var i;return t.pull(12).then(function(o){i=PB.parse(o).word32lu("version").word32lu("pubKeyLength").word32lu("signatureLength").vars}).then(function(){return t.pull(i.pubKeyLength+i.signatureLength)}).then(function(o){return i.publicKey=o.slice(0,i.pubKeyLength),i.signature=o.slice(i.pubKeyLength),i.size=16+i.pubKeyLength+i.signatureLength,i})}})}function FCr(e,t){var r=PB.parse(t).word32lu("signature").word32lu("diskNumber").word64lu("offsetToStartOfCentralDirectory").word32lu("numberOfDisks").vars;if(r.signature!=117853008)throw new Error("invalid zip64 end of central dir locator signature (0x07064b50): 0x"+r.signature.toString(16));var n=QB();return e.stream(r.offsetToStartOfCentralDirectory).pipe(n),n.pull(56)}function LCr(e){var t=PB.parse(e).word32lu("signature").word64lu("sizeOfCentralDirectory").word16lu("version").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskStart").word64lu("numberOfRecordsOnDisk").word64lu("numberOfRecords").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;if(t.signature!=101075792)throw new Error("invalid zip64 end of central dir locator signature (0x06064b50): 0x0"+t.signature.toString(16));return t}dot.exports=function(t,r){var n=QB(),i=QB(),o=r&&r.tailSize||80,s,a,c,u;return r&&r.crx&&(a=OCr(t)),t.size().then(function(d){return s=d,t.stream(Math.max(0,d-o)).on("error",function(f){n.emit("error",f)}).pipe(n),n.pull(uot)}).then(function(){return LB.props({directory:n.pull(22),crxHeader:a})}).then(function(d){var f=d.directory;if(c=d.crxHeader&&d.crxHeader.size||0,u=PB.parse(f).word32lu("signature").word16lu("diskNumber").word16lu("diskStart").word16lu("numberOfRecordsOnDisk").word16lu("numberOfRecords").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars,u.numberOfRecords==65535||u.numberOfRecords==65535||u.offsetToStartOfCentralDirectory==4294967295){let h=s-(o-n.match+20),m=QB();return t.stream(h).pipe(m),m.pull(20).then(function(A){return FCr(t,A)}).then(function(A){u=LCr(A)})}else u.offsetToStartOfCentralDirectory+=c}).then(function(){if(u.commentLength)return n.pull(u.commentLength).then(function(d){u.comment=d.toString("utf8")})}).then(function(){return t.stream(u.offsetToStartOfCentralDirectory).pipe(i),u.extract=function(d){if(!d||!d.path)throw new Error("PATH_MISSING");return d.path=Ame.resolve(Ame.normalize(d.path)),u.files.then(function(f){return LB.map(f,function(p){if(p.type!="Directory"){var h=Ame.join(d.path,p.path);if(h.indexOf(d.path)==0){var m=d.getWriter?d.getWriter({path:h}):NCr({path:h});return new LB(function(A,g){p.stream(d.password).on("error",g).pipe(m).on("close",A).on("error",g)})}}},{concurrency:d.concurrency>1?d.concurrency:1})})},u.files=LB.mapSeries(Array(u.numberOfRecords),function(){return i.pull(46).then(function(d){var f=PB.parse(d).word32lu("signature").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;return f.offsetToLocalFileHeader+=c,f.lastModifiedDateTime=BCr(f.lastModifiedDate,f.lastModifiedTime),i.pull(f.fileNameLength).then(function(p){return f.pathBuffer=p,f.path=p.toString("utf8"),f.isUnicode=(f.flags&2048)!=0,i.pull(f.extraFieldLength)}).then(function(p){return f.extra=xCr(p,f),i.pull(f.fileCommentLength)}).then(function(p){return f.comment=p,f.type=f.uncompressedSize===0&&/[\/\\]$/.test(f.path)?"Directory":"File",f.stream=function(h){return RCr(t,f.offsetToLocalFileHeader,h,f)},f.buffer=function(h){return TCr(f.stream(h))},f})})}),LB.props(u)})}});var mot=I((drn,hot)=>{var pot=Da(),MG=Jm(),MB=fot(),UG=z("stream");(!UG.Writable||!UG.Writable.prototype.destroy)&&(UG=Ia());hot.exports={buffer:function(e,t){var r={stream:function(n,i){var o=UG.PassThrough();return o.end(e.slice(n,i)),o},size:function(){return MG.resolve(e.length)}};return MB(r,t)},file:function(e,t){var r={stream:function(n,i){return pot.createReadStream(e,{start:n,end:i&&n+i})},size:function(){return new MG(function(n,i){pot.stat(e,function(o,s){o?i(o):n(s.size)})})}};return MB(r,t)},url:function(e,t,r){if(typeof t=="string"&&(t={url:t}),!t.url)throw"URL missing";t.headers=t.headers||{};var n={stream:function(i,o){var s=Object.create(t);return s.headers=Object.create(t.headers),s.headers.range="bytes="+i+"-"+(o||""),e(s)},size:function(){return new MG(function(i,o){var s=e(t);s.on("response",function(a){s.abort(),a.headers["content-length"]?i(a.headers["content-length"]):o(new Error("Missing content length header"))}).on("error",o)})}};return MB(n,r)},s3:function(e,t,r){var n={size:function(){return new MG(function(i,o){e.headObject(t,function(s,a){s?o(s):i(a.ContentLength)})})},stream:function(i,o){var s={};for(var a in t)s[a]=t[a];return s.Range="bytes="+i+"-"+(o||""),e.getObject(s).createReadStream()}};return MB(n,r)},custom:function(e,t){return MB(e,t)}}});var Aot=I(UB=>{"use strict";Ktt();trt();aie();UB.Parse=DG();UB.ParseOne=sit();UB.Extract=not();UB.Open=mot()});var Oot=I((prn,np)=>{var An=z("fs"),qG=z("os"),wo=z("path"),got=z("crypto"),hd={fs:An.constants,os:qG.constants},yot="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Cot=/XXXXXX/,QCr=3,_ot=(hd.O_CREAT||hd.fs.O_CREAT)|(hd.O_EXCL||hd.fs.O_EXCL)|(hd.O_RDWR||hd.fs.O_RDWR),PCr=qG.platform()==="win32",MCr=hd.EBADF||hd.os.errno.EBADF,UCr=hd.ENOENT||hd.os.errno.ENOENT,wot=448,vot=384,$Cr="exit",zw=[],Sot=An.rmdirSync.bind(An),Dot=!1;function qCr(e,t){return An.rm(e,{recursive:!0},t)}function Rot(e){return An.rmSync(e,{recursive:!0})}function bme(e,t){let r=Jw(e,t),n=r[0],i=r[1];XCr(n,function(o,s){if(o)return i(o);let a=s.tries;(function c(){try{let u=xot(s);An.stat(u,function(d){if(!d)return a-- >0?c():i(new Error("Could not get a unique tmp filename, max tries reached "+u));i(null,u)})}catch(u){i(u)}})()})}function Ime(e){let t=Jw(e),r=t[0],n=ZCr(r),i=n.tries;do{let o=xot(n);try{An.statSync(o)}catch{return o}}while(i-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function jCr(e,t){let r=Jw(e,t),n=r[0],i=r[1];bme(n,function(s,a){if(s)return i(s);An.open(a,_ot,n.mode||vot,function(u,d){if(u)return i(u);if(n.discardDescriptor)return An.close(d,function(p){return i(p,a,void 0,yme(a,-1,n,!1))});{let f=n.discardDescriptor||n.detachDescriptor;i(null,a,d,yme(a,f?-1:d,n,!1))}})})}function YCr(e){let t=Jw(e),r=t[0],n=r.discardDescriptor||r.detachDescriptor,i=Ime(r),o=An.openSync(i,_ot,r.mode||vot);return r.discardDescriptor&&(An.closeSync(o),o=void 0),{name:i,fd:o,removeCallback:yme(i,n?-1:o,r,!0)}}function HCr(e,t){let r=Jw(e,t),n=r[0],i=r[1];bme(n,function(s,a){if(s)return i(s);An.mkdir(a,n.mode||wot,function(u){if(u)return i(u);i(null,a,Tot(a,n,!1))})})}function zCr(e){let t=Jw(e),r=t[0],n=Ime(r);return An.mkdirSync(n,r.mode||wot),{name:n,removeCallback:Tot(n,r,!0)}}function JCr(e,t){let r=function(n){if(n&&!Eme(n))return t(n);t()};0<=e[0]?An.close(e[0],function(){An.unlink(e[1],r)}):An.unlink(e[1],r)}function GCr(e){let t=null;try{0<=e[0]&&An.closeSync(e[0])}catch(r){if(!e_r(r)&&!Eme(r))throw r}finally{try{An.unlinkSync(e[1])}catch(r){Eme(r)||(t=r)}}if(t!==null)throw t}function yme(e,t,r,n){let i=$G(GCr,[t,e],n),o=$G(JCr,[t,e],n,i);return r.keep||zw.unshift(i),n?i:o}function Tot(e,t,r){let n=t.unsafeCleanup?qCr:An.rmdir.bind(An),i=t.unsafeCleanup?Rot:Sot,o=$G(i,e,r),s=$G(n,e,r,o);return t.keep||zw.unshift(o),r?o:s}function $G(e,t,r,n){let i=!1;return function o(s){if(!i){let a=n||o,c=zw.indexOf(a);return c>=0&&zw.splice(c,1),i=!0,r||e===Sot||e===Rot?e(t):e(t,s||function(){})}}}function VCr(){if(Dot)for(;zw.length;)try{zw[0]()}catch{}}function Eot(e){let t=[],r=null;try{r=got.randomBytes(e)}catch{r=got.pseudoRandomBytes(e)}for(let n=0;n<e;n++)t.push(yot[r[n]%yot.length]);return t.join("")}function Ra(e){return typeof e>"u"}function Jw(e,t){if(typeof e=="function")return[{},e];if(Ra(e))return[{},t];let r={};for(let n of Object.getOwnPropertyNames(e))r[n]=e[n];return[r,t]}function WCr(e,t,r){let n=wo.isAbsolute(e)?e:wo.join(t,e);An.stat(n,function(i){i?An.realpath(wo.dirname(n),function(o,s){if(o)return r(o);r(null,wo.join(s,wo.basename(n)))}):An.realpath(n,r)})}function KCr(e,t){let r=wo.isAbsolute(e)?e:wo.join(t,e);try{return An.statSync(r),An.realpathSync(r)}catch{let i=An.realpathSync(wo.dirname(r));return wo.join(i,wo.basename(r))}}function xot(e){let t=e.tmpdir;if(!Ra(e.name))return wo.join(t,e.dir,e.name);if(!Ra(e.template))return wo.join(t,e.dir,e.template).replace(Cot,Eot(6));let r=[e.prefix?e.prefix:"tmp","-",process.pid,"-",Eot(12),e.postfix?"-"+e.postfix:""].join("");return wo.join(t,e.dir,r)}function gme(e,t){if(typeof t!="string")throw new Error(`${e} option must be a string, got "${typeof t}".`);if(t.includes(".."))throw new Error("Relative value not allowed");return t}function kot(e){if(!Ra(e.name)){let t=e.name;if(wo.isAbsolute(t))throw new Error(`name option must not contain an absolute path, found "${t}".`);let r=wo.basename(t);if(r===".."||r==="."||r!==t)throw new Error(`name option must not contain a path, found "${t}".`)}if(!Ra(e.template)){if(typeof e.template!="string")throw new Error(`template option must be a string, got "${typeof e.template}".`);if(!e.template.match(Cot))throw new Error(`Invalid template, found "${e.template}".`)}if(!Ra(e.tries)&&isNaN(e.tries)||e.tries<0)throw new Error(`Invalid tries, found "${e.tries}".`);e.tries=Ra(e.name)?e.tries||QCr:1,e.keep=!!e.keep,e.detachDescriptor=!!e.detachDescriptor,e.discardDescriptor=!!e.discardDescriptor,e.unsafeCleanup=!!e.unsafeCleanup,e.prefix=Ra(e.prefix)?"":gme("prefix",e.prefix),e.postfix=Ra(e.postfix)?"":gme("postfix",e.postfix),e.template=Ra(e.template)?void 0:gme("template",e.template)}function bot(e,t,r,n){if(Ra(t))return n(null);WCr(t,r,function(i,o){if(i)return n(i);let s=wo.relative(r,o);if(s.startsWith("..")||wo.isAbsolute(s))return n(new Error(`${e} option must be relative to "${r}", found "${s}".`));n(null,s)})}function Iot(e,t,r){if(Ra(t))return;let n=KCr(t,r),i=wo.relative(r,n);if(i.startsWith("..")||wo.isAbsolute(i))throw new Error(`${e} option must be relative to "${r}", found "${i}".`);return i}function XCr(e,t){r_r(e,function(r,n){if(r)return t(r);e.tmpdir=n;try{kot(e,n)}catch(i){return t(i)}bot("dir",e.dir,n,function(i,o){if(i)return t(i);e.dir=Ra(o)?"":o,bot("template",e.template,n,function(s,a){if(s)return t(s);e.template=a,t(null,e)})})})}function ZCr(e){let t=e.tmpdir=Bot(e);kot(e,t);let r=Iot("dir",e.dir,t);return e.dir=Ra(r)?"":r,e.template=Iot("template",e.template,t),e}function e_r(e){return Not(e,-MCr,"EBADF")}function Eme(e){return Not(e,-UCr,"ENOENT")}function Not(e,t,r){return PCr?e.code===r:e.code===r&&e.errno===t}function t_r(){Dot=!0}function r_r(e,t){return An.realpath(e&&e.tmpdir||qG.tmpdir(),t)}function Bot(e){return An.realpathSync(e&&e.tmpdir||qG.tmpdir())}process.addListener($Cr,VCr);Object.defineProperty(np.exports,"tmpdir",{enumerable:!0,configurable:!1,get:function(){return Bot()}});np.exports.dir=HCr;np.exports.dirSync=zCr;np.exports.file=jCr;np.exports.fileSync=YCr;np.exports.tmpName=bme;np.exports.tmpNameSync=Ime;np.exports.setGracefulCleanup=t_r});var Lot=I((hrn,Fot)=>{Fot.exports=async function*(t){let r=[];t.on("data",a=>r.push(a));let n,i=new Promise(a=>n=a),o=!1;t.on("end",()=>{o=!0,n()});let s=!1;for(t.on("error",a=>{s=a,n()});!o||r.length>0;)if(r.length===0?(t.resume(),await Promise.race([n_r(t,"data"),i])):(t.pause(),yield r.shift()),s)throw s;n()};function n_r(e,t){return new Promise(r=>{let n=!1,i=()=>{n||(n=!0,e.removeListener(t,i),r())};e.addListener(t,i)})}});var Uot=I((mrn,Mot)=>{var{EventEmitter:i_r}=z("events"),o_r=Kk(),s_r=ki(),jG=Ts(),Qot=mi(),a_r=Tf(),c_r=Ij(),Pot=Cj(),Cme=class extends i_r{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i||{},this.name=`Sheet${this.id}`,this._columns=null,this._keys={},this._dimensions=new a_r}destroy(){throw new Error("Invalid Operation: destroy")}get dimensions(){return this._dimensions}get columns(){return this._columns}getColumn(t){if(typeof t=="string"){let r=this._keys[t];if(r)return r;t=Qot.l2n(t)}if(this._columns||(this._columns=[]),t>this._columns.length){let r=this._columns.length+1;for(;r<=t;)this._columns.push(new Pot(this,r++))}return this._columns[t-1]}getColumnKey(t){return this._keys[t]}setColumnKey(t,r){this._keys[t]=r}deleteColumnKey(t){delete this._keys[t]}eachColumnKey(t){s_r.each(this._keys,t)}async read(){try{for await(let t of this.parse())for(let{eventType:r,value:n}of t)this.emit(r,n);this.emit("finished")}catch(t){this.emit("error",t)}}async*[Symbol.asyncIterator](){for await(let t of this.parse())for(let{eventType:r,value:n}of t)r==="row"&&(yield n)}async*parse(){let{iterator:t,options:r}=this,n=!1,i=!1,o=null;switch(r.worksheets){case"emit":n=!0;break;case"prep":break;default:break}switch(r.hyperlinks){case"emit":i=!0;break;case"cache":this.hyperlinks=o={};break;default:break}if(!n&&!i&&!o)return;let{sharedStrings:s,styles:a,properties:c}=this.workbook,u=!1,d=!1,f=!1,p=null,h=null,m=null,A=null;for await(let g of o_r(t)){let y=[];for(let{eventType:b,value:E}of g)if(b==="opentag"){let C=E;if(n)switch(C.name){case"cols":u=!0,p=[];break;case"sheetData":d=!0;break;case"col":u&&p.push({min:parseInt(C.attributes.min,10),max:parseInt(C.attributes.max,10),width:parseFloat(C.attributes.width),styleId:parseInt(C.attributes.style||"0",10)});break;case"row":if(d){let w=parseInt(C.attributes.r,10);if(h=new c_r(this,w),C.attributes.ht&&(h.height=parseFloat(C.attributes.ht)),C.attributes.s){let T=parseInt(C.attributes.s,10),D=a.getStyleModel(T);D&&(h.style=D)}}break;case"c":h&&(m={ref:C.attributes.r,s:parseInt(C.attributes.s,10),t:C.attributes.t});break;case"f":m&&(A=m.f={text:""});break;case"v":m&&(A=m.v={text:""});break;case"is":case"t":m&&(A=m.v={text:""});break;case"mergeCell":break;default:break}if(i||o)switch(C.name){case"hyperlinks":f=!0;break;case"hyperlink":if(f){let w={ref:C.attributes.ref,rId:C.attributes["r:id"]};i?y.push({eventType:"hyperlink",value:w}):o[w.ref]=w}break;default:break}}else if(b==="text")n&&A&&(A.text+=E);else if(b==="closetag"){let C=E;if(n)switch(C.name){case"cols":u=!1,this._columns=Pot.fromModel(p);break;case"sheetData":d=!1;break;case"row":this._dimensions.expandRow(h),y.push({eventType:"row",value:h}),h=null;break;case"c":if(h&&m){let w=Qot.decodeAddress(m.ref),T=h.getCell(w.col);if(m.s){let D=a.getStyleModel(m.s);D&&(T.style=D)}if(m.f){let D={formula:m.f.text};m.v&&(m.t==="str"?D.result=jG.xmlDecode(m.v.text):D.result=parseFloat(m.v.text)),T.value=D}else if(m.v)switch(m.t){case"s":{let D=parseInt(m.v.text,10);s?T.value=s[D]:T.value={sharedString:D};break}case"inlineStr":case"str":T.value=jG.xmlDecode(m.v.text);break;case"e":T.value={error:m.v.text};break;case"b":T.value=parseInt(m.v.text,10)!==0;break;default:jG.isDateFmt(T.numFmt)?T.value=jG.excelToDate(parseFloat(m.v.text),c.model&&c.model.date1904):T.value=parseFloat(m.v.text);break}if(o){let D=o[m.ref];D&&(T.text=T.value,T.value=void 0,T.hyperlink=D)}m=null}break;default:break}(i||o)&&C.name==="hyperlinks"&&(f=!1)}y.length>0&&(yield y)}}};Mot.exports=Cme});var qot=I((Arn,$ot)=>{var{EventEmitter:l_r}=z("events"),u_r=Kk(),d_r=Yl(),f_r=Kh(),_me=class extends l_r{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i}get count(){return this.hyperlinks&&this.hyperlinks.length||0}each(t){return this.hyperlinks.forEach(t)}async read(){let{iterator:t,options:r}=this,n=!1,i=null;switch(r.hyperlinks){case"emit":n=!0;break;case"cache":this.hyperlinks=i={};break;default:break}if(!n&&!i){this.emit("finished");return}try{for await(let o of u_r(t))for(let{eventType:s,value:a}of o)if(s==="opentag"){let c=a;if(c.name==="Relationship"){let u=c.attributes.Id;switch(c.attributes.Type){case f_r.Hyperlink:{let d={type:d_r.RelationshipType.Styles,rId:u,target:c.attributes.Target,targetMode:c.attributes.TargetMode};n?this.emit("hyperlink",d):i[d.rId]=d}break;default:break}}}this.emit("finished")}catch(o){this.emit("error",o)}}};$ot.exports=_me});var zot=I((grn,Hot)=>{var wme=z("fs"),{EventEmitter:p_r}=z("events"),{PassThrough:h_r,Readable:m_r}=zk(),A_r=z("stream"),g_r=Aot(),Yot=Oot(),bE=Lot(),y_r=Kk(),jot=eH(),E_r=sH(),b_r=iH(),I_r=Uot(),C_r=qot();Yot.setGracefulCleanup();var YG=class extends p_r{constructor(t,r={}){super(),this.input=t,this.options={worksheets:"emit",sharedStrings:"cache",hyperlinks:"ignore",styles:"ignore",entries:"ignore",...r},this.styles=new jot,this.styles.init()}_getStream(t){if(t instanceof A_r.Readable||t instanceof m_r)return t;if(typeof t=="string")return wme.createReadStream(t);throw new Error(`Could not recognise input: ${t}`)}async read(t,r){try{for await(let{eventType:n,value:i}of this.parse(t,r))switch(n){case"shared-strings":this.emit(n,i);break;case"worksheet":this.emit(n,i),await i.read();break;case"hyperlinks":this.emit(n,i);break}this.emit("end"),this.emit("finished")}catch(n){this.emit("error",n)}}async*[Symbol.asyncIterator](){for await(let{eventType:t,value:r}of this.parse())t==="worksheet"&&(yield r)}async*parse(t,r){r&&(this.options=r);let n=this.stream=this._getStream(t||this.input),i=g_r.Parse({forceStream:!0});n.pipe(i);let o=[];for await(let s of bE(i)){let a,c;switch(s.path){case"_rels/.rels":break;case"xl/_rels/workbook.xml.rels":await this._parseRels(s);break;case"xl/workbook.xml":await this._parseWorkbook(s);break;case"xl/sharedStrings.xml":yield*this._parseSharedStrings(s);break;case"xl/styles.xml":await this._parseStyles(s);break;default:s.path.match(/xl\/worksheets\/sheet\d+[.]xml/)?(a=s.path.match(/xl\/worksheets\/sheet(\d+)[.]xml/),c=a[1],this.sharedStrings&&this.workbookRels?yield*this._parseWorksheet(bE(s),c):await new Promise((u,d)=>{Yot.file((f,p,h,m)=>{if(f)return d(f);o.push({sheetNo:c,path:p,tempFileCleanupCallback:m});let A=wme.createWriteStream(p);return A.on("error",d),s.pipe(A),A.on("finish",()=>u())})})):s.path.match(/xl\/worksheets\/_rels\/sheet\d+[.]xml.rels/)&&(a=s.path.match(/xl\/worksheets\/_rels\/sheet(\d+)[.]xml.rels/),c=a[1],yield*this._parseHyperlinks(bE(s),c));break}s.autodrain()}for(let{sheetNo:s,path:a,tempFileCleanupCallback:c}of o){let u=wme.createReadStream(a);u[Symbol.asyncIterator]||(u=u.pipe(new h_r)),yield*this._parseWorksheet(u,s),c()}}_emitEntry(t){this.options.entries==="emit"&&this.emit("entry",t)}async _parseRels(t){let r=new b_r;this.workbookRels=await r.parseStream(bE(t))}async _parseWorkbook(t){this._emitEntry({type:"workbook"});let r=new E_r;await r.parseStream(bE(t)),this.properties=r.map.workbookPr,this.model=r.model}async*_parseSharedStrings(t){switch(this._emitEntry({type:"shared-strings"}),this.options.sharedStrings){case"cache":this.sharedStrings=[];break;case"emit":break;default:return}let r=null,n=[],i=0,o=null;for await(let s of y_r(bE(t)))for(let{eventType:a,value:c}of s)if(a==="opentag"){let u=c;switch(u.name){case"b":o=o||{},o.bold=!0;break;case"charset":o=o||{},o.charset=parseInt(u.attributes.charset,10);break;case"color":o=o||{},o.color={},u.attributes.rgb&&(o.color.argb=u.attributes.argb),u.attributes.val&&(o.color.argb=u.attributes.val),u.attributes.theme&&(o.color.theme=u.attributes.theme);break;case"family":o=o||{},o.family=parseInt(u.attributes.val,10);break;case"i":o=o||{},o.italic=!0;break;case"outline":o=o||{},o.outline=!0;break;case"rFont":o=o||{},o.name=u.value;break;case"si":o=null,n=[],r=null;break;case"sz":o=o||{},o.size=parseInt(u.attributes.val,10);break;case"strike":break;case"t":r=null;break;case"u":o=o||{},o.underline=!0;break;case"vertAlign":o=o||{},o.vertAlign=u.attributes.val;break}}else if(a==="text")r=r?r+c:c;else if(a==="closetag")switch(c.name){case"r":n.push({font:o,text:r}),o=null,r=null;break;case"si":this.options.sharedStrings==="cache"?this.sharedStrings.push(n.length?{richText:n}:r):this.options.sharedStrings==="emit"&&(yield{index:i++,text:n.length?{richText:n}:r}),n=[],o=null,r=null;break}}async _parseStyles(t){this._emitEntry({type:"styles"}),this.options.styles==="cache"&&(this.styles=new jot,await this.styles.parseStream(bE(t)))}*_parseWorksheet(t,r){this._emitEntry({type:"worksheet",id:r});let n=new I_r({workbook:this,id:r,iterator:t,options:this.options}),i=(this.workbookRels||[]).find(s=>s.Target===`worksheets/sheet${r}.xml`),o=i&&(this.model.sheets||[]).find(s=>s.rId===i.Id);o&&(n.id=o.id,n.name=o.name,n.state=o.state),this.options.worksheets==="emit"&&(yield{eventType:"worksheet",value:n})}*_parseHyperlinks(t,r){this._emitEntry({type:"hyperlinks",id:r});let n=new C_r({workbook:this,id:r,iterator:t,options:this.options});this.options.hyperlinks==="emit"&&(yield{eventType:"hyperlinks",value:n})}};YG.Options={worksheets:["emit","ignore"],sharedStrings:["cache","emit","ignore"],hyperlinks:["cache","emit","ignore"],styles:["cache","ignore"],entries:["emit","ignore"]};Hot.exports=YG});var Vot=I((yrn,Got)=>{var Jot={Workbook:J3e(),ModelContainer:V3e(),stream:{xlsx:{WorkbookWriter:Vtt(),WorkbookReader:zot()}}};Object.assign(Jot,Yl());Got.exports=Jot});var Kot=I((Ern,Wot)=>{if(parseInt(process.versions.node.split(".")[0],10)<10)throw new Error("For node versions older than 10, please use the ES5 Import: https://github.com/exceljs/exceljs#es5-imports");Wot.exports=Vot()});function est(e){let t=new Set;for(let r=0;r<e.length;r++){let n=e[r];if(!n.trim())throw new Error(`Header row contains a blank column at position ${r+1}`);let i=n.trim().toLowerCase();if(t.has(i))throw new Error(`Header row contains a duplicate column: "${n}"`);t.add(i)}}function v_r(e,t){let r=new URL(e).pathname.toLowerCase();if(r.endsWith(".xls")||r.endsWith(".xlsx")||r.endsWith(".xlsm")||r.endsWith(".xlsb")||r.endsWith(".ods"))return"excel";let n=(t??"").toLowerCase();return n.includes("spreadsheet")||n.includes("excel")||n.includes("sheet")?"excel":"csv"}async function S_r(e){let r=(await Promise.resolve().then(()=>uo(R$e(),1))).default.parse(e,{header:!1,skipEmptyLines:"greedy",dynamicTyping:!1,transform:o=>o.trim()});if(r.errors.length>0&&r.data.length===0){let o=r.errors[0];throw new Error(`CSV parse error at row ${o.row}: ${o.message}`)}if(r.data.length===0)return{columns:[],rows:[]};let n=(r.data[0]??[]).map(o=>String(o??"").trim());est(n);let i=[];for(let o=1;o<r.data.length;o++){let s=r.data[o]??[],a={};for(let c=0;c<n.length;c++)a[n[c]]=s[c]??null;i.push(a)}return{columns:n,rows:i}}function vme(e){if(e==null)return null;if(e instanceof Date)return e.toISOString().slice(0,10);if(typeof e=="number")return String(e);if(typeof e=="string"||typeof e=="boolean")return e;let t=e;return"text"in t?String(t.text??""):"result"in t?vme(t.result):"richText"in t&&Array.isArray(t.richText)?t.richText.map(r=>r.text??"").join(""):"hyperlink"in t?String(t.hyperlink??""):String(e)}async function D_r(e){let t=(await Promise.resolve().then(()=>uo(VZ(),1))).default,n=new t(Buffer.from(e)).getEntries().reduce((i,o)=>i+o.header.size,0);if(n>Xot)throw new Error(`XLSX uncompressed size ${n} bytes exceeds ${Xot}-byte safety cap`)}function tst(e){let t=0,r=[];return e.eachRow({includeEmpty:!1},(n,i)=>{if(t>0)return;let o=n.values.slice(1);o.some(s=>s!=null&&s!=="")&&(t=i,r=o.map(s=>String(vme(s)??"").trim()))}),{headerRowNum:t,columns:r}}function Zot(e){let{headerRowNum:t,columns:r}=tst(e);if(!t)return{columns:[],rows:[]};est(r);let n=[];return e.eachRow({includeEmpty:!1},(i,o)=>{if(o<=t)return;let s=i.values.slice(1);if(s.every(c=>c==null||c===""))return;let a={};for(let c=0;c<r.length;c++)a[r[c]]=vme(s[c]);n.push(a)}),{columns:r,rows:n}}async function R_r(e,t,r){await D_r(e);let n=await Promise.resolve().then(()=>uo(Kot(),1)),i=n.default??n,o=new i.Workbook;await o.xlsx.load(e);let s=o.worksheets.map(u=>u.name);if(t<0||t>=s.length)throw new Error(`sheetIndex ${t} out of range (have ${s.length} sheets: ${s.join(", ")})`);let a=()=>s.map((u,d)=>`${d}:"${u}"`).join(", "),c=(u,d)=>{throw new Error(`${u.message} on sheet ${d} ("${s[d]}"). availableSheets: [${a()}]. Re-call with a sheetIndex pointing at the data sheet.`)};if(r)try{return{...Zot(o.worksheets[t]),sheetName:o.worksheets[t].name,sheetIndex:t,availableSheets:s}}catch(u){c(u,t)}for(let u=t;u<s.length;u++){let d=o.worksheets[u];if(tst(d).headerRowNum!==0)try{return{...Zot(d),sheetName:d.name,sheetIndex:u,availableSheets:s}}catch(f){c(f,u)}}throw new Error(`No sheet with a header row was found. availableSheets: [${a()}].`)}async function rst(e){let t=Math.max(0,e.offset??0),r=Math.min(__r,Math.max(1,e.limit??w_r)),n=e.sheetIndex??0,i=await lf(e.sourceUrl),o=await wc(i,{timeoutMs:JI,maxBytes:IM});if(!o.ok)throw new Error(`fetch ${e.sourceUrl}: ${o.status} ${o.statusText}`);let s=await o.arrayBuffer(),a=e.kind??v_r(e.sourceUrl,o.headers.get("content-type")),c,u,d,f,p=n;if(a==="csv"){let A=await S_r(new TextDecoder("utf-8").decode(s));c=A.columns,u=A.rows}else{let A=await R_r(s,n,e.sheetIndex!==void 0);c=A.columns,u=A.rows,d=A.sheetName,f=A.availableSheets,p=A.sheetIndex}let h=u.length,m=u.slice(t,t+r);return{sourceUrl:e.sourceUrl,kind:a,...a==="excel"?{sheetIndex:p,sheetName:d,availableSheets:f}:{},totalRows:h,offset:t,limit:r,returned:m.length,hasMore:t+m.length<h,columns:c,rows:m}}var __r,w_r,Xot,nst=J(()=>{"use strict";Lu();__r=500,w_r=200,Xot=100*1024*1024});function T_r(e){if(e.internalNotes!==void 0)throw ut(new Error("A cash entry's notes cannot be edited via the API today (the update fails upstream). Nothing was changed. To change the notes, void the entry and create a new one."));if((Array.isArray(e.lines)?e.lines:[]).some(r=>!!r?.taxProfileResourceId))throw ut(new Error("A taxed cash entry's lines cannot be edited via the API today: void it and create a new one. Nothing was changed."))}function ist(e){return{create:(t,r)=>t.post(`/api/v1/${Gw[e]}`,{saveAsDraft:!1,...r,currency:Wt(r.currency),taxCurrency:Wt(r.taxCurrency)},Wi),list:(t,r)=>t.list(`/api/v1/${Gw[e]}`,r),get:(t,r)=>t.get(`/api/v1/${Gw[e]}/${r}`),update:async(t,r,n,i)=>{T_r(n);let o={...n,resourceId:r};if(!o.accountResourceId){let s=i??(await t.get(`/api/v1/${Gw[e]}/${r}`)).data;if(o.accountResourceId=s.organizationAccountResourceId??s.account?.resourceId,!o.accountResourceId)throw new Error(`accountResourceId required for ${Gw[e]} update and could not be derived from existing entry`)}return o.currency&&(o.currency=Wt(o.currency)),t.put(`/api/v1/${Gw[e]}/${r}`,o)}}}var Gw,HG,zG,JG,GG,IE,VG,WG,KG,CE,XG,ZG=J(()=>{"use strict";tr();ot();Gw={IN:"cash-in-entries",OUT:"cash-out-entries"};HG=ist("IN"),zG=ist("OUT"),JG=HG.create,GG=HG.list,IE=HG.get,VG=HG.update,WG=zG.create,KG=zG.list,CE=zG.get,XG=zG.update});async function $B(e,t){return e.post("/api/v1/cash-transfers",{saveAsDraft:!1,...t},Wi)}async function eV(e,t){return e.list("/api/v1/cash-transfers",t)}async function tV(e,t){return e.get(`/api/v1/cash-transfers/${t}`)}var Sme=J(()=>{"use strict";tr();an()});async function rV(e,t){return e.list("/api/v1/scheduled/invoices",t)}async function nV(e,t){return e.list("/api/v1/scheduled/bills",t)}async function iV(e,t){return e.list("/api/v1/scheduled/journals",t)}async function Vw(e,t){return e.get(`/api/v1/scheduled/invoices/${t}`)}async function oV(e,t,r){return e.put(`/api/v1/scheduled/invoices/${t}`,r)}async function sV(e,t){await e.delete(`/api/v1/scheduled/invoices/${t}`)}async function Ww(e,t){return e.get(`/api/v1/scheduled/bills/${t}`)}async function aV(e,t,r){return e.put(`/api/v1/scheduled/bills/${t}`,r)}async function cV(e,t){await e.delete(`/api/v1/scheduled/bills/${t}`)}async function Kw(e,t){return e.get(`/api/v1/scheduled/journals/${t}`)}async function lV(e,t,r){let{currency:n,...i}=x_r(r);return e.put(`/api/v1/scheduled/journals/${t}`,n===void 0?i:{...i,currency:Wt(n)})}function x_r(e){let t={...e};xM(t);let r=Array.isArray(t.schedulerEntries)?t.schedulerEntries:[];if(typeof t.taxVatApplicable!="boolean"&&r.some(n=>!!n?.taxProfileResourceId)&&(t.taxVatApplicable=!0),t.taxVatApplicable===!0&&typeof t.taxInclusion!="boolean")throw ut(new Error("taxInclusion is required when the schedule is taxed (a schedulerEntries line carries a tax profile, or taxVatApplicable is true): the update resets it when omitted, and the stored value cannot be read back. Send taxInclusion true (prices include tax) or false (CLI: --tax-inclusion inclusive|exclusive). Nothing was changed."));return t}async function uV(e,t){await e.delete(`/api/v1/scheduled/journals/${t}`)}var dV=J(()=>{"use strict";ot()});import{statSync as ost}from"node:fs";function sst(e){for(let t of e)try{if(ost(t).isFile())return t}catch{}return null}function ast(e){for(let t of e)try{if(ost(t).isDirectory())return t}catch{}return null}var Dme=J(()=>{"use strict"});import{readFileSync as Tme}from"node:fs";import{dirname as dst,join as Zm}from"node:path";import{fileURLToPath as fst}from"node:url";function pst(e){let t=new Set(e);for(let r of e){let n=B_r.get(r);if(n)for(let i of n)t.add(i)}return Array.from(t)}function hst(e){let t=e.toLowerCase();return t=t.replace(/https?:\/\/\S+/g,""),t=t.replace(/[*#`|_\-~\[\]()>]/g," "),(t.match(/[a-z0-9]+/g)??[]).filter(n=>n.length>1&&!N_r.has(n))}function qB(e){let t=e??P_r();if(fV&&ust===t)return fV;let r=Tme(t,"utf-8");return fV=JSON.parse(r),ust=t,fV}function mst(){let e=fst(import.meta.url),t=dst(e),r=[Zm(t,"..","..","..","help-center-mirror","help-center-index.json"),Zm(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-index.json"),Zm(t,"help-center-mirror","help-center-index.json")];return sst(r)??void 0}function P_r(){let e=mst();if(!e)throw new Error("Help center index not found. Run the help center sync or reinstall the package.");return e}function jB(){return Rme===null&&(Rme=mst()!==void 0),Rme}function _E(e,t,r={}){let n=r.limit??5,i=hst(t);if(i.length===0)return[];let o=pst(i).slice(0,L_r),s=new Map(e.sections.map(c=>[c.slug,c])),a=[];for(let c of e.articles){if(r.section&&c.section!==r.section)continue;let u=new Map;for(let h of c.tokens)u.set(h,(u.get(h)??0)+1);let d=0,f=[],p=c.title.toLowerCase();for(let h of o){let m=u.get(h)??0,A=e.idf[h]??0,g=!1;if(m===0&&h.length>=F_r){let C=0;for(let[w,T]of u)if(w.startsWith(h)&&w!==h&&(m+=T,A=Math.max(A,e.idf[w]??0),g=!0,++C>=Q_r))break}if(m===0)continue;f.push(g?`${h}*`:h);let y=m*(cst+1),b=m+cst*(1-lst+lst*(c.tokenCount/e.avgDocLen)),E=A*(y/b);g&&(E*=O_r),p.includes(h)&&(E*=k_r),d+=E}if(d>0){let h=s.get(c.section);h&&a.push({article:c,score:d,scoreKind:"bm25",section:h,matchedTerms:f})}}return a.sort((c,u)=>u.score-c.score),a.slice(0,n)}function xme(e,t){let r=t??M_r();if(!r)return null;try{let n=Zm(r,`${e.section}.md`),i=Tme(n,"utf-8"),o=`### ${e.title}`,s=i.indexOf(o);if(s===-1)return null;let a=s+o.length,c=i.indexOf(`
660
660
  ---
661
661
  `,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function M_r(){let e=fst(import.meta.url),t=dst(e),r=[Zm(t,"..","..","..","help-center-mirror"),Zm(t,"..","..","..","assets","skills","api","help-center-mirror"),Zm(t,"help-center-mirror")];for(let n of r)try{return Tme(Zm(n,"index.md"),"utf-8"),n}catch{}return null}var cst,lst,k_r,N_r,B_r,O_r,F_r,L_r,Q_r,fV,ust,Rme,YB=J(()=>{"use strict";Dme();Tg();cst=1.2,lst=.75,k_r=1.5,N_r=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","shall","should","may","might","must","can","could","am","i","me","my","we","our","you","your","he","she","it","they","them","this","that","these","those","what","which","who","whom","how","when","where","why","if","then","than","so","no","not","or","and","but","in","on","at","to","for","of","with","by","from","as","into","about","between","through","after","before","during","above","below","up","down","out","off","over","under","again","further","just","also","very","too","only","own","same","both","each","all","any","few","more","most","other","some","such","here","there"]),B_r=new Map([["recon",["reconciliation","reconcile","reconciled"]],["txn",["transaction","transactions"]],["txns",["transactions","transaction"]],["acct",["account","accounts"]],["accts",["accounts","account"]],["inv",["invoice","invoices"]],["cn",["credit","note"]],["ar",["receivable","receivables"]],["ap",["payable","payables"]],["pmt",["payment","payments"]],["stmt",["statement","statements"]],["bal",["balance","balances"]],["fa",["fixed","assets","asset"]],["gst",["tax","goods","services"]],["vat",["tax","value","added"]],["fx",["foreign","exchange","currency"]],["config",["configuration","configure","settings"]],["depr",["depreciation"]],["amort",["amortization"]],["coa",["chart","accounts"]],["po",["purchase","order"]],["so",["sales","order"]],["org",["organization"]],["subs",["subscription","subscriptions"]],["amt",["amount","amounts"]],["qty",["quantity"]],["desc",["description"]],["ref",["reference"]],["num",["number"]]]);O_r=.7,F_r=3,L_r=32,Q_r=5;fV=null,ust=null;Rme=null});import{existsSync as U_r,readFileSync as $_r}from"node:fs";import{dirname as q_r,join as kme}from"node:path";import{fileURLToPath as j_r}from"node:url";function HB(e){let t=e??G_r();if(!t)return null;if(pV&&gst===t)return pV;try{let r=$_r(t,"utf-8");return pV=JSON.parse(r),gst=t,pV}catch{return null}}function G_r(){let e=j_r(import.meta.url),t=q_r(e),r=[kme(t,"..","..","..","help-center-mirror","help-center-embeddings.json"),kme(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),kme(t,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(U_r(n))return n;return null}function bst(e,t){let r=Math.min(e.length,t.length),n=0;for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function Ist(){return hV!==null?hV:(hV=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",hV||null)}async function Nme(e){let t=Ist();if(!t)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),H_r),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:Y_r,input:e}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!yst&&(yst=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
662
- `)),null)}catch{return null}}async function zB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??z_r,c=n.minBm25??J_r;if(i==="bm25"||!t)return _E(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Nme(r);return m?Est(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):_E(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Nme(r),Promise.resolve(_E(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Est(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Cst(p,h,o)}function Est(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=bst(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Cst(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Ast+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(Ast+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function Bme(e){return e!==null&&!!Ist()}var Y_r,H_r,Ast,z_r,J_r,pV,gst,hV,yst,mV=J(()=>{"use strict";YB();Y_r="text-embedding-3-small",H_r=2e3,Ast=60,z_r=.3,J_r=1.5,pV=null,gst=null,hV=null,yst=!1});async function _st(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=qB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:HB(),u=await zB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(xme(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function wst(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:V_r}async function AV(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(wst())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(W_r),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return K_r(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function K_r(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Ome(e,t={}){return process.env.CLIO_DAEMON==="1"||jB()?_st(e,t):AV(e,t)}var V_r,W_r,vst=J(()=>{"use strict";YB();mV();V_r="https://mcp.jaz.ai/help-center/search",W_r=4e3});var Fme=J(()=>{"use strict";YB();mV();vst();YB()});async function eA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function tA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var JB=J(()=>{"use strict";an()});async function gV(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency)},zke)}var Lme=J(()=>{"use strict";ot();tr()});async function yV(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function EV(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function GB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function bV(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Qme=J(()=>{"use strict"});function X_r(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Xw(e,t){return e.post("/api/v1/jots",{entries:t.map(X_r)})}async function IV(e,t){return e.post("/api/v1/jots/search",t,et)}async function Sst(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var CV=J(()=>{"use strict";tr()});async function Dst(e,t){return e.post("/api/v1/agents/memories",t)}async function Pme(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Rst=J(()=>{"use strict";tr()});function _V(){return process.env.ENABLE_MEMORY==="true"}function Mme(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Tst(e){return!_V()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Ume=J(()=>{"use strict"});import{createHash as Z_r}from"node:crypto";function uwr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:Nst.some(r=>t.includes(r))?[null,"directive_invalid"]:kst.test(t)?[null,"directive_invalid"]:owr.test(t)?[null,"directive_contains_url"]:swr.test(t)?[null,"directive_contains_email"]:[t,null]}function dwr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>awr?[null,"match_condition_too_long"]:Nst.some(r=>t.includes(r))?[null,"match_condition_invalid"]:kst.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function fwr(e){return e==null?[null,null]:Number.isInteger(e)?e<cwr||e>lwr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function pwr(e,t,r,n,i,o,s,a){if(e)return Z_r("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function hwr(e){Promise.resolve().then(()=>(mD(),hD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Lst(e,t,r){let n=t.action,i=t.category,o=nwr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(hwr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Tst(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>ewr||!iwr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=uwr(t.directive);if(E)return u(E);p=b;let[C,w]=fwr(t.importance);if(w)return u(w);h=C}let[m,A]=dwr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=twr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,rwr));let E=pwr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await $me(()=>Dst(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await $me(()=>Pme(e.client,b))}else{let b={forgetAll:!0};y=await $me(()=>Pme(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function $me(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof gr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var kst,Nst,ewr,twr,rwr,Bst,Ost,Fst,nwr,iwr,owr,swr,awr,cwr,lwr,Qst=J(()=>{"use strict";Rst();Ki();Ume();Ume();kst=/[\x00-\x1f\x7f]/,Nst=["{{","}}","```","<",">"],ewr=120,twr=3,rwr=140,Bst=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Ost=["set","forget","forget_all"],Fst=["this_org","all_orgs"],nwr={this_org:"ORG_USER",all_orgs:"USER"},iwr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,owr=/https?:\/\//i,swr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,awr=255,cwr=0,lwr=100});async function wV(e,t){return e.list("/api/v1/organization-users",t)}async function vV(e,t){return e.search("/api/v1/organization-users/search",t)}async function Zw(e,t){return e.post("/api/v1/organization-users/invite",t)}async function SV(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function DV(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var qme=J(()=>{"use strict"});async function RV(e,t){return e.get(`/api/v1/payments/${t}`)}async function TV(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Wt(r.currency)})}async function xV(e,t){await e.delete(`/api/v1/payments/${t}`)}function kV(e){return(t,r)=>t.post(`/api/v1/${mwr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Wt(n.currency)}))},Lke)}var mwr,Cnn,Pst,_nn,wnn,jme=J(()=>{"use strict";ot();tr();mwr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};Cnn=kV("saleBulk"),Pst=kV("saleBatch"),_nn=kV("purchaseBulk"),wnn=kV("purchaseBatch")});async function ip(e,t,r,n,i,o=Hke){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof gr?c.status<500&&c.status!==401?ut(c):new rf(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof zp?ut(c):c}let a=s?.data;if(!i(a))throw new rf(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function BV(e,t,r){try{Zi(e,t,r)}catch(n){throw ut(n)}}function wE(e){return BV(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function OV(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function FV(e,t){return ip(e,"POST",Awr,t,rA)}async function LV(e,t,r){return ip(e,"PUT",`/api/v1/unapplied-payments/${wE(t)}`,r,rA)}async function QV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/activate`,{hash:r},rA)}async function PV(e,t,r,n){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/attributions`,{hash:r,attributions:n},rA)}async function MV(e,t,r,n){return BV(n,"paymentResourceId","Pass the payment record resourceId."),ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/payments`,{hash:r,paymentResourceId:n},rA)}async function UV(e,t,r,n){return BV(r,"childResourceId","Pass the payment record resourceId from the children list."),ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}/children/${encodeURIComponent(r)}`,{hash:n},rA)}async function $V(e,t,r){return ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}`,{hash:r},rA)}async function qV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/unbatch`,{hash:r},rA)}async function jV(e,t){return BV(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),ip(e,"POST",gwr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,ya)}var Awr,gwr,NV,Mst,Ust,rA,Yme=J(()=>{"use strict";Ki();tr();lP();ot();Awr="/api/v1/unapplied-payments",gwr="/api/v1/reconciliations/unapplied-payment",NV=["SALE","PURCHASE"],Mst=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ust=["AMOUNT","PERCENTAGE"];rA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function YV(e,t,r={},n=Hme){let i=ywr.has(t)?`/api/v1/${Sc($st,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=Hg.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...Hg.keys()].join(", ")}.`);let A=await Df(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...et,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new ue(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...VB].join(", ")}.`}:d}var $st,ywr,Hme,VB,qst,zme=J(()=>{"use strict";tr();ot();Mx();Yu();$st=["statement-of-account-export"],ywr=new Set($st),Hme=9e4,VB=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),qst={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as Ewr}from"node:crypto";import{writeFile as bwr,mkdir as Iwr}from"node:fs/promises";import{dirname as Cwr,isAbsolute as _wr,join as wwr}from"node:path";async function HV(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},et)}async function WB(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function ev(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function jst(e){return`query-export-${e.slice(0,8)}.csv`}function Jme(e){return Ewr("sha256").update(e).digest("hex").slice(0,16)}async function zV(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Jme(t),o=await WB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await ev(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await ev(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!_wr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??wwr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Iwr(Cwr(p),{recursive:!0}),await bwr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function JV(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new ue(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function tv(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var Gme=J(()=>{"use strict";ot();tr()});async function Ei(e,t,r){let n=await e.get(`/api/v1/${Vme[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function GV(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${Vme[r]}/${n}/attachments`,o)}async function VV(e,t,r,n){return e.delete(`/api/v1/${Vme[t]}/${r}/attachments/${n}`)}var Vme,KB,nA=J(()=>{"use strict";Vme={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders"},KB=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function kwr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&xwr.some(n=>r.startsWith(n)))}async function op(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&kwr(t)&&(t.refusal=Twr),t}}function Yst(e,t,r){return Zi(e,t,r),e.toLowerCase()}function rv(e,t){return{type:Sc(Wme,e,"entityType"),record:Yst(t,"entityId",vwr)}}function XB(e){DZ(e,"threadId",Dwr)}function Hst(e){DZ(e,"commentId",Rwr)}function nv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Yst(e.bankAccountResourceId,"bankAccountResourceId",Swr)}}async function zst(e,t,r,n={}){let{type:i,record:o}=rv(t,r),s={...nv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return op(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Jst(e,t,r,n,i={}){let{type:o,record:s}=rv(t,r),a={...nv(i),limit:i.limit,offset:i.offset};return XB(n),op(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Gst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return n.threadId!==void 0&&XB(n.threadId),(await op(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...Yke,query:a}))).data}async function Vst(e,t,r,n,i,o,s){let{type:a,record:c}=rv(t,r),u=nv(s);return XB(n),Hst(i),(await op(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function Wst(e,t,r,n,i,o){let{type:s,record:a}=rv(t,r),c=nv(o);return XB(n),Hst(i),(await op(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function Kst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return XB(n),(await op(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function Xst(e,t={}){return op(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function Zst(e,t,r){return HNe(t,"Get it from list_notifications."),(await op(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function eat(e){return(await op(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Wme,vwr,Swr,Dwr,Rwr,Twr,xwr,tat=J(()=>{"use strict";Ki();ot();tr();Wme=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],vwr="Pass the resourceId of the bill, invoice, credit note or bank record.",Swr="Pass the resourceId of the bank account that holds the bank record.",Dwr="Get it from list_comment_threads.",Rwr="Get it from list_comments or list_comment_threads.",Twr={code:"USER_CREDENTIAL_REQUIRED",hint:"Comments and notifications act as a user, so the credential must name an active member of the organization. A service or organization key with no user is refused with this 401. Use a user credential: sign in with `clio auth login`, a personal access token, or an API key a member created."},xwr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Qo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var iv=J(()=>{"use strict"});async function WV(e,t){return e.post("/api/v1/claims/conversion/preview",t,et)}async function KV(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new ue('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:AP)}var ZB,Kme=J(()=>{"use strict";ot();tr();ZB=["POST","POST_AND_RECORD"]});async function XV(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,Qke)}async function ZV(e,t){return e.search("/api/v1/employees/payouts/search",t)}var rat,Xme=J(()=>{"use strict";ot();tr();rat=["REIMBURSEMENT","ADVANCE"]});async function e8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Zme=J(()=>{"use strict"});function eAe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function tAe(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${nat(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>Pu.has(u)),s=i.filter(u=>!Pu.has(u)&&Rc.has(u)),a=[`Nothing here can be extracted: found ${nat(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=KBe[u];d&&a.push(d)}return o.length>0&&a.push(`${eU(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${eU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Pu.has(u)&&!Rc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${eU([...Pu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function nat(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var iat=J(()=>{"use strict";Mu()});function t8(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function eO(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&t8()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function vE(e,t){return{error:e,hint:t,...rAe}}function oat(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${eO(e)}.`,...rAe}}function SE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function iA(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${eO({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...rAe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var rAe,sat=J(()=>{"use strict";rAe={kind:"validation",retriable:!1}});import{randomUUID as Nwr}from"node:crypto";import{rmSync as Bwr}from"node:fs";function iAe(e){for(let t of e.tempDirs??[])try{Bwr(t,{recursive:!0,force:!0})}catch{}}function cat(e){for(let[t,r]of DE)e-r.createdAt>aat&&(iAe(r.plan),DE.delete(t))}function Fwr(){nAe||(nAe=setInterval(()=>cat(Date.now()),Owr),nAe.unref?.())}function oAe(e,t){let r=Date.now();cat(r),Fwr();let n=`dc_${Nwr()}`;return DE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function sAe(e,t){let r=DE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>aat?(iAe(r.plan),DE.delete(e),null):r.plan}function lat(e,t){let r=DE.get(e);!r||r.ownerKey!==t||(iAe(r.plan),DE.delete(e))}var aat,Owr,DE,nAe,uat=J(()=>{"use strict";aat=1800*1e3,Owr=300*1e3,DE=new Map});function Lwr(e){if(!e||typeof e!="object")return{};let t=e,r=t.validFiles?.[0],n=r?.workflowResourceId??t.workflowResourceId;return{...n?{workflowId:n}:{},...r?.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},...r?.subscriptionFBPath?{subscriptionFBPath:r.subscriptionFBPath}:{},...r?.backgroundJobFBPath?{backgroundJobFBPath:r.backgroundJobFBPath}:{}}}function dat(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>_g(i.documentType)&&r.has(i.documentType))}))}}async function fat(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?dat(t,i):t;if(!n&&Qwr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");vD(o);let a=await mU({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,...d.status==="uploaded"?Lwr(d.response):{},error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function pat(e,t){return(t&&t.length>0?dat(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>_g(o.documentType)).length,0)}function Qwr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var hat=J(()=>{"use strict";nee();Mu();Af()});function Pwr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function Uwr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function $wr(e,t){if(e!==Mwr)return;let r=Uwr(t);if(r)return mat.get(r)??mat.get(r.replace(/_ERROR$/,""))}function r8(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function qwr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=r8(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function aAe(e){return $wr(e.status,e.body)??e.refusal?.hint??qwr(e)}function RE(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function n8(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function tO(e,t={}){let r=t.readOnly===!1&&PD()?PFe:"";if(e instanceof gr){let o=[aAe(e)??Pwr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...r8(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=i8(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof ct;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var Mwr,mat,TE=J(()=>{"use strict";Ki();fo();o8();bU();Mwr=422,mat=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});async function md(e,t,r){if(!t)return e;let n=jwr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}async function Ad(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${RE(i)}`],...n}}}function jwr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function sp(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var Aat=J(()=>{"use strict";TE()});async function s8(e,t){return e.list("/api/v1/bank-rules",t)}async function rO(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function a8(e,t){return e.search("/api/v1/bank-rules/search",t)}async function c8(e,t){return e.post("/api/v1/bank-rules",t)}async function l8(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function u8(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var cAe=J(()=>{"use strict"});async function d8(e,t){return e.list("/api/v1/fixed-assets",t)}async function xE(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function nO(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function f8(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},iZ)}function yat(e,t){let r={};for(let n of Ywr){let i=e[n];if(i==null)continue;let o=Hwr.has(n)?cf(i):i;o!==void 0&&(r[n]=o)}for(let[n,i]of Object.entries(t))i!==void 0&&n!=="resourceId"&&(r[n]=i);return r}async function p8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ut(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await xE(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,yat(i,r))}async function h8(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function m8(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},hP)}async function iO(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,hP)}async function A8(e,t){return e.post("/api/v1/transfer-fixed-assets",t,iZ)}async function g8(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},hP)}async function y8(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},oZ)}async function E8(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},oZ)}async function zwr(e,t){let r=new Map;for(let i=0;i<t.length;i+=gat){let o=t.slice(i,i+gat),s=await nO(e,{filter:{resourceId:{in:o}},limit:o.length});for(let a of s.data)r.set(a.resourceId,a)}let n=t.filter(i=>!r.has(i));if(n.length>0)throw ut(new ue(`No fixed asset found for ${n.length} resourceId${n.length===1?"":"s"}: ${n.join(", ")}. Nothing was submitted; fix or remove those rows and retry.`));return r}async function b8(e,t){mt(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=HS(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw ut(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw ut(new ue(`resourceId ${u} appears more than once in fixedAssets; put all of an asset's changes in one row. Nothing was submitted.`));return r.add(u),u}),i=t.map((a,c)=>Xn(a.tags,`fixedAssets[${c}].tags`)),o=await zwr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...yat(u,{...a,tags:d&&ui(u.tags,d)})}});return En(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function I8(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function C8(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function _8(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,et)}async function w8(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},et)}async function v8(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function S8(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function D8(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function Gwr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function Vwr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=Gwr(i);if(o.length===0)return;let s=typeof i.reference=="string"&&i.reference?` (${i.reference})`:"";t.push(`row ${n}${s}: ${o.map(a=>`${a} (${Jwr[a]})`).join(", ")}`)}),t.length>0)throw ut(new ue(`Every fixed asset row needs its reference, registrationType and depreciationStartDate; the import job rejects a row without them. Missing: ${t.join("; ")}. Nothing was sent.`))}async function R8(e,t){return mt(t,"fixedAssets",500,"fixed assets"),SNe(t,["purchaseDate","depreciationStartDate"]),Vwr(t),En(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var oA,Ywr,Hwr,gat,Jwr,T8=J(()=>{"use strict";an();KS();tr();ot();xl();oA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];Ywr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],Hwr=new Set(["purchaseDate","depreciationStartDate"]);gat=100;Jwr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function x8(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function kE(e,t){return e.get(`/api/v1/leases/${t}`)}async function k8(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},Uke)}async function N8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names lease ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await kE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function B8(e,t){await e.delete(`/api/v1/leases/${t}`)}async function O8(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},qS)}async function F8(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},qS)}async function L8(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},qS)}async function Q8(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},et)}async function P8(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},qS)}async function M8(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function U8(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function $8(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function q8(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,et)}async function j8(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,et)}async function Y8(e,t){return mt(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`leases[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that lease. Bulk update does not take tags: change them with update_lease (clio leases update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/leases/bulk-update","leases",t)}var lAe=J(()=>{"use strict";an();ot();tr()});async function H8(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function NE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function z8(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Jp)}async function J8(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await NE(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw Wwr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function Wwr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function G8(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function V8(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function W8(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var K8=J(()=>{"use strict";tr()});async function X8(e,t){return e.list("/api/v1/contact-groups",t)}async function Z8(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function eW(e,t){return e.search("/api/v1/contact-groups/search",t)}async function tW(e,t){return e.post("/api/v1/contact-groups",t)}async function rW(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,TI(r,hZ))}async function nW(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var uAe=J(()=>{"use strict";an()});async function iW(e,t){return e.list("/api/v1/inventory-items",t)}async function oW(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function sW(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function cW(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&Kwr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var aW,Kwr,dAe=J(()=>{"use strict";Ki();aW=["ALL","AVAILABLE","FULLY_DRAWN"],Kwr=/Inventory balance Not Found/i});async function lW(e,t){return e.list("/api/v1/custom-fields",t)}async function oO(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function uW(e,t){return e.search("/api/v1/custom-fields/search",t)}async function dW(e,t){return e.post("/api/v1/custom-fields",t)}function Zwr(e){return e!==void 0&&Xwr.every(t=>e[t]!==void 0)}function evr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function tvr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function fW(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!Zwr(n.appliesTo)){let i=await oO(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??tvr(i.data),n.appliesTo={...evr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function pW(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var Xwr,fAe=J(()=>{"use strict";Xwr=["invoices","bills","customerCredits","supplierCredits","payments"]});var el,BE,rvr,nvr,pAe,hW,mW,ivr,Ta,ru,OE,ov,FE,hAe=J(()=>{"use strict";el={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217). Required whenever this settings object is sent."}},required:["sourceCurrencyCode"]},BE={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field. Required unless resourceId is given; when resourceId is given, the organization's own name for that field is stored instead of this one."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition. Required unless customFieldName is given. When omitted, the field is matched by customFieldName (case-insensitive) and linked only if exactly one active custom field in the organization has that name."}}},rvr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},nvr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},pAe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},hW={type:"object",properties:{billingAddress:{...pAe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},mW={type:"object",properties:{billingAddress:{...pAe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...pAe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},ivr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Ta={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:ivr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},ru={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},OE={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},ov={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:BE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...rvr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...nvr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...hW,description:"Issuer identity and billing address (credit from)."},creditTo:{...mW,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:BE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},FE={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}}}});function AAe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function gAe(e){let t=e.updated??[],r=AAe(e.failed);return{...t.length===0&&r.length>0?{error:avr}:{},updated:t,failed:r}}function bat(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function AW(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Iat(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=bat(s);if(a)for(let c of Array.isArray(o)?o:[o])AW(c)&&n.push(...Iat(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function cvr(e){return Object.entries(e).map(([t,r])=>{let n=bat(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function yAe(e,t,r){if(!AW(t))return;let n=Iat(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw ut(new ct(`${e} has no field ${i.join("; ")}. Fields: ${cvr(r)}. Nothing was changed.`))}function lvr(e){let t=ov[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function uvr(e){let t=FE[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function dvr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!AW(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw ut(new ct(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!AW(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw ut(new ct(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));yAe(`${e} line items`,a.attributes,t.fields)}}}function Cat(e){if(sv.includes(e))return;let t=yW.includes(e);throw ut(new ct(t?`${e} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${e} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${e} has no quick fix route. Transaction-level entities: ${sv.join(", ")}.`))}async function cv(e,t,r){Cat(t),yAe(`${t} quick fix`,r.attributes,lvr(t));let n=await e.post(`/api/v1/quick-fix/${Sc(sv,t)}`,r);return gAe(n)}async function fvr(e,t){try{return await IE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return CE(e,t);throw r}}async function _at(e,t,r,n){Cat(t);let i=EAe[t],o=async d=>i.tags(await Xi(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Eat)s.push(...await Promise.all(r.resourceIds.slice(d,d+Eat).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=ui(s[f],n),h=JSON.stringify(p);a.set(h,{tags:p,resourceIds:[...a.get(h)?.resourceIds??[],d]})});let c=[],u=[];for(let{tags:d,resourceIds:f}of a.values())try{let p=await cv(e,t,{resourceIds:f,attributes:{...r.attributes,tags:d}});c.push(...p.updated),u.push(...p.failed)}catch(p){if(c.length===0)throw p;u.push(...f.map(h=>({resourceId:h,error:p instanceof Error?p.message:String(p)})))}return gAe({updated:c,failed:u})}async function sO(e,t,r){let n=Sc(av,t),i=uvr(t);i.entryKeys?dvr(t,i,r.schedulerUpdates):yAe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return gAe(o)}var ovr,svr,gW,yW,sv,av,avr,LE,mAe,EAe,Eat,EW=J(()=>{"use strict";Ki();ot();fo();hAe();xl();zg();af();Hx();Kx();Jg();ZG();dV();K8();ovr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],svr=["journals","cash-entries"],gW=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],yW=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],sv=[...ovr,...svr,...gW],av=[...sv,...yW],avr="Nothing changed: every record failed. See failed for each reason.";LE=e=>e?.tags,mAe=e=>e?.data?.tags,EAe={invoices:{noun:"invoice",get:(e,t)=>Eo(e,t),tags:LE},bills:{noun:"bill",get:(e,t)=>ho(e,t),tags:LE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>Vs(e,t),tags:LE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>Ws(e,t),tags:LE},journals:{noun:"journal",get:(e,t)=>vs(e,t),tags:LE},"cash-entries":{noun:"cash entry",get:(e,t)=>fvr(e,t),tags:LE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Vw(e,t),tags:mAe},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Ww(e,t),tags:mAe},"subscription-schedules":{noun:"subscription",get:(e,t)=>NE(e,t),tags:mAe},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Kw(e,t),tags:LE}},Eat=10});function bW(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=bW(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<hvr&&i.length<=mvr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,bW(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function vat(e,t,r){let n=Avr(t);if(!n)return[];let i=gvr(r);if(!i){if(wat[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?vat(o,s,i[o]):[])}function yvr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function bAe(e,t,r={}){let n=Object.keys(e),i=[...new Set(n.flatMap(c=>Object.keys(e[c])))].sort(),o={},s=new Map;for(let c of i){let u=n.filter(y=>e[y][c]),d=new Map;for(let y of u){let b=Evr(e[y][c]);d.set(b,[...d.get(b)??[],y])}let[[,f],...p]=[...d].sort((y,b)=>b[1].length-y[1].length),{description:h,...m}=r[c]??bW(e[f[0]][c]),A=p.length&&m.properties&&!r[c]?{...m,required:void 0,properties:Object.assign({},...[f,...p.map(([,y])=>y)].map(y=>bW(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[wat[c],yvr(u,n),...p.map(([,y])=>{let b=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(b.properties??b.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[b,E]of vat(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(b))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function Tat(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>pvr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var pvr,wat,hvr,mvr,Avr,gvr,Evr,bvr,Ivr,lv,Sat,Dat,Rat,xat,kat,Nat,IAe=J(()=>{"use strict";hAe();xl();pvr={valueDate:"date",dueDate:"due date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},wat={currencySettings:"sourceCurrencyCode alone takes the platform rate (not on schedules); add rateFunctionalToSource to set one.",taxCurrencySettings:"Cash entries: sourceCurrency; every other record: sourceCurrencyCode, always sent.",tags:`${Yo.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}."},hvr=2,mvr=8;Avr=e=>e.properties??e.items?.properties,gvr=e=>e.properties??e.items?.properties;Evr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),bvr={tags:Yo};Ivr=Object.entries(FE).filter(([,e])=>!e.entryKeys),lv=Object.entries(FE).filter(([,e])=>e.entryKeys),Sat=bAe({...ov},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",bvr),Dat=bAe(Object.fromEntries(Ivr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),Rat=(()=>{let e=n=>lv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=lv[0],r=[...new Set(lv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>lv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${lv.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:bAe(Object.fromEntries(lv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();xat=[...new Set([...Object.keys(ov),...Object.keys(FE)])].map(e=>e.replace(/-/g," ")).join(", "),kat=Tat(Object.values(ov)),Nat=Tat(Object.values(FE).map(e=>e.fields))});function IW(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var CAe=J(()=>{"use strict"});function _W(){return sA.map(e=>`${e} sets ${dv[e].change.join(", ")}`).join("; ")}function Uat(e){let t={};for(let r of e)t[r]=Object.hasOwn(Oat,r)?Oat[r]:wvr.find(([n])=>n.test(r))?.[1]??vvr;return Object.keys(t).length>0?t:void 0}function $at(e){if(!(e instanceof gr)||!e.endpoint.startsWith(_vr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Fat,n))return;let{hint:i,repairTool:o,command:s}=Fat[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Pat.LINE_ITEMS?"line items":"records",...e.endpoint===CW?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function Rvr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function Tvr(e){return typeof e=="string"&&sA.includes(e)}function xvr(e,t){if(!Tvr(e))throw new ct(`level must be one of ${sA.join(", ")}.`);let r=sA.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))dv[e][i].includes(s)||n.push(dv[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=dv[e];throw new ct(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Lat(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new ct(`${e} must be a JSON object, not ${n}.`)}async function vW(e,t,r){let n={filter:Lat("filter",r.filter),change:Lat("change",r.change)};xvr(t,n);let i;try{i=await e.post(Pat[t],{filter:n.filter,change:n.change},et)}catch(u){throw $at(u),u}let{data:o,...s}=i,a=Uat([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=Rvr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function wAe(e,t){return{error:`${t} ${jat}`,outcome:"UNKNOWN",previewId:e,next:qat}}function Bvr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return wAe(e,"The apply answered without a per-record result.");let i=AAe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=Uat(Object.keys(o)),a=o[Svr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Nvr}:a==="UNKNOWN"?{error:jat}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?qat:kvr},failed:i.slice(0,_Ae),...i.length>_Ae?{failedNotShown:i.length-_Ae}:{},data:r}}async function SW(e,t,r=Dvr){let n;try{n=await e.post(CW,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=$at(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw ut(i);return wAe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof zp)throw ut(i);let o=i instanceof Error?i.message:String(i);return wAe(t,`No answer arrived from the apply (${o}).`)}return Bvr(t,n)}var Qat,sA,Pat,CW,_vr,Mat,Bat,dv,Oat,wvr,vvr,Svr,Dvr,wW,_Ae,fv,lon,uv,Fat,qat,kvr,Nvr,jat,vAe=J(()=>{"use strict";Ki();EW();lP();ot();fo();tr();CAe();Qat=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],sA=["TRANSACTIONS","LINE_ITEMS"],Pat={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},CW="/api/v1/ledger/find-fix/apply",_vr=CW.slice(0,CW.lastIndexOf("/")+1),Mat={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},Bat=["types","resourceIds","reference","valueDate","contactResourceId"],dv={TRANSACTIONS:{filter:Bat,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Bat,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Oat={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},wvr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],vvr="Not described by this client version; read the records that carry it.";Svr="OUTCOME_UNKNOWN",Dvr=25e3,wW=3e5,_Ae=50,fv=12,lon=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${fv}}(?![A-Za-z0-9_-])`,"i"),uv=e=>e.resourceId?` (${e.resourceId})`:"",Fat={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${uv(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${uv(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${uv(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${uv(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${uv(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${uv(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};qat="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",kvr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",Nvr="Nothing changed: every record in the preview failed.",jat="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function DW(e,t){return e.list("/api/v1/nano-classifiers",t)}async function QE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function RW(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function aO(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function cO(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function TW(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Ovr(e,t):{};let{data:n}=await QE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Hat(n)}async function Ovr(e,t){let{data:r}=await QE(e,t);return Hat(r)}function Hat(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function xW(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var Yat,SAe=J(()=>{"use strict";Yat=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function kW(e,t){return e.post("/api/v1/export-records",t,et)}async function NW(e,t){return e.post("/api/v1/export-records/preview",t,et)}async function BW(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var DAe=J(()=>{"use strict";tr()});function OW(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Vat(e,t,r,n=!1){if(!Array.isArray(e))throw new ue(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new ue(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new ue(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new ue(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function FW(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function LW(e,t,r){return OW(t,Jat),Zi(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Sc(ap,t)}/${encodeURIComponent(r)}/approve`,void 0,Oke)}async function QW(e,t,r){return OW(t,Jat),Vat(r,Fvr,"bulk approve",!0),r.forEach(n=>Zi(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Sc(ap,t)}/bulk-approve`,{resourceIds:r},Fke)}async function PW(e,t,r,n){OW(t,Gat),Zi(r,"resourceId","Pass the document resourceId."),Wat(n);let i=await e.post(`/api/v1/${Sc(PE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Pvr(i)}}}async function MW(e,t,r,n){return OW(t,Gat),Wat(n),Vat(r,Lvr,"bulk request changes"),r.forEach(i=>Zi(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(Qvr(t),{resourceIds:r,message:n})}function Qvr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Sc(zat,e)}/bulk-request-changes`}function Wat(e){if(!e||e.trim().length===0)throw new ue("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function Pvr(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ap,zat,PE,Jat,Gat,Fvr,Lvr,RAe=J(()=>{"use strict";ot();tr();ap=["invoices","bills","customer-credit-notes","supplier-credit-notes"],zat=[...ap,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],PE=[...zat,"claims"],Jat=new Set(ap),Gat=new Set(PE);Fvr=100,Lvr=500});function Mvr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${Kat(t)}:${Kat(r)}:${n}`}function Kat(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function TAe(e){if(!Xat.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...Xat].join(", ")}`)}async function Zat(e,t,r){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function ect(e,t,r,n){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function tct(e,t,r,n,i){if(TAe(t),Zi(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new ue('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??Mvr(t,r,n)}})}async function rct(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var Xat,nct=J(()=>{"use strict";ot();Xat=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function Uvr({fromPeriod:e,toPeriod:t},r){for(let[n,i]of[["fromPeriod",e],["toPeriod",t]])if(i!==void 0){if(!Number.isInteger(i)||i<1)throw new ct(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new ct("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new ct(`${n} ${i} is past the last period (${r}). Send a period from 1 to ${r}.`)}if(e!==void 0&&t!==void 0&&e>t)throw new ct(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function UW(e,t,r){let n=e.length;if(Uvr(t,e[n-1]),n===0)return{start:0,end:0,window:{totalPeriods:0}};let i=t.fromPeriod===void 0?0:e.filter(u=>u<t.fromPeriod).length,o=t.toPeriod===void 0?n:e.filter(u=>u<=t.toPeriod).length,s=o===0&&t.toPeriod!==void 0,a=s?Math.min(t.toPeriod-(t.fromPeriod??1)+1,n,r):Math.min(o,i+r);if(a<=i)throw new ct(`No period falls in that range: the schedule runs from period ${e[0]} to ${e[n-1]}.`);let c={totalPeriods:n,fromPeriod:e[i],toPeriod:e[a-1]};if(i>0||a<n){let u=[`Showing periods ${e[i]} to ${e[a-1]} of ${n}.`];a<n&&u.push(`Periods ${e[a]} to ${e[n-1]} are not shown: call again with fromPeriod ${e[a]} to read the next range (at most ${r} periods come back per call).`),i>0&&u.push(`Periods ${e[0]} to ${e[i-1]} are not shown: call again with fromPeriod ${e[0]} to read them.`),c.note=u.join(" ")}return s&&(c.note=`Periods ${t.fromPeriod??1} to ${t.toPeriod} come before this schedule, which starts at period ${e[0]}. Showing the first periods instead. ${c.note??""}`.trim()),{start:i,end:a,window:c}}function pv(e,t={},r=lO){let n=e.data,i=ME(n.rows),{start:o,end:s,window:a}=UW(xAe(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function $W(e,t={},r=lO){let n=e.data,i=ME(n.rows),o=h=>h.rowType==="PERIOD",s=i.findIndex(o),a=i.map(o).lastIndexOf(!0),c=s===-1?[]:i.slice(s,a+1),{start:u,end:d,window:f}=UW(xAe(c),t,r);if(s===-1)return{...e,data:{...f,...n}};let p=[...u===0?i.slice(0,s):[],...c.slice(u,d),...d===c.length?i.slice(a+1):[]];return{...e,data:{...f,...n,rows:p}}}function ict(e,t,r,n,i){let o=e.data,s=ME(o[t]),a=s.reduce((h,m)=>h+ME(m[r]).length,0),{start:c,end:u,window:d}=UW(Array.from({length:a},(h,m)=>m+1),n,i);if(a===0)return{...e,data:{...d,...o}};let f=0,p=[];for(let h of s){let m=ME(h[r]),A=m.slice(Math.max(c-f,0),Math.max(u-f,0));A.length>0&&p.push({...h,[r]:A}),f+=m.length}return{...e,data:{...d,...o,[t]:p}}}function gd(e,t={},r=lO){let n=e.data,i=ME(n.periods),{start:o,end:s,window:a}=UW(xAe(i,"period"),t,r);if(i.length===0)return{...e,data:{...a,...n}};let c=i[o].startDate,u=i[s-1].endDate,d=f=>typeof f.toDate!="string"||typeof f.fromDate!="string"||typeof c!="string"||typeof u!="string"||f.toDate>=c&&f.fromDate<=u;return typeof a.note=="string"&&(a.note+=" The timeline lists only the segments that touch these periods."),{...e,data:{...a,...n,periods:i.slice(o,s),timeline:ME(n.timeline).filter(d)}}}var lO,ME,xAe,qW,jW,hv=J(()=>{"use strict";fo();lO=60;ME=e=>Array.isArray(e)?e:[],xAe=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);qW=(e,t={},r=lO)=>ict(e,"depreciationScheduled","depreciation",t,r),jW=(e,t={},r=lO)=>ict(e,"amortizationScheduled","amortization",t,r)});async function UE(e,t){return e.get(`/api/v1/loans/${t}`)}async function YW(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function HW(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function zW(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},$ke)}async function JW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names loan ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await UE(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function GW(e,t){await e.delete(`/api/v1/loans/${t}`)}async function VW(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},sZ)}async function WW(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},sZ)}async function KW(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function XW(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function ZW(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function e4(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function t4(e,t){return e.post("/api/v1/loans/preview-schedule",t,et)}async function r4(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,et)}async function n4(e,t){return mt(t,"loans",500,"loans"),jo(t,oct),En(e,"/api/v1/loans/bulk-upsert","loans",t)}async function i4(e,t){return mt(t,"loans",500,"loans"),jo(t,$vr),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`loans[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that loan. Bulk update does not take tags: change them with update_loan (clio loans update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/loans/bulk-update","loans",t)}async function o4(e,t,r,n,i){let o=uO[t];if(i){if(!o.calculate)throw new Error(`Loan event ${t} has no preview.`);let s=Object.fromEntries(Object.entries(n).filter(([a])=>!o.recordOnly?.includes(a)));return e.post(o.calculate,{...s,resourceId:r},et)}return e.post(o.record(r),{...n,resourceId:r},qke)}var oct,$vr,uO,kAe=J(()=>{"use strict";an();ot();tr();oct=["drawdownDate","trackingStartDate","firstRepaymentDate"],$vr=[...oct,"capitalizationStartDate","capitalizationEndDate"];uO={drawdown:{calculate:"/api/v1/loans/calculate-drawdown",record:e=>`/api/v1/record-drawdown/loans/${e}`},prepayment:{calculate:"/api/v1/loans/calculate-prepayment",record:e=>`/api/v1/prepay/loans/${e}`},rateChange:{calculate:"/api/v1/loans/calculate-rate-change",record:e=>`/api/v1/change-rate/loans/${e}`},capitalization:{calculate:"/api/v1/loans/calculate-capitalization",record:e=>`/api/v1/capitalize-interest/loans/${e}`},paymentHoliday:{calculate:"/api/v1/loans/calculate-payment-holiday",record:e=>`/api/v1/payment-holiday/loans/${e}`},restructure:{calculate:"/api/v1/loans/calculate-restructure",record:e=>`/api/v1/restructure/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},settlement:{calculate:"/api/v1/loans/calculate-settlement",record:e=>`/api/v1/settle/loans/${e}`},forgiveness:{calculate:"/api/v1/loans/calculate-forgiveness",record:e=>`/api/v1/forgive/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},conversion:{calculate:"/api/v1/loans/calculate-conversion",record:e=>`/api/v1/convert-to-shares/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},refinance:{record:e=>`/api/v1/refinance/loans/${e}`},reclassifyAsCurrent:{record:e=>`/api/v1/reclassify-as-current/loans/${e}`},undo:{record:e=>`/api/v1/undo-event/loans/${e}`}}});function mv(e){mt(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new ue(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!BFe(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!qvr.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new ue(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function s4(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},et);return{data:Yvr(r.data)}}function jvr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function Yvr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(jvr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function a4(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function c4(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var qvr,NAe=J(()=>{"use strict";ot();iee();an();tr();qvr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function lct(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new ue("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function BAe(e,t){if(!e||typeof e!="object")throw new ue(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new ue(`${t}.lineItems array is empty.`);if(n.length>500)throw new ue(`max 500 ${t}.lineItems per call.`);jo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&jo([i],["valueDate"])}async function u4(e,t,r=OAe){return e.post("/api/v1/search-magic-reconciliation",t,{...et,timeoutMs:r})}function l4(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Gvr(e){let t=l4(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=l4(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function Vvr(e){return e?e.value>=(e.from==="confidenceScore"?Hvr:zvr)?"high":e.value>=Jvr?"medium":"low":"low"}function Kvr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(sct,t))return;let r=sct[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function aA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function act(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function Xvr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>act({account:aA(n?.account),taxProfile:aA(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!aA(e.contact)&&!aA(e.account)&&!aA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return act({contact:aA(e.contact),account:aA(e.account),taxProfile:aA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function uct(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>n0r(c,h??{},u.length-1,t)).sort(Zvr),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function Zvr(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function e0r(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return vc.test(t)?t:void 0}function t0r(e){let{recommendationId:t,...r}=e;return r}function r0r(e,t,r){return!t||!r?t:e===$E.learnedPrediction?{...t,recommendationId:r}:e===$E.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function n0r(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=l4(t.matchScore),s=l4(t.confidenceScore),a=Gvr(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=$E.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=$E.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let F=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,G=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,j=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;F&&G&&j&&(m=$E.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:F,predictedPayload:G,predictedPayloadSchemaVersion:j});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let F=t.actionShortcut??{},G=typeof F.resourceId=="string"?F.resourceId:void 0;G&&(m=$E.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=r0r(m,A,e0r(t)),y=m?Vvr(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==$E.withPayments||b,T=Kvr(t),D=!m||!g?"NO_PLAN":T?Wvr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",k=Xvr(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:g,confidenceTier:y,autoCommitEligible:D===void 0,...D?{checkpointReason:D}:{},...k?{proposedPosting:k}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:T===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(t0r(t))}`}}function i0r(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function o0r(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await ho(e,i):await Eo(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${RE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function dct(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,cct);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await nC(e,t,{filter:{resourceId:{in:u}},limit:cct}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${RE(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return i0r(u,f,await o0r(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function d4(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,ya)}async function f4(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,ya)}async function p4(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,ya)}async function h4(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,ya)}async function m4(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,ya)}async function A4(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,ya)}async function g4(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,ya)}async function y4(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,ya)}async function E4(e,t){return e.post("/api/v1/reconciliations/with-payments",t,ya)}async function b4(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,ya)}async function I4(e,t){return e.post("/api/v1/reconciliations/magic-match",t,ya)}async function C4(e,t){return e.post("/api/v1/reconciliations/reset",t)}var $E,OAe,Hvr,zvr,Jvr,Wvr,sct,cct,_4=J(()=>{"use strict";Rg();TE();ot();af();an();zg();tr();$E={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},OAe=6e4;Hvr=.9,zvr=.95,Jvr=.7;Wvr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},sct={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};cct=25});function ia(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Po(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:FAe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=FAe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=FAe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function FAe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function ts(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=ia(e,t,n),a=Po(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var xa,tl,vo,nu,fct=J(()=>{"use strict";xa=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],tl=[...xa],vo=xa.filter(e=>e.field!=="dueDate"),nu=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function yd(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=_c(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function w4(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=BI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var pct=J(()=>{"use strict";Vp()});var LAe=J(()=>{"use strict";fct();Vp();pct()});var dO,v4,rs,oo,QAe=J(()=>{"use strict";dO="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",v4=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],rs="If the result says it runs in the background, do not poll: its result arrives by itself.",oo=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${rs} PARTIAL_SUCCESS: errorDetails.`});function hct(e){return s0r.get(e)}function mct(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!S4.has(o));return n.length===0?[]:Mi.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Mi,S4,s0r,Ed=J(()=>{"use strict";QAe();IAe();Mi=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Thirteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights. Fixed asset register reports are in register_reports.",groups:["operational_reports","exports"]},{name:"register_reports",title:"Register Reports",description:"Register reports: fixed asset register summary by account, type, category or active/closed-out/disposed state (asset register roll-forward over a period), fixed asset register vs general ledger reconciliation (does the register agree with the GL), deferrals summary (prepaid and deferred revenue roll-forward) and deferrals reconciliation (does the prepaid register agree with the GL), lease register summary (IFRS 16 lease note, lease liability roll-forward) and lease register vs general ledger reconciliation (rent coded to the lease liability account). Loan reports: borrowings note summary, loan roll-forward, related-party (director, shareholder) loan balances, loan interest cost, maturity analysis (liquidity note), loan register vs ledger reconciliation.",groups:["register_reports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Tracking categories (nano classifiers; dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. For what-if questions and topics with no register; to keep a lease, loan, prepaid or deferred revenue use its register. Keywords: calculate, what-if, monthly payment, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate, set up to repeat every month.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"],channelToolsDescription:"Check the progress of background tasks a request started, add to a waiting one, or cancel it."},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update (one or bulk), discard, sell, transfer, undo disposal, close out (stop depreciating, keep the asset) and reopen. Also: depreciation, asset register. Depreciation schedules, totals, eligible bill lines and asset types are in fixed_asset_schedules.",groups:["fixed_assets"]},{name:"fixed_asset_schedules",title:"Fixed Asset Schedules & Totals",description:"Read-only fixed asset views. Show one asset's depreciation by month and year, net book value, asset register totals as at a date, disposal totals (gain/loss), eligible bill lines to register as assets, asset types. Check custom depreciation ranges; calculate disposal (accumulated depreciation, net book value) before selling or discarding.",groups:["fixed_asset_schedules"]},{name:"deferrals",title:"Deferrals (Prepaid & Deferred Revenue)",description:"Deferrals register: prepaid expense, prepayment, deferred revenue, unearned revenue. Spread a bill over months, recognise an invoice over months (amortization, release schedule). Search, create, update, delete, stop amortising early (close out) and undo it, totals as at a date, schedule, eligible bill or invoice lines, deferral types and deferral accounts (mark the accounts first), bulk create and update.",groups:["deferrals"]},{name:"leases",title:"Leases (IFRS 16)",description:"Leases under IFRS 16: put an office rent lease on the books (right-of-use asset, ROU, and lease liability, current and non-current), hire purchase (flat rate to monthly discount rate), short-term or low-value exemption. Search, create, update, delete, close out, terminate lease (preview the gain or loss first) and undo either; lease schedule, liability totals as at a date, rent schedule preview, lease types.",groups:["leases"]},{name:"loans",title:"Loans (Borrowings)",description:"Loans and borrowings register: record a new bank loan, loan, borrowing, bank loan, term loan, director's loan, overdraft, revolving facility, instalment / installment loan. Search, create, update (one or bulk), delete, close out. What do we owe a lender or the bank: outstanding principal, current and non-current at a date, the repayment schedule, an on-demand loan ledger (an on-demand loan has no schedule, is all current and posts no interest), loan types, preview the monthly payment. Loan changes (drawdown, prepay, rate change, settle) are in loan_events; loan reports are in register_reports.",groups:["loans"]},{name:"loan_events",title:"Loan Events",description:"Events on an existing loan: drawdown, prepay or extra repayment, rate change, payment holiday, capitalize interest, restructure, refinance, settle / payoff, forgive / write off a loan, convert loan to shares, covenant breach (reclassify as current), undo loan event, balance after a missed payment. preview: true calculates the figures and saves nothing.",groups:["loan_events"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${xat}. On a record: ${kat}. On lines: ${Nat}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${v4.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"collab",title:"Collaboration",description:"Comment threads on bills, invoices, credit notes and bank records: list threads and comments, add a reply or start a thread, mention a teammate, update or delete your own comment, resolve a thread. Notifications: list unread mentions and comments, mark one read or unread, mark all read.",groups:["collaboration"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],S4=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),s0r=new Map(Mi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function bd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function a0r(e){let t=Act.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(bd(r),n);for(let r of e.enum??[])t.set(bd(r),r);Act.set(e,t)}return t}function gct(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=bd(e);if(!r)return null;let n=a0r(t).get(r);return n!==void 0&&n!==e?n:null}function c0r(e){let t=yct.get(e);return t||(t=new Map(Object.keys(e).map(r=>[bd(r),r])),yct.set(e,t)),t}function l0r(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function u0r(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function PAe(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=c0r(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=bd(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?l0r(d):u0r(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=gct(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=gct(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=fee(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=PAe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=PAe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Ect(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:PAe(t,e.params,"",r),coercions:r}}function bct(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var Act,yct,MAe=J(()=>{"use strict";NU();Act=new WeakMap;yct=new WeakMap});function Av(e){let t=new Set,r=[];for(let n of e)for(let i of iu(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function fO(){return Mi.map(e=>{let t=Av(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function d0r(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function f0r(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function cA(e,t=!1){let r=lA(void 0).length,n=Mi.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:f0r(r)}:e&&i!==void 0?{packaging:d0r(e,i,r)}:{},map:fO(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var D4=J(()=>{"use strict";Ed();ou()});function R4(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=R4(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=R4(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function su(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=R4(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function pO(e){return{name:e.name,description:e.description,input_schema:su(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var gv=J(()=>{"use strict"});function hO(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function UAe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function T4(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&hO(e),idempotentHint:e.readOnly,openWorldHint:UAe(e)}}function h0r(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function m0r(e){let t=h0r(e);return!t||p0r.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!S4.has(n)).length===0}function $Ae(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function qAe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?qAe(o,`${i}.`):[]]})}function g0r(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
662
+ `)),null)}catch{return null}}async function zB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??z_r,c=n.minBm25??J_r;if(i==="bm25"||!t)return _E(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Nme(r);return m?Est(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):_E(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Nme(r),Promise.resolve(_E(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Est(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Cst(p,h,o)}function Est(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=bst(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Cst(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Ast+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(Ast+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function Bme(e){return e!==null&&!!Ist()}var Y_r,H_r,Ast,z_r,J_r,pV,gst,hV,yst,mV=J(()=>{"use strict";YB();Y_r="text-embedding-3-small",H_r=2e3,Ast=60,z_r=.3,J_r=1.5,pV=null,gst=null,hV=null,yst=!1});async function _st(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=qB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:HB(),u=await zB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(xme(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function wst(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:V_r}async function AV(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(wst())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(W_r),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return K_r(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function K_r(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Ome(e,t={}){return process.env.CLIO_DAEMON==="1"||jB()?_st(e,t):AV(e,t)}var V_r,W_r,vst=J(()=>{"use strict";YB();mV();V_r="https://mcp.jaz.ai/help-center/search",W_r=4e3});var Fme=J(()=>{"use strict";YB();mV();vst();YB()});async function eA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function tA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var JB=J(()=>{"use strict";an()});async function gV(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency)},zke)}var Lme=J(()=>{"use strict";ot();tr()});async function yV(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function EV(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function GB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function bV(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Qme=J(()=>{"use strict"});function X_r(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Xw(e,t){return e.post("/api/v1/jots",{entries:t.map(X_r)})}async function IV(e,t){return e.post("/api/v1/jots/search",t,et)}async function Sst(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var CV=J(()=>{"use strict";tr()});async function Dst(e,t){return e.post("/api/v1/agents/memories",t)}async function Pme(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Rst=J(()=>{"use strict";tr()});function _V(){return process.env.ENABLE_MEMORY==="true"}function Mme(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Tst(e){return!_V()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Ume=J(()=>{"use strict"});import{createHash as Z_r}from"node:crypto";function uwr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:Nst.some(r=>t.includes(r))?[null,"directive_invalid"]:kst.test(t)?[null,"directive_invalid"]:owr.test(t)?[null,"directive_contains_url"]:swr.test(t)?[null,"directive_contains_email"]:[t,null]}function dwr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>awr?[null,"match_condition_too_long"]:Nst.some(r=>t.includes(r))?[null,"match_condition_invalid"]:kst.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function fwr(e){return e==null?[null,null]:Number.isInteger(e)?e<cwr||e>lwr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function pwr(e,t,r,n,i,o,s,a){if(e)return Z_r("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function hwr(e){Promise.resolve().then(()=>(mD(),hD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Lst(e,t,r){let n=t.action,i=t.category,o=nwr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(hwr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Tst(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>ewr||!iwr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=uwr(t.directive);if(E)return u(E);p=b;let[C,w]=fwr(t.importance);if(w)return u(w);h=C}let[m,A]=dwr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=twr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,rwr));let E=pwr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await $me(()=>Dst(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await $me(()=>Pme(e.client,b))}else{let b={forgetAll:!0};y=await $me(()=>Pme(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function $me(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof gr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var kst,Nst,ewr,twr,rwr,Bst,Ost,Fst,nwr,iwr,owr,swr,awr,cwr,lwr,Qst=J(()=>{"use strict";Rst();Ki();Ume();Ume();kst=/[\x00-\x1f\x7f]/,Nst=["{{","}}","```","<",">"],ewr=120,twr=3,rwr=140,Bst=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Ost=["set","forget","forget_all"],Fst=["this_org","all_orgs"],nwr={this_org:"ORG_USER",all_orgs:"USER"},iwr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,owr=/https?:\/\//i,swr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,awr=255,cwr=0,lwr=100});async function wV(e,t){return e.list("/api/v1/organization-users",t)}async function vV(e,t){return e.search("/api/v1/organization-users/search",t)}async function Zw(e,t){return e.post("/api/v1/organization-users/invite",t)}async function SV(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function DV(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var qme=J(()=>{"use strict"});async function RV(e,t){return e.get(`/api/v1/payments/${t}`)}async function TV(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Wt(r.currency)})}async function xV(e,t){await e.delete(`/api/v1/payments/${t}`)}function kV(e){return(t,r)=>t.post(`/api/v1/${mwr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Wt(n.currency)}))},Lke)}var mwr,Cnn,Pst,_nn,wnn,jme=J(()=>{"use strict";ot();tr();mwr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};Cnn=kV("saleBulk"),Pst=kV("saleBatch"),_nn=kV("purchaseBulk"),wnn=kV("purchaseBatch")});async function ip(e,t,r,n,i,o=Hke){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof gr?c.status<500&&c.status!==401?ut(c):new rf(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof zp?ut(c):c}let a=s?.data;if(!i(a))throw new rf(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function BV(e,t,r){try{Zi(e,t,r)}catch(n){throw ut(n)}}function wE(e){return BV(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function OV(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function FV(e,t){return ip(e,"POST",Awr,t,rA)}async function LV(e,t,r){return ip(e,"PUT",`/api/v1/unapplied-payments/${wE(t)}`,r,rA)}async function QV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/activate`,{hash:r},rA)}async function PV(e,t,r,n){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/attributions`,{hash:r,attributions:n},rA)}async function MV(e,t,r,n){return BV(n,"paymentResourceId","Pass the payment record resourceId."),ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/payments`,{hash:r,paymentResourceId:n},rA)}async function UV(e,t,r,n){return BV(r,"childResourceId","Pass the payment record resourceId from the children list."),ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}/children/${encodeURIComponent(r)}`,{hash:n},rA)}async function $V(e,t,r){return ip(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}`,{hash:r},rA)}async function qV(e,t,r){return ip(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/unbatch`,{hash:r},rA)}async function jV(e,t){return BV(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),ip(e,"POST",gwr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,ya)}var Awr,gwr,NV,Mst,Ust,rA,Yme=J(()=>{"use strict";Ki();tr();lP();ot();Awr="/api/v1/unapplied-payments",gwr="/api/v1/reconciliations/unapplied-payment",NV=["SALE","PURCHASE"],Mst=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ust=["AMOUNT","PERCENTAGE"];rA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function YV(e,t,r={},n=Hme){let i=ywr.has(t)?`/api/v1/${Sc($st,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=Hg.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...Hg.keys()].join(", ")}.`);let A=await Df(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...et,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new ue(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...VB].join(", ")}.`}:d}var $st,ywr,Hme,VB,qst,zme=J(()=>{"use strict";tr();ot();Mx();Yu();$st=["statement-of-account-export"],ywr=new Set($st),Hme=9e4,VB=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),qst={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as Ewr}from"node:crypto";import{writeFile as bwr,mkdir as Iwr}from"node:fs/promises";import{dirname as Cwr,isAbsolute as _wr,join as wwr}from"node:path";async function HV(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},et)}async function WB(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function ev(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function jst(e){return`query-export-${e.slice(0,8)}.csv`}function Jme(e){return Ewr("sha256").update(e).digest("hex").slice(0,16)}async function zV(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Jme(t),o=await WB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await ev(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await ev(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!_wr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??wwr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Iwr(Cwr(p),{recursive:!0}),await bwr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function JV(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new ue(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function tv(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var Gme=J(()=>{"use strict";ot();tr()});async function Ei(e,t,r){let n=await e.get(`/api/v1/${Vme[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function GV(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${Vme[r]}/${n}/attachments`,o)}async function VV(e,t,r,n){return e.delete(`/api/v1/${Vme[t]}/${r}/attachments/${n}`)}var Vme,KB,nA=J(()=>{"use strict";Vme={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders"},KB=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function kwr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&xwr.some(n=>r.startsWith(n)))}async function op(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&kwr(t)&&(t.refusal=Twr),t}}function Yst(e,t,r){return Zi(e,t,r),e.toLowerCase()}function rv(e,t){return{type:Sc(Wme,e,"entityType"),record:Yst(t,"entityId",vwr)}}function XB(e){DZ(e,"threadId",Dwr)}function Hst(e){DZ(e,"commentId",Rwr)}function nv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Yst(e.bankAccountResourceId,"bankAccountResourceId",Swr)}}async function zst(e,t,r,n={}){let{type:i,record:o}=rv(t,r),s={...nv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return op(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Jst(e,t,r,n,i={}){let{type:o,record:s}=rv(t,r),a={...nv(i),limit:i.limit,offset:i.offset};return XB(n),op(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Gst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return n.threadId!==void 0&&XB(n.threadId),(await op(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...Yke,query:a}))).data}async function Vst(e,t,r,n,i,o,s){let{type:a,record:c}=rv(t,r),u=nv(s);return XB(n),Hst(i),(await op(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function Wst(e,t,r,n,i,o){let{type:s,record:a}=rv(t,r),c=nv(o);return XB(n),Hst(i),(await op(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function Kst(e,t,r,n,i){let{type:o,record:s}=rv(t,r),a=nv(i);return XB(n),(await op(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function Xst(e,t={}){return op(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function Zst(e,t,r){return HNe(t,"Get it from list_notifications."),(await op(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function eat(e){return(await op(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Wme,vwr,Swr,Dwr,Rwr,Twr,xwr,tat=J(()=>{"use strict";Ki();ot();tr();Wme=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],vwr="Pass the resourceId of the bill, invoice, credit note or bank record.",Swr="Pass the resourceId of the bank account that holds the bank record.",Dwr="Get it from list_comment_threads.",Rwr="Get it from list_comments or list_comment_threads.",Twr={code:"USER_CREDENTIAL_REQUIRED",hint:"Comments and notifications act as a user, so the credential must name an active member of the organization. A service or organization key with no user is refused with this 401. Use a user credential: sign in with `clio auth login`, a personal access token, or an API key a member created."},xwr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Qo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var iv=J(()=>{"use strict"});async function WV(e,t){return e.post("/api/v1/claims/conversion/preview",t,et)}async function KV(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new ue('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:AP)}var ZB,Kme=J(()=>{"use strict";ot();tr();ZB=["POST","POST_AND_RECORD"]});async function XV(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,Qke)}async function ZV(e,t){return e.search("/api/v1/employees/payouts/search",t)}var rat,Xme=J(()=>{"use strict";ot();tr();rat=["REIMBURSEMENT","ADVANCE"]});async function e8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Zme=J(()=>{"use strict"});function eAe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function tAe(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${nat(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>Pu.has(u)),s=i.filter(u=>!Pu.has(u)&&Rc.has(u)),a=[`Nothing here can be extracted: found ${nat(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=KBe[u];d&&a.push(d)}return o.length>0&&a.push(`${eU(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${eU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Pu.has(u)&&!Rc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${eU([...Pu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function nat(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var iat=J(()=>{"use strict";Mu()});function t8(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function eO(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&t8()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function vE(e,t){return{error:e,hint:t,...rAe}}function oat(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${eO(e)}.`,...rAe}}function SE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function iA(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${eO({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...rAe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var rAe,sat=J(()=>{"use strict";rAe={kind:"validation",retriable:!1}});import{randomUUID as Nwr}from"node:crypto";import{rmSync as Bwr}from"node:fs";function iAe(e){for(let t of e.tempDirs??[])try{Bwr(t,{recursive:!0,force:!0})}catch{}}function cat(e){for(let[t,r]of DE)e-r.createdAt>aat&&(iAe(r.plan),DE.delete(t))}function Fwr(){nAe||(nAe=setInterval(()=>cat(Date.now()),Owr),nAe.unref?.())}function oAe(e,t){let r=Date.now();cat(r),Fwr();let n=`dc_${Nwr()}`;return DE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function sAe(e,t){let r=DE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>aat?(iAe(r.plan),DE.delete(e),null):r.plan}function lat(e,t){let r=DE.get(e);!r||r.ownerKey!==t||(iAe(r.plan),DE.delete(e))}var aat,Owr,DE,nAe,uat=J(()=>{"use strict";aat=1800*1e3,Owr=300*1e3,DE=new Map});function Lwr(e){if(!e||typeof e!="object")return{};let t=e,r=t.validFiles?.[0],n=r?.workflowResourceId??t.workflowResourceId;return{...n?{workflowId:n}:{},...r?.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},...r?.subscriptionFBPath?{subscriptionFBPath:r.subscriptionFBPath}:{},...r?.backgroundJobFBPath?{backgroundJobFBPath:r.backgroundJobFBPath}:{}}}function dat(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>_g(i.documentType)&&r.has(i.documentType))}))}}async function fat(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?dat(t,i):t;if(!n&&Qwr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");vD(o);let a=await mU({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,...d.status==="uploaded"?Lwr(d.response):{},error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function pat(e,t){return(t&&t.length>0?dat(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>_g(o.documentType)).length,0)}function Qwr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var hat=J(()=>{"use strict";nee();Mu();Af()});function Pwr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function Uwr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function $wr(e,t){if(e!==Mwr)return;let r=Uwr(t);if(r)return mat.get(r)??mat.get(r.replace(/_ERROR$/,""))}function r8(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function qwr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=r8(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function aAe(e){return $wr(e.status,e.body)??e.refusal?.hint??qwr(e)}function RE(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function n8(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function tO(e,t={}){let r=t.readOnly===!1&&PD()?PFe:"";if(e instanceof gr){let o=[aAe(e)??Pwr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...r8(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=i8(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof ct;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var Mwr,mat,TE=J(()=>{"use strict";Ki();fo();o8();bU();Mwr=422,mat=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});async function md(e,t,r){if(!t)return e;let n=jwr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}async function Ad(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${RE(i)}`],...n}}}function jwr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function sp(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var Aat=J(()=>{"use strict";TE()});async function s8(e,t){return e.list("/api/v1/bank-rules",t)}async function rO(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function a8(e,t){return e.search("/api/v1/bank-rules/search",t)}async function c8(e,t){return e.post("/api/v1/bank-rules",t)}async function l8(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function u8(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var cAe=J(()=>{"use strict"});async function d8(e,t){return e.list("/api/v1/fixed-assets",t)}async function xE(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function nO(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function f8(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},iZ)}function yat(e,t){let r={};for(let n of Ywr){let i=e[n];if(i==null)continue;let o=Hwr.has(n)?cf(i):i;o!==void 0&&(r[n]=o)}for(let[n,i]of Object.entries(t))i!==void 0&&n!=="resourceId"&&(r[n]=i);return r}async function p8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ut(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await xE(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,yat(i,r))}async function h8(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function m8(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},hP)}async function iO(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,hP)}async function A8(e,t){return e.post("/api/v1/transfer-fixed-assets",t,iZ)}async function g8(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},hP)}async function y8(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},oZ)}async function E8(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},oZ)}async function zwr(e,t){let r=new Map;for(let i=0;i<t.length;i+=gat){let o=t.slice(i,i+gat),s=await nO(e,{filter:{resourceId:{in:o}},limit:o.length});for(let a of s.data)r.set(a.resourceId,a)}let n=t.filter(i=>!r.has(i));if(n.length>0)throw ut(new ue(`No fixed asset found for ${n.length} resourceId${n.length===1?"":"s"}: ${n.join(", ")}. Nothing was submitted; fix or remove those rows and retry.`));return r}async function b8(e,t){mt(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=HS(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw ut(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw ut(new ue(`resourceId ${u} appears more than once in fixedAssets; put all of an asset's changes in one row. Nothing was submitted.`));return r.add(u),u}),i=t.map((a,c)=>Xn(a.tags,`fixedAssets[${c}].tags`)),o=await zwr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...yat(u,{...a,tags:d&&ui(u.tags,d)})}});return En(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function I8(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function C8(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function _8(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,et)}async function w8(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},et)}async function v8(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function S8(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function D8(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function Gwr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function Vwr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=Gwr(i);if(o.length===0)return;let s=typeof i.reference=="string"&&i.reference?` (${i.reference})`:"";t.push(`row ${n}${s}: ${o.map(a=>`${a} (${Jwr[a]})`).join(", ")}`)}),t.length>0)throw ut(new ue(`Every fixed asset row needs its reference, registrationType and depreciationStartDate; the import job rejects a row without them. Missing: ${t.join("; ")}. Nothing was sent.`))}async function R8(e,t){return mt(t,"fixedAssets",500,"fixed assets"),SNe(t,["purchaseDate","depreciationStartDate"]),Vwr(t),En(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var oA,Ywr,Hwr,gat,Jwr,T8=J(()=>{"use strict";an();KS();tr();ot();xl();oA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];Ywr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],Hwr=new Set(["purchaseDate","depreciationStartDate"]);gat=100;Jwr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function x8(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function kE(e,t){return e.get(`/api/v1/leases/${t}`)}async function k8(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},Uke)}async function N8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names lease ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await kE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function B8(e,t){await e.delete(`/api/v1/leases/${t}`)}async function O8(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},qS)}async function F8(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},qS)}async function L8(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},qS)}async function Q8(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},et)}async function P8(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},qS)}async function M8(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function U8(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function $8(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function q8(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,et)}async function j8(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,et)}async function Y8(e,t){return mt(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`leases[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that lease. Bulk update does not take tags: change them with update_lease (clio leases update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/leases/bulk-update","leases",t)}var lAe=J(()=>{"use strict";an();ot();tr()});async function H8(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function NE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function z8(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Jp)}async function J8(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await NE(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw Wwr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function Wwr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function G8(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function V8(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function W8(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var K8=J(()=>{"use strict";tr()});async function X8(e,t){return e.list("/api/v1/contact-groups",t)}async function Z8(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function eW(e,t){return e.search("/api/v1/contact-groups/search",t)}async function tW(e,t){return e.post("/api/v1/contact-groups",t)}async function rW(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,TI(r,hZ))}async function nW(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var uAe=J(()=>{"use strict";an()});async function iW(e,t){return e.list("/api/v1/inventory-items",t)}async function oW(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function sW(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function cW(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&Kwr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var aW,Kwr,dAe=J(()=>{"use strict";Ki();aW=["ALL","AVAILABLE","FULLY_DRAWN"],Kwr=/Inventory balance Not Found/i});async function lW(e,t){return e.list("/api/v1/custom-fields",t)}async function oO(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function uW(e,t){return e.search("/api/v1/custom-fields/search",t)}async function dW(e,t){return e.post("/api/v1/custom-fields",t)}function Zwr(e){return e!==void 0&&Xwr.every(t=>e[t]!==void 0)}function evr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function tvr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function fW(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!Zwr(n.appliesTo)){let i=await oO(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??tvr(i.data),n.appliesTo={...evr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function pW(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var Xwr,fAe=J(()=>{"use strict";Xwr=["invoices","bills","customerCredits","supplierCredits","payments"]});var el,BE,rvr,nvr,pAe,hW,mW,ivr,Ta,ru,OE,ov,FE,hAe=J(()=>{"use strict";el={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217). Required whenever this settings object is sent."}},required:["sourceCurrencyCode"]},BE={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field. Required unless resourceId is given; when resourceId is given, the organization's own name for that field is stored instead of this one."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition. Required unless customFieldName is given. When omitted, the field is matched by customFieldName (case-insensitive) and linked only if exactly one active custom field in the organization has that name."}}},rvr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},nvr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},pAe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},hW={type:"object",properties:{billingAddress:{...pAe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},mW={type:"object",properties:{billingAddress:{...pAe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...pAe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},ivr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Ta={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:ivr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},ru={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},OE={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},ov={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:BE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...rvr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...nvr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...hW,description:"Issuer identity and billing address (credit from)."},creditTo:{...mW,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:BE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...hW,description:"Seller identity and billing address."},billTo:{...mW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...el,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...el,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},FE={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...ru,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}}}});function AAe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function gAe(e){let t=e.updated??[],r=AAe(e.failed);return{...t.length===0&&r.length>0?{error:avr}:{},updated:t,failed:r}}function bat(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function AW(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Iat(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=bat(s);if(a)for(let c of Array.isArray(o)?o:[o])AW(c)&&n.push(...Iat(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function cvr(e){return Object.entries(e).map(([t,r])=>{let n=bat(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function yAe(e,t,r){if(!AW(t))return;let n=Iat(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw ut(new ct(`${e} has no field ${i.join("; ")}. Fields: ${cvr(r)}. Nothing was changed.`))}function lvr(e){let t=ov[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function uvr(e){let t=FE[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function dvr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!AW(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw ut(new ct(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!AW(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw ut(new ct(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));yAe(`${e} line items`,a.attributes,t.fields)}}}function Cat(e){if(sv.includes(e))return;let t=yW.includes(e);throw ut(new ct(t?`${e} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${e} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${e} has no quick fix route. Transaction-level entities: ${sv.join(", ")}.`))}async function cv(e,t,r){Cat(t),yAe(`${t} quick fix`,r.attributes,lvr(t));let n=await e.post(`/api/v1/quick-fix/${Sc(sv,t)}`,r);return gAe(n)}async function fvr(e,t){try{return await IE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return CE(e,t);throw r}}async function _at(e,t,r,n){Cat(t);let i=EAe[t],o=async d=>i.tags(await Xi(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Eat)s.push(...await Promise.all(r.resourceIds.slice(d,d+Eat).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=ui(s[f],n),h=JSON.stringify(p);a.set(h,{tags:p,resourceIds:[...a.get(h)?.resourceIds??[],d]})});let c=[],u=[];for(let{tags:d,resourceIds:f}of a.values())try{let p=await cv(e,t,{resourceIds:f,attributes:{...r.attributes,tags:d}});c.push(...p.updated),u.push(...p.failed)}catch(p){if(c.length===0)throw p;u.push(...f.map(h=>({resourceId:h,error:p instanceof Error?p.message:String(p)})))}return gAe({updated:c,failed:u})}async function sO(e,t,r){let n=Sc(av,t),i=uvr(t);i.entryKeys?dvr(t,i,r.schedulerUpdates):yAe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return gAe(o)}var ovr,svr,gW,yW,sv,av,avr,LE,mAe,EAe,Eat,EW=J(()=>{"use strict";Ki();ot();fo();hAe();xl();zg();af();Hx();Kx();Jg();ZG();dV();K8();ovr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],svr=["journals","cash-entries"],gW=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],yW=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],sv=[...ovr,...svr,...gW],av=[...sv,...yW],avr="Nothing changed: every record failed. See failed for each reason.";LE=e=>e?.tags,mAe=e=>e?.data?.tags,EAe={invoices:{noun:"invoice",get:(e,t)=>Eo(e,t),tags:LE},bills:{noun:"bill",get:(e,t)=>ho(e,t),tags:LE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>Vs(e,t),tags:LE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>Ws(e,t),tags:LE},journals:{noun:"journal",get:(e,t)=>vs(e,t),tags:LE},"cash-entries":{noun:"cash entry",get:(e,t)=>fvr(e,t),tags:LE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Vw(e,t),tags:mAe},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Ww(e,t),tags:mAe},"subscription-schedules":{noun:"subscription",get:(e,t)=>NE(e,t),tags:mAe},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Kw(e,t),tags:LE}},Eat=10});function bW(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=bW(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<hvr&&i.length<=mvr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,bW(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function vat(e,t,r){let n=Avr(t);if(!n)return[];let i=gvr(r);if(!i){if(wat[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?vat(o,s,i[o]):[])}function yvr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function bAe(e,t,r={}){let n=Object.keys(e),i=[...new Set(n.flatMap(c=>Object.keys(e[c])))].sort(),o={},s=new Map;for(let c of i){let u=n.filter(y=>e[y][c]),d=new Map;for(let y of u){let b=Evr(e[y][c]);d.set(b,[...d.get(b)??[],y])}let[[,f],...p]=[...d].sort((y,b)=>b[1].length-y[1].length),{description:h,...m}=r[c]??bW(e[f[0]][c]),A=p.length&&m.properties&&!r[c]?{...m,required:void 0,properties:Object.assign({},...[f,...p.map(([,y])=>y)].map(y=>bW(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[wat[c],yvr(u,n),...p.map(([,y])=>{let b=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(b.properties??b.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[b,E]of vat(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(b))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function Tat(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>pvr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var pvr,wat,hvr,mvr,Avr,gvr,Evr,bvr,Ivr,lv,Sat,Dat,Rat,xat,kat,Nat,IAe=J(()=>{"use strict";hAe();xl();pvr={valueDate:"date",dueDate:"due date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},wat={currencySettings:"sourceCurrencyCode alone takes the platform rate (not on schedules); add rateFunctionalToSource to set one.",taxCurrencySettings:"Cash entries: sourceCurrency; every other record: sourceCurrencyCode, always sent.",tags:`${Yo.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}."},hvr=2,mvr=8;Avr=e=>e.properties??e.items?.properties,gvr=e=>e.properties??e.items?.properties;Evr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),bvr={tags:Yo};Ivr=Object.entries(FE).filter(([,e])=>!e.entryKeys),lv=Object.entries(FE).filter(([,e])=>e.entryKeys),Sat=bAe({...ov},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",bvr),Dat=bAe(Object.fromEntries(Ivr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),Rat=(()=>{let e=n=>lv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=lv[0],r=[...new Set(lv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>lv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${lv.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:bAe(Object.fromEntries(lv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();xat=[...new Set([...Object.keys(ov),...Object.keys(FE)])].map(e=>e.replace(/-/g," ")).join(", "),kat=Tat(Object.values(ov)),Nat=Tat(Object.values(FE).map(e=>e.fields))});function IW(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var CAe=J(()=>{"use strict"});function _W(){return sA.map(e=>`${e} sets ${dv[e].change.join(", ")}`).join("; ")}function Uat(e){let t={};for(let r of e)t[r]=Object.hasOwn(Oat,r)?Oat[r]:wvr.find(([n])=>n.test(r))?.[1]??vvr;return Object.keys(t).length>0?t:void 0}function $at(e){if(!(e instanceof gr)||!e.endpoint.startsWith(_vr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Fat,n))return;let{hint:i,repairTool:o,command:s}=Fat[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Pat.LINE_ITEMS?"line items":"records",...e.endpoint===CW?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function Rvr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function Tvr(e){return typeof e=="string"&&sA.includes(e)}function xvr(e,t){if(!Tvr(e))throw new ct(`level must be one of ${sA.join(", ")}.`);let r=sA.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))dv[e][i].includes(s)||n.push(dv[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=dv[e];throw new ct(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Lat(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new ct(`${e} must be a JSON object, not ${n}.`)}async function vW(e,t,r){let n={filter:Lat("filter",r.filter),change:Lat("change",r.change)};xvr(t,n);let i;try{i=await e.post(Pat[t],{filter:n.filter,change:n.change},et)}catch(u){throw $at(u),u}let{data:o,...s}=i,a=Uat([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=Rvr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function wAe(e,t){return{error:`${t} ${jat}`,outcome:"UNKNOWN",previewId:e,next:qat}}function Bvr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return wAe(e,"The apply answered without a per-record result.");let i=AAe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=Uat(Object.keys(o)),a=o[Svr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Nvr}:a==="UNKNOWN"?{error:jat}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?qat:kvr},failed:i.slice(0,_Ae),...i.length>_Ae?{failedNotShown:i.length-_Ae}:{},data:r}}async function SW(e,t,r=Dvr){let n;try{n=await e.post(CW,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=$at(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw ut(i);return wAe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof zp)throw ut(i);let o=i instanceof Error?i.message:String(i);return wAe(t,`No answer arrived from the apply (${o}).`)}return Bvr(t,n)}var Qat,sA,Pat,CW,_vr,Mat,Bat,dv,Oat,wvr,vvr,Svr,Dvr,wW,_Ae,fv,lon,uv,Fat,qat,kvr,Nvr,jat,vAe=J(()=>{"use strict";Ki();EW();lP();ot();fo();tr();CAe();Qat=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],sA=["TRANSACTIONS","LINE_ITEMS"],Pat={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},CW="/api/v1/ledger/find-fix/apply",_vr=CW.slice(0,CW.lastIndexOf("/")+1),Mat={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},Bat=["types","resourceIds","reference","valueDate","contactResourceId"],dv={TRANSACTIONS:{filter:Bat,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Bat,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Oat={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},wvr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],vvr="Not described by this client version; read the records that carry it.";Svr="OUTCOME_UNKNOWN",Dvr=25e3,wW=3e5,_Ae=50,fv=12,lon=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${fv}}(?![A-Za-z0-9_-])`,"i"),uv=e=>e.resourceId?` (${e.resourceId})`:"",Fat={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${uv(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${uv(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${uv(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${uv(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${uv(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${uv(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};qat="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",kvr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",Nvr="Nothing changed: every record in the preview failed.",jat="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function DW(e,t){return e.list("/api/v1/nano-classifiers",t)}async function QE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function RW(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function aO(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function cO(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function TW(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Ovr(e,t):{};let{data:n}=await QE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Hat(n)}async function Ovr(e,t){let{data:r}=await QE(e,t);return Hat(r)}function Hat(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function xW(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var Yat,SAe=J(()=>{"use strict";Yat=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function kW(e,t){return e.post("/api/v1/export-records",t,et)}async function NW(e,t){return e.post("/api/v1/export-records/preview",t,et)}async function BW(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var DAe=J(()=>{"use strict";tr()});function OW(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function Vat(e,t,r,n=!1){if(!Array.isArray(e))throw new ue(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new ue(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new ue(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new ue(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function FW(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function LW(e,t,r){return OW(t,Jat),Zi(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Sc(ap,t)}/${encodeURIComponent(r)}/approve`,void 0,Oke)}async function QW(e,t,r){return OW(t,Jat),Vat(r,Fvr,"bulk approve",!0),r.forEach(n=>Zi(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Sc(ap,t)}/bulk-approve`,{resourceIds:r},Fke)}async function PW(e,t,r,n){OW(t,Gat),Zi(r,"resourceId","Pass the document resourceId."),Wat(n);let i=await e.post(`/api/v1/${Sc(PE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Pvr(i)}}}async function MW(e,t,r,n){return OW(t,Gat),Wat(n),Vat(r,Lvr,"bulk request changes"),r.forEach(i=>Zi(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(Qvr(t),{resourceIds:r,message:n})}function Qvr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Sc(zat,e)}/bulk-request-changes`}function Wat(e){if(!e||e.trim().length===0)throw new ue("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function Pvr(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ap,zat,PE,Jat,Gat,Fvr,Lvr,RAe=J(()=>{"use strict";ot();tr();ap=["invoices","bills","customer-credit-notes","supplier-credit-notes"],zat=[...ap,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],PE=[...zat,"claims"],Jat=new Set(ap),Gat=new Set(PE);Fvr=100,Lvr=500});function Mvr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${Kat(t)}:${Kat(r)}:${n}`}function Kat(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function TAe(e){if(!Xat.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...Xat].join(", ")}`)}async function Zat(e,t,r){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function ect(e,t,r,n){return TAe(t),Zi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function tct(e,t,r,n,i){if(TAe(t),Zi(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new ue('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??Mvr(t,r,n)}})}async function rct(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var Xat,nct=J(()=>{"use strict";ot();Xat=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function Uvr({fromPeriod:e,toPeriod:t},r){for(let[n,i]of[["fromPeriod",e],["toPeriod",t]])if(i!==void 0){if(!Number.isInteger(i)||i<1)throw new ct(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new ct("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new ct(`${n} ${i} is past the last period (${r}). Send a period from 1 to ${r}.`)}if(e!==void 0&&t!==void 0&&e>t)throw new ct(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function UW(e,t,r){let n=e.length;if(Uvr(t,e[n-1]),n===0)return{start:0,end:0,window:{totalPeriods:0}};let i=t.fromPeriod===void 0?0:e.filter(u=>u<t.fromPeriod).length,o=t.toPeriod===void 0?n:e.filter(u=>u<=t.toPeriod).length,s=o===0&&t.toPeriod!==void 0,a=s?Math.min(t.toPeriod-(t.fromPeriod??1)+1,n,r):Math.min(o,i+r);if(a<=i)throw new ct(`No period falls in that range: the schedule runs from period ${e[0]} to ${e[n-1]}.`);let c={totalPeriods:n,fromPeriod:e[i],toPeriod:e[a-1]};if(i>0||a<n){let u=[`Showing periods ${e[i]} to ${e[a-1]} of ${n}.`];a<n&&u.push(`Periods ${e[a]} to ${e[n-1]} are not shown: call again with fromPeriod ${e[a]} to read the next range (at most ${r} periods come back per call).`),i>0&&u.push(`Periods ${e[0]} to ${e[i-1]} are not shown: call again with fromPeriod ${e[0]} to read them.`),c.note=u.join(" ")}return s&&(c.note=`Periods ${t.fromPeriod??1} to ${t.toPeriod} come before this schedule, which starts at period ${e[0]}. Showing the first periods instead. ${c.note??""}`.trim()),{start:i,end:a,window:c}}function pv(e,t={},r=lO){let n=e.data,i=ME(n.rows),{start:o,end:s,window:a}=UW(xAe(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function $W(e,t={},r=lO){let n=e.data,i=ME(n.rows),o=h=>h.rowType==="PERIOD",s=i.findIndex(o),a=i.map(o).lastIndexOf(!0),c=s===-1?[]:i.slice(s,a+1),{start:u,end:d,window:f}=UW(xAe(c),t,r);if(s===-1)return{...e,data:{...f,...n}};let p=[...u===0?i.slice(0,s):[],...c.slice(u,d),...d===c.length?i.slice(a+1):[]];return{...e,data:{...f,...n,rows:p}}}function ict(e,t,r,n,i){let o=e.data,s=ME(o[t]),a=s.reduce((h,m)=>h+ME(m[r]).length,0),{start:c,end:u,window:d}=UW(Array.from({length:a},(h,m)=>m+1),n,i);if(a===0)return{...e,data:{...d,...o}};let f=0,p=[];for(let h of s){let m=ME(h[r]),A=m.slice(Math.max(c-f,0),Math.max(u-f,0));A.length>0&&p.push({...h,[r]:A}),f+=m.length}return{...e,data:{...d,...o,[t]:p}}}function gd(e,t={},r=lO){let n=e.data,i=ME(n.periods),{start:o,end:s,window:a}=UW(xAe(i,"period"),t,r);if(i.length===0)return{...e,data:{...a,...n}};let c=i[o].startDate,u=i[s-1].endDate,d=f=>typeof f.toDate!="string"||typeof f.fromDate!="string"||typeof c!="string"||typeof u!="string"||f.toDate>=c&&f.fromDate<=u;return typeof a.note=="string"&&(a.note+=" The timeline lists only the segments that touch these periods."),{...e,data:{...a,...n,periods:i.slice(o,s),timeline:ME(n.timeline).filter(d)}}}var lO,ME,xAe,qW,jW,hv=J(()=>{"use strict";fo();lO=60;ME=e=>Array.isArray(e)?e:[],xAe=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);qW=(e,t={},r=lO)=>ict(e,"depreciationScheduled","depreciation",t,r),jW=(e,t={},r=lO)=>ict(e,"amortizationScheduled","amortization",t,r)});async function UE(e,t){return e.get(`/api/v1/loans/${t}`)}async function YW(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function HW(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function zW(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},$ke)}async function JW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names loan ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await UE(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function GW(e,t){await e.delete(`/api/v1/loans/${t}`)}async function VW(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},sZ)}async function WW(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},sZ)}async function KW(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function XW(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function ZW(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function e4(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function t4(e,t){return e.post("/api/v1/loans/preview-schedule",t,et)}async function r4(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,et)}async function n4(e,t){return mt(t,"loans",500,"loans"),jo(t,oct),En(e,"/api/v1/loans/bulk-upsert","loans",t)}async function i4(e,t){return mt(t,"loans",500,"loans"),jo(t,$vr),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ut(new ue(`loans[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that loan. Bulk update does not take tags: change them with update_loan (clio loans update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/loans/bulk-update","loans",t)}async function o4(e,t,r,n,i){let o=uO[t];if(i){if(!o.calculate)throw new Error(`Loan event ${t} has no preview.`);let s=Object.fromEntries(Object.entries(n).filter(([a])=>!o.recordOnly?.includes(a)));return e.post(o.calculate,{...s,resourceId:r},et)}return e.post(o.record(r),{...n,resourceId:r},qke)}var oct,$vr,uO,kAe=J(()=>{"use strict";an();ot();tr();oct=["drawdownDate","trackingStartDate","firstRepaymentDate"],$vr=[...oct,"capitalizationStartDate","capitalizationEndDate"];uO={drawdown:{calculate:"/api/v1/loans/calculate-drawdown",record:e=>`/api/v1/record-drawdown/loans/${e}`},prepayment:{calculate:"/api/v1/loans/calculate-prepayment",record:e=>`/api/v1/prepay/loans/${e}`},rateChange:{calculate:"/api/v1/loans/calculate-rate-change",record:e=>`/api/v1/change-rate/loans/${e}`},capitalization:{calculate:"/api/v1/loans/calculate-capitalization",record:e=>`/api/v1/capitalize-interest/loans/${e}`},paymentHoliday:{calculate:"/api/v1/loans/calculate-payment-holiday",record:e=>`/api/v1/payment-holiday/loans/${e}`},restructure:{calculate:"/api/v1/loans/calculate-restructure",record:e=>`/api/v1/restructure/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},settlement:{calculate:"/api/v1/loans/calculate-settlement",record:e=>`/api/v1/settle/loans/${e}`},forgiveness:{calculate:"/api/v1/loans/calculate-forgiveness",record:e=>`/api/v1/forgive/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},conversion:{calculate:"/api/v1/loans/calculate-conversion",record:e=>`/api/v1/convert-to-shares/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},refinance:{record:e=>`/api/v1/refinance/loans/${e}`},reclassifyAsCurrent:{record:e=>`/api/v1/reclassify-as-current/loans/${e}`},undo:{record:e=>`/api/v1/undo-event/loans/${e}`}}});function mv(e){mt(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new ue(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!BFe(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!qvr.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new ue(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function s4(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},et);return{data:Yvr(r.data)}}function jvr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function Yvr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(jvr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function a4(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function c4(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var qvr,NAe=J(()=>{"use strict";ot();iee();an();tr();qvr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function lct(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new ue("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function BAe(e,t){if(!e||typeof e!="object")throw new ue(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new ue(`${t}.lineItems array is empty.`);if(n.length>500)throw new ue(`max 500 ${t}.lineItems per call.`);jo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&jo([i],["valueDate"])}async function u4(e,t,r=OAe){return e.post("/api/v1/search-magic-reconciliation",t,{...et,timeoutMs:r})}function l4(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Gvr(e){let t=l4(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=l4(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function Vvr(e){return e?e.value>=(e.from==="confidenceScore"?Hvr:zvr)?"high":e.value>=Jvr?"medium":"low":"low"}function Kvr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(sct,t))return;let r=sct[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function aA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function act(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function Xvr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>act({account:aA(n?.account),taxProfile:aA(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!aA(e.contact)&&!aA(e.account)&&!aA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return act({contact:aA(e.contact),account:aA(e.account),taxProfile:aA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function uct(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>n0r(c,h??{},u.length-1,t)).sort(Zvr),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function Zvr(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function e0r(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return vc.test(t)?t:void 0}function t0r(e){let{recommendationId:t,...r}=e;return r}function r0r(e,t,r){return!t||!r?t:e===$E.learnedPrediction?{...t,recommendationId:r}:e===$E.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function n0r(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=l4(t.matchScore),s=l4(t.confidenceScore),a=Gvr(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=$E.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=$E.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let F=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,G=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,j=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;F&&G&&j&&(m=$E.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:F,predictedPayload:G,predictedPayloadSchemaVersion:j});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let F=t.actionShortcut??{},G=typeof F.resourceId=="string"?F.resourceId:void 0;G&&(m=$E.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=r0r(m,A,e0r(t)),y=m?Vvr(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==$E.withPayments||b,T=Kvr(t),D=!m||!g?"NO_PLAN":T?Wvr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",k=Xvr(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:g,confidenceTier:y,autoCommitEligible:D===void 0,...D?{checkpointReason:D}:{},...k?{proposedPosting:k}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:T===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(t0r(t))}`}}function i0r(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function o0r(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await ho(e,i):await Eo(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${RE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function dct(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,cct);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await nC(e,t,{filter:{resourceId:{in:u}},limit:cct}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${RE(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return i0r(u,f,await o0r(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function d4(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,ya)}async function f4(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,ya)}async function p4(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,ya)}async function h4(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,ya)}async function m4(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,ya)}async function A4(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,ya)}async function g4(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,ya)}async function y4(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,ya)}async function E4(e,t){return e.post("/api/v1/reconciliations/with-payments",t,ya)}async function b4(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,ya)}async function I4(e,t){return e.post("/api/v1/reconciliations/magic-match",t,ya)}async function C4(e,t){return e.post("/api/v1/reconciliations/reset",t)}var $E,OAe,Hvr,zvr,Jvr,Wvr,sct,cct,_4=J(()=>{"use strict";Rg();TE();ot();af();an();zg();tr();$E={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},OAe=6e4;Hvr=.9,zvr=.95,Jvr=.7;Wvr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},sct={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};cct=25});function ia(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Po(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:FAe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=FAe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=FAe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function FAe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function ts(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=ia(e,t,n),a=Po(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var xa,tl,vo,nu,fct=J(()=>{"use strict";xa=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],tl=[...xa],vo=xa.filter(e=>e.field!=="dueDate"),nu=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function yd(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=_c(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function w4(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=BI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var pct=J(()=>{"use strict";Vp()});var LAe=J(()=>{"use strict";fct();Vp();pct()});var dO,v4,rs,oo,QAe=J(()=>{"use strict";dO="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",v4=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],rs="If the result says it runs in the background, do not poll: its result arrives by itself.",oo=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${rs} PARTIAL_SUCCESS: errorDetails.`});function hct(e){return s0r.get(e)}function mct(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!S4.has(o));return n.length===0?[]:Mi.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Mi,S4,s0r,Ed=J(()=>{"use strict";QAe();IAe();Mi=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Thirteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights. Fixed asset register reports are in register_reports.",groups:["operational_reports","exports"]},{name:"register_reports",title:"Register Reports",description:"Register reports: fixed asset register summary by account, type, category or active/closed-out/disposed state (asset register roll-forward over a period), fixed asset register vs general ledger reconciliation (does the register agree with the GL), deferrals summary (prepaid and deferred revenue roll-forward) and deferrals reconciliation (does the prepaid register agree with the GL), lease register summary (IFRS 16 lease note, lease liability roll-forward) and lease register vs general ledger reconciliation (rent coded to the lease liability account). Loan reports: borrowings note summary, loan roll-forward, related-party (director, shareholder) loan balances, loan interest cost, maturity analysis (liquidity note), loan register vs ledger reconciliation.",groups:["register_reports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Tracking categories (nano classifiers; dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. For what-if questions and topics with no register; to keep a lease, loan, prepaid or deferred revenue use its register. Keywords: calculate, what-if, monthly payment, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate, set up to repeat every month.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"],channelToolsDescription:"Check the progress of background tasks a request started, add to a waiting one, or cancel it."},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update (one or bulk), discard, sell, transfer, undo disposal, close out (stop depreciating, keep the asset) and reopen. Also: depreciation, asset register. Depreciation schedules, totals, eligible bill lines and asset types are in fixed_asset_schedules.",groups:["fixed_assets"]},{name:"fixed_asset_schedules",title:"Fixed Asset Schedules & Totals",description:"Read-only fixed asset views. Show one asset's depreciation by month and year, net book value, asset register totals as at a date, disposal totals (gain/loss), eligible bill lines to register as assets, asset types. Check custom depreciation ranges; calculate disposal (accumulated depreciation, net book value) before selling or discarding.",groups:["fixed_asset_schedules"]},{name:"deferrals",title:"Deferrals (Prepaid & Deferred Revenue)",description:"Deferrals register: prepaid expense, prepayment, deferred revenue, unearned revenue. Spread a bill over months, recognise an invoice over months (amortization, release schedule). Search, create, update, delete, stop amortising early (close out) and undo it, totals as at a date, schedule, eligible bill or invoice lines, deferral types and deferral accounts (mark the accounts first), bulk create and update.",groups:["deferrals"]},{name:"leases",title:"Leases (IFRS 16)",description:"Leases under IFRS 16: put an office rent lease on the books (right-of-use asset, ROU, and lease liability, current and non-current), hire purchase (flat rate to monthly discount rate), short-term or low-value exemption. Search, create, update, delete, close out, terminate lease (preview the gain or loss first) and undo either; lease schedule, liability totals as at a date, rent schedule preview, lease types.",groups:["leases"]},{name:"loans",title:"Loans (Borrowings)",description:"Loans and borrowings register: record a new bank loan, loan, borrowing, bank loan, term loan, director's loan (revolving credit and loans given are not in the register), instalment / installment loan. Search, create, update (one or bulk), delete, close out. What do we owe a lender or the bank: outstanding principal, current and non-current at a date, the repayment schedule, an on-demand loan ledger (an on-demand loan has no schedule, is all current and posts no interest), loan types, preview the monthly payment. Loan changes (drawdown, prepay, rate change, settle) are in loan_events; loan reports are in register_reports.",groups:["loans"]},{name:"loan_events",title:"Loan Events",description:"Events on an existing loan: drawdown, prepay or extra repayment, rate change, payment holiday, capitalize interest, restructure, refinance, settle / payoff, forgive / write off a loan, convert loan to shares, covenant breach (reclassify as current), undo loan event, balance after a missed payment. preview: true calculates the figures and saves nothing.",groups:["loan_events"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${xat}. On a record: ${kat}. On lines: ${Nat}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${v4.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"collab",title:"Collaboration",description:"Comment threads on bills, invoices, credit notes and bank records: list threads and comments, add a reply or start a thread, mention a teammate, update or delete your own comment, resolve a thread. Notifications: list unread mentions and comments, mark one read or unread, mark all read.",groups:["collaboration"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],S4=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),s0r=new Map(Mi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function bd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function a0r(e){let t=Act.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(bd(r),n);for(let r of e.enum??[])t.set(bd(r),r);Act.set(e,t)}return t}function gct(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=bd(e);if(!r)return null;let n=a0r(t).get(r);return n!==void 0&&n!==e?n:null}function c0r(e){let t=yct.get(e);return t||(t=new Map(Object.keys(e).map(r=>[bd(r),r])),yct.set(e,t)),t}function l0r(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function u0r(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function PAe(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=c0r(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=bd(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?l0r(d):u0r(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=gct(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=gct(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=fee(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=PAe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=PAe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Ect(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:PAe(t,e.params,"",r),coercions:r}}function bct(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var Act,yct,MAe=J(()=>{"use strict";NU();Act=new WeakMap;yct=new WeakMap});function Av(e){let t=new Set,r=[];for(let n of e)for(let i of iu(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function fO(){return Mi.map(e=>{let t=Av(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function d0r(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function f0r(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function cA(e,t=!1){let r=lA(void 0).length,n=Mi.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:f0r(r)}:e&&i!==void 0?{packaging:d0r(e,i,r)}:{},map:fO(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var D4=J(()=>{"use strict";Ed();ou()});function R4(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=R4(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=R4(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function su(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=R4(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function pO(e){return{name:e.name,description:e.description,input_schema:su(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var gv=J(()=>{"use strict"});function hO(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function UAe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function T4(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&hO(e),idempotentHint:e.readOnly,openWorldHint:UAe(e)}}function h0r(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function m0r(e){let t=h0r(e);return!t||p0r.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!S4.has(n)).length===0}function $Ae(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function qAe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?qAe(o,`${i}.`):[]]})}function g0r(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
663
663
  `)[0]}`.toLowerCase(),n=[...e.description.split(`
664
664
  `).slice(1),...qAe(e.params)].map(i=>i.trim()).filter(Boolean);for(let i of t){if(r.includes(i))continue;let o=n.find(s=>s.replace(/\b(Only|Not): [^.]*\./g,"").toLowerCase().includes(i));if(o)return o.length>Ict?`${o.slice(0,Ict-1)}\u2026`:o}}function x4(e,t="meta"){let r=t==="meta"?"search_tools with an empty query":"describe_capabilities with no arguments";if(m0r(e)){if(t!=="meta")return cA(t);let{next:a,...c}=cA();return{...c,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let n=Rl(e.trim());if(n)return{matches:[],hint:n};let i=mct(e,5);if(i.length===0){let{operations:a,namespaces:c}=cA();return{matches:[],hint:`No operation matches "${e}". Jaz has ${a} operations across ${c} namespaces \u2014 call ${r} for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let s=e.toLowerCase().split(/\s+/).filter(Boolean);return{matches:i.map(a=>{let c=a.groups.flatMap(m=>iu(m)),u=c.map(m=>`${m.name} ${(m.aliases??[]).join(" ")} ${m.searchHint??""} ${m.description} ${qAe(m.params).join(" ")}`.toLowerCase()),d=new Map(s.map(m=>{let A=u.filter(g=>g.includes(m)).length;return[m,Math.log((c.length+1)/(A+1))]})),f=s.slice(1).map((m,A)=>`${s[A]} ${m}`),p=c.map((m,A)=>{let g=u[A],y=s.reduce((b,E)=>g.includes(E)?b+(d.get(E)??0):b,0)+f.filter(b=>g.includes(b)).length;return{tool:m,score:y}}).sort((m,A)=>A.score-m.score),h=[...d].filter(([m,A])=>A>0&&m.length>=3&&!S4.has(m)&&!A0r.has(m)).sort((m,A)=>A[1]-m[1]).map(([m])=>m);return{namespace:a.name,description:a.description,tools:p.map(m=>{let A=m.score>0?g0r(m.tool,h):void 0;return{name:m.tool.name,description:m.tool.description.split(`
665
665
  `)[0],...m.tool.searchHint?{searchHint:m.tool.searchHint}:{},...A?{matched:A}:{}}})}}),hint:t==="meta"?"Call describe_tools with the tool names you need, then execute_tool to run them.":`These are summaries. Before concluding something is unsupported, open the namespace with describe_capabilities({ namespace }) for every operation and its parameters. ${$Ae(t)}`}}function Cct(e){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(e.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let t=[],r=[];for(let n of e){let i=mO(n);if(!i){r.push(n);continue}t.push({...pO(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&hO(i),group:i.group})}return{tools:t,...r.length>0?{notFound:r,hint:r.map(Rl).find(Boolean)??`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var p0r,Ict,A0r,y0r,E0r,b0r,yv,uA,qE=J(()=>{"use strict";Ed();D4();ou();gv();hg();p0r=new Set(["capabilities","capability","overview","everything","catalog","catalogue","menu","features","feature list","functions","tool list","all tools","all operations","list tools","list all tools","list operations","full list","full catalog","full catalogue","whats available","what is available","whats possible","show everything","show me everything","what else can you do","how many tools","how many operations"]);Ict=160,A0r=new Set(["change","changes","changing","update","updates","updating","edit","modify","set","make","existing","new","add","create","remove","delete","all","every","each","these","those","record","records","want","need","keep","keeping","remaining","unchanged","while","only"]);y0r={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:su({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};E0r={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:su({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},b0r={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:su({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},yv={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs to pass as org_id on other tool calls.",inputSchema:su({},[])},uA=[y0r,E0r,b0r]});function w0r(e){if(!(ka in e))return{cleanedInput:e};let{[ka]:t,...r}=e;return{jotText:typeof t=="string"&&t.trim()!==""?t.trim():void 0,cleanedInput:r}}function AO(e){return!e.readOnly&&!e.params[ka]&&e.group!=="jots"}function vct(e,t){if(e.params[ka])return{cleanedInput:t};let{jotText:r,cleanedInput:n}=w0r(t);return AO(e)?{jotText:r,cleanedInput:n}:{cleanedInput:n}}function v0r(e){let t=C0r.exec(e);return t?{kind:t[1],call:e.slice(t[0].length)||e}:{call:e}}function D0r(e){let t=e.toLowerCase();for(let[r,n]of S0r)if(n.test(t))return r}function R0r(e,t){let r=D0r(e),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=_ct||a>_0r||!s||typeof s!="object")){if(Array.isArray(s)){for(let c of s)o(c,a+1);return}for(let[c,u]of Object.entries(s)){if(n.length>=_ct)return;c==="resourceId"&&typeof u=="string"&&u&&!i.has(u)?(i.add(u),n.push(u)):o(u,a+1)}}};return o(t,0),n.map(s=>({id:s,...r?{relation:r}:{}}))}function k4(e,t,r,n){let{kind:i,call:o}=v0r(r),s=R0r(t,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${t}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};Xw(e,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(mD(),hD)).then(({log:d})=>d.error({tool:t,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${t}): ${u}
@@ -670,7 +670,7 @@ Call with { operation, arguments${o?`, ${ka}`:""}${c.length?", file":""}${e?", o
670
670
  `+r.map(Ev).join(`
671
671
  `)+(e?`
672
672
 
673
- Multiple organizations are accessible: pass org_id (from list_organizations) to target one. Confirm the organization with the user before any create/update/delete.`:""),d={operation:{type:"string",enum:n,description:`The ${t.name} operation to run.`},arguments:{type:"object",description:"Parameters for the chosen operation (see the operation list above). Validated by the Jaz API.",additionalProperties:!0}};return o&&(d[ka]=O4()),c.length&&(d[cp]=F4(c)),e&&(d[jE]=B4()),{name:t.name,description:u,inputSchema:{type:"object",properties:d,required:["operation"],additionalProperties:!1},...c.length?{_meta:{...N4}}:{},annotations:{title:`${t.title??L4(t.name)} \xB7 ${r.length} operation${r.length===1?"":"s"}`,readOnlyHint:i,destructiveHint:!i&&s,idempotentHint:i,openWorldHint:a}}})}function P4(e,t=new Set){return t.has(e)?[]:(t.add(e),Object.hasOwn(jAe,e)?jAe[e].flatMap(r=>P4(r,t)):[e])}function YAe(e){return T0r.has(e)||Object.hasOwn(jAe,e)}function HAe(e,t){let r=P4(e),n=Mi.filter(a=>r.includes(a.name)).flatMap(a=>a.groups);if(n.length===0)return{error:`Unknown namespace: ${e}.`};let i=Object.hasOwn(Sct,e)?Sct[e]:[],o=[...Dct(n),...EO().filter(a=>i.includes(a.name))],s=o.find(a=>a.name===t||a.aliases?.includes(t))??o.find(a=>bd(a.name)===bd(t)||a.aliases?.some(c=>bd(c)===bd(t)));return s?{tool:s}:{error:Rl(t)??`Unknown operation "${t}" for the ${e} tool.`,operations:o.map(a=>a.name)}}var T0r,jAe,Sct,bv=J(()=>{"use strict";Ed();MAe();ou();qE();hg();Q4();T0r=new Set(Mi.map(e=>e.name)),jAe={capsules_and_recipes:["capsules","calculators"],capsules:["transaction_groups"],nano_classifiers:["tracking_categories"]},Sct={organization:["list_organization_report_templates","get_organization_report_template","search_organization_report_templates"],operational_reports:["generate_fixed_assets_summary","generate_fixed_assets_reconciliation_summary"]}});var Rct={};$o(Rct,{loadAgentSuiteContent:()=>F0r});import{readFileSync as x0r}from"node:fs";import{dirname as k0r,join as N0r}from"node:path";import{fileURLToPath as B0r}from"node:url";function F0r(){return zAe||(zAe=JSON.parse(x0r(N0r(O0r,"agent-suite-content.json"),"utf8"))),zAe}var O0r,zAe,Tct=J(()=>{"use strict";O0r=k0r(B0r(import.meta.url)),zAe=null});var xct={};$o(xct,{buildCapabilityMap:()=>Q0r});async function L0r(){try{let{loadAgentSuiteContent:e}=await Promise.resolve().then(()=>(Tct(),Rct)),t=e().counts;return{cli_command_groups:t.commands,api_rules:t.apiRules,skills:t.skills,ifrs_recipes:t.recipes,calculators:t.calculators,job_playbooks:t.jobs}}catch{return}}async function Q0r(e={}){if(e.query&&e.query.trim())return x4(e.query,e.surface);if(e.namespace){let r=P4(e.namespace),n=Mi.filter(s=>r.includes(s.name));if(n.length===0)return{error:`Unknown namespace "${e.namespace}".`,namespaces:Mi.map(s=>s.name),hint:"Call with no arguments for the full map, or pass `query` to rank operations by keyword."};let i=Av(n.flatMap(s=>s.groups)),o=n.length!==1||n[0].name!==e.namespace;return{namespace:e.namespace,...o?{now_called:n.map(s=>s.name)}:{},description:n.map(s=>s.description).join(" "),operations:i.length,operation_list:i.map(Ev),hint:$Ae(e.surface)}}let t=cA(e.surface,e.multiOrg);return{...t,map:e.full?fO().map(r=>({...r,operation_list:Av(Mi.find(n=>n.name===r.namespace).groups).map(Ev)})):t.map,beyond_mcp:await L0r()}}var kct=J(()=>{"use strict";Ed();bv();qE();D4()});import{randomUUID as P0r}from"node:crypto";import{mkdtempSync as M0r,writeFileSync as U0r,rmSync as $0r}from"node:fs";import{join as Nct,extname as q0r,resolve as Bct,sep as j0r}from"node:path";import{tmpdir as Y0r}from"node:os";function q4(e,t,r){let n=Z0r[t],i=r==="byContact";return{name:e,description:i?`${n.label} as at endDate, by ${n.party}: what is outstanding per contact, in aging buckets. For ${n.use}.`:`${n.label} Summary as at endDate: the summary report the dashboard shows under that name. For ${n.use}; for the breakdown per ${n.party}, use generate_aged_${t}.`,params:i?{endDate:nge,view:X0r}:{endDate:nge},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:i?`${n.label.toLowerCase()} by ${n.party} aging report`:`${n.label.toLowerCase()} summary report`,isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(o,s)=>{let{view:a,...c}=s;if(!i)return n.summary(o.client,{endDate:c.endDate});let u=await n.byContact(o.client,c);return a==="aggregate"?Tx(u,t):u}}}function eSr(e){let t=Object.keys(e).filter(i=>!$ct.has(i));if(t.length>0)throw new ct(`generate_general_ledger does not take ${t.join(", ")}. Its parameters: ${[...$ct].filter(i=>i!=="accountResourceId").join(", ")}.`);let r=[...e.accountResourceIds??[]],n=e.accountResourceId;if(n&&!r.includes(n)&&r.push(n),r.length>Hu)throw new ct(`accountResourceIds takes at most ${Hu} accounts per call (got ${r.length}). Split them across calls.`);return xx(e.limit),{startDate:e.startDate,endDate:e.endDate,groupBy:e.groupBy??"ACCOUNT",limit:e.limit??ylt,...e.offset!==void 0?{offset:e.offset}:{},...r.length>0?{accountResourceIds:r}:{}}}function Xct(e,t,r){return{type:"object",description:`The ${e.toLowerCase()} to create. Required.`,properties:{reference:{type:"string",description:`${e} reference`},contactResourceId:{type:"string",description:`${t} UUID`},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:`${e} line items (max 500)`,items:{type:"object",properties:{name:{type:"string",description:"Line description"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:`${r} account UUID`},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}},required:["name"]}},recordedPayment:{type:"object",description:"Optional. The matching payment record, auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:lp,adjustment:Sv}},capsuleResourceId:{type:"string"}},required:["reference","lineItems"]}}function FO(e){let t=e.limit,r=e.offset;return{limit:t,offset:r,sortBy:void 0,sortOrder:void 0}}function br(e,t,r,n,i,o){let s={...OO,...o?.filters};return o?.offsetMode==="row"&&(s.offset=HD),o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:e,description:t,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=FO(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0,p=o?.defaultLimit??(f==="lean"?50:20),h=o?.filters?Object.fromEntries(Object.keys(o.filters).filter(m=>c[m]!=null).map(m=>[m,String(c[m])])):void 0;return lh((m,A)=>n(a.client,m,A,f,h),u,d,p)}}}function ni(e,t,r,n,i,o){return{name:e,description:t,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,a)=>n(s.client,a.resourceId)}}function rl(e){let t="calculate"in uO[e.event];return{name:e.name,description:t?`${e.description} Preview first (preview: true saves nothing), then record. Recording: Admin only.`:`${e.description} ${zi}`,params:{resourceId:{type:"string",description:"Loan resourceId"},...e.params,...t?{preview:aSr}:{}},required:["resourceId",...e.required],group:"loan_events",readOnly:!1,isDestructive:!0,...t?{writesNothingWhen:r=>r.preview===!0}:{},searchHint:e.searchHint,execute:async(r,n)=>{let{resourceId:i,preview:o,...s}=n;return o4(r.client,e.event,i,s,o===!0)}}}function wO(e,t,r,n){return{name:e,description:r,params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD); positions are as at this date"},groupBy:{type:"string",enum:["TYPE","STATUS","ACCOUNT","LENDER"],description:"Grouping; omit for the template's"},filter:{type:"object",description:"Strict keys and operators, others are a 400: loanAccount{resourceId:{in:[]}}, loanBalance{gte,lte}, loanReference{contains}, loanName{contains}, loanType{in:[type names]}, loanStatus{in:[ACTIVE|REPAID|SETTLED|CLOSED_OUT|COMPLETED]}"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:n,isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(i,o)=>Nx(i.client,t,o)}}function Clt(e,t,r,n){return{[t]:!0,...yee(e),[r]:n}}function vO(e){return`Deletes a DRAFT ${e}; VOIDs an active one and KEEPS it. force: true hard-deletes either.`}function Ur(e,t,r,n,i,o){let s=o?.verb??"deleted";return{name:e,description:t,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"},...o?.voidable?uSr:{}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(a,c)=>{let u=c.resourceId;Zi(u,"resourceId",`Nothing was deleted. Source a real resourceId from a search_* or list_* result before calling ${e}.`);let d=c.force,f=await n(a.client,u,{force:d,internalNotes:c.internalNotes});return o?.voidable?xc(f,u,d):Clt(f,s,"resourceId",u)}}}function Y4(e,t){return{type:"object",...t?{description:t}:{},properties:Object.fromEntries(Object.entries(Mat[e]).map(([r,n])=>[r,n==="list"?{type:"array",items:{type:"string"},...r==="in"?{description:"Up to 100"}:{}}:{type:"string"}]))}}function Dv(e,t){return{error:e,_guard:"confirmation_required",message:t}}function ige(e,t){return typeof t=="string"&&e.taskRecordIds?.has(t)===!0}function olt(e,t,r,n,i){let o=dv[i].change.filter(c=>c in n),s=[...gW,...yW].includes(t);if(!e.toolCalls||!Array.isArray(r)||o.length===0||s)return;let a=r.filter(c=>!ige(e,c));if(!(a.length<2))return Dv(`Not changed: ${o.join(", ")} on ${a.length} records needs a preview the user confirms.`,`Nothing was changed. Several records: preview them with preview_ledger_find_fix (level ${i}), show the user, and apply after they confirm. Fields Ledger Find & Fix does not set can still use this tool.`)}function HE(e,t,r){let n=e.toolCalls;if(!n||ige(e,r)||n.some(o=>o.tool_name==="preview_ledger_find_fix"))return;let i=n.filter(o=>ESr.has(o.tool_name)&&!ige(e,o.input?.resourceId)).length;if(!(i<bSr))return Dv(`Not changed: ${i+1} single-record ledger writes in this run with no preview.`,`Nothing was changed by ${t}. Several records are getting the same kind of fix one at a time: stop looping update_* calls and use preview_ledger_find_fix instead (level TRANSACTIONS for contact, date, capsule or tags; LINE_ITEMS for account or classifiers). Show the user the preview and apply only after they confirm.`)}function ISr(e){let t=e.toolCalls;if(t){for(let r=t.length-1;r>=0;r--)if(t[r].tool_name==="preview_ledger_find_fix")return t[r].input?.filter}}function _Sr(e){if(!(e<CSr))return{tool:"preview_ledger_find_fix",reason:`This filter matched ${e} records; a single preview can apply at most 500. A count this large from a conversational request usually means a constraint (a reference, a contact, a date range) is missing rather than genuinely intended. Check the filter before applying, or before telling the user this many records matched; narrow it or split the work into several previews.`}}function wSr(e,t){if(!t||typeof t!="object"||Array.isArray(t)||!e||typeof e!="object"||Array.isArray(e))return;let r=Object.keys(t).filter(n=>!(n in e));if(r.length!==0)return{tool:"preview_ledger_find_fix",reason:`This preview's filter has no ${r.join(", ")}, but the previous preview in this conversation did. If this was meant to narrow further, ${r.length===1?"that constraint":"those constraints"} may have been dropped by mistake rather than intentionally removed; check before treating this as the right set of records.`}}function RO(e,t,r,n){return{name:e,description:`Download ${/^[aeiou]/i.test(t)?"an":"a"} ${t} as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).`,params:{resourceId:{type:"string",description:`${t[0].toUpperCase()}${t.slice(1)} resourceId`}},required:["resourceId"],group:r,readOnly:!0,searchHint:`download ${t} as PDF document file`,isConcurrencySafe:!0,execute:async(i,o)=>n(i.client,o.resourceId)}}function ZAe(e,t,r,n,i){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function slt(e){if(typeof e!="string"||/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=/^(\d{4}-\d{2}-\d{2})T/.exec(e);return t?t[1]:e}function RSr(e){return Array.isArray(e)?e.map(t=>{let r={};for(let[n,i]of Object.entries(t)){if(i==null)continue;let o=dee.get(n);if(o)r[o]=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else if(n==="withholdingTax"){let s=NI(i);s&&(r.withholdingTax=s)}else DSr.has(n)&&(r[n]=i)}return r}):e}async function _lt(e,t,r){let n=t==="invoice"?Eo:t==="bill"?ho:t==="customer_credit_note"?Vs:t==="supplier_credit_note"?Ws:void 0;if(!n)throw new ct(`Unknown transaction type "${String(t)}". Use one of: ${oge.join(", ")}.`);let o=(await n(e,r)).data,s=SSr[t],a={};for(let[c,u]of Object.entries(o))s.has(c)&&u!==null&&u!==void 0&&(a[c]=u);return a.valueDate&&(a.valueDate=slt(a.valueDate)),a.dueDate&&(a.dueDate=slt(a.dueDate)),a.lineItems&&(a.lineItems=RSr(a.lineItems)),a}function wlt(e,t){for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}async function H4(e,t,r,n,i){let o=await _lt(e,t,r);delete o.lineItems;let s=o.tags,a=wlt(o,n);return i&&(a.tags=ui(s,i)),a}function alt(e){return e===void 0?void 0:Xn({add:[e]},"tag")}async function TO(e,t,r,n){let i=wlt(await _lt(e,t,r),n),o=t==="invoice"?tl:t==="bill"?xa:vo,{missingFields:s,ready:a}=ia(i,o);if(!a)throw new Error(`Cannot finalize: missing ${s.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return i}async function clt(e,t,r,n){if((await e(t,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function zE(e,t,r){if(!(typeof e=="string"&&t.includes(e)))return{error:`Unknown documentType ${JSON.stringify(e)}.`,status:422,hint:`Use one of: ${t.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}async function llt(e,t,r,n,i,o,s,a){let c;try{c=(await t(e,r)).data?.status}catch{return}if(c==="DRAFT"){let u=vf[i],d=`A DRAFT ${n} can't be linked or accepted. Issue this one in place with ${s} ${u}:true plus every stored line with its resourceId (status ${a}; without lineItems the update is refused), then link the order to it. Do not create a second ${n}.`;return{error:`Cannot create an order linked to a DRAFT ${n} (${r}).`,status:422,hint:`Pre-flight guard, request never hit the API. ${d}`,repair:{tool:s,arguments:{documentType:i,resourceId:r,[u]:!0},reason:d}}}if(c==="VOID"){let u=`A VOID ${n} can't be used. Create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a VOID ${n} (${r}).`,status:422,hint:`Pre-flight guard, request never hit the API. ${u}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:u}}}}async function ult(e,t,r,n,i,o,s){let a=Ore(e,r);if(a.length>0){let u=vf[e],d=`${a.join(", ")} does not apply to ${e}; its flag is ${u}.`;return{error:d,status:422,hint:"Pre-flight guard, request never hit the API.",repair:{tool:s,arguments:{documentType:e,resourceId:t,[u]:!0},reason:d}}}let c=await Fre(e,r.lineItems,i,{appendLines:n===!0,appendOptIn:"appendLines: true"});if(c)return{error:c.message,status:422,code:c.code,hint:`Pre-flight guard, request never hit the API. Call ${o} for the stored lines, then resend every one with its resourceId.`,repair:{tool:o,arguments:{documentType:e,resourceId:t},reason:"Read the resourceId of every stored line before editing lines."}}}async function dlt(e,t,r,n,i,o){let s;try{s=(await t(e,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard: request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function TSr(e,t,r,n,i){let o;try{o=(await t(e,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r}; delete is only allowed on DRAFT records.`,status:422,hint:`Use ${i} to cancel a non-draft quote/request/order.`,repair:{tool:i,arguments:{documentType:r,resourceId:n},reason:`${r} is ${o}; void it instead of deleting.`}}}function flt(e){let t=`${e.quote} or ${e.order}`,r=i=>({type:"string",description:`${i} resourceId`}),n=(i,o)=>zE(o.documentType,e.docTypes,i);return[{name:e.names.accept,description:`Accept an issued ${e.quote} (${e.issued} \u2192 ACCEPTED). A DRAFT can't be accepted: issue it first with ${e.issueVia}. An issued ${e.quote} can already be linked, so accepting is optional.`,params:{resourceId:r(e.quote)},required:["resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`accept ${e.quote.toLowerCase()} approve`,execute:async(i,o)=>e.accept(i.client,o.resourceId)},{name:e.names.confirm,description:`Confirm a ${e.order} (\u2192 CONFIRMED).`,params:{resourceId:r(e.order)},required:["resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`confirm ${e.order.toLowerCase()}`,execute:async(i,o)=>e.confirm(i.client,o.resourceId)},{name:e.names.void,description:`Void (cancel) a ${t} that is not a draft. For a draft use ${e.names.delete}.`,params:{documentType:e.docTypeParam,resourceId:sc,internalNotes:{type:"string",description:"Optional reason recorded on the document."}},required:["documentType","resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`void cancel ${e.quote.toLowerCase()} ${e.order.toLowerCase()}`,execute:async(i,o)=>{let s=n(e.names.void,o);return s||e.voidDoc(i.client,o.documentType,o.resourceId,o.internalNotes)}},{name:e.names.delete,description:`Delete a DRAFT ${t}. Anything issued: ${e.names.void}.`,params:{documentType:e.docTypeParam,resourceId:sc},required:["documentType","resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`delete draft ${e.quote.toLowerCase()} ${e.order.toLowerCase()}`,execute:async(i,o)=>{let s=n(e.names.delete,o);if(s)return s;let a=o.documentType,c=o.resourceId,u=await TSr(i.client,e.getDoc,a,c,e.names.void);return u||(await e.deleteDoc(i.client,a,c),{deleted:!0,resourceId:c})}}]}async function cge(e,t,r){return Promise.all(r.map(async n=>(await V4[t].get(e.client,n)).data))}function lge(e,t){let r=t.filter(i=>SZ(i).length>0);if(r.length===0)return;let n=V4[e].settlementKey==="refunds";return Dv(`Not changed: this would delete the recorded ${n?"refunds":"payments"} on ${r.length} document${r.length>1?"s":""}.`,YNe(r,n))}async function hA(e,t,r,n,i){let{lineItems:o,taxInclusion:s}=n;if(i===!0||o===void 0&&s===void 0)return;let[a]=await cge(e,t,[r]),c=s!==void 0&&s!==a.taxInclusion,u=o!==void 0&&jNe(a.lineItems,o);return c||u?lge(t,[a]):void 0}async function kSr(e,t,r,n,i,o){if(!Array.isArray(i)||i.length===0)throw ut(new ct(`Changing ${o.join(", ")} on lines can delete their documents' payments: also send resourceIds, the ${r} these lines are on. Nothing was changed.`));let s=new Set(Array.isArray(n)?n:[]),a=f=>(Array.isArray(f.lineItems)?f.lineItems:[]).map(p=>p.resourceId),c=(await cge(e,t,i)).filter(f=>a(f).some(p=>p!==void 0&&s.has(p))),u=new Set(c.flatMap(a)),d=[...s].filter(f=>!u.has(f));if(d.length)throw ut(new ct(`Line ${d.join(", ")} is not on the ${r} in resourceIds: send the documents these lines are on. Nothing was changed.`));return lge(t,c)}function ege(e,t){return(t.data?.validFiles?.length??0)>0&&SD(e)?{...t,next:eh[e]}:t}function LO(e,t,r){return`${e} ${e===1?t:r}`}function QO(e,...t){return t.reduce((r,n)=>r+(Array.isArray(e[n])?e[n].length:0),0)}function BSr(e){if(typeof e=="string")try{let t=new URL(e).pathname.split("/").filter(Boolean).pop();return t?decodeURIComponent(t):void 0}catch{return}}function OSr(e,t,r){let n=t?.data;if(!n||!Array.isArray(n.validFiles))return[];let i=typeof n.filename=="string"&&n.filename!==""?n.filename:void 0;return n.validFiles.flatMap(o=>{if(typeof o?.workflowResourceId!="string"||o.workflowResourceId==="")return[];let s=o.fileDetails?.fileName||i||r,a=e!=="MAGIC_CLAIM"&&typeof o.backgroundJobId=="string"&&o.backgroundJobId!=="";return[{kind:e,id:o.workflowResourceId,label:s,...a?{backgroundJobId:o.backgroundJobId}:{},..._U(o.subscriptionFBPath,o.backgroundJobFBPath)}]})}function tge(e,t,r){return{kind:e,count:()=>1,jobs:(n,i)=>OSr(e,n,BSr(i[t])??r)}}function PO(e,t){return{kind:"BACKGROUND_JOB",...t?{finishedNote:t}:{},count:()=>1,jobs:(r,n)=>{let i=CU(r);return i?[{kind:"BACKGROUND_JOB",id:i,label:e(n),..._U(qFe(r))}]:[]}}}function Pn(e,t,r,...n){return PO(i=>`${e} ${LO(QO(i,...n),t,r)}`)}function FSr(e){let t=typeof e=="string"?/\bfrom\s+([a-z_][\w.]*)/i.exec(e)?.[1]:void 0;return t?`${t} export`:"Query export"}function mlt(e,t){return e.data?.status!=="COMPLETED"||!e.data.downloadUrl?e:{...e,data:{...e.data,fileName:jst(t),fileUrl:e.data.downloadUrl}}}function vlt(e){let t=Array.isArray(e.documentTypes)?e.documentTypes:[],r=t.map(i=>({raw:i,doc:th(i)})),n=r.filter(i=>i.doc===null).map(i=>i.raw);return{documentTypes:t.length>0?r.map(i=>i.doc):void 0,unresolved:n}}async function Alt(e,t,r){let n=MD(e,hlt,t);if(n)return n;let i=t.filter(s=>!MD(e,hlt,[s]));if(i.length===t.length)return r(t);let o=await r(i);return{note:e.loopTurn?.backgroundNote,collectedWorkflowIds:t.filter(s=>!i.includes(s)),...o}}function MSr(e){let t=e.execute;return{...e,execute:async(r,n,i)=>{let o=n.id??n.filter?.resourceId?.eq;return(typeof o=="string"?MD(r,"BACKGROUND_JOB",[o]):null)??t(r,n,i)}}}function mA(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==null&&t!==""))}var H0r,sc,Oct,Fct,So,au,zi,M4,Iv,JAe,Mo,cu,bi,U4,dA,NO,BO,YE,z0r,lu,J0r,Lct,G0r,$4,V0r,Id,Qct,Pct,Mct,GAe,VAe,JE,bO,W0r,K0r,nge,X0r,Z0r,Uct,WAe,OO,fA,pA,ylt,$ct,oa,KAe,qct,jct,Yct,Hct,IO,Tn,Elt,blt,zct,Jct,CO,up,tSr,rSr,Ilt,nSr,sa,uu,iSr,oSr,sSr,Cv,aSr,G4,cSr,Gct,j4,Cd,age,_O,Vct,Wct,Kct,lp,Sv,lSr,uSr,Zct,elt,tlt,dSr,SO,DO,fSr,rlt,pSr,hSr,XAe,nlt,mSr,ASr,gSr,ySr,ilt,ESr,bSr,CSr,vSr,oge,SSr,DSr,xO,kO,z4,V4,plt,xSr,NSr,hlt,sge,LSr,QSr,PSr,_v,wv,vv,J4,glt,rge,du,W4=J(()=>{"use strict";FFe();bU();zFe();cee();aC();NU();pee();Aee();kg();qD();Ki();zt();ot();nf();Fl();eD();xre();kre();yg();zg();af();Nre();Bre();Lre();Jg();Qre();Rg();PP();xl();JP();Pre();S$e();Yu();Hx();Kx();gj();nst();oD();aM();uD();AD();pD();A2();ZG();Sme();dV();JM();Fme();Rg();JB();Lme();Qme();CV();Qst();qme();jme();Yme();zme();Gme();nA();tat();iv();Af();Kme();Xme();Zme();gD();eee();iat();Mu();sat();uat();hat();Cee();Aat();cAe();T8();lAe();K8();uAe();dAe();fAe();EW();IAe();vAe();fo();CAe();SAe();DAe();IU();yg();YS();zg();RAe();Jg();nct();af();Hx();Kx();Jg();T8();hv();hq();kAe();an();NAe();_4();zt();LAe();QAe();TE();hf();Lu();H0r=PU.join(" | "),sc={type:"string",description:"Resource ID of the record"},Oct={type:"string",description:"Optional: the suggestion's recommendationId (UUID) from view_auto_reconciliation, so the accept is credited to it"},Fct={learnedPredictionResourceId:{type:"string",description:"Learned-prediction id from the suggestion (required to accept one)"},predictedPayload:{type:"string",description:"Opaque JSON string from the suggestion, passed verbatim (required to accept one)"},predictedPayloadSchemaVersion:{type:"string",description:"Schema version from the suggestion (required to accept one)"},retryToken:{type:"string",description:"Optional idempotency retry token: a fresh one forces a new journal on an edit-then-retry; omit it to replay"}},So={type:"string",description:"Transaction date (YYYY-MM-DD)"},au={type:"string",description:"Due date (YYYY-MM-DD)"},zi="Admin only.",M4="Confirm first: say what it changes and wait for a yes.",Iv="Term loans, not CUSTOM-schedule.",JAe={type:"string",description:"Ignored in a preview. Needed unless the loan already has one, when a gain or loss posts (LOAN_GAIN_LOSS_ACCOUNT_REQUIRED)."},Mo={type:"string",description:"Reference number"},cu={type:"boolean",description:"Use the org's own next number instead of `reference`."},bi={type:"string",description:"Notes or memo text"},U4={type:"boolean",description:"Line amounts include tax"},dA={type:"string",description:"Tag name for categorization"},NO={type:"array",items:{type:"string"},description:"Tags (string array)"},BO={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},YE={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},z0r={type:{type:"string",enum:[...VI],description:"Calculator to run"},amount:{type:"number",description:"Amount (for prepaid-expense, deferred-revenue, accrued-expense, dividend, provision, fx-reval)"},principal:{type:"number",description:"Principal (for loan, fixed-deposit)"},startDate:{type:"string",description:"Start date YYYY-MM-DD. Needed for dated steps; without it most calculators return the schedule only."},currency:{type:"string",description:"Currency code (e.g. SGD, USD)"},periods:{type:"number",description:"Number of periods (for prepaid-expense, deferred-revenue, accrued-expense; leave-accrual months, default 12)"},frequency:{type:"string",enum:["monthly","quarterly","annual"],description:"depreciation: annual (default) or monthly. prepaid-expense, deferred-revenue, accrued-expense: monthly (default) or quarterly"},annualRate:{type:"number",description:"Annual interest/discount rate %"},termMonths:{type:"number"},monthlyPayment:{type:"number",description:"Monthly lease payment (for lease)"},usefulLifeMonths:{type:"number",description:"Asset useful life in months (hire purchase)"},cost:{type:"number",description:"Asset cost"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"],description:"Depreciation method"},acquisitionDate:{type:"string",description:"Acquisition date YYYY-MM-DD"},disposalDate:{type:"string",description:"Disposal date YYYY-MM-DD"},proceeds:{type:"number",description:"Disposal proceeds"},bookRate:{type:"number",description:"Original booking rate. Declare which way it reads via rateDirection (REQUIRED for fx-reval)."},closingRate:{type:"number",description:"Period-end closing rate. Same direction as bookRate."},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"REQUIRED for fx-reval. FUNCTIONAL_TO_SOURCE = 1 base unit = N foreign, what list_currency_rates returns. SOURCE_TO_FUNCTIONAL = 1 foreign unit = N base, the everyday quote."},position:{type:"string",enum:["ASSET","LIABILITY"],description:"Balance-sheet side: ASSET (receivable/deposit, default) or LIABILITY (payable/provision). A rising base value is a gain on an asset and a loss on a liability."},baseCurrency:{type:"string",description:"Base (functional) currency"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string",description:'Bucket label, e.g. "1-30 days"'},balance:{type:"number",description:"Receivables balance in this bucket"},rate:{type:"number",description:"Expected loss rate %"}},required:["name","balance","rate"]},description:"ECL aging buckets"},existingProvision:{type:"number",description:"Existing ECL provision balance"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number",description:"Leave days per employee per year"},dailyRate:{type:"number",description:"Average daily rate"},declarationDate:{type:"string",description:"Board resolution date YYYY-MM-DD"},paymentDate:{type:"string",description:"Settlement date YYYY-MM-DD"},withholdingRate:{type:"number",description:"Withholding tax rate %"}},lu={type:"string",description:"Capsule to file this under (from create_capsule)"},J0r={in:"{in: [names]}",gte:"{gte, lte: number}",lte:"{gte, lte: number}",contains:"{contains: text}"},Lct=e=>({type:"object",description:[...new Set(e.map(t=>J0r[t]))].join(" ")}),G0r={type:"object",description:"deferralCategory: PREPAID_EXPENSE, DEFERRED_REVENUE. deferralStatus: ACTIVE, FULLY_AMORTIZED, CLOSED_OUT, COMPLETED. deferralType: type name",properties:Object.fromEntries(Object.entries(pq).map(([e,t])=>[e,Array.isArray(t)?Lct(t):{type:"object",properties:{resourceId:Lct(t.resourceId)}}]))},$4={type:"array",items:{type:"object",properties:{fromPeriod:{type:"number",description:"First period, 1-based"},toPeriod:{type:"number",description:"Last period, inclusive"},amount:{type:"number",description:"Released in EACH period of the range"}},required:["fromPeriod","toPeriod","amount"]}},V0r={type:"boolean",description:"Retry-only: set true after the duplicate guard surfaced a candidate and the user confirmed this is a separate document. Never on a first attempt."},Id={type:"boolean",description:"Only after the user confirmed the payment deletion this tool reported."},Qct={type:"string",enum:[...bee],description:"CUSTOM (default) = free text; ALL_* = a picklist of that population. Datatype is derived, not chosen."},Pct={type:"object",properties:{address:{type:"string",description:"Street address, sent as addressLine1"},city:{type:"string"},state:{type:"string"},postalCode:{type:"string"},country:{type:"string"}},required:["address","country"]},Mct={type:"object",properties:{name:{type:"string",enum:[...fZ]},value:{type:"string",description:'Days, e.g. "21". CUSTOM only; dropped otherwise.'}}},GAe={type:"string",description:"Contact resourceId (customer or supplier)"},VAe={type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID)"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Draft entity type"}},required:["btResourceId","btType"]}},JE={type:"string",description:"Chart-of-accounts account the line posts to (revenue on a sale, expense on a purchase)"},bO={type:"string",description:"Account the payment posts to. For paymentMethod BANK_TRANSFER/CASH/CHEQUE this MUST be a bank or cash account. Any other method accepts any org account; that is how a deposit drawdown works (paymentMethod OTHER + the deposit account)."},W0r={type:"number",description:"Payment amount (in bank currency)"},K0r={type:"string",description:"Period start date (YYYY-MM-DD)"},nge={type:"string",description:"Period end date (YYYY-MM-DD)"},X0r={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report"); it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},Z0r={receivables:{label:"Aged Receivables",party:"customer",use:"credit control, collections and customer payment follow-up",byContact:(e,t)=>bq(e,t),summary:(e,t)=>Nq(e,t)},payables:{label:"Aged Payables",party:"supplier",use:"payment runs and supplier follow-up",byContact:(e,t)=>Iq(e,t),summary:(e,t)=>Bq(e,t)}};Uct={type:"string",description:"Currency code (e.g. SGD, USD)"},WAe={type:"string",description:"Display name"},OO={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},fA={fromPeriod:{type:"number",description:"First period, from 1."},toPeriod:{type:"number",description:"Last period, inclusive."}},pA=e=>({fromPeriod:e.fromPeriod,toPeriod:e.toPeriod}),ylt=50,$ct=new Set(["startDate","endDate","groupBy","limit","offset","accountResourceIds","accountResourceId"]);oa={type:"object",required:["sourceCurrency"],properties:{sourceCurrency:{type:"string",description:"Foreign currency code (ISO 4217)."},exchangeRate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N sourceCurrency. Invert ONLY if your quote reads "1 source = X base" (send 1/X), or declare rateDirection and skip the arithmetic. Omit for the org/platform rate.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"How exchangeRate reads. SOURCE_TO_FUNCTIONAL accepts a bank quote verbatim. Default FUNCTIONAL_TO_SOURCE."}}},KAe={type:"string",enum:[...yf],description:"Entity type to export"},qct={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter; pass one or the other, never both.'},jct={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query; pass one or the other, never both.'},Yct={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},Hct={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},IO={type:"array",description:"CUSTOM_SCHEDULE only: month ranges (1-based, amount per month) covering 1..effectiveLife, no gap or overlap, summing to the depreciable value (book value for a transfer). Update: omit to keep.",items:{type:"object",properties:{fromPeriod:{type:"number",description:"First month"},toPeriod:{type:"number",description:"Last month"},amount:{type:"number",description:"Per month"}},required:["fromPeriod","toPeriod","amount"]}},Tn={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Elt={type:"array",description:"The rent: amount is the rent of EACH month in the range. Ranges cover months 1 to leaseTerm, no gap or overlap. Quarterly or yearly rent goes month by month, 0 in the other months.",items:{type:"object",properties:{fromPeriod:{type:"number",description:"First month, 1-based"},toPeriod:{type:"number",description:"Last month, inclusive"},amount:{type:"number",description:"Rent per month"}},required:["fromPeriod","toPeriod","amount"]}},blt=["RIGHT_OF_USE_ASSET","EXEMPT"],zct={name:{type:"string",description:"Lease name"},typeCode:{type:"string",description:"From search_lease_types; HIRE_PURCHASE for hire purchase"},exemptionType:{type:"string",enum:[...blt],description:"EXEMPT = short-term or low-value, posts nothing"},contactResourceId:{type:"string",description:"Lessor contact"},commencementDate:{type:"string",description:"YYYY-MM-DD. Month 1 runs to that month-end, no day pro-rating. A lease from before Jaz starts at go-live."},leaseTerm:{type:"number",description:"Months, 1-600"},customSchedule:Elt,paymentTiming:{type:"string",enum:[...sh],description:"ADVANCE (start of month) or ARREARS (end)"},discountRate:{type:"number",description:"% per MONTH, up to 4 decimals: 6% a year is 0.5, not 6 and not 0.06. Nominal annual rate / 12."},prepaidLeasePaymentsAmount:{type:"number",description:"Rent paid before the start; with ADVANCE leave month 1 out"},restorationCostAmount:{type:"number",description:"Expected make-good cost at term end, booked day 1 at present value"},ownershipTransfers:{type:"boolean",description:"Ownership passes at the end (hire purchase): depreciates over usefulLife"},usefulLife:{type:"number",description:"Months, 1-1200; needed with ownershipTransfers"},purchaseOptionPrice:{type:"number",description:"Balloon paid at term end, with ownershipTransfers"},rouAssetAccountResourceId:{type:"string",description:"Right-of-Use Asset account (Fixed Asset type)"},accumulatedDepreciationAccountResourceId:{type:"string",description:"Accumulated Depreciation account (Fixed Asset type)"},depreciationExpenseAccountResourceId:{type:"string",description:"Depreciation Expense account"},leaseLiabilityAccountResourceId:{type:"string",description:"Current Lease Liability account: rent is coded here"},leaseLiabilityNonCurrentAccountResourceId:{type:"string",description:"Non-current Lease Liability account, needed when principal falls due after 12 months"},interestExpenseAccountResourceId:{type:"string",description:"Interest Expense account (Finance Cost type)"},restorationProvisionAccountResourceId:{type:"string",description:"Needed when restorationCostAmount > 0"},prepaidLeasePaymentsAccountResourceId:{type:"string",description:"Prepaid Rent account (Current Asset, not a deferral account), needed when prepaid rent > 0"},internalNotes:{type:"string",description:"Internal notes"},customFields:Tn,capsuleResourceId:lu},Jct={type:"array",description:"Full replacement line-item set: non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},CO={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},up={type:"array",items:{type:"object",required:["resourceId","type","selectedClasses","printable"],properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",required:["className"],properties:{className:{type:"string"},resourceId:sc,entityResourceId:{type:"string"}}}},printable:{type:"boolean",description:"Show on printed documents."}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},tSr={type:"object",description:"Defaults for documents generated from the asset: notes, numbering, account, tax, payment, currency. Send only to set or change; omit to keep. get_fixed_asset returns it as opaque text.",properties:{resourceId:{type:"string"},businessTransactionType:{type:"string"},invoiceNotes:{type:"string"},currencySettings:{type:"object",properties:{sourceCurrencyCode:{type:"string"},rateFunctionalToSource:{type:"number"},exchangeToken:{type:"string"}}},taxCurrencySettings:{type:"object",properties:{sourceCurrencyCode:{type:"string"},rateFunctionalToSource:{type:"number"},exchangeToken:{type:"string"}}},detailSettings:{type:"object",properties:{prefix:{type:"string"},separator:{type:"string"},dateInclusion:{type:"string"},seriesStart:{type:"number"}}},itemAccount:{type:"object",properties:{itemLevel:{type:"boolean"},organizationAccountResourceId:{type:"string"}}},itemAttribute:{type:"object",properties:{discount:{type:"boolean"},quantity:{type:"boolean"},unit:{type:"boolean"}}},itemTax:{type:"object",properties:{itemLevel:{type:"boolean"},taxInclusive:{type:"boolean"},taxProfileResourceId:{type:"string"}}},paymentSettings:{type:"object",properties:{organizationAccountResourceId:{type:"string"},paymentMethod:{type:"string"}}}}},rSr={...up,items:{...up.items,properties:{...up.items.properties,selectedClasses:{...up.items.properties.selectedClasses,description:"Classes picked within the classifier"}}}},Ilt={type:"array",description:"Max 50. On update the list REPLACES all fees: send every one to keep.",items:{type:"object",required:["feeType","amount","treatment","paidFrom"],properties:{resourceId:{type:"string"},feeType:{type:"string",enum:["ARRANGEMENT","LEGAL","STAMP_DUTY","VALUATION","GUARANTEE","OTHER"],description:"Fee kind"},amount:{type:"number"},treatment:{type:"string",enum:["SPREAD","EXPENSE","ON_SETTLEMENT"],description:"SPREAD needs the loan's unamortizedCostsAccountResourceId; EXPENSE needs accountResourceId; ON_SETTLEMENT is only quoted"},paidFrom:{type:"string",enum:["DEDUCTED","SEPARATE"],description:"DEDUCTED = lender took it from the drawdown"},accountResourceId:{type:"string"}}}},nSr={type:"array",description:"CUSTOM only: the lender's rows (max 600). For a lender change send revised rows with update_loan; schedule-rebuilding events are refused.",items:{type:"object",required:["dueDate","principal","interest"],properties:{dueDate:{type:"string",description:"YYYY-MM-DD, after drawdown, ascending"},principal:{type:"number",description:"Principal in this installment"},interest:{type:"number",description:"Interest in this installment"}}}},sa={kind:{type:"string",enum:["TERM","ON_DEMAND"],description:"ON_DEMAND = overdraft, revolving or director account, no schedule"},principalAmount:{type:"number",description:"Above 0, 2 dp"},drawdownDate:{type:"string",description:"YYYY-MM-DD"},trackingStartDate:{type:"string",description:"Existing loan: go-live date; needs openingPrincipalAmount"},openingPrincipalAmount:{type:"number",description:"Principal outstanding on trackingStartDate"},annualInterestRate:{type:"number",description:"Percent per YEAR as the lender quotes it: 6.5 = 6.5% a year, not 0.065; 0 = interest-free. Required for TERM unless CUSTOM."},dayCount:{type:"string",enum:["ACTUAL_365","ACTUAL_360","THIRTY_E_360","MONTHLY"],description:"MONTHLY = rate / 12; most banks ACTUAL_365. Required for TERM unless CUSTOM."},repaymentShape:{type:"string",enum:["ANNUITY","EQUAL_PRINCIPAL","INTEREST_ONLY_THEN_ANNUITY","BULLET","BALLOON","CUSTOM"],description:"ANNUITY = level installment. Required for TERM."},customSchedule:nSr,loanTerm:{type:"number",description:"Months, 1-600. Required for TERM unless CUSTOM."},firstRepaymentDate:{type:"string",description:"YYYY-MM-DD; default one month after drawdown"},interestOnlyMonths:{type:"number",description:"INTEREST_ONLY_THEN_ANNUITY: 1 to term-1"},balloonAmount:{type:"number",description:"BALLOON: principal left for the last installment"},installmentOverride:{type:"number",description:"The lender's installment when it differs by rounding; not on EQUAL_PRINCIPAL or BULLET"},fees:Ilt},uu={reference:{type:"string",description:"Unique; get_next_reference (LOAN)"},name:{type:"string",description:"Required to activate"},typeCode:{type:"string",description:"From search_loan_types. Required to activate."},contactResourceId:{type:"string",description:"Lender contact"},...sa,capitalizationStartDate:{type:"string",description:"IAS 23: interest from here to capitalizationEndDate goes to capitalizationAccountResourceId, not expense"},capitalizationEndDate:{type:"string",description:"YYYY-MM-DD"},currentLiabilityAccountResourceId:{type:"string",description:"Current Liability account; each installment is recorded IN FULL here"},nonCurrentLiabilityAccountResourceId:{type:"string",description:"Non-current Liability account; drawdown cash is recorded here. Needed when principal falls due after 12 months"},interestExpenseAccountResourceId:{type:"string",description:"Finance Cost account, for a rate above 0"},unamortizedCostsAccountResourceId:{type:"string",description:"For SPREAD fees and restructures under 10%"},gainLossAccountResourceId:{type:"string",description:"For forgiveness, conversion, restructure"},capitalizationAccountResourceId:{type:"string",description:"Fixed Asset account"},internalNotes:{type:"string"},tags:NO},iSr=["reference","name","typeCode","contactResourceId","kind","principalAmount","drawdownDate","annualInterestRate","dayCount","repaymentShape","loanTerm","interestOnlyMonths","balloonAmount","currentLiabilityAccountResourceId","nonCurrentLiabilityAccountResourceId","interestExpenseAccountResourceId","fees","unamortizedCostsAccountResourceId"],oSr=Object.fromEntries(iSr.map(e=>[e,uu[e]])),sSr=Object.fromEntries(Object.entries(uu).filter(([e])=>e!=="tags")),Cv={type:"number",description:"Principal confirmed on the date after a missed, late or partial payment; rebases the schedule, posts no cash. See calculate_loan_opening_balance."},aSr={type:"boolean",description:"true = figures only, nothing saved. Default false records the event."},G4={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},cSr={type:"number",description:"Line rate, account currency to base (opposite of currency.exchangeRate). Foreign-account lines only; 0, or non-1 on a base-currency line, is 422."},Gct={...G4,items:{...G4.items,properties:{...G4.items.properties,exchangeRate:cSr}}},j4={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Offset account resourceId"},amount:{type:"number",description:"Amount (positive; direction comes from the endpoint)"},description:{type:"string",description:"Line description"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId"}},required:["accountResourceId","amount"]},description:"Offset lines. No `type`; cash-in credits these and cash-out debits them, decided by the endpoint."},Cd={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:JE,taxProfileResourceId:{type:"string"},classifierConfig:up},required:["name","quantity","unitPrice"]},description:"Line items: include accountResourceId on each line when finalizing (saveAsDraft: false)"},age={type:"object",required:["code","rate"],properties:{code:{type:"string",description:'e.g. "WC 158"'},rate:{type:"number",description:"Rate %"},type:{type:"string"},description:{type:"string"}},description:"EWT (PH): copy all four from a list_withholding_codes row; omitted ones are not stored."},_O={...Cd,items:{...Cd.items,properties:{...Cd.items.properties,withholdingTax:age}}},Vct={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Stored line id (from get). Omit only for a new line."},deleted:{type:"boolean",description:"With resourceId: remove the line."},name:{type:"string",description:"Line name (every line, deleted too)."},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:JE,taxProfileResourceId:{type:"string"},discount:{type:"number"},unit:{type:"string"},itemResourceId:{type:"string"},taxVatAdjustment:{type:"object",properties:{adjustmentAmount:{type:"number"},notes:{type:"string"}}},withholdingTax:age,classifierConfig:up}},description:"Edits, not a replacement: send EVERY stored line with its resourceId, in order (deleted:true removes; a line without resourceId is ADDED). An edited line keeps only what is sent: resend every stored field you want kept (tax profile, taxVatAdjustment, withholdingTax, discount, unit, itemResourceId). A partial id set is refused; id-less lines on a document with lines are refused unless appendLines."},Wct={type:"boolean",description:"true: add id-less lineItems beside the stored lines on purpose."},Kct={type:"array",items:{type:"object",properties:{itemName:{type:"string",description:"Display name of the catalog item"},itemResourceId:{type:"string",description:"Underlying item resourceId (from search_items)"},price:{type:"number",description:"Default unit price (0-1e9)"},unit:{type:"string",description:"Unit of measure"},quantityDefault:{type:"number",description:"Default quantity when added to a document (0-100)"},discountDefault:{type:"number",description:"Default discount % when added to a document (0-100)"},uiIndex:{type:"number",description:"Display position in the catalog (integer, min 0)"},classifiers:{type:"array",items:{type:"object"},description:"Classifier assignments. Same shape as classifierConfig on invoice/bill line items."}},required:["itemName","itemResourceId","price"]},description:"Catalog item rows. itemName, itemResourceId and price are required on every row."},lp={type:"string",enum:[...MU],description:"Payment method (default BANK_TRANSFER)"},Sv={type:"object",description:"Cash-leg adjustment (overpayment/rounding). Bank leg only, never AR/AP. Not with DEBT_WRITE_OFF/CLEARING_SETTLEMENT/INTER_COMPANY/WITHHOLDING_TAX_CERTIFICATE. See rule 160.",properties:{adjustmentValue:{type:"number",description:"Signed, non-zero, max 2dp"},adjustmentAccountResourceId:{type:"string",description:"Non-controlled account, not bank/cash"},adjustmentDescription:{type:"string",description:"Optional"}},required:["adjustmentValue","adjustmentAccountResourceId"]},lSr={...Sv,description:"Adding or changing an adjustment applies here. REMOVING does not: 0 is rejected and null reads as omitted, so both leave the stored value unchanged. To remove one, delete the payment and record it again. A change is rejected if the payment is reconciled or lock-dated, and amount, account and description are all compared, so resend all three unchanged if you are not editing it. See rule 160."};uSr={force:{type:"boolean",description:gee.force},internalNotes:{type:"string",description:gee.internalNotes}};Zct={type:"string",description:"Document family",enum:[...ap]},elt={type:"string",description:"Document family",enum:[...PE]},tlt={type:"string",description:"Why it is sent back. Opens a thread; the only record of the reason."},dSr=[{name:"approve_documents",description:"Approve one PENDING document (a DRAFT takes finalize_*). Irreversible, posts its ledger: confirm with the user first. Unknown or other-org id: 404. A refusal or an unconfirmed answer returns error. After a timeout or 500, read approvalStatus before retrying.",params:{entity:Zct,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"approve pending invoice bill credit note post ledger",execute:async(e,t)=>{let r=await LW(e.client,t.entity,t.resourceId),n=FW(r?.data?.records);return n.state==="approved"?r:n.state==="refused"?{error:`Not approved: ${n.reason}`,outcome:"REFUSED",...r}:{error:"UNCONFIRMED: the API returned no per-record outcome, so the approval neither succeeded nor failed provably.",outcome:"UNCONFIRMED",hint:"Read the document's approvalStatus before approving again or reporting it approved.",...r}}},{name:"bulk_approve_documents",description:`Approve up to 100 PENDING documents. Irreversible, posts each ledger: confirm first. Async: returns the final job if it finished, else a jobId to poll with search_background_jobs. ${rs} One unknown or other-org id: whole batch 422. Non-pending ones are skipped, listed on the job tasks. After a timeout or 500, read approvalStatus before retrying.`,params:{entity:Zct,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-100)"}},required:["entity","resourceIds"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"bulk approve many pending documents at once",backgroundJob:Pn("Approve","document","documents","resourceIds"),execute:async(e,t)=>QW(e.client,t.entity,t.resourceIds)},{name:"request_document_changes",description:"Send one document back for changes instead of approving it. Also covers orders, quotes, requests and claims.",params:{entity:elt,resourceId:{type:"string",description:"Document resourceId"},message:tlt},required:["entity","resourceId","message"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"request changes reject send back document for revision",execute:async(e,t)=>PW(e.client,t.entity,t.resourceId,t.message)},{name:"bulk_request_document_changes",description:`Send up to 500 documents back for changes with one message. Async: returns the final job if it finished, else a jobId to poll with search_background_jobs. ${rs}`,params:{entity:elt,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-500)"},message:tlt},required:["entity","resourceIds","message"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"bulk request changes send back many documents",backgroundJob:PO(e=>`Send ${LO(QO(e,"resourceIds"),"document","documents")} back for changes`),execute:async(e,t)=>MW(e.client,t.entity,t.resourceIds,t.message)}],SO={type:"string",description:"Unapplied payment resourceId"},DO={type:"string",description:"From search_unapplied_payments or the last write"},fSr={type:"string",enum:[...Mst],description:"Document type"},rlt={type:"object",properties:{feeValue:{type:"number",description:"Amount or percent"},feeType:{type:"string",enum:[...Ust],description:"AMOUNT, not FLAT"},feeOrganizationAccountResourceId:{type:"string",description:"Fee account"},taxVatProfileResourceId:{type:"string"},feeTaxVatApplicable:{type:"boolean"}},required:["feeValue","feeType","feeOrganizationAccountResourceId"]},pSr=[Nt({name:"search_unapplied_payments",description:"Unapplied payments (cash not yet applied to documents). The only read path: rows carry hash (every write needs it), unappliedStatus and unappliedBalance. A record whose cash is all applied became a batch payment and no longer appears here.",group:"unapplied_payments",fields:jR,defaults:YR,fetcher:OV,searchHint:"unallocated receipt deposit prepayment on account"}),{name:"record_unapplied_payment",description:"Record cash received (SALE) or paid (PURCHASE) before applying it to documents. Draft by default (posts nothing until finalize_unapplied_payment); saveAsDraft:false posts to the ledger now.",params:{businessTransactionType:{type:"string",enum:[...NV],description:"SALE received, PURCHASE paid"},organizationAccountResourceId:{type:"string",description:"Bank/cash account"},paymentMethod:lp,amount:{type:"number"},valueDate:{type:"string",description:"YYYY-MM-DD"},currencyCode:{type:"string",description:"ISO 4217"},rateToFunctional:{type:"number",description:"Required for a foreign currency"},contactResourceId:{type:"string"},reference:{type:"string"},notes:{type:"string"},saveAsDraft:BO},required:["businessTransactionType","organizationAccountResourceId","paymentMethod","amount","valueDate","currencyCode"],group:"unapplied_payments",readOnly:!1,searchHint:"record unapplied payment advance",execute:async(e,t)=>FV(e.client,{...t,saveAsDraft:t.saveAsDraft??!0})},{name:"update_unapplied_payment",description:"Edit an unapplied payment. New amount, account or date releases its bank match; a move to a foreign-currency account needs amount restated and rateToFunctional. Attribution rows (children): CLI --input.",params:{resourceId:SO,hash:DO,reference:{type:"string"},notes:{type:"string"},paymentMethod:lp,amount:{type:"number"},organizationAccountResourceId:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD"},rateToFunctional:{type:"number"}},required:["resourceId","hash"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"edit unapplied payment",execute:async(e,t)=>{let{resourceId:r,...n}=t;return LV(e.client,r,n)}},{name:"finalize_unapplied_payment",description:"Activate a DRAFT unapplied payment; the ledger posts now.",params:{resourceId:SO,hash:DO},required:["resourceId","hash"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"activate draft unapplied payment",execute:async(e,t)=>QV(e.client,t.resourceId,t.hash)},{name:"apply_unapplied_payment",description:"Apply unapplied cash: attributions create a payment on each document; paymentResourceId instead groups an existing payment under it. Using up the balance converts it to a batch payment, one-way.",params:{resourceId:SO,hash:DO,attributions:{type:"array",description:"1-500",items:{type:"object",properties:{businessTransactionResourceId:{type:"string",description:"Invoice, bill or credit note"},businessTransactionType:fSr,amount:{type:"number"},transactionAmount:{type:"number",description:"In document currency, if different"},transactionFee:rlt,transactionFeeCollected:rlt},required:["businessTransactionResourceId","businessTransactionType","amount"]}},paymentResourceId:{type:"string",description:"Existing payment to attach"}},required:["resourceId","hash"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"allocate attach unapplied payment to invoice bill",execute:async(e,t)=>{let r=t.resourceId,n=t.hash,i=t.attributions,o=t.paymentResourceId;if(!!i?.length==!!o)throw ut(new ct("Send exactly one of attributions (create payments on documents) or paymentResourceId (attach an existing payment). Nothing was applied."));return o?MV(e.client,r,n,o):PV(e.client,r,n,i)}},{name:"remove_unapplied_payment_attribution",description:"Remove one child; its cash returns to the balance. childOrigin ATTRIBUTED deletes that payment, ATTACHED keeps it standalone.",params:{resourceId:SO,hash:DO,childResourceId:{type:"string",description:"From children"}},required:["resourceId","hash","childResourceId"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"unapply detach payment",execute:async(e,t)=>UV(e.client,t.resourceId,t.childResourceId,t.hash)},{name:"delete_unapplied_payment",description:"Delete an unapplied payment. payments DELETE deletes its payments too (documents unpaid again) and releases any bank match: if bankStatementEntryResourceId is set, warn the user and confirm first. RELEASE (unbatch) keeps them standalone and is refused while reconciled.",params:{resourceId:SO,hash:DO,payments:{type:"string",enum:["DELETE","RELEASE"],description:"Fate of its payments"}},required:["resourceId","hash","payments"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"unbatch release payments",execute:async(e,t)=>{let r=t.resourceId,n=t.hash;if(t.payments==="RELEASE")return qV(e.client,r,n);if(t.payments==="DELETE")return $V(e.client,r,n);throw ut(new ct("payments must be DELETE or RELEASE. Nothing was deleted."))}},{name:"reconcile_unapplied_payment",description:"Record an unapplied payment for a bank record and match both. Direction, account, currency, date and amount come from the record; amount, if sent, must EQUAL it.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID"},unappliedPaymentDetails:{type:"object",description:"The payment",properties:{paymentMethod:lp,contactResourceId:{type:"string"},reference:{type:"string"},amount:{type:"number"},rateToFunctional:{type:"number",description:"Foreign-currency account only"}},required:["paymentMethod"]}},required:["bankStatementEntryResourceId","unappliedPaymentDetails"],group:"reconciliations",readOnly:!1,isDestructive:!0,searchHint:"bank unallocated receipt",execute:async(e,t)=>jV(e.client,t)}],hSr=["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"],XAe={type:"string",description:"Document family",enum:hSr},nlt={type:"string",description:"Version id from get_document_version_history"},mSr=[{name:"get_document_version_history",description:"The stored versions of a document, OLDEST first (last entry = current). Not paginated. Use before restoring to pick a version id.",params:{entity:XAe,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"versions",readOnly:!0,searchHint:"list document version history revisions audit trail",isConcurrencySafe:!0,execute:async(e,t)=>Zat(e.client,t.entity,t.resourceId)},{name:"get_document_version",description:"Read one stored version of a document. An unknown resourceId/version pair returns 422.",params:{entity:XAe,resourceId:{type:"string",description:"Document resourceId"},version:nlt},required:["entity","resourceId","version"],group:"versions",readOnly:!0,searchHint:"get read one document version snapshot",isConcurrencySafe:!0,execute:async(e,t)=>ect(e.client,t.entity,t.resourceId,t.version)},{name:"rollback_document_version",description:"Restore a document to a stored version. REPLACES current state; read it first with get_document_version. `CREATED` is refused: it would delete the document (the API also 422s it).",params:{entity:XAe,resourceId:{type:"string",description:"Document resourceId"},version:nlt},required:["entity","resourceId","version"],group:"versions",readOnly:!1,searchHint:"restore rollback document to previous version undo changes",isDestructive:!0,execute:async(e,t)=>tct(e.client,t.entity,t.resourceId,t.version)},{name:"get_currency_effective_rate",description:"The organization effective rate for a currency on a date: its own custom rate when set, else the platform daily rate. Defaults to today.",params:{currencyCode:{type:"string",description:"ISO 4217 code, e.g. USD (not a resourceId)"},date:{type:"string",description:"YYYY-MM-DD (optional, defaults to today)"}},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"currency effective exchange rate for a date custom or platform",isConcurrencySafe:!0,execute:async(e,t)=>rct(e.client,t.currencyCode,t.date)}];ASr={type:"object",description:"Needs a condition besides types; LINE_ITEMS ids are line IDs",required:["types"],properties:{types:{type:"array",items:{type:"string",enum:[...Qat]},description:"JOURNAL: manual, cashflow"},resourceIds:{type:"array",items:{type:"string"},description:"Up to 500"},reference:Y4("reference","References, not tags. eq matches only a WHOLE reference; a prefix or partial value needs startWith or contains"),valueDate:Y4("valueDate","YYYY-MM-DD; between [from, to]"),contactResourceId:Y4("contactResourceId"),organizationAccountResourceId:Y4("organizationAccountResourceId","LINE_ITEMS only")}},gSr={...up,description:"Max 50; unlisted stay; a set needs type, printable, a class",items:{...up.items,required:["resourceId"],properties:{...up.items.properties,deleted:{type:"boolean",description:"Remove: {resourceId, deleted: true}"}}}},ySr={type:"object",description:"One change",properties:{contactResourceId:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD, within a year"},capsuleResourceId:{type:"string"},tags:Yo,organizationAccountResourceId:{type:"string",description:"Not bank, cash or control"},classifierConfig:gSr}};ilt=e=>`Nothing was changed. Show the counts, exclusions and blocked fields from the preview, end your turn, and apply only after ${e} confirms in a new message. The preview stays valid for 30 minutes.`;ESr=new Set(["update_invoice","update_bill","update_customer_credit_note","update_supplier_credit_note","update_journal","update_cash_in","update_cash_out"]),bSr=2;CSr=500;vSr=[{name:"preview_ledger_find_fix",description:"Find and fix (recode) records across invoices, bills, credit notes, journals and cash entries: one filter, one change, max 500. Returns previewId (30 min), counts, reasons and before/after rows; a blocked field stays, the rest changes. Show counts, exclusions, blocked fields and sample rows, ask to confirm, end the turn; last line `Preview ID: <id>`. LINE_ITEMS ids are line IDs. One record or other fields: quick fix tools.",params:{level:{type:"string",enum:[...sA],description:_W()},filter:ASr,change:ySr},required:["level","filter","change"],group:"quick_fix",readOnly:!0,isConcurrencySafe:!0,noCache:!0,searchHint:v4.join(", "),maxResultSizeChars:3e4,execute:async(e,t)=>{let r=ISr(e)??e.previousPreviewFilter?.(),n=await vW(e.client,t.level,{filter:t.filter,change:t.change});n.previewId&&e.recordIssuedPreviewId?.(n.previewId,t.filter);let i=[...n.filterNotes??[],wSr(t.filter,r),_Sr(n.counts?.matched??0)].filter(o=>o!==void 0);return i.length>0?{...n,filterNotes:i}:n}},{name:"apply_ledger_find_fix",description:"Apply a find and fix preview once, only after the user confirms it in a later message (enforced on chat, email and Telegram; by email, the inbox owner). Saves previewed values over later edits (tags too); e-invoice filings may re-submit. UNKNOWN: runs up to 4 more minutes; wait before re-previewing, never re-apply.",params:{previewId:{type:"string",description:`${fv} characters, from preview_ledger_find_fix`}},required:["previewId"],group:"quick_fix",readOnly:!1,isDestructive:!0,searchHint:"apply confirmed find fix preview",maxResultSizeChars:2e4,execute:async(e,t)=>{let r=Object.keys(t).filter(o=>o!=="previewId");if(r.length>0)throw ut(new ct(`apply_ledger_find_fix takes only previewId; remove ${r.join(", ")}. To apply a different change, run a new preview.`));let n=t.previewId;if(n.length!==fv){let o=n.length<fv?"looks incomplete":"looks too long";throw ut(new ct(`That preview id ${o}: got ${n.length} character${n.length===1?"":"s"}, and a previewId from preview_ledger_find_fix is always ${fv}. This is different from an expired or already-applied preview; check the full id was copied (e.g. every character of the "Preview ID:" line) and retry with the complete value before assuming a new preview is needed.`))}if(MNe(e.toolCalls,"preview_ledger_find_fix",n))return Dv("Not applied: this preview was created in the same turn, so the user has not seen it.",ilt("the user"));if(UNe(e.toolCalls,"apply_ledger_find_fix",n)||e.appliedPreviewIds?.has(n))return Dv("Not applied: this previewId was already sent to apply earlier.","Nothing was sent. This previewId was already applied once in this conversation, and the outcome of that apply may still be unknown. Do not apply it again. Re-read the affected records (or search for them) to see what actually changed, or run a new preview if more still needs fixing.");if(e.senderIsOwner===!1)return Dv("Not applied: by email, only the inbox owner can confirm a Ledger Find & Fix.",ilt("the inbox owner"));let i=await SW(e.client,n,IW(e,wW));return e.appliedPreviewIds?.record(n),i}}];oge=["invoice","bill","customer_credit_note","supplier_credit_note"],SSr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};DSr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);xO={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},kO={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},z4={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."};V4={invoice:{get:(e,t)=>Eo(e,t),attachType:"invoices",settlementKey:"payments",settlementCountKey:"paymentCount",settlements:Ex},bill:{get:(e,t)=>ho(e,t),attachType:"bills",settlementKey:"payments",settlementCountKey:"paymentCount",settlements:WS},customer_credit_note:{get:(e,t)=>Vs(e,t),attachType:"customer-credit-notes",settlementKey:"refunds",settlementCountKey:"refundCount",settlements:Yx},supplier_credit_note:{get:(e,t)=>Ws(e,t),attachType:"supplier-credit-notes",settlementKey:"refunds",settlementCountKey:"refundCount",settlements:Wx},journal:{get:(e,t)=>vs(e,t),attachType:"journals",settlementKey:"payments",settlementCountKey:"paymentCount",settlements:null}},plt={invoices:"invoice",bills:"bill","customer-credit-notes":"customer_credit_note","supplier-credit-notes":"supplier_credit_note"},xSr=["quantity","unitPrice","discount","taxProfileResourceId","withholdingTax"];NSr={INVOICE:"sales.modal.import-invoices",SALE_QUOTE:"sales-orders.modal.import-sales-orders",SALE_ORDER:"sales-orders.modal.import-sales-orders",PURCHASE_REQUEST:"purchase-orders.modal.import-purchase-orders",PURCHASE_ORDER:"purchase-orders.modal.import-purchase-orders"};hlt=["MAGIC_WORKFLOW","MAGIC_CLAIM","BANK_STATEMENT"];sge={kind:"PSEUDO_SQL_EXPORT",count:()=>1,jobs:(e,t)=>{let r=CU(e);return r?[{kind:"PSEUDO_SQL_EXPORT",id:r,label:FSr(t.query)}]:[]}},LSr=new Set(["TIMED_OUT","PENDING","RUNNING"]),QSr={...sge,admitAfter:!0,jobs:(e,t)=>{let r=e?.data?.status;return typeof r=="string"&&LSr.has(r)?sge.jobs(e,t):[]}};PSr={kind:"MAGIC_WORKFLOW",count:(e,t)=>{let r=sAe(e.collectionId,t.client.scopeKey);return r?pat(r,vlt(e).documentTypes):0},jobs:e=>{let t=e?.files;return Array.isArray(t)?t.flatMap(r=>r.status!=="uploaded"||!r.workflowId?[]:[{kind:r.type==="BANK_STATEMENT"?"BANK_STATEMENT":"MAGIC_WORKFLOW",id:r.workflowId,label:r.file.split("/").pop()||r.file,...r.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},..._U(r.subscriptionFBPath,r.backgroundJobFBPath)}]):[]}};_v={type:"string",enum:[...Wme],description:"Record type: bills, invoices, supplier-credit-notes, customer-credit-notes or bank-records."},wv={type:"string",description:"resourceId of the record."},vv={type:"string",description:"Bank account resourceId. Required when entityType is bank-records."},J4={type:"string",description:"Thread id from list_comment_threads."},glt={type:"string",description:"Comment id from list_comments or list_comment_threads."},rge={type:"number",description:"Zero-indexed page. Default 0."};du=[{name:"get_next_reference",description:"Next document number in the org's own series. Same number the web app prefills. Reading does NOT reserve it; two callers reading at once get the same value. Date embedded is always today. Never invent a reference; use this.",params:{type:{type:"string",description:"Document family whose next number is wanted.",enum:[...LD]}},required:["type"],group:"organization",readOnly:!0,noCache:!0,searchHint:"next reference number document numbering series auto reference",isConcurrencySafe:!0,maxResultSizeChars:5e3,execute:async(e,t)=>QD(e.client,t.type)},{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>ms(e.client)},{name:"get_my_context",description:"Resolve the CALLER's own context: identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side; no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>oNe(e.client)},br("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated; response includes totalElements. Use limit/offset to page.","accounts",(e,t,r)=>LI(e,{limit:r,offset:t}),"list chart of accounts with code type class status"),Nt({name:"search_accounts",description:'Search chart of accounts. For OR (name or code), use filter: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:KT,defaults:XT,fetcher:QI,searchHint:"find accounts chart of accounts CoA by name code type class status OR search"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name; returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:`Exact API string: ${H0r}. COGS = "Direct Costs". Common variants normalized client-side. "interest expense"/"interest income" is NOT auto-classified; ask, do not infer: Finance/Financing, Investing or Operating by main business activity.`},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(e,t)=>{let r=t.name,n=await OM(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=PI(t.accountType);return ZS(e.client,{code:t.code,name:r,accountType:i,currencyCode:t.currencyCode,lockDate:t.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry: rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,isDestructive:!0,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(e,t)=>{let r=t.resourceId,n=(await MP(e.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=t.clearLockDate===!0;if(s&&t.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive; pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),t.name!==void 0&&(o.name=t.name),t.code!==void 0&&(o.code=t.code),!s&&t.lockDate!==void 0&&(o.lockDate=t.lockDate),xNe(e.client,r,o)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount }; no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
673
+ Multiple organizations are accessible: pass org_id (from list_organizations) to target one. Confirm the organization with the user before any create/update/delete.`:""),d={operation:{type:"string",enum:n,description:`The ${t.name} operation to run.`},arguments:{type:"object",description:"Parameters for the chosen operation (see the operation list above). Validated by the Jaz API.",additionalProperties:!0}};return o&&(d[ka]=O4()),c.length&&(d[cp]=F4(c)),e&&(d[jE]=B4()),{name:t.name,description:u,inputSchema:{type:"object",properties:d,required:["operation"],additionalProperties:!1},...c.length?{_meta:{...N4}}:{},annotations:{title:`${t.title??L4(t.name)} \xB7 ${r.length} operation${r.length===1?"":"s"}`,readOnlyHint:i,destructiveHint:!i&&s,idempotentHint:i,openWorldHint:a}}})}function P4(e,t=new Set){return t.has(e)?[]:(t.add(e),Object.hasOwn(jAe,e)?jAe[e].flatMap(r=>P4(r,t)):[e])}function YAe(e){return T0r.has(e)||Object.hasOwn(jAe,e)}function HAe(e,t){let r=P4(e),n=Mi.filter(a=>r.includes(a.name)).flatMap(a=>a.groups);if(n.length===0)return{error:`Unknown namespace: ${e}.`};let i=Object.hasOwn(Sct,e)?Sct[e]:[],o=[...Dct(n),...EO().filter(a=>i.includes(a.name))],s=o.find(a=>a.name===t||a.aliases?.includes(t))??o.find(a=>bd(a.name)===bd(t)||a.aliases?.some(c=>bd(c)===bd(t)));return s?{tool:s}:{error:Rl(t)??`Unknown operation "${t}" for the ${e} tool.`,operations:o.map(a=>a.name)}}var T0r,jAe,Sct,bv=J(()=>{"use strict";Ed();MAe();ou();qE();hg();Q4();T0r=new Set(Mi.map(e=>e.name)),jAe={capsules_and_recipes:["capsules","calculators"],capsules:["transaction_groups"],nano_classifiers:["tracking_categories"]},Sct={organization:["list_organization_report_templates","get_organization_report_template","search_organization_report_templates"],operational_reports:["generate_fixed_assets_summary","generate_fixed_assets_reconciliation_summary"]}});var Rct={};$o(Rct,{loadAgentSuiteContent:()=>F0r});import{readFileSync as x0r}from"node:fs";import{dirname as k0r,join as N0r}from"node:path";import{fileURLToPath as B0r}from"node:url";function F0r(){return zAe||(zAe=JSON.parse(x0r(N0r(O0r,"agent-suite-content.json"),"utf8"))),zAe}var O0r,zAe,Tct=J(()=>{"use strict";O0r=k0r(B0r(import.meta.url)),zAe=null});var xct={};$o(xct,{buildCapabilityMap:()=>Q0r});async function L0r(){try{let{loadAgentSuiteContent:e}=await Promise.resolve().then(()=>(Tct(),Rct)),t=e().counts;return{cli_command_groups:t.commands,api_rules:t.apiRules,skills:t.skills,ifrs_recipes:t.recipes,calculators:t.calculators,job_playbooks:t.jobs}}catch{return}}async function Q0r(e={}){if(e.query&&e.query.trim())return x4(e.query,e.surface);if(e.namespace){let r=P4(e.namespace),n=Mi.filter(s=>r.includes(s.name));if(n.length===0)return{error:`Unknown namespace "${e.namespace}".`,namespaces:Mi.map(s=>s.name),hint:"Call with no arguments for the full map, or pass `query` to rank operations by keyword."};let i=Av(n.flatMap(s=>s.groups)),o=n.length!==1||n[0].name!==e.namespace;return{namespace:e.namespace,...o?{now_called:n.map(s=>s.name)}:{},description:n.map(s=>s.description).join(" "),operations:i.length,operation_list:i.map(Ev),hint:$Ae(e.surface)}}let t=cA(e.surface,e.multiOrg);return{...t,map:e.full?fO().map(r=>({...r,operation_list:Av(Mi.find(n=>n.name===r.namespace).groups).map(Ev)})):t.map,beyond_mcp:await L0r()}}var kct=J(()=>{"use strict";Ed();bv();qE();D4()});import{randomUUID as P0r}from"node:crypto";import{mkdtempSync as M0r,writeFileSync as U0r,rmSync as $0r}from"node:fs";import{join as Nct,extname as q0r,resolve as Bct,sep as j0r}from"node:path";import{tmpdir as Y0r}from"node:os";function q4(e,t,r){let n=Z0r[t],i=r==="byContact";return{name:e,description:i?`${n.label} as at endDate, by ${n.party}: what is outstanding per contact, in aging buckets. For ${n.use}.`:`${n.label} Summary as at endDate: the summary report the dashboard shows under that name. For ${n.use}; for the breakdown per ${n.party}, use generate_aged_${t}.`,params:i?{endDate:nge,view:X0r}:{endDate:nge},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:i?`${n.label.toLowerCase()} by ${n.party} aging report`:`${n.label.toLowerCase()} summary report`,isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(o,s)=>{let{view:a,...c}=s;if(!i)return n.summary(o.client,{endDate:c.endDate});let u=await n.byContact(o.client,c);return a==="aggregate"?Tx(u,t):u}}}function eSr(e){let t=Object.keys(e).filter(i=>!$ct.has(i));if(t.length>0)throw new ct(`generate_general_ledger does not take ${t.join(", ")}. Its parameters: ${[...$ct].filter(i=>i!=="accountResourceId").join(", ")}.`);let r=[...e.accountResourceIds??[]],n=e.accountResourceId;if(n&&!r.includes(n)&&r.push(n),r.length>Hu)throw new ct(`accountResourceIds takes at most ${Hu} accounts per call (got ${r.length}). Split them across calls.`);return xx(e.limit),{startDate:e.startDate,endDate:e.endDate,groupBy:e.groupBy??"ACCOUNT",limit:e.limit??ylt,...e.offset!==void 0?{offset:e.offset}:{},...r.length>0?{accountResourceIds:r}:{}}}function Xct(e,t,r){return{type:"object",description:`The ${e.toLowerCase()} to create. Required.`,properties:{reference:{type:"string",description:`${e} reference`},contactResourceId:{type:"string",description:`${t} UUID`},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:`${e} line items (max 500)`,items:{type:"object",properties:{name:{type:"string",description:"Line description"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:`${r} account UUID`},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}},required:["name"]}},recordedPayment:{type:"object",description:"Optional. The matching payment record, auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:lp,adjustment:Sv}},capsuleResourceId:{type:"string"}},required:["reference","lineItems"]}}function FO(e){let t=e.limit,r=e.offset;return{limit:t,offset:r,sortBy:void 0,sortOrder:void 0}}function br(e,t,r,n,i,o){let s={...OO,...o?.filters};return o?.offsetMode==="row"&&(s.offset=HD),o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:e,description:t,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=FO(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0,p=o?.defaultLimit??(f==="lean"?50:20),h=o?.filters?Object.fromEntries(Object.keys(o.filters).filter(m=>c[m]!=null).map(m=>[m,String(c[m])])):void 0;return lh((m,A)=>n(a.client,m,A,f,h),u,d,p)}}}function ni(e,t,r,n,i,o){return{name:e,description:t,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,a)=>n(s.client,a.resourceId)}}function rl(e){let t="calculate"in uO[e.event];return{name:e.name,description:t?`${e.description} Preview first (preview: true saves nothing), then record. Recording: Admin only.`:`${e.description} ${zi}`,params:{resourceId:{type:"string",description:"Loan resourceId"},...e.params,...t?{preview:aSr}:{}},required:["resourceId",...e.required],group:"loan_events",readOnly:!1,isDestructive:!0,...t?{writesNothingWhen:r=>r.preview===!0}:{},searchHint:e.searchHint,execute:async(r,n)=>{let{resourceId:i,preview:o,...s}=n;return o4(r.client,e.event,i,s,o===!0)}}}function wO(e,t,r,n){return{name:e,description:r,params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD); positions are as at this date"},groupBy:{type:"string",enum:["TYPE","STATUS","ACCOUNT","LENDER"],description:"Grouping; omit for the template's"},filter:{type:"object",description:"Strict keys and operators, others are a 400: loanAccount{resourceId:{in:[]}}, loanBalance{gte,lte}, loanReference{contains}, loanName{contains}, loanType{in:[type names]}, loanStatus{in:[ACTIVE|REPAID|SETTLED|CLOSED_OUT|COMPLETED]}"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:n,isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(i,o)=>Nx(i.client,t,o)}}function Clt(e,t,r,n){return{[t]:!0,...yee(e),[r]:n}}function vO(e){return`Deletes a DRAFT ${e}; VOIDs an active one and KEEPS it. force: true hard-deletes either.`}function Ur(e,t,r,n,i,o){let s=o?.verb??"deleted";return{name:e,description:t,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"},...o?.voidable?uSr:{}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(a,c)=>{let u=c.resourceId;Zi(u,"resourceId",`Nothing was deleted. Source a real resourceId from a search_* or list_* result before calling ${e}.`);let d=c.force,f=await n(a.client,u,{force:d,internalNotes:c.internalNotes});return o?.voidable?xc(f,u,d):Clt(f,s,"resourceId",u)}}}function Y4(e,t){return{type:"object",...t?{description:t}:{},properties:Object.fromEntries(Object.entries(Mat[e]).map(([r,n])=>[r,n==="list"?{type:"array",items:{type:"string"},...r==="in"?{description:"Up to 100"}:{}}:{type:"string"}]))}}function Dv(e,t){return{error:e,_guard:"confirmation_required",message:t}}function ige(e,t){return typeof t=="string"&&e.taskRecordIds?.has(t)===!0}function olt(e,t,r,n,i){let o=dv[i].change.filter(c=>c in n),s=[...gW,...yW].includes(t);if(!e.toolCalls||!Array.isArray(r)||o.length===0||s)return;let a=r.filter(c=>!ige(e,c));if(!(a.length<2))return Dv(`Not changed: ${o.join(", ")} on ${a.length} records needs a preview the user confirms.`,`Nothing was changed. Several records: preview them with preview_ledger_find_fix (level ${i}), show the user, and apply after they confirm. Fields Ledger Find & Fix does not set can still use this tool.`)}function HE(e,t,r){let n=e.toolCalls;if(!n||ige(e,r)||n.some(o=>o.tool_name==="preview_ledger_find_fix"))return;let i=n.filter(o=>ESr.has(o.tool_name)&&!ige(e,o.input?.resourceId)).length;if(!(i<bSr))return Dv(`Not changed: ${i+1} single-record ledger writes in this run with no preview.`,`Nothing was changed by ${t}. Several records are getting the same kind of fix one at a time: stop looping update_* calls and use preview_ledger_find_fix instead (level TRANSACTIONS for contact, date, capsule or tags; LINE_ITEMS for account or classifiers). Show the user the preview and apply only after they confirm.`)}function ISr(e){let t=e.toolCalls;if(t){for(let r=t.length-1;r>=0;r--)if(t[r].tool_name==="preview_ledger_find_fix")return t[r].input?.filter}}function _Sr(e){if(!(e<CSr))return{tool:"preview_ledger_find_fix",reason:`This filter matched ${e} records; a single preview can apply at most 500. A count this large from a conversational request usually means a constraint (a reference, a contact, a date range) is missing rather than genuinely intended. Check the filter before applying, or before telling the user this many records matched; narrow it or split the work into several previews.`}}function wSr(e,t){if(!t||typeof t!="object"||Array.isArray(t)||!e||typeof e!="object"||Array.isArray(e))return;let r=Object.keys(t).filter(n=>!(n in e));if(r.length!==0)return{tool:"preview_ledger_find_fix",reason:`This preview's filter has no ${r.join(", ")}, but the previous preview in this conversation did. If this was meant to narrow further, ${r.length===1?"that constraint":"those constraints"} may have been dropped by mistake rather than intentionally removed; check before treating this as the right set of records.`}}function RO(e,t,r,n){return{name:e,description:`Download ${/^[aeiou]/i.test(t)?"an":"a"} ${t} as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).`,params:{resourceId:{type:"string",description:`${t[0].toUpperCase()}${t.slice(1)} resourceId`}},required:["resourceId"],group:r,readOnly:!0,searchHint:`download ${t} as PDF document file`,isConcurrencySafe:!0,execute:async(i,o)=>n(i.client,o.resourceId)}}function ZAe(e,t,r,n,i){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function slt(e){if(typeof e!="string"||/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=/^(\d{4}-\d{2}-\d{2})T/.exec(e);return t?t[1]:e}function RSr(e){return Array.isArray(e)?e.map(t=>{let r={};for(let[n,i]of Object.entries(t)){if(i==null)continue;let o=dee.get(n);if(o)r[o]=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else if(n==="withholdingTax"){let s=NI(i);s&&(r.withholdingTax=s)}else DSr.has(n)&&(r[n]=i)}return r}):e}async function _lt(e,t,r){let n=t==="invoice"?Eo:t==="bill"?ho:t==="customer_credit_note"?Vs:t==="supplier_credit_note"?Ws:void 0;if(!n)throw new ct(`Unknown transaction type "${String(t)}". Use one of: ${oge.join(", ")}.`);let o=(await n(e,r)).data,s=SSr[t],a={};for(let[c,u]of Object.entries(o))s.has(c)&&u!==null&&u!==void 0&&(a[c]=u);return a.valueDate&&(a.valueDate=slt(a.valueDate)),a.dueDate&&(a.dueDate=slt(a.dueDate)),a.lineItems&&(a.lineItems=RSr(a.lineItems)),a}function wlt(e,t){for(let[r,n]of Object.entries(t))n!==void 0&&(e[r]=n);return e}async function H4(e,t,r,n,i){let o=await _lt(e,t,r);delete o.lineItems;let s=o.tags,a=wlt(o,n);return i&&(a.tags=ui(s,i)),a}function alt(e){return e===void 0?void 0:Xn({add:[e]},"tag")}async function TO(e,t,r,n){let i=wlt(await _lt(e,t,r),n),o=t==="invoice"?tl:t==="bill"?xa:vo,{missingFields:s,ready:a}=ia(i,o);if(!a)throw new Error(`Cannot finalize: missing ${s.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return i}async function clt(e,t,r,n){if((await e(t,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function zE(e,t,r){if(!(typeof e=="string"&&t.includes(e)))return{error:`Unknown documentType ${JSON.stringify(e)}.`,status:422,hint:`Use one of: ${t.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}async function llt(e,t,r,n,i,o,s,a){let c;try{c=(await t(e,r)).data?.status}catch{return}if(c==="DRAFT"){let u=vf[i],d=`A DRAFT ${n} can't be linked or accepted. Issue this one in place with ${s} ${u}:true plus every stored line with its resourceId (status ${a}; without lineItems the update is refused), then link the order to it. Do not create a second ${n}.`;return{error:`Cannot create an order linked to a DRAFT ${n} (${r}).`,status:422,hint:`Pre-flight guard, request never hit the API. ${d}`,repair:{tool:s,arguments:{documentType:i,resourceId:r,[u]:!0},reason:d}}}if(c==="VOID"){let u=`A VOID ${n} can't be used. Create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a VOID ${n} (${r}).`,status:422,hint:`Pre-flight guard, request never hit the API. ${u}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:u}}}}async function ult(e,t,r,n,i,o,s){let a=Ore(e,r);if(a.length>0){let u=vf[e],d=`${a.join(", ")} does not apply to ${e}; its flag is ${u}.`;return{error:d,status:422,hint:"Pre-flight guard, request never hit the API.",repair:{tool:s,arguments:{documentType:e,resourceId:t,[u]:!0},reason:d}}}let c=await Fre(e,r.lineItems,i,{appendLines:n===!0,appendOptIn:"appendLines: true"});if(c)return{error:c.message,status:422,code:c.code,hint:`Pre-flight guard, request never hit the API. Call ${o} for the stored lines, then resend every one with its resourceId.`,repair:{tool:o,arguments:{documentType:e,resourceId:t},reason:"Read the resourceId of every stored line before editing lines."}}}async function dlt(e,t,r,n,i,o){let s;try{s=(await t(e,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard: request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function TSr(e,t,r,n,i){let o;try{o=(await t(e,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r}; delete is only allowed on DRAFT records.`,status:422,hint:`Use ${i} to cancel a non-draft quote/request/order.`,repair:{tool:i,arguments:{documentType:r,resourceId:n},reason:`${r} is ${o}; void it instead of deleting.`}}}function flt(e){let t=`${e.quote} or ${e.order}`,r=i=>({type:"string",description:`${i} resourceId`}),n=(i,o)=>zE(o.documentType,e.docTypes,i);return[{name:e.names.accept,description:`Accept an issued ${e.quote} (${e.issued} \u2192 ACCEPTED). A DRAFT can't be accepted: issue it first with ${e.issueVia}. An issued ${e.quote} can already be linked, so accepting is optional.`,params:{resourceId:r(e.quote)},required:["resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`accept ${e.quote.toLowerCase()} approve`,execute:async(i,o)=>e.accept(i.client,o.resourceId)},{name:e.names.confirm,description:`Confirm a ${e.order} (\u2192 CONFIRMED).`,params:{resourceId:r(e.order)},required:["resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`confirm ${e.order.toLowerCase()}`,execute:async(i,o)=>e.confirm(i.client,o.resourceId)},{name:e.names.void,description:`Void (cancel) a ${t} that is not a draft. For a draft use ${e.names.delete}.`,params:{documentType:e.docTypeParam,resourceId:sc,internalNotes:{type:"string",description:"Optional reason recorded on the document."}},required:["documentType","resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`void cancel ${e.quote.toLowerCase()} ${e.order.toLowerCase()}`,execute:async(i,o)=>{let s=n(e.names.void,o);return s||e.voidDoc(i.client,o.documentType,o.resourceId,o.internalNotes)}},{name:e.names.delete,description:`Delete a DRAFT ${t}. Anything issued: ${e.names.void}.`,params:{documentType:e.docTypeParam,resourceId:sc},required:["documentType","resourceId"],group:e.group,readOnly:!1,isDestructive:!0,searchHint:`delete draft ${e.quote.toLowerCase()} ${e.order.toLowerCase()}`,execute:async(i,o)=>{let s=n(e.names.delete,o);if(s)return s;let a=o.documentType,c=o.resourceId,u=await TSr(i.client,e.getDoc,a,c,e.names.void);return u||(await e.deleteDoc(i.client,a,c),{deleted:!0,resourceId:c})}}]}async function cge(e,t,r){return Promise.all(r.map(async n=>(await V4[t].get(e.client,n)).data))}function lge(e,t){let r=t.filter(i=>SZ(i).length>0);if(r.length===0)return;let n=V4[e].settlementKey==="refunds";return Dv(`Not changed: this would delete the recorded ${n?"refunds":"payments"} on ${r.length} document${r.length>1?"s":""}.`,YNe(r,n))}async function hA(e,t,r,n,i){let{lineItems:o,taxInclusion:s}=n;if(i===!0||o===void 0&&s===void 0)return;let[a]=await cge(e,t,[r]),c=s!==void 0&&s!==a.taxInclusion,u=o!==void 0&&jNe(a.lineItems,o);return c||u?lge(t,[a]):void 0}async function kSr(e,t,r,n,i,o){if(!Array.isArray(i)||i.length===0)throw ut(new ct(`Changing ${o.join(", ")} on lines can delete their documents' payments: also send resourceIds, the ${r} these lines are on. Nothing was changed.`));let s=new Set(Array.isArray(n)?n:[]),a=f=>(Array.isArray(f.lineItems)?f.lineItems:[]).map(p=>p.resourceId),c=(await cge(e,t,i)).filter(f=>a(f).some(p=>p!==void 0&&s.has(p))),u=new Set(c.flatMap(a)),d=[...s].filter(f=>!u.has(f));if(d.length)throw ut(new ct(`Line ${d.join(", ")} is not on the ${r} in resourceIds: send the documents these lines are on. Nothing was changed.`));return lge(t,c)}function ege(e,t){return(t.data?.validFiles?.length??0)>0&&SD(e)?{...t,next:eh[e]}:t}function LO(e,t,r){return`${e} ${e===1?t:r}`}function QO(e,...t){return t.reduce((r,n)=>r+(Array.isArray(e[n])?e[n].length:0),0)}function BSr(e){if(typeof e=="string")try{let t=new URL(e).pathname.split("/").filter(Boolean).pop();return t?decodeURIComponent(t):void 0}catch{return}}function OSr(e,t,r){let n=t?.data;if(!n||!Array.isArray(n.validFiles))return[];let i=typeof n.filename=="string"&&n.filename!==""?n.filename:void 0;return n.validFiles.flatMap(o=>{if(typeof o?.workflowResourceId!="string"||o.workflowResourceId==="")return[];let s=o.fileDetails?.fileName||i||r,a=e!=="MAGIC_CLAIM"&&typeof o.backgroundJobId=="string"&&o.backgroundJobId!=="";return[{kind:e,id:o.workflowResourceId,label:s,...a?{backgroundJobId:o.backgroundJobId}:{},..._U(o.subscriptionFBPath,o.backgroundJobFBPath)}]})}function tge(e,t,r){return{kind:e,count:()=>1,jobs:(n,i)=>OSr(e,n,BSr(i[t])??r)}}function PO(e,t){return{kind:"BACKGROUND_JOB",...t?{finishedNote:t}:{},count:()=>1,jobs:(r,n)=>{let i=CU(r);return i?[{kind:"BACKGROUND_JOB",id:i,label:e(n),..._U(qFe(r))}]:[]}}}function Pn(e,t,r,...n){return PO(i=>`${e} ${LO(QO(i,...n),t,r)}`)}function FSr(e){let t=typeof e=="string"?/\bfrom\s+([a-z_][\w.]*)/i.exec(e)?.[1]:void 0;return t?`${t} export`:"Query export"}function mlt(e,t){return e.data?.status!=="COMPLETED"||!e.data.downloadUrl?e:{...e,data:{...e.data,fileName:jst(t),fileUrl:e.data.downloadUrl}}}function vlt(e){let t=Array.isArray(e.documentTypes)?e.documentTypes:[],r=t.map(i=>({raw:i,doc:th(i)})),n=r.filter(i=>i.doc===null).map(i=>i.raw);return{documentTypes:t.length>0?r.map(i=>i.doc):void 0,unresolved:n}}async function Alt(e,t,r){let n=MD(e,hlt,t);if(n)return n;let i=t.filter(s=>!MD(e,hlt,[s]));if(i.length===t.length)return r(t);let o=await r(i);return{note:e.loopTurn?.backgroundNote,collectedWorkflowIds:t.filter(s=>!i.includes(s)),...o}}function MSr(e){let t=e.execute;return{...e,execute:async(r,n,i)=>{let o=n.id??n.filter?.resourceId?.eq;return(typeof o=="string"?MD(r,"BACKGROUND_JOB",[o]):null)??t(r,n,i)}}}function mA(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==null&&t!==""))}var H0r,sc,Oct,Fct,So,au,zi,M4,Iv,JAe,Mo,cu,bi,U4,dA,NO,BO,YE,z0r,lu,J0r,Lct,G0r,$4,V0r,Id,Qct,Pct,Mct,GAe,VAe,JE,bO,W0r,K0r,nge,X0r,Z0r,Uct,WAe,OO,fA,pA,ylt,$ct,oa,KAe,qct,jct,Yct,Hct,IO,Tn,Elt,blt,zct,Jct,CO,up,tSr,rSr,Ilt,nSr,sa,uu,iSr,oSr,sSr,Cv,aSr,G4,cSr,Gct,j4,Cd,age,_O,Vct,Wct,Kct,lp,Sv,lSr,uSr,Zct,elt,tlt,dSr,SO,DO,fSr,rlt,pSr,hSr,XAe,nlt,mSr,ASr,gSr,ySr,ilt,ESr,bSr,CSr,vSr,oge,SSr,DSr,xO,kO,z4,V4,plt,xSr,NSr,hlt,sge,LSr,QSr,PSr,_v,wv,vv,J4,glt,rge,du,W4=J(()=>{"use strict";FFe();bU();zFe();cee();aC();NU();pee();Aee();kg();qD();Ki();zt();ot();nf();Fl();eD();xre();kre();yg();zg();af();Nre();Bre();Lre();Jg();Qre();Rg();PP();xl();JP();Pre();S$e();Yu();Hx();Kx();gj();nst();oD();aM();uD();AD();pD();A2();ZG();Sme();dV();JM();Fme();Rg();JB();Lme();Qme();CV();Qst();qme();jme();Yme();zme();Gme();nA();tat();iv();Af();Kme();Xme();Zme();gD();eee();iat();Mu();sat();uat();hat();Cee();Aat();cAe();T8();lAe();K8();uAe();dAe();fAe();EW();IAe();vAe();fo();CAe();SAe();DAe();IU();yg();YS();zg();RAe();Jg();nct();af();Hx();Kx();Jg();T8();hv();hq();kAe();an();NAe();_4();zt();LAe();QAe();TE();hf();Lu();H0r=PU.join(" | "),sc={type:"string",description:"Resource ID of the record"},Oct={type:"string",description:"Optional: the suggestion's recommendationId (UUID) from view_auto_reconciliation, so the accept is credited to it"},Fct={learnedPredictionResourceId:{type:"string",description:"Learned-prediction id from the suggestion (required to accept one)"},predictedPayload:{type:"string",description:"Opaque JSON string from the suggestion, passed verbatim (required to accept one)"},predictedPayloadSchemaVersion:{type:"string",description:"Schema version from the suggestion (required to accept one)"},retryToken:{type:"string",description:"Optional idempotency retry token: a fresh one forces a new journal on an edit-then-retry; omit it to replay"}},So={type:"string",description:"Transaction date (YYYY-MM-DD)"},au={type:"string",description:"Due date (YYYY-MM-DD)"},zi="Admin only.",M4="Confirm first: say what it changes and wait for a yes.",Iv="Term loans, not CUSTOM-schedule.",JAe={type:"string",description:"Ignored in a preview. Needed unless the loan already has one, when a gain or loss posts (LOAN_GAIN_LOSS_ACCOUNT_REQUIRED)."},Mo={type:"string",description:"Reference number"},cu={type:"boolean",description:"Use the org's own next number instead of `reference`."},bi={type:"string",description:"Notes or memo text"},U4={type:"boolean",description:"Line amounts include tax"},dA={type:"string",description:"Tag name for categorization"},NO={type:"array",items:{type:"string"},description:"Tags (string array)"},BO={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},YE={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},z0r={type:{type:"string",enum:[...VI],description:"Calculator to run"},amount:{type:"number",description:"Amount (for prepaid-expense, deferred-revenue, accrued-expense, dividend, provision, fx-reval)"},principal:{type:"number",description:"Principal (for loan, fixed-deposit)"},startDate:{type:"string",description:"Start date YYYY-MM-DD. Needed for dated steps; without it most calculators return the schedule only."},currency:{type:"string",description:"Currency code (e.g. SGD, USD)"},periods:{type:"number",description:"Number of periods (for prepaid-expense, deferred-revenue, accrued-expense; leave-accrual months, default 12)"},frequency:{type:"string",enum:["monthly","quarterly","annual"],description:"depreciation: annual (default) or monthly. prepaid-expense, deferred-revenue, accrued-expense: monthly (default) or quarterly"},annualRate:{type:"number",description:"Annual interest/discount rate %"},termMonths:{type:"number"},monthlyPayment:{type:"number",description:"Monthly lease payment (for lease)"},usefulLifeMonths:{type:"number",description:"Asset useful life in months (hire purchase)"},cost:{type:"number",description:"Asset cost"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"],description:"Depreciation method"},acquisitionDate:{type:"string",description:"Acquisition date YYYY-MM-DD"},disposalDate:{type:"string",description:"Disposal date YYYY-MM-DD"},proceeds:{type:"number",description:"Disposal proceeds"},bookRate:{type:"number",description:"Original booking rate. Declare which way it reads via rateDirection (REQUIRED for fx-reval)."},closingRate:{type:"number",description:"Period-end closing rate. Same direction as bookRate."},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"REQUIRED for fx-reval. FUNCTIONAL_TO_SOURCE = 1 base unit = N foreign, what list_currency_rates returns. SOURCE_TO_FUNCTIONAL = 1 foreign unit = N base, the everyday quote."},position:{type:"string",enum:["ASSET","LIABILITY"],description:"Balance-sheet side: ASSET (receivable/deposit, default) or LIABILITY (payable/provision). A rising base value is a gain on an asset and a loss on a liability."},baseCurrency:{type:"string",description:"Base (functional) currency"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string",description:'Bucket label, e.g. "1-30 days"'},balance:{type:"number",description:"Receivables balance in this bucket"},rate:{type:"number",description:"Expected loss rate %"}},required:["name","balance","rate"]},description:"ECL aging buckets"},existingProvision:{type:"number",description:"Existing ECL provision balance"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number",description:"Leave days per employee per year"},dailyRate:{type:"number",description:"Average daily rate"},declarationDate:{type:"string",description:"Board resolution date YYYY-MM-DD"},paymentDate:{type:"string",description:"Settlement date YYYY-MM-DD"},withholdingRate:{type:"number",description:"Withholding tax rate %"}},lu={type:"string",description:"Capsule to file this under (from create_capsule)"},J0r={in:"{in: [names]}",gte:"{gte, lte: number}",lte:"{gte, lte: number}",contains:"{contains: text}"},Lct=e=>({type:"object",description:[...new Set(e.map(t=>J0r[t]))].join(" ")}),G0r={type:"object",description:"deferralCategory: PREPAID_EXPENSE, DEFERRED_REVENUE. deferralStatus: ACTIVE, FULLY_AMORTIZED, CLOSED_OUT, COMPLETED. deferralType: type name",properties:Object.fromEntries(Object.entries(pq).map(([e,t])=>[e,Array.isArray(t)?Lct(t):{type:"object",properties:{resourceId:Lct(t.resourceId)}}]))},$4={type:"array",items:{type:"object",properties:{fromPeriod:{type:"number",description:"First period, 1-based"},toPeriod:{type:"number",description:"Last period, inclusive"},amount:{type:"number",description:"Released in EACH period of the range"}},required:["fromPeriod","toPeriod","amount"]}},V0r={type:"boolean",description:"Retry-only: set true after the duplicate guard surfaced a candidate and the user confirmed this is a separate document. Never on a first attempt."},Id={type:"boolean",description:"Only after the user confirmed the payment deletion this tool reported."},Qct={type:"string",enum:[...bee],description:"CUSTOM (default) = free text; ALL_* = a picklist of that population. Datatype is derived, not chosen."},Pct={type:"object",properties:{address:{type:"string",description:"Street address, sent as addressLine1"},city:{type:"string"},state:{type:"string"},postalCode:{type:"string"},country:{type:"string"}},required:["address","country"]},Mct={type:"object",properties:{name:{type:"string",enum:[...fZ]},value:{type:"string",description:'Days, e.g. "21". CUSTOM only; dropped otherwise.'}}},GAe={type:"string",description:"Contact resourceId (customer or supplier)"},VAe={type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID)"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Draft entity type"}},required:["btResourceId","btType"]}},JE={type:"string",description:"Chart-of-accounts account the line posts to (revenue on a sale, expense on a purchase)"},bO={type:"string",description:"Account the payment posts to. For paymentMethod BANK_TRANSFER/CASH/CHEQUE this MUST be a bank or cash account. Any other method accepts any org account; that is how a deposit drawdown works (paymentMethod OTHER + the deposit account)."},W0r={type:"number",description:"Payment amount (in bank currency)"},K0r={type:"string",description:"Period start date (YYYY-MM-DD)"},nge={type:"string",description:"Period end date (YYYY-MM-DD)"},X0r={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report"); it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},Z0r={receivables:{label:"Aged Receivables",party:"customer",use:"credit control, collections and customer payment follow-up",byContact:(e,t)=>bq(e,t),summary:(e,t)=>Nq(e,t)},payables:{label:"Aged Payables",party:"supplier",use:"payment runs and supplier follow-up",byContact:(e,t)=>Iq(e,t),summary:(e,t)=>Bq(e,t)}};Uct={type:"string",description:"Currency code (e.g. SGD, USD)"},WAe={type:"string",description:"Display name"},OO={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},fA={fromPeriod:{type:"number",description:"First period, from 1."},toPeriod:{type:"number",description:"Last period, inclusive."}},pA=e=>({fromPeriod:e.fromPeriod,toPeriod:e.toPeriod}),ylt=50,$ct=new Set(["startDate","endDate","groupBy","limit","offset","accountResourceIds","accountResourceId"]);oa={type:"object",required:["sourceCurrency"],properties:{sourceCurrency:{type:"string",description:"Foreign currency code (ISO 4217)."},exchangeRate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N sourceCurrency. Invert ONLY if your quote reads "1 source = X base" (send 1/X), or declare rateDirection and skip the arithmetic. Omit for the org/platform rate.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"How exchangeRate reads. SOURCE_TO_FUNCTIONAL accepts a bank quote verbatim. Default FUNCTIONAL_TO_SOURCE."}}},KAe={type:"string",enum:[...yf],description:"Entity type to export"},qct={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter; pass one or the other, never both.'},jct={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query; pass one or the other, never both.'},Yct={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},Hct={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},IO={type:"array",description:"CUSTOM_SCHEDULE only: month ranges (1-based, amount per month) covering 1..effectiveLife, no gap or overlap, summing to the depreciable value (book value for a transfer). Update: omit to keep.",items:{type:"object",properties:{fromPeriod:{type:"number",description:"First month"},toPeriod:{type:"number",description:"Last month"},amount:{type:"number",description:"Per month"}},required:["fromPeriod","toPeriod","amount"]}},Tn={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Elt={type:"array",description:"The rent: amount is the rent of EACH month in the range. Ranges cover months 1 to leaseTerm, no gap or overlap. Quarterly or yearly rent goes month by month, 0 in the other months.",items:{type:"object",properties:{fromPeriod:{type:"number",description:"First month, 1-based"},toPeriod:{type:"number",description:"Last month, inclusive"},amount:{type:"number",description:"Rent per month"}},required:["fromPeriod","toPeriod","amount"]}},blt=["RIGHT_OF_USE_ASSET","EXEMPT"],zct={name:{type:"string",description:"Lease name"},typeCode:{type:"string",description:"From search_lease_types; HIRE_PURCHASE for hire purchase"},exemptionType:{type:"string",enum:[...blt],description:"EXEMPT = short-term or low-value, posts nothing"},contactResourceId:{type:"string",description:"Lessor contact"},commencementDate:{type:"string",description:"YYYY-MM-DD. Month 1 runs to that month-end, no day pro-rating. A lease from before Jaz: start at go-live with the remaining term and rent; keep it out of opening balances."},leaseTerm:{type:"number",description:"Months, 1-600"},customSchedule:Elt,paymentTiming:{type:"string",enum:[...sh],description:"ADVANCE (start of month) or ARREARS (end)"},discountRate:{type:"number",description:"% per MONTH, up to 4 decimals: 6% a year is 0.5, not 6 and not 0.06. Nominal annual rate / 12."},prepaidLeasePaymentsAmount:{type:"number",description:"Rent paid before the start; with ADVANCE leave month 1 out"},restorationCostAmount:{type:"number",description:"Expected make-good cost at term end, booked day 1 at present value"},ownershipTransfers:{type:"boolean",description:"Ownership passes at the end (hire purchase): depreciates over usefulLife"},usefulLife:{type:"number",description:"Months, 1-1200; needed with ownershipTransfers"},purchaseOptionPrice:{type:"number",description:"Balloon paid at term end, with ownershipTransfers"},rouAssetAccountResourceId:{type:"string",description:"Right-of-Use Asset account (Fixed Asset type)"},accumulatedDepreciationAccountResourceId:{type:"string",description:"Accumulated Depreciation account (Fixed Asset type)"},depreciationExpenseAccountResourceId:{type:"string",description:"Depreciation Expense account"},leaseLiabilityAccountResourceId:{type:"string",description:"Current Lease Liability account: rent is coded here"},leaseLiabilityNonCurrentAccountResourceId:{type:"string",description:"Non-current Lease Liability account, needed when principal falls due after 12 months"},interestExpenseAccountResourceId:{type:"string",description:"Interest Expense account (Finance Cost type)"},restorationProvisionAccountResourceId:{type:"string",description:"Needed when restorationCostAmount > 0"},prepaidLeasePaymentsAccountResourceId:{type:"string",description:"Prepaid Rent account (Current Asset, not a deferral account), needed when prepaid rent > 0"},internalNotes:{type:"string",description:"Internal notes"},customFields:Tn,capsuleResourceId:lu},Jct={type:"array",description:"Full replacement line-item set: non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},CO={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},up={type:"array",items:{type:"object",required:["resourceId","type","selectedClasses","printable"],properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",required:["className"],properties:{className:{type:"string"},resourceId:sc,entityResourceId:{type:"string"}}}},printable:{type:"boolean",description:"Show on printed documents."}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},tSr={type:"object",description:"Defaults for documents generated from the asset: notes, numbering, account, tax, payment, currency. Send only to set or change; omit to keep. get_fixed_asset returns it as opaque text.",properties:{resourceId:{type:"string"},businessTransactionType:{type:"string"},invoiceNotes:{type:"string"},currencySettings:{type:"object",properties:{sourceCurrencyCode:{type:"string"},rateFunctionalToSource:{type:"number"},exchangeToken:{type:"string"}}},taxCurrencySettings:{type:"object",properties:{sourceCurrencyCode:{type:"string"},rateFunctionalToSource:{type:"number"},exchangeToken:{type:"string"}}},detailSettings:{type:"object",properties:{prefix:{type:"string"},separator:{type:"string"},dateInclusion:{type:"string"},seriesStart:{type:"number"}}},itemAccount:{type:"object",properties:{itemLevel:{type:"boolean"},organizationAccountResourceId:{type:"string"}}},itemAttribute:{type:"object",properties:{discount:{type:"boolean"},quantity:{type:"boolean"},unit:{type:"boolean"}}},itemTax:{type:"object",properties:{itemLevel:{type:"boolean"},taxInclusive:{type:"boolean"},taxProfileResourceId:{type:"string"}}},paymentSettings:{type:"object",properties:{organizationAccountResourceId:{type:"string"},paymentMethod:{type:"string"}}}}},rSr={...up,items:{...up.items,properties:{...up.items.properties,selectedClasses:{...up.items.properties.selectedClasses,description:"Classes picked within the classifier"}}}},Ilt={type:"array",description:"Max 50. On update the list REPLACES all fees: send every one to keep.",items:{type:"object",required:["feeType","amount","treatment","paidFrom"],properties:{resourceId:{type:"string"},feeType:{type:"string",enum:["ARRANGEMENT","LEGAL","STAMP_DUTY","VALUATION","GUARANTEE","OTHER"],description:"Fee kind"},amount:{type:"number"},treatment:{type:"string",enum:["SPREAD","EXPENSE","ON_SETTLEMENT"],description:"SPREAD needs the loan's unamortizedCostsAccountResourceId; EXPENSE needs accountResourceId; ON_SETTLEMENT is only quoted"},paidFrom:{type:"string",enum:["DEDUCTED","SEPARATE"],description:"DEDUCTED = lender took it from the drawdown"},accountResourceId:{type:"string"}}}},nSr={type:"array",description:"CUSTOM only: the lender's rows (max 600). For a lender change send revised rows with update_loan; schedule-rebuilding events are refused.",items:{type:"object",required:["dueDate","principal","interest"],properties:{dueDate:{type:"string",description:"YYYY-MM-DD, after drawdown, ascending"},principal:{type:"number",description:"Principal in this installment"},interest:{type:"number",description:"Interest in this installment"}}}},sa={kind:{type:"string",enum:["TERM","ON_DEMAND"],description:"ON_DEMAND = director, shareholder, related-party or intercompany account: no schedule, no interest posted (the user journals it)"},principalAmount:{type:"number",description:"Above 0, 2 dp"},drawdownDate:{type:"string",description:"YYYY-MM-DD"},trackingStartDate:{type:"string",description:"Existing loan: go-live date; needs openingPrincipalAmount"},openingPrincipalAmount:{type:"number",description:"Principal outstanding on trackingStartDate"},annualInterestRate:{type:"number",description:"Percent per YEAR: 6.5 = 6.5% a year, not 0.065; 0 = interest-free. Required for TERM unless CUSTOM."},dayCount:{type:"string",enum:["ACTUAL_365","ACTUAL_360","THIRTY_E_360","MONTHLY"],description:"MONTHLY = rate / 12; most banks ACTUAL_365. Required for TERM unless CUSTOM."},repaymentShape:{type:"string",enum:["ANNUITY","EQUAL_PRINCIPAL","INTEREST_ONLY_THEN_ANNUITY","BULLET","BALLOON","CUSTOM"],description:"ANNUITY = level installment. Required for TERM."},customSchedule:nSr,loanTerm:{type:"number",description:"Months, 1-600. Required for TERM unless CUSTOM."},firstRepaymentDate:{type:"string",description:"YYYY-MM-DD; default one month after drawdown"},interestOnlyMonths:{type:"number",description:"INTEREST_ONLY_THEN_ANNUITY: 1 to term-1"},balloonAmount:{type:"number",description:"BALLOON: principal left for the last installment"},installmentOverride:{type:"number",description:"The lender's installment when it differs by rounding; not on EQUAL_PRINCIPAL or BULLET"},fees:Ilt},uu={reference:{type:"string",description:"Unique; get_next_reference (LOAN)"},name:{type:"string",description:"Required to activate"},typeCode:{type:"string",description:"From search_loan_types. Required to activate."},contactResourceId:{type:"string",description:"Lender contact"},...sa,capitalizationStartDate:{type:"string",description:"IAS 23: interest from here to capitalizationEndDate goes to capitalizationAccountResourceId, not expense"},capitalizationEndDate:{type:"string",description:"YYYY-MM-DD"},currentLiabilityAccountResourceId:{type:"string",description:"Current Liability account; each installment is recorded IN FULL here"},nonCurrentLiabilityAccountResourceId:{type:"string",description:"Non-current Liability account; drawdown cash is recorded here. Needed when principal falls due after 12 months"},interestExpenseAccountResourceId:{type:"string",description:"Finance Cost account, for a rate above 0"},unamortizedCostsAccountResourceId:{type:"string",description:"For SPREAD fees and restructures under 10%"},gainLossAccountResourceId:{type:"string",description:"For forgiveness, conversion, restructure"},capitalizationAccountResourceId:{type:"string",description:"Fixed Asset account"},internalNotes:{type:"string"},tags:NO},iSr=["reference","name","typeCode","contactResourceId","kind","principalAmount","drawdownDate","annualInterestRate","dayCount","repaymentShape","loanTerm","interestOnlyMonths","balloonAmount","currentLiabilityAccountResourceId","nonCurrentLiabilityAccountResourceId","interestExpenseAccountResourceId","fees","unamortizedCostsAccountResourceId"],oSr=Object.fromEntries(iSr.map(e=>[e,uu[e]])),sSr=Object.fromEntries(Object.entries(uu).filter(([e])=>e!=="tags")),Cv={type:"number",description:"Principal confirmed on the date after a missed, late or partial payment; rebases the schedule. See calculate_loan_opening_balance."},aSr={type:"boolean",description:"true = figures only, nothing saved. Default false records the event."},G4={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},cSr={type:"number",description:"Line rate, account currency to base (opposite of currency.exchangeRate). Foreign-account lines only; 0, or non-1 on a base-currency line, is 422."},Gct={...G4,items:{...G4.items,properties:{...G4.items.properties,exchangeRate:cSr}}},j4={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Offset account resourceId"},amount:{type:"number",description:"Amount (positive; direction comes from the endpoint)"},description:{type:"string",description:"Line description"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId"}},required:["accountResourceId","amount"]},description:"Offset lines. No `type`; cash-in credits these and cash-out debits them, decided by the endpoint."},Cd={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:JE,taxProfileResourceId:{type:"string"},classifierConfig:up},required:["name","quantity","unitPrice"]},description:"Line items: include accountResourceId on each line when finalizing (saveAsDraft: false)"},age={type:"object",required:["code","rate"],properties:{code:{type:"string",description:'e.g. "WC 158"'},rate:{type:"number",description:"Rate %"},type:{type:"string"},description:{type:"string"}},description:"EWT (PH): copy all four from a list_withholding_codes row; omitted ones are not stored."},_O={...Cd,items:{...Cd.items,properties:{...Cd.items.properties,withholdingTax:age}}},Vct={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Stored line id (from get). Omit only for a new line."},deleted:{type:"boolean",description:"With resourceId: remove the line."},name:{type:"string",description:"Line name (every line, deleted too)."},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:JE,taxProfileResourceId:{type:"string"},discount:{type:"number"},unit:{type:"string"},itemResourceId:{type:"string"},taxVatAdjustment:{type:"object",properties:{adjustmentAmount:{type:"number"},notes:{type:"string"}}},withholdingTax:age,classifierConfig:up}},description:"Edits, not a replacement: send EVERY stored line with its resourceId, in order (deleted:true removes; a line without resourceId is ADDED). An edited line keeps only what is sent: resend every stored field you want kept (tax profile, taxVatAdjustment, withholdingTax, discount, unit, itemResourceId). A partial id set is refused; id-less lines on a document with lines are refused unless appendLines."},Wct={type:"boolean",description:"true: add id-less lineItems beside the stored lines on purpose."},Kct={type:"array",items:{type:"object",properties:{itemName:{type:"string",description:"Display name of the catalog item"},itemResourceId:{type:"string",description:"Underlying item resourceId (from search_items)"},price:{type:"number",description:"Default unit price (0-1e9)"},unit:{type:"string",description:"Unit of measure"},quantityDefault:{type:"number",description:"Default quantity when added to a document (0-100)"},discountDefault:{type:"number",description:"Default discount % when added to a document (0-100)"},uiIndex:{type:"number",description:"Display position in the catalog (integer, min 0)"},classifiers:{type:"array",items:{type:"object"},description:"Classifier assignments. Same shape as classifierConfig on invoice/bill line items."}},required:["itemName","itemResourceId","price"]},description:"Catalog item rows. itemName, itemResourceId and price are required on every row."},lp={type:"string",enum:[...MU],description:"Payment method (default BANK_TRANSFER)"},Sv={type:"object",description:"Cash-leg adjustment (overpayment/rounding). Bank leg only, never AR/AP. Not with DEBT_WRITE_OFF/CLEARING_SETTLEMENT/INTER_COMPANY/WITHHOLDING_TAX_CERTIFICATE. See rule 160.",properties:{adjustmentValue:{type:"number",description:"Signed, non-zero, max 2dp"},adjustmentAccountResourceId:{type:"string",description:"Non-controlled account, not bank/cash"},adjustmentDescription:{type:"string",description:"Optional"}},required:["adjustmentValue","adjustmentAccountResourceId"]},lSr={...Sv,description:"Adding or changing an adjustment applies here. REMOVING does not: 0 is rejected and null reads as omitted, so both leave the stored value unchanged. To remove one, delete the payment and record it again. A change is rejected if the payment is reconciled or lock-dated, and amount, account and description are all compared, so resend all three unchanged if you are not editing it. See rule 160."};uSr={force:{type:"boolean",description:gee.force},internalNotes:{type:"string",description:gee.internalNotes}};Zct={type:"string",description:"Document family",enum:[...ap]},elt={type:"string",description:"Document family",enum:[...PE]},tlt={type:"string",description:"Why it is sent back. Opens a thread; the only record of the reason."},dSr=[{name:"approve_documents",description:"Approve one PENDING document (a DRAFT takes finalize_*). Irreversible, posts its ledger: confirm with the user first. Unknown or other-org id: 404. A refusal or an unconfirmed answer returns error. After a timeout or 500, read approvalStatus before retrying.",params:{entity:Zct,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"approve pending invoice bill credit note post ledger",execute:async(e,t)=>{let r=await LW(e.client,t.entity,t.resourceId),n=FW(r?.data?.records);return n.state==="approved"?r:n.state==="refused"?{error:`Not approved: ${n.reason}`,outcome:"REFUSED",...r}:{error:"UNCONFIRMED: the API returned no per-record outcome, so the approval neither succeeded nor failed provably.",outcome:"UNCONFIRMED",hint:"Read the document's approvalStatus before approving again or reporting it approved.",...r}}},{name:"bulk_approve_documents",description:`Approve up to 100 PENDING documents. Irreversible, posts each ledger: confirm first. Async: returns the final job if it finished, else a jobId to poll with search_background_jobs. ${rs} One unknown or other-org id: whole batch 422. Non-pending ones are skipped, listed on the job tasks. After a timeout or 500, read approvalStatus before retrying.`,params:{entity:Zct,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-100)"}},required:["entity","resourceIds"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"bulk approve many pending documents at once",backgroundJob:Pn("Approve","document","documents","resourceIds"),execute:async(e,t)=>QW(e.client,t.entity,t.resourceIds)},{name:"request_document_changes",description:"Send one document back for changes instead of approving it. Also covers orders, quotes, requests and claims.",params:{entity:elt,resourceId:{type:"string",description:"Document resourceId"},message:tlt},required:["entity","resourceId","message"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"request changes reject send back document for revision",execute:async(e,t)=>PW(e.client,t.entity,t.resourceId,t.message)},{name:"bulk_request_document_changes",description:`Send up to 500 documents back for changes with one message. Async: returns the final job if it finished, else a jobId to poll with search_background_jobs. ${rs}`,params:{entity:elt,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-500)"},message:tlt},required:["entity","resourceIds","message"],group:"approvals",readOnly:!1,isDestructive:!0,searchHint:"bulk request changes send back many documents",backgroundJob:PO(e=>`Send ${LO(QO(e,"resourceIds"),"document","documents")} back for changes`),execute:async(e,t)=>MW(e.client,t.entity,t.resourceIds,t.message)}],SO={type:"string",description:"Unapplied payment resourceId"},DO={type:"string",description:"From search_unapplied_payments or the last write"},fSr={type:"string",enum:[...Mst],description:"Document type"},rlt={type:"object",properties:{feeValue:{type:"number",description:"Amount or percent"},feeType:{type:"string",enum:[...Ust],description:"AMOUNT, not FLAT"},feeOrganizationAccountResourceId:{type:"string",description:"Fee account"},taxVatProfileResourceId:{type:"string"},feeTaxVatApplicable:{type:"boolean"}},required:["feeValue","feeType","feeOrganizationAccountResourceId"]},pSr=[Nt({name:"search_unapplied_payments",description:"Unapplied payments (cash not yet applied to documents). The only read path: rows carry hash (every write needs it), unappliedStatus and unappliedBalance. A record whose cash is all applied became a batch payment and no longer appears here.",group:"unapplied_payments",fields:jR,defaults:YR,fetcher:OV,searchHint:"unallocated receipt deposit prepayment on account"}),{name:"record_unapplied_payment",description:"Record cash received (SALE) or paid (PURCHASE) before applying it to documents. Draft by default (posts nothing until finalize_unapplied_payment); saveAsDraft:false posts to the ledger now.",params:{businessTransactionType:{type:"string",enum:[...NV],description:"SALE received, PURCHASE paid"},organizationAccountResourceId:{type:"string",description:"Bank/cash account"},paymentMethod:lp,amount:{type:"number"},valueDate:{type:"string",description:"YYYY-MM-DD"},currencyCode:{type:"string",description:"ISO 4217"},rateToFunctional:{type:"number",description:"Required for a foreign currency"},contactResourceId:{type:"string"},reference:{type:"string"},notes:{type:"string"},saveAsDraft:BO},required:["businessTransactionType","organizationAccountResourceId","paymentMethod","amount","valueDate","currencyCode"],group:"unapplied_payments",readOnly:!1,searchHint:"record unapplied payment advance",execute:async(e,t)=>FV(e.client,{...t,saveAsDraft:t.saveAsDraft??!0})},{name:"update_unapplied_payment",description:"Edit an unapplied payment. New amount, account or date releases its bank match; a move to a foreign-currency account needs amount restated and rateToFunctional. Attribution rows (children): CLI --input.",params:{resourceId:SO,hash:DO,reference:{type:"string"},notes:{type:"string"},paymentMethod:lp,amount:{type:"number"},organizationAccountResourceId:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD"},rateToFunctional:{type:"number"}},required:["resourceId","hash"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"edit unapplied payment",execute:async(e,t)=>{let{resourceId:r,...n}=t;return LV(e.client,r,n)}},{name:"finalize_unapplied_payment",description:"Activate a DRAFT unapplied payment; the ledger posts now.",params:{resourceId:SO,hash:DO},required:["resourceId","hash"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"activate draft unapplied payment",execute:async(e,t)=>QV(e.client,t.resourceId,t.hash)},{name:"apply_unapplied_payment",description:"Apply unapplied cash: attributions create a payment on each document; paymentResourceId instead groups an existing payment under it. Using up the balance converts it to a batch payment, one-way.",params:{resourceId:SO,hash:DO,attributions:{type:"array",description:"1-500",items:{type:"object",properties:{businessTransactionResourceId:{type:"string",description:"Invoice, bill or credit note"},businessTransactionType:fSr,amount:{type:"number"},transactionAmount:{type:"number",description:"In document currency, if different"},transactionFee:rlt,transactionFeeCollected:rlt},required:["businessTransactionResourceId","businessTransactionType","amount"]}},paymentResourceId:{type:"string",description:"Existing payment to attach"}},required:["resourceId","hash"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"allocate attach unapplied payment to invoice bill",execute:async(e,t)=>{let r=t.resourceId,n=t.hash,i=t.attributions,o=t.paymentResourceId;if(!!i?.length==!!o)throw ut(new ct("Send exactly one of attributions (create payments on documents) or paymentResourceId (attach an existing payment). Nothing was applied."));return o?MV(e.client,r,n,o):PV(e.client,r,n,i)}},{name:"remove_unapplied_payment_attribution",description:"Remove one child; its cash returns to the balance. childOrigin ATTRIBUTED deletes that payment, ATTACHED keeps it standalone.",params:{resourceId:SO,hash:DO,childResourceId:{type:"string",description:"From children"}},required:["resourceId","hash","childResourceId"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"unapply detach payment",execute:async(e,t)=>UV(e.client,t.resourceId,t.childResourceId,t.hash)},{name:"delete_unapplied_payment",description:"Delete an unapplied payment. payments DELETE deletes its payments too (documents unpaid again) and releases any bank match: if bankStatementEntryResourceId is set, warn the user and confirm first. RELEASE (unbatch) keeps them standalone and is refused while reconciled.",params:{resourceId:SO,hash:DO,payments:{type:"string",enum:["DELETE","RELEASE"],description:"Fate of its payments"}},required:["resourceId","hash","payments"],group:"unapplied_payments",readOnly:!1,isDestructive:!0,searchHint:"unbatch release payments",execute:async(e,t)=>{let r=t.resourceId,n=t.hash;if(t.payments==="RELEASE")return qV(e.client,r,n);if(t.payments==="DELETE")return $V(e.client,r,n);throw ut(new ct("payments must be DELETE or RELEASE. Nothing was deleted."))}},{name:"reconcile_unapplied_payment",description:"Record an unapplied payment for a bank record and match both. Direction, account, currency, date and amount come from the record; amount, if sent, must EQUAL it.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID"},unappliedPaymentDetails:{type:"object",description:"The payment",properties:{paymentMethod:lp,contactResourceId:{type:"string"},reference:{type:"string"},amount:{type:"number"},rateToFunctional:{type:"number",description:"Foreign-currency account only"}},required:["paymentMethod"]}},required:["bankStatementEntryResourceId","unappliedPaymentDetails"],group:"reconciliations",readOnly:!1,isDestructive:!0,searchHint:"bank unallocated receipt",execute:async(e,t)=>jV(e.client,t)}],hSr=["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"],XAe={type:"string",description:"Document family",enum:hSr},nlt={type:"string",description:"Version id from get_document_version_history"},mSr=[{name:"get_document_version_history",description:"The stored versions of a document, OLDEST first (last entry = current). Not paginated. Use before restoring to pick a version id.",params:{entity:XAe,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"versions",readOnly:!0,searchHint:"list document version history revisions audit trail",isConcurrencySafe:!0,execute:async(e,t)=>Zat(e.client,t.entity,t.resourceId)},{name:"get_document_version",description:"Read one stored version of a document. An unknown resourceId/version pair returns 422.",params:{entity:XAe,resourceId:{type:"string",description:"Document resourceId"},version:nlt},required:["entity","resourceId","version"],group:"versions",readOnly:!0,searchHint:"get read one document version snapshot",isConcurrencySafe:!0,execute:async(e,t)=>ect(e.client,t.entity,t.resourceId,t.version)},{name:"rollback_document_version",description:"Restore a document to a stored version. REPLACES current state; read it first with get_document_version. `CREATED` is refused: it would delete the document (the API also 422s it).",params:{entity:XAe,resourceId:{type:"string",description:"Document resourceId"},version:nlt},required:["entity","resourceId","version"],group:"versions",readOnly:!1,searchHint:"restore rollback document to previous version undo changes",isDestructive:!0,execute:async(e,t)=>tct(e.client,t.entity,t.resourceId,t.version)},{name:"get_currency_effective_rate",description:"The organization effective rate for a currency on a date: its own custom rate when set, else the platform daily rate. Defaults to today.",params:{currencyCode:{type:"string",description:"ISO 4217 code, e.g. USD (not a resourceId)"},date:{type:"string",description:"YYYY-MM-DD (optional, defaults to today)"}},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"currency effective exchange rate for a date custom or platform",isConcurrencySafe:!0,execute:async(e,t)=>rct(e.client,t.currencyCode,t.date)}];ASr={type:"object",description:"Needs a condition besides types; LINE_ITEMS ids are line IDs",required:["types"],properties:{types:{type:"array",items:{type:"string",enum:[...Qat]},description:"JOURNAL: manual, cashflow"},resourceIds:{type:"array",items:{type:"string"},description:"Up to 500"},reference:Y4("reference","References, not tags. eq matches only a WHOLE reference; a prefix or partial value needs startWith or contains"),valueDate:Y4("valueDate","YYYY-MM-DD; between [from, to]"),contactResourceId:Y4("contactResourceId"),organizationAccountResourceId:Y4("organizationAccountResourceId","LINE_ITEMS only")}},gSr={...up,description:"Max 50; unlisted stay; a set needs type, printable, a class",items:{...up.items,required:["resourceId"],properties:{...up.items.properties,deleted:{type:"boolean",description:"Remove: {resourceId, deleted: true}"}}}},ySr={type:"object",description:"One change",properties:{contactResourceId:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD, within a year"},capsuleResourceId:{type:"string"},tags:Yo,organizationAccountResourceId:{type:"string",description:"Not bank, cash or control"},classifierConfig:gSr}};ilt=e=>`Nothing was changed. Show the counts, exclusions and blocked fields from the preview, end your turn, and apply only after ${e} confirms in a new message. The preview stays valid for 30 minutes.`;ESr=new Set(["update_invoice","update_bill","update_customer_credit_note","update_supplier_credit_note","update_journal","update_cash_in","update_cash_out"]),bSr=2;CSr=500;vSr=[{name:"preview_ledger_find_fix",description:"Find and fix (recode) records across invoices, bills, credit notes, journals and cash entries: one filter, one change, max 500. Returns previewId (30 min), counts, reasons and before/after rows; a blocked field stays, the rest changes. Show counts, exclusions, blocked fields and sample rows, ask to confirm, end the turn; last line `Preview ID: <id>`. LINE_ITEMS ids are line IDs. One record or other fields: quick fix tools.",params:{level:{type:"string",enum:[...sA],description:_W()},filter:ASr,change:ySr},required:["level","filter","change"],group:"quick_fix",readOnly:!0,isConcurrencySafe:!0,noCache:!0,searchHint:v4.join(", "),maxResultSizeChars:3e4,execute:async(e,t)=>{let r=ISr(e)??e.previousPreviewFilter?.(),n=await vW(e.client,t.level,{filter:t.filter,change:t.change});n.previewId&&e.recordIssuedPreviewId?.(n.previewId,t.filter);let i=[...n.filterNotes??[],wSr(t.filter,r),_Sr(n.counts?.matched??0)].filter(o=>o!==void 0);return i.length>0?{...n,filterNotes:i}:n}},{name:"apply_ledger_find_fix",description:"Apply a find and fix preview once, only after the user confirms it in a later message (enforced on chat, email and Telegram; by email, the inbox owner). Saves previewed values over later edits (tags too); e-invoice filings may re-submit. UNKNOWN: runs up to 4 more minutes; wait before re-previewing, never re-apply.",params:{previewId:{type:"string",description:`${fv} characters, from preview_ledger_find_fix`}},required:["previewId"],group:"quick_fix",readOnly:!1,isDestructive:!0,searchHint:"apply confirmed find fix preview",maxResultSizeChars:2e4,execute:async(e,t)=>{let r=Object.keys(t).filter(o=>o!=="previewId");if(r.length>0)throw ut(new ct(`apply_ledger_find_fix takes only previewId; remove ${r.join(", ")}. To apply a different change, run a new preview.`));let n=t.previewId;if(n.length!==fv){let o=n.length<fv?"looks incomplete":"looks too long";throw ut(new ct(`That preview id ${o}: got ${n.length} character${n.length===1?"":"s"}, and a previewId from preview_ledger_find_fix is always ${fv}. This is different from an expired or already-applied preview; check the full id was copied (e.g. every character of the "Preview ID:" line) and retry with the complete value before assuming a new preview is needed.`))}if(MNe(e.toolCalls,"preview_ledger_find_fix",n))return Dv("Not applied: this preview was created in the same turn, so the user has not seen it.",ilt("the user"));if(UNe(e.toolCalls,"apply_ledger_find_fix",n)||e.appliedPreviewIds?.has(n))return Dv("Not applied: this previewId was already sent to apply earlier.","Nothing was sent. This previewId was already applied once in this conversation, and the outcome of that apply may still be unknown. Do not apply it again. Re-read the affected records (or search for them) to see what actually changed, or run a new preview if more still needs fixing.");if(e.senderIsOwner===!1)return Dv("Not applied: by email, only the inbox owner can confirm a Ledger Find & Fix.",ilt("the inbox owner"));let i=await SW(e.client,n,IW(e,wW));return e.appliedPreviewIds?.record(n),i}}];oge=["invoice","bill","customer_credit_note","supplier_credit_note"],SSr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};DSr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);xO={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},kO={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},z4={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."};V4={invoice:{get:(e,t)=>Eo(e,t),attachType:"invoices",settlementKey:"payments",settlementCountKey:"paymentCount",settlements:Ex},bill:{get:(e,t)=>ho(e,t),attachType:"bills",settlementKey:"payments",settlementCountKey:"paymentCount",settlements:WS},customer_credit_note:{get:(e,t)=>Vs(e,t),attachType:"customer-credit-notes",settlementKey:"refunds",settlementCountKey:"refundCount",settlements:Yx},supplier_credit_note:{get:(e,t)=>Ws(e,t),attachType:"supplier-credit-notes",settlementKey:"refunds",settlementCountKey:"refundCount",settlements:Wx},journal:{get:(e,t)=>vs(e,t),attachType:"journals",settlementKey:"payments",settlementCountKey:"paymentCount",settlements:null}},plt={invoices:"invoice",bills:"bill","customer-credit-notes":"customer_credit_note","supplier-credit-notes":"supplier_credit_note"},xSr=["quantity","unitPrice","discount","taxProfileResourceId","withholdingTax"];NSr={INVOICE:"sales.modal.import-invoices",SALE_QUOTE:"sales-orders.modal.import-sales-orders",SALE_ORDER:"sales-orders.modal.import-sales-orders",PURCHASE_REQUEST:"purchase-orders.modal.import-purchase-orders",PURCHASE_ORDER:"purchase-orders.modal.import-purchase-orders"};hlt=["MAGIC_WORKFLOW","MAGIC_CLAIM","BANK_STATEMENT"];sge={kind:"PSEUDO_SQL_EXPORT",count:()=>1,jobs:(e,t)=>{let r=CU(e);return r?[{kind:"PSEUDO_SQL_EXPORT",id:r,label:FSr(t.query)}]:[]}},LSr=new Set(["TIMED_OUT","PENDING","RUNNING"]),QSr={...sge,admitAfter:!0,jobs:(e,t)=>{let r=e?.data?.status;return typeof r=="string"&&LSr.has(r)?sge.jobs(e,t):[]}};PSr={kind:"MAGIC_WORKFLOW",count:(e,t)=>{let r=sAe(e.collectionId,t.client.scopeKey);return r?pat(r,vlt(e).documentTypes):0},jobs:e=>{let t=e?.files;return Array.isArray(t)?t.flatMap(r=>r.status!=="uploaded"||!r.workflowId?[]:[{kind:r.type==="BANK_STATEMENT"?"BANK_STATEMENT":"MAGIC_WORKFLOW",id:r.workflowId,label:r.file.split("/").pop()||r.file,...r.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},..._U(r.subscriptionFBPath,r.backgroundJobFBPath)}]):[]}};_v={type:"string",enum:[...Wme],description:"Record type: bills, invoices, supplier-credit-notes, customer-credit-notes or bank-records."},wv={type:"string",description:"resourceId of the record."},vv={type:"string",description:"Bank account resourceId. Required when entityType is bank-records."},J4={type:"string",description:"Thread id from list_comment_threads."},glt={type:"string",description:"Comment id from list_comments or list_comment_threads."},rge={type:"number",description:"Zero-indexed page. Default 0."};du=[{name:"get_next_reference",description:"Next document number in the org's own series. Same number the web app prefills. Reading does NOT reserve it; two callers reading at once get the same value. Date embedded is always today. Never invent a reference; use this.",params:{type:{type:"string",description:"Document family whose next number is wanted.",enum:[...LD]}},required:["type"],group:"organization",readOnly:!0,noCache:!0,searchHint:"next reference number document numbering series auto reference",isConcurrencySafe:!0,maxResultSizeChars:5e3,execute:async(e,t)=>QD(e.client,t.type)},{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>ms(e.client)},{name:"get_my_context",description:"Resolve the CALLER's own context: identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side; no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>oNe(e.client)},br("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated; response includes totalElements. Use limit/offset to page.","accounts",(e,t,r)=>LI(e,{limit:r,offset:t}),"list chart of accounts with code type class status"),Nt({name:"search_accounts",description:'Search chart of accounts. For OR (name or code), use filter: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:KT,defaults:XT,fetcher:QI,searchHint:"find accounts chart of accounts CoA by name code type class status OR search"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name; returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:`Exact API string: ${H0r}. COGS = "Direct Costs". Common variants normalized client-side. "interest expense"/"interest income" is NOT auto-classified; ask, do not infer: Finance/Financing, Investing or Operating by main business activity.`},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(e,t)=>{let r=t.name,n=await OM(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=PI(t.accountType);return ZS(e.client,{code:t.code,name:r,accountType:i,currencyCode:t.currencyCode,lockDate:t.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry: rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,isDestructive:!0,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(e,t)=>{let r=t.resourceId,n=(await MP(e.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=t.clearLockDate===!0;if(s&&t.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive; pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),t.name!==void 0&&(o.name=t.name),t.code!==void 0&&(o.code=t.code),!s&&t.lockDate!==void 0&&(o.lockDate=t.lockDate),xNe(e.client,r,o)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount }; no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
674
674
 
675
675
  resourceId per row \u2192 update; omit \u2192 create. Note: dedup is by NAME (not code); duplicate name surfaces ORGANIZATION_CHART_OF_ACCOUNT_DUPLICATED per row. Accepts all 23 accountType values (see create_account); common variants normalized via normalizeAccountType.
676
676
 
@@ -791,15 +791,16 @@ Optional fields, the minimum payload, the mapping shape and the condition gramma
791
791
  Then create_lease with typeCode HIRE_PURCHASE, the same term and timing, rent instalment for months 1 to term-1 and finalInstalment for the last, usually ownershipTransfers true with usefulLife.`,params:{flatRate:{type:"number",description:"% per year, flat. 2.78 is 2.78%."},financedAmount:{type:"number",description:"Cash price less down payment"},leaseTerm:{type:"number",description:"Months, 1 to 600"},paymentTiming:{type:"string",enum:[...sh],description:"Default ARREARS"}},required:["flatRate","financedAmount","leaseTerm"],group:"leases",readOnly:!0,isConcurrencySafe:!0,searchHint:"hire purchase flat rate instalment monthly discount rate",execute:async(e,t)=>j8(e.client,t)},{name:"bulk_update_leases",description:`Bulk update leases (max 500) for renaming or activating drafts, not for rent changes. Each row is a partial update and needs resourceId and reference. A resourceId may appear once. No tags: use update_lease. Admin only for active rows. ${oo}`,params:{leases:{type:"array",description:"Lease rows (max 500)",items:{type:"object",properties:{resourceId:{type:"string",description:"Lease resourceId"},reference:{type:"string",description:"The lease reference (the stored one if unchanged)"},name:{type:"string"},typeCode:{type:"string"},contactResourceId:{type:"string"},exemptionType:{type:"string",enum:[...blt]},internalNotes:{type:"string"},isDraftToActive:{type:"boolean",description:"Activate a draft (needs an Admin role)"}},required:["resourceId","reference"]}}},required:["leases"],group:"leases",readOnly:!1,isDestructive:!0,searchHint:"bulk update activate rename leases",backgroundJob:Pn("Update","lease","leases","leases"),execute:async(e,t)=>Y8(e.client,t.leases)},{name:"get_fixed_asset_totals",description:"Asset register totals as at a date: purchase amount, accumulated depreciation, net book value.",params:{endDate:{type:"string",description:"YYYY-MM-DD, default today"}},required:[],group:"fixed_asset_schedules",readOnly:!0,isConcurrencySafe:!0,searchHint:"asset register totals net book value",execute:async(e,t)=>I8(e.client,t.endDate)},{name:"get_fixed_asset_disposal_totals",description:"Disposed (sold or discarded) asset totals as at a date: book value, sale proceeds, gain/loss. Positive = loss.",params:{endDate:{type:"string",description:"As-at date (YYYY-MM-DD). Default today."}},required:[],group:"fixed_asset_schedules",readOnly:!0,isConcurrencySafe:!0,searchHint:"disposal totals gain loss",execute:async(e,t)=>C8(e.client,t.endDate)},{name:"get_fixed_asset_schedule",description:"One asset's depreciation schedule by month and year with book value, plus disposal rows once disposed. At most 60 months per call (totalPeriods): pass fromPeriod/toPeriod for the months asked about (row 1 is period 1).",params:{resourceId:{type:"string",description:"Fixed asset resourceId"},viewDate:{type:"string",description:"YYYY-MM-DD, default today"},...fA},required:["resourceId"],group:"fixed_asset_schedules",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"depreciation schedule per month",execute:async(e,t)=>qW(await v8(e.client,t.resourceId,t.viewDate),pA(t))},{name:"preview_fixed_asset_custom_schedule",description:"Check a custom depreciation schedule and get its month-by-month timeline. Saves nothing. Save it (create or update with CUSTOM_SCHEDULE) only when status is FULLY_SCHEDULED with no errors. defaultSchedule is the straight-line split. At most 60 periods per call: see totalPeriods, page with fromPeriod/toPeriod.",params:{depreciableValueAmount:{type:"number",description:"What the ranges must add up to: depreciable value (book value at transfer for a transferred asset)"},depreciationStartDate:{type:"string",description:"YYYY-MM-DD; month 1 is this calendar month"},effectiveLife:{type:"number",description:"Months (1-1200)"},customSchedule:IO,...fA},required:["depreciableValueAmount","depreciationStartDate","effectiveLife","customSchedule"],group:"fixed_asset_schedules",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"preview check custom depreciation schedule uneven depreciation",execute:async(e,t)=>gd(await _8(e.client,{depreciableValueAmount:t.depreciableValueAmount,depreciationStartDate:t.depreciationStartDate,effectiveLife:t.effectiveLife,customSchedule:t.customSchedule}),pA(t))},{name:"calculate_fixed_asset_disposal",description:"Accumulated depreciation up to the month of depreciationEndDate, plus any brought in, before you sell or discard an asset. Saves nothing but needs the Admin role. Net book value = purchase amount minus totalAccumulateDepreciationAtDisposal; gain or loss on a sale = sale amount minus net book value (negative is a loss; get_fixed_asset_disposal_totals reports loss as positive).",params:{resourceId:{type:"string",description:"Fixed asset resourceId"},depreciationEndDate:{type:"string",description:"YYYY-MM-DD; the date to send to mark_fixed_asset_sold or discard_fixed_asset"}},required:["resourceId","depreciationEndDate"],group:"fixed_asset_schedules",readOnly:!0,isConcurrencySafe:!0,searchHint:"disposal net book value gain loss before sale discard accumulated depreciation",execute:async(e,t)=>w8(e.client,t.resourceId,t.depreciationEndDate)},Nt({name:"search_fixed_asset_eligible_lines",description:"Search unclaimed bill and journal lines on Fixed Asset accounts, grouped by document then account; limit counts documents, not lines. To register one: sourceLineResourceId is purchaseBusinessTransactionResourceId, documentType is purchaseBusinessTransactionType, amount is purchaseAmount.",group:"fixed_asset_schedules",fields:KR,defaults:XR,fetcher:S8,searchHint:"eligible bill lines to register as assets"}),Nt({name:"search_fixed_asset_types",description:"Search asset types. Pick a typeCode whose categoryCode matches the asset category.",group:"fixed_asset_schedules",fields:ZR,defaults:eT,fetcher:D8,searchHint:"asset types type code"}),Nt({name:"search_deferrals",description:"Search deferrals (prepaid expenses and deferred revenue) with figures as at endDate: deferralAmount, amortizedAmount, remainingAmount. Find by reference or name.",group:"deferrals",fields:tT,defaults:rT,fetcher:X2,extraParams:nT,searchHint:"find prepaid deferred revenue deferrals by reference status category type amount as at date"}),ni("get_deferral","Get one deferral: status, viewStatus, category, deferralAmount, amortizedAmount, remainingAmount, schedule settings, accounts and the source lines.","deferrals",(e,t)=>Gg(e,t),"get deferral prepaid details remaining amount source lines"),{name:"create_deferral",description:`Create a deferral that spreads whole bill, invoice or journal lines over months; several: bulk_upsert_deferrals. saveAsDraft defaults to TRUE and a draft posts nothing: pass false to post, then check status before saying it is booked.
792
792
  Nothing is eligible until an account is marked as a deferral account: check search_deferral_accounts first. If the line's account is not marked, say so and ask: marking it and recoding the posted line are both changes to the books that need a yes.
793
793
  The amount is NOT an input: it is the sum of the sourceLineResourceIds lines net of tax, so half a line cannot be deferred. Lines must come from ONE document and ONE deferral account (search_deferral_eligible_lines); category comes from the lines. Activating: Admin only.
794
- A draft needs only reference; saveAsDraft: false also needs the lines, typeCode, name, start date, effectiveLife and amortization account.`,params:{reference:{type:"string",description:"Unique among non-draft deferrals; get_next_reference (DEFERRAL)"},sourceLineResourceIds:{type:"array",items:{type:"string"},description:"sourceLineResourceId values from search_deferral_eligible_lines (max 500), one document, one account"},typeCode:{type:"string",description:"From search_deferral_types for the lines' category"},name:{type:"string",description:"Deferral name (max 500)"},amortizationStartDate:{type:"string",description:"YYYY-MM-DD, on or after the document date. Period 1 starts here; periods are anniversaries, not calendar months."},effectiveLife:{type:"number",description:"Whole months, 1-1200"},amortizationAccountResourceId:{type:"string",description:"P&L account the release posts to: Expense class for prepaid, Revenue class for deferred revenue"},amortizationMethod:{type:"string",enum:[...K2],description:"Default STRAIGHT_LINE"},customSchedule:{...$4,description:"CUSTOM_SCHEDULE only: period ranges 1..effectiveLife, no gap or overlap, total equal to the amount. Check with preview_deferral_custom_schedule."},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"},description:"Tag names"},customFields:Tn,capsuleResourceId:lu,saveAsDraft:{type:"boolean",description:"Default true (nothing posts). False = activate and post the whole schedule."}},required:["reference"],group:"deferrals",readOnly:!1,searchHint:"create deferral spread bill over months prepaid expense recognise invoice deferred revenue",execute:async(e,t)=>Z2(e.client,t)},{name:"update_deferral",description:"Update one deferral or activate a draft (isDraftToActive: true); 2 or more: one bulk_update_deferrals call. Partial: send only what changes; text, tags and lists cannot be cleared. Changing schedule fields (lines, start, months, account, method) on an ACTIVE deferral deletes and re-posts every row and is refused once a period is locked. CLOSED_OUT must be reopened first. Never send a get_deferral result back. Activating or changing an ACTIVE deferral: Admin only.",params:{resourceId:{type:"string",description:"Deferral resourceId"},reference:{type:"string",description:"Default: the stored reference"},sourceLineResourceIds:{type:"array",items:{type:"string"},description:"Replaces the lines; amount and category are re-derived"},typeCode:{type:"string"},name:{type:"string"},amortizationStartDate:{type:"string",description:"YYYY-MM-DD"},effectiveLife:{type:"number",description:"Whole months, 1-1200"},amortizationAccountResourceId:{type:"string"},amortizationMethod:{type:"string",enum:[...K2]},customSchedule:{...$4,description:"Replaces the ranges (CUSTOM_SCHEDULE); STRAIGHT_LINE drops them"},internalNotes:{type:"string"},tags:Yo,customFields:Tn,capsuleResourceId:lu,isDraftToActive:{type:"boolean",description:"Activate a draft and post the whole schedule; several: bulk_update_deferrals"}},required:["resourceId"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"update deferral change start months activate draft",execute:async(e,t)=>{let{resourceId:r,tags:n,...i}=t,o=Xn(n),s=o&&await Xi("deferral",r,()=>Gg(e.client,r));return eq(e.client,r,{...i,...o&&{tags:ui(s?.tags,o)}},s||void 0)}},Ur("delete_deferral","Delete a DRAFT deferral, freeing its source lines and reference. Any other status is not deleted by the agent: the user does it in Jaz. To stop releasing partway and keep history, use close_out_deferral instead. "+M4+" "+zi,"deferrals",(e,t)=>tq(e,t),"delete deferral wrong bill remove prepaid"),{name:"close_out_deferral",description:"Stop releasing after closeOutDate (used as given, any day, not moved to month-end). Posts NOTHING for the remaining balance: it stays on the deferral account (balance sheet) until a journal clears it, so offer a write-off or refund journal. ACTIVE only; reverse with reopen_deferral. Use this, not delete, when a subscription is cancelled. "+zi,params:{resourceId:{type:"string",description:"Deferral resourceId"},closeOutDate:{type:"string",description:"YYYY-MM-DD. On or after the first period date, before the last; not in a locked period."}},required:["resourceId","closeOutDate"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"close out stop amortising cancelled subscription keep remaining balance",execute:async(e,t)=>rq(e.client,t.resourceId,t.closeOutDate)},{name:"reopen_deferral",description:"Reopen a CLOSED_OUT deferral: the stored schedule after the close-out date is posted again and it returns to ACTIVE. "+zi,params:{resourceId:{type:"string",description:"Deferral resourceId"}},required:["resourceId"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"reopen undo close out resume amortising",execute:async(e,t)=>nq(e.client,t.resourceId)},{name:"get_deferral_totals",description:"Register totals as at a date: deferralAmount, amortizedAmount, remainingAmount for ACTIVE and CLOSED_OUT deferrals. ALWAYS pass category, once per category: without it prepaid assets and deferred revenue liabilities add into one meaningless number.",params:{category:{type:"string",enum:[...W2],description:"PREPAID_EXPENSE or DEFERRED_REVENUE"},endDate:{type:"string",description:"As-at date (YYYY-MM-DD). Default today."}},required:["category"],group:"deferrals",readOnly:!0,isConcurrencySafe:!0,searchHint:"how much prepaid left deferred revenue remaining totals as at date",execute:async(e,t)=>iq(e.client,{category:t.category,endDate:t.endDate})},{name:"get_deferral_schedule",description:"One deferral's release rows by year: valueDate, amount released, remaining value. Rows come from posted ledger rows, so a draft returns none. A closed-out deferral has a final CLOSED_OUT row. At most 60 rows per call (totalPeriods): pass fromPeriod/toPeriod for the periods asked about (row 1 is period 1).",params:{resourceId:{type:"string",description:"Deferral resourceId"},viewDate:{type:"string",description:"YYYY-MM-DD, default today"},...fA},required:["resourceId"],group:"deferrals",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"deferral release schedule per month amortization rows",execute:async(e,t)=>jW(await oq(e.client,t.resourceId,t.viewDate),pA(t))},Nt({name:"search_deferral_eligible_lines",description:"Search unclaimed bill, invoice and journal lines on deferral accounts, grouped by document then account; limit counts documents, not lines. Empty until an account is marked as a deferral account. A line with draftDeferralReference is already held by that draft. amount is net of tax: the figure the deferral is built from.",group:"deferrals",fields:iT,defaults:oT,fetcher:sq,searchHint:"eligible bill invoice lines to defer prepaid"}),Nt({name:"search_deferral_types",description:"Search deferral types. Pick a typeCode and always filter by categoryCode: the same typeCode exists in both categories.",group:"deferrals",fields:sT,defaults:aT,fetcher:aq,searchHint:"deferral types type code insurance rent subscription"}),Nt({name:"search_deferral_accounts",description:"Search the accounts marked as deferral accounts (Current Asset gives PREPAID_EXPENSE, Current Liability gives DEFERRED_REVENUE). Reconciliation reports take these accountResourceIds.",group:"deferrals",fields:cT,defaults:lT,fetcher:cq,extraParams:uT,searchHint:"deferral accounts prepaid accounts marked setup"}),{name:"mark_deferral_accounts",description:"Mark (deferralAccount: true) or unmark chart-of-accounts entries as deferral accounts. This changes org setup: confirm with the user first. Only active, non-control Current Asset (prepaid) or Current Liability (deferred revenue) accounts; the source line must already be coded to that account. Unmarking an account any deferral uses (drafts included) is refused. "+zi,params:{accounts:{type:"array",description:"Accounts to mark or unmark (1-500)",items:{type:"object",properties:{organizationAccountResourceId:{type:"string",description:"Chart of accounts resourceId"},deferralAccount:{type:"boolean",description:"true marks, false unmarks"}},required:["organizationAccountResourceId","deferralAccount"]}}},required:["accounts"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"mark account as deferral account prepaid setup",execute:async(e,t)=>(mt(t.accounts,"accounts",500,"accounts"),lq(e.client,t.accounts))},{name:"preview_deferral_custom_schedule",description:"Check uneven release ranges without saving. deferralAmount is the sum of the eligible line amounts. Save with create_deferral only when status is FULLY_SCHEDULED with no errors (others: SHORT, OVER, INCOMPLETE). Periods are anniversary periods from the start date, not calendar months. At most 60 periods per call: see totalPeriods, page with fromPeriod/toPeriod.",params:{deferralAmount:{type:"number",description:"Sum of the eligible line amounts to defer"},amortizationStartDate:{type:"string",description:"YYYY-MM-DD, period 1 starts here"},effectiveLife:{type:"number",description:"Whole months, 1-1200"},customSchedule:{...$4,description:"Period ranges (1-600 items, any order)"},...fA},required:["deferralAmount","amortizationStartDate","effectiveLife","customSchedule"],group:"deferrals",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"preview custom release schedule uneven deferral",execute:async(e,t)=>{let{fromPeriod:r,toPeriod:n,...i}=t;return gd(await uq(e.client,i),pA({fromPeriod:r,toPeriod:n}))}},Nt({name:"search_loans",description:"Search loans (borrowings: term, overdraft, revolving, director loans). Each row carries outstandingPrincipal, currentPortion, nextDueDate and nextDueAmount as at endDate (default today). No free-text query: use the named filters, then get_loan.",group:"loans",fields:AT,defaults:gT,fetcher:YW,extraParams:yT,searchHint:"find loans borrowings bank loan balance what do we owe lender by status reference type"}),ni("get_loan","Get a loan with its terms, accounts and figures as of today: outstandingPrincipal, accruedInterest, currentPortion, nonCurrentPortion, nextDueDate. Schedule: get_loan_schedule; changes: list_loan_events.","loans",(e,t)=>UE(e,t),"get loan details outstanding principal terms accounts"),{name:"create_loan",description:`Record a borrowing after preview_loan_schedule; several: bulk_upsert_loans. The register books interest every month-end and the current/non-current split. It never posts cash: the user records the drawdown receipt and EVERY installment IN FULL themselves, to the accounts named in the params.
794
+ A draft needs only reference; saveAsDraft: false also needs the lines, typeCode, name, start date, effectiveLife and amortization account.`,params:{reference:{type:"string",description:"Unique among non-draft deferrals; get_next_reference (DEFERRAL)"},sourceLineResourceIds:{type:"array",items:{type:"string"},description:"sourceLineResourceId values from search_deferral_eligible_lines (max 500), one document, one account"},typeCode:{type:"string",description:"From search_deferral_types for the lines' category"},name:{type:"string",description:"Deferral name (max 500)"},amortizationStartDate:{type:"string",description:"YYYY-MM-DD, on or after the document date. Period 1 starts here; periods are anniversaries, not calendar months. A past date posts every past period at once on activation (no already-recognised input)."},effectiveLife:{type:"number",description:"Whole months, 1-1200"},amortizationAccountResourceId:{type:"string",description:"P&L account the release posts to: Expense class for prepaid, Revenue class for deferred revenue"},amortizationMethod:{type:"string",enum:[...K2],description:"Default STRAIGHT_LINE"},customSchedule:{...$4,description:"CUSTOM_SCHEDULE only: period ranges 1..effectiveLife, no gap or overlap, total equal to the amount. Check with preview_deferral_custom_schedule."},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"},description:"Tag names"},customFields:Tn,capsuleResourceId:lu,saveAsDraft:{type:"boolean",description:"Default true (nothing posts). False = activate and post the whole schedule."}},required:["reference"],group:"deferrals",readOnly:!1,searchHint:"create deferral spread bill over months prepaid expense recognise invoice deferred revenue",execute:async(e,t)=>Z2(e.client,t)},{name:"update_deferral",description:"Update one deferral or activate a draft (isDraftToActive: true); 2 or more: one bulk_update_deferrals call. Partial: send only what changes; text, tags and lists cannot be cleared. Changing schedule fields (lines, start, months, account, method) on an ACTIVE deferral deletes and re-posts every row and is refused once a period is locked. CLOSED_OUT must be reopened first. Never send a get_deferral result back. Activating or changing an ACTIVE deferral: Admin only.",params:{resourceId:{type:"string",description:"Deferral resourceId"},reference:{type:"string",description:"Default: the stored reference"},sourceLineResourceIds:{type:"array",items:{type:"string"},description:"Replaces the lines; amount and category are re-derived"},typeCode:{type:"string"},name:{type:"string"},amortizationStartDate:{type:"string",description:"YYYY-MM-DD"},effectiveLife:{type:"number",description:"Whole months, 1-1200"},amortizationAccountResourceId:{type:"string"},amortizationMethod:{type:"string",enum:[...K2]},customSchedule:{...$4,description:"Replaces the ranges (CUSTOM_SCHEDULE); STRAIGHT_LINE drops them"},internalNotes:{type:"string"},tags:Yo,customFields:Tn,capsuleResourceId:lu,isDraftToActive:{type:"boolean",description:"Activate a draft and post the whole schedule; several: bulk_update_deferrals"}},required:["resourceId"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"update deferral change start months activate draft",execute:async(e,t)=>{let{resourceId:r,tags:n,...i}=t,o=Xn(n),s=o&&await Xi("deferral",r,()=>Gg(e.client,r));return eq(e.client,r,{...i,...o&&{tags:ui(s?.tags,o)}},s||void 0)}},Ur("delete_deferral","Delete a DRAFT deferral, freeing its source lines and reference. Any other status is not deleted by the agent: the user does it in Jaz. To stop releasing partway and keep history, use close_out_deferral instead. "+M4+" "+zi,"deferrals",(e,t)=>tq(e,t),"delete deferral wrong bill remove prepaid"),{name:"close_out_deferral",description:"Stop releasing after closeOutDate (used as given, any day, not moved to month-end). Posts NOTHING for the remaining balance: it stays on the deferral account (balance sheet) until a journal clears it, so offer a write-off or refund journal. ACTIVE only; reverse with reopen_deferral. Use this, not delete, when a subscription is cancelled. "+zi,params:{resourceId:{type:"string",description:"Deferral resourceId"},closeOutDate:{type:"string",description:"YYYY-MM-DD. On or after the first period date, before the last; not in a locked period."}},required:["resourceId","closeOutDate"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"close out stop amortising cancelled subscription keep remaining balance",execute:async(e,t)=>rq(e.client,t.resourceId,t.closeOutDate)},{name:"reopen_deferral",description:"Reopen a CLOSED_OUT deferral: the stored schedule after the close-out date is posted again and it returns to ACTIVE. "+zi,params:{resourceId:{type:"string",description:"Deferral resourceId"}},required:["resourceId"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"reopen undo close out resume amortising",execute:async(e,t)=>nq(e.client,t.resourceId)},{name:"get_deferral_totals",description:"Register totals as at a date: deferralAmount, amortizedAmount, remainingAmount for ACTIVE and CLOSED_OUT deferrals. ALWAYS pass category, once per category: without it prepaid assets and deferred revenue liabilities add into one meaningless number.",params:{category:{type:"string",enum:[...W2],description:"PREPAID_EXPENSE or DEFERRED_REVENUE"},endDate:{type:"string",description:"As-at date (YYYY-MM-DD). Default today."}},required:["category"],group:"deferrals",readOnly:!0,isConcurrencySafe:!0,searchHint:"how much prepaid left deferred revenue remaining totals as at date",execute:async(e,t)=>iq(e.client,{category:t.category,endDate:t.endDate})},{name:"get_deferral_schedule",description:"One deferral's release rows by year: valueDate, amount released, remaining value. Rows come from posted ledger rows, so a draft returns none. A closed-out deferral has a final CLOSED_OUT row. At most 60 rows per call (totalPeriods): pass fromPeriod/toPeriod for the periods asked about (row 1 is period 1).",params:{resourceId:{type:"string",description:"Deferral resourceId"},viewDate:{type:"string",description:"YYYY-MM-DD, default today"},...fA},required:["resourceId"],group:"deferrals",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"deferral release schedule per month amortization rows",execute:async(e,t)=>jW(await oq(e.client,t.resourceId,t.viewDate),pA(t))},Nt({name:"search_deferral_eligible_lines",description:"Search unclaimed bill, invoice and journal lines on deferral accounts, grouped by document then account; limit counts documents, not lines. Empty until an account is marked as a deferral account. A line with draftDeferralReference is already held by that draft. amount is net of tax: the figure the deferral is built from.",group:"deferrals",fields:iT,defaults:oT,fetcher:sq,searchHint:"eligible bill invoice lines to defer prepaid"}),Nt({name:"search_deferral_types",description:"Search deferral types. Pick a typeCode and always filter by categoryCode: the same typeCode exists in both categories.",group:"deferrals",fields:sT,defaults:aT,fetcher:aq,searchHint:"deferral types type code insurance rent subscription"}),Nt({name:"search_deferral_accounts",description:"Search the accounts marked as deferral accounts (Current Asset gives PREPAID_EXPENSE, Current Liability gives DEFERRED_REVENUE). Reconciliation reports take these accountResourceIds.",group:"deferrals",fields:cT,defaults:lT,fetcher:cq,extraParams:uT,searchHint:"deferral accounts prepaid accounts marked setup"}),{name:"mark_deferral_accounts",description:"Mark (deferralAccount: true) or unmark chart-of-accounts entries as deferral accounts. This changes org setup: confirm with the user first. Only active, non-control Current Asset (prepaid) or Current Liability (deferred revenue) accounts; the source line must already be coded to that account. Unmarking an account any deferral uses (drafts included) is refused. "+zi,params:{accounts:{type:"array",description:"Accounts to mark or unmark (1-500)",items:{type:"object",properties:{organizationAccountResourceId:{type:"string",description:"Chart of accounts resourceId"},deferralAccount:{type:"boolean",description:"true marks, false unmarks"}},required:["organizationAccountResourceId","deferralAccount"]}}},required:["accounts"],group:"deferrals",readOnly:!1,isDestructive:!0,searchHint:"mark account as deferral account prepaid setup",execute:async(e,t)=>(mt(t.accounts,"accounts",500,"accounts"),lq(e.client,t.accounts))},{name:"preview_deferral_custom_schedule",description:"Check uneven release ranges without saving. deferralAmount is the sum of the eligible line amounts. Save with create_deferral only when status is FULLY_SCHEDULED with no errors (others: SHORT, OVER, INCOMPLETE). Periods are anniversary periods from the start date, not calendar months. At most 60 periods per call: see totalPeriods, page with fromPeriod/toPeriod.",params:{deferralAmount:{type:"number",description:"Sum of the eligible line amounts to defer"},amortizationStartDate:{type:"string",description:"YYYY-MM-DD, period 1 starts here"},effectiveLife:{type:"number",description:"Whole months, 1-1200"},customSchedule:{...$4,description:"Period ranges (1-600 items, any order)"},...fA},required:["deferralAmount","amortizationStartDate","effectiveLife","customSchedule"],group:"deferrals",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"preview custom release schedule uneven deferral",execute:async(e,t)=>{let{fromPeriod:r,toPeriod:n,...i}=t;return gd(await uq(e.client,i),pA({fromPeriod:r,toPeriod:n}))}},Nt({name:"search_loans",description:"Search loans (borrowings: term loans and director, shareholder, related-party or intercompany accounts). Each row carries outstandingPrincipal, currentPortion, nextDueDate and nextDueAmount as at endDate (default today). No free-text query: use the named filters, then get_loan.",group:"loans",fields:AT,defaults:gT,fetcher:YW,extraParams:yT,searchHint:"find loans borrowings bank loan balance what do we owe lender by status reference type"}),ni("get_loan","Get a loan with its terms, accounts and figures as of today: outstandingPrincipal, accruedInterest, currentPortion, nonCurrentPortion, nextDueDate. Schedule: get_loan_schedule; changes: list_loan_events.","loans",(e,t)=>UE(e,t),"get loan details outstanding principal terms accounts"),{name:"create_loan",description:`Record a borrowing after preview_loan_schedule; several: bulk_upsert_loans. The register books interest every month-end and the current/non-current split. It never posts cash: the user records the drawdown receipt and EVERY installment IN FULL themselves, to the accounts named in the params.
795
795
  - saveAsDraft defaults to true (posts nothing). false activates (Admin only): needs kind, typeCode, name, principalAmount, drawdownDate, the current liability account and, for a term loan, shape, rate, day count and term.
796
796
  - Existing loan: send trackingStartDate + openingPrincipalAmount. Its opening balance stays in the user's opening balances.
797
797
  - Hire purchase is not a loan: use the leases register.
798
- - reference is required: pass one or set autoReference.`,params:{...uu,autoReference:cu,saveAsDraft:{type:"boolean",description:"Default true = draft, nothing posted. false = activate and post every ledger row."}},required:[],group:"loans",readOnly:!1,searchHint:"create record new loan borrowing bank loan term loan director loan overdraft",execute:async(e,t)=>{let{autoReference:r,...n}=t,i=await hi(e.client,"LOAN",n,r);return zW(e.client,i)}},{name:"update_loan",description:"Update one loan or activate a draft (isDraftToActive: true); 2 or more: one bulk_update_loans call. Partial: send only what changes; a field cannot be cleared. reference is kept. CLOSED_OUT and ENDED loans refuse edits. On an ACTIVE loan a term, fee or account change rewrites the whole schedule from the start (refused when a month is locked): for a mid-life change use a loan event (rate: change_loan_rate). Activating or changing an ACTIVE loan: Admin only.",params:{resourceId:{type:"string",description:"Loan resourceId"},...uu,tags:Yo,isDraftToActive:{type:"boolean",description:"Activate a draft and post its schedule; several: bulk_update_loans"}},required:["resourceId"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"update edit loan terms activate draft loan",execute:async(e,t)=>{let{resourceId:r,tags:n,...i}=t,o=Xn(n),s=o&&await Xi("loan",r,()=>UE(e.client,r));return JW(e.client,r,{...i,...o&&{tags:ui(s?.tags,o)}},s||void 0)}},Ur("delete_loan","Delete a DRAFT loan with its schedule, fees and events. Any other status is not deleted by the agent: the user does it in Jaz. To stop posting but keep the loan, use close_out_loan. Irreversible. "+M4+" "+zi,"loans",(e,t)=>GW(e,t),"delete loan remove borrowing"),{name:"close_out_loan",description:"Stop posting a loan from the month-end of closeOutDate; balances stay and the loan stays on the register. Not an exit: to end a loan use settle_loan, refinance_loan, forgive_loan or convert_loan_to_shares. ACTIVE loans only, and a term loan only before its end date. After close out and reopen, earlier events can never be undone, so undo any you need first. Reverse with reopen_loan. "+zi,params:{resourceId:{type:"string",description:"Loan resourceId"},closeOutDate:{type:"string",description:"YYYY-MM-DD, moved to month-end; after the start, before the end date, after the accounts' lock dates"}},required:["resourceId","closeOutDate"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"close out loan stop posting keep loan tracked elsewhere",execute:async(e,t)=>VW(e.client,t.resourceId,t.closeOutDate)},{name:"reopen_loan",description:"Reopen a CLOSED_OUT loan: rows are rebuilt from its terms and events and it returns to ACTIVE. Events recorded before the close out can no longer be undone afterwards. "+zi,params:{resourceId:{type:"string",description:"Loan resourceId"}},required:["resourceId"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"reopen loan resume posting after close out",execute:async(e,t)=>WW(e.client,t.resourceId)},{name:"get_loan_totals",description:"What the business owes in total at a date: outstandingPrincipal, currentPortion, nonCurrentPortion, accruedInterest across loans on the books (drafts left out, ended loans 0).",params:{endDate:{type:"string",description:"As-at date (YYYY-MM-DD), default today"}},required:[],group:"loans",readOnly:!0,isConcurrencySafe:!0,searchHint:"total borrowings owed current non-current portion accrued interest at date",execute:async(e,t)=>KW(e.client,t.endDate)},{name:"get_loan_schedule",description:"One loan's repayment schedule: per installment dueDate, installment, interest, principal, closingBalance, currentPortion, status (SCHEDULED or SKIPPED), posted. Term loans only: a draft or on-demand loan has no rows. At most 60 installments per call (totalPeriods): pass fromPeriod/toPeriod (periodNumber) for the installments asked about.",params:{resourceId:{type:"string",description:"Loan resourceId"},viewDate:{type:"string",description:"YYYY-MM-DD, default today; sets which rows read as posted"},...fA},required:["resourceId"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"loan repayment schedule instalment installment next payment due",execute:async(e,t)=>pv(await XW(e.client,t.resourceId,t.viewDate),pA(t))},{name:"list_loan_events",description:"A loan's events, latest first: eventType, effectiveDate, details and canUndo. Read it before undo_loan_event (only the latest event can be undone) and before retrying an event, since a retry within 2 minutes returns LOAN_EVENT_DUPLICATE (the first call committed).",params:{resourceId:{type:"string",description:"Loan resourceId"},...OO},required:["resourceId"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"loan events history what changed canUndo",execute:async(e,t)=>{let{limit:r,offset:n}=FO(t);return lh((i,o)=>ZW(e.client,t.resourceId,{limit:o,offset:i}),r,n,20)}},{name:"get_loan_ledger",description:"On-demand loans only (term loans return LOAN_NOT_ON_DEMAND): who drew and repaid what on the loan account, latest first, with balance, totalAdvances, totalRepayments and the balance per contact. A negative balance reads owedToYou. Amount above 0 is an advance owed by the company.",params:{resourceId:{type:"string",description:"Loan resourceId"},endDate:{type:"string",description:"As-at date (YYYY-MM-DD), default today"},...OO},required:["resourceId"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"director loan account ledger overdraft advances repayments balance by contact",execute:async(e,t)=>{let{limit:r,offset:n}=FO(t);return lh((i,o)=>e4(e.client,t.resourceId,{limit:o,offset:i,endDate:t.endDate}),r,n,20)}},Nt({name:"search_loan_types",description:'Search loan types ("Loan Category"). DIRECTOR, SHAREHOLDER, RELATED_PARTY and INTERCOMPANY feed the related-party report.',group:"loans",fields:ET,defaults:bT,fetcher:HW,searchHint:"loan types category bank director shareholder related party"}),{name:"preview_loan_schedule",description:"The repayment schedule these terms would produce, with installmentAmount, totalInterest, totalPayments, effectiveRate, endDate and nonCurrentAccountRequired. Saves nothing. Use it before create_loan. No accounts needed. At most 60 installments per call: see totalPeriods, page with fromPeriod/toPeriod.",params:{...sa,...fA},required:["kind","principalAmount","drawdownDate"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"preview loan schedule monthly payment installment what would payment be",execute:async(e,t)=>{let{fromPeriod:r,toPeriod:n,...i}=t;return pv(await t4(e.client,i),pA({fromPeriod:r,toPeriod:n}))}},{name:"bulk_upsert_loans",description:`Bulk CREATE loans (max 500), each ACTIVE as create_loan with saveAsDraft false. Creates only: an existing reference fails LOAN_DUPLICATE_REFERENCE and is never updated. No CUSTOM shape, fees, capitalization, tags or gain/loss accounts: add those with update_loan afterwards. Dates are YYYY-MM-DD. ${zi} ${oo}`,params:{loans:{type:"array",description:"Loans to create (max 500)",items:{type:"object",properties:{rowIndex:{type:"string"},reference:uu.reference,kind:sa.kind,typeCode:uu.typeCode,name:uu.name,contactResourceId:uu.contactResourceId,principalAmount:sa.principalAmount,drawdownDate:sa.drawdownDate,trackingStartDate:sa.trackingStartDate,openingPrincipalAmount:sa.openingPrincipalAmount,repaymentShape:{...sa.repaymentShape,enum:["ANNUITY","EQUAL_PRINCIPAL","INTEREST_ONLY_THEN_ANNUITY","BULLET","BALLOON"]},annualInterestRate:sa.annualInterestRate,dayCount:sa.dayCount,loanTerm:sa.loanTerm,firstRepaymentDate:sa.firstRepaymentDate,interestOnlyMonths:sa.interestOnlyMonths,balloonAmount:sa.balloonAmount,installmentOverride:sa.installmentOverride,currentLiabilityAccountResourceId:uu.currentLiabilityAccountResourceId,nonCurrentLiabilityAccountResourceId:uu.nonCurrentLiabilityAccountResourceId,interestExpenseAccountResourceId:uu.interestExpenseAccountResourceId,internalNotes:{type:"string"}},required:["reference"]}}},required:["loans"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"bulk import loans migrate bank loans",backgroundJob:Pn("Import","loan","loans","loans"),execute:async(e,t)=>n4(e.client,t.loans)},{name:"bulk_update_loans",description:`Bulk update loans (max 500): update_loan per row, in order, same rules. Each row is partial (omitted fields keep the stored value); fees REPLACE the stored list; an ACTIVE loan's term change rewrites its schedule. No tags (rows with tags are refused: use update_loan, which keeps tags you do not name), attachments or custom fields. A resourceId may appear once. reference is required on every row. Admin only for active rows. ${oo}`,params:{loans:{type:"array",description:"Loans to update (max 500)",items:{type:"object",properties:{resourceId:{type:"string",description:"Loan resourceId"},...sSr,isDraftToActive:{type:"boolean",description:"Activate a draft"}},required:["resourceId","reference"]}}},required:["loans"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"bulk update loans activate drafts",backgroundJob:Pn("Update","loan","loans","loans"),execute:async(e,t)=>i4(e.client,t.loans)},rl({name:"record_loan_drawdown",event:"drawdown",description:"Raise the principal of a loan on a date (a second tranche) and rebuild the schedule. "+Iv+" An on-demand advance is just the user's bank entry. The user records Dr Bank / Cr Non-current Loan; the register posts no cash.",params:{drawdownDate:{type:"string",description:"YYYY-MM-DD, on or after the latest event"},amount:{type:"number",description:"Above 0, 2 dp"},keep:{type:"string",enum:["TERM","INSTALLMENT"],description:"TERM (default): installments rise. INSTALLMENT: the term lengthens (not on BULLET or BALLOON)."},openingBalance:Cv},required:["drawdownDate","amount"],searchHint:"loan drawdown second tranche draw more"}),rl({name:"prepay_loan",event:"prepayment",description:"Reduce principal on a date with an extra repayment and rebuild the schedule. keep says what stays: the same installment (term shortens) or the same term (installments fall). "+Iv+" The user records the cash and any penalty.",params:{prepaymentDate:{type:"string",description:"YYYY-MM-DD, any day, between due dates too"},amount:{type:"number",description:"Above 0, 2 dp, not above the balance"},keep:{type:"string",enum:["TERM","INSTALLMENT"],description:"INSTALLMENT = keep the same monthly payment, the term shortens. TERM = keep the term, installments fall."},openingBalance:Cv},required:["prepaymentDate","amount","keep"],searchHint:"loan prepayment extra repayment paid early lump sum keep same payment"}),rl({name:"change_loan_rate",event:"rateChange",description:"The lender changed the interest rate from a date. Use this, never update_loan, for a rate change: an update rewrites history and fails once a month is locked. "+Iv,params:{effectiveDate:{type:"string",description:"YYYY-MM-DD, any day"},annualInterestRate:{type:"number",description:"New rate, percent per YEAR (0 to below 100, 8 dp)"},keep:{type:"string",enum:["TERM","INSTALLMENT"],description:"TERM = keep the term, installments change. INSTALLMENT = keep the payment, the term changes."},openingBalance:Cv},required:["effectiveDate","annualInterestRate","keep"],searchHint:"loan rate change interest rate moved bank cut raised"}),rl({name:"capitalize_loan_interest",event:"capitalization",description:"The lender added one installment's whole interest to the principal. Later installments are recalculated over the same term. "+Iv,params:{capitalizationDate:{type:"string",description:"YYYY-MM-DD, must be an installment due date (see get_loan_schedule)"},openingBalance:Cv},required:["capitalizationDate"],searchHint:"loan capitalize interest added to principal"}),rl({name:"record_loan_payment_holiday",event:"paymentHoliday",description:"Skip installments (a payment holiday). The skipped interest is added to the balance in both treatments. Read the periodNumbers from get_loan_schedule first. "+Iv,params:{fromPeriod:{type:"number",description:"First skipped installment (periodNumber), due after the latest event"},toPeriod:{type:"number",description:"Last skipped installment, >= fromPeriod"},treatment:{type:"string",enum:["ADD_INTEREST_TO_BALANCE","EXTEND_TERM"],description:"ADD_INTEREST_TO_BALANCE: end date stays. EXTEND_TERM: end date moves by the holiday. Installments rise in both."},openingBalance:Cv},required:["fromPeriod","toPeriod","treatment"],searchHint:"loan payment holiday skip installments months off"}),rl({name:"restructure_loan",event:"restructure",description:"New terms from an installment due date, with the 10% test: under 10% the loan continues with a catch-up posted (needs a gain/loss account and the unamortized costs account on the loan: set the latter with update_loan first); 10% or more ends the loan and creates a NEW one (its id is in the event details, reference <old>-R). Send at least one of annualInterestRate, loanTerm, installmentOverride, fees. Sign: gainLossAmount above 0 is a gain. "+Iv,params:{effectiveDate:{type:"string",description:"YYYY-MM-DD, must be an installment due date"},annualInterestRate:{type:"number",description:"New rate, percent per YEAR; omit to keep"},loanTerm:{type:"number",description:"Installments left after the date, 1-600"},installmentOverride:{type:"number",description:"The lender's new installment"},fees:Ilt,openingBalance:Cv,gainLossAccountResourceId:JAe},required:["effectiveDate"],searchHint:"loan restructure renegotiate new terms substantial modification"}),rl({name:"settle_loan",event:"settlement",description:"End a loan early (payoff). The preview shows the payoff (totalAmount = principal + interest + settlement fees + penalty). Recording ends the loan SETTLED and posts no payoff entry: the user records Dr Current Loan / Cr Bank. A term loan cannot be settled on its final due date. On-demand: the user records the repayment first so the ledger reads exactly 0 on the date (LOAN_PAYOFF_NOT_RECORDED); money owed to the company is refused (LOAN_NOTHING_OWED).",params:{settlementDate:{type:"string",description:"YYYY-MM-DD; term loans: before the last due date"},penaltyAmount:{type:"number",description:"Lender's penalty, quoted only, never posted"}},required:["settlementDate"],searchHint:"loan settle payoff early repayment settlement figure"}),rl({name:"forgive_loan",event:"forgiveness",description:"Write off the whole loan: the lender forgave it (gain to profit and loss) or a shareholder forgave it (capital contribution). Term or on-demand (on-demand uses the ledger balance; nothing owed at 0 or below is refused, LOAN_NOTHING_OWED). amount must equal the outstanding principal; interest to date is written off too. Ends the loan SETTLED. Sign: gainLossAmount above 0 is a gain.",params:{forgivenessDate:{type:"string",description:"YYYY-MM-DD"},amount:{type:"number",description:"The principal outstanding on forgivenessDate (closingBalance in get_loan_schedule), else refused, preview too"},forgivenBy:{type:"string",enum:["LENDER","SHAREHOLDER"],description:"LENDER: needs a gain or loss account. SHAREHOLDER: needs equityAccountResourceId."},equityAccountResourceId:{type:"string",description:"Shareholders Equity account (Retained Earnings is refused). Required for SHAREHOLDER, preview too"},gainLossAccountResourceId:JAe},required:["forgivenessDate","amount","forgivenBy"],searchHint:"loan forgiven written off director waived forgiveness"}),rl({name:"convert_loan_to_shares",event:"conversion",description:"Convert the whole loan (term or on-demand) into shares (IFRIC 19): principal and interest to date are cleared against share capital at fairValue; the difference goes to gain or loss (above 0 is a gain). Ends the loan SETTLED.",params:{conversionDate:{type:"string",description:"YYYY-MM-DD"},fairValue:{type:"number",description:"Fair value of the shares issued, 2 dp, 0 or more (the API accepts 0)"},shareCapitalAccountResourceId:{type:"string",description:"Shareholders Equity account"},gainLossAccountResourceId:JAe},required:["conversionDate","fairValue","shareCapitalAccountResourceId"],searchHint:"loan convert to shares equity investor conversion"}),rl({name:"refinance_loan",event:"refinance",description:"Settle the old TERM loan on refinanceDate and create a new ACTIVE loan from newLoan. Returns the NEW loan. Preview the payoff with settle_loan (preview: true) and the new terms with preview_loan_schedule. The user records the cash.",params:{refinanceDate:{type:"string",description:"YYYY-MM-DD; the old loan is settled on it"},newLoan:{type:"object",description:"The replacement loan, created ACTIVE, with the fields listed. Not here (update_loan after; no CUSTOM shape): tracking, capitalization, gain/loss account.",properties:oSr,required:["reference"]}},required:["refinanceDate","newLoan"],searchHint:"loan refinance replace with new loan lender"}),rl({name:"reclassify_loan_as_current",event:"reclassifyAsCurrent",description:"Make the whole TERM loan balance current from the first month-end on or after the date (IAS 1.74): use for a covenant breach. waiverDate, when the bank waived it, returns the split to schedule. A waiver cannot be added later: undo the event and record it again with waiverDate.",params:{reclassificationDate:{type:"string",description:"YYYY-MM-DD, the breach date"},waiverDate:{type:"string",description:"YYYY-MM-DD, after reclassificationDate"}},required:["reclassificationDate"],searchHint:"loan covenant breach reclassify current waiver"}),rl({name:"undo_loan_event",event:"undo",description:"Reverse the latest event on a loan and rebuild from the day before it. Find it with list_loan_events (canUndo), then undo it. Only the latest event can be undone; ACTIVATE, CLOSE_OUT and REOPEN cannot. If the user names an older event, list the later ones and ask before undoing them, newest first. A replacement loan from refinance or a 10%+ restructure is deleted with it while it has no later event.",params:{eventResourceId:{type:"string",description:"The event resourceId from list_loan_events (the latest one)"}},required:["eventResourceId"],searchHint:"undo loan event reverse rate change prepayment settlement mistake"}),{name:"calculate_loan_opening_balance",description:"Suggest an openingBalance for a loan event after a missed, late or partial payment: scheduleBalance (assumes on-time payment), ledgerBalance (what the user posted on the loan accounts) and suggestedBalance. Saves nothing. TERM loans only. Pass the figure the user confirms as openingBalance on the event.",params:{resourceId:{type:"string",description:"Loan resourceId"},eventType:{type:"string",enum:["DRAWDOWN","PREPAYMENT","RATE_CHANGE","CAPITALIZE_INTEREST","PAYMENT_HOLIDAY","RESTRUCTURE"],description:"The event the balance is for"},date:{type:"string",description:"YYYY-MM-DD, the event date (for a holiday, the first skipped due date)"}},required:["resourceId","eventType","date"],group:"loan_events",readOnly:!0,isConcurrencySafe:!0,searchHint:"loan opening balance missed payment late partial suggest balance",execute:async(e,t)=>r4(e.client,t)},br("list_subscriptions","List recurring subscriptions. Returns status, interval, next schedule date, amount, transaction type.","subscriptions",(e,t,r)=>H8(e,{limit:r,offset:t}),"list recurring subscriptions billing schedules"),ni("get_subscription","Get full subscription details including line items, schedule, and payment history.","subscriptions",(e,t)=>NE(e,t),"get subscription recurring billing details"),{name:"create_subscription",description:`Subscription: auto-generates invoices on schedule WITH proration. DIFFERENT from scheduled_invoice: subscriptions prorate partial periods (credit notes for mid-period changes), but currency/tax/account are immutable after creation. Use for software licenses, retainers, recurring SaaS. Invoices only (no bills).
798
+ - Not in the register: revolving credit, foreign-currency loans (base currency only), loans given, fixed deposits.
799
+ - reference is required: pass one or set autoReference.`,params:{...uu,autoReference:cu,saveAsDraft:{type:"boolean",description:"Default true = draft, nothing posted. false = activate and post every ledger row."}},required:[],group:"loans",readOnly:!1,searchHint:"create record new loan borrowing bank loan term loan director loan overdraft",execute:async(e,t)=>{let{autoReference:r,...n}=t,i=await hi(e.client,"LOAN",n,r);return zW(e.client,i)}},{name:"update_loan",description:"Update one loan or activate a draft (isDraftToActive: true); 2 or more: one bulk_update_loans call. Partial: send only what changes; a field cannot be cleared. reference is kept. CLOSED_OUT and ENDED loans refuse edits. On an ACTIVE loan a term, fee or account change rewrites the whole schedule from the start (refused when a month is locked): for a mid-life change use a loan event (rate: change_loan_rate). Activating or changing an ACTIVE loan: Admin only.",params:{resourceId:{type:"string",description:"Loan resourceId"},...uu,tags:Yo,isDraftToActive:{type:"boolean",description:"Activate a draft and post its schedule; several: bulk_update_loans"}},required:["resourceId"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"update edit loan terms activate draft loan",execute:async(e,t)=>{let{resourceId:r,tags:n,...i}=t,o=Xn(n),s=o&&await Xi("loan",r,()=>UE(e.client,r));return JW(e.client,r,{...i,...o&&{tags:ui(s?.tags,o)}},s||void 0)}},Ur("delete_loan","Delete a DRAFT loan with its schedule, fees and events. Any other status is not deleted by the agent: the user does it in Jaz. To stop posting but keep the loan, use close_out_loan. Irreversible. "+M4+" "+zi,"loans",(e,t)=>GW(e,t),"delete loan remove borrowing"),{name:"close_out_loan",description:"Stop posting a loan from the month-end of closeOutDate; balances stay and the loan stays on the register. Not an exit: to end a loan use settle_loan, refinance_loan, forgive_loan or convert_loan_to_shares. ACTIVE loans only, and a term loan only before its end date. After close out and reopen, earlier events can never be undone, so undo any you need first. Reverse with reopen_loan. "+zi,params:{resourceId:{type:"string",description:"Loan resourceId"},closeOutDate:{type:"string",description:"YYYY-MM-DD, moved to month-end; after the start, before the end date, after the accounts' lock dates"}},required:["resourceId","closeOutDate"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"close out loan stop posting keep loan tracked elsewhere",execute:async(e,t)=>VW(e.client,t.resourceId,t.closeOutDate)},{name:"reopen_loan",description:"Reopen a CLOSED_OUT loan: rows are rebuilt from its terms and events and it returns to ACTIVE. Events recorded before the close out can no longer be undone afterwards. "+zi,params:{resourceId:{type:"string",description:"Loan resourceId"}},required:["resourceId"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"reopen loan resume posting after close out",execute:async(e,t)=>WW(e.client,t.resourceId)},{name:"get_loan_totals",description:"What the business owes in total at a date: outstandingPrincipal, currentPortion, nonCurrentPortion, accruedInterest across loans on the books (drafts left out, ended loans 0).",params:{endDate:{type:"string",description:"As-at date (YYYY-MM-DD), default today"}},required:[],group:"loans",readOnly:!0,isConcurrencySafe:!0,searchHint:"total borrowings owed current non-current portion accrued interest at date",execute:async(e,t)=>KW(e.client,t.endDate)},{name:"get_loan_schedule",description:"One loan's repayment schedule: per installment dueDate, installment, interest, principal, closingBalance, currentPortion, status (SCHEDULED or SKIPPED), posted. Term loans only: a draft or on-demand loan has no rows. At most 60 installments per call (totalPeriods): pass fromPeriod/toPeriod (periodNumber) for the installments asked about.",params:{resourceId:{type:"string",description:"Loan resourceId"},viewDate:{type:"string",description:"YYYY-MM-DD, default today; sets which rows read as posted"},...fA},required:["resourceId"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"loan repayment schedule instalment installment next payment due",execute:async(e,t)=>pv(await XW(e.client,t.resourceId,t.viewDate),pA(t))},{name:"list_loan_events",description:"A loan's events, latest first: eventType, effectiveDate, details and canUndo. Read it before undo_loan_event (only the latest event can be undone) and before retrying an event, since a retry within 2 minutes returns LOAN_EVENT_DUPLICATE (the first call committed).",params:{resourceId:{type:"string",description:"Loan resourceId"},...OO},required:["resourceId"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"loan events history what changed canUndo",execute:async(e,t)=>{let{limit:r,offset:n}=FO(t);return lh((i,o)=>ZW(e.client,t.resourceId,{limit:o,offset:i}),r,n,20)}},{name:"get_loan_ledger",description:"On-demand loans only (term loans return LOAN_NOT_ON_DEMAND): who drew and repaid what on the loan account, latest first, with balance, totalAdvances, totalRepayments and the balance per contact. A negative balance reads owedToYou. Amount above 0 is an advance owed by the company.",params:{resourceId:{type:"string",description:"Loan resourceId"},endDate:{type:"string",description:"As-at date (YYYY-MM-DD), default today"},...OO},required:["resourceId"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"director loan account ledger overdraft advances repayments balance by contact",execute:async(e,t)=>{let{limit:r,offset:n}=FO(t);return lh((i,o)=>e4(e.client,t.resourceId,{limit:o,offset:i,endDate:t.endDate}),r,n,20)}},Nt({name:"search_loan_types",description:'Search loan types ("Loan Category"). DIRECTOR, SHAREHOLDER, RELATED_PARTY and INTERCOMPANY feed the related-party report.',group:"loans",fields:ET,defaults:bT,fetcher:HW,searchHint:"loan types category bank director shareholder related party"}),{name:"preview_loan_schedule",description:"The repayment schedule these terms would produce, with installmentAmount, totalInterest, totalPayments, effectiveRate, endDate and nonCurrentAccountRequired. Saves nothing. Use it before create_loan. No accounts needed. At most 60 installments per call: see totalPeriods, page with fromPeriod/toPeriod.",params:{...sa,...fA},required:["kind","principalAmount","drawdownDate"],group:"loans",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,searchHint:"preview loan schedule monthly payment installment what would payment be",execute:async(e,t)=>{let{fromPeriod:r,toPeriod:n,...i}=t;return pv(await t4(e.client,i),pA({fromPeriod:r,toPeriod:n}))}},{name:"bulk_upsert_loans",description:`Bulk CREATE loans (max 500), each ACTIVE as create_loan with saveAsDraft false. Creates only: an existing reference fails LOAN_DUPLICATE_REFERENCE and is never updated. No CUSTOM shape, fees, capitalization, tags or gain/loss accounts: add those with update_loan afterwards. Dates are YYYY-MM-DD. ${zi} ${oo}`,params:{loans:{type:"array",description:"Loans to create (max 500)",items:{type:"object",properties:{rowIndex:{type:"string"},reference:uu.reference,kind:sa.kind,typeCode:uu.typeCode,name:uu.name,contactResourceId:uu.contactResourceId,principalAmount:sa.principalAmount,drawdownDate:sa.drawdownDate,trackingStartDate:sa.trackingStartDate,openingPrincipalAmount:sa.openingPrincipalAmount,repaymentShape:{...sa.repaymentShape,enum:["ANNUITY","EQUAL_PRINCIPAL","INTEREST_ONLY_THEN_ANNUITY","BULLET","BALLOON"]},annualInterestRate:sa.annualInterestRate,dayCount:sa.dayCount,loanTerm:sa.loanTerm,firstRepaymentDate:sa.firstRepaymentDate,interestOnlyMonths:sa.interestOnlyMonths,balloonAmount:sa.balloonAmount,installmentOverride:sa.installmentOverride,currentLiabilityAccountResourceId:uu.currentLiabilityAccountResourceId,nonCurrentLiabilityAccountResourceId:uu.nonCurrentLiabilityAccountResourceId,interestExpenseAccountResourceId:uu.interestExpenseAccountResourceId,internalNotes:{type:"string"}},required:["reference"]}}},required:["loans"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"bulk import loans migrate bank loans",backgroundJob:Pn("Import","loan","loans","loans"),execute:async(e,t)=>n4(e.client,t.loans)},{name:"bulk_update_loans",description:`Bulk update loans (max 500): update_loan per row, in order, same rules. Each row is partial (omitted fields keep the stored value); fees REPLACE the stored list; an ACTIVE loan's term change rewrites its schedule. No tags (rows with tags are refused: use update_loan, which keeps tags you do not name), attachments or custom fields. A resourceId may appear once. reference is required on every row. Admin only for active rows. ${oo}`,params:{loans:{type:"array",description:"Loans to update (max 500)",items:{type:"object",properties:{resourceId:{type:"string",description:"Loan resourceId"},...sSr,isDraftToActive:{type:"boolean",description:"Activate a draft"}},required:["resourceId","reference"]}}},required:["loans"],group:"loans",readOnly:!1,isDestructive:!0,searchHint:"bulk update loans activate drafts",backgroundJob:Pn("Update","loan","loans","loans"),execute:async(e,t)=>i4(e.client,t.loans)},rl({name:"record_loan_drawdown",event:"drawdown",description:"Raise the principal of a loan on a date (a second tranche) and rebuild the schedule. "+Iv+" An on-demand advance is just the user's bank entry. The user records Dr Bank / Cr Non-current Loan; the register posts no cash.",params:{drawdownDate:{type:"string",description:"YYYY-MM-DD, on or after the latest event"},amount:{type:"number",description:"Above 0, 2 dp"},keep:{type:"string",enum:["TERM","INSTALLMENT"],description:"TERM (default): installments rise. INSTALLMENT: the term lengthens (not on BULLET or BALLOON)."},openingBalance:Cv},required:["drawdownDate","amount"],searchHint:"loan drawdown second tranche draw more"}),rl({name:"prepay_loan",event:"prepayment",description:"Reduce principal on a date with an extra repayment and rebuild the schedule. keep says what stays: the same installment (term shortens) or the same term (installments fall). "+Iv+" The user records the cash and any penalty.",params:{prepaymentDate:{type:"string",description:"YYYY-MM-DD, any day, between due dates too"},amount:{type:"number",description:"Above 0, 2 dp, not above the balance"},keep:{type:"string",enum:["TERM","INSTALLMENT"],description:"INSTALLMENT = keep the same monthly payment, the term shortens. TERM = keep the term, installments fall."},openingBalance:Cv},required:["prepaymentDate","amount","keep"],searchHint:"loan prepayment extra repayment paid early lump sum keep same payment"}),rl({name:"change_loan_rate",event:"rateChange",description:"The lender changed the interest rate from a date. Use this, never update_loan, for a rate change: an update rewrites history and fails once a month is locked. "+Iv,params:{effectiveDate:{type:"string",description:"YYYY-MM-DD, any day"},annualInterestRate:{type:"number",description:"New rate, percent per YEAR (0 to below 100, 8 dp)"},keep:{type:"string",enum:["TERM","INSTALLMENT"],description:"TERM = keep the term, installments change. INSTALLMENT = keep the payment, the term changes."},openingBalance:Cv},required:["effectiveDate","annualInterestRate","keep"],searchHint:"loan rate change interest rate moved bank cut raised"}),rl({name:"capitalize_loan_interest",event:"capitalization",description:"The lender added one installment's whole interest to the principal. Later installments are recalculated over the same term. "+Iv,params:{capitalizationDate:{type:"string",description:"YYYY-MM-DD, must be an installment due date (see get_loan_schedule)"},openingBalance:Cv},required:["capitalizationDate"],searchHint:"loan capitalize interest added to principal"}),rl({name:"record_loan_payment_holiday",event:"paymentHoliday",description:"Skip installments (a payment holiday). The skipped interest is added to the balance in both treatments. Read the periodNumbers from get_loan_schedule first. "+Iv,params:{fromPeriod:{type:"number",description:"First skipped installment (periodNumber), due after the latest event"},toPeriod:{type:"number",description:"Last skipped installment, >= fromPeriod"},treatment:{type:"string",enum:["ADD_INTEREST_TO_BALANCE","EXTEND_TERM"],description:"ADD_INTEREST_TO_BALANCE: end date stays. EXTEND_TERM: end date moves by the holiday. Installments rise in both."},openingBalance:Cv},required:["fromPeriod","toPeriod","treatment"],searchHint:"loan payment holiday skip installments months off"}),rl({name:"restructure_loan",event:"restructure",description:"New terms from an installment due date, with the 10% test: under 10% the loan continues with a catch-up posted (needs a gain/loss account and the unamortized costs account on the loan: set the latter with update_loan first); 10% or more ends the loan and creates a NEW one (its id is in the event details, reference <old>-R). Send at least one of annualInterestRate, loanTerm, installmentOverride, fees. Sign: gainLossAmount above 0 is a gain. "+Iv,params:{effectiveDate:{type:"string",description:"YYYY-MM-DD, must be an installment due date"},annualInterestRate:{type:"number",description:"New rate, percent per YEAR; omit to keep"},loanTerm:{type:"number",description:"Installments left after the date, 1-600"},installmentOverride:{type:"number",description:"The lender's new installment"},fees:Ilt,openingBalance:Cv,gainLossAccountResourceId:JAe},required:["effectiveDate"],searchHint:"loan restructure renegotiate new terms substantial modification"}),rl({name:"settle_loan",event:"settlement",description:"End a loan early (payoff). The preview shows the payoff (totalAmount = principal + interest + settlement fees + penalty). Recording ends the loan SETTLED, writes off fees not yet amortized and posts no payoff entry: the user records Dr Current Loan / Cr Bank. A term loan cannot be settled on its final due date. On-demand: the user records the repayment first so the ledger reads exactly 0 on the date (LOAN_PAYOFF_NOT_RECORDED); money owed to the company is refused (LOAN_NOTHING_OWED).",params:{settlementDate:{type:"string",description:"YYYY-MM-DD; term loans: before the last due date"},penaltyAmount:{type:"number",description:"Lender's penalty, quoted only, never posted"}},required:["settlementDate"],searchHint:"loan settle payoff early repayment settlement figure"}),rl({name:"forgive_loan",event:"forgiveness",description:"Write off the whole loan: the lender forgave it (gain to profit and loss) or a shareholder forgave it (capital contribution). Term or on-demand (on-demand uses the ledger balance; nothing owed at 0 or below is refused, LOAN_NOTHING_OWED). amount must equal the outstanding principal; interest to date is written off too. Ends the loan SETTLED. Sign: gainLossAmount above 0 is a gain.",params:{forgivenessDate:{type:"string",description:"YYYY-MM-DD"},amount:{type:"number",description:"The principal outstanding on forgivenessDate (closingBalance in get_loan_schedule), else refused, preview too"},forgivenBy:{type:"string",enum:["LENDER","SHAREHOLDER"],description:"LENDER: needs a gain or loss account. SHAREHOLDER: needs equityAccountResourceId."},equityAccountResourceId:{type:"string",description:"Shareholders Equity account (Retained Earnings is refused). Required for SHAREHOLDER, preview too"},gainLossAccountResourceId:JAe},required:["forgivenessDate","amount","forgivenBy"],searchHint:"loan forgiven written off director waived forgiveness"}),rl({name:"convert_loan_to_shares",event:"conversion",description:"Convert the whole loan (term or on-demand) into shares (IFRIC 19): principal and interest to date are cleared against share capital at fairValue; the difference goes to gain or loss (above 0 is a gain). Ends the loan SETTLED.",params:{conversionDate:{type:"string",description:"YYYY-MM-DD"},fairValue:{type:"number",description:"Fair value of the shares issued, 2 dp, 0 or more (the API accepts 0)"},shareCapitalAccountResourceId:{type:"string",description:"Shareholders Equity account"},gainLossAccountResourceId:JAe},required:["conversionDate","fairValue","shareCapitalAccountResourceId"],searchHint:"loan convert to shares equity investor conversion"}),rl({name:"refinance_loan",event:"refinance",description:"Settle the old TERM loan on refinanceDate and create a new ACTIVE loan from newLoan. Returns the NEW loan. Preview the payoff with settle_loan (preview: true) and the new terms with preview_loan_schedule. The user records the cash.",params:{refinanceDate:{type:"string",description:"YYYY-MM-DD; the old loan is settled on it"},newLoan:{type:"object",description:"The replacement loan, created ACTIVE, with the fields listed. Not here (update_loan after; no CUSTOM shape): tracking, capitalization, gain/loss account.",properties:oSr,required:["reference"]}},required:["refinanceDate","newLoan"],searchHint:"loan refinance replace with new loan lender"}),rl({name:"reclassify_loan_as_current",event:"reclassifyAsCurrent",description:"Make the whole TERM loan balance current from the first month-end on or after the date (IAS 1.74): use for a covenant breach. waiverDate, when the bank waived it, returns the split to schedule. A waiver cannot be added later: undo the event and record it again with waiverDate.",params:{reclassificationDate:{type:"string",description:"YYYY-MM-DD, the breach date"},waiverDate:{type:"string",description:"YYYY-MM-DD, after reclassificationDate"}},required:["reclassificationDate"],searchHint:"loan covenant breach reclassify current waiver"}),rl({name:"undo_loan_event",event:"undo",description:"Reverse the latest event on a loan and rebuild from the day before it. Find it with list_loan_events (canUndo), then undo it. Only the latest event can be undone; ACTIVATE, CLOSE_OUT and REOPEN cannot. If the user names an older event, list the later ones and ask before undoing them, newest first. A replacement loan from refinance or a 10%+ restructure is deleted with it while it has no later event.",params:{eventResourceId:{type:"string",description:"The event resourceId from list_loan_events (the latest one)"}},required:["eventResourceId"],searchHint:"undo loan event reverse rate change prepayment settlement mistake"}),{name:"calculate_loan_opening_balance",description:"Suggest an openingBalance for a loan event after a missed, late or partial payment: scheduleBalance (assumes on-time payment), ledgerBalance (what the user posted on the loan accounts) and suggestedBalance. Saves nothing. TERM loans only. Pass the figure the user confirms as openingBalance on the event.",params:{resourceId:{type:"string",description:"Loan resourceId"},eventType:{type:"string",enum:["DRAWDOWN","PREPAYMENT","RATE_CHANGE","CAPITALIZE_INTEREST","PAYMENT_HOLIDAY","RESTRUCTURE"],description:"The event the balance is for"},date:{type:"string",description:"YYYY-MM-DD, the event date (for a holiday, the first skipped due date)"}},required:["resourceId","eventType","date"],group:"loan_events",readOnly:!0,isConcurrencySafe:!0,searchHint:"loan opening balance missed payment late partial suggest balance",execute:async(e,t)=>r4(e.client,t)},br("list_subscriptions","List recurring subscriptions. Returns status, interval, next schedule date, amount, transaction type.","subscriptions",(e,t,r)=>H8(e,{limit:r,offset:t}),"list recurring subscriptions billing schedules"),ni("get_subscription","Get full subscription details including line items, schedule, and payment history.","subscriptions",(e,t)=>NE(e,t),"get subscription recurring billing details"),{name:"create_subscription",description:`Subscription: auto-generates invoices on schedule WITH proration. DIFFERENT from scheduled_invoice: subscriptions prorate partial periods (credit notes for mid-period changes), but currency/tax/account are immutable after creation. Use for software licenses, retainers, recurring SaaS. Invoices only (no bills).
799
800
 
800
801
  accountResourceId + taxProfileResourceId apply to ALL line items (immutable). interval: WEEKLY | MONTHLY | QUARTERLY | YEARLY. reference REQUIRED. proratedConfig (optional) tunes the first period; response carries bundledPeriodEndDate + bundledAmount when includeNextPeriod=true.
801
802
 
802
- Dynamic strings (reference/lineItem name/notes): ${dO}, relative to transaction date.`,params:{interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Billing interval, sent as `repeat`. QUARTERLY is rejected with 422."},startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD, optional for ongoing)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference (REQUIRED). Supports dynamic strings: {{Month}}, {{Year}}, etc."},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},accountResourceId:{type:"string",description:"Revenue account resourceId (applied to ALL line items; must be same)"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId (applied to ALL line items; must be same)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"}},required:["name","unitPrice","quantity"]},description:"Line items (name, unitPrice, quantity only; account/tax set at top level)"},proratedConfig:{type:"object",description:"Optional prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"Prorated window start (YYYY-MM-DD). Defaults to subscription startDate."},proratedAdjustmentLineText:{type:"string",description:'Adjustment line label on the prorated invoice (default "Prorated adjustment").'},itemResourceId:{type:"string",description:"Non-inventory item resourceId (UUIDv4) for the prorated adjustment line. Defaults to the subscription's first line item."},includeNextPeriod:{type:"boolean",description:"If true: bundle the next full period at 2x quantity AND advance nextScheduleDate by one extra interval. Response carries bundledPeriodEndDate + bundledAmount."}}}},required:["interval","startDate","contactResourceId","lineItems","accountResourceId","valueDate","dueDate","reference"],group:"subscriptions",readOnly:!1,searchHint:"create new recurring subscription billing schedule with proration",execute:async(e,t)=>{let{interval:r,startDate:n,endDate:i,contactResourceId:o,reference:s,valueDate:a,dueDate:c,accountResourceId:u,taxProfileResourceId:d,lineItems:f,proratedConfig:p}=t,h=f.map(A=>({...A,accountResourceId:u,...d?{taxProfileResourceId:d}:{}})),m={repeat:r,startDate:n,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment",...p??{}},invoice:{contactResourceId:o,reference:s||Qo("SUB"),valueDate:a,dueDate:c,lineItems:h,saveAsDraft:!1}};return i&&(m.endDate=i),z8(e.client,m)}},{name:"update_subscription",description:"Update a subscription (interval, end date, status, template, proratedConfig). `data` is required on every update, even end-date-only: create shape (reference, valueDate, dueDate, contactResourceId, lineItems with accountResourceId), not get_subscription's `data`. Omitted status is kept. Line accounts and tax profiles are immutable: cancel and recreate.",params:{resourceId:{type:"string",description:"Subscription id"},interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Sent as `repeat`"},endDate:{type:"string",description:"New end date (YYYY-MM-DD)"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"INACTIVE pauses"},proratedConfig:{type:"object",description:"Prorated-period settings, all optional",properties:{proratedStartDate:{type:"string",description:"YYYY-MM-DD"},proratedAdjustmentLineText:{type:"string"},itemResourceId:{type:"string",description:"UUIDv4"},includeNextPeriod:{type:"boolean"}}},data:{type:"object",description:"Transaction template (replaces the stored one)"}},required:["resourceId","data"],group:"subscriptions",readOnly:!1,isDestructive:!0,searchHint:"update subscription schedule amount proration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return J8(e.client,r,n)}},Ur("delete_subscription","Delete a subscription. Removes the recurring schedule.","subscriptions",(e,t)=>G8(e,t),"permanently delete a subscription schedule"),{name:"cancel_subscription",description:"Cancel an active subscription. Prorates remaining period and stops future billing. Safe to call; subscriptions can be reactivated after cancellation. Always use this tool when the user asks to cancel a subscription. Must cancel before delete.",params:{resourceId:{type:"string",description:"Subscription resourceId"},cancelDateType:{type:"string",enum:["END_OF_CURRENT_PERIOD","END_OF_LAST_PERIOD","CUSTOM_DATE"],description:"When to end (default: END_OF_CURRENT_PERIOD)"},endDate:{type:"string",description:"Custom cancel date YYYY-MM-DD (only with CUSTOM_DATE)"},proratedAdjustmentLineText:{type:"string",description:'Label for proration line item (default: "Prorated adjustment")'}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"cancel stop a recurring subscription",isDestructive:!0,execute:async(e,t)=>V8(e.client,t.resourceId,{cancelDateType:t.cancelDateType,endDate:t.endDate,proratedAdjustmentLineText:t.proratedAdjustmentLineText})},Nt({name:"search_scheduled_transactions",description:"Search scheduled transactions (subscriptions / recurring invoices / journals / cash entries).",group:"subscriptions",fields:IT,defaults:CT,fetcher:W8,searchHint:"find scheduled recurring transactions subscriptions schedulers by type status interval contact"}),{name:"generate_vat_ledger",description:"Generate VAT/GST ledger report showing all tax transactions for the period.",params:{startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD)"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate VAT GST tax ledger report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>_q(e.client,{startDate:t.startDate,endDate:t.endDate})},{name:"generate_equity_movement",description:"Generate equity movement report (statement of changes in equity).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},compareWith:{type:"string",description:"Comparison period unit; compareCount sets how many",enum:["PREVIOUS_MONTHS","PREVIOUS_DAYS","PREVIOUS_QUARTERS","PREVIOUS_YEARS"]},compareCount:{type:"number",description:"Number of comparison periods"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"financial_reports",readOnly:!0,searchHint:"generate equity movement statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>wq(e.client,t)},{name:"generate_bank_balance_summary",description:"Generate bank balance summary report: snapshot of all bank account balances at a point in time.",params:{primarySnapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["primarySnapshotDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank account balance summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>vq(e.client,{primarySnapshotDate:t.primarySnapshotDate,currencyCode:t.currencyCode})},{name:"generate_bank_reconciliation_summary",description:"Generate bank reconciliation summary for a specific bank account. Essential for month-end close; call this for each in-scope bank account for the current entity and reporting period. Use for bank recon status, unreconciled items count, or reconciliation summaries.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Sq(e.client,t)},{name:"generate_bank_reconciliation_details",description:"Generate detailed bank reconciliation report showing matched/unmatched items.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},filter:{type:"object",description:"Report filter. valueDate is required.",properties:{valueDate:{type:"object",description:"Report window.",properties:{range:{type:"array",items:{type:"string"},description:"Inclusive [from, to], YYYY-MM-DD. The only accepted operator."}},required:["range"]},reconciliationStatus:{type:"string",description:"Reconciliation status (no published enum)."}},required:["valueDate"]},currencyCode:{type:"string",description:"Currency code"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate","filter"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation detailed report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Dq(e.client,t)},{name:"generate_fixed_assets_summary",description:"Generate fixed assets summary report grouped by account, type, category, or status.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["ACCOUNT","TYPE","CATEGORY","STATUS"],description:"Grouping dimension"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate","groupBy"],group:"register_reports",readOnly:!0,searchHint:"generate fixed asset summary depreciation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Rq(e.client,t)},{name:"generate_fixed_assets_reconciliation_summary",description:"Generate fixed assets reconciliation summary: reconciles asset register with general ledger.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate fixed asset reconciliation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Tq(e.client,t)},{name:"generate_deferrals_summary",description:"Generate the deferrals roll-forward for a period: deferral amount, opening remaining, amortized in period, closing remaining. Sections never mix categories (prepaid vs deferred revenue).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["CATEGORY","TYPE","ACCOUNT","STATUS"],description:"Default CATEGORY"},filter:G0r,currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate deferrals summary prepaid roll-forward amortized in period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>xq(e.client,t)},{name:"generate_deferrals_reconciliation_summary",description:"Generate the deferrals reconciliation: does the deferral register agree with the general ledger, per deferral account and per category. A difference usually means a line on the account not yet deferred.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Deferral account ids from search_deferral_accounts (max 500). Omit for all."},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate deferrals reconciliation prepaid register agree general ledger",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>kq(e.client,t)},{name:"generate_leases_summary",description:"Generate the lease register (the IFRS 16 lease note) for a period: opening liability, additions, interest, payments, terminations, closing, current and non-current, right-of-use asset, grouped by type, status or account.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["TYPE","STATUS","ACCOUNT"],description:"Grouping dimension (default TYPE)"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate lease register IFRS 16 note lease liability roll-forward",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>VUe(e.client,t)},{name:"generate_leases_reconciliation_summary",description:"Reconcile the lease register to the general ledger per lease account, counting scheduled rent as debits to the current lease liability. A liability difference almost always means a rent bill coded elsewhere, posted in another month, or not booked.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Lease account resourceIds (max 500). Default: all lease accounts."},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate lease register vs general ledger reconciliation rent coding",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>WUe(e.client,t)},wO("generate_loans_summary","loans-summary","Borrowings note: per loan opening balance, drawdowns, repayments, interest, closing balance, current and non-current portion and accrued interest, grouped by type, status, account or lender. Positions are the register's; movements read the ledger, so an unrecorded repayment shows here.","generate loans summary borrowings note by lender type"),wO("generate_loans_roll_forward","loans-roll-forward","Loan roll-forward over a period: opening + drawdowns + repayments + interest + fees + non-cash = closing, tying to the balance sheet. Drawdowns and repayments are the user's own postings, so a missing repayment shows as a gap.","generate loans roll forward movement borrowings"),wO("generate_loans_related_party","loans-related-party","Related-party loan balances by contact: loans of type DIRECTOR, SHAREHOLDER, RELATED_PARTY and INTERCOMPANY, for the audit.","generate related party director shareholder loans balances audit"),wO("generate_loans_interest","loans-interest","Interest cost per loan for the period: interest, interest added to principal, interest to an asset, fees amortized and total finance cost.","generate loan interest cost finance cost per loan"),wO("generate_loans_maturity_analysis","loans-maturity-analysis","Liquidity note as at the end date: per term loan the undiscounted installments still due within one year, one to two, two to five and over five years, plus future interest and principal outstanding. On-demand balances fall within one year.","generate loan maturity analysis liquidity undiscounted installments buckets"),{name:"generate_loans_reconciliation_summary",description:"Loan register vs general ledger per account, in two groups: loan liability accounts and unamortized transaction cost accounts. The register side includes what the user is expected to post, so a non-zero difference means a missed, late, partial or mis-coded installment: name the account and amount and check that month. Debit minus credit, so liabilities read negative.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Loan account resourceIds (max 500); omit for all"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate loan reconciliation register vs ledger month end difference",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Nx(e.client,"loans-recon-summary",t)},q4("generate_aged_receivables_summary","receivables","summary"),q4("generate_aged_payables_summary","payables","summary"),{name:"get_ledger_highlights",description:"Get ledger highlights, summary metadata about the org general ledger: transaction counts by type, date range, active accounts, active currencies, and cross-currency detection. No parameters needed.",params:{},required:[],group:"operational_reports",readOnly:!0,searchHint:"get ledger highlights key metrics for period",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>Oq(e.client)},br("list_contact_groups","List contact groups with their associated contacts. Used to segment customers/suppliers.","contact_groups",(e,t,r)=>X8(e,{limit:r,offset:t}),"list contact groups customer supplier categories"),ni("get_contact_group","Get contact group details including all associated contacts.","contact_groups",(e,t)=>Z8(e,t),"get contact group details members"),Nt({name:"search_contact_groups",description:"Search contact groups.",group:"contact_groups",fields:ax,defaults:cx,fetcher:eW,searchHint:"find contact groups segments categories by name"}),{name:"create_contact_group",description:'Create a new contact group for segmenting contacts (e.g., "VIP Customers", "Government", "Overdue > 90 Days").',params:{name:{type:"string",description:"Group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to add to the group"}},required:["name"],group:"contact_groups",readOnly:!1,searchHint:"create new contact group category",execute:async(e,t)=>tW(e.client,{name:t.name,contactResourceIds:t.contactResourceIds})},{name:"update_contact_group",description:"Update a contact group name or members. Membership replaces the existing set.",params:{resourceId:{type:"string",description:"Contact group resourceId"},name:{type:"string",description:"New group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to set as group members, max 50 (replaces existing). Sent as associatedContactResourceIds."}},required:["resourceId"],group:"contact_groups",readOnly:!1,isDestructive:!0,searchHint:"update contact group name details",execute:async(e,t)=>rW(e.client,t.resourceId,{name:t.name,contactResourceIds:t.contactResourceIds})},Ur("delete_contact_group","Delete a contact group. Does not delete the contacts themselves.","contact_groups",(e,t)=>nW(e,t),"permanently delete a contact group"),br("list_custom_fields","List custom fields defined for the organization. Custom fields add extra data to invoices, bills, credit notes, and payments.","custom_fields",(e,t,r)=>lW(e,{limit:r,offset:t}),"list custom fields metadata on transactions"),{name:"get_custom_field",description:"Get a custom field by resourceId. Returns full definition including appliesTo flags and list options.",params:{resourceId:{type:"string",description:"Custom field resourceId"}},required:["resourceId"],group:"custom_fields",readOnly:!0,searchHint:"get custom field definition details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>oO(e.client,t.resourceId)},Nt({name:"search_custom_fields",description:"Search custom fields.",group:"custom_fields",fields:ox,defaults:sx,fetcher:uW,searchHint:"find custom fields user-defined attributes by name data type"}),{name:"create_custom_field",description:`Create a new custom field. Custom fields appear on transactions (invoices, bills, credit notes, payments).
803
+ Dynamic strings (reference/lineItem name/notes): ${dO}, relative to transaction date.`,params:{interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Billing interval, sent as `repeat`. QUARTERLY is rejected with 422."},startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD, optional for ongoing)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference (REQUIRED). Supports dynamic strings: {{Month}}, {{Year}}, etc."},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},accountResourceId:{type:"string",description:"Revenue account resourceId (applied to ALL line items; must be same)"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId (applied to ALL line items; must be same)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"}},required:["name","unitPrice","quantity"]},description:"Line items (name, unitPrice, quantity only; account/tax set at top level)"},proratedConfig:{type:"object",description:"Optional prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"Prorated window start (YYYY-MM-DD). Defaults to subscription startDate."},proratedAdjustmentLineText:{type:"string",description:'Adjustment line label on the prorated invoice (default "Prorated adjustment").'},itemResourceId:{type:"string",description:"Non-inventory item resourceId (UUIDv4) for the prorated adjustment line. Defaults to the subscription's first line item."},includeNextPeriod:{type:"boolean",description:"If true: bundle the next full period at 2x quantity AND advance nextScheduleDate by one extra interval. Response carries bundledPeriodEndDate + bundledAmount."}}}},required:["interval","startDate","contactResourceId","lineItems","accountResourceId","valueDate","dueDate","reference"],group:"subscriptions",readOnly:!1,searchHint:"create new recurring subscription billing schedule with proration",execute:async(e,t)=>{let{interval:r,startDate:n,endDate:i,contactResourceId:o,reference:s,valueDate:a,dueDate:c,accountResourceId:u,taxProfileResourceId:d,lineItems:f,proratedConfig:p}=t,h=f.map(A=>({...A,accountResourceId:u,...d?{taxProfileResourceId:d}:{}})),m={repeat:r,startDate:n,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment",...p??{}},invoice:{contactResourceId:o,reference:s||Qo("SUB"),valueDate:a,dueDate:c,lineItems:h,saveAsDraft:!1}};return i&&(m.endDate=i),z8(e.client,m)}},{name:"update_subscription",description:"Update a subscription (interval, end date, status, template, proratedConfig). `data` is required on every update, even end-date-only: create shape (reference, valueDate, dueDate, contactResourceId, lineItems with accountResourceId), not get_subscription's `data`. Omitted status is kept. Line accounts and tax profiles are immutable: cancel and recreate.",params:{resourceId:{type:"string",description:"Subscription id"},interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Sent as `repeat`"},endDate:{type:"string",description:"New end date (YYYY-MM-DD)"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"INACTIVE pauses"},proratedConfig:{type:"object",description:"Prorated-period settings, all optional",properties:{proratedStartDate:{type:"string",description:"YYYY-MM-DD"},proratedAdjustmentLineText:{type:"string"},itemResourceId:{type:"string",description:"UUIDv4"},includeNextPeriod:{type:"boolean"}}},data:{type:"object",description:"Transaction template (replaces the stored one)"}},required:["resourceId","data"],group:"subscriptions",readOnly:!1,isDestructive:!0,searchHint:"update subscription schedule amount proration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return J8(e.client,r,n)}},Ur("delete_subscription","Delete a subscription. Removes the recurring schedule.","subscriptions",(e,t)=>G8(e,t),"permanently delete a subscription schedule"),{name:"cancel_subscription",description:"Cancel an active subscription. Prorates remaining period and stops future billing. Safe to call; subscriptions can be reactivated after cancellation. Always use this tool when the user asks to cancel a subscription. Must cancel before delete.",params:{resourceId:{type:"string",description:"Subscription resourceId"},cancelDateType:{type:"string",enum:["END_OF_CURRENT_PERIOD","END_OF_LAST_PERIOD","CUSTOM_DATE"],description:"When to end (default: END_OF_CURRENT_PERIOD)"},endDate:{type:"string",description:"Custom cancel date YYYY-MM-DD (only with CUSTOM_DATE)"},proratedAdjustmentLineText:{type:"string",description:'Label for proration line item (default: "Prorated adjustment")'}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"cancel stop a recurring subscription",isDestructive:!0,execute:async(e,t)=>V8(e.client,t.resourceId,{cancelDateType:t.cancelDateType,endDate:t.endDate,proratedAdjustmentLineText:t.proratedAdjustmentLineText})},Nt({name:"search_scheduled_transactions",description:"Search scheduled transactions (subscriptions / recurring invoices / journals / cash entries).",group:"subscriptions",fields:IT,defaults:CT,fetcher:W8,searchHint:"find scheduled recurring transactions subscriptions schedulers by type status interval contact"}),{name:"generate_vat_ledger",description:"Generate VAT/GST ledger report showing all tax transactions for the period.",params:{startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD)"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate VAT GST tax ledger report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>_q(e.client,{startDate:t.startDate,endDate:t.endDate})},{name:"generate_equity_movement",description:"Generate equity movement report (statement of changes in equity).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},compareWith:{type:"string",description:"Comparison period unit; compareCount sets how many",enum:["PREVIOUS_MONTHS","PREVIOUS_DAYS","PREVIOUS_QUARTERS","PREVIOUS_YEARS"]},compareCount:{type:"number",description:"Number of comparison periods"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"financial_reports",readOnly:!0,searchHint:"generate equity movement statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>wq(e.client,t)},{name:"generate_bank_balance_summary",description:"Generate bank balance summary report: snapshot of all bank account balances at a point in time.",params:{primarySnapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["primarySnapshotDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank account balance summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>vq(e.client,{primarySnapshotDate:t.primarySnapshotDate,currencyCode:t.currencyCode})},{name:"generate_bank_reconciliation_summary",description:"Generate bank reconciliation summary for a specific bank account. Essential for month-end close; call this for each in-scope bank account for the current entity and reporting period. Use for bank recon status, unreconciled items count, or reconciliation summaries.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Sq(e.client,t)},{name:"generate_bank_reconciliation_details",description:"Generate detailed bank reconciliation report showing matched/unmatched items.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},filter:{type:"object",description:"Report filter. valueDate is required.",properties:{valueDate:{type:"object",description:"Report window.",properties:{range:{type:"array",items:{type:"string"},description:"Inclusive [from, to], YYYY-MM-DD. The only accepted operator."}},required:["range"]},reconciliationStatus:{type:"string",description:"Reconciliation status (no published enum)."}},required:["valueDate"]},currencyCode:{type:"string",description:"Currency code"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate","filter"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation detailed report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Dq(e.client,t)},{name:"generate_fixed_assets_summary",description:"Generate fixed assets summary report grouped by account, type, category, or status.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["ACCOUNT","TYPE","CATEGORY","STATUS"],description:"Grouping dimension"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate","groupBy"],group:"register_reports",readOnly:!0,searchHint:"generate fixed asset summary depreciation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Rq(e.client,t)},{name:"generate_fixed_assets_reconciliation_summary",description:"Generate fixed assets reconciliation summary: reconciles asset register with general ledger.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate fixed asset reconciliation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Tq(e.client,t)},{name:"generate_deferrals_summary",description:"Generate the deferrals roll-forward for a period: deferral amount, opening remaining, amortized in period, closing remaining. Sections never mix categories (prepaid vs deferred revenue).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["CATEGORY","TYPE","ACCOUNT","STATUS"],description:"Default CATEGORY"},filter:G0r,currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate deferrals summary prepaid roll-forward amortized in period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>xq(e.client,t)},{name:"generate_deferrals_reconciliation_summary",description:"Generate the deferrals reconciliation: does the deferral register agree with the general ledger, per deferral account and per category. A difference usually means a line on the account not yet deferred.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Deferral account ids from search_deferral_accounts (max 500). Omit for all."},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate deferrals reconciliation prepaid register agree general ledger",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>kq(e.client,t)},{name:"generate_leases_summary",description:"Generate the lease register (the IFRS 16 lease note) for a period: opening liability, additions, interest, payments, terminations, closing, current and non-current, right-of-use asset, grouped by type, status or account. The maturity analysis is a sheet of the download_export leases-register file.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["TYPE","STATUS","ACCOUNT"],description:"Grouping dimension (default TYPE)"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate lease register IFRS 16 note lease liability roll-forward",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>VUe(e.client,t)},{name:"generate_leases_reconciliation_summary",description:"Reconcile the lease register to the general ledger per lease account, counting scheduled rent as debits to the current lease liability. A liability difference almost always means a rent bill coded elsewhere, posted in another month, or not booked.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Lease account resourceIds (max 500). Default: all lease accounts."},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate lease register vs general ledger reconciliation rent coding",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>WUe(e.client,t)},wO("generate_loans_summary","loans-summary","Borrowings note: per loan opening balance, drawdowns, repayments, interest, closing balance, current and non-current portion and accrued interest, grouped by type, status, account or lender. Positions are the register's; movements read the ledger, so an unrecorded repayment shows here.","generate loans summary borrowings note by lender type"),wO("generate_loans_roll_forward","loans-roll-forward","Loan roll-forward over a period: opening + drawdowns + repayments + interest + fees + non-cash = closing, tying to the balance sheet. Drawdowns and repayments are the user's own postings, so a missing repayment shows as a gap.","generate loans roll forward movement borrowings"),wO("generate_loans_related_party","loans-related-party","Related-party loan balances by contact: loans of type DIRECTOR, SHAREHOLDER, RELATED_PARTY and INTERCOMPANY, for the audit.","generate related party director shareholder loans balances audit"),wO("generate_loans_interest","loans-interest","Interest cost per loan for the period: interest, interest added to principal, interest to an asset, fees amortized and total finance cost.","generate loan interest cost finance cost per loan"),wO("generate_loans_maturity_analysis","loans-maturity-analysis","Liquidity note as at the end date: per term loan the undiscounted installments still due within one year, one to two, two to five and over five years, plus future interest and principal outstanding. On-demand balances fall within one year.","generate loan maturity analysis liquidity undiscounted installments buckets"),{name:"generate_loans_reconciliation_summary",description:"Loan register vs general ledger per account, in two groups: loan liability accounts and unamortized transaction cost accounts. The register side includes what the user is expected to post, so a non-zero difference means a missed, late, partial or mis-coded installment: name the account and amount and check that month. Debit minus credit, so liabilities read negative.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Loan account resourceIds (max 500); omit for all"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate loan reconciliation register vs ledger month end difference",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Nx(e.client,"loans-recon-summary",t)},q4("generate_aged_receivables_summary","receivables","summary"),q4("generate_aged_payables_summary","payables","summary"),{name:"get_ledger_highlights",description:"Get ledger highlights, summary metadata about the org general ledger: transaction counts by type, date range, active accounts, active currencies, and cross-currency detection. No parameters needed.",params:{},required:[],group:"operational_reports",readOnly:!0,searchHint:"get ledger highlights key metrics for period",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>Oq(e.client)},br("list_contact_groups","List contact groups with their associated contacts. Used to segment customers/suppliers.","contact_groups",(e,t,r)=>X8(e,{limit:r,offset:t}),"list contact groups customer supplier categories"),ni("get_contact_group","Get contact group details including all associated contacts.","contact_groups",(e,t)=>Z8(e,t),"get contact group details members"),Nt({name:"search_contact_groups",description:"Search contact groups.",group:"contact_groups",fields:ax,defaults:cx,fetcher:eW,searchHint:"find contact groups segments categories by name"}),{name:"create_contact_group",description:'Create a new contact group for segmenting contacts (e.g., "VIP Customers", "Government", "Overdue > 90 Days").',params:{name:{type:"string",description:"Group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to add to the group"}},required:["name"],group:"contact_groups",readOnly:!1,searchHint:"create new contact group category",execute:async(e,t)=>tW(e.client,{name:t.name,contactResourceIds:t.contactResourceIds})},{name:"update_contact_group",description:"Update a contact group name or members. Membership replaces the existing set.",params:{resourceId:{type:"string",description:"Contact group resourceId"},name:{type:"string",description:"New group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to set as group members, max 50 (replaces existing). Sent as associatedContactResourceIds."}},required:["resourceId"],group:"contact_groups",readOnly:!1,isDestructive:!0,searchHint:"update contact group name details",execute:async(e,t)=>rW(e.client,t.resourceId,{name:t.name,contactResourceIds:t.contactResourceIds})},Ur("delete_contact_group","Delete a contact group. Does not delete the contacts themselves.","contact_groups",(e,t)=>nW(e,t),"permanently delete a contact group"),br("list_custom_fields","List custom fields defined for the organization. Custom fields add extra data to invoices, bills, credit notes, and payments.","custom_fields",(e,t,r)=>lW(e,{limit:r,offset:t}),"list custom fields metadata on transactions"),{name:"get_custom_field",description:"Get a custom field by resourceId. Returns full definition including appliesTo flags and list options.",params:{resourceId:{type:"string",description:"Custom field resourceId"}},required:["resourceId"],group:"custom_fields",readOnly:!0,searchHint:"get custom field definition details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>oO(e.client,t.resourceId)},Nt({name:"search_custom_fields",description:"Search custom fields.",group:"custom_fields",fields:ox,defaults:sx,fetcher:uW,searchHint:"find custom fields user-defined attributes by name data type"}),{name:"create_custom_field",description:`Create a new custom field. Custom fields appear on transactions (invoices, bills, credit notes, payments).
803
804
  - appliesTo controls which transaction types show this field. Omit it and it shows on none.
804
805
  - printOnDocuments controls whether the field appears on PDFs.`,params:{name:{type:"string",description:'Field name (e.g., "PO Number", "Cost Center")'},description:{type:"string",description:"Field description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents (default false)"},appliesTo:{type:"object",description:"Which transaction types: { invoices: true, bills: true, customerCredits: true, supplierCredits: true, payments: true }"},format:Qct},required:["name"],group:"custom_fields",readOnly:!1,searchHint:"create new custom field for transactions",execute:async(e,t)=>dW(e.client,{...t,printOnDocuments:t.printOnDocuments??!1})},{name:"update_custom_field",description:"Update a custom field definition. Omitted fields keep their current values.",params:{resourceId:{type:"string",description:"Custom field resourceId"},name:{type:"string",description:"New field name"},description:{type:"string",description:"New description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents"},appliesTo:{type:"object",description:"Which transaction types: { invoices, bills, customerCredits, supplierCredits, payments }"},format:Qct},required:["resourceId"],group:"custom_fields",readOnly:!1,isDestructive:!0,searchHint:"update custom field name type settings",execute:async(e,t)=>{let{resourceId:r,...n}=t;return fW(e.client,r,n)}},Ur("delete_custom_field","Delete a custom field. Removes it from all future transactions.","custom_fields",(e,t)=>pW(e,t),"permanently delete a custom field definition"),br("list_withholding_codes","List withholding codes (BIR ATCs, PH): code, rate, type, description. A row feeds a bill or supplier credit note line's withholdingTax (EWT) and, by its resourceId, a Withholding Tax Certificate (BIR Form 2307, CWT) allocation. limit max 100.","tax_profiles",(e,t,r,n,i)=>KP(e,{offset:t,limit:r},i),"withholding codes WHT ATC EWT CWT expanded creditable withholding tax BIR 2307",{filters:{countryCode:{type:"string",description:"e.g. PH"},code:{type:"string",description:'Contains match; codes have a space ("WC 158"; "WC158" matches nothing)'},type:{type:"string",enum:["corp","ind","final","wvat"]}}}),Nt({name:"search_tax_profiles",description:"Search tax profiles. Use appliesToSale / appliesToPurchase filters to scope by transaction type.",group:"tax_profiles",fields:tx,defaults:rx,fetcher:qI,searchHint:"find tax profiles GST VAT WHT by name tax type code applicability sale purchase"}),Nt({name:"search_filing_submissions",description:"Search tax return filings (PH BIR 2550Q, SG GST F5): period, due date, tax due, status.",group:"tax_profiles",fields:ST,defaults:DT,fetcher:e8,searchHint:"BIR GST filings"}),ni("get_tax_profile","Get full tax profile details including tax rate, type code, and status.","tax_profiles",(e,t)=>iD(e,t),"get tax profile details rate code"),{name:"update_tax_profile",description:"Update an existing tax profile. Omitted fields keep their current values; status is not updatable.",params:{resourceId:{type:"string",description:"Tax profile resourceId"},name:WAe,description:{type:"string"},vatValue:{type:"number",description:"Tax rate % (0-100)"},taxType:{type:"string",description:"Tax type code (list_tax_types)"}},required:["resourceId"],group:"tax_profiles",readOnly:!1,isDestructive:!0,searchHint:"update tax profile name rate details",execute:async(e,t)=>WP(e.client,t.resourceId,{name:t.name,description:t.description,vatValue:t.vatValue,taxType:t.taxType})},{name:"create_claim_type",description:"Create a claim type (expense category for employee claims). Dedups by name. expenseAccountResourceId is server-required.",params:{name:{type:"string",description:"Claim type name (unique per org)"},expenseAccountResourceId:{type:"string",description:'Expense CoA resourceId, REQUIRED server-side (search_accounts; accountType is a display label e.g. "Operating Expense")'},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Magic OCR classifier defaults (JSON string)"}},required:["name"],group:"claim_types",readOnly:!1,searchHint:"create claim type expense category",execute:async(e,t)=>{let r=t.name,n=await QM(e.client,r);return n?{_guard:"duplicate_skipped",message:`Claim type "${r}" already exists.`,existing:n}:iM(e.client,{name:r,expenseAccountResourceId:t.expenseAccountResourceId,taxProfileResourceId:t.taxProfileResourceId,classifierConfig:t.classifierConfig})}},{name:"update_claim_type",description:"Update a claim type. Omitted fields unchanged; clearFields NULLs optional fields.",params:{resourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"New name"},expenseAccountResourceId:{type:"string",description:"Default expense CoA resourceId"},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Classifier defaults (JSON string)"},clearFields:{type:"array",items:{type:"string",enum:[...aD]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_types",readOnly:!1,isDestructive:!0,searchHint:"update claim type",execute:async(e,t)=>oM(e.client,t.resourceId,{name:t.name,expenseAccountResourceId:t.expenseAccountResourceId,taxProfileResourceId:t.taxProfileResourceId,classifierConfig:t.classifierConfig,...bg(t.clearFields,aD)})},Nt({name:"search_claim_types",description:"Search claim types.",group:"claim_types",fields:$T,defaults:qT,fetcher:YI,searchHint:"find claim types by name default expense account tax profile"}),br("list_claim_types","List claim types (alphabetical).","claim_types",(e,t,r)=>rM(e,{offset:t,limit:r}),"list claim types"),ni("get_claim_type","Get a claim type incl. nested expense account + tax profile.","claim_types",(e,t)=>nM(e,t),"get claim type details"),Ur("delete_claim_type","Soft-delete a claim type (name becomes reusable).","claim_types",(e,t)=>sM(e,t),"delete claim type"),{name:"create_claim_profile",description:"Create a claim profile (per-employee policy bundle: approver, limits, visible types, balance account). Dedups by name. taxMode EXCLUSIVE is rejected.",params:{name:{type:"string",description:"Profile name (unique per org)"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (free-text vendors always allowed)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (null = no restriction)"},minClaimAmount:{type:"number",description:"Min claim total (<= max)"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap (requires perPeriod)"},perPeriod:{type:"string",enum:[...cD],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Per-employee liability (CURRENT_LIABILITY) CoA resourceId; required for reimbursement conversion"},taxMode:{type:"string",enum:[...mZ],description:"Tax policy (NO_TAX or INCLUSIVE)"}},required:["name"],group:"claim_profiles",readOnly:!1,searchHint:"create claim profile policy approver limits",execute:async(e,t)=>{let r=t.name,n=await PM(e.client,r);return n?{_guard:"duplicate_skipped",message:`Claim profile "${r}" already exists.`,existing:n}:uM(e.client,{name:r,approverUserResourceId:t.approverUserResourceId,visibleClaimTypeIds:t.visibleClaimTypeIds,visibleTaxProfileIds:t.visibleTaxProfileIds,visibleClassifierIds:t.visibleClassifierIds,visibleVendorResourceIds:t.visibleVendorResourceIds,allowedCurrencies:t.allowedCurrencies,minClaimAmount:t.minClaimAmount,maxClaimAmount:t.maxClaimAmount,maxPerPeriodAmount:t.maxPerPeriodAmount,perPeriod:t.perPeriod,employeeBalanceAccountResourceId:t.employeeBalanceAccountResourceId,taxMode:t.taxMode})}},{name:"update_claim_profile",description:"Update a claim profile. Omitted fields unchanged; clearFields NULLs optional fields. Balance account cannot change while an employee has a non-zero balance.",params:{resourceId:{type:"string",description:"Claim profile resourceId"},name:{type:"string",description:"New name"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs (replaces)"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs (replaces)"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs (replaces)"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (replaces)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (replaces)"},minClaimAmount:{type:"number",description:"Min claim total"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap"},perPeriod:{type:"string",enum:[...cD],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Employee balance CoA resourceId"},taxMode:{type:"string",enum:[...mZ],description:"Tax policy (NO_TAX or INCLUSIVE)"},clearFields:{type:"array",items:{type:"string",enum:[...lD]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_profiles",readOnly:!1,isDestructive:!0,searchHint:"update claim profile policy limits",execute:async(e,t)=>dM(e.client,t.resourceId,{name:t.name,approverUserResourceId:t.approverUserResourceId,visibleClaimTypeIds:t.visibleClaimTypeIds,visibleTaxProfileIds:t.visibleTaxProfileIds,visibleClassifierIds:t.visibleClassifierIds,visibleVendorResourceIds:t.visibleVendorResourceIds,allowedCurrencies:t.allowedCurrencies,minClaimAmount:t.minClaimAmount,maxClaimAmount:t.maxClaimAmount,maxPerPeriodAmount:t.maxPerPeriodAmount,perPeriod:t.perPeriod,employeeBalanceAccountResourceId:t.employeeBalanceAccountResourceId,taxMode:t.taxMode,...bg(t.clearFields,lD)})},Nt({name:"search_claim_profiles",description:"Search claim profiles.",group:"claim_profiles",fields:jT,defaults:YT,fetcher:HI,searchHint:"find claim profiles by name approver default limits balance account"}),br("list_claim_profiles","List claim profiles (alphabetical).","claim_profiles",(e,t,r)=>cM(e,{offset:t,limit:r}),"list claim profiles"),ni("get_claim_profile","Get a claim profile incl. nested balance account.","claim_profiles",(e,t)=>lM(e,t),"get claim profile details"),Ur("delete_claim_profile","Soft-delete a claim profile.","claim_profiles",(e,t)=>fM(e,t),"delete claim profile"),{name:"create_posting_rule",description:"Create a posting rule (how approved claims group into journals at conversion). outerAxis + innerAxis + lineDescriptionTemplate required. Dedups by name.",params:{name:{type:"string",description:"Rule name (unique per org)"},outerAxis:{type:"string",enum:[...dD],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...fD],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:'Handlebars line template, e.g. "{employeeName} - {claimType}"'},journalReferenceTemplate:{type:"string",description:"Optional Handlebars journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank (Cash/Bank) account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["name","outerAxis","innerAxis","lineDescriptionTemplate"],group:"posting_rules",readOnly:!1,searchHint:"create posting rule claim conversion grouping",execute:async(e,t)=>{let r=t.name,n=await MM(e.client,r);return n?{_guard:"duplicate_skipped",message:`Posting rule "${r}" already exists.`,existing:n}:mM(e.client,{name:r,outerAxis:t.outerAxis,innerAxis:t.innerAxis,lineDescriptionTemplate:t.lineDescriptionTemplate,journalReferenceTemplate:t.journalReferenceTemplate,defaultBankAccountResourceId:t.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:t.defaultIncludeReimbursementPayout,isDefault:t.isDefault})}},{name:"update_posting_rule",description:"Update a posting rule. Omitted fields unchanged.",params:{resourceId:{type:"string",description:"Posting rule resourceId"},name:{type:"string",description:"New name"},outerAxis:{type:"string",enum:[...dD],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...fD],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:"Handlebars line template"},journalReferenceTemplate:{type:"string",description:"Journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["resourceId"],group:"posting_rules",readOnly:!1,isDestructive:!0,searchHint:"update posting rule",execute:async(e,t)=>AM(e.client,t.resourceId,{name:t.name,outerAxis:t.outerAxis,innerAxis:t.innerAxis,lineDescriptionTemplate:t.lineDescriptionTemplate,journalReferenceTemplate:t.journalReferenceTemplate,defaultBankAccountResourceId:t.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:t.defaultIncludeReimbursementPayout,isDefault:t.isDefault})},Nt({name:"search_posting_rules",description:"Search posting rules.",group:"posting_rules",fields:HT,defaults:zT,fetcher:zI,searchHint:"find posting rules by name axis default bank reimbursement"}),br("list_posting_rules","List posting rules (alphabetical).","posting_rules",(e,t,r)=>pM(e,{offset:t,limit:r}),"list posting rules"),ni("get_posting_rule","Get a posting rule.","posting_rules",(e,t)=>hM(e,t),"get posting rule details"),Ur("delete_posting_rule","Delete a posting rule. The org default cannot be deleted while default (set another default first).","posting_rules",(e,t)=>gM(e,t),"delete posting rule"),Nt({name:"search_claims",description:'Search/list employee-expense claims. Status: DRAFT|SUBMITTED|APPROVED|CONVERTED|REJECTED|CANCELLED (CONVERTED = "Processed"). Claims are born via create_claim, attachment, or conversion (no bare list; use search).',group:"claims",fields:QT,defaults:PT,fetcher:Z$,searchHint:"find employee expense claims by status employee contact reference date amount"}),ni("get_claim","Get a claim incl. line items, employee, amounts, status.","claims",(e,t)=>FT(e,t),"get claim details line items"),{name:"create_claim",description:"Create an employee-expense claim directly (bare create, no attachment). Vendor is EITHER contactResourceId OR vendorName, never both. saveAsDraft defaults to true (lands DRAFT with relaxed line validation); set false to validate + submit in one call (lands SUBMITTED). reference is REQUIRED when submitting (saveAsDraft=false): omitting it returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT; a DRAFT saves without one.",params:{valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},saveAsDraft:{type:"boolean",description:"true (default) creates DRAFT; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId the claim is filed for"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},reference:{type:"string",description:"User reference"},autoReference:cu,currencySymbol:{type:"string",description:"Currency symbol override"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:{type:"array",items:{type:"string"},description:"Header-level tags"},internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId (defaults to org default)"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Tn,claimItems:Jct},required:["valueDate","currencyCode"],group:"claims",readOnly:!1,searchHint:"create new employee expense claim draft vendor employee line items submit",execute:async(e,t)=>e2(e.client,{valueDate:t.valueDate,currencyCode:t.currencyCode,saveAsDraft:t.saveAsDraft,employeeResourceId:t.employeeResourceId,contactResourceId:t.contactResourceId,vendorName:t.vendorName,reference:await gU(e.client,"CLAIM",t.reference,t.autoReference),currencySymbol:t.currencySymbol,taxInclusion:t.taxInclusion,tags:t.tags,internalNotes:t.internalNotes,claimProfileResourceId:t.claimProfileResourceId,approverUserResourceId:t.approverUserResourceId,customFields:t.customFields,claimItems:t.claimItems})},{name:"update_claim",description:"Update a DRAFT claim (partial: omitted fields unchanged). claimItems non-empty REPLACES all lines, [] clears. Set saveAsDraft=false to validate + submit in one call: reference is REQUIRED at submit (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT); a DRAFT save needs none. Only DRAFT claims are editable.",params:{resourceId:{type:"string",description:"Claim resourceId"},saveAsDraft:{type:"boolean",description:"true (default) keeps editing; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},reference:{type:"string",description:"User reference"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:Yo,internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Tn,claimItems:Jct},required:["resourceId"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"edit draft claim line items employee reference submit",execute:async(e,t)=>{let r=t.resourceId,n=Xn(t.tags),i=n&&await Xi("claim",r,()=>FT(e.client,r));return t2(e.client,r,{saveAsDraft:t.saveAsDraft,employeeResourceId:t.employeeResourceId,contactResourceId:t.contactResourceId,vendorName:t.vendorName,valueDate:t.valueDate,reference:t.reference,currencyCode:t.currencyCode,taxInclusion:t.taxInclusion,tags:n&&ui(i?.tags,n),internalNotes:t.internalNotes,claimProfileResourceId:t.claimProfileResourceId,approverUserResourceId:t.approverUserResourceId,customFields:t.customFields,claimItems:t.claimItems})}},Ur("delete_claim","Delete a claim. Only DRAFT / REJECTED / CANCELLED claims are deletable (else 422).","claims",(e,t)=>r2(e,t),"delete remove claim record"),{name:"delete_claim_attachment",description:"Remove one attachment (receipt) from a claim. Returns the updated claim.",params:{resourceId:{type:"string",description:"Claim resourceId"},attachmentResourceId:{type:"string",description:"Attachment resourceId"}},required:["resourceId","attachmentResourceId"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"remove delete claim attachment receipt",execute:async(e,t)=>n2(e.client,t.resourceId,t.attachmentResourceId)},ZAe("submit_claim","Submit a DRAFT claim for approval (DRAFT \u2192 SUBMITTED). Server enforces the transition. The claim must carry a reference; a referenceless DRAFT returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (set it via update_claim first).","claims",(e,t)=>i2(e,t),{destructive:!0,searchHint:"submit draft claim for approval"}),ZAe("approve_claim","Approve a SUBMITTED claim (SUBMITTED \u2192 APPROVED). Approved claims become convertible to journals.","claims",(e,t)=>o2(e,t),{destructive:!0,searchHint:"approve submitted claim"}),{name:"reject_claim",description:"Reject a SUBMITTED/APPROVED claim with a reason (\u2192 REJECTED).",params:{resourceId:{type:"string",description:"Claim resourceId"},rejectionReason:{type:"string",description:"Rejection reason (1-1000 chars)"}},required:["resourceId","rejectionReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"reject claim with reason",execute:async(e,t)=>s2(e.client,t.resourceId,t.rejectionReason)},{name:"cancel_claim",description:"Cancel a DRAFT/SUBMITTED claim with a reason (\u2192 CANCELLED).",params:{resourceId:{type:"string",description:"Claim resourceId"},cancellationReason:{type:"string",description:"Cancellation reason (1-1000 chars)"}},required:["resourceId","cancellationReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"cancel claim with reason",execute:async(e,t)=>a2(e.client,t.resourceId,t.cancellationReason)},ZAe("unpost_claim","Unpost a CONVERTED claim: voids its journal, back to APPROVED. Re-unpost: 200 no-op. Aggregated claims unpost together. Ignores payouts (employee balance can go negative).","claims",(e,t)=>c2(e,t),{destructive:!0,searchHint:"unpost reverse converted claim conversion"}),{name:"bulk_submit_claims",description:`Bulk-submit DRAFT claims (ASYNC). Returns the final job if it finished, else a job handle {jobId,...} to poll with search_background_jobs by jobId for per-item results. ${rs} Max 500 ids. Each claim must have a reference; referenceless claims fail per-item with CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (check the job result).`,params:{resourceIds:CO},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk submit many claims async job",backgroundJob:Pn("Submit","claim","claims","resourceIds"),execute:async(e,t)=>l2(e.client,t.resourceIds)},{name:"bulk_approve_claims",description:`Bulk-approve SUBMITTED claims (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:CO},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk approve many claims async job",backgroundJob:Pn("Approve","claim","claims","resourceIds"),execute:async(e,t)=>u2(e.client,t.resourceIds)},{name:"bulk_reject_claims",description:`Bulk-reject claims with one shared reason (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:CO,rejectionReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","rejectionReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk reject many claims async job reason",backgroundJob:Pn("Reject","claim","claims","resourceIds"),execute:async(e,t)=>f2(e.client,t.resourceIds,t.rejectionReason)},{name:"bulk_cancel_claims",description:`Bulk-cancel claims with one shared reason (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:CO,cancellationReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","cancellationReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk cancel many claims async job reason",backgroundJob:Pn("Cancel","claim","claims","resourceIds"),execute:async(e,t)=>p2(e.client,t.resourceIds,t.cancellationReason)},{name:"bulk_delete_claims",description:`Bulk-delete claims (ASYNC; only DRAFT/REJECTED/CANCELLED are deletable). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:CO},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk delete many claims async job",backgroundJob:Pn("Delete","claim","claims","resourceIds"),execute:async(e,t)=>d2(e.client,t.resourceIds)},{name:"get_claim_tracking_tags",description:"List the tracking-tag values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim tracking tags picker",execute:async e=>h2(e.client)},{name:"get_claim_custom_field_values",description:"List the custom-field values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim custom field values picker",execute:async e=>m2(e.client)},{name:"preview_claims_conversion",description:"Preview the journals an APPROVED claim batch would produce at conversion, no write. Returns expenseSubTotal, previewJournals, and reimbursement DCE counts; non-APPROVED claims come back under erroredClaims (check it is empty before converting). Needs a default posting rule or an explicit postingRuleResourceId.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},payoutFlow:{type:"string",enum:[...ZB],description:"POST (journals only) or POST_AND_RECORD (+ books-only reimbursement DCE)"},includeReimbursementPayout:{type:"boolean",description:"Include per-employee reimbursement DCE lines"},bankAccountResourceId:{type:"string",description:"Reimbursement bank account for preview validation"}},required:["claimResourceIds"],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview claim conversion journals before posting",execute:async(e,t)=>WV(e.client,{claimResourceIds:t.claimResourceIds,postingRuleResourceId:t.postingRuleResourceId,payoutFlow:t.payoutFlow,includeReimbursementPayout:t.includeReimbursementPayout,bankAccountResourceId:t.bankAccountResourceId})},{name:"convert_claims_to_journal",description:"Convert an APPROVED claim batch into journals (atomic write). valueDate (YYYY-MM-DD) required. Preview first and confirm erroredClaims is empty. idempotencyKey is auto-generated for safe retries (pass your own to dedup across calls). includeReimbursementPayout adds a books-only reimbursement DCE; real-money disburse is intentionally not exposed.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},valueDate:{type:"string",description:"Journal value date (YYYY-MM-DD)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},includeReimbursementPayout:{type:"boolean",description:"Create books-only reimbursement DCEs"},bankAccountResourceIdOverride:{type:"string",description:"Override the rule default reimbursement bank account"},contactResourceId:{type:"string",description:"Clearing contact for the reimbursement DCE cash-out"},idempotencyKey:{type:"string",description:"Optional retry-dedup token (must not start with CONV: / CONV-); auto-generated if omitted"}},required:["claimResourceIds","valueDate"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"convert post approved claims to journal entries",execute:async(e,t)=>KV(e.client,{claimResourceIds:t.claimResourceIds,valueDate:t.valueDate,postingRuleResourceId:t.postingRuleResourceId,includeReimbursementPayout:t.includeReimbursementPayout,bankAccountResourceIdOverride:t.bankAccountResourceIdOverride,contactResourceId:t.contactResourceId,idempotencyKey:t.idempotencyKey||P0r()})},{name:"record_employee_payout",description:"Record a books-only employee payout (reimbursement or advance): a DCE, no real-money transfer. amount, paymentAccountResourceId and valueDate are required; reference auto-generated if omitted.",params:{employeeResourceId:{type:"string",description:"Employee resourceId"},amount:{type:"number",description:"Payout amount (> 0)"},paymentAccountResourceId:{type:"string",description:"Bank/cash account the DCE credits"},valueDate:{type:"string",description:"Value date (YYYY-MM-DD)"},payoutFor:{type:"string",enum:[...rat],description:"Classification (null \u2192 ADVANCE)"},currencyCode:{type:"string",description:"Settle currency (ISO 4217; omit \u2192 payment account currency)"},reference:{type:"string",description:"Payout reference (auto-generated if omitted)"},description:{type:"string",description:"Line description on the DCE"},internalNotes:{type:"string",description:"Internal notes"}},required:["employeeResourceId","amount","paymentAccountResourceId","valueDate"],group:"claim_processing",readOnly:!1,searchHint:"record employee reimbursement advance payout books-only DCE",execute:async(e,t)=>XV(e.client,{employeeResourceId:t.employeeResourceId,amount:t.amount,paymentAccountResourceId:t.paymentAccountResourceId,valueDate:t.valueDate,payoutFor:t.payoutFor,currencyCode:t.currencyCode,reference:t.reference||Qo("EP"),description:t.description,internalNotes:t.internalNotes})},Nt({name:"search_employee_payouts",description:"Search recorded employee payouts (reimbursements + advances).",group:"claim_processing",fields:MT,defaults:UT,fetcher:ZV,searchHint:"find employee payouts reimbursements advances by employee reference status type"}),{name:"add_employee",description:"Create an employee (expense-claim member). claimProfileResourceId is REQUIRED (carries the employee balance account; the org default is NOT auto-applied). userResourceId is optional: omit for an offline employee with no login. Dedups by email.",params:{name:{type:"string",description:"Employee display name"},userResourceId:{type:"string",description:"Login user's resourceId to link: the userResourceId field from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND). Optional"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId, REQUIRED (carries the employee balance account; org default NOT auto-applied \u2192 EMPLOYEE_CLAIM_PROFILE_REQUIRED). search_claim_profiles"},email:{type:"string",description:"Work email (per-org unique)"},phone:{type:"string",description:"Phone (per-org unique)"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},active:{type:"boolean",description:"Active flag (default true)"},employmentType:{type:"string",enum:[...Ig],description:"Employment classification"}},required:["name","claimProfileResourceId"],group:"employees",readOnly:!1,searchHint:"create add employee claim member bind user",execute:async(e,t)=>{let r=t.email;if(r){let n=await UM(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Employee with email "${r}" already exists.`,existing:n}}return wM(e.client,{name:t.name,userResourceId:t.userResourceId,claimProfileResourceId:t.claimProfileResourceId,email:r,phone:t.phone,managerEmployeeResourceId:t.managerEmployeeResourceId,active:t.active,employmentType:t.employmentType})}},{name:"update_employee",description:"Update an employee (partial; omitted or null = no change). Clear only via clearFields (userResourceId = unlink). To ARCHIVE, set active=false (reversible, prefer over delete_employee).",params:{resourceId:{type:"string",description:"Employee resourceId"},name:{type:"string",description:"New name"},email:{type:"string",description:"Work email"},phone:{type:"string",description:"Phone"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},active:{type:"boolean",description:"Active flag, set false to archive"},employmentType:{type:"string",enum:[...Ig],description:"Employment classification"},userResourceId:{type:"string",description:"Login user to link/relink (search_org_users userResourceId)"},clearFields:{type:"array",items:{type:"string",enum:[...IZ]},description:"Fields to clear"}},required:["resourceId"],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"update edit archive employee active claim profile",execute:async(e,t)=>vM(e.client,t.resourceId,{name:t.name,email:t.email,phone:t.phone,managerEmployeeResourceId:t.managerEmployeeResourceId,claimProfileResourceId:t.claimProfileResourceId,active:t.active,employmentType:t.employmentType,userResourceId:t.userResourceId,clearFields:t.clearFields})},Nt({name:"search_employees",description:"Search employees by name, email, phone, manager, claim profile, active, currency.",group:"employees",fields:JT,defaults:GT,fetcher:GI,searchHint:"find employees claim members by name email manager profile active"}),Nt({name:"search_employee_balances",description:"Search the employee-balance directory (per-currency reimbursement balances owed).",group:"employees",fields:VT,defaults:WT,fetcher:CM,searchHint:"employee reimbursement balances owed by currency employment type"}),ni("get_employee","Get an employee incl. claim profile + user binding.","employees",(e,t)=>_M(e,t),"get employee details binding balance"),Ur("delete_employee","Delete an employee (server validates they are settled). Prefer update_employee active=false to archive reversibly.","employees",(e,t)=>SM(e,t),"delete remove employee"),{name:"bind_employee_user",description:"Bind a login user to an OFFLINE employee (no user bound yet, e.g. imported without a binding email). Refused once bound: relink or unlink via update_employee.",params:{resourceId:{type:"string",description:"Employee resourceId"},userResourceId:{type:"string",description:"Login user's resourceId: the userResourceId FIELD from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND)"}},required:["resourceId","userResourceId"],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bind link login user to employee",execute:async(e,t)=>DM(e.client,t.resourceId,t.userResourceId)},{name:"preprocess_employees_file",description:"Preprocess an uploaded employee import sheet (CSV/XLSX); returns a parsed row preview to review before import_employees. Provide the sheet fileUrl.",params:{fileUrl:{type:"string",description:"URL of the uploaded employee sheet"},fileName:{type:"string",description:"Display file name"},fileType:{type:"string",enum:["CSV","EML","HEIC","JPEG","JPG","PDF","PNG","TEXT","XLS","XLSX"],description:"File type (use CSV / XLS / XLSX for employee sheets)"}},required:["fileUrl"],group:"employees",readOnly:!0,isConcurrencySafe:!0,searchHint:"preprocess preview employee import sheet csv xlsx",execute:async(e,t)=>RM(e.client,{fileUrl:t.fileUrl,fileName:t.fileName,fileType:t.fileType})},{name:"import_employees",description:`Bulk create/update/delete employees (max 100 rows per array). Rows validate synchronously (422 row errors), then an async job queues: the result is the final job if it finished, else poll search_background_jobs by jobId. ${rs} Create rows need name + claimProfileResourceId (userResourceId optional).`,params:{create:{type:"array",description:"Create rows",items:{type:"object",properties:{name:{type:"string"},email:{type:"string"},userResourceId:{type:"string"},claimProfileResourceId:{type:"string"},employmentType:{type:"string",enum:[...Ig]},managerEmployeeResourceId:{type:"string"},active:{type:"boolean"}},required:["name"]}},update:{type:"array",description:"Update rows",items:{type:"object",properties:{employeeResourceId:{type:"string"},name:{type:"string"},email:{type:"string"},employmentType:{type:"string",enum:[...Ig]},active:{type:"boolean"}},required:["employeeResourceId"]}},delete:{type:"array",description:"Delete rows",items:{type:"object",properties:{employeeResourceId:{type:"string"}},required:["employeeResourceId"]}}},required:[],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bulk import employees create update delete sheet async",backgroundJob:Pn("Import","employee change","employee changes","create","update","delete"),execute:async(e,t)=>TM(e.client,{create:t.create,update:t.update,delete:t.delete})},br("list_inventory_items","List inventory-tracked items with stock details, COGS accounts, and purchase/sale accounts.","inventory",(e,t,r)=>iW(e,{limit:r,offset:t}),"list inventory items stock levels quantities"),{name:"get_inventory_balance",description:"Get current inventory balance for a specific item: quantity on hand, average cost, base unit.",params:{itemResourceId:{type:"string",description:"Item resourceId"}},required:["itemResourceId"],group:"inventory",readOnly:!0,searchHint:"get inventory balance stock level for item",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>sW(e.client,t.itemResourceId)},{name:"list_inventory_balances",description:"List stock on hand, average cost and value per inventory item. One item: get_inventory_balance.",params:{status:{type:"string",enum:[...aW],description:"Default ALL"},...OO},required:[],group:"inventory",readOnly:!0,searchHint:"stock on hand all items",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>{let{limit:r,offset:n}=FO(t),i=t.status??"ALL";return lh((o,s)=>cW(e.client,i,{limit:s,offset:o}),r,n,100)}},{name:"create_inventory_item",description:"Create a new inventory-tracked item. Requires itemCode, name, unit, costingMethod (FIXED or WAC) and three account links. Use --input for full JSON body.",params:{itemCode:{type:"string",description:"Unique item code (SKU)"},name:{type:"string",description:"Item name"},unit:{type:"string",description:'Unit of measure, e.g. "pcs"'},costingMethod:{type:"string",enum:["FIXED","WAC"],description:"Costing method: FIXED or WAC"},cogsResourceId:{type:"string",description:"COGS account resourceId (Direct Costs type)"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId (Inventory type)"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},blockInsufficientDeductions:{type:"boolean",description:"Block transactions when insufficient stock (default: false)"}},required:["itemCode","name","unit","costingMethod","cogsResourceId","purchaseAccountResourceId","saleAccountResourceId"],group:"inventory",readOnly:!1,searchHint:"create new inventory tracked stock item",execute:async(e,t)=>oW(e.client,{itemCode:t.itemCode,name:t.name,unit:t.unit,costingMethod:t.costingMethod,cogsResourceId:t.cogsResourceId,purchaseAccountResourceId:t.purchaseAccountResourceId,saleAccountResourceId:t.saleAccountResourceId,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:t.blockInsufficientDeductions??!1})},Ur("delete_contact","Delete a contact. Cannot delete contacts with existing transactions.","contacts",(e,t)=>_P(e,t),"permanently delete a customer supplier contact"),Ur("delete_account","Delete a chart of accounts entry. Cannot delete accounts with existing transactions.","accounts",(e,t)=>qP(e,t),"permanently delete a chart of accounts entry"),ni("get_cash_transfer","Fetch a cash transfer by cashflow-transaction resourceId (search_cashflow_transactions) or the parentEntityResourceId create returns.","cash_transfers",(e,t)=>tV(e,t),"get cash transfer details between accounts"),RO("download_credit_note_pdf","customer credit note","customer_credit_notes",(e,t)=>oj(e,t)),{name:"get_transaction_summary",description:`Get a complete summary of any transaction: fetches the transaction, its attachments, and payment history in one call.
805
806
  Works for invoices, bills, customer credit notes, supplier credit notes, and journals. Invoices and bills carry payments, credit notes refunds, journals neither. A failed leg omits its keys and is named in 'partialFailures'.`,params:{transactionType:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note","journal"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["transactionType","resourceId"],group:"search",readOnly:!0,searchHint:"transaction summary attachments payments refunds",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=t.resourceId,n=V4[t.transactionType]??V4.journal,[i,o,s]=await Promise.allSettled([n.get(e.client,r),Ei(e.client,n.attachType,r),n.settlements?n.settlements(e.client,r):Promise.resolve(void 0)]);if(i.status==="rejected")throw i.reason;let a=p=>{let h=p.reason instanceof Error?p.reason.message:typeof p.reason=="string"?p.reason:(()=>{try{return JSON.stringify(p.reason)??"unknown error"}catch{return"unknown error"}})();return h.length>300?`${h.slice(0,297)}...`:h},c=[];o.status==="rejected"&&c.push(`attachments: ${a(o)}`),s.status==="rejected"&&c.push(`${n.settlementKey}: ${a(s)}`);let u=p=>Array.isArray(p)?p:Array.isArray(p?.data)?p.data:void 0,d=o.status==="fulfilled"?u(o.value):void 0,f=s.status==="fulfilled"?u(s.value):void 0;return{...c.length?{partialFailures:c}:{},transaction:i.value.data,...d?{attachments:d,attachmentCount:d.length}:{},...f?{[n.settlementKey]:f,[n.settlementCountKey]:f.length}:{}}}},{name:"bulk_finalize_drafts",description:"Finalize multiple draft transactions in one call. Attempts finalization for each item and returns per-item pass/fail results. Supports invoices, bills, and credit notes.",params:{items:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["type","resourceId"]},description:"Array of {type, resourceId} to finalize"}},required:["items"],group:"drafts",readOnly:!1,searchHint:"bulk finalize approve multiple draft transactions",isDestructive:!0,execute:async(e,t)=>{let r=t.items,n=[];for(let i of r){let o=oge.includes(i.type)?typeof i.resourceId!="string"||i.resourceId.trim()===""?"resourceId is required":void 0:`type must be one of ${oge.join(", ")}`;if(o){let s="btResourceId"in i||"btType"in i?" A validate_drafts result names them btType and btResourceId: map btType SALE to invoice, PURCHASE to bill, SALE_CREDIT_NOTE to customer_credit_note, PURCHASE_CREDIT_NOTE to supplier_credit_note, and btResourceId to resourceId.":"";n.push({...i,success:!1,error:`${o}.${s}`});continue}try{let s=await TO(e.client,i.type,i.resourceId,{});i.type==="invoice"?await yx(e.client,i.resourceId,s):i.type==="bill"?await JS(e.client,i.resourceId,s):i.type==="customer_credit_note"?await qx(e.client,i.resourceId,s):i.type==="supplier_credit_note"&&await Gx(e.client,i.resourceId,s),n.push({...i,success:!0})}catch(s){n.push({...i,success:!1,error:s instanceof Error?s.message:String(s)})}}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_invite_org_users",description:"Invite multiple users to the organization in one call. Accepts an array of user objects. Each user follows the same contract as invite_org_user. Returns per-user pass/fail results.",params:{users:{type:"array",items:{type:"object",properties:{email:{type:"string",description:"User email"},firstName:{type:"string",description:"First name"},lastName:{type:"string",description:"Last name"},userType:{type:"string",enum:[...Bg],description:"ADMIN = full access (moduleRoles ignored). CUSTOM_USER = per-module access via moduleRoles."},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",enum:[...lC]},roleCode:{type:"string",enum:[...Ng]}},required:["moduleName","roleCode"]},description:"Use when userType is CUSTOM_USER; ignored for ADMIN."}},required:["email","firstName","lastName","userType"]},description:"Array of users to invite"}},required:["users"],group:"org_users",readOnly:!1,openWorld:!0,searchHint:"bulk invite multiple users to organization",execute:async(e,t)=>{let r=t.users,n=[];for(let i of r)try{uf({userType:i.userType,moduleRoles:i.moduleRoles});let o=await Zw(e.client,i);n.push({email:i.email,success:!0,resourceId:o.data?.resourceId})}catch(o){n.push({email:i.email,success:!1,error:o instanceof Error?o.message:String(o)})}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_create_contacts",description:`Create multiple contacts in one call. Deduplicates against existing contacts (exact name match).
@@ -1079,7 +1080,7 @@ Dynamic Strings (usable in name, reference \u2014 any free text field):
1079
1080
  {{bankPayee}} Payer/payee name (e.g., Fruit Planet)
1080
1081
  {{bankDescription}} Transaction description (e.g., QR Payment)
1081
1082
  Strings are replaced with actual bank record values during reconciliation.`);co({parent:t,description:"List bank rules",columns:Iyt,label:"Fetching bank rules",title:"Bank Rules",fetch:(r,n)=>s8(r,n)}),t.command("get <resourceId>").description("Get a bank rule").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await rO(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(S("Name:"),o.data.name),console.log(S("Action:"),o.data.actionType),console.log(S("ID:"),o.data.resourceId);let s=o.data.searchFilter;if(s){let a=typeof s.raw=="string"?s.raw:"";console.log(S("Condition:"),a!==""?a:U("(no one-line form)")),console.log(S("Matches:"),s.parsed?JSON.stringify(s.parsed):U("(not returned)"))}else console.log(S("Condition:"),Z("none \u2014 never suggested by auto-reconciliation"))})(n)),Fe({parent:t,fields:dx,defaults:fx,fetcher:a8,columns:Iyt,label:"Searching bank rules",positionalArg:"name",positionalFilter:r=>({name:{contains:r}})}),t.command("create").description("Create a bank reconciliation rule").option("--jot <text>",me).option("--name <name>","Rule name (required)").option("--account <resourceId>","Bank account resourceId this rule applies to (required)").option("--config <json>","Rule configuration as JSON (nested under reconcileWithDirectCashEntry key)").option("--search-filter <json>","Condition deciding which bank lines the rule applies to. Without one the rule is never suggested").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);if(!i){if((!n.name||!n.account)&&(console.error(Z("Required: --name, --account")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,appliesToReconciliationAccount:n.account},n.config)try{i.configuration=JSON.parse(n.config)}catch{console.error(Z("Invalid --config JSON")),process.exit(1)}if(n.searchFilter)try{i.searchFilter=JSON.parse(n.searchFilter)}catch{console.error(Z("Invalid --search-filter JSON")),process.exit(1)}}if(i&&i.searchFilter==null){let s;try{s=Ka(n)}catch{s=!0}s||console.error(U("No condition set: the rule will apply by hand, but reconciliation will never suggest it."))}let o=await c8(r,i);if(pe(r,"create_bank_rule",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q("Bank rule created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a bank rule (FULL REPLACEMENT \u2014 reads current state, merges changes, writes back)").option("--jot <text>",me).option("--name <name>","New name").option("--account <resourceId>","Bank account resourceId (required \u2014 PUT is full replacement)").option("--config <json>","Updated configuration as JSON (full replacement)").option("--search-filter <json>","Replace the condition. Omit to keep the stored one").option("--clear-search-filter","Remove the condition, which stops the rule being suggested").option("--input <file>","Read full update body from JSON file (overrides flags; not combinable with the condition flags)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(n.clearSearchFilter&&n.searchFilter){console.error(Z("--search-filter and --clear-search-filter are mutually exclusive")),process.exitCode=1;return}if(n.input&&(n.searchFilter||n.clearSearchFilter)){console.error(Z("--input carries the whole body; --search-filter and --clear-search-filter cannot be combined with it")),console.error(U("Put searchFilter in the file instead (null clears it, omitting the key keeps the stored one).")),process.exitCode=1;return}let o=ye(n),s;if(o)s={resourceId:r,...o};else{if(!n.account){console.error(Z("--account is required for update (PUT is full replacement \u2014 GET does not return the UUID)")),console.error(U("Use: clio bank-rules update <id> --account <bank-account-uuid> [--name ...] [--config ...]")),process.exitCode=1;return}let u=(await rO(i,r)).data;if(s={resourceId:r,name:n.name??u.name,appliesToReconciliationAccount:n.account,configuration:u.configuration},n.config)try{s.configuration=JSON.parse(n.config)}catch{console.error(Z("Invalid --config JSON")),process.exit(1)}if(n.clearSearchFilter)s.searchFilter=null;else if(n.searchFilter)try{s.searchFilter=JSON.parse(n.searchFilter)}catch{console.error(Z("Invalid --search-filter JSON")),process.exit(1)}}let a=await l8(i,r,s);if(pe(i,"update_bank_rule",n,a.data),n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(Q(`Bank rule ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a bank rule").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await u8(i,r),pe(i,"delete_bank_rule",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Bank rule ${r} deleted.`))})(n))}Be();_4();nt();gt();function _yt(e){let t=e.command("reconciliations").alias("recon").description("Apply reconciliation decisions to bank statement entries");t.command("quick-reconcile").description("Async, bulk: match bank entries to journals (max 500). Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(n,i)=>{let o=ye(i);o||(console.error("Error: --input <file> is required (JSON with bankAccountResourceId + journalsForReconciliation[])"),process.exit(1));let s=await d4(n,o);i.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Quick reconcile started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bank-rule").description("Async, bulk: apply a bank rule to a batch of bank entries (max 500). Returns a jobId.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(n,i)=>{let o=ye(i);o||(console.error("Error: --input <file> is required (JSON with actionShortcutResourceId + businessTransactionResourceIds[])"),process.exit(1));let s=await f4(n,o);i.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Apply bank rule started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("magic-match").description("Sync, bulk: accept magic suggestions (MAGIC_MATCH to EXISTING transactions/payments, or MAGIC_RECONCILE_WITH_CASH_IN_OUT learned predictions; max 500). Returns { reconciled[], failed[] }, either possibly absent or empty; a non-empty failed[] is a partial success and exits 1. A failed entry may still have posted: re-read its line before any retry.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(n,i)=>{let o=ye(i);o||(console.error("Error: --input <file> is required (JSON with bankAccountResourceId + entries[])"),process.exit(1));let s=await I4(n,o),a=s.data.reconciled?.length??0,c=s.data.failed?.length??0;if(c>0&&(process.exitCode=1),i.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q(`Magic match: ${a} reconciled, ${c} failed.`));for(let u of s.data.failed??[]){let d=u.errors?.[0]?.errorCode??"UNKNOWN",f=u.errors?.[0]?.errorMessage??"";console.log(Se(` \u2717 ${u.bankStatementEntryResourceId}: ${d}${f?` \u2014 ${f}`:""}`))}}));let r=[{name:"direct-cash-entry",description:"Sync: reconcile a bank entry with a single cash-in / cash-out line. Direction inferred from the entry sign. NOT idempotent.",fn:p4},{name:"cash-journal",description:"Sync: reconcile a bank entry with a multi-line cashflow journal (max 200 lines). NOT idempotent.",fn:h4},{name:"manual-journal",description:"Sync: reconcile a bank entry with a double-entry manual journal. Bank-side leg auto-added by API. NOT idempotent.",fn:m4},{name:"cash-transfer",description:"Sync: reconcile a bank entry with an inter-account transfer. NOT idempotent.",fn:A4},{name:"invoice-receipt",description:"Sync (AR): CREATE an invoice and auto-reconcile it to a bank entry. To match an EXISTING invoice, use with-payments. NOT idempotent.",fn:g4},{name:"bill-receipt",description:"Sync (AP): CREATE a bill and auto-reconcile it to a bank entry. To match an EXISTING bill, use with-payments. NOT idempotent.",fn:y4},{name:"with-payments",description:"Sync: match a bank entry to an EXISTING open bill/invoice/payment (creates the payment + reconciles in one call). FX resolved server-side. NOT idempotent.",fn:E4},{name:"learned-prediction",description:"Sync: accept an ML learned-prediction suggestion (predictedPayload passed through from view_auto_reconciliation). NOT idempotent.",fn:b4}];for(let n of r)t.command(n.name).description(n.description).option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(i,o)=>{let s=ye(o);s||(console.error(`Error: --input <file> is required (JSON body for ${n.name})`),process.exit(1));let a=await n.fn(i,s);if(o.json)console.log(JSON.stringify(a.data,null,2));else{let c=a.data;console.log(Q(`Reconciled. Entry ${c.bankStatementEntryResourceId} \u2192 status ${c.status}${c.reference?` (ref: ${c.reference})`:""}`))}}));t.command("undo").description("Unlink bank entries from what they were reconciled against. Does NOT delete the record that was matched; prints its id so you can delete it separately.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(n,i)=>{let o=ye(i);o||(console.error("Error: --input <file> is required (JSON body with bankStatementEntryResourceIds)"),process.exit(1));let s=await C4(n,o);if(i.json){console.log(JSON.stringify(s.data,null,2));return}let a=s.data.resetReconciliationResponse??[],c=a.filter(m=>m.status==="SUCCESS"),u=a.filter(m=>m.status!=="SUCCESS"),d=o.bankStatementEntryResourceIds??[];console.log(Q(`Unlinked ${c.length}/${d.length} entries.`));let f=new Set(a.map(m=>m.bankStatementEntryResourceId)),p=d.filter(m=>!f.has(m));for(let m of p)console.log(Se(` ? ${m}: not found (no result returned for this id)`));for(let m of u){let A=m.errorCode??"FAILED";console.log(Se(` \u2717 ${m.bankStatementEntryResourceId}: ${A}${m.errorMessage?` (${m.errorMessage})`:""}`))}let h=s.data.linkedRecords??[];if(h.length>0){console.log(Se(`
1082
- ${h.length} record(s) were left in place and are NOT deleted:`));let m=new Set(["JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"]);for(let A of h){let g=A.businessTransactionType??"UNKNOWN_TYPE",y=m.has(g),b=(y?A.parentEntityResourceId:A.businessTransactionResourceId)??"(id not returned)";console.log(` ${g} ${b}${y?" [delete by parentEntityResourceId]":""} (was on ${A.bankStatementEntryResourceId??"?"})`)}console.log(Se(" Delete them with the matching delete command if they were created by the reconcile call."))}}))}Be();NAe();nt();gt();function wyt(e){let t=e.command("drafts").description("Bulk-action server-side draft lifecycle (max 500 per call, mixed BT types): validate, convert to active, submit for approval");t.command("validate").description("BULK validate (sync) \u2014 up to 500 drafts in ONE call, mixing any combination of invoices/bills/credit notes. Returns per-item errors inline. No state change.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=rIe(n),o=await s4(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):console.log(Q(`Validated ${i.length} draft(s). See JSON for per-item details (--json).`))})),t.command("convert-to-active").description("BULK promote drafts to ACTIVE (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`. NOT idempotent \u2014 filter by status: DRAFT before submitting.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=rIe(n),o=await a4(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Q(`Convert started. Job ID: ${o.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${o.data.jobId}`)))})),t.command("submit-for-approval").description("BULK submit drafts for approval (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId. NOT idempotent on drafts with an in-flight approval.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=rIe(n),o=await c4(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Q(`Submit started. Job ID: ${o.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${o.data.jobId}`)))}))}function rIe(e){let t=ye(e);t||(console.error('Error: --input <file> is required (JSON with { "items": [{btResourceId, btType}] } or a bare array)'),process.exit(1));let r=t.items??t;try{mv(r)}catch(n){console.error(`Error: ${n.message}`),process.exit(1)}return r}jn();Be();T8();hv();xl();nt();gt();zt();Bt();var vyt=[{key:"resourceId",header:"ID",format:De},{key:"name",header:"Name"},{key:"status",header:"Status"},{key:"purchasePrice",header:"Cost",align:"right",format:Rr}],Z1r=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Supplier"},{key:"documentResourceId",header:"Document ID",format:De}],eQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}];function Syt(e,t){return e.saveAsDraft===!1?`Fixed asset ${t} and registered. It is active.`:`Fixed asset ${t} and saved as a draft. Nothing is posted until it is registered; use --finalize to register it at once.`}function Dyt(e){let t=e.command("fixed-assets").alias("fa").description("Manage fixed assets");co({parent:t,description:"List fixed assets",columns:vyt,label:"Fetching fixed assets",title:"Fixed Assets",fetch:(r,n)=>d8(r,n)}),t.command("get <resourceId>").description("Get fixed asset details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await xE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.status),console.log(S("Type:"),s.typeName),console.log(S("Purchase:"),s.purchaseAmount),console.log(S("NBV:"),s.netBookValueAmount),console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:VR,defaults:WR,fetcher:nO,columns:vyt,label:"Searching fixed assets"}),t.command("create").description("Register a new fixed asset").option("--jot <text>",me).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Buildings", "Vehicles", "Furniture")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",It).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",de).option("--residual <n>","Residual/salvage value",It).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").addOption(new lt("--purchase-bt-type <type>","Linked purchase BT type (PURCHASE = bill)").choices([...oA])).option("--purchase-bt-id <id>","Linked purchase BT resourceId (required for ACTIVE assets)").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(Z("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.purchaseBtType&&(i.purchaseBusinessTransactionType=n.purchaseBtType),n.purchaseBtId&&(i.purchaseBusinessTransactionResourceId=n.purchaseBtId),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag]),n.finalize&&(i.saveAsDraft=!1)),n.customFields&&(i.customFields=Nr(n.customFields));let o=await f8(r,i);if(pe(r,"create_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(Syt(i,"created"))),console.log(S("ID:"),o.data.resourceId)})),t.command("delete <resourceId>").description("Delete a draft fixed asset").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await h8(i,r),pe(i,"delete_fixed_asset",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Fixed asset ${r} deleted.`))})(n)),t.command("update <resourceId>").description("Update a fixed asset").option("--jot <text>",me).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",de).option("--tag <name>","Add this tag; the asset keeps its other tags").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=ye(n),s;o?s=o:(s={},n.name!==void 0&&(s.name=n.name),n.notes!==void 0&&(s.internalNotes=n.notes),n.depreciationMethod&&(s.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(s.effectiveLife=n.effectiveLife),n.tag&&(s.tags={add:[n.tag]})),n.customFields&&(s.customFields=Nr(n.customFields));let{tags:a,...c}=s,u=Xn(a),d=u&&await Xi("fixed asset",r,()=>xE(i,r)),f=await p8(i,r,{...c,...u&&{tags:ui(d?.tags,u)}},d||void 0);if(pe(i,"update_fixed_asset",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(Q(s.isDraftToActive===!0?`Fixed asset ${r} activated and registered. It is active.`:`Fixed asset ${r} updated.`))})(n)),t.command("sell").description("Mark a fixed asset as sold").option("--jot <text>",me).option("--id <resourceId>","Fixed asset resourceId").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").addOption(new lt("--sale-type <type>","Sale BT type (SALE = invoice)").choices([...oA])).option("--sale-item <id>","Sale item resourceId").option("--input <file>","Read full body from JSON file").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);if(i){let s=await iO(r,i);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q("Fixed asset marked as sold."));return}(!n.id||!n.depreciationEndDate||!n.gainLossAccount||!n.saleType||!n.saleItem)&&(console.error(Z("Required: --id, --depreciation-end-date, --gain-loss-account, --sale-type, --sale-item")),process.exit(1));let o=await iO(r,{resourceId:n.id,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount,saleBusinessTransactionType:n.saleType,saleItemResourceId:n.saleItem});if(pe(r,"mark_fixed_asset_sold",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${n.id} marked as sold.`))})),t.command("transfer").description("Register a pre-existing fixed asset with accumulated depreciation (no linked purchase transaction)").option("--jot <text>",me).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Computers and Electronics")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",It).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",de).option("--accumulated-depreciation <n>","Depreciation already incurred",It).option("--residual <n>","Residual/salvage value",It).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--input <file>","Read full transfer body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(Z("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.accumulatedDepreciation!==void 0&&(i.bookValueAccumulatedDepreciationAmount=n.accumulatedDepreciation),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.notes&&(i.internalNotes=n.notes),n.finalize&&(i.saveAsDraft=!1));let o=await A8(r,i);if(pe(r,"transfer_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(Syt(i,"transferred")))})),t.command("discard <resourceId>").description("Discard (write off) a fixed asset").option("--jot <text>",me).option("--disposal-date <date>","Disposal date (YYYY-MM-DD)").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{(!n.disposalDate||!n.depreciationEndDate)&&(console.error(Z("--disposal-date and --depreciation-end-date are required.")),process.exit(1));let o=await m8(i,r,{disposalDate:n.disposalDate,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount});if(pe(i,"discard_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${r} discarded.`))})(n)),t.command("undo-disposal <resourceId>").description("Undo a fixed asset disposal").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await g8(i,r);if(pe(i,"undo_fixed_asset_disposal",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Disposal undone for ${r}.`))})(n)),t.command("close-out <resourceId>").description("Stop depreciating from a month while keeping the asset (reverse with reopen)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Last month to depreciate (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await y8(i,r,n.date);if(pe(i,"close_out_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out fixed asset").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await E8(i,r);if(pe(i,"reopen_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${r} reopened.`))})(n)),t.command("totals").description("Asset register totals (purchase amount, accumulated depreciation, net book value)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await I8(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("disposal-totals").description("Disposed asset totals (book value, sale proceeds, gain/loss; positive = loss)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await C8(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One asset's depreciation schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await v8(i,r,n.viewDate);console.log(JSON.stringify(qW(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("preview-schedule").description("Check a custom depreciation schedule and show its timeline; saves nothing (save only when status is FULLY_SCHEDULED with no errors)").option("--input <file>","JSON body: { depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule: [{ fromPeriod, toPeriod, amount }] }").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error(Z("--input <file> is required (JSON with depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule).")),process.exit(1));let o=await _8(r,i);console.log(JSON.stringify(gd(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("calculate-disposal <resourceId>").description("Accumulated depreciation at disposal, before mark-sold or discard; saves nothing").option("--depreciation-end-date <YYYY-MM-DD>","Final depreciation date (the one you will send to sell or discard)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.depreciationEndDate||(console.error(Z("--depreciation-end-date is required.")),process.exit(1));let o=await w8(i,r,n.depreciationEndDate);console.log(JSON.stringify(o.data,null,2))})(n)),Fe({parent:t,commandName:"eligible-lines",fields:KR,defaults:XR,fetcher:S8,columns:Z1r,label:"Searching bill lines eligible to register as assets"}),Fe({parent:t,commandName:"types",fields:ZR,defaults:eT,fetcher:D8,columns:eQr,label:"Searching asset types"}),t.command("bulk-upsert").description("Create or update fixed assets in bulk (max 500). Natural key: reference. Each row requires reference, registrationType (NEW | TRANSFER), a typeCode and a depreciationStartDate (epoch ms). Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await R8(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk upsert started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update fixed assets in bulk (max 500). Each row is resourceId plus only the fields to change; the stored asset is merged in first (tags take { add, remove }). Unknown or repeated resourceIds fail the whole call. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await b8(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}jn();an();xl();Be();hq();hv();nt();gt();zt();Bt();var tQr=[{key:"resourceId",header:"ID",format:De},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"deferralAmount",header:"Amount",align:"right",format:Rr},{key:"remainingAmount",header:"Remaining",align:"right",format:Rr}],rQr=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Contact"},{key:"documentResourceId",header:"Document ID",format:De}],nQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}],iQr=[{key:"accountResourceId",header:"ID",format:De},{key:"accountCode",header:"Code"},{key:"accountName",header:"Name"},{key:"category",header:"Category"}];function Ryt(e){let t=e.command("deferrals").description("Manage deferrals: prepaid expenses and deferred revenue released over months");t.command("get <resourceId>").description("Get deferral details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await Gg(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Category:"),s.category),console.log(S("Amount:"),s.deferralAmount),console.log(S("Remaining:"),s.remainingAmount),console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:tT,defaults:rT,fetcher:X2,columns:tQr,label:"Searching deferrals",extraParams:nT}),t.command("create").description("Create a deferral over eligible bill, invoice or journal lines (a draft unless --activate)").option("--jot <text>",me).option("--ref <reference>","Reference (required; see `clio references next DEFERRAL`)").option("--line <id...>","sourceLineResourceId from `clio deferrals eligible-lines` (one document, one account; required with --activate)").option("--type <typeCode>","Type code from `clio deferrals types`").option("--name <name>","Deferral name").option("--start <YYYY-MM-DD>","Amortization start date (on or after the document date)").option("--months <n>","Effective life in whole months",de).option("--amortization-account <id>","Expense (prepaid) or Revenue (deferred revenue) account resourceId").option("--notes <text>","Internal notes").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--activate","Post the whole schedule now (saveAsDraft: false); needs --line, --type, --name, --start, --months and --amortization-account").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);if(!i){let a=(n.activate?[["--ref",n.ref],["--line",n.line],["--type",n.type],["--name",n.name],["--start",n.start],["--months",n.months],["--amortization-account",n.amortizationAccount]]:[["--ref",n.ref]]).filter(([,u])=>u===void 0).map(([u])=>u);a.length>0&&(console.error(Z(`Required${n.activate?" with --activate":""}: ${a.join(", ")}`)),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1));let c={reference:n.ref,sourceLineResourceIds:n.line,typeCode:n.type,name:n.name,amortizationStartDate:n.start,effectiveLife:n.months,amortizationAccountResourceId:n.amortizationAccount};i=Object.fromEntries(Object.entries(c).filter(([,u])=>u!==void 0)),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag]),n.activate&&(i.saveAsDraft=!1)}n.customFields&&(i.customFields=Nr(n.customFields));let o=await Z2(r,i);if(pe(r,"create_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(o.data.status==="DRAFT"?"Deferral saved as a draft (nothing posted).":"Deferral created, active and posted: the whole schedule is on the books.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a deferral (partial) or activate a draft").option("--jot <text>",me).option("--ref <reference>","Reference (default: the stored one)").option("--name <name>","New name").option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",de).option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=ye(n),s;o?s=o:(s={},n.ref!==void 0&&(s.reference=n.ref),n.name!==void 0&&(s.name=n.name),n.start!==void 0&&(s.amortizationStartDate=n.start),n.months&&(s.effectiveLife=n.months),n.notes!==void 0&&(s.internalNotes=n.notes),n.activate&&(s.isDraftToActive=!0)),n.customFields&&(s.customFields=Nr(n.customFields));let{tags:a,...c}=s,u=Xn(a),d=u&&await Xi("deferral",r,()=>Gg(i,r)),f=await eq(i,r,{...c,...u&&{tags:ui(d?.tags,u)}},d||void 0);if(pe(i,"update_deferral",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(Q(s.isDraftToActive===!0?`Deferral ${r} activated: its schedule is posted.`:`Deferral ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a deferral of any status (removes every posted row, frees the lines)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await tq(i,r),pe(i,"delete_deferral",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Deferral ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop releasing after a date. Posts nothing: the remaining balance stays on the deferral account (reverse with reopen)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Close-out date, used as given").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await rq(i,r,n.date);if(pe(i,"close_out_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Deferral ${r} closed out. The remaining balance stays on the deferral account.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out deferral").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await nq(i,r);if(pe(i,"reopen_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Deferral ${r} reopened.`))})(n)),t.command("totals").description("Register totals for one category as at a date (never add the two categories together)").addOption(new lt("--category <cat>","Category").choices([...W2]).makeOptionMandatory()).option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await iq(n,{category:r.category,endDate:r.endDate});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One deferral's release schedule (posted rows only: a draft has none)").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await oq(i,r,n.viewDate);console.log(JSON.stringify(jW(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Fe({parent:t,commandName:"eligible-lines",fields:iT,defaults:oT,fetcher:sq,columns:rQr,label:"Searching bill, invoice and journal lines eligible to defer"}),Fe({parent:t,commandName:"types",fields:sT,defaults:aT,fetcher:aq,columns:nQr,label:"Searching deferral types"}),Fe({parent:t,commandName:"accounts",fields:cT,defaults:lT,fetcher:cq,columns:iQr,label:"Searching deferral accounts",extraParams:uT}),t.command("mark-accounts").description("Mark or unmark chart-of-accounts entries as deferral accounts (changes org setup)").option("--jot <text>",me).option("--account <id...>","Chart of accounts resourceId(s)").option("--unmark","Unmark instead of mark").option("--input <file>",'Read { "accounts": [{ organizationAccountResourceId, deferralAccount }] } from file').option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n),o=i?i.accounts??i:n.account?.map(f=>({organizationAccountResourceId:f,deferralAccount:!n.unmark}));Array.isArray(o)||(console.error(Z("Required: --account <id...> or --input <file>")),process.exit(1)),mt(o,"accounts",500,"accounts");let s=await lq(r,o);if(pe(r,"mark_deferral_accounts",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}let a=o.map(f=>f?.deferralAccount),c=a.filter(f=>f===!0).length,u=a.filter(f=>f===!1).length,d=[c>0&&`${c} account(s) marked as deferral accounts`,u>0&&(c>0?`${u} unmarked`:`${u} account(s) unmarked as deferral accounts`)].filter(Boolean);console.log(Q(`${d.length>0?d.join(", "):`${o.length} account(s) submitted`}.`))})),t.command("preview-schedule").description("Check custom release ranges without saving").option("--amount <n>","Deferral amount (sum of the eligible line amounts)",It).option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",de).option("--schedule <json>","JSON array of { fromPeriod, toPeriod, amount }").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||((n.amount===void 0||!n.start||!n.months||!n.schedule)&&(console.error(Z("Required: --amount, --start, --months, --schedule")),process.exit(1)),i={deferralAmount:n.amount,amortizationStartDate:n.start,effectiveLife:n.months,customSchedule:JSON.parse(n.schedule)});let o=await uq(r,i);console.log(JSON.stringify(gd(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("bulk-upsert").description("Create deferrals in bulk (max 500). Creates only, always ACTIVE, STRAIGHT_LINE, dates YYYY-MM-DD. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await dq(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk create started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update deferrals in bulk (max 500). Each row is partial; resourceId and reference are required per row. Not for tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await fq(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}jn();xl();Be();lAe();hv();nt();gt();zt();Bt();var oQr=[{key:"resourceId",header:"ID",format:De},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status",format:e=>hn(e)},{key:"leaseLiabilityRemaining",header:"Liability",align:"right",format:Rr},{key:"rouNetBookValue",header:"ROU NBV",align:"right",format:Rr}],sQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"}];function aQr(e){return(!/^\d+(\.\d{1,4})?$/.test(e)||Number(e)>=100)&&(console.error(Z(`Error: invalid discount rate: ${e} (% per MONTH, below 100, max 4 decimal places; 6% a year is 0.5)`)),process.exit(1)),Number(e)}function Tyt(e){let t=e.command("leases").description("Manage IFRS 16 leases and hire purchase (the register never posts rent: code rent bills to the current lease liability account)");t.command("get <resourceId>").description("Get lease details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await kE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Type:"),s.typeName),console.log(S("Liability:"),s.leaseLiabilityRemaining),console.log(S("ROU NBV:"),s.rouNetBookValue),console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:dT,defaults:fT,fetcher:x8,columns:oQr,label:"Searching leases",extraParams:pT}),t.command("create").description("Put a lease on the books (a draft unless --finalize). Rent is flat with --rent, stepped with --input.").option("--jot <text>",me).option("--reference <ref>","Lease reference (required; see `clio references next --type LEASE`)").option("--name <name>","Lease name").option("--type <typeCode>","Lease type code (see `clio leases types`; HIRE_PURCHASE for hire purchase)").option("--lessor <contactResourceId>","Lessor contact resourceId").option("--start <YYYY-MM-DD>","Commencement date").option("--term <months>","Lease term in months (1-600)",de).option("--rent <n>","Rent per month for the whole term",It).addOption(new lt("--payment-timing <timing>","ADVANCE (start of month) or ARREARS (end)").choices([...sh])).option("--discount-rate <n>","Discount rate in % per MONTH (6% a year is 0.5)",aQr).option("--rou-account <id>","Right-of-Use Asset account resourceId").option("--accumulated-depreciation-account <id>","Accumulated Depreciation account resourceId").option("--depreciation-expense-account <id>","Depreciation Expense account resourceId").option("--liability-account <id>","Current Lease Liability account resourceId (rent is coded here)").option("--non-current-liability-account <id>","Non-current Lease Liability account resourceId").option("--interest-account <id>","Interest Expense account resourceId (Finance Cost type)").option("--exempt","Short-term or low-value lease exemption (posts nothing)").option("--notes <text>","Internal notes").option("--finalize","Post the lease now (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags); needed for stepped rent, prepaid rent, restoration and ownership").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(n.reference||(console.error(Z("Required: --reference")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1)),n.rent!==void 0&&!n.term&&(console.error(Z("--rent needs --term: the rent is entered for every month of the term.")),process.exit(1)),i={reference:n.reference},n.name&&(i.name=n.name),n.type&&(i.typeCode=n.type),n.lessor&&(i.contactResourceId=n.lessor),n.start&&(i.commencementDate=n.start),n.term&&(i.leaseTerm=n.term),n.rent!==void 0&&(i.customSchedule=[{fromPeriod:1,toPeriod:n.term,amount:n.rent}]),n.paymentTiming&&(i.paymentTiming=n.paymentTiming),n.discountRate!==void 0&&(i.discountRate=n.discountRate),n.rouAccount&&(i.rouAssetAccountResourceId=n.rouAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.liabilityAccount&&(i.leaseLiabilityAccountResourceId=n.liabilityAccount),n.nonCurrentLiabilityAccount&&(i.leaseLiabilityNonCurrentAccountResourceId=n.nonCurrentLiabilityAccount),n.interestAccount&&(i.interestExpenseAccountResourceId=n.interestAccount),n.exempt&&(i.exemptionType="EXEMPT"),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag]),n.finalize&&(i.saveAsDraft=!1)),n.customFields&&(i.customFields=Nr(n.customFields));let o=await k8(r,i);if(pe(r,"create_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}let s=i.exemptionType==="EXEMPT";console.log(Q(i.saveAsDraft!==!1?"Lease saved as a draft. Nothing is posted until it is activated.":s?"Lease registered as exempt. Nothing is posted.":"Lease created, active and posted.")),console.log(S("ID:"),o.data.resourceId),console.log(S("Liability:"),o.data.leaseLiabilityAmount??U("-")),console.log(S("ROU asset:"),o.data.rouAssetAmount??U("-"))})),t.command("update <resourceId>").description("Edit or activate a lease (partial). A schedule change on an ACTIVE lease rewrites every entry from the start date.").option("--jot <text>",me).option("--reference <ref>","Reference (default: the stored one)").option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read the update body from JSON file (overrides flags); needed for schedule fields. tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let s=ye(n)??{...n.reference!==void 0&&{reference:n.reference},...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}};n.customFields&&(s.customFields=Nr(n.customFields));let{tags:a,...c}=s,u=Xn(a),d=u&&await Xi("lease",r,()=>kE(i,r)),f=await N8(i,r,{...c,...u&&{tags:ui(d?.tags,u)}},d||void 0);if(pe(i,"update_lease",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(Q(s.isDraftToActive!==!0?`Lease ${r} updated.`:f.data.exemptionType==="EXEMPT"?`Lease ${r} is now active as exempt. Nothing is posted.`:`Lease ${r} is now active and posted.`))})(n)),t.command("delete <resourceId>").description("Delete a lease of any status (removes every posted entry)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await B8(i,r),pe(i,"delete_lease",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Lease ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting after a month while the liability and right-of-use asset stay on the books (not an exit: use terminate)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Last month to post (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await O8(i,r,n.date);if(pe(i,"close_out_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Lease ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out lease").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await F8(i,r);if(pe(i,"reopen_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Lease ${r} reopened.`))})(n)),t.command("calculate-termination <resourceId>").description("Preview a termination: liability and right-of-use value removed, and the gain or loss (positive = gain). Saves nothing.").option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await Q8(i,r,n.date);console.log(JSON.stringify(o.data,null,2))})(n)),t.command("terminate <resourceId>").description("Take a lease off the books at a month-end, posting the gain or loss (run calculate-termination first)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--gain-loss-account <id>","Gain/loss account resourceId (required when the gain or loss is not 0)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await L8(i,r,{terminationDate:n.date,terminationGainLossAccountResourceId:n.gainLossAccount});if(pe(i,"terminate_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Lease ${r} terminated.`))})(n)),t.command("undo-termination <resourceId>").description("Undo a termination").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await P8(i,r);if(pe(i,"undo_lease_termination",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Termination undone for ${r}.`))})(n)),t.command("totals").description("Lease liability (current and non-current) and right-of-use net book value as at a date, from the schedule").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await M8(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One lease's schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First month to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await U8(i,r,n.viewDate);console.log(JSON.stringify($W(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Fe({parent:t,commandName:"types",fields:hT,defaults:mT,fetcher:$8,columns:sQr,label:"Searching lease types"}),t.command("preview-rent").description("Check rent ranges against the term (COMPLETE or INCOMPLETE). Body: { commencementDate, leaseTerm, customSchedule }.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error("Error: --input <file> is required (JSON with commencementDate, leaseTerm, customSchedule)"),process.exit(1));let o=await q8(r,i);console.log(JSON.stringify(gd(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("flat-rate").description("Hire purchase: convert a flat annual rate into the monthly discount rate and instalments. Saves nothing.").requiredOption("--rate <n>","Flat rate, % per year",Number).requiredOption("--financed <n>","Financed amount (cash price less down payment)",It).requiredOption("--term <months>","Term in months (1-600)",de).addOption(new lt("--payment-timing <timing>","ADVANCE or ARREARS (default ARREARS)").choices([...sh])).option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await j8(n,{flatRate:r.rate,financedAmount:r.financed,leaseTerm:r.term,paymentTiming:r.paymentTiming});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("bulk-update").description("Update leases in bulk (max 500): each row is partial and needs resourceId and reference. Not for rent or tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "leases": [...] })'),process.exit(1));let o=i.leases??i;Array.isArray(o)||(console.error('Error: expected { "leases": [...] }'),process.exit(1));let s=await Y8(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}Be();kAe();hv();xl();nt();gt();mn();zt();Ht();Bt();var cQr=[{key:"resourceId",header:"ID",format:De},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"outstandingPrincipal",header:"Outstanding",align:"right",format:Rr}],lQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"status",header:"Status"}],xyt="TERM or INSTALLMENT",c0=["--opening-balance <n>","Principal you confirm on the date after a missed, late or partial payment","openingBalance",It],uQr=[{name:"drawdown",event:"drawdown",tool:"record_loan_drawdown",description:"Raise the principal of a term loan on a date (a second tranche)",flags:[["--date <YYYY-MM-DD>","Drawdown date","drawdownDate"],["--amount <n>","Amount drawn","amount",It],["--keep <keep>",`${xyt} (default TERM)`,"keep"],c0],required:["drawdownDate","amount"]},{name:"prepay",event:"prepayment",tool:"prepay_loan",description:"Reduce principal with an extra repayment; the register posts no cash",flags:[["--date <YYYY-MM-DD>","Prepayment date","prepaymentDate"],["--amount <n>","Amount prepaid","amount",It],["--keep <keep>","INSTALLMENT keeps the monthly payment (term shortens), TERM keeps the term","keep"],c0],required:["prepaymentDate","amount","keep"]},{name:"change-rate",event:"rateChange",tool:"change_loan_rate",description:"The lender changed the rate from a date (never use update for this)",flags:[["--date <YYYY-MM-DD>","Effective date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR (7.25 = 7.25% a year)","annualInterestRate",Number],["--keep <keep>",xyt,"keep"],c0],required:["effectiveDate","annualInterestRate","keep"]},{name:"capitalize",event:"capitalization",tool:"capitalize_loan_interest",description:"Add one installment's whole interest to the principal",flags:[["--date <YYYY-MM-DD>","An installment due date","capitalizationDate"],c0],required:["capitalizationDate"]},{name:"payment-holiday",event:"paymentHoliday",tool:"record_loan_payment_holiday",description:"Skip installments (skipped interest is added to the balance)",flags:[["--from-period <n>","First skipped installment (periodNumber)","fromPeriod",de],["--to-period <n>","Last skipped installment","toPeriod",de],["--treatment <t>","ADD_INTEREST_TO_BALANCE (end date stays) or EXTEND_TERM","treatment"],c0],required:["fromPeriod","toPeriod","treatment"]},{name:"restructure",event:"restructure",tool:"restructure_loan",description:"New terms from an installment due date; 10% or more ends the loan and creates a new one",flags:[["--date <YYYY-MM-DD>","An installment due date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR","annualInterestRate",Number],["--term <months>","Installments left after the date","loanTerm",de],["--installment <n>","The lender's new installment","installmentOverride",It],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"],c0],required:["effectiveDate"]},{name:"settle",event:"settlement",tool:"settle_loan",description:"End a loan early; use --preview for the payoff figure",flags:[["--date <YYYY-MM-DD>","Settlement date","settlementDate"],["--penalty <n>","Lender's penalty (quoted only)","penaltyAmount",It]],required:["settlementDate"]},{name:"forgive",event:"forgiveness",tool:"forgive_loan",description:"Write off the whole loan (gain above 0)",flags:[["--date <YYYY-MM-DD>","Forgiveness date","forgivenessDate"],["--amount <n>","The whole outstanding principal","amount",It],["--forgiven-by <who>","LENDER or SHAREHOLDER","forgivenBy"],["--equity-account <id>","Equity account, for SHAREHOLDER","equityAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["forgivenessDate","amount","forgivenBy"]},{name:"convert",event:"conversion",tool:"convert_loan_to_shares",description:"Convert the whole loan into shares (IFRIC 19)",flags:[["--date <YYYY-MM-DD>","Conversion date","conversionDate"],["--fair-value <n>","Fair value of the shares","fairValue",It],["--share-capital-account <id>","Shareholders Equity account","shareCapitalAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["conversionDate","fairValue","shareCapitalAccountResourceId"]},{name:"refinance",event:"refinance",tool:"refinance_loan",description:"Settle the loan and create a new active one; returns the NEW loan. --input: { refinanceDate, newLoan: {...} }",flags:[["--date <YYYY-MM-DD>","Refinance date","refinanceDate"]],required:["refinanceDate","newLoan"]},{name:"reclassify-current",event:"reclassifyAsCurrent",tool:"reclassify_loan_as_current",description:"Make the whole balance current from a covenant breach date (IAS 1.74)",flags:[["--date <YYYY-MM-DD>","Breach date","reclassificationDate"],["--waiver-date <YYYY-MM-DD>","Date the bank waived it","waiverDate"]],required:["reclassificationDate"]},{name:"undo",event:"undo",tool:"undo_loan_event",description:"Reverse the latest event (see `clio loans events` for the id and canUndo)",flags:[["--event <resourceId>","The latest event resourceId","eventResourceId"]],required:["eventResourceId"]}];function O9(e){console.error(Z(e)),process.exit(1)}var kyt=e=>e.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(t,r)=>r.toUpperCase());function dQr(e,t){let r="calculate"in uO[t.event],n=e.command(`${t.name} <resourceId>`).description(r?`${t.description}. --preview shows the figures and saves nothing`:t.description);n.option("--jot <text>",me);for(let[i,o]of t.flags)n.option(i,o);r&&n.option("--preview","Calculate only: nothing is saved"),n.option("--input <file>","Read the whole event body from JSON file (not with the event flags)").option("--api-key <key>","API key").option("--json","JSON output").action((i,o)=>N(async s=>{let a=o.preview===!0;a&&o.jot!==void 0&&O9("--jot records the judgment behind a recorded event; a preview records nothing.");let c=ye(o),u=t.flags.filter(([p])=>o[kyt(p)]!==void 0).map(([p])=>p.split(" ")[0]);if(c&&u.length>0&&O9(`${u.join(", ")} would be ignored: --input supplies the whole body. Use the flags or --input, not both.`),!c){c={};for(let[p,,h,m]of t.flags){let A=o[kyt(p)];A!==void 0&&(c[h]=m?m(A):A)}}let d=t.required.filter(p=>c[p]===void 0);d.length>0&&(console.error(Z(`Required: ${d.join(", ")}`)),console.error(U("Pass the flags, or --input <file> with the full JSON body.")),process.exit(1));let f=await o4(s,t.event,i,c,a);if(a||pe(s,t.tool,o,f.data),o.json){console.log(JSON.stringify(f.data,null,2));return}console.log(a?Se("Preview only, nothing saved."):Q(`${t.name}: recorded on loan ${i}.`)),console.log(JSON.stringify(f.data,null,2))})(o))}function Nyt(e){let t=e.command("loans").description("Manage loans (borrowings): term and on demand, with their events");Fe({parent:t,fields:AT,defaults:gT,fetcher:YW,columns:cQr,label:"Searching loans",extraParams:yT}),Fe({parent:t,commandName:"types",fields:ET,defaults:bT,fetcher:HW,columns:lQr,label:"Searching loan types"}),t.command("get <resourceId>").description("Get a loan with its figures as of today").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await UE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Kind:"),s.kind),console.log(S("Rate (% a year):"),s.annualInterestRate),console.log(S("Outstanding principal:"),s.outstandingPrincipal),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a loan (a draft that posts nothing unless --activate). The register posts no cash: record the drawdown and every installment yourself. Body is a JSON file; run `loans preview-schedule` first.").option("--jot <text>",me).option("--input <file>","JSON body: reference, kind, typeCode, name, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, accounts...").option("--activate","Activate immediately (saveAsDraft: false)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error(Z("--input <file> is required (JSON with reference and the loan terms).")),process.exit(1)),n.activate&&(i.saveAsDraft=!1);let o=await zW(r,i);if(pe(r,"create_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(i.saveAsDraft===!1?"Loan created, active and posted. The register posts no cash: record the drawdown and every installment yourself.":"Loan saved as a draft. Nothing is posted until it is activated.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a loan (partial). A term, fee or account change on an ACTIVE loan rewrites the whole schedule: use an event for a mid-life change").option("--jot <text>",me).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--input <file>",'Read the whole update body from JSON file (not with --name, --notes or --activate). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o={...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}},s=ye(n);s&&Object.keys(o).length>0&&O9("--name, --notes and --activate would be ignored: --input supplies the whole body. Use the flags or --input, not both.");let a=s??o;Object.keys(a).length===0&&O9("Nothing to update: pass --name, --notes, --activate or --input.");let{tags:c,...u}=a,d=Xn(c),f=d&&await Xi("loan",r,()=>UE(i,r)),p=await JW(i,r,{...u,...d&&{tags:ui(f?.tags,d)}},f||void 0);if(pe(i,"update_loan",n,p.data),n.json){console.log(JSON.stringify(p.data,null,2));return}console.log(Q(a.isDraftToActive===!0?`Loan ${r} activated: its schedule is posted.`:`Loan ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a loan in any status (its own ledger rows go; your bank postings stay)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await GW(i,r),pe(i,"delete_loan",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Loan ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting from a month-end; balances stay. Not an exit (use settle). Reverse with reopen").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Close-out date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await VW(i,r,n.date);if(pe(i,"close_out_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Loan ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out loan (earlier events can no longer be undone afterwards)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await WW(i,r);if(pe(i,"reopen_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Loan ${r} reopened.`))})(n)),t.command("totals").description("What we owe in total: outstanding principal, current, non-current, accrued interest").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await KW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("A term loan's repayment schedule").option("--view-date <YYYY-MM-DD>","Rows posted as at this date (default today)").option("--from-period <n>","First installment number to print (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await XW(i,r,n.viewDate);console.log(JSON.stringify(pv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("events <resourceId>").description("A loan's events, latest first (canUndo marks the one that can be undone)").option("--limit <n>","Max results",de).option("--offset <n>","Page number (0-indexed)",tt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await st(n,({limit:s,offset:a})=>ZW(i,r,{limit:s,offset:a}),{label:"Fetching loan events",defaultLimit:20});Ke(o,[{key:"resourceId",header:"ID",format:De},{key:"eventType",header:"Event"},{key:"effectiveDate",header:"Date"},{key:"canUndo",header:"Can undo"}],n,"Loan events")})(n)),t.command("ledger <resourceId>").description("On-demand loans only: advances and repayments with the balance").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--limit <n>","Max results",de).option("--offset <n>","Page number (0-indexed)",tt).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await e4(i,r,{endDate:n.endDate,limit:n.limit,offset:n.offset});console.log(JSON.stringify(o,null,2))})(n)),t.command("preview-schedule").description("The schedule these terms would produce; saves nothing").option("--input <file>","JSON body: kind, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, fees...").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error(Z("--input <file> is required (JSON with kind, principalAmount, drawdownDate and the terms).")),process.exit(1));let o=await t4(r,i);console.log(JSON.stringify(pv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("opening-balance <resourceId>").description("Suggest an --opening-balance for an event after a missed, late or partial payment; saves nothing").option("--event-type <type>","DRAWDOWN, PREPAYMENT, RATE_CHANGE, CAPITALIZE_INTEREST, PAYMENT_HOLIDAY or RESTRUCTURE").option("--date <YYYY-MM-DD>","Event date (for a holiday, the first skipped due date)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{(!n.eventType||!n.date)&&(console.error(Z("Required: --event-type, --date")),process.exit(1));let o=await r4(i,{resourceId:r,eventType:n.eventType,date:n.date});console.log(JSON.stringify(o.data,null,2))})(n));for(let r of uQr)dQr(t,r);for(let[r,n,i]of[["bulk-upsert","Create ACTIVE loans in bulk (max 500; creates only, dates YYYY-MM-DD, no CUSTOM shape or fees)",n4],["bulk-update","Update loans in bulk (max 500; update per row, reference required on each). Not for tag changes (use update)",i4]])t.command(r).description(`${n}. Returns a jobId; poll with \`clio background-jobs get <jobId>\`.`).option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(o,s)=>{let a=ye(s);a||(console.error('Error: --input <file> is required (JSON with { "loans": [...] })'),process.exit(1));let c=a.loans??a;Array.isArray(c)||(console.error('Error: expected { "loans": [...] }'),process.exit(1));let u=await i(o,c);s.json?console.log(JSON.stringify(u.data,null,2)):(console.log(Q(`${r} started. Job ID: ${u.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${u.data.jobId}`)))}))}Be();K8();nt();KS();gt();Bt();zt();var fQr=[{key:"resourceId",header:"ID",format:De},{key:"status",header:"Status",format:e=>String(e)==="ACTIVE"?Q(String(e)):U(String(e))},{key:"interval",header:"Interval"},{key:"totalAmount",header:"Amount",align:"right"},{key:"businessTransactionType",header:"Type"}],pQr=[{key:"resourceId",header:"ID",format:De},{key:"scheduledTransactionType",header:"Type"},{key:"status",header:"Status",format:e=>U(String(e??""))}];function Byt(e){let t=e.command("subscriptions").alias("subs").description("Manage recurring subscriptions");co({parent:t,description:"List subscriptions",columns:fQr,label:"Fetching subscriptions",title:"Subscriptions",fetch:(r,n)=>H8(r,n)}),t.command("get <resourceId>").description("Get subscription details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await NE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Status:"),s.status),console.log(S("Interval:"),s.interval),console.log(S("Amount:"),s.totalAmount),console.log(S("Next:"),cf(s.nextScheduleDate)??"N/A"),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a recurring subscription (invoices only, with proration)").option("--jot <text>",me).option("--interval <interval>","WEEKLY, MONTHLY, QUARTERLY, or YEARLY (required)").option("--start-date <YYYY-MM-DD>","Start date (required)").option("--end-date <YYYY-MM-DD>","End date (optional, omit for ongoing)").option("--contact <name|resourceId>","Customer contact (required)").option("--ref <reference>","Invoice reference").option("--date <YYYY-MM-DD>","Invoice date").option("--due <YYYY-MM-DD>","Due date").option("--account <name|resourceId>","Revenue account \u2014 applied to ALL line items (required)").option("--tax-profile <name|resourceId>","Tax profile \u2014 applied to ALL line items").option("--lines <json>","Line items as JSON array (name, unitPrice, quantity)").option("--amount <n>","Single line item amount (shorthand)",It).option("--line-name <name>","Line item name (used with --amount)").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);if(!i){(!n.interval||!n.startDate)&&(console.error(Z("Required: --interval, --start-date")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1));let s;if(n.lines)try{s=JSON.parse(n.lines)}catch{console.error(Z("Invalid --lines JSON")),process.exit(1)}else n.amount!==void 0&&(s=[{name:n.lineName??"Subscription",unitPrice:n.amount,quantity:1}]);s&&(n.account||n.taxProfile)&&(s=s.map(a=>({...a,...n.account&&!a.accountResourceId?{accountResourceId:n.account}:{},...n.taxProfile&&!a.taxProfileResourceId?{taxProfileResourceId:n.taxProfile}:{}}))),i={repeat:n.interval,startDate:n.startDate,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment"},invoice:{contactResourceId:n.contact,reference:n.ref,valueDate:n.date,dueDate:n.due,lineItems:s,saveAsDraft:!1}},n.endDate&&(i.endDate=n.endDate)}let o=await z8(r,i);if(pe(r,"create_subscription",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q("Subscription created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a subscription (the body must carry the invoice template; status is kept when omitted)").option("--jot <text>",me).option("--input <file>","Read full update body from JSON file: `invoice` template required (create shape), optional endDate, repeat, status, proratedConfig").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=ye(n);o||(console.error(Z("Use --input <file> to provide update data.")),process.exit(1));let s=await J8(i,r,o);if(pe(i,"update_subscription",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q(`Subscription ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a subscription").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await G8(i,r),pe(i,"delete_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Subscription ${r} deleted.`))})(n)),t.command("cancel <resourceId>").description("Cancel an active subscription (prorates remaining period)").option("--jot <text>",me).option("--cancel-date-type <type>","END_OF_CURRENT_PERIOD, END_OF_LAST_PERIOD, or CUSTOM_DATE","END_OF_CURRENT_PERIOD").option("--end-date <YYYY-MM-DD>","Custom cancel date (only with CUSTOM_DATE)").option("--prorated-text <text>","Prorated adjustment line text","Prorated adjustment").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await V8(i,r,{cancelDateType:n.cancelDateType,proratedAdjustmentLineText:n.proratedText,endDate:n.endDate}),pe(i,"cancel_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({cancelled:!0,resourceId:r}));return}console.log(Q(`Subscription ${r} cancelled.`))})(n)),Fe({parent:t,commandName:"search-scheduled",fields:IT,defaults:CT,fetcher:W8,columns:pQr,label:"Searching scheduled transactions"})}Be();uAe();nt();gt();Bt();zt();var Oyt=[{key:"resourceId",header:"ID",format:De},{key:"name",header:"Name"}];function Fyt(e){let t=e.command("contact-groups").description("Manage contact groups");co({parent:t,description:"List contact groups",columns:Oyt,label:"Fetching contact groups",title:"Contact Groups",fetch:(r,n)=>X8(r,n)}),t.command("get <resourceId>").description("Get contact group details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await Z8(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Contacts:"),s.associatedContacts?.length??0);for(let a of s.associatedContacts??[])console.log(` ${Se(a.resourceId)} ${a.name}`);console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:ax,defaults:cx,fetcher:eW,columns:Oyt,label:"Searching contact groups",positionalArg:"name",positionalFilter:r=>({name:{contains:r}})}),t.command("create").description("Create a contact group").option("--jot <text>",me).option("--name <name>","Group name").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{Me(n,[{flag:"--name",key:"name"}]);let i=await tW(r,{name:n.name});if(pe(r,"create_contact_group",n,i.data),n.json){console.log(JSON.stringify(i.data,null,2));return}console.log(Q(`Contact group "${n.name}" created.`)),console.log(S("ID:"),i.data.resourceId)})),t.command("update <resourceId>").description("Update a contact group").option("--name <name>","New group name").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o={};n.name&&(o.name=n.name);let s=await rW(i,r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q("Contact group updated.")),console.log(S("ID:"),s.data.resourceId)})(n)),t.command("delete <resourceId>").description("Delete a contact group").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await nW(i,r),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Contact group ${r} deleted.`))})(n))}jn();dAe();nt();gt();mn();Ht();Bt();Be();var hQr=[{key:"resourceId",header:"ID",format:De},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"itemCode",header:"Code",format:e=>U(String(e??""))}],mQr=[{key:"itemCode",header:"Code",format:e=>U(String(e??""))},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"totalQuantity",header:"Qty",format:e=>String(e??"")},{key:"baseUnit",header:"Unit",format:e=>String(e??"")},{key:"averageCostAmount",header:"Avg Cost",format:e=>String(e??"")},{key:"balanceAmount",header:"Value",format:e=>String(e??"")}];function Lyt(e){let t=e.command("inventory").alias("inv").description("Inventory management");t.command("items").description("List inventory-tracked items").option("--limit <n>","Max results",de).option("--offset <n>","Page number offset (0-indexed)",tt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=await st(n,o=>iW(r,o),{label:"Fetching inventory items"});Ke(i,hQr,n,"Inventory Items")})),t.command("balance <itemResourceId>").description("Get inventory balance for an item").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await sW(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Item:"),s.itemResourceId),console.log(S("Qty:"),`${s.baseQty} ${s.baseUnit}`),console.log(S("Avg Cost:"),s.latestAverageCostAmount)})(n)),t.command("balances").description("List inventory balances across items, by balance status").addOption(new lt("--status <status>","Balance status").choices([...aW]).default("ALL")).option("--limit <n>","Max results",de).option("--offset <n>","Page number offset (0-indexed)",tt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=n.status,o=await st(n,s=>cW(r,i,s),{label:"Fetching inventory balances"});Ke(o,mQr,n,"Inventory Balances")})),t.command("create").description("Create an inventory-tracked item (use --input for full JSON body)").option("--item-code <code>","Item code (SKU) (required)").option("--name <name>","Item name (required)").option("--unit <unit>","Unit of measure (required)").option("--costing-method <method>","FIXED or WAC (required)").option("--cogs-account <resourceId>","COGS account resourceId, Direct Costs type (required)").option("--purchase-account <resourceId>","Purchase account resourceId, Inventory type (required)").option("--sale-account <resourceId>","Sale account resourceId (required)").option("--block-insufficient","Block transactions when stock is insufficient").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||Me(n,[{flag:"--item-code",key:"itemCode"},{flag:"--name",key:"name"},{flag:"--unit",key:"unit"},{flag:"--costing-method",key:"costingMethod"},{flag:"--cogs-account",key:"cogsAccount"},{flag:"--purchase-account",key:"purchaseAccount"},{flag:"--sale-account",key:"saleAccount"}]);let o=i??{itemCode:n.itemCode,name:n.name,unit:n.unit,costingMethod:n.costingMethod,cogsResourceId:n.cogsAccount,purchaseAccountResourceId:n.purchaseAccount,saleAccountResourceId:n.saleAccount,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:!!n.blockInsufficient},s=await oW(r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q("Inventory item created.")),console.log(S("ID:"),s.data.resourceId)}))}Be();fAe();nt();gt();Bt();zt();var Qyt=[{key:"resourceId",header:"ID",format:De},{key:"customFieldName",header:"Name"}];function Pyt(e){let t=e.command("custom-fields").description("Manage custom fields");co({parent:t,description:"List custom fields",columns:Qyt,label:"Fetching custom fields",title:"Custom Fields",fetch:(r,n)=>lW(r,n)}),t.command("get <resourceId>").description("Get a custom field by resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let s=(await oO(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Name:"),s.customFieldName||s.name||"(unnamed)"),console.log(S("ID:"),s.resourceId),console.log(S("Type:"),s.datatypeCode||s.fieldType||"\u2014"),s.description&&console.log(S("Description:"),s.description),s.defaultValue&&console.log(S("Default:"),s.defaultValue),s.listOptions?.length&&console.log(S("Options:"),s.listOptions.join(", "));let a=u=>u==="SHOW"||u==="PRINT",c=[];a(s.applyToSales)&&c.push("invoices"),a(s.applyToPurchase)&&c.push("bills"),a(s.applyToSaleCreditNote)&&c.push("customer CNs"),a(s.applyToPurchaseCreditNote)&&c.push("supplier CNs"),a(s.applyToPayment)&&c.push("payments"),a(s.appliesToFixedAssets)&&c.push("fixed assets"),c.length&&console.log(S("Applies to:"),c.join(", "))})(n)),Fe({parent:t,fields:ox,defaults:sx,fetcher:uW,columns:Qyt,label:"Searching custom fields"}),t.command("create").description("Create a custom field").option("--jot <text>",me).option("--name <name>","Field name").option("--description <text>","Field description").option("--print-on-documents","Print this field on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--field-format <fmt>","CUSTOM (default, free text) or ALL_CUSTOMERS / ALL_SUPPLIERS / ALL_CONTACTS / ALL_EMPLOYEES / ALL_USERS for a picklist of that population").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{Me(n,[{flag:"--name",key:"name"}]);let o=n.invoices||n.bills||n.customerCredits||n.supplierCredits||n.payments?{invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1}:void 0,s=await dW(r,{name:n.name,description:n.description,printOnDocuments:n.printOnDocuments??!1,appliesTo:o,format:n.fieldFormat});if(pe(r,"create_custom_field",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q(`Custom field "${n.name}" created.`)),console.log(S("ID:"),s.data.resourceId)})),t.command("update <resourceId>").description("Update a custom field").option("--name <name>","New field name").option("--description <text>","New description").option("--print-on-documents","Print on PDF documents").option("--no-print-on-documents","Do not print on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.description!==void 0&&(o.description=n.description),n.printOnDocuments!==void 0&&(o.printOnDocuments=n.printOnDocuments),(n.invoices!==void 0||n.bills!==void 0||n.customerCredits!==void 0||n.supplierCredits!==void 0||n.payments!==void 0)&&(o.appliesTo={invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1});let a=await fW(i,r,o);if(n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(Q(`Custom field ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a custom field").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await pW(i,r),pe(i,"delete_custom_field",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Custom field ${r} deleted.`))})(n))}jn();Be();RAe();nt();gt();Ht();function Myt(e){let t=po(e)??[];if(t.length===0)throw new hr("--ids must contain at least one resourceId (comma-separated).");return t}function Uyt(e,t){if(!e||typeof e!="object")throw new Error(`${t}: the API returned no job handle. The batch may still have been accepted \u2014 check \`clio background-jobs search\` before resending.`);return e}function $yt(e){return JSON.stringify({...e,pollWith:e.jobId?`clio background-jobs get ${e.jobId}`:"clio background-jobs search",note:"Bulk is async. Per-record outcomes exist ONLY in the job, never in this response."},null,2)}function qyt(e,t){console.log(Q(`${t} queued.`)),e.jobId&&console.log(S("Job ID:"),e.jobId),e.totalRecords!==void 0&&console.log(S("Records:"),String(e.totalRecords)),console.log(Se(` Poll progress: clio background-jobs get ${e.jobId??"<jobId>"}`))}function jyt(e,t,r){let n=FW(e);if(t.json){let i=n.state==="approved"?!0:n.state==="refused"?!1:null;console.log(JSON.stringify({entity:r.entity,resourceId:r.resourceId,[r.jsonKey]:i,records:e},null,2))}else n.state==="refused"?console.log(Z(`Not ${r.doneVerb}: ${r.entity} ${r.resourceId} \u2014 ${n.reason}`)):n.state==="unconfirmed"?console.log(Z(`UNCONFIRMED: ${r.entity} ${r.resourceId} \u2014 the API returned no per-record outcome, so this neither succeeded nor failed provably. Re-read the document before recording it.`)):(console.log(Q(`${r.entity} ${r.resourceId} ${r.doneVerb}.`)),e?.[0]&&r.extra?.(e[0]));return n.state!=="approved"?(process.exitCode=1,!1):!0}function Yyt(e){let t=e.command("approvals").description("Approve documents or send them back for changes"),r=n=>new lt("-e, --entity <entity>","Document family").choices([...n]).makeOptionMandatory();t.command("approve <resourceId>").description("Approve one document \u2014 posts its ledger entries and makes it live").addOption(r(ap)).option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>N(async o=>{let s=await LW(o,i.entity,n);jyt(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"approved",doneVerb:"approved",extra:c=>{c.status&&console.log(S("Status:"),c.status)}})&&pe(o,"approve_documents",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-approve").description("Approve up to 100 documents (async \u2014 returns a job)").addOption(r(ap)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-100)").option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>N(async i=>{let o=Myt(n.ids),s=await QW(i,n.entity,o),a=Uyt(s?.data,"bulk approve");n.json?console.log($yt(a)):qyt(a,`Approval of ${o.length} ${n.entity}`),pe(i,"bulk_approve_documents",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n)),t.command("request-changes <resourceId>").description("Send one document back for changes instead of approving it").addOption(r(PE)).requiredOption("-m, --message <text>","Why it is sent back \u2014 opens a thread and is the only record of the reason").option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>N(async o=>{let s=await PW(o,i.entity,n,i.message);jyt(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"sentBack",doneVerb:"sent back for changes",extra:c=>{let u=c.collaborationThreadPath;u&&console.log(S("Thread:"),u)}})&&pe(o,"request_document_changes",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-request-changes").description("Send up to 500 documents back for changes with one message (async \u2014 returns a job)").addOption(r(PE)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-500)").requiredOption("-m, --message <text>","Why they are sent back \u2014 the only record of the reason").option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>N(async i=>{let o=Myt(n.ids),s=await MW(i,n.entity,o,n.message),a=Uyt(s?.data,"bulk request changes");n.json?console.log($yt(a)):qyt(a,`Request-changes on ${o.length} ${n.entity}`),pe(i,"bulk_request_document_changes",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n))}Be();kre();nt();zt();Bt();var Hyt=[{key:"resourceId",header:"ID",format:De},{key:"name",header:"Name"},{key:"reference",header:"Reference"},{key:"currencyCode",header:"Currency"}];function zyt(e){let t=e.command("purchase-items").description("Browse the purchase-side catalog (read-only)");co({parent:t,description:"List purchase items",columns:Hyt,label:"Fetching purchase items",title:"Purchase Items",offsetMode:qg.offsetMode,fetch:(r,n)=>E2(r,n)}),t.command("get <resourceId>").description("Get a purchase item by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let s=(await b2(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("ID:"),s.resourceId);for(let[a,c]of[["Name","name"],["Reference","reference"],["Currency","currencyCode"]]){let u=s[c];u!=null&&u!==""&&console.log(S(`${a}:`),String(u))}})(n)),Fe({parent:t,fields:vT,defaults:qg,columns:Hyt,label:"Searching purchase items",fetcher:I2})}Gme();nt();DC();Be();gt();Ht();import{readFileSync as Jyt}from"node:fs";import{isAbsolute as AQr}from"node:path";function Gyt(e,t){if(e!==void 0&&t)throw new hr("Pass the query as an argument OR --input <file>, not both.");if(t){let n;try{n=Jyt(t,"utf-8")}catch{throw new hr(`Cannot read --input file: ${t}`)}let i=n.trim();if(!i)throw new hr(`--input file is empty: ${t}`);return i}let r=e?.trim();if(r)return r;if(!process.stdin.isTTY){let n=Jyt(0,"utf-8").trim();if(n)return n}throw new hr("A query is required. Pass it as an argument, --input <file>, or on stdin.")}var gQr=new Set(["numeric","int","int8","bigint","float8","double precision"]);function yQr(e){return e.map((t,r)=>({key:String(r),header:t.name,align:gQr.has(t.type)?"right":"left"}))}function EQr(e,t){return t.map(r=>Object.fromEntries(e.map((n,i)=>[String(i),r[n.name]])))}function Vyt(e){let t=e.command("pseudo-sql").alias("sql").description("Read-only queries over Jaz's curated reporting tables (a restricted SQL subset, not your database)");t.command("preview [query]").description("Run a SELECT and print up to 100 rows").option("--input <file>","Read the query from a file instead of an argument").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let s=(await HV(i,Gyt(r,n.input))).data;if(n.json){console.log(JSON.stringify(s,null,2));return}for(let u of s.warnings??[])console.error(Te("Warning:"),u);if(!Array.isArray(s.rows)||!Array.isArray(s.columns))throw new Error("pseudo-sql preview: upstream returned no rows/columns array");if(s.rows.length===0){console.log(U("No rows."));return}let c=s.columns.slice(0,8);console.log(Gs(EQr(c,s.rows),yQr(c))),s.columns.length>c.length&&console.log(U(`Showing ${c.length} of ${s.columns.length} columns \u2014 use --json for all`)),console.log(U(`${s.rowCount} row(s)${s.truncated?" \u2014 `clio sql export` returns the full set":""}`))})(n)),t.command("export [query]").description("Export a SELECT to CSV (waits for the job by default)").option("--input <file>","Read the query from a file instead of an argument").option("--out <path>","Absolute path to write the CSV to (implies download)").option("--download","Download the CSV to ~/Downloads instead of printing the URL").option("--no-wait","Return the jobId immediately; poll with `export-status`").option("--timeout <seconds>","How long to wait for the job (default 25, max 90)",de).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let o=Gyt(r,n.input);if(n.wait===!1){let u=[["--out",n.out],["--download",n.download],["--timeout",n.timeout]].filter(([,d])=>d!==void 0).map(([d])=>d);if(u.length)throw new hr(`--no-wait cannot be combined with ${u.join(", ")} \u2014 it returns before the export runs. Drop --no-wait, or poll with \`clio sql export-status <jobId>\`.`)}if(n.out&&!AQr(n.out))throw new hr(`--out must be an absolute path; got "${n.out}".`);if(n.wait===!1){let u=await WB(i,o,{idempotencyKey:Jme(o)});if(n.json){console.log(JSON.stringify(u.data,null,2));return}console.log(Q("Export started")),console.log(S("Job:"),u.data.jobId,U(`(${u.data.status})`)),console.log(U(`Poll with: clio sql export-status ${u.data.jobId}`));return}typeof n.timeout=="number"&&n.timeout>90&&console.error(Te(`--timeout ${n.timeout} exceeds the 90s ceiling; waiting 90s. Use --no-wait for a longer job.`));let s=!!(n.download||n.out),c=(await zV(i,o,{timeoutSeconds:n.timeout,downloadToFile:s,outPath:n.out})).data;if(n.json){let{buffer:u,...d}=c;console.log(JSON.stringify(d,null,2));return}if(c.status==="TIMED_OUT"){console.error(Te("Still running."),U(`Poll with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(c.status!=="COMPLETED"){console.error(Z(`Export ${c.status}`),c.error??""),process.exitCode=1;return}if(c.error){console.error(Z("Export completed but the download failed:"),c.error),console.error(U(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(!c.localPath&&!c.downloadUrl){console.error(Z("Export reported COMPLETED but returned no file and no URL.")),console.error(U(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}console.log(Q("Export ready")),c.rowCount!==void 0&&console.log(S("Rows:"),String(c.rowCount)+(c.truncated?U(" \u2014 more rows match than the LIMIT returned"):"")),c.localPath?console.log(S("Saved:"),c.localPath):c.downloadUrl&&console.log(S("URL:"),c.downloadUrl,U("(expires in ~15 min)"))})(n)),t.command("export-status <jobId>").description("Poll an export job").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let s=(await ev(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Status:"),s.status),s.rowCount!==void 0&&console.log(S("Rows:"),String(s.rowCount)),s.downloadUrl&&console.log(S("URL:"),s.downloadUrl,U("(expires in ~15 min)")),s.error?(console.error(Z("Error:"),s.error),process.exitCode=1):(s.status==="FAILED"||s.status==="EXPIRED")&&(process.exitCode=1)})(n)),t.command("schema [table]").description("Show the curated catalog: tables, columns, joins").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let{data:o}=await tv(i),s=JV(o,r),a=s.scopedTo?.toLowerCase();if(n.json){console.log(JSON.stringify(s,null,2));return}if(a){let c=s.tables[0];if(console.log(S(c.name),U(c.label??"")),console.log(Gs((c.columns??[]).map(u=>({column:u.name,type:u.type})),[{key:"column",header:"Column"},{key:"type",header:"Type"}])),s.joins.length){console.log(`
1083
+ ${h.length} record(s) were left in place and are NOT deleted:`));let m=new Set(["JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"]);for(let A of h){let g=A.businessTransactionType??"UNKNOWN_TYPE",y=m.has(g),b=(y?A.parentEntityResourceId:A.businessTransactionResourceId)??"(id not returned)";console.log(` ${g} ${b}${y?" [delete by parentEntityResourceId]":""} (was on ${A.bankStatementEntryResourceId??"?"})`)}console.log(Se(" Delete them with the matching delete command if they were created by the reconcile call."))}}))}Be();NAe();nt();gt();function wyt(e){let t=e.command("drafts").description("Bulk-action server-side draft lifecycle (max 500 per call, mixed BT types): validate, convert to active, submit for approval");t.command("validate").description("BULK validate (sync) \u2014 up to 500 drafts in ONE call, mixing any combination of invoices/bills/credit notes. Returns per-item errors inline. No state change.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=rIe(n),o=await s4(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):console.log(Q(`Validated ${i.length} draft(s). See JSON for per-item details (--json).`))})),t.command("convert-to-active").description("BULK promote drafts to ACTIVE (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`. NOT idempotent \u2014 filter by status: DRAFT before submitting.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=rIe(n),o=await a4(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Q(`Convert started. Job ID: ${o.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${o.data.jobId}`)))})),t.command("submit-for-approval").description("BULK submit drafts for approval (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId. NOT idempotent on drafts with an in-flight approval.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=rIe(n),o=await c4(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Q(`Submit started. Job ID: ${o.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${o.data.jobId}`)))}))}function rIe(e){let t=ye(e);t||(console.error('Error: --input <file> is required (JSON with { "items": [{btResourceId, btType}] } or a bare array)'),process.exit(1));let r=t.items??t;try{mv(r)}catch(n){console.error(`Error: ${n.message}`),process.exit(1)}return r}jn();Be();T8();hv();xl();nt();gt();zt();Bt();var vyt=[{key:"resourceId",header:"ID",format:De},{key:"name",header:"Name"},{key:"status",header:"Status"},{key:"purchasePrice",header:"Cost",align:"right",format:Rr}],Z1r=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Supplier"},{key:"documentResourceId",header:"Document ID",format:De}],eQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}];function Syt(e,t){return e.saveAsDraft===!1?`Fixed asset ${t} and registered. It is active.`:`Fixed asset ${t} and saved as a draft. Nothing is posted until it is registered; use --finalize to register it at once.`}function Dyt(e){let t=e.command("fixed-assets").alias("fa").description("Manage fixed assets");co({parent:t,description:"List fixed assets",columns:vyt,label:"Fetching fixed assets",title:"Fixed Assets",fetch:(r,n)=>d8(r,n)}),t.command("get <resourceId>").description("Get fixed asset details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await xE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.status),console.log(S("Type:"),s.typeName),console.log(S("Purchase:"),s.purchaseAmount),console.log(S("NBV:"),s.netBookValueAmount),console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:VR,defaults:WR,fetcher:nO,columns:vyt,label:"Searching fixed assets"}),t.command("create").description("Register a new fixed asset").option("--jot <text>",me).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Buildings", "Vehicles", "Furniture")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",It).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",de).option("--residual <n>","Residual/salvage value",It).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").addOption(new lt("--purchase-bt-type <type>","Linked purchase BT type (PURCHASE = bill)").choices([...oA])).option("--purchase-bt-id <id>","Linked purchase BT resourceId (required for ACTIVE assets)").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(Z("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.purchaseBtType&&(i.purchaseBusinessTransactionType=n.purchaseBtType),n.purchaseBtId&&(i.purchaseBusinessTransactionResourceId=n.purchaseBtId),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])),n.finalize&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=Nr(n.customFields));let o=await f8(r,i);if(pe(r,"create_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(Syt(i,"created"))),console.log(S("ID:"),o.data.resourceId)})),t.command("delete <resourceId>").description("Delete a draft fixed asset").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await h8(i,r),pe(i,"delete_fixed_asset",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Fixed asset ${r} deleted.`))})(n)),t.command("update <resourceId>").description("Update a fixed asset").option("--jot <text>",me).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",de).option("--tag <name>","Add this tag; the asset keeps its other tags").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=ye(n),s;o?s=o:(s={},n.name!==void 0&&(s.name=n.name),n.notes!==void 0&&(s.internalNotes=n.notes),n.depreciationMethod&&(s.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(s.effectiveLife=n.effectiveLife),n.tag&&(s.tags={add:[n.tag]})),n.customFields&&(s.customFields=Nr(n.customFields));let{tags:a,...c}=s,u=Xn(a),d=u&&await Xi("fixed asset",r,()=>xE(i,r)),f=await p8(i,r,{...c,...u&&{tags:ui(d?.tags,u)}},d||void 0);if(pe(i,"update_fixed_asset",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(Q(s.isDraftToActive===!0?`Fixed asset ${r} activated and registered. It is active.`:`Fixed asset ${r} updated.`))})(n)),t.command("sell").description("Mark a fixed asset as sold").option("--jot <text>",me).option("--id <resourceId>","Fixed asset resourceId").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").addOption(new lt("--sale-type <type>","Sale BT type (SALE = invoice)").choices([...oA])).option("--sale-item <id>","Sale item resourceId").option("--input <file>","Read full body from JSON file").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);if(i){let s=await iO(r,i);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q("Fixed asset marked as sold."));return}(!n.id||!n.depreciationEndDate||!n.gainLossAccount||!n.saleType||!n.saleItem)&&(console.error(Z("Required: --id, --depreciation-end-date, --gain-loss-account, --sale-type, --sale-item")),process.exit(1));let o=await iO(r,{resourceId:n.id,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount,saleBusinessTransactionType:n.saleType,saleItemResourceId:n.saleItem});if(pe(r,"mark_fixed_asset_sold",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${n.id} marked as sold.`))})),t.command("transfer").description("Register a pre-existing fixed asset with accumulated depreciation (no linked purchase transaction)").option("--jot <text>",me).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Computers and Electronics")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",It).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",de).option("--accumulated-depreciation <n>","Depreciation already incurred",It).option("--residual <n>","Residual/salvage value",It).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--input <file>","Read full transfer body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(Z("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.accumulatedDepreciation!==void 0&&(i.bookValueAccumulatedDepreciationAmount=n.accumulatedDepreciation),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.notes&&(i.internalNotes=n.notes)),n.finalize&&(i.saveAsDraft=!1);let o=await A8(r,i);if(pe(r,"transfer_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(Syt(i,"transferred")))})),t.command("discard <resourceId>").description("Discard (write off) a fixed asset").option("--jot <text>",me).option("--disposal-date <date>","Disposal date (YYYY-MM-DD)").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{(!n.disposalDate||!n.depreciationEndDate)&&(console.error(Z("--disposal-date and --depreciation-end-date are required.")),process.exit(1));let o=await m8(i,r,{disposalDate:n.disposalDate,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount});if(pe(i,"discard_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${r} discarded.`))})(n)),t.command("undo-disposal <resourceId>").description("Undo a fixed asset disposal").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await g8(i,r);if(pe(i,"undo_fixed_asset_disposal",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Disposal undone for ${r}.`))})(n)),t.command("close-out <resourceId>").description("Stop depreciating from a month while keeping the asset (reverse with reopen)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Last month to depreciate (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await y8(i,r,n.date);if(pe(i,"close_out_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out fixed asset").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await E8(i,r);if(pe(i,"reopen_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Fixed asset ${r} reopened.`))})(n)),t.command("totals").description("Asset register totals (purchase amount, accumulated depreciation, net book value)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await I8(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("disposal-totals").description("Disposed asset totals (book value, sale proceeds, gain/loss; positive = loss)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await C8(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One asset's depreciation schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await v8(i,r,n.viewDate);console.log(JSON.stringify(qW(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("preview-schedule").description("Check a custom depreciation schedule and show its timeline; saves nothing (save only when status is FULLY_SCHEDULED with no errors)").option("--input <file>","JSON body: { depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule: [{ fromPeriod, toPeriod, amount }] }").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error(Z("--input <file> is required (JSON with depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule).")),process.exit(1));let o=await _8(r,i);console.log(JSON.stringify(gd(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("calculate-disposal <resourceId>").description("Accumulated depreciation at disposal, before mark-sold or discard; saves nothing").option("--depreciation-end-date <YYYY-MM-DD>","Final depreciation date (the one you will send to sell or discard)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.depreciationEndDate||(console.error(Z("--depreciation-end-date is required.")),process.exit(1));let o=await w8(i,r,n.depreciationEndDate);console.log(JSON.stringify(o.data,null,2))})(n)),Fe({parent:t,commandName:"eligible-lines",fields:KR,defaults:XR,fetcher:S8,columns:Z1r,label:"Searching bill lines eligible to register as assets"}),Fe({parent:t,commandName:"types",fields:ZR,defaults:eT,fetcher:D8,columns:eQr,label:"Searching asset types"}),t.command("bulk-upsert").description("Create or update fixed assets in bulk (max 500). Natural key: reference. Each row requires reference, registrationType (NEW | TRANSFER), a typeCode and a depreciationStartDate (epoch ms). Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await R8(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk upsert started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update fixed assets in bulk (max 500). Each row is resourceId plus only the fields to change; the stored asset is merged in first (tags take { add, remove }). Unknown or repeated resourceIds fail the whole call. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await b8(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}jn();an();xl();Be();hq();hv();nt();gt();zt();Bt();var tQr=[{key:"resourceId",header:"ID",format:De},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"deferralAmount",header:"Amount",align:"right",format:Rr},{key:"remainingAmount",header:"Remaining",align:"right",format:Rr}],rQr=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Contact"},{key:"documentResourceId",header:"Document ID",format:De}],nQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}],iQr=[{key:"accountResourceId",header:"ID",format:De},{key:"accountCode",header:"Code"},{key:"accountName",header:"Name"},{key:"category",header:"Category"}];function Ryt(e){let t=e.command("deferrals").description("Manage deferrals: prepaid expenses and deferred revenue released over months");t.command("get <resourceId>").description("Get deferral details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await Gg(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Category:"),s.category),console.log(S("Amount:"),s.deferralAmount),console.log(S("Remaining:"),s.remainingAmount),console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:tT,defaults:rT,fetcher:X2,columns:tQr,label:"Searching deferrals",extraParams:nT}),t.command("create").description("Create a deferral over eligible bill, invoice or journal lines (a draft unless --activate)").option("--jot <text>",me).option("--ref <reference>","Reference (required; see `clio references next DEFERRAL`)").option("--line <id...>","sourceLineResourceId from `clio deferrals eligible-lines` (one document, one account; required with --activate)").option("--type <typeCode>","Type code from `clio deferrals types`").option("--name <name>","Deferral name").option("--start <YYYY-MM-DD>","Amortization start date (on or after the document date)").option("--months <n>","Effective life in whole months",de).option("--amortization-account <id>","Expense (prepaid) or Revenue (deferred revenue) account resourceId").option("--notes <text>","Internal notes").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--activate","Post the whole schedule now (saveAsDraft: false); needs --line, --type, --name, --start, --months and --amortization-account").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);if(!i){let a=(n.activate?[["--ref",n.ref],["--line",n.line],["--type",n.type],["--name",n.name],["--start",n.start],["--months",n.months],["--amortization-account",n.amortizationAccount]]:[["--ref",n.ref]]).filter(([,u])=>u===void 0).map(([u])=>u);a.length>0&&(console.error(Z(`Required${n.activate?" with --activate":""}: ${a.join(", ")}`)),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1));let c={reference:n.ref,sourceLineResourceIds:n.line,typeCode:n.type,name:n.name,amortizationStartDate:n.start,effectiveLife:n.months,amortizationAccountResourceId:n.amortizationAccount};i=Object.fromEntries(Object.entries(c).filter(([,u])=>u!==void 0)),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])}n.activate&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=Nr(n.customFields));let o=await Z2(r,i);if(pe(r,"create_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(o.data.status==="DRAFT"?"Deferral saved as a draft (nothing posted).":"Deferral created, active and posted: the whole schedule is on the books.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a deferral (partial) or activate a draft").option("--jot <text>",me).option("--ref <reference>","Reference (default: the stored one)").option("--name <name>","New name").option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",de).option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=ye(n),s;o?s=o:(s={},n.ref!==void 0&&(s.reference=n.ref),n.name!==void 0&&(s.name=n.name),n.start!==void 0&&(s.amortizationStartDate=n.start),n.months&&(s.effectiveLife=n.months),n.notes!==void 0&&(s.internalNotes=n.notes),n.activate&&(s.isDraftToActive=!0)),n.customFields&&(s.customFields=Nr(n.customFields));let{tags:a,...c}=s,u=Xn(a),d=u&&await Xi("deferral",r,()=>Gg(i,r)),f=await eq(i,r,{...c,...u&&{tags:ui(d?.tags,u)}},d||void 0);if(pe(i,"update_deferral",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(Q(s.isDraftToActive===!0?`Deferral ${r} activated: its schedule is posted.`:`Deferral ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a deferral of any status (removes every posted row, frees the lines)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await tq(i,r),pe(i,"delete_deferral",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Deferral ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop releasing after a date. Posts nothing: the remaining balance stays on the deferral account (reverse with reopen)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Close-out date, used as given").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await rq(i,r,n.date);if(pe(i,"close_out_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Deferral ${r} closed out. The remaining balance stays on the deferral account.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out deferral").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await nq(i,r);if(pe(i,"reopen_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Deferral ${r} reopened.`))})(n)),t.command("totals").description("Register totals for one category as at a date (never add the two categories together)").addOption(new lt("--category <cat>","Category").choices([...W2]).makeOptionMandatory()).option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await iq(n,{category:r.category,endDate:r.endDate});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One deferral's release schedule (posted rows only: a draft has none)").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await oq(i,r,n.viewDate);console.log(JSON.stringify(jW(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Fe({parent:t,commandName:"eligible-lines",fields:iT,defaults:oT,fetcher:sq,columns:rQr,label:"Searching bill, invoice and journal lines eligible to defer"}),Fe({parent:t,commandName:"types",fields:sT,defaults:aT,fetcher:aq,columns:nQr,label:"Searching deferral types"}),Fe({parent:t,commandName:"accounts",fields:cT,defaults:lT,fetcher:cq,columns:iQr,label:"Searching deferral accounts",extraParams:uT}),t.command("mark-accounts").description("Mark or unmark chart-of-accounts entries as deferral accounts (changes org setup)").option("--jot <text>",me).option("--account <id...>","Chart of accounts resourceId(s)").option("--unmark","Unmark instead of mark").option("--input <file>",'Read { "accounts": [{ organizationAccountResourceId, deferralAccount }] } from file').option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n),o=i?i.accounts??i:n.account?.map(f=>({organizationAccountResourceId:f,deferralAccount:!n.unmark}));Array.isArray(o)||(console.error(Z("Required: --account <id...> or --input <file>")),process.exit(1)),mt(o,"accounts",500,"accounts");let s=await lq(r,o);if(pe(r,"mark_deferral_accounts",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}let a=o.map(f=>f?.deferralAccount),c=a.filter(f=>f===!0).length,u=a.filter(f=>f===!1).length,d=[c>0&&`${c} account(s) marked as deferral accounts`,u>0&&(c>0?`${u} unmarked`:`${u} account(s) unmarked as deferral accounts`)].filter(Boolean);console.log(Q(`${d.length>0?d.join(", "):`${o.length} account(s) submitted`}.`))})),t.command("preview-schedule").description("Check custom release ranges without saving").option("--amount <n>","Deferral amount (sum of the eligible line amounts)",It).option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",de).option("--schedule <json>","JSON array of { fromPeriod, toPeriod, amount }").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||((n.amount===void 0||!n.start||!n.months||!n.schedule)&&(console.error(Z("Required: --amount, --start, --months, --schedule")),process.exit(1)),i={deferralAmount:n.amount,amortizationStartDate:n.start,effectiveLife:n.months,customSchedule:JSON.parse(n.schedule)});let o=await uq(r,i);console.log(JSON.stringify(gd(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("bulk-upsert").description("Create deferrals in bulk (max 500). Creates only, always ACTIVE, STRAIGHT_LINE, dates YYYY-MM-DD. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await dq(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk create started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update deferrals in bulk (max 500). Each row is partial; resourceId and reference are required per row. Not for tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await fq(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}jn();xl();Be();lAe();hv();nt();gt();zt();Bt();var oQr=[{key:"resourceId",header:"ID",format:De},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status",format:e=>hn(e)},{key:"leaseLiabilityRemaining",header:"Liability",align:"right",format:Rr},{key:"rouNetBookValue",header:"ROU NBV",align:"right",format:Rr}],sQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"}];function aQr(e){return(!/^\d+(\.\d{1,4})?$/.test(e)||Number(e)>=100)&&(console.error(Z(`Error: invalid discount rate: ${e} (% per MONTH, below 100, max 4 decimal places; 6% a year is 0.5)`)),process.exit(1)),Number(e)}function Tyt(e){let t=e.command("leases").description("Manage IFRS 16 leases and hire purchase (the register never posts rent: code rent bills to the current lease liability account)");t.command("get <resourceId>").description("Get lease details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await kE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Type:"),s.typeName),console.log(S("Liability:"),s.leaseLiabilityRemaining),console.log(S("ROU NBV:"),s.rouNetBookValue),console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:dT,defaults:fT,fetcher:x8,columns:oQr,label:"Searching leases",extraParams:pT}),t.command("create").description("Put a lease on the books (a draft unless --finalize). Rent is flat with --rent, stepped with --input.").option("--jot <text>",me).option("--reference <ref>","Lease reference (required; see `clio references next --type LEASE`)").option("--name <name>","Lease name").option("--type <typeCode>","Lease type code (see `clio leases types`; HIRE_PURCHASE for hire purchase)").option("--lessor <contactResourceId>","Lessor contact resourceId").option("--start <YYYY-MM-DD>","Commencement date").option("--term <months>","Lease term in months (1-600)",de).option("--rent <n>","Rent per month for the whole term",It).addOption(new lt("--payment-timing <timing>","ADVANCE (start of month) or ARREARS (end)").choices([...sh])).option("--discount-rate <n>","Discount rate in % per MONTH (6% a year is 0.5)",aQr).option("--rou-account <id>","Right-of-Use Asset account resourceId").option("--accumulated-depreciation-account <id>","Accumulated Depreciation account resourceId").option("--depreciation-expense-account <id>","Depreciation Expense account resourceId").option("--liability-account <id>","Current Lease Liability account resourceId (rent is coded here)").option("--non-current-liability-account <id>","Non-current Lease Liability account resourceId").option("--interest-account <id>","Interest Expense account resourceId (Finance Cost type)").option("--exempt","Short-term or low-value lease exemption (posts nothing)").option("--notes <text>","Internal notes").option("--finalize","Post the lease now (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags); needed for stepped rent, prepaid rent, restoration and ownership").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(n.reference||(console.error(Z("Required: --reference")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1)),n.rent!==void 0&&!n.term&&(console.error(Z("--rent needs --term: the rent is entered for every month of the term.")),process.exit(1)),i={reference:n.reference},n.name&&(i.name=n.name),n.type&&(i.typeCode=n.type),n.lessor&&(i.contactResourceId=n.lessor),n.start&&(i.commencementDate=n.start),n.term&&(i.leaseTerm=n.term),n.rent!==void 0&&(i.customSchedule=[{fromPeriod:1,toPeriod:n.term,amount:n.rent}]),n.paymentTiming&&(i.paymentTiming=n.paymentTiming),n.discountRate!==void 0&&(i.discountRate=n.discountRate),n.rouAccount&&(i.rouAssetAccountResourceId=n.rouAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.liabilityAccount&&(i.leaseLiabilityAccountResourceId=n.liabilityAccount),n.nonCurrentLiabilityAccount&&(i.leaseLiabilityNonCurrentAccountResourceId=n.nonCurrentLiabilityAccount),n.interestAccount&&(i.interestExpenseAccountResourceId=n.interestAccount),n.exempt&&(i.exemptionType="EXEMPT"),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])),n.finalize&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=Nr(n.customFields));let o=await k8(r,i);if(pe(r,"create_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}let s=i.exemptionType==="EXEMPT";console.log(Q(i.saveAsDraft!==!1?"Lease saved as a draft. Nothing is posted until it is activated.":s?"Lease registered as exempt. Nothing is posted.":"Lease created, active and posted.")),console.log(S("ID:"),o.data.resourceId),console.log(S("Liability:"),o.data.leaseLiabilityAmount??U("-")),console.log(S("ROU asset:"),o.data.rouAssetAmount??U("-"))})),t.command("update <resourceId>").description("Edit or activate a lease (partial). A schedule change on an ACTIVE lease rewrites every entry from the start date.").option("--jot <text>",me).option("--reference <ref>","Reference (default: the stored one)").option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read the update body from JSON file (overrides flags); needed for schedule fields. tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let s=ye(n)??{...n.reference!==void 0&&{reference:n.reference},...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}};n.customFields&&(s.customFields=Nr(n.customFields));let{tags:a,...c}=s,u=Xn(a),d=u&&await Xi("lease",r,()=>kE(i,r)),f=await N8(i,r,{...c,...u&&{tags:ui(d?.tags,u)}},d||void 0);if(pe(i,"update_lease",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(Q(s.isDraftToActive!==!0?`Lease ${r} updated.`:f.data.exemptionType==="EXEMPT"?`Lease ${r} is now active as exempt. Nothing is posted.`:`Lease ${r} is now active and posted.`))})(n)),t.command("delete <resourceId>").description("Delete a lease of any status (removes every posted entry)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await B8(i,r),pe(i,"delete_lease",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Lease ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting after a month while the liability and right-of-use asset stay on the books (not an exit: use terminate)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Last month to post (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await O8(i,r,n.date);if(pe(i,"close_out_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Lease ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out lease").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await F8(i,r);if(pe(i,"reopen_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Lease ${r} reopened.`))})(n)),t.command("calculate-termination <resourceId>").description("Preview a termination: liability and right-of-use value removed, and the gain or loss (positive = gain). Saves nothing.").option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await Q8(i,r,n.date);console.log(JSON.stringify(o.data,null,2))})(n)),t.command("terminate <resourceId>").description("Take a lease off the books at a month-end, posting the gain or loss (run calculate-termination first)").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--gain-loss-account <id>","Gain/loss account resourceId (required when the gain or loss is not 0)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await L8(i,r,{terminationDate:n.date,terminationGainLossAccountResourceId:n.gainLossAccount});if(pe(i,"terminate_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Lease ${r} terminated.`))})(n)),t.command("undo-termination <resourceId>").description("Undo a termination").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await P8(i,r);if(pe(i,"undo_lease_termination",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Termination undone for ${r}.`))})(n)),t.command("totals").description("Lease liability (current and non-current) and right-of-use net book value as at a date, from the schedule").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await M8(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One lease's schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First month to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await U8(i,r,n.viewDate);console.log(JSON.stringify($W(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Fe({parent:t,commandName:"types",fields:hT,defaults:mT,fetcher:$8,columns:sQr,label:"Searching lease types"}),t.command("preview-rent").description("Check rent ranges against the term (COMPLETE or INCOMPLETE). Body: { commencementDate, leaseTerm, customSchedule }.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error("Error: --input <file> is required (JSON with commencementDate, leaseTerm, customSchedule)"),process.exit(1));let o=await q8(r,i);console.log(JSON.stringify(gd(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("flat-rate").description("Hire purchase: convert a flat annual rate into the monthly discount rate and instalments. Saves nothing.").requiredOption("--rate <n>","Flat rate, % per year",Number).requiredOption("--financed <n>","Financed amount (cash price less down payment)",It).requiredOption("--term <months>","Term in months (1-600)",de).addOption(new lt("--payment-timing <timing>","ADVANCE or ARREARS (default ARREARS)").choices([...sh])).option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await j8(n,{flatRate:r.rate,financedAmount:r.financed,leaseTerm:r.term,paymentTiming:r.paymentTiming});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("bulk-update").description("Update leases in bulk (max 500): each row is partial and needs resourceId and reference. Not for rent or tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(r,n)=>{let i=ye(n);i||(console.error('Error: --input <file> is required (JSON with { "leases": [...] })'),process.exit(1));let o=i.leases??i;Array.isArray(o)||(console.error('Error: expected { "leases": [...] }'),process.exit(1));let s=await Y8(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(Q(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}Be();kAe();hv();xl();nt();gt();mn();zt();Ht();Bt();var cQr=[{key:"resourceId",header:"ID",format:De},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"outstandingPrincipal",header:"Outstanding",align:"right",format:Rr}],lQr=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"status",header:"Status"}],xyt="TERM or INSTALLMENT",c0=["--opening-balance <n>","Principal you confirm on the date after a missed, late or partial payment","openingBalance",It],uQr=[{name:"drawdown",event:"drawdown",tool:"record_loan_drawdown",description:"Raise the principal of a term loan on a date (a second tranche)",flags:[["--date <YYYY-MM-DD>","Drawdown date","drawdownDate"],["--amount <n>","Amount drawn","amount",It],["--keep <keep>",`${xyt} (default TERM)`,"keep"],c0],required:["drawdownDate","amount"]},{name:"prepay",event:"prepayment",tool:"prepay_loan",description:"Reduce principal with an extra repayment; the register posts no cash",flags:[["--date <YYYY-MM-DD>","Prepayment date","prepaymentDate"],["--amount <n>","Amount prepaid","amount",It],["--keep <keep>","INSTALLMENT keeps the monthly payment (term shortens), TERM keeps the term","keep"],c0],required:["prepaymentDate","amount","keep"]},{name:"change-rate",event:"rateChange",tool:"change_loan_rate",description:"The lender changed the rate from a date (never use update for this)",flags:[["--date <YYYY-MM-DD>","Effective date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR (7.25 = 7.25% a year)","annualInterestRate",Number],["--keep <keep>",xyt,"keep"],c0],required:["effectiveDate","annualInterestRate","keep"]},{name:"capitalize",event:"capitalization",tool:"capitalize_loan_interest",description:"Add one installment's whole interest to the principal",flags:[["--date <YYYY-MM-DD>","An installment due date","capitalizationDate"],c0],required:["capitalizationDate"]},{name:"payment-holiday",event:"paymentHoliday",tool:"record_loan_payment_holiday",description:"Skip installments (skipped interest is added to the balance)",flags:[["--from-period <n>","First skipped installment (periodNumber)","fromPeriod",de],["--to-period <n>","Last skipped installment","toPeriod",de],["--treatment <t>","ADD_INTEREST_TO_BALANCE (end date stays) or EXTEND_TERM","treatment"],c0],required:["fromPeriod","toPeriod","treatment"]},{name:"restructure",event:"restructure",tool:"restructure_loan",description:"New terms from an installment due date; 10% or more ends the loan and creates a new one",flags:[["--date <YYYY-MM-DD>","An installment due date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR","annualInterestRate",Number],["--term <months>","Installments left after the date","loanTerm",de],["--installment <n>","The lender's new installment","installmentOverride",It],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"],c0],required:["effectiveDate"]},{name:"settle",event:"settlement",tool:"settle_loan",description:"End a loan early; use --preview for the payoff figure",flags:[["--date <YYYY-MM-DD>","Settlement date","settlementDate"],["--penalty <n>","Lender's penalty (quoted only)","penaltyAmount",It]],required:["settlementDate"]},{name:"forgive",event:"forgiveness",tool:"forgive_loan",description:"Write off the whole loan (gain above 0)",flags:[["--date <YYYY-MM-DD>","Forgiveness date","forgivenessDate"],["--amount <n>","The whole outstanding principal","amount",It],["--forgiven-by <who>","LENDER or SHAREHOLDER","forgivenBy"],["--equity-account <id>","Equity account, for SHAREHOLDER","equityAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["forgivenessDate","amount","forgivenBy"]},{name:"convert",event:"conversion",tool:"convert_loan_to_shares",description:"Convert the whole loan into shares (IFRIC 19)",flags:[["--date <YYYY-MM-DD>","Conversion date","conversionDate"],["--fair-value <n>","Fair value of the shares","fairValue",It],["--share-capital-account <id>","Shareholders Equity account","shareCapitalAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["conversionDate","fairValue","shareCapitalAccountResourceId"]},{name:"refinance",event:"refinance",tool:"refinance_loan",description:"Settle the loan and create a new active one; returns the NEW loan. --input: { refinanceDate, newLoan: {...} }",flags:[["--date <YYYY-MM-DD>","Refinance date","refinanceDate"]],required:["refinanceDate","newLoan"]},{name:"reclassify-current",event:"reclassifyAsCurrent",tool:"reclassify_loan_as_current",description:"Make the whole balance current from a covenant breach date (IAS 1.74)",flags:[["--date <YYYY-MM-DD>","Breach date","reclassificationDate"],["--waiver-date <YYYY-MM-DD>","Date the bank waived it","waiverDate"]],required:["reclassificationDate"]},{name:"undo",event:"undo",tool:"undo_loan_event",description:"Reverse the latest event (see `clio loans events` for the id and canUndo)",flags:[["--event <resourceId>","The latest event resourceId","eventResourceId"]],required:["eventResourceId"]}];function O9(e){console.error(Z(e)),process.exit(1)}var kyt=e=>e.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(t,r)=>r.toUpperCase());function dQr(e,t){let r="calculate"in uO[t.event],n=e.command(`${t.name} <resourceId>`).description(r?`${t.description}. --preview shows the figures and saves nothing`:t.description);n.option("--jot <text>",me);for(let[i,o]of t.flags)n.option(i,o);r&&n.option("--preview","Calculate only: nothing is saved"),n.option("--input <file>","Read the whole event body from JSON file (not with the event flags)").option("--api-key <key>","API key").option("--json","JSON output").action((i,o)=>N(async s=>{let a=o.preview===!0;a&&o.jot!==void 0&&O9("--jot records the judgment behind a recorded event; a preview records nothing.");let c=ye(o),u=t.flags.filter(([p])=>o[kyt(p)]!==void 0).map(([p])=>p.split(" ")[0]);if(c&&u.length>0&&O9(`${u.join(", ")} would be ignored: --input supplies the whole body. Use the flags or --input, not both.`),!c){c={};for(let[p,,h,m]of t.flags){let A=o[kyt(p)];A!==void 0&&(c[h]=m?m(A):A)}}let d=t.required.filter(p=>c[p]===void 0);d.length>0&&(console.error(Z(`Required: ${d.join(", ")}`)),console.error(U("Pass the flags, or --input <file> with the full JSON body.")),process.exit(1));let f=await o4(s,t.event,i,c,a);if(a||pe(s,t.tool,o,f.data),o.json){console.log(JSON.stringify(f.data,null,2));return}console.log(a?Se("Preview only, nothing saved."):Q(`${t.name}: recorded on loan ${i}.`)),console.log(JSON.stringify(f.data,null,2))})(o))}function Nyt(e){let t=e.command("loans").description("Manage loans (borrowings): term and on demand, with their events");Fe({parent:t,fields:AT,defaults:gT,fetcher:YW,columns:cQr,label:"Searching loans",extraParams:yT}),Fe({parent:t,commandName:"types",fields:ET,defaults:bT,fetcher:HW,columns:lQr,label:"Searching loan types"}),t.command("get <resourceId>").description("Get a loan with its figures as of today").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await UE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Kind:"),s.kind),console.log(S("Rate (% a year):"),s.annualInterestRate),console.log(S("Outstanding principal:"),s.outstandingPrincipal),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a loan (a draft that posts nothing unless --activate). The register posts no cash: record the drawdown and every installment yourself. Body is a JSON file; run `loans preview-schedule` first.").option("--jot <text>",me).option("--input <file>","JSON body: reference, kind, typeCode, name, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, accounts...").option("--activate","Activate immediately (saveAsDraft: false)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error(Z("--input <file> is required (JSON with reference and the loan terms).")),process.exit(1)),n.activate&&(i.saveAsDraft=!1);let o=await zW(r,i);if(pe(r,"create_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(i.saveAsDraft===!1?"Loan created, active and posted. The register posts no cash: record the drawdown and every installment yourself.":"Loan saved as a draft. Nothing is posted until it is activated.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a loan (partial). A term, fee or account change on an ACTIVE loan rewrites the whole schedule: use an event for a mid-life change").option("--jot <text>",me).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--input <file>",'Read the whole update body from JSON file (not with --name, --notes or --activate). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o={...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}},s=ye(n);s&&Object.keys(o).length>0&&O9("--name, --notes and --activate would be ignored: --input supplies the whole body. Use the flags or --input, not both.");let a=s??o;Object.keys(a).length===0&&O9("Nothing to update: pass --name, --notes, --activate or --input.");let{tags:c,...u}=a,d=Xn(c),f=d&&await Xi("loan",r,()=>UE(i,r)),p=await JW(i,r,{...u,...d&&{tags:ui(f?.tags,d)}},f||void 0);if(pe(i,"update_loan",n,p.data),n.json){console.log(JSON.stringify(p.data,null,2));return}console.log(Q(a.isDraftToActive===!0?`Loan ${r} activated: its schedule is posted.`:`Loan ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a loan in any status (its own ledger rows go; your bank postings stay)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await GW(i,r),pe(i,"delete_loan",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Loan ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting from a month-end; balances stay. Not an exit (use settle). Reverse with reopen").option("--jot <text>",me).option("--date <YYYY-MM-DD>","Close-out date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{n.date||(console.error(Z("--date is required.")),process.exit(1));let o=await VW(i,r,n.date);if(pe(i,"close_out_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Loan ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out loan (earlier events can no longer be undone afterwards)").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await WW(i,r);if(pe(i,"reopen_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q(`Loan ${r} reopened.`))})(n)),t.command("totals").description("What we owe in total: outstanding principal, current, non-current, accrued interest").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>N(async n=>{let i=await KW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("A term loan's repayment schedule").option("--view-date <YYYY-MM-DD>","Rows posted as at this date (default today)").option("--from-period <n>","First installment number to print (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await XW(i,r,n.viewDate);console.log(JSON.stringify(pv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("events <resourceId>").description("A loan's events, latest first (canUndo marks the one that can be undone)").option("--limit <n>","Max results",de).option("--offset <n>","Page number (0-indexed)",tt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await st(n,({limit:s,offset:a})=>ZW(i,r,{limit:s,offset:a}),{label:"Fetching loan events",defaultLimit:20});Ke(o,[{key:"resourceId",header:"ID",format:De},{key:"eventType",header:"Event"},{key:"effectiveDate",header:"Date"},{key:"canUndo",header:"Can undo"}],n,"Loan events")})(n)),t.command("ledger <resourceId>").description("On-demand loans only: advances and repayments with the balance").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--limit <n>","Max results",de).option("--offset <n>","Page number (0-indexed)",tt).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await e4(i,r,{endDate:n.endDate,limit:n.limit,offset:n.offset});console.log(JSON.stringify(o,null,2))})(n)),t.command("preview-schedule").description("The schedule these terms would produce; saves nothing").option("--input <file>","JSON body: kind, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, fees...").option("--from-period <n>","First period to print, from 1 (default: all)",de).option("--to-period <n>","Last period to print, inclusive",de).option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||(console.error(Z("--input <file> is required (JSON with kind, principalAmount, drawdownDate and the terms).")),process.exit(1));let o=await t4(r,i);console.log(JSON.stringify(pv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("opening-balance <resourceId>").description("Suggest an --opening-balance for an event after a missed, late or partial payment; saves nothing").option("--event-type <type>","DRAWDOWN, PREPAYMENT, RATE_CHANGE, CAPITALIZE_INTEREST, PAYMENT_HOLIDAY or RESTRUCTURE").option("--date <YYYY-MM-DD>","Event date (for a holiday, the first skipped due date)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{(!n.eventType||!n.date)&&(console.error(Z("Required: --event-type, --date")),process.exit(1));let o=await r4(i,{resourceId:r,eventType:n.eventType,date:n.date});console.log(JSON.stringify(o.data,null,2))})(n));for(let r of uQr)dQr(t,r);for(let[r,n,i]of[["bulk-upsert","Create ACTIVE loans in bulk (max 500; creates only, dates YYYY-MM-DD, no CUSTOM shape or fees)",n4],["bulk-update","Update loans in bulk (max 500; update per row, reference required on each). Not for tag changes (use update)",i4]])t.command(r).description(`${n}. Returns a jobId; poll with \`clio background-jobs get <jobId>\`.`).option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(N(async(o,s)=>{let a=ye(s);a||(console.error('Error: --input <file> is required (JSON with { "loans": [...] })'),process.exit(1));let c=a.loans??a;Array.isArray(c)||(console.error('Error: expected { "loans": [...] }'),process.exit(1));let u=await i(o,c);s.json?console.log(JSON.stringify(u.data,null,2)):(console.log(Q(`${r} started. Job ID: ${u.data.jobId}`)),console.log(Se(` Poll progress: clio background-jobs get ${u.data.jobId}`)))}))}Be();K8();nt();KS();gt();Bt();zt();var fQr=[{key:"resourceId",header:"ID",format:De},{key:"status",header:"Status",format:e=>String(e)==="ACTIVE"?Q(String(e)):U(String(e))},{key:"interval",header:"Interval"},{key:"totalAmount",header:"Amount",align:"right"},{key:"businessTransactionType",header:"Type"}],pQr=[{key:"resourceId",header:"ID",format:De},{key:"scheduledTransactionType",header:"Type"},{key:"status",header:"Status",format:e=>U(String(e??""))}];function Byt(e){let t=e.command("subscriptions").alias("subs").description("Manage recurring subscriptions");co({parent:t,description:"List subscriptions",columns:fQr,label:"Fetching subscriptions",title:"Subscriptions",fetch:(r,n)=>H8(r,n)}),t.command("get <resourceId>").description("Get subscription details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await NE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Status:"),s.status),console.log(S("Interval:"),s.interval),console.log(S("Amount:"),s.totalAmount),console.log(S("Next:"),cf(s.nextScheduleDate)??"N/A"),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a recurring subscription (invoices only, with proration)").option("--jot <text>",me).option("--interval <interval>","WEEKLY, MONTHLY, QUARTERLY, or YEARLY (required)").option("--start-date <YYYY-MM-DD>","Start date (required)").option("--end-date <YYYY-MM-DD>","End date (optional, omit for ongoing)").option("--contact <name|resourceId>","Customer contact (required)").option("--ref <reference>","Invoice reference").option("--date <YYYY-MM-DD>","Invoice date").option("--due <YYYY-MM-DD>","Due date").option("--account <name|resourceId>","Revenue account \u2014 applied to ALL line items (required)").option("--tax-profile <name|resourceId>","Tax profile \u2014 applied to ALL line items").option("--lines <json>","Line items as JSON array (name, unitPrice, quantity)").option("--amount <n>","Single line item amount (shorthand)",It).option("--line-name <name>","Line item name (used with --amount)").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);if(!i){(!n.interval||!n.startDate)&&(console.error(Z("Required: --interval, --start-date")),console.error(U("Or use --input <file> to provide full JSON body.")),process.exit(1));let s;if(n.lines)try{s=JSON.parse(n.lines)}catch{console.error(Z("Invalid --lines JSON")),process.exit(1)}else n.amount!==void 0&&(s=[{name:n.lineName??"Subscription",unitPrice:n.amount,quantity:1}]);s&&(n.account||n.taxProfile)&&(s=s.map(a=>({...a,...n.account&&!a.accountResourceId?{accountResourceId:n.account}:{},...n.taxProfile&&!a.taxProfileResourceId?{taxProfileResourceId:n.taxProfile}:{}}))),i={repeat:n.interval,startDate:n.startDate,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment"},invoice:{contactResourceId:n.contact,reference:n.ref,valueDate:n.date,dueDate:n.due,lineItems:s,saveAsDraft:!1}},n.endDate&&(i.endDate=n.endDate)}let o=await z8(r,i);if(pe(r,"create_subscription",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(Q("Subscription created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a subscription (the body must carry the invoice template; status is kept when omitted)").option("--jot <text>",me).option("--input <file>","Read full update body from JSON file: `invoice` template required (create shape), optional endDate, repeat, status, proratedConfig").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=ye(n);o||(console.error(Z("Use --input <file> to provide update data.")),process.exit(1));let s=await J8(i,r,o);if(pe(i,"update_subscription",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q(`Subscription ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a subscription").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await G8(i,r),pe(i,"delete_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Subscription ${r} deleted.`))})(n)),t.command("cancel <resourceId>").description("Cancel an active subscription (prorates remaining period)").option("--jot <text>",me).option("--cancel-date-type <type>","END_OF_CURRENT_PERIOD, END_OF_LAST_PERIOD, or CUSTOM_DATE","END_OF_CURRENT_PERIOD").option("--end-date <YYYY-MM-DD>","Custom cancel date (only with CUSTOM_DATE)").option("--prorated-text <text>","Prorated adjustment line text","Prorated adjustment").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await V8(i,r,{cancelDateType:n.cancelDateType,proratedAdjustmentLineText:n.proratedText,endDate:n.endDate}),pe(i,"cancel_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({cancelled:!0,resourceId:r}));return}console.log(Q(`Subscription ${r} cancelled.`))})(n)),Fe({parent:t,commandName:"search-scheduled",fields:IT,defaults:CT,fetcher:W8,columns:pQr,label:"Searching scheduled transactions"})}Be();uAe();nt();gt();Bt();zt();var Oyt=[{key:"resourceId",header:"ID",format:De},{key:"name",header:"Name"}];function Fyt(e){let t=e.command("contact-groups").description("Manage contact groups");co({parent:t,description:"List contact groups",columns:Oyt,label:"Fetching contact groups",title:"Contact Groups",fetch:(r,n)=>X8(r,n)}),t.command("get <resourceId>").description("Get contact group details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await Z8(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Contacts:"),s.associatedContacts?.length??0);for(let a of s.associatedContacts??[])console.log(` ${Se(a.resourceId)} ${a.name}`);console.log(S("ID:"),s.resourceId)})(n)),Fe({parent:t,fields:ax,defaults:cx,fetcher:eW,columns:Oyt,label:"Searching contact groups",positionalArg:"name",positionalFilter:r=>({name:{contains:r}})}),t.command("create").description("Create a contact group").option("--jot <text>",me).option("--name <name>","Group name").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{Me(n,[{flag:"--name",key:"name"}]);let i=await tW(r,{name:n.name});if(pe(r,"create_contact_group",n,i.data),n.json){console.log(JSON.stringify(i.data,null,2));return}console.log(Q(`Contact group "${n.name}" created.`)),console.log(S("ID:"),i.data.resourceId)})),t.command("update <resourceId>").description("Update a contact group").option("--name <name>","New group name").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o={};n.name&&(o.name=n.name);let s=await rW(i,r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q("Contact group updated.")),console.log(S("ID:"),s.data.resourceId)})(n)),t.command("delete <resourceId>").description("Delete a contact group").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await nW(i,r),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Contact group ${r} deleted.`))})(n))}jn();dAe();nt();gt();mn();Ht();Bt();Be();var hQr=[{key:"resourceId",header:"ID",format:De},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"itemCode",header:"Code",format:e=>U(String(e??""))}],mQr=[{key:"itemCode",header:"Code",format:e=>U(String(e??""))},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"totalQuantity",header:"Qty",format:e=>String(e??"")},{key:"baseUnit",header:"Unit",format:e=>String(e??"")},{key:"averageCostAmount",header:"Avg Cost",format:e=>String(e??"")},{key:"balanceAmount",header:"Value",format:e=>String(e??"")}];function Lyt(e){let t=e.command("inventory").alias("inv").description("Inventory management");t.command("items").description("List inventory-tracked items").option("--limit <n>","Max results",de).option("--offset <n>","Page number offset (0-indexed)",tt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=await st(n,o=>iW(r,o),{label:"Fetching inventory items"});Ke(i,hQr,n,"Inventory Items")})),t.command("balance <itemResourceId>").description("Get inventory balance for an item").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o=await sW(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Item:"),s.itemResourceId),console.log(S("Qty:"),`${s.baseQty} ${s.baseUnit}`),console.log(S("Avg Cost:"),s.latestAverageCostAmount)})(n)),t.command("balances").description("List inventory balances across items, by balance status").addOption(new lt("--status <status>","Balance status").choices([...aW]).default("ALL")).option("--limit <n>","Max results",de).option("--offset <n>","Page number offset (0-indexed)",tt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",de).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=n.status,o=await st(n,s=>cW(r,i,s),{label:"Fetching inventory balances"});Ke(o,mQr,n,"Inventory Balances")})),t.command("create").description("Create an inventory-tracked item (use --input for full JSON body)").option("--item-code <code>","Item code (SKU) (required)").option("--name <name>","Item name (required)").option("--unit <unit>","Unit of measure (required)").option("--costing-method <method>","FIXED or WAC (required)").option("--cogs-account <resourceId>","COGS account resourceId, Direct Costs type (required)").option("--purchase-account <resourceId>","Purchase account resourceId, Inventory type (required)").option("--sale-account <resourceId>","Sale account resourceId (required)").option("--block-insufficient","Block transactions when stock is insufficient").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{let i=ye(n);i||Me(n,[{flag:"--item-code",key:"itemCode"},{flag:"--name",key:"name"},{flag:"--unit",key:"unit"},{flag:"--costing-method",key:"costingMethod"},{flag:"--cogs-account",key:"cogsAccount"},{flag:"--purchase-account",key:"purchaseAccount"},{flag:"--sale-account",key:"saleAccount"}]);let o=i??{itemCode:n.itemCode,name:n.name,unit:n.unit,costingMethod:n.costingMethod,cogsResourceId:n.cogsAccount,purchaseAccountResourceId:n.purchaseAccount,saleAccountResourceId:n.saleAccount,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:!!n.blockInsufficient},s=await oW(r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q("Inventory item created.")),console.log(S("ID:"),s.data.resourceId)}))}Be();fAe();nt();gt();Bt();zt();var Qyt=[{key:"resourceId",header:"ID",format:De},{key:"customFieldName",header:"Name"}];function Pyt(e){let t=e.command("custom-fields").description("Manage custom fields");co({parent:t,description:"List custom fields",columns:Qyt,label:"Fetching custom fields",title:"Custom Fields",fetch:(r,n)=>lW(r,n)}),t.command("get <resourceId>").description("Get a custom field by resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let s=(await oO(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Name:"),s.customFieldName||s.name||"(unnamed)"),console.log(S("ID:"),s.resourceId),console.log(S("Type:"),s.datatypeCode||s.fieldType||"\u2014"),s.description&&console.log(S("Description:"),s.description),s.defaultValue&&console.log(S("Default:"),s.defaultValue),s.listOptions?.length&&console.log(S("Options:"),s.listOptions.join(", "));let a=u=>u==="SHOW"||u==="PRINT",c=[];a(s.applyToSales)&&c.push("invoices"),a(s.applyToPurchase)&&c.push("bills"),a(s.applyToSaleCreditNote)&&c.push("customer CNs"),a(s.applyToPurchaseCreditNote)&&c.push("supplier CNs"),a(s.applyToPayment)&&c.push("payments"),a(s.appliesToFixedAssets)&&c.push("fixed assets"),c.length&&console.log(S("Applies to:"),c.join(", "))})(n)),Fe({parent:t,fields:ox,defaults:sx,fetcher:uW,columns:Qyt,label:"Searching custom fields"}),t.command("create").description("Create a custom field").option("--jot <text>",me).option("--name <name>","Field name").option("--description <text>","Field description").option("--print-on-documents","Print this field on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--field-format <fmt>","CUSTOM (default, free text) or ALL_CUSTOMERS / ALL_SUPPLIERS / ALL_CONTACTS / ALL_EMPLOYEES / ALL_USERS for a picklist of that population").option("--api-key <key>","API key").option("--json","JSON output").action(N(async(r,n)=>{Me(n,[{flag:"--name",key:"name"}]);let o=n.invoices||n.bills||n.customerCredits||n.supplierCredits||n.payments?{invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1}:void 0,s=await dW(r,{name:n.name,description:n.description,printOnDocuments:n.printOnDocuments??!1,appliesTo:o,format:n.fieldFormat});if(pe(r,"create_custom_field",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(Q(`Custom field "${n.name}" created.`)),console.log(S("ID:"),s.data.resourceId)})),t.command("update <resourceId>").description("Update a custom field").option("--name <name>","New field name").option("--description <text>","New description").option("--print-on-documents","Print on PDF documents").option("--no-print-on-documents","Do not print on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.description!==void 0&&(o.description=n.description),n.printOnDocuments!==void 0&&(o.printOnDocuments=n.printOnDocuments),(n.invoices!==void 0||n.bills!==void 0||n.customerCredits!==void 0||n.supplierCredits!==void 0||n.payments!==void 0)&&(o.appliesTo={invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1});let a=await fW(i,r,o);if(n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(Q(`Custom field ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a custom field").option("--jot <text>",me).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>N(async i=>{if(await pW(i,r),pe(i,"delete_custom_field",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(Q(`Custom field ${r} deleted.`))})(n))}jn();Be();RAe();nt();gt();Ht();function Myt(e){let t=po(e)??[];if(t.length===0)throw new hr("--ids must contain at least one resourceId (comma-separated).");return t}function Uyt(e,t){if(!e||typeof e!="object")throw new Error(`${t}: the API returned no job handle. The batch may still have been accepted \u2014 check \`clio background-jobs search\` before resending.`);return e}function $yt(e){return JSON.stringify({...e,pollWith:e.jobId?`clio background-jobs get ${e.jobId}`:"clio background-jobs search",note:"Bulk is async. Per-record outcomes exist ONLY in the job, never in this response."},null,2)}function qyt(e,t){console.log(Q(`${t} queued.`)),e.jobId&&console.log(S("Job ID:"),e.jobId),e.totalRecords!==void 0&&console.log(S("Records:"),String(e.totalRecords)),console.log(Se(` Poll progress: clio background-jobs get ${e.jobId??"<jobId>"}`))}function jyt(e,t,r){let n=FW(e);if(t.json){let i=n.state==="approved"?!0:n.state==="refused"?!1:null;console.log(JSON.stringify({entity:r.entity,resourceId:r.resourceId,[r.jsonKey]:i,records:e},null,2))}else n.state==="refused"?console.log(Z(`Not ${r.doneVerb}: ${r.entity} ${r.resourceId} \u2014 ${n.reason}`)):n.state==="unconfirmed"?console.log(Z(`UNCONFIRMED: ${r.entity} ${r.resourceId} \u2014 the API returned no per-record outcome, so this neither succeeded nor failed provably. Re-read the document before recording it.`)):(console.log(Q(`${r.entity} ${r.resourceId} ${r.doneVerb}.`)),e?.[0]&&r.extra?.(e[0]));return n.state!=="approved"?(process.exitCode=1,!1):!0}function Yyt(e){let t=e.command("approvals").description("Approve documents or send them back for changes"),r=n=>new lt("-e, --entity <entity>","Document family").choices([...n]).makeOptionMandatory();t.command("approve <resourceId>").description("Approve one document \u2014 posts its ledger entries and makes it live").addOption(r(ap)).option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>N(async o=>{let s=await LW(o,i.entity,n);jyt(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"approved",doneVerb:"approved",extra:c=>{c.status&&console.log(S("Status:"),c.status)}})&&pe(o,"approve_documents",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-approve").description("Approve up to 100 documents (async \u2014 returns a job)").addOption(r(ap)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-100)").option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>N(async i=>{let o=Myt(n.ids),s=await QW(i,n.entity,o),a=Uyt(s?.data,"bulk approve");n.json?console.log($yt(a)):qyt(a,`Approval of ${o.length} ${n.entity}`),pe(i,"bulk_approve_documents",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n)),t.command("request-changes <resourceId>").description("Send one document back for changes instead of approving it").addOption(r(PE)).requiredOption("-m, --message <text>","Why it is sent back \u2014 opens a thread and is the only record of the reason").option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>N(async o=>{let s=await PW(o,i.entity,n,i.message);jyt(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"sentBack",doneVerb:"sent back for changes",extra:c=>{let u=c.collaborationThreadPath;u&&console.log(S("Thread:"),u)}})&&pe(o,"request_document_changes",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-request-changes").description("Send up to 500 documents back for changes with one message (async \u2014 returns a job)").addOption(r(PE)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-500)").requiredOption("-m, --message <text>","Why they are sent back \u2014 the only record of the reason").option("--jot <text>",me).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>N(async i=>{let o=Myt(n.ids),s=await MW(i,n.entity,o,n.message),a=Uyt(s?.data,"bulk request changes");n.json?console.log($yt(a)):qyt(a,`Request-changes on ${o.length} ${n.entity}`),pe(i,"bulk_request_document_changes",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n))}Be();kre();nt();zt();Bt();var Hyt=[{key:"resourceId",header:"ID",format:De},{key:"name",header:"Name"},{key:"reference",header:"Reference"},{key:"currencyCode",header:"Currency"}];function zyt(e){let t=e.command("purchase-items").description("Browse the purchase-side catalog (read-only)");co({parent:t,description:"List purchase items",columns:Hyt,label:"Fetching purchase items",title:"Purchase Items",offsetMode:qg.offsetMode,fetch:(r,n)=>E2(r,n)}),t.command("get <resourceId>").description("Get a purchase item by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let s=(await b2(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("ID:"),s.resourceId);for(let[a,c]of[["Name","name"],["Reference","reference"],["Currency","currencyCode"]]){let u=s[c];u!=null&&u!==""&&console.log(S(`${a}:`),String(u))}})(n)),Fe({parent:t,fields:vT,defaults:qg,columns:Hyt,label:"Searching purchase items",fetcher:I2})}Gme();nt();DC();Be();gt();Ht();import{readFileSync as Jyt}from"node:fs";import{isAbsolute as AQr}from"node:path";function Gyt(e,t){if(e!==void 0&&t)throw new hr("Pass the query as an argument OR --input <file>, not both.");if(t){let n;try{n=Jyt(t,"utf-8")}catch{throw new hr(`Cannot read --input file: ${t}`)}let i=n.trim();if(!i)throw new hr(`--input file is empty: ${t}`);return i}let r=e?.trim();if(r)return r;if(!process.stdin.isTTY){let n=Jyt(0,"utf-8").trim();if(n)return n}throw new hr("A query is required. Pass it as an argument, --input <file>, or on stdin.")}var gQr=new Set(["numeric","int","int8","bigint","float8","double precision"]);function yQr(e){return e.map((t,r)=>({key:String(r),header:t.name,align:gQr.has(t.type)?"right":"left"}))}function EQr(e,t){return t.map(r=>Object.fromEntries(e.map((n,i)=>[String(i),r[n.name]])))}function Vyt(e){let t=e.command("pseudo-sql").alias("sql").description("Read-only queries over Jaz's curated reporting tables (a restricted SQL subset, not your database)");t.command("preview [query]").description("Run a SELECT and print up to 100 rows").option("--input <file>","Read the query from a file instead of an argument").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let s=(await HV(i,Gyt(r,n.input))).data;if(n.json){console.log(JSON.stringify(s,null,2));return}for(let u of s.warnings??[])console.error(Te("Warning:"),u);if(!Array.isArray(s.rows)||!Array.isArray(s.columns))throw new Error("pseudo-sql preview: upstream returned no rows/columns array");if(s.rows.length===0){console.log(U("No rows."));return}let c=s.columns.slice(0,8);console.log(Gs(EQr(c,s.rows),yQr(c))),s.columns.length>c.length&&console.log(U(`Showing ${c.length} of ${s.columns.length} columns \u2014 use --json for all`)),console.log(U(`${s.rowCount} row(s)${s.truncated?" \u2014 `clio sql export` returns the full set":""}`))})(n)),t.command("export [query]").description("Export a SELECT to CSV (waits for the job by default)").option("--input <file>","Read the query from a file instead of an argument").option("--out <path>","Absolute path to write the CSV to (implies download)").option("--download","Download the CSV to ~/Downloads instead of printing the URL").option("--no-wait","Return the jobId immediately; poll with `export-status`").option("--timeout <seconds>","How long to wait for the job (default 25, max 90)",de).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let o=Gyt(r,n.input);if(n.wait===!1){let u=[["--out",n.out],["--download",n.download],["--timeout",n.timeout]].filter(([,d])=>d!==void 0).map(([d])=>d);if(u.length)throw new hr(`--no-wait cannot be combined with ${u.join(", ")} \u2014 it returns before the export runs. Drop --no-wait, or poll with \`clio sql export-status <jobId>\`.`)}if(n.out&&!AQr(n.out))throw new hr(`--out must be an absolute path; got "${n.out}".`);if(n.wait===!1){let u=await WB(i,o,{idempotencyKey:Jme(o)});if(n.json){console.log(JSON.stringify(u.data,null,2));return}console.log(Q("Export started")),console.log(S("Job:"),u.data.jobId,U(`(${u.data.status})`)),console.log(U(`Poll with: clio sql export-status ${u.data.jobId}`));return}typeof n.timeout=="number"&&n.timeout>90&&console.error(Te(`--timeout ${n.timeout} exceeds the 90s ceiling; waiting 90s. Use --no-wait for a longer job.`));let s=!!(n.download||n.out),c=(await zV(i,o,{timeoutSeconds:n.timeout,downloadToFile:s,outPath:n.out})).data;if(n.json){let{buffer:u,...d}=c;console.log(JSON.stringify(d,null,2));return}if(c.status==="TIMED_OUT"){console.error(Te("Still running."),U(`Poll with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(c.status!=="COMPLETED"){console.error(Z(`Export ${c.status}`),c.error??""),process.exitCode=1;return}if(c.error){console.error(Z("Export completed but the download failed:"),c.error),console.error(U(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(!c.localPath&&!c.downloadUrl){console.error(Z("Export reported COMPLETED but returned no file and no URL.")),console.error(U(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}console.log(Q("Export ready")),c.rowCount!==void 0&&console.log(S("Rows:"),String(c.rowCount)+(c.truncated?U(" \u2014 more rows match than the LIMIT returned"):"")),c.localPath?console.log(S("Saved:"),c.localPath):c.downloadUrl&&console.log(S("URL:"),c.downloadUrl,U("(expires in ~15 min)"))})(n)),t.command("export-status <jobId>").description("Poll an export job").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let s=(await ev(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Status:"),s.status),s.rowCount!==void 0&&console.log(S("Rows:"),String(s.rowCount)),s.downloadUrl&&console.log(S("URL:"),s.downloadUrl,U("(expires in ~15 min)")),s.error?(console.error(Z("Error:"),s.error),process.exitCode=1):(s.status==="FAILED"||s.status==="EXPIRED")&&(process.exitCode=1)})(n)),t.command("schema [table]").description("Show the curated catalog: tables, columns, joins").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let{data:o}=await tv(i),s=JV(o,r),a=s.scopedTo?.toLowerCase();if(n.json){console.log(JSON.stringify(s,null,2));return}if(a){let c=s.tables[0];if(console.log(S(c.name),U(c.label??"")),console.log(Gs((c.columns??[]).map(u=>({column:u.name,type:u.type})),[{key:"column",header:"Column"},{key:"type",header:"Type"}])),s.joins.length){console.log(`
1083
1084
  ${S("Joins")}`);for(let u of s.joins)console.log(` ${u.leftTable}.${u.leftColumn} = ${u.rightTable}.${u.rightColumn}`)}return}console.log(Gs(s.tables.map(c=>({table:c.name,label:c.label,columns:(c.columns??[]).length})),[{key:"table",header:"Table"},{key:"label",header:"Label"},{key:"columns",header:"Cols",align:"right"}])),console.log(U(`${s.tableCount} tables \xB7 ${s.joinCount} joins \xB7 ${s.functionCount} functions \xB7 version ${s.version}`))})(n)),t.command("syntax").description("Print the pseudo-SQL syntax guide").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(r=>N(async n=>{let{data:i}=await tv(n),o=i.agentSkillsDoc;if(r.json){console.log(JSON.stringify(o,null,2));return}console.log(o.content)})(r))}xre();nt();Bt();Be();function Wyt(e){return Array.isArray(e)?e.length?e.join(", "):"-":e!==null&&typeof e=="object"?JSON.stringify(e):String(e)}var bQr=[{key:"resourceId",header:"ID",format:De},{key:"code",header:"Code"},{key:"privileged",header:"Privileged"},{key:"roleCodes",header:"Roles",format:Wyt}];function Kyt(e){let t=e.command("modules").alias("features").description("Show which features are enabled for the organization, and which roles may use them (read-only)");co({parent:t,description:"List enabled modules",columns:bQr,label:"Fetching modules",title:"Modules",fetch:(r,n)=>g2(r,n)}),t.command("get <resourceId>").description("Get a module by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let s=(await y2(i,r))?.data;if(!s)throw new Error(`modules get: upstream returned no record for ${r}`);if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("ID:"),s.resourceId),J$(s,[["Code","code"],["Privileged","privileged"]]),s.roleCodes!==void 0&&s.roleCodes!==null&&(console.log(S("Roles:"),Wyt(s.roleCodes)),console.log(U("A module can be enabled and still deny you \u2014 access is per role.")))})(n))}Mx();Yu();Jq();zt();nt();Ht();gt();Bt();Be();import{readFileSync as IQr,writeFileSync as Xyt}from"node:fs";var Zyt=[{key:"resourceId",header:"ID",format:De},{key:"templateName",header:"Name"},{key:"reportType",header:"Type"},{key:"isDefault",header:"Default"}],F9="<template>",L9="resourceId or exact name";function rEt(e,t){let r;try{r=IQr(e,"utf-8")}catch{throw new hr(`${t}: cannot read ${e}`)}try{return JSON.parse(r)}catch{throw new hr(`${t}: ${e} is not valid JSON`)}}function CQr(e){let t=e.indexOf("=");if(t<=0)throw new hr(`--set takes path=value (got "${e}"), e.g. --set pdfTitleConfigs.title="Monthly P&L"`);let r=e.slice(t+1);return{op:"set",path:e.slice(0,t).trim(),value:r,fromText:!0}}function _Qr(e){let t=[];if(e.edits){let r=rEt(e.edits,"--edits");if(!Array.isArray(r))throw new hr("--edits must be a JSON array of edits");t.push(...r)}for(let r of e.set??[])t.push(CQr(r));for(let r of e.remove??[])t.push({op:"remove",path:r});return t.length>0?t:void 0}function eEt(e){return e.option("--config-file <path>","The whole layout, from a JSON file (e.g. one written by get --config-out)").option("--set <path=value>",'Change one layout value, e.g. pdfTitleConfigs.title="Monthly P&L"; read as the kind already stored there (repeatable)',Ag,[]).option("--remove <path>","Remove one layout value (repeatable)",Ag,[]).option("--edits <path>",`A JSON file with a list of edits (${LC.join(", ")})`).option("--report <template>","REPORT_PACK: a report in the pack, by resourceId or name (repeat, in order)",Ag,[])}function tEt(e){let t=e.report;return{templateConfiguration:e.configFile?rEt(e.configFile,"--config-file"):void 0,edits:_Qr(e),packTemplates:t&&t.length>0?t:void 0}}function Q9(e,t,r){if(r){console.log(JSON.stringify(t,null,2));return}for(let u of t.partialFailures??[])console.log(Te(u));let n=t.template,i=n?.templateName??t.templateName,o=n?.reportType??t.reportType;console.log(Q(`Report template ${e}: ${i?`${i} (${o}), `:""}${t.resourceId}`)),n?.isDefault&&console.log(U(`It is the default ${n.reportType} template.`));let s=t.previousDefault;s&&console.log(U(`Was the default: ${s.templateName} (${s.resourceId}). Undo: clio report-templates set-default ${s.resourceId}`));let a=t.removedFromPacks;a?.length&&console.log(U(`Also removed from: ${a.map(u=>u.templateName).join(", ")}`));let c=t.newDefault;c&&console.log(U(`Default pack is now: ${c.templateName}`)),t.notSaved?.length&&console.log(Te(`Saved, but the server did not keep: ${t.notSaved.join(", ")}. That part of the layout is not something this report type stores.`))}function nEt(e){let t=e.command("report-templates").description("Report templates: the saved layout of each report, and report packs");t.command("list").description("List every report template (returns all at once; no layouts)").option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(r=>N(async n=>{let i=await Gq(n);Ke({data:i.data,totalElements:i.totalElements,totalPages:i.totalPages,truncated:i.totalElements>i.data.length},Zyt,r,"Report Templates")})(r)),t.command(`get ${F9}`).description(`Read a report template and its layout (${L9})`).option("--keys <list>","Only these top-level layout keys, comma-separated (e.g. pdfTitleConfigs,columnConfigs)").option("--row <rowId>",`Only this row, children included (${NC.join(", ")})`).option("--config-out <path>","Write the layout to a JSON file, ready to edit and pass back with update --config-file").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON (includes the whole layout)").action((r,n)=>N(async i=>{let o=n.keys?n.keys.split(",").map(c=>c.trim()).filter(Boolean):void 0;if(n.configOut&&(o||n.row))throw new hr("--config-out writes the WHOLE layout, to edit and pass back with update --config-file; it cannot be combined with --keys or --row.");let s=await Wq(i,r,{keys:o,row:n.row,whole:!0});if(n.row&&!n.json&&!o){console.log(JSON.stringify(s.row,null,2));return}if(n.configOut&&Xyt(n.configOut,`${JSON.stringify(s.templateConfiguration??{},null,2)}
1084
1085
  `),n.json){console.log(JSON.stringify(s,null,2));return}if(console.log(S("ID:"),s.resourceId),J$(s,[["Name","templateName"],["Type","reportType"],["Category","reportCategory"],["Pack","reportPackType"],["Default","isDefault"]]),s.packTemplates?.length){console.log(S("Reports:"));for(let c of s.packTemplates)console.log(` ${c.templateOrder}. ${c.templateName??c.templateResourceId} (${c.reportType??""})`)}if(o){console.log(JSON.stringify(s.templateConfiguration,null,2));return}let a=Object.keys(s.templateConfiguration??{});console.log(U(`Layout: ${s.configurationChars} characters, keys: ${a.join(", ")}`)),console.log(U(n.configOut?`Layout written to ${n.configOut}`:"Read part of it with --keys, or all of it with --json or --config-out <file>."))})(n)),Fe({parent:t,fields:BT,defaults:OT,columns:Zyt,label:"Searching report templates",fetcher:Vq}),t.command("default-config").description("The system default layout a new template starts from").requiredOption("--type <reportType>",`Report type: ${jg.join(", ")}`).option("--framework <framework>",`For ${Yg.join(", ")}; defaults exist for ${Sh.join(" and ")}`).option("--out <path>","Write the layout to a JSON file").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(r=>N(async n=>{let i=await PC(n,r.type,r.framework);if(r.out&&(Xyt(r.out,`${JSON.stringify(i.templateConfiguration,null,2)}
1085
1086
  `),!r.json)){console.log(Q(`Default ${i.reportType} layout written to ${r.out}`));return}console.log(JSON.stringify(r.json?i:i.templateConfiguration,null,2))})(r)),eEt(t.command("create").description("Create a report template from the default layout (or --config-file), with any edits applied. Not made the default.").requiredOption("--name <name>","Template name, unique within its report type").requiredOption("--type <reportType>",`Report type: ${ws.join(", ")}`).option("--framework <framework>",`For ${Yg.join(", ")}; picks the starting layout of ${fUe.join(" and ")} (${Sh.join(" and ")} have one)`)).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(r=>N(async n=>{let i=await Kq(n,{templateName:r.name,reportType:r.type,framework:r.framework,...tEt(r)});Q9("created",i,r.json)})(r)),eEt(t.command(`update ${F9}`).description(`Rename a report template, change its layout, or change a pack's reports (${L9})`).option("--name <name>","New name")).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let o=await Xq(i,r,{templateName:n.name,...tEt(n)});Q9("updated",o,n.json)})(n)),t.command(`set-default ${F9}`).description(`Make a template the default of its report type, for every export and dashboard view (${L9})`).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let o=await Zq(i,r);if(o.alreadyDefault&&!n.json){console.log(U(`${o.template?.templateName} is already the default ${o.template?.reportType} template. Nothing changed.`));return}Q9("set as default",o,n.json)})(n)),t.command(`delete ${F9}`).description(`Delete a report template (${L9}). Refused for a default, and for the last report in a pack.`).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>N(async i=>{let o=await ej(i,r);Q9("deleted",o,n.json)})(n))}jn();Aee();pee();DC();Ht();Be();var wQr=[{key:"key",header:"Destination"},{key:"label",header:"Label",format:e=>{let t=String(e??"");return t.length>28?`${t.slice(0,27)}\u2026`:t}}];function iEt(e){e.command("navigate [destination]").alias("nav").description("Find a dashboard destination and build a deep link to it (offline)").option("--query <text>","Discovery: match a substring of the key or label").option("--resource <namespace>","Discovery: restrict to one namespace, e.g. sales, purchases").addOption(new lt("--kind <kind>","Discovery: restrict to screens or modals").choices(["screen","modal"])).option("--resource-id <resourceId>","Record to focus \u2014 only with a record-modal destination").option("--org-id <resourceId>","Append org= so the link names the organization explicitly").addOption(new lt("--platform <brand>","Dashboard brand").choices(["jaz","juan"]).default("jaz")).option("--json","Output as JSON").action((t,r)=>{let{dashboardUrl:n}=UD(r.platform);if(e.opts().org)throw new hr("--org selects a credential profile and this command reads none. Use --org-id <resourceId> to name the organization in the link.");if(!t){if(r.resourceId)throw new hr("A --resource-id needs a destination. Pass a record-modal destination key, or drop --resource-id to search.");let o=r.resource;if(o){let a=oLe();if(!a.includes(o))throw new hr(`Unknown --resource '${o}'. Known: ${a.join(", ")}.`)}let s=BU({query:r.query,resource:o,kind:r.kind});if(r.json){console.log(JSON.stringify(s,null,2));return}if(s.results.length===0){console.error(U(s.hint??"No destinations matched."));return}console.log(Gs(s.results,wQr)),console.error(U(`${s.results.length} of ${s.total}`)),s.hint&&console.error(Te(s.hint));return}let i=$D(t,r.resourceId,{dashboardUrl:n,orgResourceId:r.orgId});if(r.json){console.log(JSON.stringify(i,null,2));return}console.log(i.url),console.error(U(`${i.label} (${i.kind})`))})}Be();EW();nt();import{readFileSync as vQr}from"node:fs";function oEt(e,t){try{return JSON.parse(e)}catch(r){return console.error(Z(`Invalid JSON in ${t}: ${r.message}`)),process.exitCode=1,null}}function sEt(e){let t=e.command("quick-fix <entity>").description("Bulk-update transactions or line items in one call").option("--jot <text>",me).addHelpText("after",`