jaz-clio 5.14.0 → 5.14.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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-api
3
- version: 5.14.0
3
+ version: 5.14.2
4
4
  description: >-
5
5
  Use this skill whenever you call, debug, or review code that touches the Jaz
6
6
  REST API. Covers field names, response shapes, 141 production gotchas, error
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-cli
3
- version: 5.14.0
3
+ version: 5.14.2
4
4
  description: >-
5
5
  Use this skill when running Clio CLI commands, building shell scripts with
6
6
  Clio, debugging auth issues, understanding --json output, paginating results,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-conversion
3
- version: 5.14.0
3
+ version: 5.14.2
4
4
  description: >-
5
5
  Use this skill when migrating accounting data into Jaz — importing from Xero,
6
6
  QuickBooks, Sage, MYOB, or Excel exports. Covers the full conversion pipeline:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-pseudo-sql
3
- version: 5.14.0
3
+ version: 5.14.2
4
4
  description: >-
5
5
  Use this skill when answering ad-hoc data questions that aren't covered by
6
6
  download_export (canonical reports — anomaly, audit, aging, P&L, BS, GL,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-jobs
3
- version: 5.14.0
3
+ version: 5.14.2
4
4
  description: >-
5
5
  Use this skill for recurring accounting workflows — month/quarter/year-end
6
6
  close, bank reconciliation, GST/VAT filing, payment runs, credit control,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-practice
3
- version: 5.14.0
3
+ version: 5.14.2
4
4
  description: >-
5
5
  Use this skill whenever an accounting practitioner is doing client work in
6
6
  Jaz — closing the books, filing GST, year-end statutory, onboarding a new
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-recipes
3
- version: 5.14.0
3
+ version: 5.14.2
4
4
  description: >-
5
5
  Use this skill when modeling complex multi-step accounting transactions —
6
6
  anything that spans multiple periods, involves changing amounts, or requires
package/cli.mjs CHANGED
@@ -193,7 +193,7 @@ ${c}${o}
193
193
  ${a}`:""}`}default:{let o=e?`${Z("cyan",Qe)} `:"",a=e?Z("cyan",Zi):"";return`${r}${o}${i}
194
194
  ${a}
195
195
  `}}}}).prompt()});var Ebe,bbe,eyt,tyt,ryt,nyt,iyt,Vc,UNr,Cbe=re(()=>{fG();Ebe={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},bbe={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},eyt={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},tyt={...Ebe,...bbe},ryt={...Ebe,...eyt},nyt=RI(),iyt=nyt?tyt:ryt,Vc=iyt,UNr=Object.entries(bbe)});var XG={};jc(XG,{COL_GAP:()=>MI,INDENT:()=>Dt,accent:()=>Se,box:()=>Cn,danger:()=>se,highlight:()=>N,info:()=>Ka,isCI:()=>vbe,isTTY:()=>MN,muted:()=>H,shouldAnimate:()=>KG,subtle:()=>No,success:()=>V,sym:()=>co,underline:()=>ZG,warning:()=>Me});function MN(){return!!process.stdout.isTTY}function vbe(){return!!process.env.CI}function KG(){return MN()&&!vbe()&&!process.env.NO_COLOR}var Se,H,V,Me,se,Ka,N,No,ZG,co,Cn,Dt,MI,Le=re(()=>{"use strict";Ty();Cbe();Se=tr.hex("#6699ff"),H=tr.dim,V=tr.hex("#14b856"),Me=tr.hex("#ff9466"),se=tr.hex("#f87777"),Ka=tr.cyan,N=tr.bold,No=tr.gray,ZG=tr.underline,co={tick:Vc.tick,cross:Vc.cross,warning:Vc.warning,info:Vc.info,pointer:Vc.pointer,bullet:Vc.bullet,arrowRight:Vc.arrowRight,ellipsis:Vc.ellipsis,line:Vc.line,pointerSmall:Vc.pointerSmall},Cn={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",leftT:"\u251C",rightT:"\u2524"},Dt=" ",MI=2});var Ky,t4=re(()=>{"use strict";Ky="pat-"});import{readFileSync as lyt,writeFileSync as fyt,renameSync as dyt,mkdirSync as pyt,unlinkSync as hyt,existsSync as myt,openSync as Ayt,fsyncSync as gyt,closeSync as yyt}from"fs";import{join as Rbe}from"path";import{homedir as Eyt}from"os";function Hu(){try{let t=lyt(PI,"utf-8"),e=JSON.parse(t);if(e.version===2)return e;if(e.apiKey){let r={version:2,active:"default",orgs:{default:{apiKey:e.apiKey,orgName:"Unknown (migrated)",orgId:"",currency:"",country:"",addedAt:e.createdAt??new Date().toISOString()}}};try{$I(r)}catch{}return r}return null}catch{return null}}function $I(t){pyt(xbe,{recursive:!0});let e=PI+".tmp";fyt(e,JSON.stringify(t,null,2)+`
196
- `,{mode:384});let r=Ayt(e,"r");try{gyt(r)}finally{yyt(r)}dyt(e,PI)}function Xa(t){return Hu()?.orgs[t]??null}function UI(t,e){let r=Hu()??{version:2,active:"",orgs:{}};r.orgs[t]=e,(!r.active||Object.keys(r.orgs).length===1)&&(r.active=t),$I(r)}function r4(t){let e=Hu();return!e||!(t in e.orgs)?!1:(delete e.orgs[t],e.active===t&&(e.active=""),$I(e),!0)}function Fo(){return Hu()?.active||null}function n4(t){let e=Hu();if(!e)throw new Error("No credentials file found. Run `clio auth add <key>` first.");if(!(t in e.orgs)){let r=Object.keys(e.orgs).join(", ");throw new Error(`Org '${t}' not found. Available: ${r}`)}e.active=t,$I(e)}function Jc(){return Hu()?.orgs??{}}function i4(t){let e=Hu();if(!e)return null;for(let[r,n]of Object.entries(e.orgs))if(n.apiKey===t)return r;return null}function s4(){return myt(PI)?(hyt(PI),!0):!1}var xbe,PI,qI=re(()=>{"use strict";xbe=Rbe(Eyt(),".config","jaz-clio"),PI=Rbe(xbe,"credentials.json")});function o4(t){jI=t}function zI(){return $N}function HI(){return fa}function PN(t){let e=process.env[t];if(e===void 0)return;let r=e.trim();if(r!==""&&!r.includes("${"))return r}function YI(t){let e=t.split(",").map(o=>o.trim()).filter(Boolean);if(e.length===0)throw new lo("Empty key value. Provide a Jaz API key (jk-...) or personal access token (pat-...).");let r=e.filter(o=>o.startsWith(Ky)),n=e.filter(o=>o.startsWith("jk-"));if(e.filter(o=>!o.startsWith(Ky)&&!o.startsWith("jk-")).length>0)throw new lo("Invalid key format (unrecognized prefix). Expected jk-... (API key) or pat-... (personal access token).");if(r.length>0&&n.length>0)throw new lo("Cannot mix PAT and API keys. Use either a single personal access token (pat-...) or one or more API keys (jk-...).");if(r.length>0&&e.length!==1)throw new lo("Only one personal access token allowed. Do not combine with other keys.");return r.length===1?[{mode:"pat",token:r[0]}]:[...new Set(n)].map(o=>({mode:"direct",apiKey:o}))}function UN(t){if($N=null,fa=null,t)return fa="flag-api-key",YI(t)[0];let e=PN("JAZ_API_KEY");if(e)return fa="env-api-key",YI(e)[0];if(jI)return fa="flag-org",Xy(jI);let r=PN("JAZ_ORG");if(r)return fa="env-org",Xy(r);let n=Fo();return n?(fa="active-file",Xy(n)):null}function Xy(t){let e=Xa(t);if(!e){let r=Hu(),n=r?Object.keys(r.orgs):[],i=n.length>0?` Available: ${n.join(", ")}`:" No orgs registered. Run `clio auth add <key>` first.";throw new lo(`Org '${t}' not found.${i}`)}return $N=t,{mode:"direct",apiKey:e.apiKey}}function a4(t){if($N=null,fa=null,t)return fa="flag-api-key",YI(t);let e=PN("JAZ_API_KEY");if(e)return fa="env-api-key",YI(e);if(jI)return fa="flag-org",[Xy(jI)];let r=PN("JAZ_ORG");if(r)return fa="env-org",[Xy(r)];let n=Fo();return n?(fa="active-file",[Xy(n)]):[]}function km(t){let e=UN(t);if(!e)throw new lo("No API key configured. Run `clio auth add <key>`, set JAZ_API_KEY, or pass --api-key.");return e}var jI,$N,fa,lo,c4=re(()=>{"use strict";t4();qI();$N=null;fa=null;lo=class extends Error{constructor(e){super(e),this.name="AuthError"}}});function u4(t){return t.replace(/\/[a-f0-9-]{8,}(?=[/?#]|$)/gi,"/{id}")}function Tbe(t){let e=u4(t),r=qN.get(e);if(!(!r||r.state==="closed")&&r.state==="open"){if(Date.now()-r.lastFailure>3e4){r.state="half-open";return}let n=Math.ceil((3e4-(Date.now()-r.lastFailure))/1e3);throw new Error(`Circuit open for ${e} \u2014 API endpoint appears down (${r.failures} consecutive failures). Retry in ${n}s.`)}}function kbe(t){let e=u4(t),r=qN.get(e);r&&(r.failures=0,r.state="closed")}function Nbe(t){let e=u4(t),r=qN.get(e)??{failures:0,lastFailure:0,state:"closed"};r.failures++,r.lastFailure=Date.now(),r.failures>=5&&(r.state="open"),qN.set(e,r)}var qN,Fbe=re(()=>{"use strict";qN=new Map});function Obe(t){return new Promise(e=>setTimeout(e,t))}function Qbe(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t;if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"){let r=e.error;if(Array.isArray(r.errors)&&r.errors.length>0)return r.errors.join("; ");if(typeof r.error_type=="string")return r.error_type}return JSON.stringify(t)}return String(t)}var byt,Cyt,vyt,Iyt,wyt,Oo,Qs,Gu=re(()=>{"use strict";Fbe();byt="https://api.getjaz.com",Cyt=3e4,vyt=3,Iyt=[429],wyt=[500,502,503],Oo=class extends Error{status;body;endpoint;constructor(e,r,n,i){super(e),this.status=r,this.body=n,this.endpoint=i,this.name="JazApiError"}},Qs=class{baseUrl;timeout;maxRetries;auth;onRequest;constructor(e,r={}){this.auth=e,this.baseUrl=(r.baseUrl??byt).replace(/\/$/,""),this.timeout=r.timeout??Cyt,this.maxRetries=r.maxRetries??vyt,this.onRequest=r.onRequest}get isPatAuth(){return this.auth.mode==="pat"}buildHeaders(e){let r={"Content-Type":"application/json",...e};switch(this.auth.mode){case"direct":r["x-jk-api-key"]=this.auth.apiKey;break;case"pat":r.Authorization=`Bearer ${this.auth.token}`,this.auth.orgId&&(r["x-jaz-org-key"]=this.auth.orgId);break;case"delegated":this.auth.orgUserId?(r["x-channel-key"]=this.auth.adminKey,r["x-jaz-org-key"]=this.auth.orgId,r["x-jaz-org-user-key"]=this.auth.orgUserId):(r["x-clio-admin-key"]=this.auth.adminKey,r["x-user-id"]=this.auth.userId,r["x-org-id"]=this.auth.orgId);break}return r}async request(e,r,n={}){let i=new URL(`${this.baseUrl}${r}`);if(n.query)for(let[u,f]of Object.entries(n.query))f!==void 0&&i.searchParams.set(u,String(f));let s=this.buildHeaders(n.headers);n.raw&&delete s["Content-Type"];let o={method:e,headers:s,signal:AbortSignal.timeout(this.timeout)};n.body!==void 0&&e!=="GET"&&e!=="DELETE"&&(o.body=n.raw?n.body:JSON.stringify(n.body)),Tbe(r);let a,c=Date.now();for(let u=0;u<=this.maxRetries;u++){let f=Date.now();try{let d=await fetch(i.toString(),o),p=["GET","HEAD"].includes(e);if((Iyt.includes(d.status)||p&&wyt.includes(d.status))&&u<this.maxRetries){this.onRequest?.({method:e,path:r,statusCode:d.status,durationMs:Date.now()-f,attempt:u,retried:!0});let m=Math.min(1e3*2**u,8e3);await Obe(m);continue}if(!d.ok){let m;try{m=await d.json()}catch{m=await d.text()}throw this.onRequest?.({method:e,path:r,statusCode:d.status,durationMs:Date.now()-f,attempt:u,retried:!1,error:Qbe(m)}),d.status>=500&&Nbe(r),new Oo(`${e} ${r} \u2192 ${d.status}: ${Qbe(m)}`,d.status,m,r)}return this.onRequest?.({method:e,path:r,statusCode:d.status,durationMs:Date.now()-f,attempt:u,retried:!1}),kbe(r),d.status===204?void 0:await d.json()}catch(d){if(d instanceof Oo)throw d;if(a=d,this.onRequest?.({method:e,path:r,statusCode:0,durationMs:Date.now()-f,attempt:u,retried:u<this.maxRetries,error:a.message}),u<this.maxRetries){let p=Math.min(1e3*2**u,8e3);await Obe(p);continue}}}throw a??new Error(`Request failed: ${e} ${r}`)}async get(e,r){return this.request("GET",e,{query:r})}async post(e,r,n){return this.request("POST",e,{body:r,headers:n?.headers})}async put(e,r,n){return this.request("PUT",e,{body:r,headers:n?.headers})}async delete(e){return this.request("DELETE",e)}async postMultipart(e,r){return this.request("POST",e,{body:r,raw:!0})}async list(e,r){let n=await this.get(e,{limit:r?.limit??100,offset:r?.offset??0});return n.data||(n.data=[]),n}async search(e,r){let n={};r.query&&(n.query=r.query),r.filter&&(n.filter=r.filter),r.limit!==void 0&&(n.limit=r.limit),r.offset!==void 0&&(n.offset=r.offset),r.view&&(n.view=r.view),r.sort?n.sort=r.sort:r.offset!==void 0&&(n.sort={sortBy:["createdAt"],order:"DESC"});let i=await this.post(e,n);return i.data||(i.data=[]),i}async listAll(e,r=200){let n=[],i=0,s=!0;for(;s;){let o=await this.list(e,{limit:r,offset:i});if(n.push(...o.data),o.data.length<r)break;i+=1,s=i*r<o.totalElements}return n}}});async function da(t){let e=await t.get("/api/v1/organization");return Array.isArray(e.data)?e.data[0]:e.data}var Nm=re(()=>{"use strict"});var Gbe=b(Hr=>{"use strict";function jbe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}var Ybe;function Hbe(t,e,r,n,i){if(i===void 0&&(i=Hr.PaymentDueTime.End),t===0)return-(n+r*e);var s=Math.pow(1+t,e);return-n*s-r*(1+t*(i===Hr.PaymentDueTime.Begin?1:0))/t*(s-1)}function f4(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=Hr.PaymentDueTime.End);var s=t===0,o=Math.pow(1+t,e),a=i===Hr.PaymentDueTime.Begin?1:0,c=s?1:t;return-(n+r*o)/(s?e:(1+c*a)*(o-1)/c)}function zbe(t,e,r,n,i,s){if(i===void 0&&(i=0),s===void 0&&(s=Hr.PaymentDueTime.End),e<1)return Number.NaN;if(s===Hr.PaymentDueTime.Begin&&e===1)return 0;var o=kyt(t,e,f4(t,r,n,i,s),n,s)*t;return s===Hr.PaymentDueTime.Begin&&e>1&&(o/=1+t),o}function l4(t,e){return e.reduce((function(r,n,i){return r+n/Math.pow(1+t,i)}),0)}function kyt(t,e,r,n,i){return Hbe(t,e-1,r,n,i)}function Nyt(t,e,r,n,i,s){var o=s===Hr.PaymentDueTime.Begin?1:0,a=Math.pow(t+1,e),c=Math.pow(t+1,e-1);return(i+a*n+r*(a-1)*(t*o+1)/t)/(e*c*n-r*(a-1)*(t*o+1)/Math.pow(t,2)+e*r*c*(t*o+1)/t+r*(a-1)*o/t)}function Fyt(t,e,r){for(var n=r+1,i=t[0],s=1;s<t.length;s++)i+=t[s]/Math.pow(n,(e[s]-e[0])/365);return i}function Oyt(t,e,r){for(var n=r+1,i=0,s=1;s<t.length;s++){var o=(e[s]-e[0])/365;i-=o*t[s]/Math.pow(n,o+1)}return i}Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.PaymentDueTime=void 0,(Ybe=Hr.PaymentDueTime||(Hr.PaymentDueTime={})).Begin="begin",Ybe.End="end",Hr.fv=Hbe,Hr.ipmt=zbe,Hr.irr=function(t,e,r,n){e===void 0&&(e=.1),r===void 0&&(r=1e-6),n===void 0&&(n=100);for(var i=[],s=!1,o=!1,a=0;a<t.length;a++)i[a]=a===0?0:i[a-1]+365,t[a]>0&&(s=!0),t[a]<0&&(o=!0);if(!s||!o)return Number.NaN;var c=e,u=0,f=0,d=0,p=0,h=!0;do u=c-(d=Fyt(t,i,c))/Oyt(t,i,c),f=Math.abs(u-c),c=u,h=f>r&&Math.abs(d)>r;while(h&&++p<n);return h?Number.NaN:c},Hr.mirr=function(t,e,r){for(var n,i=!1,s=!1,o=(function(f,d){var p=typeof Symbol<"u"&&f[Symbol.iterator]||f["@@iterator"];if(p)return(p=p.call(f)).next.bind(p);if(Array.isArray(f)||(p=(function(m,A){if(m){if(typeof m=="string")return jbe(m,A);var g=Object.prototype.toString.call(m).slice(8,-1);return g==="Object"&&m.constructor&&(g=m.constructor.name),g==="Map"||g==="Set"?Array.from(m):g==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(g)?jbe(m,A):void 0}})(f))){p&&(f=p);var h=0;return function(){return h>=f.length?{done:!0}:{done:!1,value:f[h++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
196
+ `,{mode:384});let r=Ayt(e,"r");try{gyt(r)}finally{yyt(r)}dyt(e,PI)}function Xa(t){return Hu()?.orgs[t]??null}function UI(t,e){let r=Hu()??{version:2,active:"",orgs:{}};r.orgs[t]=e,(!r.active||Object.keys(r.orgs).length===1)&&(r.active=t),$I(r)}function r4(t){let e=Hu();return!e||!(t in e.orgs)?!1:(delete e.orgs[t],e.active===t&&(e.active=""),$I(e),!0)}function Fo(){return Hu()?.active||null}function n4(t){let e=Hu();if(!e)throw new Error("No credentials file found. Run `clio auth add <key>` first.");if(!(t in e.orgs)){let r=Object.keys(e.orgs).join(", ");throw new Error(`Org '${t}' not found. Available: ${r}`)}e.active=t,$I(e)}function Jc(){return Hu()?.orgs??{}}function i4(t){let e=Hu();if(!e)return null;for(let[r,n]of Object.entries(e.orgs))if(n.apiKey===t)return r;return null}function s4(){return myt(PI)?(hyt(PI),!0):!1}var xbe,PI,qI=re(()=>{"use strict";xbe=Rbe(Eyt(),".config","jaz-clio"),PI=Rbe(xbe,"credentials.json")});function o4(t){jI=t}function zI(){return $N}function HI(){return fa}function PN(t){let e=process.env[t];if(e===void 0)return;let r=e.trim();if(r!==""&&!r.includes("${"))return r}function YI(t){let e=t.split(",").map(o=>o.trim()).filter(Boolean);if(e.length===0)throw new lo("Empty key value. Provide a Jaz API key (jk-...) or personal access token (pat-...).");let r=e.filter(o=>o.startsWith(Ky)),n=e.filter(o=>o.startsWith("jk-"));if(e.filter(o=>!o.startsWith(Ky)&&!o.startsWith("jk-")).length>0)throw new lo("Invalid key format (unrecognized prefix). Expected jk-... (API key) or pat-... (personal access token).");if(r.length>0&&n.length>0)throw new lo("Cannot mix PAT and API keys. Use either a single personal access token (pat-...) or one or more API keys (jk-...).");if(r.length>0&&e.length!==1)throw new lo("Only one personal access token allowed. Do not combine with other keys.");return r.length===1?[{mode:"pat",token:r[0]}]:[...new Set(n)].map(o=>({mode:"direct",apiKey:o}))}function UN(t){if($N=null,fa=null,t)return fa="flag-api-key",YI(t)[0];let e=PN("JAZ_API_KEY");if(e)return fa="env-api-key",YI(e)[0];if(jI)return fa="flag-org",Xy(jI);let r=PN("JAZ_ORG");if(r)return fa="env-org",Xy(r);let n=Fo();return n?(fa="active-file",Xy(n)):null}function Xy(t){let e=Xa(t);if(!e){let r=Hu(),n=r?Object.keys(r.orgs):[],i=n.length>0?` Available: ${n.join(", ")}`:" No orgs registered. Run `clio auth add <key>` first.";throw new lo(`Org '${t}' not found.${i}`)}return $N=t,{mode:"direct",apiKey:e.apiKey}}function a4(t){if($N=null,fa=null,t)return fa="flag-api-key",YI(t);let e=PN("JAZ_API_KEY");if(e)return fa="env-api-key",YI(e);if(jI)return fa="flag-org",[Xy(jI)];let r=PN("JAZ_ORG");if(r)return fa="env-org",[Xy(r)];let n=Fo();return n?(fa="active-file",[Xy(n)]):[]}function km(t){let e=UN(t);if(!e)throw new lo("No API key configured. Run `clio auth add <key>`, set JAZ_API_KEY, or pass --api-key.");return e}var jI,$N,fa,lo,c4=re(()=>{"use strict";t4();qI();$N=null;fa=null;lo=class extends Error{constructor(e){super(e),this.name="AuthError"}}});function u4(t){return t.replace(/\/[a-f0-9-]{8,}(?=[/?#]|$)/gi,"/{id}")}function Tbe(t){let e=u4(t),r=qN.get(e);if(!(!r||r.state==="closed")&&r.state==="open"){if(Date.now()-r.lastFailure>3e4){r.state="half-open";return}let n=Math.ceil((3e4-(Date.now()-r.lastFailure))/1e3);throw new Error(`Circuit open for ${e} \u2014 API endpoint appears down (${r.failures} consecutive failures). Retry in ${n}s.`)}}function kbe(t){let e=u4(t),r=qN.get(e);r&&(r.failures=0,r.state="closed")}function Nbe(t){let e=u4(t),r=qN.get(e)??{failures:0,lastFailure:0,state:"closed"};r.failures++,r.lastFailure=Date.now(),r.failures>=5&&(r.state="open"),qN.set(e,r)}var qN,Fbe=re(()=>{"use strict";qN=new Map});function Obe(t){return new Promise(e=>setTimeout(e,t))}function Qbe(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t;if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(e.error&&typeof e.error=="object"){let r=e.error;if(Array.isArray(r.errors)&&r.errors.length>0)return r.errors.join("; ");if(typeof r.error_type=="string")return r.error_type}return JSON.stringify(t)}return String(t)}var byt,Cyt,vyt,Iyt,wyt,Oo,Qs,Gu=re(()=>{"use strict";Fbe();byt="https://api.getjaz.com",Cyt=3e4,vyt=3,Iyt=[429],wyt=[500,502,503],Oo=class extends Error{status;body;endpoint;constructor(e,r,n,i){super(e),this.status=r,this.body=n,this.endpoint=i,this.name="JazApiError"}},Qs=class{baseUrl;timeout;maxRetries;auth;onRequest;constructor(e,r={}){this.auth=e,this.baseUrl=(r.baseUrl??byt).replace(/\/$/,""),this.timeout=r.timeout??Cyt,this.maxRetries=r.maxRetries??vyt,this.onRequest=r.onRequest}get isPatAuth(){return this.auth.mode==="pat"}buildHeaders(e){let r={"Content-Type":"application/json",...e};switch(this.auth.mode){case"direct":r["x-jk-api-key"]=this.auth.apiKey;break;case"pat":r.Authorization=`Bearer ${this.auth.token}`,this.auth.orgId&&(r["x-jaz-org-key"]=this.auth.orgId);break;case"delegated":this.auth.orgUserId?(r["x-channel-key"]=this.auth.adminKey,r["x-jaz-org-key"]=this.auth.orgId,r["x-jaz-org-user-key"]=this.auth.orgUserId):(r["x-clio-admin-key"]=this.auth.adminKey,r["x-user-id"]=this.auth.userId,r["x-org-id"]=this.auth.orgId);break}return r}async request(e,r,n={}){let i=new URL(`${this.baseUrl}${r}`);if(n.query)for(let[u,f]of Object.entries(n.query))f!==void 0&&i.searchParams.set(u,String(f));let s=this.buildHeaders(n.headers);n.raw&&delete s["Content-Type"];let o={method:e,headers:s,signal:AbortSignal.timeout(this.timeout)};n.body!==void 0&&e!=="GET"&&e!=="DELETE"&&(o.body=n.raw?n.body:JSON.stringify(n.body)),Tbe(r);let a,c=Date.now();for(let u=0;u<=this.maxRetries;u++){let f=Date.now();try{let d=await fetch(i.toString(),o),p=["GET","HEAD"].includes(e);if((Iyt.includes(d.status)||p&&wyt.includes(d.status))&&u<this.maxRetries){this.onRequest?.({method:e,path:r,statusCode:d.status,durationMs:Date.now()-f,attempt:u,retried:!0});let m=Math.min(1e3*2**u,8e3);await Obe(m);continue}if(!d.ok){let m;try{m=await d.json()}catch{m=await d.text()}throw this.onRequest?.({method:e,path:r,statusCode:d.status,durationMs:Date.now()-f,attempt:u,retried:!1,error:Qbe(m)}),d.status>=500&&Nbe(r),new Oo(`${e} ${r} \u2192 ${d.status}: ${Qbe(m)}`,d.status,m,r)}return this.onRequest?.({method:e,path:r,statusCode:d.status,durationMs:Date.now()-f,attempt:u,retried:!1}),kbe(r),d.status===204?void 0:await d.json()}catch(d){if(d instanceof Oo)throw d;if(a=d,this.onRequest?.({method:e,path:r,statusCode:0,durationMs:Date.now()-f,attempt:u,retried:u<this.maxRetries,error:a.message}),u<this.maxRetries){let p=Math.min(1e3*2**u,8e3);await Obe(p);continue}}}throw a??new Error(`Request failed: ${e} ${r}`)}async get(e,r){return this.request("GET",e,{query:r})}async post(e,r,n){return this.request("POST",e,{body:r,headers:n?.headers})}async put(e,r,n){return this.request("PUT",e,{body:r,headers:n?.headers})}async delete(e){return this.request("DELETE",e)}async postMultipart(e,r){return this.request("POST",e,{body:r,raw:!0})}async list(e,r){let n=await this.get(e,{limit:r?.limit??100,offset:r?.offset??0,...r?.view?{view:r.view}:{}});return n.data||(n.data=[]),n}async search(e,r){let n={};r.query&&(n.query=r.query),r.filter&&(n.filter=r.filter),r.limit!==void 0&&(n.limit=r.limit),r.offset!==void 0&&(n.offset=r.offset),r.view&&(n.view=r.view),r.sort?n.sort=r.sort:r.offset!==void 0&&(n.sort={sortBy:["createdAt"],order:"DESC"});let i=await this.post(e,n);return i.data||(i.data=[]),i}async listAll(e,r=200){let n=[],i=0,s=!0;for(;s;){let o=await this.list(e,{limit:r,offset:i});if(n.push(...o.data),o.data.length<r)break;i+=1,s=i*r<o.totalElements}return n}}});async function da(t){let e=await t.get("/api/v1/organization");return Array.isArray(e.data)?e.data[0]:e.data}var Nm=re(()=>{"use strict"});var Gbe=b(Hr=>{"use strict";function jbe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}var Ybe;function Hbe(t,e,r,n,i){if(i===void 0&&(i=Hr.PaymentDueTime.End),t===0)return-(n+r*e);var s=Math.pow(1+t,e);return-n*s-r*(1+t*(i===Hr.PaymentDueTime.Begin?1:0))/t*(s-1)}function f4(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=Hr.PaymentDueTime.End);var s=t===0,o=Math.pow(1+t,e),a=i===Hr.PaymentDueTime.Begin?1:0,c=s?1:t;return-(n+r*o)/(s?e:(1+c*a)*(o-1)/c)}function zbe(t,e,r,n,i,s){if(i===void 0&&(i=0),s===void 0&&(s=Hr.PaymentDueTime.End),e<1)return Number.NaN;if(s===Hr.PaymentDueTime.Begin&&e===1)return 0;var o=kyt(t,e,f4(t,r,n,i,s),n,s)*t;return s===Hr.PaymentDueTime.Begin&&e>1&&(o/=1+t),o}function l4(t,e){return e.reduce((function(r,n,i){return r+n/Math.pow(1+t,i)}),0)}function kyt(t,e,r,n,i){return Hbe(t,e-1,r,n,i)}function Nyt(t,e,r,n,i,s){var o=s===Hr.PaymentDueTime.Begin?1:0,a=Math.pow(t+1,e),c=Math.pow(t+1,e-1);return(i+a*n+r*(a-1)*(t*o+1)/t)/(e*c*n-r*(a-1)*(t*o+1)/Math.pow(t,2)+e*r*c*(t*o+1)/t+r*(a-1)*o/t)}function Fyt(t,e,r){for(var n=r+1,i=t[0],s=1;s<t.length;s++)i+=t[s]/Math.pow(n,(e[s]-e[0])/365);return i}function Oyt(t,e,r){for(var n=r+1,i=0,s=1;s<t.length;s++){var o=(e[s]-e[0])/365;i-=o*t[s]/Math.pow(n,o+1)}return i}Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.PaymentDueTime=void 0,(Ybe=Hr.PaymentDueTime||(Hr.PaymentDueTime={})).Begin="begin",Ybe.End="end",Hr.fv=Hbe,Hr.ipmt=zbe,Hr.irr=function(t,e,r,n){e===void 0&&(e=.1),r===void 0&&(r=1e-6),n===void 0&&(n=100);for(var i=[],s=!1,o=!1,a=0;a<t.length;a++)i[a]=a===0?0:i[a-1]+365,t[a]>0&&(s=!0),t[a]<0&&(o=!0);if(!s||!o)return Number.NaN;var c=e,u=0,f=0,d=0,p=0,h=!0;do u=c-(d=Fyt(t,i,c))/Oyt(t,i,c),f=Math.abs(u-c),c=u,h=f>r&&Math.abs(d)>r;while(h&&++p<n);return h?Number.NaN:c},Hr.mirr=function(t,e,r){for(var n,i=!1,s=!1,o=(function(f,d){var p=typeof Symbol<"u"&&f[Symbol.iterator]||f["@@iterator"];if(p)return(p=p.call(f)).next.bind(p);if(Array.isArray(f)||(p=(function(m,A){if(m){if(typeof m=="string")return jbe(m,A);var g=Object.prototype.toString.call(m).slice(8,-1);return g==="Object"&&m.constructor&&(g=m.constructor.name),g==="Map"||g==="Set"?Array.from(m):g==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(g)?jbe(m,A):void 0}})(f))){p&&(f=p);var h=0;return function(){return h>=f.length?{done:!0}:{done:!1,value:f[h++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
197
197
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})(t);!(n=o()).done;){var a=n.value;a>0&&(i=!0),a<0&&(s=!0)}if(!i||!s)return Number.NaN;var c=Math.abs(l4(r,t.map((function(f){return f>0?f:0})))),u=Math.abs(l4(e,t.map((function(f){return f<0?f:0}))));return Math.pow(c/u,1/(t.length-1))*(1+r)-1},Hr.nper=function(t,e,r,n,i){if(n===void 0&&(n=0),i===void 0&&(i=Hr.PaymentDueTime.End),t===0)return-(n+r)/e;var s=e*(1+t*(i===Hr.PaymentDueTime.Begin?1:0))/t;return Math.log((-n+s)/(r+s))/Math.log(1+t)},Hr.npv=l4,Hr.pmt=f4,Hr.ppmt=function(t,e,r,n,i,s){return i===void 0&&(i=0),s===void 0&&(s=Hr.PaymentDueTime.End),f4(t,r,n,i,s)-zbe(t,e,r,n,i,s)},Hr.pv=function(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=Hr.PaymentDueTime.End);var s=i===Hr.PaymentDueTime.Begin?1:0,o=t===0,a=Math.pow(1+t,e);return-(n+r*(o?e:(1+t*s)*(a-1)/t))/a},Hr.rate=function(t,e,r,n,i,s,o,a){i===void 0&&(i=Hr.PaymentDueTime.End),s===void 0&&(s=.1),o===void 0&&(o=1e-6),a===void 0&&(a=100);for(var c=s,u=0,f=!1;u<a&&!f;){var d=c-Nyt(c,t,e,r,n,i);f=Math.abs(d-c)<o,u++,c=d}return f?c:Number.NaN}});var Zbe=b(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});function Qyt(t,e){if(t){if(typeof t=="string")return Vbe(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Vbe(t,e)}}function Vbe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function Lyt(t,e){var r=typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=Qyt(t))||e&&t&&typeof t.length=="number"){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
198
198
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}Gr.PaymentDueTime=void 0;(function(t){t.Begin="begin",t.End="end"})(Gr.PaymentDueTime||(Gr.PaymentDueTime={}));function Jbe(t,e,r,n,i){i===void 0&&(i=Gr.PaymentDueTime.End);var s=t===0;if(s)return-(n+r*e);var o=Math.pow(1+t,e),a=i===Gr.PaymentDueTime.Begin?1:0;return-n*o-r*(1+t*a)/t*(o-1)}function p4(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=Gr.PaymentDueTime.End);var s=t===0,o=Math.pow(1+t,e),a=i===Gr.PaymentDueTime.Begin?1:0,c=s?1:t,u=s?e:(1+c*a)*(o-1)/c;return-(n+r*o)/u}function Myt(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=Gr.PaymentDueTime.End);var s=t===0;if(s)return-(n+r)/e;var o=i===Gr.PaymentDueTime.Begin?1:0,a=e*(1+t*o)/t;return Math.log((-n+a)/(r+a))/Math.log(1+t)}function Wbe(t,e,r,n,i,s){if(i===void 0&&(i=0),s===void 0&&(s=Gr.PaymentDueTime.End),e<1)return Number.NaN;if(s===Gr.PaymentDueTime.Begin&&e===1)return 0;var o=p4(t,r,n,i,s),a=Yyt(t,e,o,n,s)*t;return s===Gr.PaymentDueTime.Begin&&e>1&&(a=a/(1+t)),a}function Pyt(t,e,r,n,i,s){i===void 0&&(i=0),s===void 0&&(s=Gr.PaymentDueTime.End);var o=p4(t,r,n,i,s);return o-Wbe(t,e,r,n,i,s)}function $yt(t,e,r,n,i){n===void 0&&(n=0),i===void 0&&(i=Gr.PaymentDueTime.End);var s=i===Gr.PaymentDueTime.Begin?1:0,o=t===0,a=Math.pow(1+t,e),c=o?e:(1+t*s)*(a-1)/t;return-(n+r*c)/a}function Uyt(t,e,r,n,i,s,o,a){i===void 0&&(i=Gr.PaymentDueTime.End),s===void 0&&(s=.1),o===void 0&&(o=1e-6),a===void 0&&(a=100);for(var c=s,u=0,f=!1;u<a&&!f;){var d=c-zyt(c,t,e,r,n,i),p=Math.abs(d-c);f=p<o,u++,c=d}return f?c:Number.NaN}function qyt(t,e,r,n){e===void 0&&(e=.1),r===void 0&&(r=1e-6),n===void 0&&(n=100);for(var i=[],s=!1,o=!1,a=0;a<t.length;a++)i[a]=a===0?0:i[a-1]+365,t[a]>0&&(s=!0),t[a]<0&&(o=!0);if(!s||!o)return Number.NaN;var c=e,u=0,f=0,d=0,p=0,h=!0;do d=Hyt(t,i,c),u=c-d/Gyt(t,i,c),f=Math.abs(u-c),c=u,h=f>r&&Math.abs(d)>r;while(h&&++p<n);return h?Number.NaN:c}function d4(t,e){return e.reduce(function(r,n,i){return r+n/Math.pow(1+t,i)},0)}function jyt(t,e,r){for(var n=!1,i=!1,s=Lyt(t),o;!(o=s()).done;){var a=o.value;a>0&&(n=!0),a<0&&(i=!0)}if(!n||!i)return Number.NaN;var c=Math.abs(d4(r,t.map(function(f){return f>0?f:0}))),u=Math.abs(d4(e,t.map(function(f){return f<0?f:0})));return Math.pow(c/u,1/(t.length-1))*(1+r)-1}function Yyt(t,e,r,n,i){return Jbe(t,e-1,r,n,i)}function zyt(t,e,r,n,i,s){var o=s===Gr.PaymentDueTime.Begin?1:0,a=Math.pow(t+1,e),c=Math.pow(t+1,e-1),u=i+a*n+r*(a-1)*(t*o+1)/t,f=e*c*n-r*(a-1)*(t*o+1)/Math.pow(t,2)+e*r*c*(t*o+1)/t+r*(a-1)*o/t;return u/f}function Hyt(t,e,r){for(var n=r+1,i=t[0],s=1;s<t.length;s++)i+=t[s]/Math.pow(n,(e[s]-e[0])/365);return i}function Gyt(t,e,r){for(var n=r+1,i=0,s=1;s<t.length;s++){var o=(e[s]-e[0])/365;i-=o*t[s]/Math.pow(n,o+1)}return i}Gr.fv=Jbe;Gr.ipmt=Wbe;Gr.irr=qyt;Gr.mirr=jyt;Gr.nper=Myt;Gr.npv=d4;Gr.pmt=p4;Gr.ppmt=Pyt;Gr.pv=$yt;Gr.rate=Uyt});var GI=b((OFr,h4)=>{"use strict";process.env.NODE_ENV==="production"?h4.exports=Gbe():h4.exports=Zbe()});function te(t){return Math.round(t*100)/100}function Ki(t,e){let r=t.split("-");if(r.length!==3)throw new Error(`Invalid date format: ${t}`);let[n,i,s]=r.map(Number);if(!Number.isFinite(n)||!Number.isFinite(i)||!Number.isFinite(s))throw new Error(`Invalid date: ${t}`);let o=i-1+e,a=n+Math.floor(o/12),c=(o%12+12)%12,u=new Date(Date.UTC(a,c+1,0)).getUTCDate(),f=Math.min(s,u);return`${String(a).padStart(4,"0")}-${String(c+1).padStart(2,"0")}-${String(f).padStart(2,"0")}`}var fo=re(()=>{"use strict"});function sn(t,e){if(!Number.isFinite(t)||t<=0)throw new Ut(`${e} must be a positive number (got ${t})`)}function Vu(t,e){if(!Number.isFinite(t)||t<0)throw new Ut(`${e} must be zero or positive (got ${t})`)}function Si(t,e){if(!Number.isInteger(t)||t<1)throw new Ut(`${e} must be a positive integer (got ${t})`)}function jN(t,e){if(t>=e)throw new Ut(`Salvage value (${t}) must be less than cost (${e})`)}function bi(t){if(!t)return;if(!/^\d{4}-\d{2}-\d{2}$/.test(t))throw new Ut(`Date must be YYYY-MM-DD format (got "${t}")`);let e=new Date(t+"T00:00:00");if(isNaN(e.getTime()))throw new Ut(`Invalid date: "${t}"`)}function vd(t,e="Rate"){Vu(t,e),t>100&&process.stderr.write(`Warning: ${e} is ${t}% \u2014 are you sure this isn't a decimal? (e.g. 6 for 6%, not 0.06)
199
199
  `)}function Kbe(t){if(!t||typeof t!="object")throw new Ut("Input must be a JSON object with bankRecords and transactions arrays");let e=t;if(!Array.isArray(e.bankRecords))throw new Ut("bankRecords must be an array");if(!Array.isArray(e.transactions))throw new Ut("transactions must be an array");if(e.bankRecords.length===0)throw new Ut("bankRecords array is empty \u2014 nothing to match");if(e.transactions.length===0)throw new Ut("transactions array is empty \u2014 nothing to match");for(let i=0;i<e.bankRecords.length;i++){let s=e.bankRecords[i];if(!s.id||typeof s.id!="string")throw new Ut(`bankRecords[${i}]: id is required (string)`);if(typeof s.amount!="number"||!Number.isFinite(s.amount))throw new Ut(`bankRecords[${i}]: amount must be a finite number`);if(s.amount===0)throw new Ut(`bankRecords[${i}]: amount must not be zero`);if(!s.date||typeof s.date!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(s.date))throw new Ut(`bankRecords[${i}]: date must be YYYY-MM-DD format`)}for(let i=0;i<e.transactions.length;i++){let s=e.transactions[i];if(!s.id||typeof s.id!="string")throw new Ut(`transactions[${i}]: id is required (string)`);if(s.direction!=="PAYIN"&&s.direction!=="PAYOUT")throw new Ut(`transactions[${i}]: direction must be 'PAYIN' or 'PAYOUT'`);if(typeof s.amount!="number"||!Number.isFinite(s.amount)||s.amount<=0)throw new Ut(`transactions[${i}]: amount must be a positive number`);if(!s.date||typeof s.date!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(s.date))throw new Ut(`transactions[${i}]: date must be YYYY-MM-DD format`);if(s.crossCurrency&&(!s.currency||typeof s.currency!="string"))throw new Ut(`transactions[${i}]: crossCurrency is true but currency is missing`)}let r=e.options;if(r){if(r.tolerance!==void 0&&(typeof r.tolerance!="number"||r.tolerance<0))throw new Ut("options.tolerance must be a non-negative number");if(r.dateWindowDays!==void 0&&(typeof r.dateWindowDays!="number"||!Number.isInteger(r.dateWindowDays)||r.dateWindowDays<0))throw new Ut("options.dateWindowDays must be a non-negative integer");if(r.maxGroupSize!==void 0&&(typeof r.maxGroupSize!="number"||!Number.isInteger(r.maxGroupSize)||r.maxGroupSize<2||r.maxGroupSize>10))throw new Ut("options.maxGroupSize must be an integer between 2 and 10")}let n=r?.exchangeRates;for(let i=0;i<e.transactions.length;i++){let s=e.transactions[i];if(s.crossCurrency&&s.currency&&(!n||typeof n[s.currency]!="number"))throw new Ut(`transactions[${i}]: crossCurrency is true with currency "${s.currency}" but no exchange rate provided in options.exchangeRates`)}return t}var Ut,Ls=re(()=>{"use strict";Ut=class extends Error{constructor(e){super(e),this.name="CalcValidationError"}}});function Qr(t,e,r,n){return{step:t,action:"journal",description:e,date:r,lines:n}}function Xbe(t,e,r,n){return{step:t,action:"bill",description:e,date:r,lines:n}}function e0e(t,e,r,n){return{step:t,action:"invoice",description:e,date:r,lines:n}}function Fm(t,e,r,n){return{step:t,action:"cash-out",description:e,date:r,lines:n}}function YN(t,e,r,n){return{step:t,action:"cash-in",description:e,date:r,lines:n}}function t0e(t,e,r=null){return{step:t,action:"fixed-asset",description:e,date:r,lines:[]}}function r0e(t,e,r=null){return{step:t,action:"note",description:e,date:r,lines:[]}}function oi(t,e){let r=t.toLocaleString("en-US",{minimumFractionDigits:0,maximumFractionDigits:0});return e?`${e} ${r}`:r}function Fe(t,e){let r=t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});return e?`${e} ${r}`:r}var pa=re(()=>{"use strict"});function zN(t){let{principal:e,annualRate:r,termMonths:n,startDate:i,currency:s}=t;sn(e,"Principal"),vd(r,"Annual rate"),Si(n,"Term (months)"),bi(i);let o=r/100/12,a=te(-(0,n0e.pmt)(o,n,e)),c=[],u=e,f=0,d=0;for(let h=1;h<=n;h++){let m=te(u),A=h===n,g,y,C;A?(g=te(m*o),y=m,C=te(y+g)):(g=te(m*o),y=te(a-g),C=a),u=te(m-y),f=te(f+g),d=te(d+y);let E=i?Ki(i,h):null,v={description:`Loan payment \u2014 Month ${h} of ${n}`,lines:[{account:"Loan Payable",debit:y,credit:0},{account:"Interest Expense",debit:g,credit:0},{account:"Cash / Bank Account",debit:0,credit:C}]};c.push({period:h,date:E,openingBalance:m,payment:C,interest:g,principal:y,closingBalance:u,journal:v})}let p=null;if(i){let h=[YN(1,"Record loan proceeds received from bank",i,[{account:"Cash / Bank Account",debit:e,credit:0},{account:"Loan Payable",debit:0,credit:e}]),...c.map((g,y)=>Qr(y+2,g.journal.description,g.date,g.journal.lines))],m=s??void 0,A=["Loan Amortization Workings",`Principal: ${Fe(e,m)} | Rate: ${r}% p.a. (${te(o*100)}% monthly)`,`Term: ${n} months | Monthly payment: ${Fe(a,m)}`,`Total payments: ${Fe(te(f+d),m)} | Total interest: ${Fe(f,m)}`,"Method: PMT formula, constant payment amortization","Rounding: 2dp per period, final period closes balance to $0.00"].join(`
@@ -669,22 +669,22 @@ Unsupported type: `+t.type,"ENOTSUP");t._finish()})};Tc.prototype._stat=function
669
669
  ---
670
670
  `,a),u=c!==-1?c:i.length;return i.slice(o,u).trim()}catch{return null}}function JAr(){let t=QXe(import.meta.url),e=OXe(t),r=[Oh(e,"..","..","..","help-center-mirror"),Oh(e,"..","..","..","assets","skills","api","help-center-mirror"),Oh(e,"help-center-mirror")];for(let n of r)try{return Lce(Oh(n,"index.md"),"utf-8"),n}catch{}return null}var kXe,NXe,UAr,qAr,jAr,YAr,zAr,HAr,GAr,Yj,FXe,Pce=re(()=>{"use strict";Qce();lE();kXe=1.2,NXe=.75,UAr=1.5,qAr=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"]),jAr=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"]]]);YAr=.7,zAr=3,HAr=32,GAr=5;Yj=null,FXe=null});import{existsSync as WAr,readFileSync as ZAr}from"node:fs";import{dirname as KAr,join as $ce}from"node:path";import{fileURLToPath as XAr}from"node:url";function ux(t){let e=t??igr();if(!e)return null;if(zj&&$Xe===e)return zj;try{let r=ZAr(e,"utf-8");return zj=JSON.parse(r),$Xe=e,zj}catch{return null}}function igr(){let t=XAr(import.meta.url),e=KAr(t),r=[$ce(e,"..","..","..","help-center-mirror","help-center-embeddings.json"),$ce(e,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),$ce(e,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(WAr(n))return n;return null}function jXe(t,e){let r=Math.min(t.length,e.length),n=0;for(let i=0;i<r;i++)n+=t[i]*e[i];return n}function YXe(){return Hj!==null?Hj:(Hj=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",Hj||null)}async function Uce(t){let e=YXe();if(!e)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),tgr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:egr,input:t}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!UXe&&(UXe=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
671
671
  `)),null)}catch{return null}}async function lx(t,e,r,n={}){let i=n.mode??"hybrid",s=n.limit??5,o=n.section,a=n.minCosine??rgr,c=n.minBm25??ngr;if(i==="bm25"||!e)return iy(t,r,{limit:s,section:o}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Uce(r);return m?qXe(t,e,m,{limit:s,section:o}).filter(g=>g.score>=a):iy(t,r,{limit:s,section:o}).filter(y=>y.score>=c)}let[u,f]=await Promise.all([Uce(r),Promise.resolve(iy(t,r,{limit:s*2,section:o}))]);if(!u)return f.filter(m=>m.score>=c).slice(0,s);let p=qXe(t,e,u,{limit:s*2,section:o}).filter(m=>m.score>=a),h=f.filter(m=>m.score>=c);return zXe(p,h,s)}function qXe(t,e,r,n){let i=new Map(t.sections.map(c=>[c.slug,c])),s=new Map(t.articles.map(c=>[c.id,c])),o=[];for(let c of e.embeddings){let u=s.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let f=jXe(r,c.vector);o.push({articleId:c.articleId,score:f})}o.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of o.slice(0,n.limit)){let f=s.get(c);if(!f)continue;let d=i.get(f.section);d&&a.push({article:f,score:u,scoreKind:"cosine",section:d,matchedTerms:[]})}return a}function zXe(t,e,r){let n=new Map;for(let s=0;s<t.length;s++){let o=t[s],a=1/(PXe+s+1),c=n.get(o.article.id);c?c.score+=a:n.set(o.article.id,{score:a,result:o})}for(let s=0;s<e.length;s++){let o=e[s],a=1/(PXe+s+1),c=n.get(o.article.id);c?(c.score+=a,c.result=o):n.set(o.article.id,{score:a,result:o})}let i=Array.from(n.values());return i.sort((s,o)=>o.score-s.score),i.slice(0,r).map(s=>({...s.result,score:s.score,scoreKind:"rrf"}))}function qce(t){return t!==null&&!!YXe()}var egr,tgr,PXe,rgr,ngr,zj,$Xe,Hj,UXe,jce=re(()=>{"use strict";Pce();egr="text-embedding-3-small",tgr=2e3,PXe=60,rgr=.3,ngr=1.5,zj=null,$Xe=null,Hj=null,UXe=!1});var Yce=re(()=>{"use strict";Pce();jce()});var HXe,GXe=re(()=>{"use strict";HXe={loan:["cash-in"],lease:["journal"],"prepaid-expense":["bill","cash-out"],"deferred-revenue":["invoice","cash-in"],provision:["journal"],"fixed-deposit":["cash-out"],"accrued-expense":["journal"],dividend:["journal"]}});async function Gj(t,e){let{blueprint:r,accountMap:n,finalize:i}=e,s=!i;sgr(e);let o=await ogr(t,r.capsuleType),a=r.steps[0]?.date??new Date().toISOString().slice(0,10),c=`${r.capsuleName} (${a})`,f={resourceId:(await Xm(t,{capsuleTypeResourceId:o,title:c,description:r.capsuleDescription})).data.resourceId,type:r.capsuleType,title:c},d=WXe(e),p=[],h=[];for(let A of r.steps){if(A.step===d){p.push({step:A.step,action:A.action,status:"existing",resourceId:e.existingTxnId,description:A.description});continue}if(A.action==="fixed-asset"||A.action==="note"){p.push({step:A.step,action:A.action,status:"skipped",description:A.description}),h.push(`Step ${A.step} (${A.action}): ${A.description}`);continue}let g=await agr(t,A,e,s);p.push(g),g.error&&h.push(`Step ${A.step} failed: ${g.error}`)}let m={total:p.length,created:p.filter(A=>A.status==="created").length,existing:p.filter(A=>A.status==="existing").length,skipped:p.filter(A=>A.status==="skipped").length,errors:p.filter(A=>A.status==="error").length,notes:h};return{recipe:e.calcType,capsule:f,steps:p,summary:m}}function sgr(t){let{blueprint:e,accountMap:r,bankAccountId:n,contactId:i}=t;if(!e.steps.length)throw new Error("Blueprint has no steps to execute.");let s=[];for(let f of e.steps)for(let d of f.lines)Hce(d.account,r)||s.push(d.account);let o=[...new Set(s)];if(o.length>0)throw new Error(`Unmapped account(s) in --input: ${o.join(", ")}.
672
- Add these to your account mapping JSON.`);let a=WXe(t);if(e.steps.some(f=>(f.action==="cash-in"||f.action==="cash-out")&&f.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(e.steps.some(f=>(f.action==="bill"||f.action==="invoice")&&f.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function ogr(t,e){let n=(await kE(t)).data.find(s=>s.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await jw(t,{displayName:e})).data.resourceId}function WXe(t){if(!t.existingTxnId)return null;let e=HXe[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function agr(t,e,r,n){let{accountMap:i,referencePrefix:s}=r,o=s?`${s}-${e.step}`:void 0;try{let a;switch(e.action){case"journal":{a=(await fA(t,{reference:o,valueDate:e.date,journalEntries:zce(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await qm(t,{reference:o,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:VXe(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await lA(t,{reference:o,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:VXe(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=JXe(e.lines,r.bankAccountId,i);a=(await cv(t,{reference:o,valueDate:e.date,accountResourceId:r.bankAccountId,lines:zce(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=JXe(e.lines,r.bankAccountId,i);a=(await uv(t,{reference:o,valueDate:e.date,accountResourceId:r.bankAccountId,lines:zce(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:e.step,action:e.action,status:"skipped",description:e.description}}return{step:e.step,action:e.action,status:"created",resourceId:a,description:e.description}}catch(a){return{step:e.step,action:e.action,status:"error",description:e.description,error:a.message}}}function zce(t,e){return t.map(r=>({accountResourceId:Gce(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function VXe(t,e){return t.filter(r=>Hce(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:Gce(r.account,e)}))}function JXe(t,e,r){let n=[],i=null;for(let s of t)Gce(s.account,r)===e&&!i?i=s:n.push(s);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function Hce(t,e){if(e[t])return t;let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return n;return null}function Gce(t,e){let r=Hce(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var Vce=re(()=>{"use strict";ib();jm();rb();Rj();zw();GXe()});async function ZXe(t,e){let n=(await Md((o,a)=>af(t,{offset:o,limit:a}))).data;if(n.length===0)return{mapping:{},failures:e.map(o=>({name:o,candidates:[]}))};let i={},s=[];for(let o of e){let a=_O(o,n);if(a)i[o]=a.resourceId;else{let c=$E(o,n,{threshold:.3,limit:3});s.push({name:o,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:s}}async function KXe(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let f=(await Dd(t,e)).data;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}let n=e.trim(),s=(await rc(t,{filter:{billingName:{contains:n}},limit:50})).data;if(s.length===0&&(s=(await _d(t,{offset:0,limit:500})).data),s.length===0)throw new Error("No contacts found. Create one in Jaz first.");let o=n.toLowerCase(),a=s.find(u=>u.billingName?.toLowerCase()===o||u.name?.toLowerCase()===o);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=DO(n,s,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],f=c.length>1?c[1].score:0;if(c.length===1||u.score-f>=.1){let d=u.item;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}}if(c.length>1){let u=c.map(f=>`${f.item.billingName||f.item.name} (${(f.score*100).toFixed(0)}%)`).join(", ");throw new Error(`Multiple contacts match "${n}": ${u}. Be more specific.`)}throw new Error(`No contact matching "${n}".`)}async function XXe(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let i=await cE(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await $m(t,e);return{resourceId:n.resourceId,displayName:n.name}}var eet=re(()=>{"use strict";PE();Sd();Mm();$1();ZJ();KJ();xF()});async function Qh(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function Lh(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var fx=re(()=>{"use strict"});async function Vj(t,e){return t.post("/api/v1/transfer-trial-balance",e)}var Jce=re(()=>{"use strict"});async function Jj(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function Wj(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function dx(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function Zj(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var Wce=re(()=>{"use strict"});async function Kj(t,e){return t.list("/api/v1/organization-users",e)}async function Xj(t,e){return t.search("/api/v1/organization-users/search",e)}async function fv(t,e){return t.post("/api/v1/organization-users/invite",e)}async function eY(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function tY(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Zce=re(()=>{"use strict"});async function rY(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function px(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function nY(t,e){return t.get(`/api/v1/payments/${e}`)}async function iY(t,e,r){return t.put(`/api/v1/payments/${e}`,r)}async function sY(t,e){await t.delete(`/api/v1/payments/${e}`)}var Kce=re(()=>{"use strict"});async function oY(t,e,r={}){let n=cgr.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var cgr,Xce=re(()=>{"use strict";cgr=new Set(["statement-of-account-export"])});import{createHash as ugr}from"node:crypto";import{writeFile as lgr,mkdir as fgr}from"node:fs/promises";import{dirname as dgr,isAbsolute as pgr,join as hgr}from"node:path";async function tet(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function eue(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function tue(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function mgr(t){return ugr("sha256").update(t).digest("hex").slice(0,16)}async function net(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=mgr(e),s=await eue(t,e,{idempotencyKey:i}),o=s.data.jobId,a=Date.now()+n*1e3,c=s.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await tue(t,o)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:o,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:o,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let f=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let d=process.env.HOME??".";if(r.outPath&&!pgr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??hgr(d,"Downloads",`pseudo-sql-${o}.csv`);return await fgr(dgr(p),{recursive:!0}),await lgr(p,f),{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:f}}}async function iet(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.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 e}var set=re(()=>{"use strict"});async function aY(t){return t.get("/api/v1/capsule-recipes")}async function cY(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function uY(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function lY(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function fY(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function Xo(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((s,o)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`capsuleRecipe.templateOverrides[${o}] must be an object {slotKey, template?}.`);let a=s;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${o}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${o}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var rue=re(()=>{"use strict"});async function ti(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(o=>({...o,resourceId:o.resourceId??o.attachmentResourceId??""})):[]}}async function pY(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,s=new FormData;return i.file&&s.append("file",i.file,i.fileName??"file"),i.attachmentId&&s.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,s)}async function hY(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var dY,Mh=re(()=>{"use strict";dY=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Tl(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var nue=re(()=>{"use strict"});async function kl(t,e,r){if(!e)return t;let n=Agr(t);if(!n)return t;try{return await r(n)}catch(i){let s=i instanceof Error?i.message:String(i),o={status:"failed",resourceId:n,message:s};return t&&typeof t=="object"?{...t,_hydration:o}:{result:t,_hydration:o}}}function Agr(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}var oet=re(()=>{"use strict"});async function mY(t,e){return t.list("/api/v1/bank-rules",e)}async function hx(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),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/${e}`)}async function AY(t,e){return t.search("/api/v1/bank-rules/search",e)}async function gY(t,e){return t.post("/api/v1/bank-rules",e)}async function yY(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function EY(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var iue=re(()=>{"use strict"});async function bY(t,e){return t.list("/api/v1/fixed-assets",e)}async function CY(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function vY(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function IY(t,e){return t.post("/api/v1/fixed-assets",e)}async function wY(t,e,r){return t.put(`/api/v1/fixed-assets/${e}`,r)}async function _Y(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function DY(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function mx(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function SY(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function BY(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function RY(t,e){return $s(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var xY=re(()=>{"use strict";tc()});async function TY(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function Ax(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function kY(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function NY(t,e,r){let n={...r};if(n.endDate){let i=!n.startDate,s=!n.repeat&&!n.interval;if(i||s){let o=await Ax(t,e);if(i&&(n.startDate=o.data.startDate),s){if(!o.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=o.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function FY(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function OY(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function QY(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var sue=re(()=>{"use strict"});async function LY(t,e){return t.list("/api/v1/contact-groups",e)}async function MY(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function PY(t,e){return t.search("/api/v1/contact-groups/search",e)}async function $Y(t,e){return t.post("/api/v1/contact-groups",e)}async function UY(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,r)}async function qY(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var oue=re(()=>{"use strict"});async function jY(t,e){return t.list("/api/v1/inventory-items",e)}async function YY(t,e){return t.post("/api/v1/inventory-items",e)}async function zY(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var aue=re(()=>{"use strict"});async function HY(t,e){return t.list("/api/v1/custom-fields",e)}async function GY(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function VY(t,e){return t.search("/api/v1/custom-fields/search",e)}async function JY(t,e){return t.post("/api/v1/custom-fields",e)}async function WY(t,e,r){return t.put(`/api/v1/custom-fields/${e}`,r)}async function ZY(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var cue=re(()=>{"use strict"});function aet(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function gx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return aet(n)}async function yx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return aet(n)}var ggr,ygr,Egr,dv,uue=re(()=>{"use strict";ggr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],ygr=["journals","cash-entries"],Egr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],dv=[...ggr,...ygr,...Egr]});async function KY(t,e){return t.list("/api/v1/nano-classifiers",e)}async function XY(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function ez(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function Ex(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function bx(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,r)}async function tz(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var lue=re(()=>{"use strict"});async function rz(t,e){return t.post("/api/v1/export-records",e)}async function nz(t,e){return t.post("/api/v1/export-records/preview",e)}async function iz(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var fue=re(()=>{"use strict"});async function Cx(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var due=re(()=>{"use strict"});function pv(t){Ci(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!bgr.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function sz(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:vgr(r.data)}}function Cgr(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function vgr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(Cgr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function oz(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function az(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var bgr,pue=re(()=>{"use strict";tc();bgr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function uet(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function hue(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);ec([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&ec([i],["valueDate"])}function _gr(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=Igr?"high":r>=cet?"medium":"low";if(n!==void 0){if(n>=wgr)return"high";if(n>=cet)return"medium"}return"low"}function fet(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let s=[];for(let o of i){let a=o??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){s.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let f=u.slice().sort((D,R)=>{let Q=D.confidenceScore??D.matchScore??-1;return(R.confidenceScore??R.matchScore??-1)-Q}),d=f[0],p=typeof d.recommendationType=="string"?d.recommendationType:void 0,h=typeof d.matchScore=="number"?d.matchScore:void 0,m=typeof d.confidenceScore=="number"?d.confidenceScore:void 0,A=typeof d.isCrossCurrency=="boolean"?d.isCrossCurrency:void 0,g=typeof d.cftBtResourceId=="string"?d.cftBtResourceId:void 0,y=Array.isArray(d.cftBtResourceIds)?d.cftBtResourceIds:[],C=d.isBatch===!0||y.length>1,E=typeof d.cftAmount=="number"?d.cftAmount:void 0,v,I;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=vx.magicMatch,I={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=vx.withPayments,I={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof d.learnedPredictionResourceId=="string"?d.learnedPredictionResourceId:void 0,R=typeof d.predictedPayload=="string"?d.predictedPayload:void 0,Q=typeof d.predictedPayloadSchemaVersion=="string"?d.predictedPayloadSchemaVersion:void 0;D&&R&&Q&&(v=vx.learnedPrediction,I={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:R,predictedPayloadSchemaVersion:Q});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=d.actionShortcut??{},R=typeof D.resourceId=="string"?D.resourceId:void 0;R&&(v=vx.applyBankRule,I={actionShortcutResourceId:R,businessTransactionResourceIds:[c]});break}default:break}let T=v?_gr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),k=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,Y=v!==vx.withPayments||S,U=T==="high"&&!!v&&!!I&&Y&&k;s.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:v,execute:I,confidenceTier:T,autoCommitEligible:U,alternativeCount:f.length-1})}return s}async function cz(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function uz(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function lz(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function fz(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function dz(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function pz(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function hz(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function mz(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function Az(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function gz(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function yz(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}var vx,Igr,wgr,cet,mue=re(()=>{"use strict";tc();vx={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Igr=.9,wgr=.95,cet=.7});function Do(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let s=t[r]??[];for(let o=0;o<s.length;o++)i.check(s[o])||n.push(`${r}[${o}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function ss(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),s={valueDate:Aue(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(s.contact=Aue(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(s.dueDate=Aue(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let o=t[r]??[];return s.lineItems=o.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,f=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(I=>I.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,v=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||v||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:f}}let d=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=d?d.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:f}}),s}function Aue(t,e,r,n,i){let s=i.find(o=>o.field===e);if(!s){let o=t[e];return o?{status:"ok",value:o}:{status:"ok"}}if(s.check(t)){let o=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||o,resourceId:o}:{status:"ok",value:o}}return{status:"missing",hint:n}}function ws(t,e,r,n="lineItems"){let{missingFields:i,missingCount:s,ready:o}=Do(t,e,n),a=ss(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:o,missingCount:s,missingFields:i,validation:a}}var ea,kc,Gi,Ru,det=re(()=>{"use strict";ea=[{field:"contactResourceId",label:"Contact",hint:"--contact <name or UUID>",check:t=>!!t.contactResourceId},{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],kc=[...ea],Gi=ea.filter(t=>t.field!=="dueDate"),Ru=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Nc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function hv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Ft(t){if(t)return t.split("T")[0]}var gue=re(()=>{"use strict"});function Nl(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let s=Nc(i);return e.account&&!s.accountResourceId&&(s.accountResourceId=e.account),e.taxProfile&&!s.taxProfileResourceId&&(s.taxProfileResourceId=e.taxProfile),s})}return r}function Ez(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let s=hv(i);return e.account&&!s.accountResourceId&&(s.accountResourceId=e.account),s})}return r}var pet=re(()=>{"use strict";gue()});var yue=re(()=>{"use strict";det();gue();pet()});var Ix,xu,het=re(()=>{"use strict";Ix="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",xu="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function xet(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function cn(t,e,r,n,i){return{name:t,description:e,params:{...Iue},required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(s,o)=>{let{limit:a,offset:c}=xet(o);return h_((u,f)=>n(s.client,u,f),a,c,20)}}}function Ma(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,o)=>n(s.client,o.resourceId)}}function So(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(s,o)=>(await n(s.client,o.resourceId),{deleted:!0,resourceId:o.resourceId})}}function bet(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function Tgr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e))if(i!=null)if(n==="organizationAccountResourceId")r.accountResourceId=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 xgr.has(n)&&(r[n]=i);return r}):t}async function _x(t,e,r,n){let o=(await(e==="invoice"?ba:e==="bill"?ga:e==="customer_credit_note"?su:ou)(t,r)).data,a=Rgr[e],c={};for(let[p,h]of Object.entries(o))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=bet(c.valueDate)),c.dueDate&&(c.dueDate=bet(c.dueDate)),c.lineItems&&(c.lineItems=Tgr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?kc:e==="bill"?ea:Gi,{missingFields:f,ready:d}=Do(c,u);if(!d)throw new Error(`Cannot finalize: missing ${f.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function Cet(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function vz(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function wet(t,e,r){let n=Iet[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(Iet).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function _et(t,e,r,n,i,s,o){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${o}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:s,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function Det(t,e,r,n,i,s){let o;try{o=(await e(t,r)).data?.status}catch{return}if(o==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:s,arguments:{},reason:`The source ${n} is VOID.`}}}async function Bet(t,e,r,n,i){let s;try{s=(await e(t,r,n)).data?.status}catch{return}if(s&&s!=="DRAFT")return{error:`Cannot DELETE a ${s} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${s}; void it instead of deleting.`}}}var Pa,os,Tu,as,ri,Fl,bz,sy,Eue,cy,Dgr,Sgr,bue,met,Cue,Iue,oy,vue,Aet,get,yet,Eet,Vi,Bgr,ay,ta,Ret,Ol,wx,Rgr,xgr,Dx,Sx,Cz,vet,Iet,Fc,mv=re(()=>{"use strict";f_();Gu();Jr();Ud();Nm();PE();Sd();rb();jm();F9();O9();ib();Q9();Mm();iO();gO();zw();qQ();JQ();tL();BXe();Hw();Rj();Tce();kce();Nce();Fce();Yce();Vce();eet();Mm();fx();Jce();Wce();Zce();Kce();Xce();set();rue();Mh();nue();SF();R9();oet();iue();xY();sue();oue();aue();cue();uue();lue();fue();due();Sd();rb();jm();qQ();JQ();ib();xY();tc();pue();mue();Jr();aF();_9();cF();R4();x4();T4();k4();N4();F4();O4();Q4();L4();M4();yue();het();Pa={type:"string",description:"Resource ID of the record"},os={type:"string",description:"Transaction date (YYYY-MM-DD)"},Tu={type:"string",description:"Due date (YYYY-MM-DD)"},as={type:"string",description:"Reference number"},ri={type:"string",description:"Notes or memo text"},Fl={type:"string",description:"Tag name for categorization"},bz={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},sy={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Eue={type:"string",description:"Contact resourceId (customer or supplier)"},cy={type:"string",description:"Bank/cash account resourceId"},Dgr={type:"number",description:"Payment amount (in bank currency)"},Sgr={type:"string",description:"Period start date (YYYY-MM-DD)"},bue={type:"string",description:"Period end date (YYYY-MM-DD)"},met={type:"string",description:"Currency code (e.g. SGD, USD)"},Cue={type:"string",description:"Display name"},Iue={limit:{type:"number",description:"Max results per page (default 20, max 1000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},oy={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},vue={type:"string",enum:[...ff],description:"Entity type to export"},Aet={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},get={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},yet={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."},Eet={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."},Vi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Bgr={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",properties:{className:{type:"string"},resourceId:Pa}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},ay={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)"},ta={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:cy,taxProfileResourceId:{type:"string"},classifierConfig:Bgr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},Ret={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},Ol={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",description:"list_capsule_recipes enum. Must match mutation's allowedBaseTransactionTypes."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:Ret},required:["recipeName","inputs"]},wx={type:"string",enum:[...rSe],description:"Payment method (default BANK_TRANSFER)"};Rgr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","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"])};xgr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);Dx={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},Sx={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},Cz={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},vet={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},Iet={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};Fc=[{name:"get_organization",description:"Get organization details (name, currency, country, lock date, fiscal year end).",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>da(t.client)},cn("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>af(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),en({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:L_,defaults:M_,fetcher:ME,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 \u2014 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. Classic 12: Bank Accounts | Cash | Current Asset | Fixed Asset | Inventory | Current Liability | Non-current Liability | Shareholders Equity | Operating Revenue | Other Revenue | Operating Expense | Direct Costs. IFRS 18 (effective 2027): Discontinued Expense | Discontinued Income | Finance Cost | Financing Income | Goodwill | Income Tax Expense | Investing Expense | Investing Income | Investment. Common variants normalized client-side. For "interest expense"/"interest income", pick Financing or Investing yourself \u2014 depends on entity main business activity, NOT auto-classified.'},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code",execute:async(t,e)=>{let r=e.name,n=await EO(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=LE(e.accountType);return Jw(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode})}},{name:"update_account",description:"Update an existing chart of accounts entry (name or code).",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code",execute:async(t,e)=>{let r=e.resourceId,n=(await j_e(t.client,r)).data,s=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(o=>n[o]!==void 0&&n[o]!==null).map(o=>[o,n[o]]));return!s.classificationType&&n.accountType&&(s.classificationType=n.accountType),e.name!==void 0&&(s.name=e.name),e.code!==void 0&&(s.code=e.code),Y_e(t.client,r,s)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
672
+ Add these to your account mapping JSON.`);let a=WXe(t);if(e.steps.some(f=>(f.action==="cash-in"||f.action==="cash-out")&&f.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(e.steps.some(f=>(f.action==="bill"||f.action==="invoice")&&f.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function ogr(t,e){let n=(await kE(t)).data.find(s=>s.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await jw(t,{displayName:e})).data.resourceId}function WXe(t){if(!t.existingTxnId)return null;let e=HXe[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function agr(t,e,r,n){let{accountMap:i,referencePrefix:s}=r,o=s?`${s}-${e.step}`:void 0;try{let a;switch(e.action){case"journal":{a=(await fA(t,{reference:o,valueDate:e.date,journalEntries:zce(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await qm(t,{reference:o,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:VXe(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await lA(t,{reference:o,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:VXe(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=JXe(e.lines,r.bankAccountId,i);a=(await cv(t,{reference:o,valueDate:e.date,accountResourceId:r.bankAccountId,lines:zce(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=JXe(e.lines,r.bankAccountId,i);a=(await uv(t,{reference:o,valueDate:e.date,accountResourceId:r.bankAccountId,lines:zce(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:e.step,action:e.action,status:"skipped",description:e.description}}return{step:e.step,action:e.action,status:"created",resourceId:a,description:e.description}}catch(a){return{step:e.step,action:e.action,status:"error",description:e.description,error:a.message}}}function zce(t,e){return t.map(r=>({accountResourceId:Gce(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function VXe(t,e){return t.filter(r=>Hce(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:Gce(r.account,e)}))}function JXe(t,e,r){let n=[],i=null;for(let s of t)Gce(s.account,r)===e&&!i?i=s:n.push(s);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function Hce(t,e){if(e[t])return t;let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return n;return null}function Gce(t,e){let r=Hce(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var Vce=re(()=>{"use strict";ib();jm();rb();Rj();zw();GXe()});async function ZXe(t,e){let n=(await Md((o,a)=>af(t,{offset:o,limit:a}))).data;if(n.length===0)return{mapping:{},failures:e.map(o=>({name:o,candidates:[]}))};let i={},s=[];for(let o of e){let a=_O(o,n);if(a)i[o]=a.resourceId;else{let c=$E(o,n,{threshold:.3,limit:3});s.push({name:o,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:s}}async function KXe(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let f=(await Dd(t,e)).data;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}let n=e.trim(),s=(await rc(t,{filter:{billingName:{contains:n}},limit:50})).data;if(s.length===0&&(s=(await _d(t,{offset:0,limit:500})).data),s.length===0)throw new Error("No contacts found. Create one in Jaz first.");let o=n.toLowerCase(),a=s.find(u=>u.billingName?.toLowerCase()===o||u.name?.toLowerCase()===o);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=DO(n,s,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],f=c.length>1?c[1].score:0;if(c.length===1||u.score-f>=.1){let d=u.item;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}}if(c.length>1){let u=c.map(f=>`${f.item.billingName||f.item.name} (${(f.score*100).toFixed(0)}%)`).join(", ");throw new Error(`Multiple contacts match "${n}": ${u}. Be more specific.`)}throw new Error(`No contact matching "${n}".`)}async function XXe(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let i=await cE(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await $m(t,e);return{resourceId:n.resourceId,displayName:n.name}}var eet=re(()=>{"use strict";PE();Sd();Mm();$1();ZJ();KJ();xF()});async function Qh(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function Lh(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var fx=re(()=>{"use strict"});async function Vj(t,e){return t.post("/api/v1/transfer-trial-balance",e)}var Jce=re(()=>{"use strict"});async function Jj(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function Wj(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function dx(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function Zj(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var Wce=re(()=>{"use strict"});async function Kj(t,e){return t.list("/api/v1/organization-users",e)}async function Xj(t,e){return t.search("/api/v1/organization-users/search",e)}async function fv(t,e){return t.post("/api/v1/organization-users/invite",e)}async function eY(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function tY(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Zce=re(()=>{"use strict"});async function rY(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function px(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function nY(t,e){return t.get(`/api/v1/payments/${e}`)}async function iY(t,e,r){return t.put(`/api/v1/payments/${e}`,r)}async function sY(t,e){await t.delete(`/api/v1/payments/${e}`)}var Kce=re(()=>{"use strict"});async function oY(t,e,r={}){let n=cgr.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var cgr,Xce=re(()=>{"use strict";cgr=new Set(["statement-of-account-export"])});import{createHash as ugr}from"node:crypto";import{writeFile as lgr,mkdir as fgr}from"node:fs/promises";import{dirname as dgr,isAbsolute as pgr,join as hgr}from"node:path";async function tet(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function eue(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function tue(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function mgr(t){return ugr("sha256").update(t).digest("hex").slice(0,16)}async function net(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=mgr(e),s=await eue(t,e,{idempotencyKey:i}),o=s.data.jobId,a=Date.now()+n*1e3,c=s.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await tue(t,o)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:o,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:o,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let f=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let d=process.env.HOME??".";if(r.outPath&&!pgr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??hgr(d,"Downloads",`pseudo-sql-${o}.csv`);return await fgr(dgr(p),{recursive:!0}),await lgr(p,f),{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:f}}}async function iet(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.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 e}var set=re(()=>{"use strict"});async function aY(t){return t.get("/api/v1/capsule-recipes")}async function cY(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function uY(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function lY(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function fY(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function Xo(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((s,o)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`capsuleRecipe.templateOverrides[${o}] must be an object {slotKey, template?}.`);let a=s;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${o}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${o}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var rue=re(()=>{"use strict"});async function ti(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(o=>({...o,resourceId:o.resourceId??o.attachmentResourceId??""})):[]}}async function pY(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,s=new FormData;return i.file&&s.append("file",i.file,i.fileName??"file"),i.attachmentId&&s.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,s)}async function hY(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var dY,Mh=re(()=>{"use strict";dY=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Tl(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var nue=re(()=>{"use strict"});async function kl(t,e,r){if(!e)return t;let n=Agr(t);if(!n)return t;try{return await r(n)}catch(i){let s=i instanceof Error?i.message:String(i),o={status:"failed",resourceId:n,message:s};return t&&typeof t=="object"?{...t,_hydration:o}:{result:t,_hydration:o}}}function Agr(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}var oet=re(()=>{"use strict"});async function mY(t,e){return t.list("/api/v1/bank-rules",e)}async function hx(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),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/${e}`)}async function AY(t,e){return t.search("/api/v1/bank-rules/search",e)}async function gY(t,e){return t.post("/api/v1/bank-rules",e)}async function yY(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function EY(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var iue=re(()=>{"use strict"});async function bY(t,e){return t.list("/api/v1/fixed-assets",e)}async function CY(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function vY(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function IY(t,e){return t.post("/api/v1/fixed-assets",e)}async function wY(t,e,r){return t.put(`/api/v1/fixed-assets/${e}`,r)}async function _Y(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function DY(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function mx(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function SY(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function BY(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function RY(t,e){return $s(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var xY=re(()=>{"use strict";tc()});async function TY(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function Ax(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function kY(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function NY(t,e,r){let n={...r};if(n.endDate){let i=!n.startDate,s=!n.repeat&&!n.interval;if(i||s){let o=await Ax(t,e);if(i&&(n.startDate=o.data.startDate),s){if(!o.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=o.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function FY(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function OY(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function QY(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var sue=re(()=>{"use strict"});async function LY(t,e){return t.list("/api/v1/contact-groups",e)}async function MY(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function PY(t,e){return t.search("/api/v1/contact-groups/search",e)}async function $Y(t,e){return t.post("/api/v1/contact-groups",e)}async function UY(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,r)}async function qY(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var oue=re(()=>{"use strict"});async function jY(t,e){return t.list("/api/v1/inventory-items",e)}async function YY(t,e){return t.post("/api/v1/inventory-items",e)}async function zY(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var aue=re(()=>{"use strict"});async function HY(t,e){return t.list("/api/v1/custom-fields",e)}async function GY(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function VY(t,e){return t.search("/api/v1/custom-fields/search",e)}async function JY(t,e){return t.post("/api/v1/custom-fields",e)}async function WY(t,e,r){return t.put(`/api/v1/custom-fields/${e}`,r)}async function ZY(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var cue=re(()=>{"use strict"});function aet(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function gx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return aet(n)}async function yx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return aet(n)}var ggr,ygr,Egr,dv,uue=re(()=>{"use strict";ggr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],ygr=["journals","cash-entries"],Egr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],dv=[...ggr,...ygr,...Egr]});async function KY(t,e){return t.list("/api/v1/nano-classifiers",e)}async function XY(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function ez(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function Ex(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function bx(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,r)}async function tz(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var lue=re(()=>{"use strict"});async function rz(t,e){return t.post("/api/v1/export-records",e)}async function nz(t,e){return t.post("/api/v1/export-records/preview",e)}async function iz(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var fue=re(()=>{"use strict"});async function Cx(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var due=re(()=>{"use strict"});function pv(t){Ci(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!bgr.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function sz(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:vgr(r.data)}}function Cgr(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function vgr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(Cgr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function oz(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function az(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var bgr,pue=re(()=>{"use strict";tc();bgr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function uet(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function hue(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);ec([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&ec([i],["valueDate"])}function _gr(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=Igr?"high":r>=cet?"medium":"low";if(n!==void 0){if(n>=wgr)return"high";if(n>=cet)return"medium"}return"low"}function fet(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let s=[];for(let o of i){let a=o??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){s.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let f=u.slice().sort((D,R)=>{let Q=D.confidenceScore??D.matchScore??-1;return(R.confidenceScore??R.matchScore??-1)-Q}),d=f[0],p=typeof d.recommendationType=="string"?d.recommendationType:void 0,h=typeof d.matchScore=="number"?d.matchScore:void 0,m=typeof d.confidenceScore=="number"?d.confidenceScore:void 0,A=typeof d.isCrossCurrency=="boolean"?d.isCrossCurrency:void 0,g=typeof d.cftBtResourceId=="string"?d.cftBtResourceId:void 0,y=Array.isArray(d.cftBtResourceIds)?d.cftBtResourceIds:[],C=d.isBatch===!0||y.length>1,E=typeof d.cftAmount=="number"?d.cftAmount:void 0,v,I;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=vx.magicMatch,I={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=vx.withPayments,I={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof d.learnedPredictionResourceId=="string"?d.learnedPredictionResourceId:void 0,R=typeof d.predictedPayload=="string"?d.predictedPayload:void 0,Q=typeof d.predictedPayloadSchemaVersion=="string"?d.predictedPayloadSchemaVersion:void 0;D&&R&&Q&&(v=vx.learnedPrediction,I={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:R,predictedPayloadSchemaVersion:Q});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=d.actionShortcut??{},R=typeof D.resourceId=="string"?D.resourceId:void 0;R&&(v=vx.applyBankRule,I={actionShortcutResourceId:R,businessTransactionResourceIds:[c]});break}default:break}let T=v?_gr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),k=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,Y=v!==vx.withPayments||S,U=T==="high"&&!!v&&!!I&&Y&&k;s.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:v,execute:I,confidenceTier:T,autoCommitEligible:U,alternativeCount:f.length-1})}return s}async function cz(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function uz(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function lz(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function fz(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function dz(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function pz(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function hz(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function mz(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function Az(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function gz(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function yz(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}var vx,Igr,wgr,cet,mue=re(()=>{"use strict";tc();vx={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Igr=.9,wgr=.95,cet=.7});function Do(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let s=t[r]??[];for(let o=0;o<s.length;o++)i.check(s[o])||n.push(`${r}[${o}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function ss(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),s={valueDate:Aue(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(s.contact=Aue(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(s.dueDate=Aue(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let o=t[r]??[];return s.lineItems=o.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,f=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(I=>I.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,v=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||v||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:f}}let d=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=d?d.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:f}}),s}function Aue(t,e,r,n,i){let s=i.find(o=>o.field===e);if(!s){let o=t[e];return o?{status:"ok",value:o}:{status:"ok"}}if(s.check(t)){let o=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||o,resourceId:o}:{status:"ok",value:o}}return{status:"missing",hint:n}}function ws(t,e,r,n="lineItems"){let{missingFields:i,missingCount:s,ready:o}=Do(t,e,n),a=ss(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:o,missingCount:s,missingFields:i,validation:a}}var ea,kc,Gi,Ru,det=re(()=>{"use strict";ea=[{field:"contactResourceId",label:"Contact",hint:"--contact <name or UUID>",check:t=>!!t.contactResourceId},{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],kc=[...ea],Gi=ea.filter(t=>t.field!=="dueDate"),Ru=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Nc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function hv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Ft(t){if(t)return t.split("T")[0]}var gue=re(()=>{"use strict"});function Nl(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let s=Nc(i);return e.account&&!s.accountResourceId&&(s.accountResourceId=e.account),e.taxProfile&&!s.taxProfileResourceId&&(s.taxProfileResourceId=e.taxProfile),s})}return r}function Ez(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let s=hv(i);return e.account&&!s.accountResourceId&&(s.accountResourceId=e.account),s})}return r}var pet=re(()=>{"use strict";gue()});var yue=re(()=>{"use strict";det();gue();pet()});var Ix,xu,het=re(()=>{"use strict";Ix="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",xu="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function xet(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function cn(t,e,r,n,i,s){let o={...Iue};return s?.leanView&&(o.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:t,description:e,params:o,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:f}=xet(c),d=s?.leanView?c.view==="full"?"full":"lean":void 0;return h_((p,h)=>n(a.client,p,h,d),u,f,20)}}}function Ma(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,o)=>n(s.client,o.resourceId)}}function So(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(s,o)=>(await n(s.client,o.resourceId),{deleted:!0,resourceId:o.resourceId})}}function bet(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function Tgr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e))if(i!=null)if(n==="organizationAccountResourceId")r.accountResourceId=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 xgr.has(n)&&(r[n]=i);return r}):t}async function _x(t,e,r,n){let o=(await(e==="invoice"?ba:e==="bill"?ga:e==="customer_credit_note"?su:ou)(t,r)).data,a=Rgr[e],c={};for(let[p,h]of Object.entries(o))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=bet(c.valueDate)),c.dueDate&&(c.dueDate=bet(c.dueDate)),c.lineItems&&(c.lineItems=Tgr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?kc:e==="bill"?ea:Gi,{missingFields:f,ready:d}=Do(c,u);if(!d)throw new Error(`Cannot finalize: missing ${f.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function Cet(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function vz(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function wet(t,e,r){let n=Iet[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(Iet).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function _et(t,e,r,n,i,s,o){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${o}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:s,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function Det(t,e,r,n,i,s){let o;try{o=(await e(t,r)).data?.status}catch{return}if(o==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:s,arguments:{},reason:`The source ${n} is VOID.`}}}async function Bet(t,e,r,n,i){let s;try{s=(await e(t,r,n)).data?.status}catch{return}if(s&&s!=="DRAFT")return{error:`Cannot DELETE a ${s} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${s}; void it instead of deleting.`}}}var Pa,os,Tu,as,ri,Fl,bz,sy,Eue,cy,Dgr,Sgr,bue,met,Cue,Iue,oy,vue,Aet,get,yet,Eet,Vi,Bgr,ay,ta,Ret,Ol,wx,Rgr,xgr,Dx,Sx,Cz,vet,Iet,Fc,mv=re(()=>{"use strict";f_();Gu();Jr();Ud();Nm();PE();Sd();rb();jm();F9();O9();ib();Q9();Mm();iO();gO();zw();qQ();JQ();tL();BXe();Hw();Rj();Tce();kce();Nce();Fce();Yce();Vce();eet();Mm();fx();Jce();Wce();Zce();Kce();Xce();set();rue();Mh();nue();SF();R9();oet();iue();xY();sue();oue();aue();cue();uue();lue();fue();due();Sd();rb();jm();qQ();JQ();ib();xY();tc();pue();mue();Jr();aF();_9();cF();R4();x4();T4();k4();N4();F4();O4();Q4();L4();M4();yue();het();Pa={type:"string",description:"Resource ID of the record"},os={type:"string",description:"Transaction date (YYYY-MM-DD)"},Tu={type:"string",description:"Due date (YYYY-MM-DD)"},as={type:"string",description:"Reference number"},ri={type:"string",description:"Notes or memo text"},Fl={type:"string",description:"Tag name for categorization"},bz={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},sy={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Eue={type:"string",description:"Contact resourceId (customer or supplier)"},cy={type:"string",description:"Bank/cash account resourceId"},Dgr={type:"number",description:"Payment amount (in bank currency)"},Sgr={type:"string",description:"Period start date (YYYY-MM-DD)"},bue={type:"string",description:"Period end date (YYYY-MM-DD)"},met={type:"string",description:"Currency code (e.g. SGD, USD)"},Cue={type:"string",description:"Display name"},Iue={limit:{type:"number",description:"Max results per page (default 20, max 1000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},oy={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},vue={type:"string",enum:[...ff],description:"Entity type to export"},Aet={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},get={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},yet={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."},Eet={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."},Vi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Bgr={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",properties:{className:{type:"string"},resourceId:Pa}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},ay={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)"},ta={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:cy,taxProfileResourceId:{type:"string"},classifierConfig:Bgr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},Ret={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},Ol={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",description:"list_capsule_recipes enum. Must match mutation's allowedBaseTransactionTypes."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:Ret},required:["recipeName","inputs"]},wx={type:"string",enum:[...rSe],description:"Payment method (default BANK_TRANSFER)"};Rgr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","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"])};xgr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);Dx={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},Sx={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},Cz={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},vet={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},Iet={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};Fc=[{name:"get_organization",description:"Get organization details (name, currency, country, lock date, fiscal year end).",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>da(t.client)},cn("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>af(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),en({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:L_,defaults:M_,fetcher:ME,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 \u2014 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. Classic 12: Bank Accounts | Cash | Current Asset | Fixed Asset | Inventory | Current Liability | Non-current Liability | Shareholders Equity | Operating Revenue | Other Revenue | Operating Expense | Direct Costs. IFRS 18 (effective 2027): Discontinued Expense | Discontinued Income | Finance Cost | Financing Income | Goodwill | Income Tax Expense | Investing Expense | Investing Income | Investment. Common variants normalized client-side. For "interest expense"/"interest income", pick Financing or Investing yourself \u2014 depends on entity main business activity, NOT auto-classified.'},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code",execute:async(t,e)=>{let r=e.name,n=await EO(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=LE(e.accountType);return Jw(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode})}},{name:"update_account",description:"Update an existing chart of accounts entry (name or code).",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code",execute:async(t,e)=>{let r=e.resourceId,n=(await j_e(t.client,r)).data,s=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(o=>n[o]!==void 0&&n[o]!==null).map(o=>[o,n[o]]));return!s.classificationType&&n.accountType&&(s.classificationType=n.accountType),e.name!==void 0&&(s.name=e.name),e.code!==void 0&&(s.code=e.code),Y_e(t.client,r,s)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
673
673
 
674
674
  resourceId per row \u2192 update; omit \u2192 create. Note: dedup is by NAME (not code) \u2014 duplicate name surfaces ORGANIZATION_CHART_OF_ACCOUNT_DUPLICATED per row. Accepts classic 12 + 9 IFRS 18 accountType values; common variants normalized via normalizeAccountType.
675
675
 
676
- Use for CoA imports / IFRS 18 migration / template seeding. For one-off creates with dedup, use create_account.`,params:{accounts:{type:"array",description:"Array of chart-of-accounts entries (max 500). Mix create and update freely.",items:{type:"object",properties:{resourceId:{type:"string",description:"Account resourceId (UUID) \u2014 provide to update, omit to create"},code:{type:"string",description:"Account code (unique per org)"},name:{type:"string",description:"Account name (unique per org \u2014 dedup key)"},accountType:{type:"string",description:'Classic 12 or IFRS 18 set per create_account description (e.g. "Operating Expense", "Finance Cost"). Variants normalized client-side ("income tax" \u2192 "Income Tax Expense"). Required for create.'},currencyCode:{type:"string",description:'Currency code (e.g. "SGD"). Defaults to org functional currency.'},description:{type:"string",description:"Optional description / memo"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Account status"}}}}},required:["accounts"],group:"accounts",readOnly:!1,searchHint:"bulk create or update chart of accounts import COA migration",execute:async(t,e)=>{Ci(e.accounts,"accounts",500,"chart-of-accounts entries");let r=e.accounts.map(vO);return(await IO(t.client,r)).data}},cn("list_contacts","List contacts (customers/suppliers). Returns billingName, name, emails, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","contacts",(t,e,r)=>_d(t,{limit:r,offset:e}),"list customers suppliers contacts with email status"),en({name:"search_contacts",description:"Search contacts.",group:"contacts",fields:I_,defaults:w_,fetcher:rc,searchHint:"find contacts customers suppliers vendors by name email role status tax-id tag"}),{name:"get_contact",description:"Get full contact details by resourceId.",params:{resourceId:{type:"string",description:"Contact resourceId (UUID)"}},required:["resourceId"],group:"contacts",readOnly:!0,searchHint:"get contact customer supplier details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>Dd(t.client,e.resourceId)},{name:"get_contact_signals",description:`Read-only contact pattern intelligence (cadence, outliers, divergences, severity). USE THIS for stand-alone history lookup before drafting (e.g. "what does this supplier normally look like?"). Use validate_drafts instead when you have a specific draft to score.
676
+ Use for CoA imports / IFRS 18 migration / template seeding. For one-off creates with dedup, use create_account.`,params:{accounts:{type:"array",description:"Array of chart-of-accounts entries (max 500). Mix create and update freely.",items:{type:"object",properties:{resourceId:{type:"string",description:"Account resourceId (UUID) \u2014 provide to update, omit to create"},code:{type:"string",description:"Account code (unique per org)"},name:{type:"string",description:"Account name (unique per org \u2014 dedup key)"},accountType:{type:"string",description:'Classic 12 or IFRS 18 set per create_account description (e.g. "Operating Expense", "Finance Cost"). Variants normalized client-side ("income tax" \u2192 "Income Tax Expense"). Required for create.'},currencyCode:{type:"string",description:'Currency code (e.g. "SGD"). Defaults to org functional currency.'},description:{type:"string",description:"Optional description / memo"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Account status"}}}}},required:["accounts"],group:"accounts",readOnly:!1,searchHint:"bulk create or update chart of accounts import COA migration",execute:async(t,e)=>{Ci(e.accounts,"accounts",500,"chart-of-accounts entries");let r=e.accounts.map(vO);return(await IO(t.client,r)).data}},cn("list_contacts","List contacts (customers/suppliers). Returns billingName, name, emails, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","contacts",(t,e,r,n)=>_d(t,{limit:r,offset:e,view:n}),"list customers suppliers contacts with email status",{leanView:!0}),en({name:"search_contacts",description:"Search contacts.",group:"contacts",fields:I_,defaults:w_,fetcher:rc,searchHint:"find contacts customers suppliers vendors by name email role status tax-id tag"}),{name:"get_contact",description:"Get full contact details by resourceId.",params:{resourceId:{type:"string",description:"Contact resourceId (UUID)"}},required:["resourceId"],group:"contacts",readOnly:!0,searchHint:"get contact customer supplier details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>Dd(t.client,e.resourceId)},{name:"get_contact_signals",description:`Read-only contact pattern intelligence (cadence, outliers, divergences, severity). USE THIS for stand-alone history lookup before drafting (e.g. "what does this supplier normally look like?"). Use validate_drafts instead when you have a specific draft to score.
677
677
 
678
678
  Returns null when the contact has no qualifying history yet (sampleSize < 5) or the freshness layer is unavailable. Per-pair cache (contactId \xD7 btType) \u2014 duplicate calls for the same pair return the same result.
679
679
 
680
- Three response slices (severitySummary, outlierFlags, revealedDivergences) populate ONLY on the validate_drafts path \u2014 empty/null here.`,params:{resourceId:{type:"string",description:"Contact resourceId (UUID)"},btType:{type:"string",description:"Business-transaction type to scope the signal sample to.",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"]}},required:["resourceId","btType"],group:"contacts",readOnly:!0,searchHint:"contact signals patterns cadence outliers severity history",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>{let r=e.resourceId;return q_e(r,"resourceId","Call search_contacts to get a valid contact resourceId."),NCe(t.client,r,e.btType)}},{name:"create_contact",description:"Create a new contact. Auto-checks for duplicates by name \u2014 returns existing contact if found instead of creating a duplicate.",params:{billingName:{type:"string",description:"Official billing name"},name:{type:"string",description:"Display name (usually same as billingName)"},email:{type:"string",description:"Primary email address"},customer:{type:"boolean",description:"Is a customer (default true)"},supplier:{type:"boolean",description:"Is a supplier (default false)"},returnFullEntity:sy},required:["billingName"],group:"contacts",readOnly:!1,searchHint:"create new customer or supplier contact",execute:async(t,e)=>{let r=e.name??e.billingName,n=e.returnFullEntity===!0,i=await Vw(t.client,r);if(i)return{_guard:"duplicate_skipped",message:`Contact "${r}" already exists.`,existing:i};let s=await fE(t.client,{billingName:e.billingName,name:r,emails:e.email?[e.email]:void 0,customer:e.customer??!0,supplier:e.supplier??!1});return kl(s,n,o=>Dd(t.client,o))}},{name:"update_contact",description:"Update an existing contact. Fetches current data first so you only need to send changed fields.",params:{resourceId:{type:"string",description:"Contact resourceId"},billingName:{type:"string"},name:Cue,email:{type:"string"}},required:["resourceId"],group:"contacts",readOnly:!1,searchHint:"update existing contact billing name email details",execute:async(t,e)=>{let{resourceId:r,...n}=e,{data:i}=await Dd(t.client,r),s=["billingName","name","email","customer","supplier","taxId","phone","status","currencyCode","customerPaymentTerms"],o=i,a=Object.fromEntries(s.filter(c=>o[c]!==void 0&&o[c]!==null).map(c=>[c,o[c]]));return Object.assign(a,n),UF(t.client,r,a)}},cn("list_invoices","List invoices. Returns reference, date, status, contact, totalAmount. Paginated \u2014 response includes totalElements. Use limit/offset to page.","invoices",(t,e,r)=>YO(t,{limit:r,offset:e}),"list sales invoices with pagination and status"),en({name:"search_invoices",description:'Search invoices. Supports comma-separated status (e.g., "UNPAID,PARTIALLY_PAID"). Use filter param for advanced queries (nested paths, OR groups).',group:"invoices",fields:ZE,defaults:KE,fetcher:tb,searchHint:"find sales invoices by status date contact amount"}),{name:"get_invoice",description:"Get full invoice details including line items, payments, totals.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!0,searchHint:"get invoice details line items payments totals",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>ba(t.client,e.resourceId)},{name:"create_invoice",description:`Create invoice. lineItem text field = \`name\` (not "description"). saveAsDraft defaults true \u2014 false only on "finalize".
680
+ Three response slices (severitySummary, outlierFlags, revealedDivergences) populate ONLY on the validate_drafts path \u2014 empty/null here.`,params:{resourceId:{type:"string",description:"Contact resourceId (UUID)"},btType:{type:"string",description:"Business-transaction type to scope the signal sample to.",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"]}},required:["resourceId","btType"],group:"contacts",readOnly:!0,searchHint:"contact signals patterns cadence outliers severity history",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>{let r=e.resourceId;return q_e(r,"resourceId","Call search_contacts to get a valid contact resourceId."),NCe(t.client,r,e.btType)}},{name:"create_contact",description:"Create a new contact. Auto-checks for duplicates by name \u2014 returns existing contact if found instead of creating a duplicate.",params:{billingName:{type:"string",description:"Official billing name"},name:{type:"string",description:"Display name (usually same as billingName)"},email:{type:"string",description:"Primary email address"},customer:{type:"boolean",description:"Is a customer (default true)"},supplier:{type:"boolean",description:"Is a supplier (default false)"},returnFullEntity:sy},required:["billingName"],group:"contacts",readOnly:!1,searchHint:"create new customer or supplier contact",execute:async(t,e)=>{let r=e.name??e.billingName,n=e.returnFullEntity===!0,i=await Vw(t.client,r);if(i)return{_guard:"duplicate_skipped",message:`Contact "${r}" already exists.`,existing:i};let s=await fE(t.client,{billingName:e.billingName,name:r,emails:e.email?[e.email]:void 0,customer:e.customer??!0,supplier:e.supplier??!1});return kl(s,n,o=>Dd(t.client,o))}},{name:"update_contact",description:"Update an existing contact. Fetches current data first so you only need to send changed fields.",params:{resourceId:{type:"string",description:"Contact resourceId"},billingName:{type:"string"},name:Cue,email:{type:"string"}},required:["resourceId"],group:"contacts",readOnly:!1,searchHint:"update existing contact billing name email details",execute:async(t,e)=>{let{resourceId:r,...n}=e,{data:i}=await Dd(t.client,r),s=["billingName","name","email","customer","supplier","taxId","phone","status","currencyCode","customerPaymentTerms"],o=i,a=Object.fromEntries(s.filter(c=>o[c]!==void 0&&o[c]!==null).map(c=>[c,o[c]]));return Object.assign(a,n),UF(t.client,r,a)}},cn("list_invoices","List invoices. Returns reference, date, status, contact, totalAmount. Paginated \u2014 response includes totalElements. Use limit/offset to page.","invoices",(t,e,r,n)=>YO(t,{limit:r,offset:e,view:n}),"list sales invoices with pagination and status",{leanView:!0}),en({name:"search_invoices",description:'Search invoices. Supports comma-separated status (e.g., "UNPAID,PARTIALLY_PAID"). Use filter param for advanced queries (nested paths, OR groups).',group:"invoices",fields:ZE,defaults:KE,fetcher:tb,searchHint:"find sales invoices by status date contact amount"}),{name:"get_invoice",description:"Get full invoice details including line items, payments, totals.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!0,searchHint:"get invoice details line items payments totals",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>ba(t.client,e.resourceId)},{name:"create_invoice",description:`Create invoice. lineItem text field = \`name\` (not "description"). saveAsDraft defaults true \u2014 false only on "finalize".
681
681
 
682
682
  REQUIRED: contactResourceId (search first), and accountResourceId per lineItem when finalizing. lineItem minimum: \`{ name, unitPrice, quantity, accountResourceId }\`. Currency: \`{ sourceCurrency: "USD", exchangeRate: 1.35 }\`. Dates YYYY-MM-DD.
683
683
 
684
684
  reference MUST be unique per org \u2014 auto-generate with timestamp if user doesn't specify (e.g. INV-20260309-1430). Duplicate \u2192 422.
685
685
 
686
686
  Optional capsuleRecipe (SALE base only \u2014 DEFERRED_REVENUE). Other recipes silently null here; pre-flight with preview_capsule_recipe. Mutex with capsuleResourceId. Rule 143.`,params:{reference:{type:"string",description:"Invoice reference number"},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Contact resourceId"},lineItems:ta,currency:oy,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:ri,tag:Fl,customFields:Vi,capsuleRecipe:Ol,saleOrderResourceId:{type:"string",description:"Optional: link this invoice to a source Sale Order (records the order\u2192invoice relationship)."},saleQuoteResourceId:{type:"string",description:"Optional: link this invoice to a source Sale Quote."},returnFullEntity:sy},required:["reference","valueDate","dueDate","contactResourceId","lineItems"],group:"invoices",readOnly:!1,searchHint:"create new sales invoice draft with line items deferred revenue subscription",execute:async(t,e)=>{let r=eu(e);if(r)return r;let{notes:n,tag:i,capsuleRecipe:s,returnFullEntity:o,...a}=e;s!==void 0&&Xo(s);let c={...a,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]},...s!==void 0&&{capsuleRecipe:s}},u=await lA(t.client,c);return kl(u,o===!0,f=>ba(t.client,f))}},{name:"update_invoice",description:'Update an existing draft invoice (change reference, dates, line items, notes, custom fields). Use when the user says "update", "change", "fix", or "correct" a draft invoice. Line items CAN be fully replaced \u2014 pass the complete updated lineItems array. Optional capsuleRecipe retro-attaches a recipe on activation; same base-type constraint as create variant. Mutex with capsuleResourceId. Rule 143.',params:{resourceId:{type:"string",description:"Invoice resourceId"},reference:as,valueDate:os,dueDate:Tu,lineItems:ta,notes:ri,customFields:Vi,capsuleRecipe:Ol},required:["resourceId"],group:"invoices",readOnly:!1,searchHint:"update draft invoice reference dates line items capsule recipe",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,capsuleRecipe:s,...o}=e;s!==void 0&&Xo(s);let a={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]},...s!==void 0&&{capsuleRecipe:s}};return zO(t.client,r,a)}},{name:"delete_invoice",description:"Delete a draft invoice. Cannot delete finalized invoices.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!1,searchHint:"permanently delete a draft invoice",isDestructive:!0,execute:async(t,e)=>HO(t.client,e.resourceId)},{name:"pay_invoice",description:"Record a payment against an invoice. Invoice must be APPROVED/UNPAID before payment \u2014 draft or voided invoices cannot be paid. If the invoice is still a DRAFT, call finalize_invoice first.",params:{resourceId:{type:"string",description:"Invoice resourceId"},paymentAmount:{type:"number",description:"Amount to pay (in bank currency)"},transactionAmount:{type:"number",description:"Amount in invoice currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId for payment"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:wx,customFields:Vi},required:["resourceId","paymentAmount","accountResourceId","valueDate"],group:"invoices",readOnly:!1,searchHint:"record payment against an approved invoice",isDestructive:!0,execute:async(t,e)=>{let r=e.resourceId,n=Number(e.paymentAmount);if(!Number.isFinite(n)||n<=0)throw new Error("paymentAmount must be a positive number");let i=Number(e.transactionAmount??n);if(!Number.isFinite(i)||i<=0)throw new Error("transactionAmount must be a positive number");return await Cet(ba,t.client,r,"invoice"),tD(t.client,r,{paymentAmount:n,transactionAmount:i,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference||`PMT-${Date.now()}`,paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,customFields:e.customFields})}},{name:"finalize_invoice",description:"Finalize a draft invoice (set saveAsDraft=false). Can optionally update fields in the same call. IMPORTANT: Every lineItem MUST have accountResourceId. If the draft was created without it, pass lineItems with accountResourceId added (search accounts first, e.g. Operating Revenue for sales).",params:{resourceId:{type:"string",description:"Invoice resourceId"},reference:as,valueDate:os,dueDate:Tu,lineItems:ta,notes:ri},required:["resourceId"],group:"invoices",readOnly:!1,searchHint:"approve finalize draft invoice for sending",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,s={...i,...n!==void 0&&{invoiceNotes:n}},o=await _x(t.client,"invoice",r,s),a=eu(o,{assumeFinalize:!0});if(a)return a;if(o.reference){let c=o.reference;((await tb(t.client,{filter:{reference:{eq:c}},limit:1,offset:0,sort:{sortBy:["valueDate"],order:"DESC"}})).data??[]).filter(d=>d.resourceId!==r).length>0&&(o.reference=`${c}-${Date.now()%1e4}`)}return nD(t.client,r,o)}},{name:"apply_credits_to_invoice",description:`Apply customer credit note(s) to an invoice. You MUST call this tool to actually apply credits \u2014 do not just describe the steps.
687
- Steps: 1) search_customer_credit_notes with status UNAPPLIED for the same contact. 2) If CN is still DRAFT, call finalize_customer_credit_note first. 3) Call this tool with creditNoteResourceId and amountApplied for each CN.`,params:{resourceId:{type:"string",description:"Invoice resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Customer credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"invoices",readOnly:!1,searchHint:"apply customer credit note to invoice balance",isDestructive:!0,execute:async(t,e)=>GO(t.client,e.resourceId,e.credits)},{name:"download_invoice_pdf",description:"Download an invoice as PDF. Returns { fileUrl }.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!0,searchHint:"download invoice as PDF document file",isConcurrencySafe:!0,execute:async(t,e)=>VO(t.client,e.resourceId)},cn("list_bills","List bills (purchase invoices). Returns reference, date, status, contact, amounts. Paginated \u2014 response includes totalElements. Use limit/offset to page.","bills",(t,e,r)=>TF(t,{limit:r,offset:e}),"list purchase bills with pagination and status"),en({name:"search_bills",description:'Search bills. Supports comma-separated status (e.g., "UNPAID,PARTIALLY_PAID"). Use filter param for advanced queries.',group:"bills",fields:m_,defaults:A_,fetcher:Um,searchHint:"find purchase bills by status date supplier amount"}),{name:"get_bill",description:"Get full bill details.",params:{resourceId:Pa},required:["resourceId"],group:"bills",readOnly:!0,searchHint:"get bill details line items payments totals",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>ga(t.client,e.resourceId)},{name:"create_bill",description:`Create a new bill. Same rules as create_invoice: name not description, saveAsDraft defaults true, accountResourceId REQUIRED on lineItems for finalized bills (search accounts first, e.g. Operating Expense). When selecting a tax profile, use search_tax_profiles with appliesTo "purchase" \u2014 sales-only profiles cause 422. reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify. Optional capsuleRecipe (PURCHASE base only \u2014 PREPAID_AMORTIZATION). Other recipes silently null here; pre-flight with preview_capsule_recipe. Mutex with capsuleResourceId. Rule 143.`,params:{reference:as,valueDate:os,dueDate:Tu,contactResourceId:Eue,lineItems:ta,currency:oy,saveAsDraft:bz,notes:ri,tag:Fl,customFields:Vi,capsuleRecipe:Ol,purchaseOrderResourceId:{type:"string",description:"Optional: link this bill to a source Purchase Order (records the order\u2192bill relationship)."},purchaseRequestResourceId:{type:"string",description:"Optional: link this bill to a source Purchase Request."},returnFullEntity:sy},required:["reference","valueDate","dueDate","contactResourceId","lineItems"],group:"bills",readOnly:!1,searchHint:"create new purchase bill draft with line items prepaid amortize accrual",execute:async(t,e)=>{let r=eu(e);if(r)return r;let{notes:n,tag:i,capsuleRecipe:s,returnFullEntity:o,...a}=e;s!==void 0&&Xo(s);let c={...a,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]},...s!==void 0&&{capsuleRecipe:s}},u=await qm(t.client,c);return kl(u,o===!0,f=>ga(t.client,f))}},{name:"update_bill",description:'Update an existing draft bill (change reference, dates, line items, notes, custom fields). Use when the user says "update", "change", "fix", or "correct" a draft bill. Line items CAN be fully replaced \u2014 pass the complete updated lineItems array. Optional capsuleRecipe retro-attaches a recipe on activation; same base-type constraint as create variant. Mutex with capsuleResourceId. Rule 143.',params:{resourceId:{type:"string",description:"Bill resourceId"},reference:as,valueDate:os,dueDate:Tu,lineItems:ta,notes:ri,customFields:Vi,capsuleRecipe:Ol},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"update draft bill reference dates line items capsule recipe",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,capsuleRecipe:s,...o}=e;s!==void 0&&Xo(s);let a={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]},...s!==void 0&&{capsuleRecipe:s}};return kF(t.client,r,a)}},{name:"delete_bill",description:"Delete a draft bill.",params:{resourceId:Pa},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"permanently delete a draft bill",isDestructive:!0,execute:async(t,e)=>NF(t.client,e.resourceId)},{name:"download_bill_pdf",description:"Download a bill as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"bills",readOnly:!0,searchHint:"download bill as PDF document file",isConcurrencySafe:!0,execute:async(t,e)=>FF(t.client,e.resourceId)},{name:"pay_bill",description:"Record a payment against a bill. Bill must be APPROVED before payment \u2014 draft or voided bills cannot be paid.",params:{resourceId:Pa,paymentAmount:Dgr,transactionAmount:{type:"number",description:"Amount in bill currency (defaults to paymentAmount for same-currency)"},accountResourceId:cy,valueDate:os,reference:as,paymentMethod:wx,customFields:Vi},required:["resourceId","paymentAmount","accountResourceId","valueDate"],group:"bills",readOnly:!1,searchHint:"record payment against an approved bill",isDestructive:!0,execute:async(t,e)=>{let r=e.resourceId,n=Number(e.paymentAmount);if(!Number.isFinite(n)||n<=0)throw new Error("paymentAmount must be a positive number");let i=Number(e.transactionAmount??n);if(!Number.isFinite(i)||i<=0)throw new Error("transactionAmount must be a positive number");return await Cet(ga,t.client,r,"bill"),ew(t.client,r,{paymentAmount:n,transactionAmount:i,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference||`PMT-${Date.now()}`,paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,customFields:e.customFields})}},{name:"finalize_bill",description:"Finalize a draft bill (set saveAsDraft=false). Can optionally update fields in the same call. IMPORTANT: Every lineItem MUST have accountResourceId. If the draft was created without it, pass lineItems with accountResourceId added (search accounts first, e.g. Operating Expense for purchases).",params:{resourceId:{type:"string",description:"Bill resourceId"},reference:as,valueDate:os,dueDate:Tu,lineItems:ta,notes:ri},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"approve finalize draft bill for processing",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,s={...i,...n!==void 0&&{invoiceNotes:n}},o=await _x(t.client,"bill",r,s),a=eu(o,{assumeFinalize:!0});return a||XI(t.client,r,o)}},{name:"apply_credits_to_bill",description:"Apply supplier credit note(s) to a bill. IMPORTANT: The credit note must be FINALIZED first (status UNAPPLIED, not DRAFT). If it is still a draft, call finalize_supplier_credit_note first. Then search_supplier_credit_notes with status UNAPPLIED to find available credits for the contact, and pass creditNoteResourceId and amountApplied for each.",params:{resourceId:{type:"string",description:"Bill resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Supplier credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"bills",readOnly:!1,searchHint:"apply supplier credit note to bill balance",isDestructive:!0,execute:async(t,e)=>OF(t.client,e.resourceId,e.credits)},{name:"create_sale_order",description:`Create a Sale Quote or Sale Order (pick via documentType). lineItem text field = \`name\`. Dates YYYY-MM-DD. \`reference\` auto-generates (timestamped) if omitted \u2014 must be unique per org.
687
+ Steps: 1) search_customer_credit_notes with status UNAPPLIED for the same contact. 2) If CN is still DRAFT, call finalize_customer_credit_note first. 3) Call this tool with creditNoteResourceId and amountApplied for each CN.`,params:{resourceId:{type:"string",description:"Invoice resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Customer credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"invoices",readOnly:!1,searchHint:"apply customer credit note to invoice balance",isDestructive:!0,execute:async(t,e)=>GO(t.client,e.resourceId,e.credits)},{name:"download_invoice_pdf",description:"Download an invoice as PDF. Returns { fileUrl }.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!0,searchHint:"download invoice as PDF document file",isConcurrencySafe:!0,execute:async(t,e)=>VO(t.client,e.resourceId)},cn("list_bills","List bills (purchase invoices). Returns reference, date, status, contact, amounts. Paginated \u2014 response includes totalElements. Use limit/offset to page.","bills",(t,e,r,n)=>TF(t,{limit:r,offset:e,view:n}),"list purchase bills with pagination and status",{leanView:!0}),en({name:"search_bills",description:'Search bills. Supports comma-separated status (e.g., "UNPAID,PARTIALLY_PAID"). Use filter param for advanced queries.',group:"bills",fields:m_,defaults:A_,fetcher:Um,searchHint:"find purchase bills by status date supplier amount"}),{name:"get_bill",description:"Get full bill details.",params:{resourceId:Pa},required:["resourceId"],group:"bills",readOnly:!0,searchHint:"get bill details line items payments totals",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>ga(t.client,e.resourceId)},{name:"create_bill",description:`Create a new bill. Same rules as create_invoice: name not description, saveAsDraft defaults true, accountResourceId REQUIRED on lineItems for finalized bills (search accounts first, e.g. Operating Expense). When selecting a tax profile, use search_tax_profiles with appliesTo "purchase" \u2014 sales-only profiles cause 422. reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify. Optional capsuleRecipe (PURCHASE base only \u2014 PREPAID_AMORTIZATION). Other recipes silently null here; pre-flight with preview_capsule_recipe. Mutex with capsuleResourceId. Rule 143.`,params:{reference:as,valueDate:os,dueDate:Tu,contactResourceId:Eue,lineItems:ta,currency:oy,saveAsDraft:bz,notes:ri,tag:Fl,customFields:Vi,capsuleRecipe:Ol,purchaseOrderResourceId:{type:"string",description:"Optional: link this bill to a source Purchase Order (records the order\u2192bill relationship)."},purchaseRequestResourceId:{type:"string",description:"Optional: link this bill to a source Purchase Request."},returnFullEntity:sy},required:["reference","valueDate","dueDate","contactResourceId","lineItems"],group:"bills",readOnly:!1,searchHint:"create new purchase bill draft with line items prepaid amortize accrual",execute:async(t,e)=>{let r=eu(e);if(r)return r;let{notes:n,tag:i,capsuleRecipe:s,returnFullEntity:o,...a}=e;s!==void 0&&Xo(s);let c={...a,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]},...s!==void 0&&{capsuleRecipe:s}},u=await qm(t.client,c);return kl(u,o===!0,f=>ga(t.client,f))}},{name:"update_bill",description:'Update an existing draft bill (change reference, dates, line items, notes, custom fields). Use when the user says "update", "change", "fix", or "correct" a draft bill. Line items CAN be fully replaced \u2014 pass the complete updated lineItems array. Optional capsuleRecipe retro-attaches a recipe on activation; same base-type constraint as create variant. Mutex with capsuleResourceId. Rule 143.',params:{resourceId:{type:"string",description:"Bill resourceId"},reference:as,valueDate:os,dueDate:Tu,lineItems:ta,notes:ri,customFields:Vi,capsuleRecipe:Ol},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"update draft bill reference dates line items capsule recipe",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,capsuleRecipe:s,...o}=e;s!==void 0&&Xo(s);let a={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]},...s!==void 0&&{capsuleRecipe:s}};return kF(t.client,r,a)}},{name:"delete_bill",description:"Delete a draft bill.",params:{resourceId:Pa},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"permanently delete a draft bill",isDestructive:!0,execute:async(t,e)=>NF(t.client,e.resourceId)},{name:"download_bill_pdf",description:"Download a bill as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"bills",readOnly:!0,searchHint:"download bill as PDF document file",isConcurrencySafe:!0,execute:async(t,e)=>FF(t.client,e.resourceId)},{name:"pay_bill",description:"Record a payment against a bill. Bill must be APPROVED before payment \u2014 draft or voided bills cannot be paid.",params:{resourceId:Pa,paymentAmount:Dgr,transactionAmount:{type:"number",description:"Amount in bill currency (defaults to paymentAmount for same-currency)"},accountResourceId:cy,valueDate:os,reference:as,paymentMethod:wx,customFields:Vi},required:["resourceId","paymentAmount","accountResourceId","valueDate"],group:"bills",readOnly:!1,searchHint:"record payment against an approved bill",isDestructive:!0,execute:async(t,e)=>{let r=e.resourceId,n=Number(e.paymentAmount);if(!Number.isFinite(n)||n<=0)throw new Error("paymentAmount must be a positive number");let i=Number(e.transactionAmount??n);if(!Number.isFinite(i)||i<=0)throw new Error("transactionAmount must be a positive number");return await Cet(ga,t.client,r,"bill"),ew(t.client,r,{paymentAmount:n,transactionAmount:i,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference||`PMT-${Date.now()}`,paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,customFields:e.customFields})}},{name:"finalize_bill",description:"Finalize a draft bill (set saveAsDraft=false). Can optionally update fields in the same call. IMPORTANT: Every lineItem MUST have accountResourceId. If the draft was created without it, pass lineItems with accountResourceId added (search accounts first, e.g. Operating Expense for purchases).",params:{resourceId:{type:"string",description:"Bill resourceId"},reference:as,valueDate:os,dueDate:Tu,lineItems:ta,notes:ri},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"approve finalize draft bill for processing",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,s={...i,...n!==void 0&&{invoiceNotes:n}},o=await _x(t.client,"bill",r,s),a=eu(o,{assumeFinalize:!0});return a||XI(t.client,r,o)}},{name:"apply_credits_to_bill",description:"Apply supplier credit note(s) to a bill. IMPORTANT: The credit note must be FINALIZED first (status UNAPPLIED, not DRAFT). If it is still a draft, call finalize_supplier_credit_note first. Then search_supplier_credit_notes with status UNAPPLIED to find available credits for the contact, and pass creditNoteResourceId and amountApplied for each.",params:{resourceId:{type:"string",description:"Bill resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Supplier credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"bills",readOnly:!1,searchHint:"apply supplier credit note to bill balance",isDestructive:!0,execute:async(t,e)=>OF(t.client,e.resourceId,e.credits)},{name:"create_sale_order",description:`Create a Sale Quote or Sale Order (pick via documentType). lineItem text field = \`name\`. Dates YYYY-MM-DD. \`reference\` auto-generates (timestamped) if omitted \u2014 must be unique per org.
688
688
 
689
689
  SALE_QUOTE: a draft estimate by default (saveAsDraft true \u2192 DRAFT). Lifecycle DRAFT \u2192 (issue: saveAsDraft:false) \u2192 CREATED \u2192 (transition_sale_order ACCEPT) \u2192 ACCEPTED. To order from a quote, create it with saveAsDraft:false \u2014 a DRAFT quote can be neither linked nor accepted.
690
690
  SALE_ORDER: created directly as CREATED (no draft state). Link to a quote via saleQuoteResourceId \u2014 the quote MUST be CREATED or ACCEPTED (not DRAFT/VOID). Lifecycle CREATED \u2192 CONFIRMED (transition_sale_order CONFIRM).
@@ -702,7 +702,7 @@ accountResourceId is required on each lineItem when not a draft. There is no ord
702
702
  - ACCEPT \u2014 Purchase Request only (ACTIVE \u2192 ACCEPTED). The request must already be issued (saveAsDraft:false); a DRAFT can't be accepted. An ACTIVE request is already linkable, so accept is optional.
703
703
  - CONFIRM \u2014 Purchase Order only (ACTIVE \u2192 CONFIRMED).
704
704
  - VOID \u2014 either, when not a draft (cancels the document).
705
- - DELETE \u2014 DRAFT only; for anything non-draft use VOID.`,params:{documentType:Sx,resourceId:Pa,action:vet,internalNotes:{type:"string",description:"(VOID only) optional reason note recorded on the document."}},required:["documentType","resourceId","action"],group:"purchase_orders",readOnly:!1,isDestructive:!0,searchHint:"accept confirm void delete purchase request or purchase order lifecycle",execute:async(t,e)=>{let r=e.documentType,n=e.resourceId,i=e.action,s=wet(r,i,"transition_purchase_order");if(s)return s;switch(i){case"ACCEPT":return hQ(t.client,n);case"CONFIRM":return mQ(t.client,n);case"VOID":return pQ(t.client,r,n,e.internalNotes);case"DELETE":{let o=await Bet(t.client,mf,r,n,"transition_purchase_order");return o||(await dQ(t.client,r,n),{deleted:!0,resourceId:n})}default:return{error:`Unsupported action "${i}".`,status:422,hint:"Use ACCEPT, CONFIRM, VOID, or DELETE.",repair:{tool:"transition_purchase_order",arguments:{},reason:"invalid action"}}}}},{name:"convert_sale_order_to_invoice",description:"Convert a Sale Quote or Sale Order (pick via documentType) into an Invoice. Creates a NEW invoice \u2014 NON-IDEMPOTENT: each call makes another invoice. On a timeout or uncertain result, do NOT blind-retry \u2014 search invoices for one already linked to this order (saleOrderResourceId / saleQuoteResourceId) first. `reference` is required by the API; if omitted a unique placeholder is generated \u2014 pass your own to follow your org's numbering. `saveAsDraft` defaults false (the new invoice is ACTIVE). The source must not be VOID.",params:{documentType:Dx,resourceId:Pa,valueDate:os,dueDate:Tu,reference:as,terms:Cz,notes:ri,internalNotes:{type:"string",description:"Internal note recorded on the new invoice (not shown on the document)."},tag:Fl,saveAsDraft:{type:"boolean",description:"Save the new invoice as a draft (default false \u2014 it is created ACTIVE). Pass true to review before it posts."}},required:["documentType","resourceId","valueDate","dueDate"],group:"sale_orders",readOnly:!1,searchHint:"convert sale quote or sale order into invoice raise invoice from order",execute:async(t,e)=>{let r=vz(e.documentType,["SALE_QUOTE","SALE_ORDER"],"convert_sale_order_to_invoice");if(r)return r;let n=e.documentType,i=e.resourceId,s=await Det(t.client,(a,c)=>hf(a,n,c),i,n==="SALE_ORDER"?"sale order":"sale quote","invoice","convert_sale_order_to_invoice");if(s)return s;let o={reference:e.reference||Tl("INV"),valueDate:e.valueDate,dueDate:e.dueDate,...e.terms!==void 0&&{terms:e.terms},...e.notes!==void 0&&{invoiceNotes:e.notes},...e.internalNotes!==void 0&&{internalNotes:e.internalNotes},...e.tag!==void 0&&{tags:[e.tag]},...e.saveAsDraft!==void 0&&{saveAsDraft:e.saveAsDraft}};return rQ(t.client,n,i,o)}},{name:"convert_purchase_order_to_bill",description:"Convert a Purchase Request or Purchase Order (pick via documentType) into a Bill. Creates a NEW bill \u2014 NON-IDEMPOTENT: each call makes another bill. On a timeout or uncertain result, do NOT blind-retry \u2014 search bills for one already linked to this order (purchaseOrderResourceId / purchaseRequestResourceId) first. `reference` is required by the API; if omitted a unique placeholder is generated \u2014 pass your own to follow your org's numbering. `saveAsDraft` defaults false (the new bill is ACTIVE). The source must not be VOID.",params:{documentType:Sx,resourceId:Pa,valueDate:os,dueDate:Tu,reference:as,terms:Cz,internalNotes:{type:"string",description:"Internal note recorded on the new bill (not shown on the document)."},tag:Fl,saveAsDraft:{type:"boolean",description:"Save the new bill as a draft (default false \u2014 it is created ACTIVE). Pass true to review before it posts."}},required:["documentType","resourceId","valueDate","dueDate"],group:"purchase_orders",readOnly:!1,searchHint:"convert purchase request or purchase order into bill raise bill from order",execute:async(t,e)=>{let r=vz(e.documentType,["PURCHASE_REQUEST","PURCHASE_ORDER"],"convert_purchase_order_to_bill");if(r)return r;let n=e.documentType,i=e.resourceId,s=await Det(t.client,(a,c)=>mf(a,n,c),i,n==="PURCHASE_ORDER"?"purchase order":"purchase request","bill","convert_purchase_order_to_bill");if(s)return s;let o={reference:e.reference||Tl("BILL"),valueDate:e.valueDate,dueDate:e.dueDate,...e.terms!==void 0&&{terms:e.terms},...e.internalNotes!==void 0&&{internalNotes:e.internalNotes},...e.tag!==void 0&&{tags:[e.tag]},...e.saveAsDraft!==void 0&&{saveAsDraft:e.saveAsDraft}};return lQ(t.client,n,i,o)}},(()=>{let t=en({name:"search_sale_order_line_items",description:"Search the LINE ITEMS across Sale Quotes or Sale Orders (line-item level, not document level). Filter by line text, parent order, contact, account, amount, open state, date. Use the filter param for advanced/nested queries.",group:"sale_orders",fields:zd,defaults:Hd,fetcher:(e,r,n)=>tQ(e,r,n),pathParam:"documentType",pathParamDescription:"Which document line items to search: SALE_QUOTE or SALE_ORDER",searchHint:"find sale quote or sale order line items by text account amount open state"});return t.params.documentType.enum=["SALE_QUOTE","SALE_ORDER"],t})(),(()=>{let t=en({name:"search_purchase_order_line_items",description:"Search the LINE ITEMS across Purchase Requests or Purchase Orders (line-item level, not document level). Filter by line text, parent order, contact, account, amount, open state, date. Use the filter param for advanced/nested queries.",group:"purchase_orders",fields:zd,defaults:Hd,fetcher:(e,r,n)=>uQ(e,r,n),pathParam:"documentType",pathParamDescription:"Which document line items to search: PURCHASE_REQUEST or PURCHASE_ORDER",searchHint:"find purchase request or purchase order line items by text account amount open state"});return t.params.documentType.enum=["PURCHASE_REQUEST","PURCHASE_ORDER"],t})(),cn("list_journals","List journal entries. Paginated \u2014 response includes totalElements. Use limit/offset to page.","journals",(t,e,r)=>AQ(t,{limit:r,offset:e}),"list journal entries with pagination and status"),Ma("get_journal","Get full journal entry details by resourceId. Returns journal lines, amounts, status, and metadata.","journals",(t,e)=>iu(t,e),"get journal entry details debit credit lines"),en({name:"search_journals",description:"Search journals. Status uses ACTIVE (not FINALIZED). Supports comma-separated status/type.",group:"journals",fields:C_,defaults:v_,fetcher:cD,searchHint:"find journals JE by status type date reference tag contact internal-notes"}),{name:"create_journal",description:`Create a journal entry. IMPORTANT:
705
+ - DELETE \u2014 DRAFT only; for anything non-draft use VOID.`,params:{documentType:Sx,resourceId:Pa,action:vet,internalNotes:{type:"string",description:"(VOID only) optional reason note recorded on the document."}},required:["documentType","resourceId","action"],group:"purchase_orders",readOnly:!1,isDestructive:!0,searchHint:"accept confirm void delete purchase request or purchase order lifecycle",execute:async(t,e)=>{let r=e.documentType,n=e.resourceId,i=e.action,s=wet(r,i,"transition_purchase_order");if(s)return s;switch(i){case"ACCEPT":return hQ(t.client,n);case"CONFIRM":return mQ(t.client,n);case"VOID":return pQ(t.client,r,n,e.internalNotes);case"DELETE":{let o=await Bet(t.client,mf,r,n,"transition_purchase_order");return o||(await dQ(t.client,r,n),{deleted:!0,resourceId:n})}default:return{error:`Unsupported action "${i}".`,status:422,hint:"Use ACCEPT, CONFIRM, VOID, or DELETE.",repair:{tool:"transition_purchase_order",arguments:{},reason:"invalid action"}}}}},{name:"convert_sale_order_to_invoice",description:"Convert a Sale Quote or Sale Order (pick via documentType) into an Invoice. Creates a NEW invoice \u2014 NON-IDEMPOTENT: each call makes another invoice. On a timeout or uncertain result, do NOT blind-retry \u2014 search invoices for one already linked to this order (saleOrderResourceId / saleQuoteResourceId) first. `reference` is required by the API; if omitted a unique placeholder is generated \u2014 pass your own to follow your org's numbering. `saveAsDraft` defaults false (the new invoice is ACTIVE). The source must not be VOID.",params:{documentType:Dx,resourceId:Pa,valueDate:os,dueDate:Tu,reference:as,terms:Cz,notes:ri,internalNotes:{type:"string",description:"Internal note recorded on the new invoice (not shown on the document)."},tag:Fl,saveAsDraft:{type:"boolean",description:"Save the new invoice as a draft (default false \u2014 it is created ACTIVE). Pass true to review before it posts."}},required:["documentType","resourceId","valueDate","dueDate"],group:"sale_orders",readOnly:!1,searchHint:"convert sale quote or sale order into invoice raise invoice from order",execute:async(t,e)=>{let r=vz(e.documentType,["SALE_QUOTE","SALE_ORDER"],"convert_sale_order_to_invoice");if(r)return r;let n=e.documentType,i=e.resourceId,s=await Det(t.client,(a,c)=>hf(a,n,c),i,n==="SALE_ORDER"?"sale order":"sale quote","invoice","convert_sale_order_to_invoice");if(s)return s;let o={reference:e.reference||Tl("INV"),valueDate:e.valueDate,dueDate:e.dueDate,...e.terms!==void 0&&{terms:e.terms},...e.notes!==void 0&&{invoiceNotes:e.notes},...e.internalNotes!==void 0&&{internalNotes:e.internalNotes},...e.tag!==void 0&&{tags:[e.tag]},...e.saveAsDraft!==void 0&&{saveAsDraft:e.saveAsDraft}};return rQ(t.client,n,i,o)}},{name:"convert_purchase_order_to_bill",description:"Convert a Purchase Request or Purchase Order (pick via documentType) into a Bill. Creates a NEW bill \u2014 NON-IDEMPOTENT: each call makes another bill. On a timeout or uncertain result, do NOT blind-retry \u2014 search bills for one already linked to this order (purchaseOrderResourceId / purchaseRequestResourceId) first. `reference` is required by the API; if omitted a unique placeholder is generated \u2014 pass your own to follow your org's numbering. `saveAsDraft` defaults false (the new bill is ACTIVE). The source must not be VOID.",params:{documentType:Sx,resourceId:Pa,valueDate:os,dueDate:Tu,reference:as,terms:Cz,internalNotes:{type:"string",description:"Internal note recorded on the new bill (not shown on the document)."},tag:Fl,saveAsDraft:{type:"boolean",description:"Save the new bill as a draft (default false \u2014 it is created ACTIVE). Pass true to review before it posts."}},required:["documentType","resourceId","valueDate","dueDate"],group:"purchase_orders",readOnly:!1,searchHint:"convert purchase request or purchase order into bill raise bill from order",execute:async(t,e)=>{let r=vz(e.documentType,["PURCHASE_REQUEST","PURCHASE_ORDER"],"convert_purchase_order_to_bill");if(r)return r;let n=e.documentType,i=e.resourceId,s=await Det(t.client,(a,c)=>mf(a,n,c),i,n==="PURCHASE_ORDER"?"purchase order":"purchase request","bill","convert_purchase_order_to_bill");if(s)return s;let o={reference:e.reference||Tl("BILL"),valueDate:e.valueDate,dueDate:e.dueDate,...e.terms!==void 0&&{terms:e.terms},...e.internalNotes!==void 0&&{internalNotes:e.internalNotes},...e.tag!==void 0&&{tags:[e.tag]},...e.saveAsDraft!==void 0&&{saveAsDraft:e.saveAsDraft}};return lQ(t.client,n,i,o)}},(()=>{let t=en({name:"search_sale_order_line_items",description:"Search the LINE ITEMS across Sale Quotes or Sale Orders (line-item level, not document level). Filter by line text, parent order, contact, account, amount, open state, date. Use the filter param for advanced/nested queries.",group:"sale_orders",fields:zd,defaults:Hd,fetcher:(e,r,n)=>tQ(e,r,n),pathParam:"documentType",pathParamDescription:"Which document line items to search: SALE_QUOTE or SALE_ORDER",searchHint:"find sale quote or sale order line items by text account amount open state"});return t.params.documentType.enum=["SALE_QUOTE","SALE_ORDER"],t})(),(()=>{let t=en({name:"search_purchase_order_line_items",description:"Search the LINE ITEMS across Purchase Requests or Purchase Orders (line-item level, not document level). Filter by line text, parent order, contact, account, amount, open state, date. Use the filter param for advanced/nested queries.",group:"purchase_orders",fields:zd,defaults:Hd,fetcher:(e,r,n)=>uQ(e,r,n),pathParam:"documentType",pathParamDescription:"Which document line items to search: PURCHASE_REQUEST or PURCHASE_ORDER",searchHint:"find purchase request or purchase order line items by text account amount open state"});return t.params.documentType.enum=["PURCHASE_REQUEST","PURCHASE_ORDER"],t})(),cn("list_journals","List journal entries. Paginated \u2014 response includes totalElements. Use limit/offset to page.","journals",(t,e,r,n)=>AQ(t,{limit:r,offset:e,view:n}),"list journal entries with pagination and status",{leanView:!0}),Ma("get_journal","Get full journal entry details by resourceId. Returns journal lines, amounts, status, and metadata.","journals",(t,e)=>iu(t,e),"get journal entry details debit credit lines"),en({name:"search_journals",description:"Search journals. Status uses ACTIVE (not FINALIZED). Supports comma-separated status/type.",group:"journals",fields:C_,defaults:v_,fetcher:cD,searchHint:"find journals JE by status type date reference tag contact internal-notes"}),{name:"create_journal",description:`Create a journal entry. IMPORTANT:
706
706
  - Each entry needs accountResourceId, type (DEBIT or CREDIT), and amount.
707
707
  - Total debits MUST equal total credits \u2014 the API rejects unbalanced journals.
708
708
  - Search accounts first to get the correct resourceIds.
@@ -714,13 +714,13 @@ Optional capsuleRecipe (JOURNAL_MANUAL base \u2014 ACCRUAL_REVERSAL, IFRS16_LEAS
714
714
  - Minimum 1 entry (unlike regular journals which require 2).
715
715
  - Each entry needs accountResourceId, type (DEBIT or CREDIT), and amount (must be > 0).
716
716
  - Skips lock date validation (opening balances are special).
717
- - Uses journalEntries (NOT lines \u2014 this is a journal type).`,params:{valueDate:{type:"string",description:"Opening balance date (YYYY-MM-DD)"},journalEntries:ay,currency:oy},required:["valueDate","journalEntries"],group:"journals",readOnly:!1,searchHint:"create transfer trial balance between periods",execute:async(t,e)=>Vj(t.client,e)},{name:"delete_journal",description:"Delete a draft journal entry.",params:{resourceId:Pa},required:["resourceId"],group:"journals",readOnly:!1,searchHint:"permanently delete a draft journal entry",isDestructive:!0,execute:async(t,e)=>gQ(t.client,e.resourceId)},{name:"generate_trial_balance",description:"Generate a trial balance report.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency override"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate trial balance report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>EQ(t.client,e)},{name:"generate_balance_sheet",description:"Generate a balance sheet report.",params:{snapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD). Defaults to today if omitted."},currencyCode:met},required:[],group:"financial_reports",readOnly:!0,searchHint:"generate balance sheet report as at date",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>{let r=e.snapshotDate??new Date().toISOString().slice(0,10);return bQ(t.client,{primarySnapshotDate:r,currencyCode:e.currencyCode})}},{name:"generate_profit_and_loss",description:"Generate a profit & loss (income statement) report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},currencyCode:met},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate profit and loss income statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>CQ(t.client,e)},{name:"generate_cashflow",description:"Generate a cashflow report.",params:{startDate:Sgr,endDate:bue},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cashflow statement report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>vQ(t.client,e)},{name:"generate_aged_ar",description:"Generate aged accounts receivable summary.",params:{endDate:bue},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts receivable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>IQ(t.client,e)},{name:"generate_aged_ap",description:"Generate aged accounts payable summary.",params:{endDate:bue},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts payable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>wQ(t.client,e)},{name:"generate_cash_balance",description:"Generate a cash balance report showing cash position at a specific date. PREFERRED for cash position questions \u2014 use this (NOT balance sheet) when asked about total cash, cash on hand, available cash, or cash position across all bank accounts.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cash balance report across accounts",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>_Q(t.client,e)},{name:"generate_general_ledger",description:"Generate a general ledger report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},groupBy:{type:"string",description:"Group by: ACCOUNT (default), TRANSACTION, or CAPSULE"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate general ledger report for account period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>{let r=e;return DQ(t.client,{...r,groupBy:r.groupBy??"ACCOUNT"})}},{name:"list_bank_accounts",description:"List bank accounts connected to the organization.",params:{},required:[],group:"bank",readOnly:!0,searchHint:"list bank and cash accounts with balances",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>aE(t.client)},cn("list_items","List items (products & services). Returns internalName, itemCode, appliesToSale/Purchase. Paginated \u2014 response includes totalElements. Use limit/offset to page.","items",(t,e,r)=>eO(t,{limit:r,offset:e}),"list products services items with pagination"),en({name:"search_items",description:"Search items. Use list_items to search by name (internalName is not a filter field).",group:"items",fields:R_,defaults:x_,fetcher:TE,searchHint:"find items products services by status category sale purchase type internalName via list_items"}),{name:"get_item",description:"Get full item details by resourceId.",params:{resourceId:{type:"string",description:"Item resourceId (UUID)"}},required:["resourceId"],group:"items",readOnly:!0,searchHint:"get item product service details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>xE(t.client,e.resourceId)},{name:"create_item",description:`Create a new item. Auto-checks for duplicates by itemCode \u2014 returns existing item if found.
717
+ - Uses journalEntries (NOT lines \u2014 this is a journal type).`,params:{valueDate:{type:"string",description:"Opening balance date (YYYY-MM-DD)"},journalEntries:ay,currency:oy},required:["valueDate","journalEntries"],group:"journals",readOnly:!1,searchHint:"create transfer trial balance between periods",execute:async(t,e)=>Vj(t.client,e)},{name:"delete_journal",description:"Delete a draft journal entry.",params:{resourceId:Pa},required:["resourceId"],group:"journals",readOnly:!1,searchHint:"permanently delete a draft journal entry",isDestructive:!0,execute:async(t,e)=>gQ(t.client,e.resourceId)},{name:"generate_trial_balance",description:"Generate a trial balance report.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency override"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate trial balance report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>EQ(t.client,e)},{name:"generate_balance_sheet",description:"Generate a balance sheet report.",params:{snapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD). Defaults to today if omitted."},currencyCode:met},required:[],group:"financial_reports",readOnly:!0,searchHint:"generate balance sheet report as at date",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>{let r=e.snapshotDate??new Date().toISOString().slice(0,10);return bQ(t.client,{primarySnapshotDate:r,currencyCode:e.currencyCode})}},{name:"generate_profit_and_loss",description:"Generate a profit & loss (income statement) report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},currencyCode:met},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate profit and loss income statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>CQ(t.client,e)},{name:"generate_cashflow",description:"Generate a cashflow report.",params:{startDate:Sgr,endDate:bue},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cashflow statement report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>vQ(t.client,e)},{name:"generate_aged_ar",description:"Generate aged accounts receivable summary.",params:{endDate:bue},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts receivable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>IQ(t.client,e)},{name:"generate_aged_ap",description:"Generate aged accounts payable summary.",params:{endDate:bue},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts payable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>wQ(t.client,e)},{name:"generate_cash_balance",description:"Generate a cash balance report showing cash position at a specific date. PREFERRED for cash position questions \u2014 use this (NOT balance sheet) when asked about total cash, cash on hand, available cash, or cash position across all bank accounts.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cash balance report across accounts",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>_Q(t.client,e)},{name:"generate_general_ledger",description:"Generate a general ledger report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},groupBy:{type:"string",description:"Group by: ACCOUNT (default), TRANSACTION, or CAPSULE"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate general ledger report for account period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(t,e)=>{let r=e;return DQ(t.client,{...r,groupBy:r.groupBy??"ACCOUNT"})}},{name:"list_bank_accounts",description:"List bank accounts connected to the organization.",params:{},required:[],group:"bank",readOnly:!0,searchHint:"list bank and cash accounts with balances",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>aE(t.client)},cn("list_items","List items (products & services). Returns internalName, itemCode, appliesToSale/Purchase. Paginated \u2014 response includes totalElements. Use limit/offset to page.","items",(t,e,r,n)=>eO(t,{limit:r,offset:e,view:n}),"list products services items with pagination",{leanView:!0}),en({name:"search_items",description:"Search items. Use list_items to search by name (internalName is not a filter field).",group:"items",fields:R_,defaults:x_,fetcher:TE,searchHint:"find items products services by status category sale purchase type internalName via list_items"}),{name:"get_item",description:"Get full item details by resourceId.",params:{resourceId:{type:"string",description:"Item resourceId (UUID)"}},required:["resourceId"],group:"items",readOnly:!0,searchHint:"get item product service details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>xE(t.client,e.resourceId)},{name:"create_item",description:`Create a new item. Auto-checks for duplicates by itemCode \u2014 returns existing item if found.
718
718
  - saleItemName/purchaseItemName are auto-set from internalName if not provided.
719
- - Set appliesToSale and/or appliesToPurchase to control where the item can be used.`,params:{itemCode:{type:"string",description:"Unique item code"},internalName:{type:"string",description:"Item name"},appliesToSale:{type:"boolean",description:"Can be used on invoices"},appliesToPurchase:{type:"boolean",description:"Can be used on bills"},salePrice:{type:"number",description:"Default sale price"},purchasePrice:{type:"number",description:"Default purchase price"},saleAccountResourceId:{type:"string",description:"Revenue account for sales"},purchaseAccountResourceId:{type:"string",description:"Expense account for purchases"},customFields:Vi,returnFullEntity:sy},required:["itemCode","internalName"],group:"items",readOnly:!1,searchHint:"create new product or service item for invoicing",execute:async(t,e)=>{let r=e.itemCode,n=await yO(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Item with code "${r}" already exists.`,existing:n};let{purchasePrice:i,returnFullEntity:s,...o}=e,a={...o,...i!==void 0&&{purchaseItemPrice:i}},c=await qw(t.client,a);return kl(c,s===!0,u=>xE(t.client,u))}},{name:"update_item",description:"Update an existing item. Only send fields you want to change \u2014 required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Item resourceId"},internalName:{type:"string",description:"New name"},itemCode:{type:"string",description:"New code"},salePrice:{type:"number"},purchasePrice:{type:"number"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status (ACTIVE or INACTIVE)"},customFields:Vi},required:["resourceId"],group:"items",readOnly:!1,searchHint:"update existing item name price account details",execute:async(t,e)=>{let{resourceId:r,purchasePrice:n,...i}=e,s={...i,...n!==void 0&&{purchaseItemPrice:n}};return tO(t.client,r,s)}},{name:"delete_item",description:"Delete an item.",params:{resourceId:{type:"string",description:"Item resourceId"}},required:["resourceId"],group:"items",readOnly:!1,searchHint:"permanently delete an item product service",isDestructive:!0,execute:async(t,e)=>rO(t.client,e.resourceId)},{name:"bulk_upsert_items",description:"Max 500 items per call. Provide resourceId per item to update (partial \u2014 only changed fields needed, server preserves existing values). Omit resourceId to create (defaults: status=ACTIVE, itemCategory=NON_INVENTORY).",params:{items:{type:"array",description:"Array of items to create or update",items:{type:"object",properties:{resourceId:{type:"string",description:"Item resourceId (omit for create, provide for update)"},itemCode:{type:"string",description:"Unique item code (required for create)"},internalName:{type:"string",description:"Internal name (required for create)"},unit:{type:"string",description:"Unit of measure"},status:{type:"string",description:"Record status",enum:["ACTIVE","INACTIVE"]},appliesToSale:{type:"boolean",description:"Whether item applies to sales"},saleItemName:{type:"string",description:"Sale display name"},salePrice:{type:"number",description:"Sale price"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},saleTaxProfileResourceId:{type:"string",description:"Sale tax profile resourceId"},appliesToPurchase:{type:"boolean",description:"Whether item applies to purchases"},purchaseItemName:{type:"string",description:"Purchase display name"},purchasePrice:{type:"number",description:"Purchase price"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId"},purchaseTaxProfileResourceId:{type:"string",description:"Purchase tax profile resourceId"},inventory:{type:"boolean",description:"Whether this is an inventory item"},cogsResourceId:{type:"string",description:"COGS account resourceId"},costingMethod:{type:"string",description:"Costing method",enum:["FIXED","WAC"]},itemCategory:{type:"string",description:"Item category",enum:["INVENTORY","NON_INVENTORY"]},blockInsufficientDeductions:{type:"boolean",description:"Block insufficient stock deductions"}}}}},required:["items"],group:"items",readOnly:!1,searchHint:"bulk create or update multiple items at once",execute:async(t,e)=>{let r=e.items.map(({purchasePrice:i,...s})=>({...s,...i!==void 0&&{purchaseItemPrice:i}}));return(await nO(t.client,r)).data}},cn("list_tags","List tags used for transaction categorization. Paginated \u2014 response includes totalElements. Use limit/offset to page.","tags",(t,e,r)=>QE(t,{limit:r,offset:e}),"list all tags for categorization tracking"),en({name:"search_tags",description:"Search tags.",group:"tags",fields:P_,defaults:$_,fetcher:hO,searchHint:"find tags labels categorization by name"}),{name:"create_tag",description:"Create a new tag. Automatically reuses existing tag if one with the same name exists.",params:{name:{type:"string",description:"Tag name"}},required:["name"],group:"tags",readOnly:!1,searchHint:"create new tag for transaction categorization",execute:async(t,e)=>{let r=e.name,n=await CO(t.client,r);return n?{data:n,_note:`Tag "${r}" already exists \u2014 reusing.`}:Gw(t.client,{name:r})}},Ma("get_tag","Get a tag by resourceId.","tags",(t,e)=>pO(t,e),"get tag details by resource id"),{name:"update_tag",description:"Rename a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"},name:{type:"string",description:"New tag name"}},required:["resourceId","name"],group:"tags",readOnly:!1,searchHint:"update rename existing tag name",execute:async(t,e)=>mO(t.client,e.resourceId,{name:e.name})},{name:"delete_tag",description:"Delete a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"}},required:["resourceId"],group:"tags",readOnly:!1,searchHint:"permanently delete a tag",isDestructive:!0,execute:async(t,e)=>AO(t.client,e.resourceId)},{name:"list_capsule_types",description:"List capsule types (e.g., PREPAID_EXPENSE, DEFERRED_REVENUE). Use to get capsuleTypeResourceId before creating capsules via create_capsule. NOT the same as list_capsule_recipes (which lists IFRS recipe descriptors with JSON Schema input contracts).",params:{},required:[],group:"capsules",readOnly:!0,searchHint:"list capsule types for transaction grouping",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>kE(t.client)},cn("list_capsules","List capsules (transaction groupings for amortization, deferred revenue, etc.). Paginated \u2014 response includes totalElements. Use limit/offset to page.","capsules",(t,e,r)=>sO(t,{limit:r,offset:e}),"list capsules grouped transactions with pagination"),en({name:"search_capsules",description:"Search capsules.",group:"capsules",fields:j_,defaults:Y_,fetcher:NE,searchHint:"find capsules workflow groups by title status type capsuleType"}),{name:"get_capsule",description:"Get full capsule details by resourceId.",params:{resourceId:{type:"string",description:"Capsule resourceId (UUID)"}},required:["resourceId"],group:"capsules",readOnly:!0,searchHint:"get capsule details grouped transactions",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>Yw(t.client,e.resourceId)},{name:"create_capsule",description:"Create a new (legacy) capsule. List capsule types first to get the capsuleTypeResourceId. `title` is required and must be non-empty (blank/empty rejected with 422). For IFRS recipe-driven capsules (PREPAID_AMORTIZATION, LOAN_AMORTIZATION, etc.), use `preview_capsule_recipe` + `capsuleRecipe` payload on a trigger mutation instead \u2014 those create the capsule + scheduler atoms in one shot. This tool is for manually-grouped legacy capsules.",params:{capsuleTypeResourceId:{type:"string",description:"Capsule type resourceId (from list_capsule_types)"},title:{type:"string",description:"Capsule title \u2014 REQUIRED, non-empty (validation rejects blank/empty)"},description:{type:"string",description:"Capsule description"}},required:["capsuleTypeResourceId","title"],group:"capsules",readOnly:!1,searchHint:"create new capsule to group related transactions",execute:async(t,e)=>{let r=e.title,n=await U_e(t.client,r);return n?{_guard:"duplicate_skipped",message:`Capsule "${r}" already exists.`,existing:n}:Xm(t.client,{capsuleTypeResourceId:e.capsuleTypeResourceId,title:r,description:e.description})}},{name:"update_capsule",description:"Update a capsule title or description. Required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Capsule resourceId"},title:{type:"string",description:"New title"},description:{type:"string",description:"New description"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"update capsule title description details",execute:async(t,e)=>{let{resourceId:r,...n}=e;return oO(t.client,r,n)}},{name:"delete_capsule",description:"Delete a capsule.",params:{resourceId:{type:"string",description:"Capsule resourceId"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"permanently delete a capsule group",isDestructive:!0,execute:async(t,e)=>aO(t.client,e.resourceId)},cn("list_customer_credit_notes","List customer credit notes (AR adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","customer_credit_notes",(t,e,r)=>QQ(t,{limit:r,offset:e}),"list customer credit notes with status pagination"),en({name:"search_customer_credit_notes",description:"Search customer credit notes. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"customer_credit_notes",fields:Gd,defaults:eb,fetcher:lD,searchHint:"find customer credit notes refunds CN by reference status contact tag"}),{name:"get_customer_credit_note",description:"Get full customer credit note details including line items.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!0,searchHint:"get customer credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>su(t.client,e.resourceId)},{name:"create_customer_credit_note",description:`Create a customer credit note. Saves as draft by default.
719
+ - Set appliesToSale and/or appliesToPurchase to control where the item can be used.`,params:{itemCode:{type:"string",description:"Unique item code"},internalName:{type:"string",description:"Item name"},appliesToSale:{type:"boolean",description:"Can be used on invoices"},appliesToPurchase:{type:"boolean",description:"Can be used on bills"},salePrice:{type:"number",description:"Default sale price"},purchasePrice:{type:"number",description:"Default purchase price"},saleAccountResourceId:{type:"string",description:"Revenue account for sales"},purchaseAccountResourceId:{type:"string",description:"Expense account for purchases"},customFields:Vi,returnFullEntity:sy},required:["itemCode","internalName"],group:"items",readOnly:!1,searchHint:"create new product or service item for invoicing",execute:async(t,e)=>{let r=e.itemCode,n=await yO(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Item with code "${r}" already exists.`,existing:n};let{purchasePrice:i,returnFullEntity:s,...o}=e,a={...o,...i!==void 0&&{purchaseItemPrice:i}},c=await qw(t.client,a);return kl(c,s===!0,u=>xE(t.client,u))}},{name:"update_item",description:"Update an existing item. Only send fields you want to change \u2014 required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Item resourceId"},internalName:{type:"string",description:"New name"},itemCode:{type:"string",description:"New code"},salePrice:{type:"number"},purchasePrice:{type:"number"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status (ACTIVE or INACTIVE)"},customFields:Vi},required:["resourceId"],group:"items",readOnly:!1,searchHint:"update existing item name price account details",execute:async(t,e)=>{let{resourceId:r,purchasePrice:n,...i}=e,s={...i,...n!==void 0&&{purchaseItemPrice:n}};return tO(t.client,r,s)}},{name:"delete_item",description:"Delete an item.",params:{resourceId:{type:"string",description:"Item resourceId"}},required:["resourceId"],group:"items",readOnly:!1,searchHint:"permanently delete an item product service",isDestructive:!0,execute:async(t,e)=>rO(t.client,e.resourceId)},{name:"bulk_upsert_items",description:"Max 500 items per call. Provide resourceId per item to update (partial \u2014 only changed fields needed, server preserves existing values). Omit resourceId to create (defaults: status=ACTIVE, itemCategory=NON_INVENTORY).",params:{items:{type:"array",description:"Array of items to create or update",items:{type:"object",properties:{resourceId:{type:"string",description:"Item resourceId (omit for create, provide for update)"},itemCode:{type:"string",description:"Unique item code (required for create)"},internalName:{type:"string",description:"Internal name (required for create)"},unit:{type:"string",description:"Unit of measure"},status:{type:"string",description:"Record status",enum:["ACTIVE","INACTIVE"]},appliesToSale:{type:"boolean",description:"Whether item applies to sales"},saleItemName:{type:"string",description:"Sale display name"},salePrice:{type:"number",description:"Sale price"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},saleTaxProfileResourceId:{type:"string",description:"Sale tax profile resourceId"},appliesToPurchase:{type:"boolean",description:"Whether item applies to purchases"},purchaseItemName:{type:"string",description:"Purchase display name"},purchasePrice:{type:"number",description:"Purchase price"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId"},purchaseTaxProfileResourceId:{type:"string",description:"Purchase tax profile resourceId"},inventory:{type:"boolean",description:"Whether this is an inventory item"},cogsResourceId:{type:"string",description:"COGS account resourceId"},costingMethod:{type:"string",description:"Costing method",enum:["FIXED","WAC"]},itemCategory:{type:"string",description:"Item category",enum:["INVENTORY","NON_INVENTORY"]},blockInsufficientDeductions:{type:"boolean",description:"Block insufficient stock deductions"}}}}},required:["items"],group:"items",readOnly:!1,searchHint:"bulk create or update multiple items at once",execute:async(t,e)=>{let r=e.items.map(({purchasePrice:i,...s})=>({...s,...i!==void 0&&{purchaseItemPrice:i}}));return(await nO(t.client,r)).data}},cn("list_tags","List tags used for transaction categorization. Paginated \u2014 response includes totalElements. Use limit/offset to page.","tags",(t,e,r)=>QE(t,{limit:r,offset:e}),"list all tags for categorization tracking"),en({name:"search_tags",description:"Search tags.",group:"tags",fields:P_,defaults:$_,fetcher:hO,searchHint:"find tags labels categorization by name"}),{name:"create_tag",description:"Create a new tag. Automatically reuses existing tag if one with the same name exists.",params:{name:{type:"string",description:"Tag name"}},required:["name"],group:"tags",readOnly:!1,searchHint:"create new tag for transaction categorization",execute:async(t,e)=>{let r=e.name,n=await CO(t.client,r);return n?{data:n,_note:`Tag "${r}" already exists \u2014 reusing.`}:Gw(t.client,{name:r})}},Ma("get_tag","Get a tag by resourceId.","tags",(t,e)=>pO(t,e),"get tag details by resource id"),{name:"update_tag",description:"Rename a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"},name:{type:"string",description:"New tag name"}},required:["resourceId","name"],group:"tags",readOnly:!1,searchHint:"update rename existing tag name",execute:async(t,e)=>mO(t.client,e.resourceId,{name:e.name})},{name:"delete_tag",description:"Delete a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"}},required:["resourceId"],group:"tags",readOnly:!1,searchHint:"permanently delete a tag",isDestructive:!0,execute:async(t,e)=>AO(t.client,e.resourceId)},{name:"list_capsule_types",description:"List capsule types (e.g., PREPAID_EXPENSE, DEFERRED_REVENUE). Use to get capsuleTypeResourceId before creating capsules via create_capsule. NOT the same as list_capsule_recipes (which lists IFRS recipe descriptors with JSON Schema input contracts).",params:{},required:[],group:"capsules",readOnly:!0,searchHint:"list capsule types for transaction grouping",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>kE(t.client)},cn("list_capsules","List capsules (transaction groupings for amortization, deferred revenue, etc.). Paginated \u2014 response includes totalElements. Use limit/offset to page.","capsules",(t,e,r)=>sO(t,{limit:r,offset:e}),"list capsules grouped transactions with pagination"),en({name:"search_capsules",description:"Search capsules.",group:"capsules",fields:j_,defaults:Y_,fetcher:NE,searchHint:"find capsules workflow groups by title status type capsuleType"}),{name:"get_capsule",description:"Get full capsule details by resourceId.",params:{resourceId:{type:"string",description:"Capsule resourceId (UUID)"}},required:["resourceId"],group:"capsules",readOnly:!0,searchHint:"get capsule details grouped transactions",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>Yw(t.client,e.resourceId)},{name:"create_capsule",description:"Create a new (legacy) capsule. List capsule types first to get the capsuleTypeResourceId. `title` is required and must be non-empty (blank/empty rejected with 422). For IFRS recipe-driven capsules (PREPAID_AMORTIZATION, LOAN_AMORTIZATION, etc.), use `preview_capsule_recipe` + `capsuleRecipe` payload on a trigger mutation instead \u2014 those create the capsule + scheduler atoms in one shot. This tool is for manually-grouped legacy capsules.",params:{capsuleTypeResourceId:{type:"string",description:"Capsule type resourceId (from list_capsule_types)"},title:{type:"string",description:"Capsule title \u2014 REQUIRED, non-empty (validation rejects blank/empty)"},description:{type:"string",description:"Capsule description"}},required:["capsuleTypeResourceId","title"],group:"capsules",readOnly:!1,searchHint:"create new capsule to group related transactions",execute:async(t,e)=>{let r=e.title,n=await U_e(t.client,r);return n?{_guard:"duplicate_skipped",message:`Capsule "${r}" already exists.`,existing:n}:Xm(t.client,{capsuleTypeResourceId:e.capsuleTypeResourceId,title:r,description:e.description})}},{name:"update_capsule",description:"Update a capsule title or description. Required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Capsule resourceId"},title:{type:"string",description:"New title"},description:{type:"string",description:"New description"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"update capsule title description details",execute:async(t,e)=>{let{resourceId:r,...n}=e;return oO(t.client,r,n)}},{name:"delete_capsule",description:"Delete a capsule.",params:{resourceId:{type:"string",description:"Capsule resourceId"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"permanently delete a capsule group",isDestructive:!0,execute:async(t,e)=>aO(t.client,e.resourceId)},cn("list_customer_credit_notes","List customer credit notes (AR adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","customer_credit_notes",(t,e,r,n)=>QQ(t,{limit:r,offset:e,view:n}),"list customer credit notes with status pagination",{leanView:!0}),en({name:"search_customer_credit_notes",description:"Search customer credit notes. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"customer_credit_notes",fields:Gd,defaults:eb,fetcher:lD,searchHint:"find customer credit notes refunds CN by reference status contact tag"}),{name:"get_customer_credit_note",description:"Get full customer credit note details including line items.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!0,searchHint:"get customer credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>su(t.client,e.resourceId)},{name:"create_customer_credit_note",description:`Create a customer credit note. Saves as draft by default.
720
720
  - Status when finalized is UNAPPLIED (not APPROVED).
721
721
  - Line items use "name" for item description.
722
722
  - contactResourceId required \u2014 search contacts first.
723
- - reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify.`,params:{reference:{type:"string",description:"Credit note reference number"},valueDate:{type:"string",description:"Credit note date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:cy},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:oy,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:ri,tag:Fl,customFields:Vi},required:["valueDate","contactResourceId","lineItems"],group:"customer_credit_notes",readOnly:!1,searchHint:"create new customer credit note draft",execute:async(t,e)=>{let r=eu(e);if(r)return r;let{notes:n,tag:i,...s}=e,o={...s,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return o.reference||(o.reference=`CCN-${Date.now()}`),fD(t.client,o)}},{name:"delete_customer_credit_note",description:"Delete a draft customer credit note.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"permanently delete draft customer credit note",isDestructive:!0,execute:async(t,e)=>MQ(t.client,e.resourceId)},{name:"update_customer_credit_note",description:'Update a draft customer credit note (change amount, line items, contact, date, notes). Use when the user says "update", "change", "fix", or "correct" a credit note.',params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:as,valueDate:os,lineItems:ta,notes:ri,tag:Fl,customFields:Vi},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"update customer credit note lines reference",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,...s}=e,o={...s,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return LQ(t.client,r,o)}},{name:"finalize_customer_credit_note",description:"Finalize a draft customer credit note (set saveAsDraft=false). Status becomes UNAPPLIED.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:as,valueDate:os,lineItems:ta,notes:ri},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"approve finalize customer credit note",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,s={...i,...n!==void 0&&{invoiceNotes:n}},o=await _x(t.client,"customer_credit_note",r,s),a=eu(o,{assumeFinalize:!0});return a||dD(t.client,r,o)}},{name:"create_customer_credit_note_refund",description:"Record a refund payment against a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"},paymentAmount:{type:"number",description:"Refund amount"},transactionAmount:{type:"number",description:"Amount in credit note currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:wx},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"customer_credit_notes",readOnly:!1,searchHint:"refund customer credit note to bank account",isDestructive:!0,execute:async(t,e)=>{let r=Number(e.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(e.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return pD(t.client,e.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference??"",paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1})}},{name:"list_customer_credit_note_refunds",description:"List refund payments for a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"}},required:["creditNoteId"],group:"customer_credit_notes",readOnly:!0,searchHint:"list refunds on a customer credit note",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(t,e)=>PQ(t.client,e.creditNoteId)},cn("list_supplier_credit_notes","List supplier credit notes (AP adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","supplier_credit_notes",(t,e,r)=>jQ(t,{limit:r,offset:e}),"list supplier credit notes with status pagination"),en({name:"search_supplier_credit_notes",description:"Search supplier credit notes. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"supplier_credit_notes",fields:Gd,defaults:b_,fetcher:hD,searchHint:"find supplier credit notes refunds CN by reference status contact tag"}),{name:"get_supplier_credit_note",description:"Get full supplier credit note details including line items.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"}},required:["resourceId"],group:"supplier_credit_notes",readOnly:!0,searchHint:"get supplier credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>ou(t.client,e.resourceId)},{name:"create_supplier_credit_note",description:`Create a supplier credit note. Saves as draft by default.
723
+ - reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify.`,params:{reference:{type:"string",description:"Credit note reference number"},valueDate:{type:"string",description:"Credit note date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:cy},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:oy,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:ri,tag:Fl,customFields:Vi},required:["valueDate","contactResourceId","lineItems"],group:"customer_credit_notes",readOnly:!1,searchHint:"create new customer credit note draft",execute:async(t,e)=>{let r=eu(e);if(r)return r;let{notes:n,tag:i,...s}=e,o={...s,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return o.reference||(o.reference=`CCN-${Date.now()}`),fD(t.client,o)}},{name:"delete_customer_credit_note",description:"Delete a draft customer credit note.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"permanently delete draft customer credit note",isDestructive:!0,execute:async(t,e)=>MQ(t.client,e.resourceId)},{name:"update_customer_credit_note",description:'Update a draft customer credit note (change amount, line items, contact, date, notes). Use when the user says "update", "change", "fix", or "correct" a credit note.',params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:as,valueDate:os,lineItems:ta,notes:ri,tag:Fl,customFields:Vi},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"update customer credit note lines reference",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,...s}=e,o={...s,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return LQ(t.client,r,o)}},{name:"finalize_customer_credit_note",description:"Finalize a draft customer credit note (set saveAsDraft=false). Status becomes UNAPPLIED.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:as,valueDate:os,lineItems:ta,notes:ri},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"approve finalize customer credit note",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,s={...i,...n!==void 0&&{invoiceNotes:n}},o=await _x(t.client,"customer_credit_note",r,s),a=eu(o,{assumeFinalize:!0});return a||dD(t.client,r,o)}},{name:"create_customer_credit_note_refund",description:"Record a refund payment against a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"},paymentAmount:{type:"number",description:"Refund amount"},transactionAmount:{type:"number",description:"Amount in credit note currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:wx},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"customer_credit_notes",readOnly:!1,searchHint:"refund customer credit note to bank account",isDestructive:!0,execute:async(t,e)=>{let r=Number(e.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(e.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return pD(t.client,e.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference??"",paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1})}},{name:"list_customer_credit_note_refunds",description:"List refund payments for a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"}},required:["creditNoteId"],group:"customer_credit_notes",readOnly:!0,searchHint:"list refunds on a customer credit note",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(t,e)=>PQ(t.client,e.creditNoteId)},cn("list_supplier_credit_notes","List supplier credit notes (AP adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","supplier_credit_notes",(t,e,r,n)=>jQ(t,{limit:r,offset:e,view:n}),"list supplier credit notes with status pagination",{leanView:!0}),en({name:"search_supplier_credit_notes",description:"Search supplier credit notes. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"supplier_credit_notes",fields:Gd,defaults:b_,fetcher:hD,searchHint:"find supplier credit notes refunds CN by reference status contact tag"}),{name:"get_supplier_credit_note",description:"Get full supplier credit note details including line items.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"}},required:["resourceId"],group:"supplier_credit_notes",readOnly:!0,searchHint:"get supplier credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>ou(t.client,e.resourceId)},{name:"create_supplier_credit_note",description:`Create a supplier credit note. Saves as draft by default.
724
724
  - Status when finalized is UNAPPLIED (not APPROVED).
725
725
  - Line items use "name" for item description.
726
726
  - contactResourceId required \u2014 search contacts first.`,params:{reference:{type:"string",description:"Credit note reference number"},valueDate:{type:"string",description:"Credit note date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Supplier contact resourceId"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:cy},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:oy,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:ri,tag:Fl,customFields:Vi},required:["valueDate","contactResourceId","lineItems"],group:"supplier_credit_notes",readOnly:!1,searchHint:"create new supplier credit note draft",execute:async(t,e)=>{let r=eu(e);if(r)return r;let{notes:n,tag:i,...s}=e,o={...s,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return o.reference||(o.reference=`SCN-${Date.now()}`),mD(t.client,o)}},{name:"delete_supplier_credit_note",description:"Delete a draft supplier credit note.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"}},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"permanently delete draft supplier credit note",isDestructive:!0,execute:async(t,e)=>zQ(t.client,e.resourceId)},{name:"download_supplier_credit_note_pdf",description:"Download a supplier credit note as PDF. Returns { fileUrl } (may be pending/empty if not yet rendered).",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"}},required:["resourceId"],group:"supplier_credit_notes",readOnly:!0,searchHint:"download supplier credit note as PDF document file",isConcurrencySafe:!0,execute:async(t,e)=>HQ(t.client,e.resourceId)},{name:"update_supplier_credit_note",description:'Update a draft supplier credit note (change amount, line items, contact, date, notes). Use when the user says "update", "change", "fix", or "correct" a credit note.',params:{resourceId:{type:"string",description:"Supplier credit note resourceId"},reference:as,valueDate:os,lineItems:ta,notes:ri,tag:Fl,customFields:Vi},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"update supplier credit note lines reference",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,...s}=e,o={...s,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return YQ(t.client,r,o)}},{name:"finalize_supplier_credit_note",description:"Finalize a draft supplier credit note (set saveAsDraft=false). Status becomes UNAPPLIED.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"},reference:as,valueDate:os,lineItems:ta,notes:ri},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"approve finalize supplier credit note",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,s={...i,...n!==void 0&&{invoiceNotes:n}},o=await _x(t.client,"supplier_credit_note",r,s),a=eu(o,{assumeFinalize:!0});return a||AD(t.client,r,o)}},{name:"create_supplier_credit_note_refund",description:"Record a refund payment against a supplier credit note.",params:{creditNoteId:{type:"string",description:"Supplier credit note resourceId"},paymentAmount:{type:"number",description:"Refund amount"},transactionAmount:{type:"number",description:"Amount in credit note currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:wx},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"supplier_credit_notes",readOnly:!1,searchHint:"refund supplier credit note from bank account",isDestructive:!0,execute:async(t,e)=>{let r=Number(e.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(e.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return gD(t.client,e.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference??"",paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1})}},{name:"list_supplier_credit_note_refunds",description:"List refund payments for a supplier credit note.",params:{creditNoteId:{type:"string",description:"Supplier credit note resourceId"}},required:["creditNoteId"],group:"supplier_credit_notes",readOnly:!0,searchHint:"list refunds on a supplier credit note",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(t,e)=>GQ(t.client,e.creditNoteId)},{name:"list_currencies",description:"List currencies enabled for the organization. Returns code, name, symbol, isBaseCurrency.",params:{},required:[],group:"currencies",readOnly:!0,searchHint:"list currencies enabled active organization base currency code symbol",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>yD(t.client)},{name:"add_currency",description:"Enable one or more currencies for the organization.",params:{currencies:{type:"array",items:{type:"string"},description:'Currency codes to add (e.g., ["USD", "EUR"])'}},required:["currencies"],group:"currencies",readOnly:!1,searchHint:"add new currency to organization",execute:async(t,e)=>{let r=e.currencies,n=await yD(t.client),i=new Set(n.data.map(c=>c.currencyCode.toUpperCase())),s=r.filter(c=>i.has(c.toUpperCase())),o=r.filter(c=>!i.has(c.toUpperCase()));if(o.length===0)return{_guard:"duplicate_skipped",message:`All currencies already enabled: ${r.join(", ")}.`,existing:s};let a=await WQ(t.client,o);return s.length>0?{...a,_note:`Skipped already-enabled: ${s.join(", ")}`}:a}},{name:"list_currency_rates",description:"List exchange rates for a specific currency. IMPORTANT: You MUST call list_currencies first to discover which currencies the org has enabled \u2014 never guess or assume currency codes.",params:{currencyCode:{type:"string",description:'Currency code (e.g., "USD")'},...Iue},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"list exchange rates for a currency pair",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(t,e)=>{let{limit:r,offset:n}=xet(e),i=e.currencyCode;return h_((s,o)=>ZQ(t.client,i,{limit:o,offset:s}),r,n,100)}},{name:"add_currency_rate",description:'Add or set an exchange rate for a currency. ALWAYS use this tool even when the user says "update rate" \u2014 it handles both new and existing rates. Rate is relative to the base currency. Call list_currencies first to get valid currency codes.',params:{currencyCode:{type:"string",description:"Currency code"},rate:{type:"number",description:"Exchange rate (e.g., 1.35 for 1 USD = 1.35 SGD)"},rateApplicableFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},rateApplicableTo:{type:"string",description:"End date (YYYY-MM-DD, optional)"}},required:["currencyCode","rate","rateApplicableFrom"],group:"currencies",readOnly:!1,searchHint:"add new exchange rate for currency pair",execute:async(t,e)=>KQ(t.client,e.currencyCode,{rate:e.rate,rateApplicableFrom:e.rateApplicableFrom,rateApplicableTo:e.rateApplicableTo})},{name:"update_currency_rate",description:'Update an EXISTING exchange rate record by its resourceId. Requires the rate resourceId from list_currency_rates. WARNING: If the user says "update the rate" or "set the rate", they almost always mean add_currency_rate (which creates/overwrites for a date). Only use this tool when explicitly modifying an existing rate record by ID.',params:{currencyCode:{type:"string",description:"Currency code"},resourceId:{type:"string",description:"Rate resourceId"},rate:{type:"number",description:"New exchange rate"},rateApplicableFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},rateApplicableTo:{type:"string",description:"End date (YYYY-MM-DD, optional)"}},required:["currencyCode","resourceId","rate","rateApplicableFrom"],group:"currencies",readOnly:!1,searchHint:"update existing exchange rate value",execute:async(t,e)=>XQ(t.client,e.currencyCode,e.resourceId,{rate:e.rate,rateApplicableFrom:e.rateApplicableFrom,rateApplicableTo:e.rateApplicableTo})},{name:"bulk_upsert_currency_rates",description:"Max 500 exchange rates per call. Auto-enables currencies not yet enabled in the org \u2014 no need to call add_currency first. Requires rateDirection per rate. Response surfaces per-row failures: `failedRows[]` (each with rowIndex, columnName, columnValue, errorCode, errorMessage) + `failedCount` alongside `resourceIds[]` for successful inserts. Omitting `rateApplicableTo` defaults it to `rateApplicableFrom - 0.999ms` (no temporal gap).",params:{rates:{type:"array",description:"Array of exchange rates to create",items:{type:"object",properties:{sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217, e.g. USD, EUR)"},rate:{type:"number",description:"Exchange rate value (must be > 0)"},rateDirection:{type:"string",description:"Rate direction",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"]},rateApplicableFrom:{type:"string",description:"Rate start date (YYYY-MM-DD)"},rateApplicableTo:{type:"string",description:"Rate end date (YYYY-MM-DD, optional)"}},required:["sourceCurrencyCode","rate","rateDirection","rateApplicableFrom"]}}},required:["rates"],group:"currencies",readOnly:!1,searchHint:"bulk create or update multiple currency rates",execute:async(t,e)=>(await eL(t.client,e.rates)).data},cn("list_tax_profiles","List tax profiles (GST, VAT, etc.). Returns name, rate, tax type.","tax_profiles",(t,e,r)=>FE(t,{limit:r,offset:e}),"list tax profiles GST VAT rates"),cn("list_tax_types","List available tax types. Use the tax type code when creating tax profiles.","tax_profiles",(t,e,r)=>cO(t,{limit:r,offset:e}),"list available tax types for profile creation"),{name:"create_tax_profile",description:"Create a new tax profile. List tax types first to get the taxTypeCode. Automatically checks for duplicates by name \u2014 returns existing profile if found.",params:{name:{type:"string",description:'Tax profile name (e.g., "GST 9%")'},taxRate:{type:"number",description:"Tax rate as percentage (e.g., 9 for 9%)"},taxTypeCode:{type:"string",description:"Tax type code (from list_tax_types)"}},required:["name","taxRate","taxTypeCode"],group:"tax_profiles",readOnly:!1,searchHint:"create new tax profile GST VAT rate",execute:async(t,e)=>{let r=e.name,n=await bO(t.client,r);return n?{_guard:"duplicate_skipped",message:`Tax profile "${r}" already exists.`,existing:n}:uO(t.client,{name:r,taxRate:e.taxRate,taxTypeCode:e.taxTypeCode})}},cn("list_cash_in","List cash-in entries (direct cash receipts). Paginated.","cash_entries",(t,e,r)=>Ij(t,{limit:r,offset:e}),"list cash in receipt entries with pagination"),{name:"create_cash_in",description:`Record money received INTO a bank account from an EXTERNAL source (customer payment, refund received, deposit). For inter-account moves use create_cash_transfer.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jaz-clio",
3
- "version": "5.14.0",
3
+ "version": "5.14.2",
4
4
  "description": "Clio: Command Line Interface Operator for Jaz AI.",
5
5
  "type": "module",
6
6
  "bin": {