jaz-clio 9.6.1 → 9.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/api/SKILL.md +1 -1
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-kit/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +4 -4
- package/dashboard-routes-manifest.json +368 -38
- package/package.json +1 -1
package/cli.mjs
CHANGED
|
@@ -659,7 +659,7 @@ actual: `+e._bytesWritten),PG.prototype._finish.call(e)}});var Ime=I((Crn,tot)=>
|
|
|
659
659
|
Unsupported type: `+e.type,"ENOTSUP");e._finish()})};Zc.prototype._stat=function(e){var t=this,r=t.props,n=r.follow?"stat":"lstat",i=t._proxy||t;e?o(null,e):Xc[n](t._path,o);function o(s,a){if(t.filter&&!t.filter.call(i,i,a)){t._aborted=!0,t.emit("end"),t.emit("close");return}if(s||!a)return Cme(t);t._old=a;var c=iot(a);if(c!==t.type||t.type==="File"&&a.nlink>1)return CCr(t._path,function(u){if(u)return t.error(u);t._old=null,Cme(t)});Cme(t)}};function Cme(e){_Cr(FB.dirname(e._path),Zc.dirmode,function(t,r){return t?e.error(t):(e._madeDir=r,e._create())})}function sot(e,t,r,n,i){var o=t.mode,s=t.follow||e.type!=="SymbolicLink"?"chmod":"lchmod";if(!Xc[s]||typeof o!="number")return i();var a=r.mode&parseInt("0777",8);if(o=o&parseInt("0777",8),o===a)return i();Xc[s](n,o,i)}function aot(e,t,r,n,i){if(process.platform==="win32"||!process.getuid||process.getuid()!==0||typeof t.uid!="number"&&typeof t.gid!="number"||r.uid===t.uid&&r.gid===t.gid)return i();var o=e.props.follow||e.type!=="SymbolicLink"?"chown":"lchown";if(!Xc[o])return i();typeof t.uid!="number"&&(t.uid=r.uid),typeof t.gid!="number"&&(t.gid=r.gid),Xc[o](n,t.uid,t.gid,i)}function cot(e,t,r,n,i){if(!Xc.utimes||process.platform==="win32")return i();var o=t.follow||e.type!=="SymbolicLink"?"utimes":"lutimes";if(o==="lutimes"&&!Xc[o]&&(o="utimes"),!Xc[o])return i();var s=r.atime,a=r.mtime,c=t.atime,u=t.mtime;if(c===void 0&&(c=s),u===void 0&&(u=a),rot(c)||(c=new Date(c)),rot(u)||(c=new Date(u)),c.getTime()===s.getTime()&&u.getTime()===a.getTime())return i();Xc[o](n,c,u,i)}Zc.prototype._finish=function(){var e=this;if(e._finishing)return;e._finishing=!0;var t=0,r=null,n=!1;if(e._old)e._old.atime=new Date(0),e._old.mtime=new Date(0),o(e._old);else{var i=e.props.follow?"stat":"lstat";Xc[i](e._path,function(a,c){if(a)if(a.code==="ENOENT"&&(e.type==="Link"||e.type==="SymbolicLink")&&process.platform==="win32"){e.ready=!0,e.emit("ready"),e.emit("end"),e.emit("close"),e.end=e._finish=function(){};return}else return e.error(a);o(e._old=c)})}return;function o(a){t+=3,sot(e,e.props,a,e._path,s("chmod")),aot(e,e.props,a,e._path,s("chown")),cot(e,e.props,a,e._path,s("utimes"))}function s(a){return function(c){if(r)return;if(c)return c.fstream_finish_call=a,e.error(r=c);if(--t>0||n)return;if(n=!0,e._madeDir)lot(e,e._path,u);else return u();function u(d){if(d)return d.fstream_finish_call="setupMadeDir",e.error(d);e.emit("end"),e.emit("close")}}}};function lot(e,t,r){var n=e._madeDir,i=FB.dirname(t);RCr(e,i,function(o){if(o)return r(o);if(i===n)return r();lot(e,i,r)})}function RCr(e,t,r){var n={};Object.keys(e.props).forEach(function(a){n[a]=e.props[a],a==="mode"&&e.type!=="Directory"&&(n[a]=n[a]|parseInt("0111",8))});var i=3,o=null;Xc.stat(t,function(a,c){if(a)return r(o=a);sot(e,n,c,t,s),aot(e,n,c,t,s),cot(e,n,c,t,s)});function s(a){if(!o){if(a)return r(o=a);if(--i===0)return r()}}}Zc.prototype.pipe=function(){this.error("Can't pipe from writable stream")};Zc.prototype.add=function(){this.error("Can't add to non-Directory type")};Zc.prototype.write=function(){return!0};function TCr(e){return Object.prototype.toString.call(e)}function rot(e){return typeof e=="object"&&TCr(e)==="[object Date]"}});var _me=I(Mr=>{Mr.Abstract=kG();Mr.Reader=AE();Mr.Writer=Hw();Mr.File={Reader:sme(),Writer:Eme()};Mr.Dir={Reader:ome(),Writer:gme()};Mr.Link={Reader:nme(),Writer:yme()};Mr.Proxy={Reader:cme(),Writer:Ime()};Mr.Reader.Dir=Mr.DirReader=Mr.Dir.Reader;Mr.Reader.File=Mr.FileReader=Mr.File.Reader;Mr.Reader.Link=Mr.LinkReader=Mr.Link.Reader;Mr.Reader.Proxy=Mr.ProxyReader=Mr.Proxy.Reader;Mr.Writer.Dir=Mr.DirWriter=Mr.Dir.Writer;Mr.Writer.File=Mr.FileWriter=Mr.File.Writer;Mr.Writer.Link=Mr.LinkWriter=Mr.Link.Writer;Mr.Writer.Proxy=Mr.ProxyWriter=Mr.Proxy.Writer;Mr.collect=LG()});var fot=I((vrn,dot)=>{dot.exports=FCr;var xCr=xG(),kCr=_me().Writer,wme=z("path"),NCr=z("stream"),BCr=eme(),OCr=Jm();function FCr(e){e.path=wme.resolve(wme.normalize(e.path));var t=new xCr(e),r=new NCr.Writable({objectMode:!0});r._write=function(i,o,s){if(i.type=="Directory")return s();var a=wme.join(e.path,i.path);if(a.indexOf(e.path)!=0)return s();let c=e.getWriter?e.getWriter({path:a}):kCr({path:a});i.pipe(c).on("error",s).on("close",s)};var n=BCr(t,r);return t.once("crx-header",function(i){n.crxHeader=i}),t.pipe(r).on("finish",function(){n.emit("close")}),n.promise=function(){return new OCr(function(i,o){n.on("close",i),n.on("error",o)})},n}});var pot=I((Srn,MG)=>{var Io=(function(e){"use strict";var t=1e7,r=7,n=9007199254740992,i=p(n),o="0123456789abcdefghijklmnopqrstuvwxyz",s=typeof BigInt=="function";function a(v,x,P,H){return typeof v>"u"?a[0]:typeof x<"u"?+x==10&&!P?ae(v):Ve(v,x,P,H):ae(v)}function c(v,x){this.value=v,this.sign=x,this.isSmall=!1}c.prototype=Object.create(a.prototype);function u(v){this.value=v,this.sign=v<0,this.isSmall=!0}u.prototype=Object.create(a.prototype);function d(v){this.value=v}d.prototype=Object.create(a.prototype);function f(v){return-n<v&&v<n}function p(v){return v<1e7?[v]:v<1e14?[v%1e7,Math.floor(v/1e7)]:[v%1e7,Math.floor(v/1e7)%1e7,Math.floor(v/1e14)]}function h(v){m(v);var x=v.length;if(x<4&&V(v,i)<0)switch(x){case 0:return 0;case 1:return v[0];case 2:return v[0]+v[1]*t;default:return v[0]+(v[1]+v[2]*t)*t}return v}function m(v){for(var x=v.length;v[--x]===0;);v.length=x+1}function A(v){for(var x=new Array(v),P=-1;++P<v;)x[P]=0;return x}function g(v){return v>0?Math.floor(v):Math.ceil(v)}function y(v,x){var P=v.length,H=x.length,ie=new Array(P),re=0,se=t,ce,ge;for(ge=0;ge<H;ge++)ce=v[ge]+x[ge]+re,re=ce>=se?1:0,ie[ge]=ce-re*se;for(;ge<P;)ce=v[ge]+re,re=ce===se?1:0,ie[ge++]=ce-re*se;return re>0&&ie.push(re),ie}function b(v,x){return v.length>=x.length?y(v,x):y(x,v)}function E(v,x){var P=v.length,H=new Array(P),ie=t,re,se;for(se=0;se<P;se++)re=v[se]-ie+x,x=Math.floor(re/ie),H[se]=re-x*ie,x+=1;for(;x>0;)H[se++]=x%ie,x=Math.floor(x/ie);return H}c.prototype.add=function(v){var x=ae(v);if(this.sign!==x.sign)return this.subtract(x.negate());var P=this.value,H=x.value;return x.isSmall?new c(E(P,Math.abs(H)),this.sign):new c(b(P,H),this.sign)},c.prototype.plus=c.prototype.add,u.prototype.add=function(v){var x=ae(v),P=this.value;if(P<0!==x.sign)return this.subtract(x.negate());var H=x.value;if(x.isSmall){if(f(P+H))return new u(P+H);H=p(Math.abs(H))}return new c(E(H,Math.abs(P)),P<0)},u.prototype.plus=u.prototype.add,d.prototype.add=function(v){return new d(this.value+ae(v).value)},d.prototype.plus=d.prototype.add;function C(v,x){var P=v.length,H=x.length,ie=new Array(P),re=0,se=t,ce,ge;for(ce=0;ce<H;ce++)ge=v[ce]-re-x[ce],ge<0?(ge+=se,re=1):re=0,ie[ce]=ge;for(ce=H;ce<P;ce++){if(ge=v[ce]-re,ge<0)ge+=se;else{ie[ce++]=ge;break}ie[ce]=ge}for(;ce<P;ce++)ie[ce]=v[ce];return m(ie),ie}function w(v,x,P){var H;return V(v,x)>=0?H=C(v,x):(H=C(x,v),P=!P),H=h(H),typeof H=="number"?(P&&(H=-H),new u(H)):new c(H,P)}function T(v,x,P){var H=v.length,ie=new Array(H),re=-x,se=t,ce,ge;for(ce=0;ce<H;ce++)ge=v[ce]+re,re=Math.floor(ge/se),ge%=se,ie[ce]=ge<0?ge+se:ge;return ie=h(ie),typeof ie=="number"?(P&&(ie=-ie),new u(ie)):new c(ie,P)}c.prototype.subtract=function(v){var x=ae(v);if(this.sign!==x.sign)return this.add(x.negate());var P=this.value,H=x.value;return x.isSmall?T(P,Math.abs(H),this.sign):w(P,H,this.sign)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(v){var x=ae(v),P=this.value;if(P<0!==x.sign)return this.add(x.negate());var H=x.value;return x.isSmall?new u(P-H):T(H,Math.abs(P),P>=0)},u.prototype.minus=u.prototype.subtract,d.prototype.subtract=function(v){return new d(this.value-ae(v).value)},d.prototype.minus=d.prototype.subtract,c.prototype.negate=function(){return new c(this.value,!this.sign)},u.prototype.negate=function(){var v=this.sign,x=new u(-this.value);return x.sign=!v,x},d.prototype.negate=function(){return new d(-this.value)},c.prototype.abs=function(){return new c(this.value,!1)},u.prototype.abs=function(){return new u(Math.abs(this.value))},d.prototype.abs=function(){return new d(this.value>=0?this.value:-this.value)};function D(v,x){var P=v.length,H=x.length,ie=P+H,re=A(ie),se=t,ce,ge,Pe,Je,dt;for(Pe=0;Pe<P;++Pe){Je=v[Pe];for(var Zt=0;Zt<H;++Zt)dt=x[Zt],ce=Je*dt+re[Pe+Zt],ge=Math.floor(ce/se),re[Pe+Zt]=ce-ge*se,re[Pe+Zt+1]+=ge}return m(re),re}function k(v,x){var P=v.length,H=new Array(P),ie=t,re=0,se,ce;for(ce=0;ce<P;ce++)se=v[ce]*x+re,re=Math.floor(se/ie),H[ce]=se-re*ie;for(;re>0;)H[ce++]=re%ie,re=Math.floor(re/ie);return H}function F(v,x){for(var P=[];x-- >0;)P.push(0);return P.concat(v)}function G(v,x){var P=Math.max(v.length,x.length);if(P<=30)return D(v,x);P=Math.ceil(P/2);var H=v.slice(P),ie=v.slice(0,P),re=x.slice(P),se=x.slice(0,P),ce=G(ie,se),ge=G(H,re),Pe=G(b(ie,H),b(se,re)),Je=b(b(ce,F(C(C(Pe,ce),ge),P)),F(ge,2*P));return m(Je),Je}function j(v,x){return-.012*v-.012*x+15e-6*v*x>0}c.prototype.multiply=function(v){var x=ae(v),P=this.value,H=x.value,ie=this.sign!==x.sign,re;if(x.isSmall){if(H===0)return a[0];if(H===1)return this;if(H===-1)return this.negate();if(re=Math.abs(H),re<t)return new c(k(P,re),ie);H=p(re)}return j(P.length,H.length)?new c(G(P,H),ie):new c(D(P,H),ie)},c.prototype.times=c.prototype.multiply;function R(v,x,P){return v<t?new c(k(x,v),P):new c(D(x,p(v)),P)}u.prototype._multiplyBySmall=function(v){return f(v.value*this.value)?new u(v.value*this.value):R(Math.abs(v.value),p(Math.abs(this.value)),this.sign!==v.sign)},c.prototype._multiplyBySmall=function(v){return v.value===0?a[0]:v.value===1?this:v.value===-1?this.negate():R(Math.abs(v.value),this.value,this.sign!==v.sign)},u.prototype.multiply=function(v){return ae(v)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,d.prototype.multiply=function(v){return new d(this.value*ae(v).value)},d.prototype.times=d.prototype.multiply;function O(v){var x=v.length,P=A(x+x),H=t,ie,re,se,ce,ge;for(se=0;se<x;se++){ce=v[se],re=0-ce*ce;for(var Pe=se;Pe<x;Pe++)ge=v[Pe],ie=2*(ce*ge)+P[se+Pe]+re,re=Math.floor(ie/H),P[se+Pe]=ie-re*H;P[se+x]=re}return m(P),P}c.prototype.square=function(){return new c(O(this.value),!1)},u.prototype.square=function(){var v=this.value*this.value;return f(v)?new u(v):new c(O(p(Math.abs(this.value))),!1)},d.prototype.square=function(v){return new d(this.value*this.value)};function M(v,x){var P=v.length,H=x.length,ie=t,re=A(x.length),se=x[H-1],ce=Math.ceil(ie/(2*se)),ge=k(v,ce),Pe=k(x,ce),Je,dt,Zt,_n,ai,co,fl;for(ge.length<=P&&ge.push(0),Pe.push(0),se=Pe[H-1],dt=P-H;dt>=0;dt--){for(Je=ie-1,ge[dt+H]!==se&&(Je=Math.floor((ge[dt+H]*ie+ge[dt+H-1])/se)),Zt=0,_n=0,co=Pe.length,ai=0;ai<co;ai++)Zt+=Je*Pe[ai],fl=Math.floor(Zt/ie),_n+=ge[dt+ai]-(Zt-fl*ie),Zt=fl,_n<0?(ge[dt+ai]=_n+ie,_n=-1):(ge[dt+ai]=_n,_n=0);for(;_n!==0;){for(Je-=1,Zt=0,ai=0;ai<co;ai++)Zt+=ge[dt+ai]-ie+Pe[ai],Zt<0?(ge[dt+ai]=Zt+ie,Zt=0):(ge[dt+ai]=Zt,Zt=1);_n+=Zt}re[dt]=Je}return ge=B(ge,ce)[0],[h(re),h(ge)]}function W(v,x){for(var P=v.length,H=x.length,ie=[],re=[],se=t,ce,ge,Pe,Je,dt;P;){if(re.unshift(v[--P]),m(re),V(re,x)<0){ie.push(0);continue}ge=re.length,Pe=re[ge-1]*se+re[ge-2],Je=x[H-1]*se+x[H-2],ge>H&&(Pe=(Pe+1)*se),ce=Math.ceil(Pe/Je);do{if(dt=k(x,ce),V(dt,re)<=0)break;ce--}while(ce);ie.push(ce),re=C(re,dt)}return ie.reverse(),[h(ie),h(re)]}function B(v,x){var P=v.length,H=A(P),ie=t,re,se,ce,ge;for(ce=0,re=P-1;re>=0;--re)ge=ce*ie+v[re],se=g(ge/x),ce=ge-se*x,H[re]=se|0;return[H,ce|0]}function Y(v,x){var P,H=ae(x);if(s)return[new d(v.value/H.value),new d(v.value%H.value)];var ie=v.value,re=H.value,se;if(re===0)throw new Error("Cannot divide by zero");if(v.isSmall)return H.isSmall?[new u(g(ie/re)),new u(ie%re)]:[a[0],v];if(H.isSmall){if(re===1)return[v,a[0]];if(re==-1)return[v.negate(),a[0]];var ce=Math.abs(re);if(ce<t){P=B(ie,ce),se=h(P[0]);var ge=P[1];return v.sign&&(ge=-ge),typeof se=="number"?(v.sign!==H.sign&&(se=-se),[new u(se),new u(ge)]):[new c(se,v.sign!==H.sign),new u(ge)]}re=p(ce)}var Pe=V(ie,re);if(Pe===-1)return[a[0],v];if(Pe===0)return[a[v.sign===H.sign?1:-1],a[0]];ie.length+re.length<=200?P=M(ie,re):P=W(ie,re),se=P[0];var Je=v.sign!==H.sign,dt=P[1],Zt=v.sign;return typeof se=="number"?(Je&&(se=-se),se=new u(se)):se=new c(se,Je),typeof dt=="number"?(Zt&&(dt=-dt),dt=new u(dt)):dt=new c(dt,Zt),[se,dt]}c.prototype.divmod=function(v){var x=Y(this,v);return{quotient:x[0],remainder:x[1]}},d.prototype.divmod=u.prototype.divmod=c.prototype.divmod,c.prototype.divide=function(v){return Y(this,v)[0]},d.prototype.over=d.prototype.divide=function(v){return new d(this.value/ae(v).value)},u.prototype.over=u.prototype.divide=c.prototype.over=c.prototype.divide,c.prototype.mod=function(v){return Y(this,v)[1]},d.prototype.mod=d.prototype.remainder=function(v){return new d(this.value%ae(v).value)},u.prototype.remainder=u.prototype.mod=c.prototype.remainder=c.prototype.mod,c.prototype.pow=function(v){var x=ae(v),P=this.value,H=x.value,ie,re,se;if(H===0)return a[1];if(P===0)return a[0];if(P===1)return a[1];if(P===-1)return x.isEven()?a[1]:a[-1];if(x.sign)return a[0];if(!x.isSmall)throw new Error("The exponent "+x.toString()+" is too large.");if(this.isSmall&&f(ie=Math.pow(P,H)))return new u(g(ie));for(re=this,se=a[1];H&!0&&(se=se.times(re),--H),H!==0;)H/=2,re=re.square();return se},u.prototype.pow=c.prototype.pow,d.prototype.pow=function(v){var x=ae(v),P=this.value,H=x.value,ie=BigInt(0),re=BigInt(1),se=BigInt(2);if(H===ie)return a[1];if(P===ie)return a[0];if(P===re)return a[1];if(P===BigInt(-1))return x.isEven()?a[1]:a[-1];if(x.isNegative())return new d(ie);for(var ce=this,ge=a[1];(H&re)===re&&(ge=ge.times(ce),--H),H!==ie;)H/=se,ce=ce.square();return ge},c.prototype.modPow=function(v,x){if(v=ae(v),x=ae(x),x.isZero())throw new Error("Cannot take modPow with modulus 0");var P=a[1],H=this.mod(x);for(v.isNegative()&&(v=v.multiply(a[-1]),H=H.modInv(x));v.isPositive();){if(H.isZero())return a[0];v.isOdd()&&(P=P.multiply(H).mod(x)),v=v.divide(2),H=H.square().mod(x)}return P},d.prototype.modPow=u.prototype.modPow=c.prototype.modPow;function V(v,x){if(v.length!==x.length)return v.length>x.length?1:-1;for(var P=v.length-1;P>=0;P--)if(v[P]!==x[P])return v[P]>x[P]?1:-1;return 0}c.prototype.compareAbs=function(v){var x=ae(v),P=this.value,H=x.value;return x.isSmall?1:V(P,H)},u.prototype.compareAbs=function(v){var x=ae(v),P=Math.abs(this.value),H=x.value;return x.isSmall?(H=Math.abs(H),P===H?0:P>H?1:-1):-1},d.prototype.compareAbs=function(v){var x=this.value,P=ae(v).value;return x=x>=0?x:-x,P=P>=0?P:-P,x===P?0:x>P?1:-1},c.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),P=this.value,H=x.value;return this.sign!==x.sign?x.sign?1:-1:x.isSmall?this.sign?-1:1:V(P,H)*(this.sign?-1:1)},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=ae(v),P=this.value,H=x.value;return x.isSmall?P==H?0:P>H?1:-1:P<0!==x.sign?P<0?-1:1:P<0?1:-1},u.prototype.compareTo=u.prototype.compare,d.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var x=this.value,P=ae(v).value;return x===P?0:x>P?1:-1},d.prototype.compareTo=d.prototype.compare,c.prototype.equals=function(v){return this.compare(v)===0},d.prototype.eq=d.prototype.equals=u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals,c.prototype.notEquals=function(v){return this.compare(v)!==0},d.prototype.neq=d.prototype.notEquals=u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals,c.prototype.greater=function(v){return this.compare(v)>0},d.prototype.gt=d.prototype.greater=u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater,c.prototype.lesser=function(v){return this.compare(v)<0},d.prototype.lt=d.prototype.lesser=u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser,c.prototype.greaterOrEquals=function(v){return this.compare(v)>=0},d.prototype.geq=d.prototype.greaterOrEquals=u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals,c.prototype.lesserOrEquals=function(v){return this.compare(v)<=0},d.prototype.leq=d.prototype.lesserOrEquals=u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals,c.prototype.isEven=function(){return(this.value[0]&1)===0},u.prototype.isEven=function(){return(this.value&1)===0},d.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},c.prototype.isOdd=function(){return(this.value[0]&1)===1},u.prototype.isOdd=function(){return(this.value&1)===1},d.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},c.prototype.isPositive=function(){return!this.sign},u.prototype.isPositive=function(){return this.value>0},d.prototype.isPositive=u.prototype.isPositive,c.prototype.isNegative=function(){return this.sign},u.prototype.isNegative=function(){return this.value<0},d.prototype.isNegative=u.prototype.isNegative,c.prototype.isUnit=function(){return!1},u.prototype.isUnit=function(){return Math.abs(this.value)===1},d.prototype.isUnit=function(){return this.abs().value===BigInt(1)},c.prototype.isZero=function(){return!1},u.prototype.isZero=function(){return this.value===0},d.prototype.isZero=function(){return this.value===BigInt(0)},c.prototype.isDivisibleBy=function(v){var x=ae(v);return x.isZero()?!1:x.isUnit()?!0:x.compareAbs(2)===0?this.isEven():this.mod(x).isZero()},d.prototype.isDivisibleBy=u.prototype.isDivisibleBy=c.prototype.isDivisibleBy;function X(v){var x=v.abs();if(x.isUnit())return!1;if(x.equals(2)||x.equals(3)||x.equals(5))return!0;if(x.isEven()||x.isDivisibleBy(3)||x.isDivisibleBy(5))return!1;if(x.lesser(49))return!0}function oe(v,x){for(var P=v.prev(),H=P,ie=0,re,se,ce,ge;H.isEven();)H=H.divide(2),ie++;e:for(ce=0;ce<x.length;ce++)if(!v.lesser(x[ce])&&(ge=Io(x[ce]).modPow(H,v),!(ge.isUnit()||ge.equals(P)))){for(re=ie-1;re!=0;re--){if(ge=ge.square().mod(v),ge.isUnit())return!1;if(ge.equals(P))continue e}return!1}return!0}c.prototype.isPrime=function(v){var x=X(this);if(x!==e)return x;var P=this.abs(),H=P.bitLength();if(H<=64)return oe(P,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var ie=Math.log(2)*H.toJSNumber(),re=Math.ceil(v===!0?2*Math.pow(ie,2):ie),se=[],ce=0;ce<re;ce++)se.push(Io(ce+2));return oe(P,se)},d.prototype.isPrime=u.prototype.isPrime=c.prototype.isPrime,c.prototype.isProbablePrime=function(v,x){var P=X(this);if(P!==e)return P;for(var H=this.abs(),ie=v===e?5:v,re=[],se=0;se<ie;se++)re.push(Io.randBetween(2,H.minus(2),x));return oe(H,re)},d.prototype.isProbablePrime=u.prototype.isProbablePrime=c.prototype.isProbablePrime,c.prototype.modInv=function(v){for(var x=Io.zero,P=Io.one,H=ae(v),ie=this.abs(),re,se,ce;!ie.isZero();)re=H.divide(ie),se=x,ce=H,x=P,H=ie,P=se.subtract(re.multiply(P)),ie=ce.subtract(re.multiply(ie));if(!H.isUnit())throw new Error(this.toString()+" and "+v.toString()+" are not co-prime");return x.compare(0)===-1&&(x=x.add(v)),this.isNegative()?x.negate():x},d.prototype.modInv=u.prototype.modInv=c.prototype.modInv,c.prototype.next=function(){var v=this.value;return this.sign?T(v,1,this.sign):new c(E(v,1),this.sign)},u.prototype.next=function(){var v=this.value;return v+1<n?new u(v+1):new c(i,!1)},d.prototype.next=function(){return new d(this.value+BigInt(1))},c.prototype.prev=function(){var v=this.value;return this.sign?new c(E(v,1),!0):T(v,1,this.sign)},u.prototype.prev=function(){var v=this.value;return v-1>-n?new u(v-1):new c(i,!0)},d.prototype.prev=function(){return new d(this.value-BigInt(1))};for(var Ee=[1];2*Ee[Ee.length-1]<=t;)Ee.push(2*Ee[Ee.length-1]);var ke=Ee.length,ve=Ee[ke-1];function yt(v){return Math.abs(v)<=t}c.prototype.shiftLeft=function(v){var x=ae(v).toJSNumber();if(!yt(x))throw new Error(String(x)+" is too large for shifting.");if(x<0)return this.shiftRight(-x);var P=this;if(P.isZero())return P;for(;x>=ke;)P=P.multiply(ve),x-=ke-1;return P.multiply(Ee[x])},d.prototype.shiftLeft=u.prototype.shiftLeft=c.prototype.shiftLeft,c.prototype.shiftRight=function(v){var x,P=ae(v).toJSNumber();if(!yt(P))throw new Error(String(P)+" is too large for shifting.");if(P<0)return this.shiftLeft(-P);for(var H=this;P>=ke;){if(H.isZero()||H.isNegative()&&H.isUnit())return H;x=Y(H,ve),H=x[1].isNegative()?x[0].prev():x[0],P-=ke-1}return x=Y(H,Ee[P]),x[1].isNegative()?x[0].prev():x[0]},d.prototype.shiftRight=u.prototype.shiftRight=c.prototype.shiftRight;function Ne(v,x,P){x=ae(x);for(var H=v.isNegative(),ie=x.isNegative(),re=H?v.not():v,se=ie?x.not():x,ce=0,ge=0,Pe=null,Je=null,dt=[];!re.isZero()||!se.isZero();)Pe=Y(re,ve),ce=Pe[1].toJSNumber(),H&&(ce=ve-1-ce),Je=Y(se,ve),ge=Je[1].toJSNumber(),ie&&(ge=ve-1-ge),re=Pe[0],se=Je[0],dt.push(P(ce,ge));for(var Zt=P(H?1:0,ie?1:0)!==0?Io(-1):Io(0),_n=dt.length-1;_n>=0;_n-=1)Zt=Zt.multiply(ve).add(Io(dt[_n]));return Zt}c.prototype.not=function(){return this.negate().prev()},d.prototype.not=u.prototype.not=c.prototype.not,c.prototype.and=function(v){return Ne(this,v,function(x,P){return x&P})},d.prototype.and=u.prototype.and=c.prototype.and,c.prototype.or=function(v){return Ne(this,v,function(x,P){return x|P})},d.prototype.or=u.prototype.or=c.prototype.or,c.prototype.xor=function(v){return Ne(this,v,function(x,P){return x^P})},d.prototype.xor=u.prototype.xor=c.prototype.xor;var Ue=1<<30,Ae=(t&-t)*(t&-t)|Ue;function le(v){var x=v.value,P=typeof x=="number"?x|Ue:typeof x=="bigint"?x|BigInt(Ue):x[0]+x[1]*t|Ae;return P&-P}function we(v,x){if(x.compareTo(v)<=0){var P=we(v,x.square(x)),H=P.p,ie=P.e,re=H.multiply(x);return re.compareTo(v)<=0?{p:re,e:ie*2+1}:{p:H,e:ie*2}}return{p:Io(1),e:0}}c.prototype.bitLength=function(){var v=this;return v.compareTo(Io(0))<0&&(v=v.negate().subtract(Io(1))),v.compareTo(Io(0))===0?Io(0):Io(we(v,Io(2)).e).add(Io(1))},d.prototype.bitLength=u.prototype.bitLength=c.prototype.bitLength;function Le(v,x){return v=ae(v),x=ae(x),v.greater(x)?v:x}function ze(v,x){return v=ae(v),x=ae(x),v.lesser(x)?v:x}function Yt(v,x){if(v=ae(v).abs(),x=ae(x).abs(),v.equals(x))return v;if(v.isZero())return x;if(x.isZero())return v;for(var P=a[1],H,ie;v.isEven()&&x.isEven();)H=ze(le(v),le(x)),v=v.divide(H),x=x.divide(H),P=P.multiply(H);for(;v.isEven();)v=v.divide(le(v));do{for(;x.isEven();)x=x.divide(le(x));v.greater(x)&&(ie=x,x=v,v=ie),x=x.subtract(v)}while(!x.isZero());return P.isUnit()?v:v.multiply(P)}function Mt(v,x){return v=ae(v).abs(),x=ae(x).abs(),v.divide(Yt(v,x)).multiply(x)}function pr(v,x,P){v=ae(v),x=ae(x);var H=P||Math.random,ie=ze(v,x),re=Le(v,x),se=re.subtract(ie).add(1);if(se.isSmall)return ie.add(Math.floor(H()*se));for(var ce=$e(se,t).value,ge=[],Pe=!0,Je=0;Je<ce.length;Je++){var dt=Pe?ce[Je]+(Je+1<ce.length?ce[Je+1]/t:0):t,Zt=g(H()*dt);ge.push(Zt),Zt<ce[Je]&&(Pe=!1)}return ie.add(a.fromArray(ge,t,!1))}var Ve=function(v,x,P,H){P=P||o,v=String(v),H||(v=v.toLowerCase(),P=P.toLowerCase());var ie=v.length,re,se=Math.abs(x),ce={};for(re=0;re<P.length;re++)ce[P[re]]=re;for(re=0;re<ie;re++){var ge=v[re];if(ge!=="-"&&ge in ce&&ce[ge]>=se){if(ge==="1"&&se===1)continue;throw new Error(ge+" is not a valid digit in base "+x+".")}}x=ae(x);var Pe=[],Je=v[0]==="-";for(re=Je?1:0;re<v.length;re++){var ge=v[re];if(ge in ce)Pe.push(ae(ce[ge]));else if(ge==="<"){var dt=re;do re++;while(v[re]!==">"&&re<v.length);Pe.push(ae(v.slice(dt+1,re)))}else throw new Error(ge+" is not a valid character")}return je(Pe,x,Je)};function je(v,x,P){var H=a[0],ie=a[1],re;for(re=v.length-1;re>=0;re--)H=H.add(v[re].times(ie)),ie=ie.times(x);return P?H.negate():H}function wt(v,x){return x=x||o,v<x.length?x[v]:"<"+v+">"}function $e(v,x){if(x=Io(x),x.isZero()){if(v.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(x.equals(-1)){if(v.isZero())return{value:[0],isNegative:!1};if(v.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-v.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var P=Array.apply(null,Array(v.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return P.unshift([1]),{value:[].concat.apply([],P),isNegative:!1}}var H=!1;if(v.isNegative()&&x.isPositive()&&(H=!0,v=v.abs()),x.isUnit())return v.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(v.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:H};for(var ie=[],re=v,se;re.isNegative()||re.compareAbs(x)>=0;){se=re.divmod(x),re=se.quotient;var ce=se.remainder;ce.isNegative()&&(ce=x.minus(ce).abs(),re=re.next()),ie.push(ce.toJSNumber())}return ie.push(re.toJSNumber()),{value:ie.reverse(),isNegative:H}}function Xe(v,x,P){var H=$e(v,x);return(H.isNegative?"-":"")+H.value.map(function(ie){return wt(ie,P)}).join("")}c.prototype.toArray=function(v){return $e(this,v)},u.prototype.toArray=function(v){return $e(this,v)},d.prototype.toArray=function(v){return $e(this,v)},c.prototype.toString=function(v,x){if(v===e&&(v=10),v!==10||x)return Xe(this,v,x);for(var P=this.value,H=P.length,ie=String(P[--H]),re="0000000",se;--H>=0;)se=String(P[H]),ie+=re.slice(se.length)+se;var ce=this.sign?"-":"";return ce+ie},u.prototype.toString=function(v,x){return v===e&&(v=10),v!=10||x?Xe(this,v,x):String(this.value)},d.prototype.toString=u.prototype.toString,d.prototype.toJSON=c.prototype.toJSON=u.prototype.toJSON=function(){return this.toString()},c.prototype.valueOf=function(){return parseInt(this.toString(),10)},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=function(){return this.value},u.prototype.toJSNumber=u.prototype.valueOf,d.prototype.valueOf=d.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};function rt(v){if(f(+v)){var x=+v;if(x===g(x))return s?new d(BigInt(x)):new u(x);throw new Error("Invalid integer: "+v)}var P=v[0]==="-";P&&(v=v.slice(1));var H=v.split(/e/i);if(H.length>2)throw new Error("Invalid integer: "+H.join("e"));if(H.length===2){var ie=H[1];if(ie[0]==="+"&&(ie=ie.slice(1)),ie=+ie,ie!==g(ie)||!f(ie))throw new Error("Invalid integer: "+ie+" is not a valid exponent.");var re=H[0],se=re.indexOf(".");if(se>=0&&(ie-=re.length-se-1,re=re.slice(0,se)+re.slice(se+1)),ie<0)throw new Error("Cannot include negative exponent part for integers");re+=new Array(ie+1).join("0"),v=re}var ce=/^([0-9][0-9]*)$/.test(v);if(!ce)throw new Error("Invalid integer: "+v);if(s)return new d(BigInt(P?"-"+v:v));for(var ge=[],Pe=v.length,Je=r,dt=Pe-Je;Pe>0;)ge.push(+v.slice(dt,Pe)),dt-=Je,dt<0&&(dt=0),Pe-=Je;return m(ge),new c(ge,P)}function Ze(v){if(s)return new d(BigInt(v));if(f(v)){if(v!==g(v))throw new Error(v+" is not an integer.");return new u(v)}return rt(v.toString())}function ae(v){return typeof v=="number"?Ze(v):typeof v=="string"?rt(v):typeof v=="bigint"?new d(v):v}for(var ee=0;ee<1e3;ee++)a[ee]=ae(ee),ee>0&&(a[-ee]=ae(-ee));return a.one=a[1],a.zero=a[0],a.minusOne=a[-1],a.max=Le,a.min=ze,a.gcd=Yt,a.lcm=Mt,a.isInstance=function(v){return v instanceof c||v instanceof u||v instanceof d},a.randBetween=pr,a.fromArray=function(v,x,P){return je(v.map(ae),ae(x||10),P)},a})();typeof MG<"u"&&MG.hasOwnProperty("exports")&&(MG.exports=Io);typeof define=="function"&&define.amd&&define(function(){return Io})});var Aot=I((Drn,mot)=>{var Xm=pot(),UG=z("stream");(!UG.Writable||!UG.Writable.prototype.destroy)&&(UG=Ia());var $G;function LCr(){var e=3988292384,t,r,n;for($G=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=t&1?e^t>>>1:t=t>>>1;$G[r]=t>>>0}}function hot(e,t){return $G||LCr(),e.charCodeAt&&(e=e.charCodeAt(0)),Xm(t).shiftRight(8).and(16777215).xor($G[Xm(t).xor(e).and(255)]).value}function zw(){if(!(this instanceof zw))return new zw;this.key0=305419896,this.key1=591751049,this.key2=878082192}zw.prototype.update=function(e){this.key0=hot(e,this.key0),this.key1=Xm(this.key0).and(255).and(4294967295).add(this.key1),this.key1=Xm(this.key1).multiply(134775813).add(1).and(4294967295).value,this.key2=hot(Xm(this.key1).shiftRight(24).and(255),this.key2)};zw.prototype.decryptByte=function(e){var t=Xm(this.key2).or(2);return e=e^Xm(t).multiply(Xm(t^1)).shiftRight(8).and(255),this.update(e),e};zw.prototype.stream=function(){var e=UG.Transform(),t=this;return e._transform=function(r,n,i){for(var o=0;o<r.length;o++)r[o]=t.decryptByte(r[o]);this.push(r),i()},e};mot.exports=zw});var yot=I((Rrn,got)=>{var QCr=Jm(),PCr=Aot(),MCr=vG(),LB=z("stream"),UCr=CB(),$Cr=z("zlib"),qCr=RG(),jCr=Uw(),YCr=TG();(!LB.Writable||!LB.Writable.prototype.destroy)&&(LB=Ia());got.exports=function(t,r,n,i){var o=MCr(),s=LB.PassThrough(),a=t.stream(r);return a.pipe(o).on("error",function(c){s.emit("error",c)}),s.vars=o.pull(30).then(function(c){var u=UCr.parse(c).word32lu("signature").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").vars;return u.lastModifiedDateTime=YCr(u.lastModifiedDate,u.lastModifiedTime),o.pull(u.fileNameLength).then(function(d){return u.fileName=d.toString("utf8"),o.pull(u.extraFieldLength)}).then(function(d){var f;return u.extra=qCr(d,u),i&&i.compressedSize&&(u=i),u.flags&1&&(f=o.pull(12).then(function(p){if(!n)throw new Error("MISSING_PASSWORD");var h=PCr();String(n).split("").forEach(function(g){h.update(g)});for(var m=0;m<p.length;m++)p[m]=h.decryptByte(p[m]);u.decrypt=h,u.compressedSize-=12;var A=u.flags&8?u.lastModifiedTime>>8&255:u.crc32>>24&255;if(p[11]!==A)throw new Error("BAD_PASSWORD");return u})),QCr.resolve(f).then(function(){return s.emit("vars",u),u})})}),s.vars.then(function(c){var u=!(c.flags&8)||c.compressedSize>0,d,f=c.compressionMethod?$Cr.createInflateRaw():LB.PassThrough();u?(s.size=c.uncompressedSize,d=c.compressedSize):(d=jCr.alloc(4),d.writeUInt32LE(134695760,0));var p=o.stream(d);c.decrypt&&(p=p.pipe(c.decrypt.stream())),p.pipe(f).on("error",function(h){s.emit("error",h)}).pipe(s).on("finish",function(){a.destroy?a.destroy():a.abort?a.abort():a.close?a.close():a.push?a.push():console.log("warning - unable to close stream")})}).catch(function(c){s.emit("error",c)}),s}});var Iot=I((Trn,bot)=>{var MB=CB(),PB=vG(),HCr=yot(),QB=Jm(),zCr=DG(),JCr=RG(),GCr=Uw(),vme=z("path"),VCr=_me().Writer,WCr=TG(),Eot=GCr.alloc(4);Eot.writeUInt32LE(101010256,0);function KCr(e){var t=e.stream(0).pipe(PB());return t.pull(4).then(function(r){var n=r.readUInt32LE(0);if(n===875721283){var i;return t.pull(12).then(function(o){i=MB.parse(o).word32lu("version").word32lu("pubKeyLength").word32lu("signatureLength").vars}).then(function(){return t.pull(i.pubKeyLength+i.signatureLength)}).then(function(o){return i.publicKey=o.slice(0,i.pubKeyLength),i.signature=o.slice(i.pubKeyLength),i.size=16+i.pubKeyLength+i.signatureLength,i})}})}function XCr(e,t){var r=MB.parse(t).word32lu("signature").word32lu("diskNumber").word64lu("offsetToStartOfCentralDirectory").word32lu("numberOfDisks").vars;if(r.signature!=117853008)throw new Error("invalid zip64 end of central dir locator signature (0x07064b50): 0x"+r.signature.toString(16));var n=PB();return e.stream(r.offsetToStartOfCentralDirectory).pipe(n),n.pull(56)}function ZCr(e){var t=MB.parse(e).word32lu("signature").word64lu("sizeOfCentralDirectory").word16lu("version").word16lu("versionsNeededToExtract").word32lu("diskNumber").word32lu("diskStart").word64lu("numberOfRecordsOnDisk").word64lu("numberOfRecords").word64lu("sizeOfCentralDirectory").word64lu("offsetToStartOfCentralDirectory").vars;if(t.signature!=101075792)throw new Error("invalid zip64 end of central dir locator signature (0x06064b50): 0x0"+t.signature.toString(16));return t}bot.exports=function(t,r){var n=PB(),i=PB(),o=r&&r.tailSize||80,s,a,c,u;return r&&r.crx&&(a=KCr(t)),t.size().then(function(d){return s=d,t.stream(Math.max(0,d-o)).on("error",function(f){n.emit("error",f)}).pipe(n),n.pull(Eot)}).then(function(){return QB.props({directory:n.pull(22),crxHeader:a})}).then(function(d){var f=d.directory;if(c=d.crxHeader&&d.crxHeader.size||0,u=MB.parse(f).word32lu("signature").word16lu("diskNumber").word16lu("diskStart").word16lu("numberOfRecordsOnDisk").word16lu("numberOfRecords").word32lu("sizeOfCentralDirectory").word32lu("offsetToStartOfCentralDirectory").word16lu("commentLength").vars,u.numberOfRecords==65535||u.numberOfRecords==65535||u.offsetToStartOfCentralDirectory==4294967295){let h=s-(o-n.match+20),m=PB();return t.stream(h).pipe(m),m.pull(20).then(function(A){return XCr(t,A)}).then(function(A){u=ZCr(A)})}else u.offsetToStartOfCentralDirectory+=c}).then(function(){if(u.commentLength)return n.pull(u.commentLength).then(function(d){u.comment=d.toString("utf8")})}).then(function(){return t.stream(u.offsetToStartOfCentralDirectory).pipe(i),u.extract=function(d){if(!d||!d.path)throw new Error("PATH_MISSING");return d.path=vme.resolve(vme.normalize(d.path)),u.files.then(function(f){return QB.map(f,function(p){if(p.type!="Directory"){var h=vme.join(d.path,p.path);if(h.indexOf(d.path)==0){var m=d.getWriter?d.getWriter({path:h}):VCr({path:h});return new QB(function(A,g){p.stream(d.password).on("error",g).pipe(m).on("close",A).on("error",g)})}}},{concurrency:d.concurrency>1?d.concurrency:1})})},u.files=QB.mapSeries(Array(u.numberOfRecords),function(){return i.pull(46).then(function(d){var f=MB.parse(d).word32lu("signature").word16lu("versionMadeBy").word16lu("versionsNeededToExtract").word16lu("flags").word16lu("compressionMethod").word16lu("lastModifiedTime").word16lu("lastModifiedDate").word32lu("crc32").word32lu("compressedSize").word32lu("uncompressedSize").word16lu("fileNameLength").word16lu("extraFieldLength").word16lu("fileCommentLength").word16lu("diskNumber").word16lu("internalFileAttributes").word32lu("externalFileAttributes").word32lu("offsetToLocalFileHeader").vars;return f.offsetToLocalFileHeader+=c,f.lastModifiedDateTime=WCr(f.lastModifiedDate,f.lastModifiedTime),i.pull(f.fileNameLength).then(function(p){return f.pathBuffer=p,f.path=p.toString("utf8"),f.isUnicode=(f.flags&2048)!=0,i.pull(f.extraFieldLength)}).then(function(p){return f.extra=JCr(p,f),i.pull(f.fileCommentLength)}).then(function(p){return f.comment=p,f.type=f.uncompressedSize===0&&/[\/\\]$/.test(f.path)?"Directory":"File",f.stream=function(h){return HCr(t,f.offsetToLocalFileHeader,h,f)},f.buffer=function(h){return zCr(f.stream(h))},f})})}),QB.props(u)})}});var wot=I((xrn,_ot)=>{var Cot=Da(),qG=Jm(),UB=Iot(),jG=z("stream");(!jG.Writable||!jG.Writable.prototype.destroy)&&(jG=Ia());_ot.exports={buffer:function(e,t){var r={stream:function(n,i){var o=jG.PassThrough();return o.end(e.slice(n,i)),o},size:function(){return qG.resolve(e.length)}};return UB(r,t)},file:function(e,t){var r={stream:function(n,i){return Cot.createReadStream(e,{start:n,end:i&&n+i})},size:function(){return new qG(function(n,i){Cot.stat(e,function(o,s){o?i(o):n(s.size)})})}};return UB(r,t)},url:function(e,t,r){if(typeof t=="string"&&(t={url:t}),!t.url)throw"URL missing";t.headers=t.headers||{};var n={stream:function(i,o){var s=Object.create(t);return s.headers=Object.create(t.headers),s.headers.range="bytes="+i+"-"+(o||""),e(s)},size:function(){return new qG(function(i,o){var s=e(t);s.on("response",function(a){s.abort(),a.headers["content-length"]?i(a.headers["content-length"]):o(new Error("Missing content length header"))}).on("error",o)})}};return UB(n,r)},s3:function(e,t,r){var n={size:function(){return new qG(function(i,o){e.headObject(t,function(s,a){s?o(s):i(a.ContentLength)})})},stream:function(i,o){var s={};for(var a in t)s[a]=t[a];return s.Range="bytes="+i+"-"+(o||""),e.getObject(s).createReadStream()}};return UB(n,r)},custom:function(e,t){return UB(e,t)}}});var vot=I($B=>{"use strict";srt();urt();Aie();$B.Parse=xG();$B.ParseOne=mit();$B.Extract=fot();$B.Open=wot()});var jot=I((Nrn,op)=>{var An=z("fs"),HG=z("os"),Co=z("path"),Sot=z("crypto"),md={fs:An.constants,os:HG.constants},Dot="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",kot=/XXXXXX/,e_r=3,Not=(md.O_CREAT||md.fs.O_CREAT)|(md.O_EXCL||md.fs.O_EXCL)|(md.O_RDWR||md.fs.O_RDWR),t_r=HG.platform()==="win32",r_r=md.EBADF||md.os.errno.EBADF,n_r=md.ENOENT||md.os.errno.ENOENT,Bot=448,Oot=384,i_r="exit",Jw=[],Fot=An.rmdirSync.bind(An),Lot=!1;function o_r(e,t){return An.rm(e,{recursive:!0},t)}function Qot(e){return An.rmSync(e,{recursive:!0})}function Tme(e,t){let r=Gw(e,t),n=r[0],i=r[1];m_r(n,function(o,s){if(o)return i(o);let a=s.tries;(function c(){try{let u=Mot(s);An.stat(u,function(d){if(!d)return a-- >0?c():i(new Error("Could not get a unique tmp filename, max tries reached "+u));i(null,u)})}catch(u){i(u)}})()})}function xme(e){let t=Gw(e),r=t[0],n=A_r(r),i=n.tries;do{let o=Mot(n);try{An.statSync(o)}catch{return o}}while(i-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function s_r(e,t){let r=Gw(e,t),n=r[0],i=r[1];Tme(n,function(s,a){if(s)return i(s);An.open(a,Not,n.mode||Oot,function(u,d){if(u)return i(u);if(n.discardDescriptor)return An.close(d,function(p){return i(p,a,void 0,Dme(a,-1,n,!1))});{let f=n.discardDescriptor||n.detachDescriptor;i(null,a,d,Dme(a,f?-1:d,n,!1))}})})}function a_r(e){let t=Gw(e),r=t[0],n=r.discardDescriptor||r.detachDescriptor,i=xme(r),o=An.openSync(i,Not,r.mode||Oot);return r.discardDescriptor&&(An.closeSync(o),o=void 0),{name:i,fd:o,removeCallback:Dme(i,n?-1:o,r,!0)}}function c_r(e,t){let r=Gw(e,t),n=r[0],i=r[1];Tme(n,function(s,a){if(s)return i(s);An.mkdir(a,n.mode||Bot,function(u){if(u)return i(u);i(null,a,Pot(a,n,!1))})})}function l_r(e){let t=Gw(e),r=t[0],n=xme(r);return An.mkdirSync(n,r.mode||Bot),{name:n,removeCallback:Pot(n,r,!0)}}function u_r(e,t){let r=function(n){if(n&&!Rme(n))return t(n);t()};0<=e[0]?An.close(e[0],function(){An.unlink(e[1],r)}):An.unlink(e[1],r)}function d_r(e){let t=null;try{0<=e[0]&&An.closeSync(e[0])}catch(r){if(!g_r(r)&&!Rme(r))throw r}finally{try{An.unlinkSync(e[1])}catch(r){Rme(r)||(t=r)}}if(t!==null)throw t}function Dme(e,t,r,n){let i=YG(d_r,[t,e],n),o=YG(u_r,[t,e],n,i);return r.keep||Jw.unshift(i),n?i:o}function Pot(e,t,r){let n=t.unsafeCleanup?o_r:An.rmdir.bind(An),i=t.unsafeCleanup?Qot:Fot,o=YG(i,e,r),s=YG(n,e,r,o);return t.keep||Jw.unshift(o),r?o:s}function YG(e,t,r,n){let i=!1;return function o(s){if(!i){let a=n||o,c=Jw.indexOf(a);return c>=0&&Jw.splice(c,1),i=!0,r||e===Fot||e===Qot?e(t):e(t,s||function(){})}}}function f_r(){if(Lot)for(;Jw.length;)try{Jw[0]()}catch{}}function Rot(e){let t=[],r=null;try{r=Sot.randomBytes(e)}catch{r=Sot.pseudoRandomBytes(e)}for(let n=0;n<e;n++)t.push(Dot[r[n]%Dot.length]);return t.join("")}function Ra(e){return typeof e>"u"}function Gw(e,t){if(typeof e=="function")return[{},e];if(Ra(e))return[{},t];let r={};for(let n of Object.getOwnPropertyNames(e))r[n]=e[n];return[r,t]}function p_r(e,t,r){let n=Co.isAbsolute(e)?e:Co.join(t,e);An.stat(n,function(i){i?An.realpath(Co.dirname(n),function(o,s){if(o)return r(o);r(null,Co.join(s,Co.basename(n)))}):An.realpath(n,r)})}function h_r(e,t){let r=Co.isAbsolute(e)?e:Co.join(t,e);try{return An.statSync(r),An.realpathSync(r)}catch{let i=An.realpathSync(Co.dirname(r));return Co.join(i,Co.basename(r))}}function Mot(e){let t=e.tmpdir;if(!Ra(e.name))return Co.join(t,e.dir,e.name);if(!Ra(e.template))return Co.join(t,e.dir,e.template).replace(kot,Rot(6));let r=[e.prefix?e.prefix:"tmp","-",process.pid,"-",Rot(12),e.postfix?"-"+e.postfix:""].join("");return Co.join(t,e.dir,r)}function Sme(e,t){if(typeof t!="string")throw new Error(`${e} option must be a string, got "${typeof t}".`);if(t.includes(".."))throw new Error("Relative value not allowed");return t}function Uot(e){if(!Ra(e.name)){let t=e.name;if(Co.isAbsolute(t))throw new Error(`name option must not contain an absolute path, found "${t}".`);let r=Co.basename(t);if(r===".."||r==="."||r!==t)throw new Error(`name option must not contain a path, found "${t}".`)}if(!Ra(e.template)){if(typeof e.template!="string")throw new Error(`template option must be a string, got "${typeof e.template}".`);if(!e.template.match(kot))throw new Error(`Invalid template, found "${e.template}".`)}if(!Ra(e.tries)&&isNaN(e.tries)||e.tries<0)throw new Error(`Invalid tries, found "${e.tries}".`);e.tries=Ra(e.name)?e.tries||e_r:1,e.keep=!!e.keep,e.detachDescriptor=!!e.detachDescriptor,e.discardDescriptor=!!e.discardDescriptor,e.unsafeCleanup=!!e.unsafeCleanup,e.prefix=Ra(e.prefix)?"":Sme("prefix",e.prefix),e.postfix=Ra(e.postfix)?"":Sme("postfix",e.postfix),e.template=Ra(e.template)?void 0:Sme("template",e.template)}function Tot(e,t,r,n){if(Ra(t))return n(null);p_r(t,r,function(i,o){if(i)return n(i);let s=Co.relative(r,o);if(s.startsWith("..")||Co.isAbsolute(s))return n(new Error(`${e} option must be relative to "${r}", found "${s}".`));n(null,s)})}function xot(e,t,r){if(Ra(t))return;let n=h_r(t,r),i=Co.relative(r,n);if(i.startsWith("..")||Co.isAbsolute(i))throw new Error(`${e} option must be relative to "${r}", found "${i}".`);return i}function m_r(e,t){E_r(e,function(r,n){if(r)return t(r);e.tmpdir=n;try{Uot(e,n)}catch(i){return t(i)}Tot("dir",e.dir,n,function(i,o){if(i)return t(i);e.dir=Ra(o)?"":o,Tot("template",e.template,n,function(s,a){if(s)return t(s);e.template=a,t(null,e)})})})}function A_r(e){let t=e.tmpdir=qot(e);Uot(e,t);let r=xot("dir",e.dir,t);return e.dir=Ra(r)?"":r,e.template=xot("template",e.template,t),e}function g_r(e){return $ot(e,-r_r,"EBADF")}function Rme(e){return $ot(e,-n_r,"ENOENT")}function $ot(e,t,r){return t_r?e.code===r:e.code===r&&e.errno===t}function y_r(){Lot=!0}function E_r(e,t){return An.realpath(e&&e.tmpdir||HG.tmpdir(),t)}function qot(e){return An.realpathSync(e&&e.tmpdir||HG.tmpdir())}process.addListener(i_r,f_r);Object.defineProperty(op.exports,"tmpdir",{enumerable:!0,configurable:!1,get:function(){return qot()}});op.exports.dir=c_r;op.exports.dirSync=l_r;op.exports.file=s_r;op.exports.fileSync=a_r;op.exports.tmpName=Tme;op.exports.tmpNameSync=xme;op.exports.setGracefulCleanup=y_r});var Hot=I((Brn,Yot)=>{Yot.exports=async function*(t){let r=[];t.on("data",a=>r.push(a));let n,i=new Promise(a=>n=a),o=!1;t.on("end",()=>{o=!0,n()});let s=!1;for(t.on("error",a=>{s=a,n()});!o||r.length>0;)if(r.length===0?(t.resume(),await Promise.race([b_r(t,"data"),i])):(t.pause(),yield r.shift()),s)throw s;n()};function b_r(e,t){return new Promise(r=>{let n=!1,i=()=>{n||(n=!0,e.removeListener(t,i),r())};e.addListener(t,i)})}});var Vot=I((Orn,Got)=>{var{EventEmitter:I_r}=z("events"),C_r=Xk(),__r=Ri(),zG=Ts(),zot=pi(),w_r=kf(),v_r=wj(),Jot=vj(),kme=class extends I_r{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i||{},this.name=`Sheet${this.id}`,this._columns=null,this._keys={},this._dimensions=new w_r}destroy(){throw new Error("Invalid Operation: destroy")}get dimensions(){return this._dimensions}get columns(){return this._columns}getColumn(t){if(typeof t=="string"){let r=this._keys[t];if(r)return r;t=zot.l2n(t)}if(this._columns||(this._columns=[]),t>this._columns.length){let r=this._columns.length+1;for(;r<=t;)this._columns.push(new Jot(this,r++))}return this._columns[t-1]}getColumnKey(t){return this._keys[t]}setColumnKey(t,r){this._keys[t]=r}deleteColumnKey(t){delete this._keys[t]}eachColumnKey(t){__r.each(this._keys,t)}async read(){try{for await(let t of this.parse())for(let{eventType:r,value:n}of t)this.emit(r,n);this.emit("finished")}catch(t){this.emit("error",t)}}async*[Symbol.asyncIterator](){for await(let t of this.parse())for(let{eventType:r,value:n}of t)r==="row"&&(yield n)}async*parse(){let{iterator:t,options:r}=this,n=!1,i=!1,o=null;switch(r.worksheets){case"emit":n=!0;break;case"prep":break;default:break}switch(r.hyperlinks){case"emit":i=!0;break;case"cache":this.hyperlinks=o={};break;default:break}if(!n&&!i&&!o)return;let{sharedStrings:s,styles:a,properties:c}=this.workbook,u=!1,d=!1,f=!1,p=null,h=null,m=null,A=null;for await(let g of C_r(t)){let y=[];for(let{eventType:b,value:E}of g)if(b==="opentag"){let C=E;if(n)switch(C.name){case"cols":u=!0,p=[];break;case"sheetData":d=!0;break;case"col":u&&p.push({min:parseInt(C.attributes.min,10),max:parseInt(C.attributes.max,10),width:parseFloat(C.attributes.width),styleId:parseInt(C.attributes.style||"0",10)});break;case"row":if(d){let w=parseInt(C.attributes.r,10);if(h=new v_r(this,w),C.attributes.ht&&(h.height=parseFloat(C.attributes.ht)),C.attributes.s){let T=parseInt(C.attributes.s,10),D=a.getStyleModel(T);D&&(h.style=D)}}break;case"c":h&&(m={ref:C.attributes.r,s:parseInt(C.attributes.s,10),t:C.attributes.t});break;case"f":m&&(A=m.f={text:""});break;case"v":m&&(A=m.v={text:""});break;case"is":case"t":m&&(A=m.v={text:""});break;case"mergeCell":break;default:break}if(i||o)switch(C.name){case"hyperlinks":f=!0;break;case"hyperlink":if(f){let w={ref:C.attributes.ref,rId:C.attributes["r:id"]};i?y.push({eventType:"hyperlink",value:w}):o[w.ref]=w}break;default:break}}else if(b==="text")n&&A&&(A.text+=E);else if(b==="closetag"){let C=E;if(n)switch(C.name){case"cols":u=!1,this._columns=Jot.fromModel(p);break;case"sheetData":d=!1;break;case"row":this._dimensions.expandRow(h),y.push({eventType:"row",value:h}),h=null;break;case"c":if(h&&m){let w=zot.decodeAddress(m.ref),T=h.getCell(w.col);if(m.s){let D=a.getStyleModel(m.s);D&&(T.style=D)}if(m.f){let D={formula:m.f.text};m.v&&(m.t==="str"?D.result=zG.xmlDecode(m.v.text):D.result=parseFloat(m.v.text)),T.value=D}else if(m.v)switch(m.t){case"s":{let D=parseInt(m.v.text,10);s?T.value=s[D]:T.value={sharedString:D};break}case"inlineStr":case"str":T.value=zG.xmlDecode(m.v.text);break;case"e":T.value={error:m.v.text};break;case"b":T.value=parseInt(m.v.text,10)!==0;break;default:zG.isDateFmt(T.numFmt)?T.value=zG.excelToDate(parseFloat(m.v.text),c.model&&c.model.date1904):T.value=parseFloat(m.v.text);break}if(o){let D=o[m.ref];D&&(T.text=T.value,T.value=void 0,T.hyperlink=D)}m=null}break;default:break}(i||o)&&C.name==="hyperlinks"&&(f=!1)}y.length>0&&(yield y)}}};Got.exports=kme});var Kot=I((Frn,Wot)=>{var{EventEmitter:S_r}=z("events"),D_r=Xk(),R_r=zl(),T_r=Kh(),Nme=class extends S_r{constructor({workbook:t,id:r,iterator:n,options:i}){super(),this.workbook=t,this.id=r,this.iterator=n,this.options=i}get count(){return this.hyperlinks&&this.hyperlinks.length||0}each(t){return this.hyperlinks.forEach(t)}async read(){let{iterator:t,options:r}=this,n=!1,i=null;switch(r.hyperlinks){case"emit":n=!0;break;case"cache":this.hyperlinks=i={};break;default:break}if(!n&&!i){this.emit("finished");return}try{for await(let o of D_r(t))for(let{eventType:s,value:a}of o)if(s==="opentag"){let c=a;if(c.name==="Relationship"){let u=c.attributes.Id;switch(c.attributes.Type){case T_r.Hyperlink:{let d={type:R_r.RelationshipType.Styles,rId:u,target:c.attributes.Target,targetMode:c.attributes.TargetMode};n?this.emit("hyperlink",d):i[d.rId]=d}break;default:break}}}this.emit("finished")}catch(o){this.emit("error",o)}}};Wot.exports=Nme});var tst=I((Lrn,est)=>{var Bme=z("fs"),{EventEmitter:x_r}=z("events"),{PassThrough:k_r,Readable:N_r}=Jk(),B_r=z("stream"),O_r=vot(),Zot=jot(),bE=Hot(),F_r=Xk(),Xot=nH(),L_r=lH(),Q_r=aH(),P_r=Vot(),M_r=Kot();Zot.setGracefulCleanup();var JG=class extends x_r{constructor(t,r={}){super(),this.input=t,this.options={worksheets:"emit",sharedStrings:"cache",hyperlinks:"ignore",styles:"ignore",entries:"ignore",...r},this.styles=new Xot,this.styles.init()}_getStream(t){if(t instanceof B_r.Readable||t instanceof N_r)return t;if(typeof t=="string")return Bme.createReadStream(t);throw new Error(`Could not recognise input: ${t}`)}async read(t,r){try{for await(let{eventType:n,value:i}of this.parse(t,r))switch(n){case"shared-strings":this.emit(n,i);break;case"worksheet":this.emit(n,i),await i.read();break;case"hyperlinks":this.emit(n,i);break}this.emit("end"),this.emit("finished")}catch(n){this.emit("error",n)}}async*[Symbol.asyncIterator](){for await(let{eventType:t,value:r}of this.parse())t==="worksheet"&&(yield r)}async*parse(t,r){r&&(this.options=r);let n=this.stream=this._getStream(t||this.input),i=O_r.Parse({forceStream:!0});n.pipe(i);let o=[];for await(let s of bE(i)){let a,c;switch(s.path){case"_rels/.rels":break;case"xl/_rels/workbook.xml.rels":await this._parseRels(s);break;case"xl/workbook.xml":await this._parseWorkbook(s);break;case"xl/sharedStrings.xml":yield*this._parseSharedStrings(s);break;case"xl/styles.xml":await this._parseStyles(s);break;default:s.path.match(/xl\/worksheets\/sheet\d+[.]xml/)?(a=s.path.match(/xl\/worksheets\/sheet(\d+)[.]xml/),c=a[1],this.sharedStrings&&this.workbookRels?yield*this._parseWorksheet(bE(s),c):await new Promise((u,d)=>{Zot.file((f,p,h,m)=>{if(f)return d(f);o.push({sheetNo:c,path:p,tempFileCleanupCallback:m});let A=Bme.createWriteStream(p);return A.on("error",d),s.pipe(A),A.on("finish",()=>u())})})):s.path.match(/xl\/worksheets\/_rels\/sheet\d+[.]xml.rels/)&&(a=s.path.match(/xl\/worksheets\/_rels\/sheet(\d+)[.]xml.rels/),c=a[1],yield*this._parseHyperlinks(bE(s),c));break}s.autodrain()}for(let{sheetNo:s,path:a,tempFileCleanupCallback:c}of o){let u=Bme.createReadStream(a);u[Symbol.asyncIterator]||(u=u.pipe(new k_r)),yield*this._parseWorksheet(u,s),c()}}_emitEntry(t){this.options.entries==="emit"&&this.emit("entry",t)}async _parseRels(t){let r=new Q_r;this.workbookRels=await r.parseStream(bE(t))}async _parseWorkbook(t){this._emitEntry({type:"workbook"});let r=new L_r;await r.parseStream(bE(t)),this.properties=r.map.workbookPr,this.model=r.model}async*_parseSharedStrings(t){switch(this._emitEntry({type:"shared-strings"}),this.options.sharedStrings){case"cache":this.sharedStrings=[];break;case"emit":break;default:return}let r=null,n=[],i=0,o=null;for await(let s of F_r(bE(t)))for(let{eventType:a,value:c}of s)if(a==="opentag"){let u=c;switch(u.name){case"b":o=o||{},o.bold=!0;break;case"charset":o=o||{},o.charset=parseInt(u.attributes.charset,10);break;case"color":o=o||{},o.color={},u.attributes.rgb&&(o.color.argb=u.attributes.argb),u.attributes.val&&(o.color.argb=u.attributes.val),u.attributes.theme&&(o.color.theme=u.attributes.theme);break;case"family":o=o||{},o.family=parseInt(u.attributes.val,10);break;case"i":o=o||{},o.italic=!0;break;case"outline":o=o||{},o.outline=!0;break;case"rFont":o=o||{},o.name=u.value;break;case"si":o=null,n=[],r=null;break;case"sz":o=o||{},o.size=parseInt(u.attributes.val,10);break;case"strike":break;case"t":r=null;break;case"u":o=o||{},o.underline=!0;break;case"vertAlign":o=o||{},o.vertAlign=u.attributes.val;break}}else if(a==="text")r=r?r+c:c;else if(a==="closetag")switch(c.name){case"r":n.push({font:o,text:r}),o=null,r=null;break;case"si":this.options.sharedStrings==="cache"?this.sharedStrings.push(n.length?{richText:n}:r):this.options.sharedStrings==="emit"&&(yield{index:i++,text:n.length?{richText:n}:r}),n=[],o=null,r=null;break}}async _parseStyles(t){this._emitEntry({type:"styles"}),this.options.styles==="cache"&&(this.styles=new Xot,await this.styles.parseStream(bE(t)))}*_parseWorksheet(t,r){this._emitEntry({type:"worksheet",id:r});let n=new P_r({workbook:this,id:r,iterator:t,options:this.options}),i=(this.workbookRels||[]).find(s=>s.Target===`worksheets/sheet${r}.xml`),o=i&&(this.model.sheets||[]).find(s=>s.rId===i.Id);o&&(n.id=o.id,n.name=o.name,n.state=o.state),this.options.worksheets==="emit"&&(yield{eventType:"worksheet",value:n})}*_parseHyperlinks(t,r){this._emitEntry({type:"hyperlinks",id:r});let n=new M_r({workbook:this,id:r,iterator:t,options:this.options});this.options.hyperlinks==="emit"&&(yield{eventType:"hyperlinks",value:n})}};JG.Options={worksheets:["emit","ignore"],sharedStrings:["cache","emit","ignore"],hyperlinks:["cache","emit","ignore"],styles:["cache","ignore"],entries:["emit","ignore"]};est.exports=JG});var ist=I((Qrn,nst)=>{var rst={Workbook:r9e(),ModelContainer:i9e(),stream:{xlsx:{WorkbookWriter:irt(),WorkbookReader:tst()}}};Object.assign(rst,zl());nst.exports=rst});var sst=I((Prn,ost)=>{if(parseInt(process.versions.node.split(".")[0],10)<10)throw new Error("For node versions older than 10, please use the ES5 Import: https://github.com/exceljs/exceljs#es5-imports");ost.exports=ist()});function lst(e){let t=new Set;for(let r=0;r<e.length;r++){let n=e[r];if(!n.trim())throw new Error(`Header row contains a blank column at position ${r+1}`);let i=n.trim().toLowerCase();if(t.has(i))throw new Error(`Header row contains a duplicate column: "${n}"`);t.add(i)}}function q_r(e,t){let r=new URL(e).pathname.toLowerCase();if(r.endsWith(".xls")||r.endsWith(".xlsx")||r.endsWith(".xlsm")||r.endsWith(".xlsb")||r.endsWith(".ods"))return"excel";let n=(t??"").toLowerCase();return n.includes("spreadsheet")||n.includes("excel")||n.includes("sheet")?"excel":"csv"}async function j_r(e){let r=(await Promise.resolve().then(()=>lo(Q$e(),1))).default.parse(e,{header:!1,skipEmptyLines:"greedy",dynamicTyping:!1,transform:o=>o.trim()});if(r.errors.length>0&&r.data.length===0){let o=r.errors[0];throw new Error(`CSV parse error at row ${o.row}: ${o.message}`)}if(r.data.length===0)return{columns:[],rows:[]};let n=(r.data[0]??[]).map(o=>String(o??"").trim());lst(n);let i=[];for(let o=1;o<r.data.length;o++){let s=r.data[o]??[],a={};for(let c=0;c<n.length;c++)a[n[c]]=s[c]??null;i.push(a)}return{columns:n,rows:i}}function Ome(e){if(e==null)return null;if(e instanceof Date)return e.toISOString().slice(0,10);if(typeof e=="number")return String(e);if(typeof e=="string"||typeof e=="boolean")return e;let t=e;return"text"in t?String(t.text??""):"result"in t?Ome(t.result):"richText"in t&&Array.isArray(t.richText)?t.richText.map(r=>r.text??"").join(""):"hyperlink"in t?String(t.hyperlink??""):String(e)}async function Y_r(e){let t=(await Promise.resolve().then(()=>lo(nee(),1))).default,n=new t(Buffer.from(e)).getEntries().reduce((i,o)=>i+o.header.size,0);if(n>ast)throw new Error(`XLSX uncompressed size ${n} bytes exceeds ${ast}-byte safety cap`)}function ust(e){let t=0,r=[];return e.eachRow({includeEmpty:!1},(n,i)=>{if(t>0)return;let o=n.values.slice(1);o.some(s=>s!=null&&s!=="")&&(t=i,r=o.map(s=>String(Ome(s)??"").trim()))}),{headerRowNum:t,columns:r}}function cst(e){let{headerRowNum:t,columns:r}=ust(e);if(!t)return{columns:[],rows:[]};lst(r);let n=[];return e.eachRow({includeEmpty:!1},(i,o)=>{if(o<=t)return;let s=i.values.slice(1);if(s.every(c=>c==null||c===""))return;let a={};for(let c=0;c<r.length;c++)a[r[c]]=Ome(s[c]);n.push(a)}),{columns:r,rows:n}}async function H_r(e,t,r){await Y_r(e);let n=await Promise.resolve().then(()=>lo(sst(),1)),i=n.default??n,o=new i.Workbook;await o.xlsx.load(e);let s=o.worksheets.map(u=>u.name);if(t<0||t>=s.length)throw new Error(`sheetIndex ${t} out of range (have ${s.length} sheets: ${s.join(", ")})`);let a=()=>s.map((u,d)=>`${d}:"${u}"`).join(", "),c=(u,d)=>{throw new Error(`${u.message} on sheet ${d} ("${s[d]}"). availableSheets: [${a()}]. Re-call with a sheetIndex pointing at the data sheet.`)};if(r)try{return{...cst(o.worksheets[t]),sheetName:o.worksheets[t].name,sheetIndex:t,availableSheets:s}}catch(u){c(u,t)}for(let u=t;u<s.length;u++){let d=o.worksheets[u];if(ust(d).headerRowNum!==0)try{return{...cst(d),sheetName:d.name,sheetIndex:u,availableSheets:s}}catch(f){c(f,u)}}throw new Error(`No sheet with a header row was found. availableSheets: [${a()}].`)}async function dst(e){let t=Math.max(0,e.offset??0),r=Math.min(U_r,Math.max(1,e.limit??$_r)),n=e.sheetIndex??0,i=await df(e.sourceUrl),o=await wc(i,{timeoutMs:GI,maxBytes:wM});if(!o.ok)throw new Error(`fetch ${e.sourceUrl}: ${o.status} ${o.statusText}`);let s=await o.arrayBuffer(),a=e.kind??q_r(e.sourceUrl,o.headers.get("content-type")),c,u,d,f,p=n;if(a==="csv"){let A=await j_r(new TextDecoder("utf-8").decode(s));c=A.columns,u=A.rows}else{let A=await H_r(s,n,e.sheetIndex!==void 0);c=A.columns,u=A.rows,d=A.sheetName,f=A.availableSheets,p=A.sheetIndex}let h=u.length,m=u.slice(t,t+r);return{sourceUrl:e.sourceUrl,kind:a,...a==="excel"?{sheetIndex:p,sheetName:d,availableSheets:f}:{},totalRows:h,offset:t,limit:r,returned:m.length,hasMore:t+m.length<h,columns:c,rows:m}}var U_r,$_r,ast,fst=J(()=>{"use strict";Qu();U_r=500,$_r=200,ast=100*1024*1024});function z_r(e){if(e.internalNotes!==void 0)throw ct(new Error("A cash entry's notes cannot be edited via the API today (the update fails upstream). Nothing was changed. To change the notes, void the entry and create a new one."));if((Array.isArray(e.lines)?e.lines:[]).some(r=>!!r?.taxProfileResourceId))throw ct(new Error("A taxed cash entry's lines cannot be edited via the API today: void it and create a new one. Nothing was changed."))}function pst(e){return{create:(t,r)=>t.post(`/api/v1/${Vw[e]}`,{saveAsDraft:!1,...r,currency:Wt(r.currency),taxCurrency:Wt(r.taxCurrency)},Gi),list:(t,r)=>t.list(`/api/v1/${Vw[e]}`,r),get:(t,r)=>t.get(`/api/v1/${Vw[e]}/${r}`),update:async(t,r,n,i)=>{z_r(n);let o={...n,resourceId:r};if(!o.accountResourceId){let s=i??(await t.get(`/api/v1/${Vw[e]}/${r}`)).data;if(o.accountResourceId=s.organizationAccountResourceId??s.account?.resourceId,!o.accountResourceId)throw new Error(`accountResourceId required for ${Vw[e]} update and could not be derived from existing entry`)}return o.currency&&(o.currency=Wt(o.currency)),t.put(`/api/v1/${Vw[e]}/${r}`,o)}}}var Vw,GG,VG,WG,KG,IE,XG,ZG,eV,CE,tV,rV=J(()=>{"use strict";tr();it();Vw={IN:"cash-in-entries",OUT:"cash-out-entries"};GG=pst("IN"),VG=pst("OUT"),WG=GG.create,KG=GG.list,IE=GG.get,XG=GG.update,ZG=VG.create,eV=VG.list,CE=VG.get,tV=VG.update});async function qB(e,t){return e.post("/api/v1/cash-transfers",{saveAsDraft:!1,...t},Gi)}async function nV(e,t){return e.list("/api/v1/cash-transfers",t)}async function iV(e,t){return e.get(`/api/v1/cash-transfers/${t}`)}var Fme=J(()=>{"use strict";tr();an()});async function oV(e,t){return e.list("/api/v1/scheduled/invoices",t)}async function sV(e,t){return e.list("/api/v1/scheduled/bills",t)}async function aV(e,t){return e.list("/api/v1/scheduled/journals",t)}async function Ww(e,t){return e.get(`/api/v1/scheduled/invoices/${t}`)}async function cV(e,t,r){return e.put(`/api/v1/scheduled/invoices/${t}`,r)}async function lV(e,t){await e.delete(`/api/v1/scheduled/invoices/${t}`)}async function Kw(e,t){return e.get(`/api/v1/scheduled/bills/${t}`)}async function uV(e,t,r){return e.put(`/api/v1/scheduled/bills/${t}`,r)}async function dV(e,t){await e.delete(`/api/v1/scheduled/bills/${t}`)}async function Xw(e,t){return e.get(`/api/v1/scheduled/journals/${t}`)}async function fV(e,t,r){let{currency:n,...i}=J_r(r);return e.put(`/api/v1/scheduled/journals/${t}`,n===void 0?i:{...i,currency:Wt(n)})}function J_r(e){let t={...e};BM(t);let r=Array.isArray(t.schedulerEntries)?t.schedulerEntries:[];if(typeof t.taxVatApplicable!="boolean"&&r.some(n=>!!n?.taxProfileResourceId)&&(t.taxVatApplicable=!0),t.taxVatApplicable===!0&&typeof t.taxInclusion!="boolean")throw ct(new Error("taxInclusion is required when the schedule is taxed (a schedulerEntries line carries a tax profile, or taxVatApplicable is true): the update resets it when omitted, and the stored value cannot be read back. Send taxInclusion true (prices include tax) or false (CLI: --tax-inclusion inclusive|exclusive). Nothing was changed."));return t}async function pV(e,t){await e.delete(`/api/v1/scheduled/journals/${t}`)}var hV=J(()=>{"use strict";it()});import{statSync as hst}from"node:fs";function mst(e){for(let t of e)try{if(hst(t).isFile())return t}catch{}return null}function Ast(e){for(let t of e)try{if(hst(t).isDirectory())return t}catch{}return null}var Lme=J(()=>{"use strict"});import{readFileSync as Pme}from"node:fs";import{dirname as bst,join as Zm}from"node:path";import{fileURLToPath as Ist}from"node:url";function Cst(e){let t=new Set(e);for(let r of e){let n=W_r.get(r);if(n)for(let i of n)t.add(i)}return Array.from(t)}function _st(e){let t=e.toLowerCase();return t=t.replace(/https?:\/\/\S+/g,""),t=t.replace(/[*#`|_\-~\[\]()>]/g," "),(t.match(/[a-z0-9]+/g)??[]).filter(n=>n.length>1&&!V_r.has(n))}function jB(e){let t=e??twr();if(mV&&Est===t)return mV;let r=Pme(t,"utf-8");return mV=JSON.parse(r),Est=t,mV}function wst(){let e=Ist(import.meta.url),t=bst(e),r=[Zm(t,"..","..","..","help-center-mirror","help-center-index.json"),Zm(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-index.json"),Zm(t,"help-center-mirror","help-center-index.json")];return mst(r)??void 0}function twr(){let e=wst();if(!e)throw new Error("Help center index not found. Run the help center sync or reinstall the package.");return e}function YB(){return Qme===null&&(Qme=wst()!==void 0),Qme}function _E(e,t,r={}){let n=r.limit??5,i=_st(t);if(i.length===0)return[];let o=Cst(i).slice(0,Z_r),s=new Map(e.sections.map(c=>[c.slug,c])),a=[];for(let c of e.articles){if(r.section&&c.section!==r.section)continue;let u=new Map;for(let h of c.tokens)u.set(h,(u.get(h)??0)+1);let d=0,f=[],p=c.title.toLowerCase();for(let h of o){let m=u.get(h)??0,A=e.idf[h]??0,g=!1;if(m===0&&h.length>=X_r){let C=0;for(let[w,T]of u)if(w.startsWith(h)&&w!==h&&(m+=T,A=Math.max(A,e.idf[w]??0),g=!0,++C>=ewr))break}if(m===0)continue;f.push(g?`${h}*`:h);let y=m*(gst+1),b=m+gst*(1-yst+yst*(c.tokenCount/e.avgDocLen)),E=A*(y/b);g&&(E*=K_r),p.includes(h)&&(E*=G_r),d+=E}if(d>0){let h=s.get(c.section);h&&a.push({article:c,score:d,scoreKind:"bm25",section:h,matchedTerms:f})}}return a.sort((c,u)=>u.score-c.score),a.slice(0,n)}function Mme(e,t){let r=t??rwr();if(!r)return null;try{let n=Zm(r,`${e.section}.md`),i=Pme(n,"utf-8"),o=`### ${e.title}`,s=i.indexOf(o);if(s===-1)return null;let a=s+o.length,c=i.indexOf(`
|
|
660
660
|
---
|
|
661
661
|
`,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function rwr(){let e=Ist(import.meta.url),t=bst(e),r=[Zm(t,"..","..","..","help-center-mirror"),Zm(t,"..","..","..","assets","skills","api","help-center-mirror"),Zm(t,"help-center-mirror")];for(let n of r)try{return Pme(Zm(n,"index.md"),"utf-8"),n}catch{}return null}var gst,yst,G_r,V_r,W_r,K_r,X_r,Z_r,ewr,mV,Est,Qme,HB=J(()=>{"use strict";Lme();Tg();gst=1.2,yst=.75,G_r=1.5,V_r=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","shall","should","may","might","must","can","could","am","i","me","my","we","our","you","your","he","she","it","they","them","this","that","these","those","what","which","who","whom","how","when","where","why","if","then","than","so","no","not","or","and","but","in","on","at","to","for","of","with","by","from","as","into","about","between","through","after","before","during","above","below","up","down","out","off","over","under","again","further","just","also","very","too","only","own","same","both","each","all","any","few","more","most","other","some","such","here","there"]),W_r=new Map([["recon",["reconciliation","reconcile","reconciled"]],["txn",["transaction","transactions"]],["txns",["transactions","transaction"]],["acct",["account","accounts"]],["accts",["accounts","account"]],["inv",["invoice","invoices"]],["cn",["credit","note"]],["ar",["receivable","receivables"]],["ap",["payable","payables"]],["pmt",["payment","payments"]],["stmt",["statement","statements"]],["bal",["balance","balances"]],["fa",["fixed","assets","asset"]],["gst",["tax","goods","services"]],["vat",["tax","value","added"]],["fx",["foreign","exchange","currency"]],["config",["configuration","configure","settings"]],["depr",["depreciation"]],["amort",["amortization"]],["coa",["chart","accounts"]],["po",["purchase","order"]],["so",["sales","order"]],["org",["organization"]],["subs",["subscription","subscriptions"]],["amt",["amount","amounts"]],["qty",["quantity"]],["desc",["description"]],["ref",["reference"]],["num",["number"]]]);K_r=.7,X_r=3,Z_r=32,ewr=5;mV=null,Est=null;Qme=null});import{existsSync as nwr,readFileSync as iwr}from"node:fs";import{dirname as owr,join as Ume}from"node:path";import{fileURLToPath as swr}from"node:url";function zB(e){let t=e??dwr();if(!t)return null;if(AV&&Sst===t)return AV;try{let r=iwr(t,"utf-8");return AV=JSON.parse(r),Sst=t,AV}catch{return null}}function dwr(){let e=swr(import.meta.url),t=owr(e),r=[Ume(t,"..","..","..","help-center-mirror","help-center-embeddings.json"),Ume(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),Ume(t,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(nwr(n))return n;return null}function Tst(e,t){let r=Math.min(e.length,t.length),n=0;for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function xst(){return gV!==null?gV:(gV=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",gV||null)}async function $me(e){let t=xst();if(!t)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),cwr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:awr,input:e}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Dst&&(Dst=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
|
|
662
|
-
`)),null)}catch{return null}}async function JB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??lwr,c=n.minBm25??uwr;if(i==="bm25"||!t)return _E(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await $me(r);return m?Rst(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):_E(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([$me(r),Promise.resolve(_E(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Rst(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return kst(p,h,o)}function Rst(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=Tst(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function kst(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(vst+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(vst+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function qme(e){return e!==null&&!!xst()}var awr,cwr,vst,lwr,uwr,AV,Sst,gV,Dst,yV=J(()=>{"use strict";HB();awr="text-embedding-3-small",cwr=2e3,vst=60,lwr=.3,uwr=1.5,AV=null,Sst=null,gV=null,Dst=!1});async function Nst(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=jB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:zB(),u=await JB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(Mme(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Bst(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:fwr}async function EV(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Bst())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(pwr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return hwr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function hwr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function jme(e,t={}){return process.env.CLIO_DAEMON==="1"||YB()?Nst(e,t):EV(e,t)}var fwr,pwr,Ost=J(()=>{"use strict";HB();yV();fwr="https://mcp.jaz.ai/help-center/search",pwr=4e3});var Yme=J(()=>{"use strict";HB();yV();Ost();HB()});async function eA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function tA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var GB=J(()=>{"use strict";an()});async function bV(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency)},rNe)}var Hme=J(()=>{"use strict";it();tr()});async function IV(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function CV(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function VB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function _V(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var zme=J(()=>{"use strict"});function mwr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Zw(e,t){return e.post("/api/v1/jots",{entries:t.map(mwr)})}async function wV(e,t){return e.post("/api/v1/jots/search",t,et)}async function Fst(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var vV=J(()=>{"use strict";tr()});async function Lst(e,t){return e.post("/api/v1/agents/memories",t)}async function Jme(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Qst=J(()=>{"use strict";tr()});function SV(){return process.env.ENABLE_MEMORY==="true"}function Gme(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Pst(e){return!SV()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Vme=J(()=>{"use strict"});import{createHash as Awr}from"node:crypto";function Dwr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:$st.some(r=>t.includes(r))?[null,"directive_invalid"]:Ust.test(t)?[null,"directive_invalid"]:Cwr.test(t)?[null,"directive_contains_url"]:_wr.test(t)?[null,"directive_contains_email"]:[t,null]}function Rwr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>wwr?[null,"match_condition_too_long"]:$st.some(r=>t.includes(r))?[null,"match_condition_invalid"]:Ust.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function Twr(e){return e==null?[null,null]:Number.isInteger(e)?e<vwr||e>Swr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function xwr(e,t,r,n,i,o,s,a){if(e)return Awr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function kwr(e){Promise.resolve().then(()=>(AD(),mD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Hst(e,t,r){let n=t.action,i=t.category,o=bwr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(kwr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Pst(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>gwr||!Iwr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=Dwr(t.directive);if(E)return u(E);p=b;let[C,w]=Twr(t.importance);if(w)return u(w);h=C}let[m,A]=Rwr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=ywr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,Ewr));let E=xwr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await Wme(()=>Lst(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await Wme(()=>Jme(e.client,b))}else{let b={forgetAll:!0};y=await Wme(()=>Jme(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function Wme(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof gr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var Ust,$st,gwr,ywr,Ewr,qst,jst,Yst,bwr,Iwr,Cwr,_wr,wwr,vwr,Swr,zst=J(()=>{"use strict";Qst();Vi();Vme();Vme();Ust=/[\x00-\x1f\x7f]/,$st=["{{","}}","```","<",">"],gwr=120,ywr=3,Ewr=140,qst=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],jst=["set","forget","forget_all"],Yst=["this_org","all_orgs"],bwr={this_org:"ORG_USER",all_orgs:"USER"},Iwr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Cwr=/https?:\/\//i,_wr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,wwr=255,vwr=0,Swr=100});async function DV(e,t){return e.list("/api/v1/organization-users",t)}async function RV(e,t){return e.search("/api/v1/organization-users/search",t)}async function ev(e,t){return e.post("/api/v1/organization-users/invite",t)}async function TV(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function xV(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var Kme=J(()=>{"use strict"});async function kV(e,t){return e.get(`/api/v1/payments/${t}`)}async function NV(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Wt(r.currency)})}async function BV(e,t){await e.delete(`/api/v1/payments/${t}`)}function OV(e){return(t,r)=>t.post(`/api/v1/${Nwr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Wt(n.currency)}))},zke)}var Nwr,$nn,Jst,qnn,jnn,Xme=J(()=>{"use strict";it();tr();Nwr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};$nn=OV("saleBulk"),Jst=OV("saleBatch"),qnn=OV("purchaseBulk"),jnn=OV("purchaseBatch")});async function sp(e,t,r,n,i,o=tNe){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof gr?c.status<500&&c.status!==401?ct(c):new nf(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof zp?ct(c):c}let a=s?.data;if(!i(a))throw new nf(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function LV(e,t,r){try{Xi(e,t,r)}catch(n){throw ct(n)}}function wE(e){return LV(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function QV(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function PV(e,t){return sp(e,"POST",Bwr,t,rA)}async function MV(e,t,r){return sp(e,"PUT",`/api/v1/unapplied-payments/${wE(t)}`,r,rA)}async function UV(e,t,r){return sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/activate`,{hash:r},rA)}async function $V(e,t,r,n){return sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/attributions`,{hash:r,attributions:n},rA)}async function qV(e,t,r,n){return LV(n,"paymentResourceId","Pass the payment record resourceId."),sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/payments`,{hash:r,paymentResourceId:n},rA)}async function jV(e,t,r,n){return LV(r,"childResourceId","Pass the payment record resourceId from the children list."),sp(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}/children/${encodeURIComponent(r)}`,{hash:n},rA)}async function YV(e,t,r){return sp(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}`,{hash:r},rA)}async function HV(e,t,r){return sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/unbatch`,{hash:r},rA)}async function zV(e,t){return LV(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),sp(e,"POST",Owr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,zs)}var Bwr,Owr,FV,Gst,Vst,rA,Zme=J(()=>{"use strict";Vi();tr();dP();it();Bwr="/api/v1/unapplied-payments",Owr="/api/v1/reconciliations/unapplied-payment",FV=["SALE","PURCHASE"],Gst=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Vst=["AMOUNT","PERCENTAGE"];rA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function JV(e,t,r={},n=eAe){let i=Fwr.has(t)?`/api/v1/${Sc(Wst,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=Hg.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...Hg.keys()].join(", ")}.`);let A=await Tf(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...et,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new ue(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...WB].join(", ")}.`}:d}var Wst,Fwr,eAe,WB,Kst,tAe=J(()=>{"use strict";tr();it();Ux();Hu();Wst=["statement-of-account-export"],Fwr=new Set(Wst),eAe=9e4,WB=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),Kst={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as Lwr}from"node:crypto";import{writeFile as Qwr,mkdir as Pwr}from"node:fs/promises";import{dirname as Mwr,isAbsolute as Uwr,join as $wr}from"node:path";async function GV(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},et)}async function KB(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function tv(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Xst(e){return`query-export-${e.slice(0,8)}.csv`}function rAe(e){return Lwr("sha256").update(e).digest("hex").slice(0,16)}async function VV(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=rAe(t),o=await KB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await tv(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await tv(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!Uwr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??$wr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Pwr(Mwr(p),{recursive:!0}),await Qwr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function WV(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new ue(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function rv(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var nAe=J(()=>{"use strict";it();tr()});async function gi(e,t,r){let n=await e.get(`/api/v1/${KV[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function XV(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),i.attachmentType&&o.append("attachmentType",i.attachmentType),e.postMultipart(`/api/v1/${KV[r]}/${n}/attachments`,o)}async function ZV(e,t,r,n){return e.delete(`/api/v1/${KV[t]}/${r}/attachments/${n}`)}var KV,el,XB,nA=J(()=>{"use strict";KV={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders","fixed-assets":"fixed-assets",deferrals:"deferrals",leases:"leases",loans:"loans","cash-in-entries":"cash-in-entries","cash-out-entries":"cash-out-entries","cash-transfers":"cash-transfers"},el=Object.keys(KV),XB=["sale-quotes","sale-orders","purchase-requests","purchase-orders","fixed-assets","deferrals","leases","loans","cash-in-entries","cash-out-entries","cash-transfers"]});function Gwr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&Jwr.some(n=>r.startsWith(n)))}async function ap(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&Gwr(t)&&(t.refusal=zwr),t}}function Zst(e,t,r){return Xi(e,t,r),e.toLowerCase()}function nv(e,t){return{type:Sc(iAe,e,"entityType"),record:Zst(t,"entityId",qwr)}}function ZB(e){FZ(e,"threadId",Ywr)}function eat(e){FZ(e,"commentId",Hwr)}function iv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Zst(e.bankAccountResourceId,"bankAccountResourceId",jwr)}}async function tat(e,t,r,n={}){let{type:i,record:o}=nv(t,r),s={...iv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return ap(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function rat(e,t,r,n,i={}){let{type:o,record:s}=nv(t,r),a={...iv(i),limit:i.limit,offset:i.offset};return ZB(n),ap(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function nat(e,t,r,n,i){let{type:o,record:s}=nv(t,r),a=iv(i);return n.threadId!==void 0&&ZB(n.threadId),(await ap(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...eNe,query:a}))).data}async function iat(e,t,r,n,i,o,s){let{type:a,record:c}=nv(t,r),u=iv(s);return ZB(n),eat(i),(await ap(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function oat(e,t,r,n,i,o){let{type:s,record:a}=nv(t,r),c=iv(o);return ZB(n),eat(i),(await ap(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function sat(e,t,r,n,i){let{type:o,record:s}=nv(t,r),a=iv(i);return ZB(n),(await ap(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function aat(e,t={}){return ap(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function cat(e,t,r){return tBe(t,"Get it from list_notifications."),(await ap(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function lat(e){return(await ap(e.post("/api/v1/collaboration/notifications/read-all"))).data}var iAe,qwr,jwr,Ywr,Hwr,zwr,Jwr,uat=J(()=>{"use strict";Vi();it();tr();iAe=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],qwr="Pass the resourceId of the bill, invoice, credit note or bank record.",jwr="Pass the resourceId of the bank account that holds the bank record.",Ywr="Get it from list_comment_threads.",Hwr="Get it from list_comments or list_comment_threads.",zwr={code:"USER_CREDENTIAL_REQUIRED",hint:"Comments and notifications act as a user, so the credential must name an active member of the organization. A service or organization key with no user is refused with this 401. Use a user credential: sign in with `clio auth login`, a personal access token, or an API key a member created."},Jwr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Lo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var ov=J(()=>{"use strict"});async function e8(e,t){return e.post("/api/v1/claims/conversion/preview",t,et)}async function t8(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new ue('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:yP)}var eO,oAe=J(()=>{"use strict";it();tr();eO=["POST","POST_AND_RECORD"]});async function r8(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,Jke)}async function n8(e,t){return e.search("/api/v1/employees/payouts/search",t)}var dat,sAe=J(()=>{"use strict";it();tr();dat=["REIMBURSEMENT","ADVANCE"]});async function i8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var aAe=J(()=>{"use strict"});function cAe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function lAe(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${fat(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>Mu.has(u)),s=i.filter(u=>!Mu.has(u)&&Rc.has(u)),a=[`Nothing here can be extracted: found ${fat(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=aOe[u];d&&a.push(d)}return o.length>0&&a.push(`${nU(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${nU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Mu.has(u)&&!Rc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${nU([...Mu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function fat(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var pat=J(()=>{"use strict";Uu()});function o8(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function tO(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&o8()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function vE(e,t){return{error:e,hint:t,...uAe}}function hat(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${tO(e)}.`,...uAe}}function SE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function iA(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${tO({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...uAe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var uAe,mat=J(()=>{"use strict";uAe={kind:"validation",retriable:!1}});import{randomUUID as Vwr}from"node:crypto";import{rmSync as Wwr}from"node:fs";function fAe(e){for(let t of e.tempDirs??[])try{Wwr(t,{recursive:!0,force:!0})}catch{}}function gat(e){for(let[t,r]of DE)e-r.createdAt>Aat&&(fAe(r.plan),DE.delete(t))}function Xwr(){dAe||(dAe=setInterval(()=>gat(Date.now()),Kwr),dAe.unref?.())}function pAe(e,t){let r=Date.now();gat(r),Xwr();let n=`dc_${Vwr()}`;return DE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function hAe(e,t){let r=DE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>Aat?(fAe(r.plan),DE.delete(e),null):r.plan}function yat(e,t){let r=DE.get(e);!r||r.ownerKey!==t||(fAe(r.plan),DE.delete(e))}var Aat,Kwr,DE,dAe,Eat=J(()=>{"use strict";Aat=1800*1e3,Kwr=300*1e3,DE=new Map});function Zwr(e){if(!e||typeof e!="object")return{};let t=e,r=t.validFiles?.[0],n=r?.workflowResourceId??t.workflowResourceId;return{...n?{workflowId:n}:{},...r?.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},...r?.subscriptionFBPath?{subscriptionFBPath:r.subscriptionFBPath}:{},...r?.backgroundJobFBPath?{backgroundJobFBPath:r.backgroundJobFBPath}:{}}}function bat(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>_g(i.documentType)&&r.has(i.documentType))}))}}async function Iat(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?bat(t,i):t;if(!n&&evr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");SD(o);let a=await yU({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,...d.status==="uploaded"?Zwr(d.response):{},error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function Cat(e,t){return(t&&t.length>0?bat(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>_g(o.documentType)).length,0)}function evr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var _at=J(()=>{"use strict";dee();Uu();yf()});function tvr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function nvr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function ivr(e,t){if(e!==rvr)return;let r=nvr(t);if(r)return wat.get(r)??wat.get(r.replace(/_ERROR$/,""))}function s8(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function ovr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=s8(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function mAe(e){return ivr(e.status,e.body)??e.refusal?.hint??ovr(e)}function RE(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function a8(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function rO(e,t={}){let r=t.readOnly===!1&&MD()?GFe:"";if(e instanceof gr){let o=[mAe(e)??tvr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...s8(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=c8(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof nt;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var rvr,wat,TE=J(()=>{"use strict";Vi();Wi();l8();_U();rvr=422,wat=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});async function Ad(e,t,r){if(!t)return e;let n=svr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}async function gd(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${RE(i)}`],...n}}}function svr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function cp(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var vat=J(()=>{"use strict";TE()});async function u8(e,t){return e.list("/api/v1/bank-rules",t)}async function nO(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function d8(e,t){return e.search("/api/v1/bank-rules/search",t)}async function f8(e,t){return e.post("/api/v1/bank-rules",t)}async function p8(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function h8(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var AAe=J(()=>{"use strict"});async function m8(e,t){return e.list("/api/v1/fixed-assets",t)}async function xE(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function iO(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function A8(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},fZ)}function Dat(e,t){let r={};for(let n of avr){let i=e[n];if(i==null)continue;let o=cvr.has(n)?uf(i):i;o!==void 0&&(r[n]=o)}for(let[n,i]of Object.entries(t))i!==void 0&&n!=="resourceId"&&(r[n]=i);return r}async function g8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ct(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await xE(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,Dat(i,r))}async function y8(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function E8(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},AP)}async function oO(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,AP)}async function b8(e,t){return e.post("/api/v1/transfer-fixed-assets",t,fZ)}async function I8(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},AP)}async function C8(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},pZ)}async function _8(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},pZ)}async function lvr(e,t){let r=new Map;for(let i=0;i<t.length;i+=Sat){let o=t.slice(i,i+Sat),s=await iO(e,{filter:{resourceId:{in:o}},limit:o.length});for(let a of s.data)r.set(a.resourceId,a)}let n=t.filter(i=>!r.has(i));if(n.length>0)throw ct(new ue(`No fixed asset found for ${n.length} resourceId${n.length===1?"":"s"}: ${n.join(", ")}. Nothing was submitted; fix or remove those rows and retry.`));return r}async function w8(e,t){ht(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=zS(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw ct(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw ct(new ue(`resourceId ${u} appears more than once in fixedAssets; put all of an asset's changes in one row. Nothing was submitted.`));return r.add(u),u}),i=t.map((a,c)=>Ui(a.tags,`fixedAssets[${c}].tags`)),o=await lvr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...Dat(u,{...a,tags:d&&Ki(u.tags,d)})}});return En(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function v8(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function S8(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function D8(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,et)}async function R8(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},et)}async function T8(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function x8(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function k8(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function dvr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function fvr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=dvr(i);if(o.length===0)return;let s=typeof i.reference=="string"&&i.reference?` (${i.reference})`:"";t.push(`row ${n}${s}: ${o.map(a=>`${a} (${uvr[a]})`).join(", ")}`)}),t.length>0)throw ct(new ue(`Every fixed asset row needs its reference, registrationType and depreciationStartDate; the import job rejects a row without them. Missing: ${t.join("; ")}. Nothing was sent.`))}async function N8(e,t){return ht(t,"fixedAssets",500,"fixed assets"),LNe(t,["purchaseDate","depreciationStartDate"]),fvr(t),En(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var oA,avr,cvr,Sat,uvr,B8=J(()=>{"use strict";an();XS();tr();it();Nl();oA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];avr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],cvr=new Set(["purchaseDate","depreciationStartDate"]);Sat=100;uvr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function O8(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function kE(e,t){return e.get(`/api/v1/leases/${t}`)}async function F8(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},Wke)}async function L8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names lease ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await kE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function Q8(e,t){await e.delete(`/api/v1/leases/${t}`)}async function P8(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},jS)}async function M8(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},jS)}async function U8(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},jS)}async function $8(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},et)}async function q8(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},jS)}async function j8(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function Y8(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function H8(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function z8(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,et)}async function J8(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,et)}async function G8(e,t){return ht(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ct(new ue(`leases[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that lease. Bulk update does not take tags: change them with update_lease (clio leases update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/leases/bulk-update","leases",t)}var gAe=J(()=>{"use strict";an();it();tr()});async function V8(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function NE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function W8(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Jp)}async function K8(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await NE(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw pvr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function pvr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function X8(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function Z8(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function eW(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var tW=J(()=>{"use strict";tr()});async function rW(e,t){return e.list("/api/v1/contact-groups",t)}async function nW(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function iW(e,t){return e.search("/api/v1/contact-groups/search",t)}async function oW(e,t){return e.post("/api/v1/contact-groups",t)}async function sW(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,xI(r,CZ))}async function aW(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var yAe=J(()=>{"use strict";an()});async function cW(e,t){return e.list("/api/v1/inventory-items",t)}async function lW(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function uW(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function fW(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&hvr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var dW,hvr,EAe=J(()=>{"use strict";Vi();dW=["ALL","AVAILABLE","FULLY_DRAWN"],hvr=/Inventory balance Not Found/i});async function pW(e,t){return e.list("/api/v1/custom-fields",t)}async function sO(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function hW(e,t){return e.search("/api/v1/custom-fields/search",t)}async function mW(e,t){return e.post("/api/v1/custom-fields",t)}function Avr(e){return e!==void 0&&mvr.every(t=>e[t]!==void 0)}function gvr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function yvr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function AW(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!Avr(n.appliesTo)){let i=await sO(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??yvr(i.data),n.appliesTo={...gvr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function gW(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var mvr,bAe=J(()=>{"use strict";mvr=["invoices","bills","customerCredits","supplierCredits","payments"]});var tl,BE,Evr,bvr,IAe,yW,EW,Ivr,Ta,iu,OE,sv,FE,CAe=J(()=>{"use strict";tl={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217). Required whenever this settings object is sent."}},required:["sourceCurrencyCode"]},BE={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field. Required unless resourceId is given; when resourceId is given, the organization's own name for that field is stored instead of this one."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition. Required unless customFieldName is given. When omitted, the field is matched by customFieldName (case-insensitive) and linked only if exactly one active custom field in the organization has that name."}}},Evr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},bvr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},IAe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},yW={type:"object",properties:{billingAddress:{...IAe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},EW={type:"object",properties:{billingAddress:{...IAe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...IAe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},Ivr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Ta={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:Ivr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},iu={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},OE={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},sv={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:BE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...Evr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...bvr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...yW,description:"Issuer identity and billing address (credit from)."},creditTo:{...EW,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...yW,description:"Seller identity and billing address."},billTo:{...EW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:BE},deliverySlipTemplateResourceId:{type:"string",description:"UUID of the delivery slip PDF template."},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...yW,description:"Seller identity and billing address."},billTo:{...EW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...yW,description:"Seller identity and billing address."},billTo:{...EW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},FE={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}}}});function wAe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function vAe(e){let t=e.updated??[],r=wAe(e.failed);return{...t.length===0&&r.length>0?{error:wvr}:{},updated:t,failed:r}}function Tat(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function xat(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=Tat(s);if(a)for(let c of Array.isArray(o)?o:[o])Sh(c)&&n.push(...xat(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function vvr(e){return Object.entries(e).map(([t,r])=>{let n=Tat(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function SAe(e,t,r){if(!Sh(t))return;let n=xat(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw ct(new nt(`${e} has no field ${i.join("; ")}. Fields: ${vvr(r)}. Nothing was changed.`))}function Svr(e){let t=sv[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function Dvr(e){let t=FE[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function Rvr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!Sh(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw ct(new nt(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!Sh(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw ct(new nt(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));SAe(`${e} line items`,a.attributes,t.fields)}}}function kat(e){if(av.includes(e))return;let t=IW.includes(e);throw ct(new nt(t?`${e} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${e} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${e} has no quick fix route. Transaction-level entities: ${av.join(", ")}.`))}async function lv(e,t,r){kat(t),SAe(`${t} quick fix`,r.attributes,Svr(t));let n=await e.post(`/api/v1/quick-fix/${Sc(av,t)}`,r);return vAe(n)}async function Tvr(e,t){try{return await IE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return CE(e,t);throw r}}async function Nat(e,t,r,n){kat(t);let i=DAe[t],o=async d=>i.tags(await Yo(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Rat)s.push(...await Promise.all(r.resourceIds.slice(d,d+Rat).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=Ki(s[f],n),h=JSON.stringify(p);a.set(h,{tags:p,resourceIds:[...a.get(h)?.resourceIds??[],d]})});let c=[],u=[];for(let{tags:d,resourceIds:f}of a.values())try{let p=await lv(e,t,{resourceIds:f,attributes:{...r.attributes,tags:d}});c.push(...p.updated),u.push(...p.failed)}catch(p){if(c.length===0)throw p;u.push(...f.map(h=>({resourceId:h,error:p instanceof Error?p.message:String(p)})))}return vAe({updated:c,failed:u})}async function aO(e,t,r){let n=Sc(cv,t),i=Dvr(t);i.entryKeys?Rvr(t,i,r.schedulerUpdates):SAe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return vAe(o)}var Cvr,_vr,bW,IW,av,cv,wvr,LE,_Ae,DAe,Rat,CW=J(()=>{"use strict";Vi();it();Wi();CAe();Nl();zg();lf();zx();Xx();Jg();rV();hV();tW();Hre();Cvr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],_vr=["journals","cash-entries"],bW=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],IW=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],av=[...Cvr,..._vr,...bW],cv=[...av,...IW],wvr="Nothing changed: every record failed. See failed for each reason.";LE=e=>e?.tags,_Ae=e=>e?.data?.tags,DAe={invoices:{noun:"invoice",get:(e,t)=>go(e,t),tags:LE},bills:{noun:"bill",get:(e,t)=>fo(e,t),tags:LE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>Ws(e,t),tags:LE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>Ks(e,t),tags:LE},journals:{noun:"journal",get:(e,t)=>vs(e,t),tags:LE},"cash-entries":{noun:"cash entry",get:(e,t)=>Tvr(e,t),tags:LE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Ww(e,t),tags:_Ae},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Kw(e,t),tags:_Ae},"subscription-schedules":{noun:"subscription",get:(e,t)=>NE(e,t),tags:_Ae},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Xw(e,t),tags:LE}},Rat=10});function _W(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=_W(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<kvr&&i.length<=Nvr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,_W(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function Oat(e,t,r){let n=Bvr(t);if(!n)return[];let i=Ovr(r);if(!i){if(Bat[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?Oat(o,s,i[o]):[])}function Fvr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function RAe(e,t,r={}){let n=Object.keys(e),i=[...new Set(n.flatMap(c=>Object.keys(e[c])))].sort(),o={},s=new Map;for(let c of i){let u=n.filter(y=>e[y][c]),d=new Map;for(let y of u){let b=Lvr(e[y][c]);d.set(b,[...d.get(b)??[],y])}let[[,f],...p]=[...d].sort((y,b)=>b[1].length-y[1].length),{description:h,...m}=r[c]??_W(e[f[0]][c]),A=p.length&&m.properties&&!r[c]?{...m,required:void 0,properties:Object.assign({},...[f,...p.map(([,y])=>y)].map(y=>_W(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[Bat[c],Fvr(u,n),...p.map(([,y])=>{let b=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(b.properties??b.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[b,E]of Oat(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(b))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function Pat(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>xvr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var xvr,Bat,kvr,Nvr,Bvr,Ovr,Lvr,Qvr,Pvr,uv,Fat,Lat,Qat,Mat,Uat,$at,TAe=J(()=>{"use strict";CAe();Nl();xvr={valueDate:"date",dueDate:"due date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",deliverySlipTemplateResourceId:"delivery slip template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},Bat={currencySettings:"sourceCurrencyCode alone takes the platform rate (not on schedules); add rateFunctionalToSource to set one.",taxCurrencySettings:"Cash entries: sourceCurrency; every other record: sourceCurrencyCode, always sent.",tags:`${jo.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}.",notes:"Printed; the form calls it Credit Notes.",internalNotes:'Not printed. The user says just "notes" and the record has printed notes too: ask which.'},kvr=2,Nvr=8;Bvr=e=>e.properties??e.items?.properties,Ovr=e=>e.properties??e.items?.properties;Lvr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),Qvr={tags:jo};Pvr=Object.entries(FE).filter(([,e])=>!e.entryKeys),uv=Object.entries(FE).filter(([,e])=>e.entryKeys),Fat=RAe({...sv},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",Qvr),Lat=RAe(Object.fromEntries(Pvr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),Qat=(()=>{let e=n=>uv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=uv[0],r=[...new Set(uv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>uv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${uv.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:RAe(Object.fromEntries(uv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Mat=[...new Set([...Object.keys(sv),...Object.keys(FE)])].map(e=>e.replace(/-/g," ")).join(", "),Uat=Pat(Object.values(sv)),$at=Pat(Object.values(FE).map(e=>e.fields))});function wW(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var xAe=J(()=>{"use strict"});function SW(){return sA.map(e=>`${e} sets ${fv[e].change.join(", ")}`).join("; ")}function Vat(e){let t={};for(let r of e)t[r]=Object.hasOwn(jat,r)?jat[r]:$vr.find(([n])=>n.test(r))?.[1]??qvr;return Object.keys(t).length>0?t:void 0}function Wat(e){if(!(e instanceof gr)||!e.endpoint.startsWith(Uvr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Yat,n))return;let{hint:i,repairTool:o,command:s}=Yat[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Jat.LINE_ITEMS?"line items":"records",...e.endpoint===vW?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function Hvr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function zvr(e){return typeof e=="string"&&sA.includes(e)}function Jvr(e,t){if(!zvr(e))throw new nt(`level must be one of ${sA.join(", ")}.`);let r=sA.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))fv[e][i].includes(s)||n.push(fv[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=fv[e];throw new nt(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Hat(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new nt(`${e} must be a JSON object, not ${n}.`)}async function RW(e,t,r){let n={filter:Hat("filter",r.filter),change:Hat("change",r.change)};Jvr(t,n);let i;try{i=await e.post(Jat[t],{filter:n.filter,change:n.change},et)}catch(u){throw Wat(u),u}let{data:o,...s}=i,a=Vat([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=Hvr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function NAe(e,t){return{error:`${t} ${Xat}`,outcome:"UNKNOWN",previewId:e,next:Kat}}function Wvr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return NAe(e,"The apply answered without a per-record result.");let i=wAe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=Vat(Object.keys(o)),a=o[jvr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Vvr}:a==="UNKNOWN"?{error:Xat}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Kat:Gvr},failed:i.slice(0,kAe),...i.length>kAe?{failedNotShown:i.length-kAe}:{},data:r}}async function TW(e,t,r=Yvr){let n;try{n=await e.post(vW,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=Wat(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw ct(i);return NAe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof zp)throw ct(i);let o=i instanceof Error?i.message:String(i);return NAe(t,`No answer arrived from the apply (${o}).`)}return Wvr(t,n)}var zat,sA,Jat,vW,Uvr,Gat,qat,fv,jat,$vr,qvr,jvr,Yvr,DW,kAe,pv,Ton,dv,Yat,Kat,Gvr,Vvr,Xat,BAe=J(()=>{"use strict";Vi();CW();dP();it();Wi();tr();xAe();zat=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],sA=["TRANSACTIONS","LINE_ITEMS"],Jat={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},vW="/api/v1/ledger/find-fix/apply",Uvr=vW.slice(0,vW.lastIndexOf("/")+1),Gat={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},qat=["types","resourceIds","reference","valueDate","contactResourceId"],fv={TRANSACTIONS:{filter:qat,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...qat,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};jat={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},$vr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],qvr="Not described by this client version; read the records that carry it.";jvr="OUTCOME_UNKNOWN",Yvr=25e3,DW=3e5,kAe=50,pv=12,Ton=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${pv}}(?![A-Za-z0-9_-])`,"i"),dv=e=>e.resourceId?` (${e.resourceId})`:"",Yat={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${dv(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${dv(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${dv(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${dv(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${dv(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${dv(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};Kat="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",Gvr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",Vvr="Nothing changed: every record in the preview failed.",Xat="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function xW(e,t){return e.list("/api/v1/nano-classifiers",t)}async function QE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function kW(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function cO(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function lO(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function NW(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Kvr(e,t):{};let{data:n}=await QE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:ect(n)}async function Kvr(e,t){let{data:r}=await QE(e,t);return ect(r)}function ect(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function BW(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}function tct(e,t="classifierConfig"){if(e==null)return;if(!(Array.isArray(e)&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.resourceId=="string")))throw ct(new nt(`${t} takes a list of classifiers, each with its resourceId: an entry sets that classifier, { resourceId, deleted: true } removes it, and classifiers it does not name stay. Nothing was changed.`));return e.length>0?e:void 0}function rct(e,t){let r=new Map((Array.isArray(e)?e:[]).map(n=>[n?.resourceId,DP(n)]));for(let n of t)n.deleted===!0?r.delete(n.resourceId):r.set(n.resourceId,DP(n));return[...r.values()]}var Zat,OAe=J(()=>{"use strict";Wi();it();af();Zat=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function OW(e,t){return e.post("/api/v1/export-records",t,et)}async function FW(e,t){return e.post("/api/v1/export-records/preview",t,et)}async function LW(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var FAe=J(()=>{"use strict";tr()});function QW(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function sct(e,t,r,n=!1){if(!Array.isArray(e))throw new ue(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new ue(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new ue(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new ue(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function PW(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function MW(e,t,r){return QW(t,ict),Xi(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Sc(lp,t)}/${encodeURIComponent(r)}/approve`,void 0,Yke)}async function UW(e,t,r){return QW(t,ict),sct(r,Xvr,"bulk approve",!0),r.forEach(n=>Xi(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Sc(lp,t)}/bulk-approve`,{resourceIds:r},Hke)}async function $W(e,t,r,n){QW(t,oct),Xi(r,"resourceId","Pass the document resourceId."),act(n);let i=await e.post(`/api/v1/${Sc(PE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:t0r(i)}}}async function qW(e,t,r,n){return QW(t,oct),act(n),sct(r,Zvr,"bulk request changes"),r.forEach(i=>Xi(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(e0r(t),{resourceIds:r,message:n})}function e0r(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Sc(nct,e)}/bulk-request-changes`}function act(e){if(!e||e.trim().length===0)throw new ue("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function t0r(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var lp,nct,PE,ict,oct,Xvr,Zvr,LAe=J(()=>{"use strict";it();tr();lp=["invoices","bills","customer-credit-notes","supplier-credit-notes"],nct=[...lp,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],PE=[...nct,"claims"],ict=new Set(lp),oct=new Set(PE);Xvr=100,Zvr=500});function r0r(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${cct(t)}:${cct(r)}:${n}`}function cct(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function QAe(e){if(!lct.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...lct].join(", ")}`)}async function uct(e,t,r){return QAe(t),Xi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function dct(e,t,r,n){return QAe(t),Xi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function fct(e,t,r,n,i){if(QAe(t),Xi(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new ue('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??r0r(t,r,n)}})}async function pct(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var lct,hct=J(()=>{"use strict";it();lct=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function n0r({fromPeriod:e,toPeriod:t},r){for(let[n,i]of[["fromPeriod",e],["toPeriod",t]])if(i!==void 0){if(!Number.isInteger(i)||i<1)throw new nt(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new nt("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new nt(`${n} ${i} is past the last period (${r}). Send a period from 1 to ${r}.`)}if(e!==void 0&&t!==void 0&&e>t)throw new nt(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function jW(e,t,r){let n=e.length;if(n0r(t,e[n-1]),n===0)return{start:0,end:0,window:{totalPeriods:0}};let i=t.fromPeriod===void 0?0:e.filter(u=>u<t.fromPeriod).length,o=t.toPeriod===void 0?n:e.filter(u=>u<=t.toPeriod).length,s=o===0&&t.toPeriod!==void 0,a=s?Math.min(t.toPeriod-(t.fromPeriod??1)+1,n,r):Math.min(o,i+r);if(a<=i)throw new nt(`No period falls in that range: the schedule runs from period ${e[0]} to ${e[n-1]}.`);let c={totalPeriods:n,fromPeriod:e[i],toPeriod:e[a-1]};if(i>0||a<n){let u=[`Showing periods ${e[i]} to ${e[a-1]} of ${n}.`];a<n&&u.push(`Periods ${e[a]} to ${e[n-1]} are not shown: call again with fromPeriod ${e[a]} to read the next range (at most ${r} periods come back per call).`),i>0&&u.push(`Periods ${e[0]} to ${e[i-1]} are not shown: call again with fromPeriod ${e[0]} to read them.`),c.note=u.join(" ")}return s&&(c.note=`Periods ${t.fromPeriod??1} to ${t.toPeriod} come before this schedule, which starts at period ${e[0]}. Showing the first periods instead. ${c.note??""}`.trim()),{start:i,end:a,window:c}}function hv(e,t={},r=uO){let n=e.data,i=ME(n.rows),{start:o,end:s,window:a}=jW(PAe(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function YW(e,t={},r=uO){let n=e.data,i=ME(n.rows),o=h=>h.rowType==="PERIOD",s=i.findIndex(o),a=i.map(o).lastIndexOf(!0),c=s===-1?[]:i.slice(s,a+1),{start:u,end:d,window:f}=jW(PAe(c),t,r);if(s===-1)return{...e,data:{...f,...n}};let p=[...u===0?i.slice(0,s):[],...c.slice(u,d),...d===c.length?i.slice(a+1):[]];return{...e,data:{...f,...n,rows:p}}}function mct(e,t,r,n,i){let o=e.data,s=ME(o[t]),a=s.reduce((h,m)=>h+ME(m[r]).length,0),{start:c,end:u,window:d}=jW(Array.from({length:a},(h,m)=>m+1),n,i);if(a===0)return{...e,data:{...d,...o}};let f=0,p=[];for(let h of s){let m=ME(h[r]),A=m.slice(Math.max(c-f,0),Math.max(u-f,0));A.length>0&&p.push({...h,[r]:A}),f+=m.length}return{...e,data:{...d,...o,[t]:p}}}function yd(e,t={},r=uO){let n=e.data,i=ME(n.periods),{start:o,end:s,window:a}=jW(PAe(i,"period"),t,r);if(i.length===0)return{...e,data:{...a,...n}};let c=i[o].startDate,u=i[s-1].endDate,d=f=>typeof f.toDate!="string"||typeof f.fromDate!="string"||typeof c!="string"||typeof u!="string"||f.toDate>=c&&f.fromDate<=u;return typeof a.note=="string"&&(a.note+=" The timeline lists only the segments that touch these periods."),{...e,data:{...a,...n,periods:i.slice(o,s),timeline:ME(n.timeline).filter(d)}}}var uO,ME,PAe,HW,zW,mv=J(()=>{"use strict";Wi();uO=60;ME=e=>Array.isArray(e)?e:[],PAe=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);HW=(e,t={},r=uO)=>mct(e,"depreciationScheduled","depreciation",t,r),zW=(e,t={},r=uO)=>mct(e,"amortizationScheduled","amortization",t,r)});async function UE(e,t){return e.get(`/api/v1/loans/${t}`)}async function JW(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function GW(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function VW(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},Kke)}async function WW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names loan ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await UE(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function KW(e,t){await e.delete(`/api/v1/loans/${t}`)}async function XW(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},hZ)}async function ZW(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},hZ)}async function e4(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function t4(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function r4(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function n4(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function i4(e,t){return e.post("/api/v1/loans/preview-schedule",t,et)}async function o4(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,et)}async function s4(e,t){return ht(t,"loans",500,"loans"),qo(t,Act),En(e,"/api/v1/loans/bulk-upsert","loans",t)}async function a4(e,t){return ht(t,"loans",500,"loans"),qo(t,i0r),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ct(new ue(`loans[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that loan. Bulk update does not take tags: change them with update_loan (clio loans update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/loans/bulk-update","loans",t)}async function c4(e,t,r,n,i){let o=dO[t];if(i){if(!o.calculate)throw new Error(`Loan event ${t} has no preview.`);let s=Object.fromEntries(Object.entries(n).filter(([a])=>!o.recordOnly?.includes(a)));return e.post(o.calculate,{...s,resourceId:r},et)}return e.post(o.record(r),{...n,resourceId:r},Xke)}var Act,i0r,dO,MAe=J(()=>{"use strict";an();it();tr();Act=["drawdownDate","trackingStartDate","firstRepaymentDate"],i0r=[...Act,"capitalizationStartDate","capitalizationEndDate"];dO={drawdown:{calculate:"/api/v1/loans/calculate-drawdown",record:e=>`/api/v1/record-drawdown/loans/${e}`},prepayment:{calculate:"/api/v1/loans/calculate-prepayment",record:e=>`/api/v1/prepay/loans/${e}`},rateChange:{calculate:"/api/v1/loans/calculate-rate-change",record:e=>`/api/v1/change-rate/loans/${e}`},capitalization:{calculate:"/api/v1/loans/calculate-capitalization",record:e=>`/api/v1/capitalize-interest/loans/${e}`},paymentHoliday:{calculate:"/api/v1/loans/calculate-payment-holiday",record:e=>`/api/v1/payment-holiday/loans/${e}`},restructure:{calculate:"/api/v1/loans/calculate-restructure",record:e=>`/api/v1/restructure/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},settlement:{calculate:"/api/v1/loans/calculate-settlement",record:e=>`/api/v1/settle/loans/${e}`},forgiveness:{calculate:"/api/v1/loans/calculate-forgiveness",record:e=>`/api/v1/forgive/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},conversion:{calculate:"/api/v1/loans/calculate-conversion",record:e=>`/api/v1/convert-to-shares/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},refinance:{record:e=>`/api/v1/refinance/loans/${e}`},reclassifyAsCurrent:{record:e=>`/api/v1/reclassify-as-current/loans/${e}`},undo:{record:e=>`/api/v1/undo-event/loans/${e}`}}});function Av(e){ht(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new ue(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!jFe(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!o0r.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new ue(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function l4(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},et);return{data:a0r(r.data)}}function s0r(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function a0r(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(s0r),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function u4(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function d4(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var o0r,UAe=J(()=>{"use strict";it();fee();an();tr();o0r=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function bct(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new ue("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function $Ae(e,t){if(!e||typeof e!="object")throw new ue(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new ue(`${t}.lineItems array is empty.`);if(n.length>500)throw new ue(`max 500 ${t}.lineItems per call.`);qo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&qo([i],["valueDate"])}async function p4(e,t,r=qAe){return e.post("/api/v1/search-magic-reconciliation",t,{...et,timeoutMs:r})}function f4(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function d0r(e){let t=f4(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=f4(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function f0r(e){return e?e.value>=(e.from==="confidenceScore"?c0r:l0r)?"high":e.value>=u0r?"medium":"low":"low"}function h0r(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(gct,t))return;let r=gct[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function aA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function yct(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function m0r(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>yct({account:aA(n?.account),taxProfile:aA(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!aA(e.contact)&&!aA(e.account)&&!aA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return yct({contact:aA(e.contact),account:aA(e.account),taxProfile:aA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function Ict(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>b0r(c,h??{},u.length-1,t)).sort(A0r),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function A0r(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function g0r(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return vc.test(t)?t:void 0}function y0r(e){let{recommendationId:t,...r}=e;return r}function E0r(e,t,r){return!t||!r?t:e===$E.learnedPrediction?{...t,recommendationId:r}:e===$E.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function b0r(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=f4(t.matchScore),s=f4(t.confidenceScore),a=d0r(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=$E.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=$E.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let F=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,G=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,j=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;F&&G&&j&&(m=$E.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:F,predictedPayload:G,predictedPayloadSchemaVersion:j});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let F=t.actionShortcut??{},G=typeof F.resourceId=="string"?F.resourceId:void 0;G&&(m=$E.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=E0r(m,A,g0r(t)),y=m?f0r(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==$E.withPayments||b,T=h0r(t),D=!m||!g?"NO_PLAN":T?p0r[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",k=m0r(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:g,confidenceTier:y,autoCommitEligible:D===void 0,...D?{checkpointReason:D}:{},...k?{proposedPosting:k}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:T===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(y0r(t))}`}}function I0r(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function C0r(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await fo(e,i):await go(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${RE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function Cct(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,Ect);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await iC(e,t,{filter:{resourceId:{in:u}},limit:Ect}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${RE(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return I0r(u,f,await C0r(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function h4(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,zs)}async function m4(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,zs)}async function A4(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,zs)}async function g4(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,zs)}async function y4(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,zs)}async function E4(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,zs)}async function b4(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,zs)}async function I4(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,zs)}async function C4(e,t){return e.post("/api/v1/reconciliations/with-payments",t,zs)}async function _4(e,t){return e.post("/api/v1/reconciliations/match-to-transaction",t,zs)}async function w4(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,zs)}async function v4(e,t){return e.post("/api/v1/reconciliations/magic-match",t,zs)}async function S4(e,t){return e.post("/api/v1/reconciliations/reset",t)}var $E,qAe,c0r,l0r,u0r,p0r,gct,Ect,D4=J(()=>{"use strict";Rg();TE();it();lf();an();zg();tr();$E={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},qAe=6e4;c0r=.9,l0r=.95,u0r=.7;p0r={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},gct={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};Ect=25});function oa(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Qo(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:jAe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=jAe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=jAe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function jAe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function ts(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=oa(e,t,n),a=Qo(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var xa,rl,_o,ou,_ct=J(()=>{"use strict";xa=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],rl=[...xa],_o=xa.filter(e=>e.field!=="dueDate"),ou=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function Ed(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=_c(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function R4(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=OI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var wct=J(()=>{"use strict";af()});var YAe=J(()=>{"use strict";_ct();af();wct()});var fO,T4,rs,io,HAe=J(()=>{"use strict";fO="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",T4=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],rs="If the result says it runs in the background, do not poll: its result arrives by itself.",io=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${rs} PARTIAL_SUCCESS: errorDetails.`});function Sct(e){return _0r.get(e)}function Dct(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!x4.has(o));return n.length===0?[]:Li.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Li,vct,x4,_0r,bd=J(()=>{"use strict";HAe();TAe();Li=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Fourteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), match_to_transaction (several entries to ONE open document), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side, except match_to_transaction, which needs transactionAmount + currencySettings with a rate when the document and bank account currencies differ or the bank account is not in the base currency. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights. Fixed asset register reports are in register_reports.",groups:["operational_reports","exports"]},{name:"register_reports",title:"Register Reports",description:"Register reports: fixed asset register summary by account, type, category or active/closed-out/disposed state (asset register roll-forward over a period), fixed asset register vs general ledger reconciliation (does the register agree with the GL), deferrals summary (prepaid and deferred revenue roll-forward) and deferrals reconciliation (does the prepaid register agree with the GL), lease register summary (IFRS 16 lease note, lease liability roll-forward) and lease register vs general ledger reconciliation (rent coded to the lease liability account). Loan reports: borrowings note summary, loan roll-forward, related-party (director, shareholder) loan balances, loan interest cost, maturity analysis (liquidity note), loan register vs ledger reconciliation.",groups:["register_reports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tracking tags (tags): transaction-level labels for filtering reports. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Nano classifiers: dimensions (department, cost center, project) per line item, or on a register record as a whole. List, search, create, update, delete classifiers and their classes. Used for dimensional reporting. Not tracking tags (use the tags_and_custom_fields namespace). Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. For what-if questions and topics with no register; to keep a lease, loan, prepaid or deferred revenue use its register. Keywords: calculate, what-if, monthly payment, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate, set up to repeat every month.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"],channelToolsDescription:"Check the progress of background tasks a request started, add to a waiting one, or cancel it."},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update (one or bulk), discard, sell, transfer, undo disposal, close out (stop depreciating, keep the asset) and reopen. Also: depreciation, asset register. Depreciation schedules, totals, eligible bill lines and asset types are in fixed_asset_schedules.",groups:["fixed_assets"]},{name:"fixed_asset_schedules",title:"Fixed Asset Schedules & Totals",description:"Read-only fixed asset views. Show one asset's depreciation by month and year, net book value, asset register totals as at a date, disposal totals (gain/loss), eligible bill lines to register as assets, asset types. Check custom depreciation ranges; calculate disposal (accumulated depreciation, net book value) before selling or discarding.",groups:["fixed_asset_schedules"]},{name:"deferrals",title:"Deferrals (Prepaid & Deferred Revenue)",description:"Deferrals register: prepaid expense, prepayment, deferred revenue, unearned revenue. Spread a bill over months, recognise an invoice over months (amortization, release schedule). Search, create, update, delete, stop amortising early (close out) and undo it, totals as at a date, schedule, eligible bill or invoice lines, deferral types and deferral accounts (mark the accounts first), bulk create and update.",groups:["deferrals"]},{name:"leases",title:"Leases (IFRS 16)",description:"Leases under IFRS 16: put an office rent lease on the books (right-of-use asset, ROU, and lease liability, current and non-current), hire purchase (flat rate to monthly discount rate), short-term or low-value exemption. Search, create, update, delete, close out, terminate lease (preview the gain or loss first) and undo either; lease schedule, liability totals as at a date, rent schedule preview, lease types.",groups:["leases"]},{name:"loans",title:"Loans (Borrowings)",description:"Loans and borrowings register: record a new bank loan, loan, borrowing, bank loan, term loan, director's loan (revolving credit and loans given are not in the register), instalment / installment loan. Search, create, update (one or bulk), delete, close out. What do we owe a lender or the bank: outstanding principal, current and non-current at a date, the repayment schedule, an on-demand loan ledger (an on-demand loan has no schedule, is all current and posts no interest), loan types, preview the monthly payment. Loan changes (drawdown, prepay, rate change, settle) are in loan_events; loan reports are in register_reports.",groups:["loans"]},{name:"loan_events",title:"Loan Events",description:"Events on an existing loan: drawdown, prepay or extra repayment, rate change, payment holiday, capitalize interest, restructure, refinance, settle / payoff, forgive / write off a loan, convert loan to shares, covenant breach (reclassify as current), undo loan event, balance after a missed payment. preview: true calculates the figures and saves nothing.",groups:["loan_events"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${Mat}. On a record: ${Uat}. On lines: ${$at}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${T4.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"collab",title:"Collaboration",description:"Comment threads on bills, invoices, credit notes and bank records: list threads and comments, add a reply or start a thread, mention a teammate, update or delete your own comment, resolve a thread. Notifications: list unread mentions and comments, mark one read or unread, mark all read.",groups:["collaboration"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],vct=[{name:"dashboard_page",title:"Dashboard Page",description:"The dashboard page the user is viewing, in their browser.",groups:["page"],channelToolsDescription:"Act on that page: read where the user is (screen, open modal, loading, unsaved changes) and move their open page to another screen or record."}],x4=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),_0r=new Map(Li.flatMap(e=>e.groups.map(t=>[t,e.name])))});function Id(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function w0r(e){let t=Rct.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(Id(r),n);for(let r of e.enum??[])t.set(Id(r),r);Rct.set(e,t)}return t}function Tct(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=Id(e);if(!r)return null;let n=w0r(t).get(r);return n!==void 0&&n!==e?n:null}function v0r(e){let t=xct.get(e);return t||(t=new Map(Object.keys(e).map(r=>[Id(r),r])),xct.set(e,t)),t}function S0r(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function D0r(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function zAe(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=v0r(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=Id(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?S0r(d):D0r(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=Tct(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=Tct(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=bee(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=zAe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=zAe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function kct(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:zAe(t,e.params,"",r),coercions:r}}function Nct(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var Rct,xct,JAe=J(()=>{"use strict";FU();Rct=new WeakMap;xct=new WeakMap});function gv(e){let t=new Set,r=[];for(let n of e)for(let i of su(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function pO(){return Li.map(e=>{let t=gv(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function R0r(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function T0r(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function cA(e,t=!1){let r=lA(void 0).length,n=Li.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:T0r(r)}:e&&i!==void 0?{packaging:R0r(e,i,r)}:{},map:pO(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var k4=J(()=>{"use strict";bd();au()});function N4(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=N4(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=N4(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function cu(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=N4(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function hO(e){return{name:e.name,description:e.description,input_schema:cu(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var yv=J(()=>{"use strict"});function mO(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function GAe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function B4(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&mO(e),idempotentHint:e.readOnly,openWorldHint:GAe(e)}}function k0r(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function N0r(e){let t=k0r(e);return!t||x0r.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!x4.has(n)).length===0}function VAe(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function WAe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?WAe(o,`${i}.`):[]]})}function O0r(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
662
|
+
`)),null)}catch{return null}}async function JB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??lwr,c=n.minBm25??uwr;if(i==="bm25"||!t)return _E(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await $me(r);return m?Rst(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):_E(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([$me(r),Promise.resolve(_E(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Rst(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return kst(p,h,o)}function Rst(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),o=new Map(e.articles.map(c=>[c.id,c])),s=[];for(let c of t.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=Tst(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function kst(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(vst+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<t.length;o++){let s=t[o],a=1/(vst+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function qme(e){return e!==null&&!!xst()}var awr,cwr,vst,lwr,uwr,AV,Sst,gV,Dst,yV=J(()=>{"use strict";HB();awr="text-embedding-3-small",cwr=2e3,vst=60,lwr=.3,uwr=1.5,AV=null,Sst=null,gV=null,Dst=!1});async function Nst(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof t.limit=="number"&&!Number.isNaN(t.limit)?t.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof t.section=="string"?t.section:void 0,s=t.mode??"hybrid";try{let a=jB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:zB(),u=await JB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(Mme(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Bst(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:fwr}async function EV(e,t={}){let r=String(e??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Bst())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(t.limit)),typeof t.section=="string"&&t.section&&i.searchParams.set("section",t.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(pwr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return hwr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function hwr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function jme(e,t={}){return process.env.CLIO_DAEMON==="1"||YB()?Nst(e,t):EV(e,t)}var fwr,pwr,Ost=J(()=>{"use strict";HB();yV();fwr="https://mcp.jaz.ai/help-center/search",pwr=4e3});var Yme=J(()=>{"use strict";HB();yV();Ost();HB()});async function eA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function tA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var GB=J(()=>{"use strict";an()});async function bV(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Wt(t.currency),taxCurrency:Wt(t.taxCurrency)},rNe)}var Hme=J(()=>{"use strict";it();tr()});async function IV(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function CV(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function VB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function _V(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var zme=J(()=>{"use strict"});function mwr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Zw(e,t){return e.post("/api/v1/jots",{entries:t.map(mwr)})}async function wV(e,t){return e.post("/api/v1/jots/search",t,et)}async function Fst(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var vV=J(()=>{"use strict";tr()});async function Lst(e,t){return e.post("/api/v1/agents/memories",t)}async function Jme(e,t){return e.post("/api/v1/agents/memories/forget",t)}var Qst=J(()=>{"use strict";tr()});function SV(){return process.env.ENABLE_MEMORY==="true"}function Gme(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Pst(e){return!SV()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Vme=J(()=>{"use strict"});import{createHash as Awr}from"node:crypto";function Dwr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:$st.some(r=>t.includes(r))?[null,"directive_invalid"]:Ust.test(t)?[null,"directive_invalid"]:Cwr.test(t)?[null,"directive_contains_url"]:_wr.test(t)?[null,"directive_contains_email"]:[t,null]}function Rwr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>wwr?[null,"match_condition_too_long"]:$st.some(r=>t.includes(r))?[null,"match_condition_invalid"]:Ust.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function Twr(e){return e==null?[null,null]:Number.isInteger(e)?e<vwr||e>Swr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function xwr(e,t,r,n,i,o,s,a){if(e)return Awr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function kwr(e){Promise.resolve().then(()=>(AD(),mD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Hst(e,t,r){let n=t.action,i=t.category,o=bwr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(kwr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=e.memoryTurn,f=Pst(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>gwr||!Iwr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[b,E]=Dwr(t.directive);if(E)return u(E);p=b;let[C,w]=Twr(t.importance);if(w)return u(w);h=C}let[m,A]=Rwr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=ywr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let b={gtid:g};d.quote&&(b.quote=d.quote.slice(0,Ewr));let E=xwr(g,n,o,i,s,p,t.confirms_key,t.replaces_key),C={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...t.replaces_key?{replacesKey:t.replaces_key}:{},...t.confirms_key?{confirmsKey:t.confirms_key}:{},pending:t.pending===!0,source:r?.source??"TOOL",provenance:b,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await Wme(()=>Lst(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let b={category:i,key:s,scope:o};y=await Wme(()=>Jme(e.client,b))}else{let b={forgetAll:!0};y=await Wme(()=>Jme(e.client,b))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function Wme(e){try{let t=await e(),r=t&&typeof t=="object"&&t.data&&typeof t.data=="object"?t.data:t??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(t){return t instanceof gr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var Ust,$st,gwr,ywr,Ewr,qst,jst,Yst,bwr,Iwr,Cwr,_wr,wwr,vwr,Swr,zst=J(()=>{"use strict";Qst();Vi();Vme();Vme();Ust=/[\x00-\x1f\x7f]/,$st=["{{","}}","```","<",">"],gwr=120,ywr=3,Ewr=140,qst=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],jst=["set","forget","forget_all"],Yst=["this_org","all_orgs"],bwr={this_org:"ORG_USER",all_orgs:"USER"},Iwr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Cwr=/https?:\/\//i,_wr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,wwr=255,vwr=0,Swr=100});async function DV(e,t){return e.list("/api/v1/organization-users",t)}async function RV(e,t){return e.search("/api/v1/organization-users/search",t)}async function ev(e,t){return e.post("/api/v1/organization-users/invite",t)}async function TV(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function xV(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var Kme=J(()=>{"use strict"});async function kV(e,t){return e.get(`/api/v1/payments/${t}`)}async function NV(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Wt(r.currency)})}async function BV(e,t){await e.delete(`/api/v1/payments/${t}`)}function OV(e){return(t,r)=>t.post(`/api/v1/${Nwr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Wt(n.currency)}))},zke)}var Nwr,$nn,Jst,qnn,jnn,Xme=J(()=>{"use strict";it();tr();Nwr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};$nn=OV("saleBulk"),Jst=OV("saleBatch"),qnn=OV("purchaseBulk"),jnn=OV("purchaseBatch")});async function sp(e,t,r,n,i,o=tNe){let s;try{s=t==="POST"?await e.post(r,n,o):t==="PUT"?await e.put(r,n,o):await e.delete(r,void 0,{...o,body:n})}catch(c){throw c instanceof gr?c.status<500&&c.status!==401?ct(c):new nf(`${t} ${r} \u2192 ${c.status}. The write may or may not have happened; it was not sent again.`,r,o.readBack,{cause:c}):c instanceof zp?ct(c):c}let a=s?.data;if(!i(a))throw new nf(`${t} ${r} answered without the record. The write may or may not have happened; it was not sent again.`,r,o.readBack);return a}function LV(e,t,r){try{Xi(e,t,r)}catch(n){throw ct(n)}}function wE(e){return LV(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function QV(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function PV(e,t){return sp(e,"POST",Bwr,t,rA)}async function MV(e,t,r){return sp(e,"PUT",`/api/v1/unapplied-payments/${wE(t)}`,r,rA)}async function UV(e,t,r){return sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/activate`,{hash:r},rA)}async function $V(e,t,r,n){return sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/attributions`,{hash:r,attributions:n},rA)}async function qV(e,t,r,n){return LV(n,"paymentResourceId","Pass the payment record resourceId."),sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/payments`,{hash:r,paymentResourceId:n},rA)}async function jV(e,t,r,n){return LV(r,"childResourceId","Pass the payment record resourceId from the children list."),sp(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}/children/${encodeURIComponent(r)}`,{hash:n},rA)}async function YV(e,t,r){return sp(e,"DELETE",`/api/v1/unapplied-payments/${wE(t)}`,{hash:r},rA)}async function HV(e,t,r){return sp(e,"POST",`/api/v1/unapplied-payments/${wE(t)}/unbatch`,{hash:r},rA)}async function zV(e,t){return LV(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),sp(e,"POST",Owr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,zs)}var Bwr,Owr,FV,Gst,Vst,rA,Zme=J(()=>{"use strict";Vi();tr();dP();it();Bwr="/api/v1/unapplied-payments",Owr="/api/v1/reconciliations/unapplied-payment",FV=["SALE","PURCHASE"],Gst=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Vst=["AMOUNT","PERCENTAGE"];rA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function JV(e,t,r={},n=eAe){let i=Fwr.has(t)?`/api/v1/${Sc(Wst,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=Hg.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...Hg.keys()].join(", ")}.`);let A=await Tf(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...et,timeoutMs:n,emptyBodyOk:!0});if(c==null)throw new ue(`${t} returned no file (HTTP 200, empty answer). This is how the export answers a report template it cannot use: one that does not exist, or one that is not a ${a??"matching"} template. Pass \`template\` (a name or resourceId) and it is checked first.`);let u=c?.data,d=Array.isArray(u)?{...c,data:u[0],...u.length>1?{files:u}:{}}:c,f=d?.data?.fileType,p=d?.data?.fileUrl,m=typeof f=="string"?f.toUpperCase()==="PDF":typeof p=="string"&&(A=>{try{return/\.pdf$/i.test(new URL(A).pathname)}catch{return!1}})(p);return r.outputFormat==="PDF"&&(typeof p=="string"||typeof f=="string")&&!m?{...d,formatDowngraded:`PDF was requested but ${t} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...WB].join(", ")}.`}:d}var Wst,Fwr,eAe,WB,Kst,tAe=J(()=>{"use strict";tr();it();Ux();Hu();Wst=["statement-of-account-export"],Fwr=new Set(Wst),eAe=9e4,WB=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register","ar-details-report","ap-details-report"]),Kst={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as Lwr}from"node:crypto";import{writeFile as Qwr,mkdir as Pwr}from"node:fs/promises";import{dirname as Mwr,isAbsolute as Uwr,join as $wr}from"node:path";async function GV(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},et)}async function KB(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function tv(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Xst(e){return`query-export-${e.slice(0,8)}.csv`}function rAe(e){return Lwr("sha256").update(e).digest("hex").slice(0,16)}async function VV(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=rAe(t),o=await KB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await tv(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await tv(e,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!Uwr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??$wr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Pwr(Mwr(p),{recursive:!0}),await Qwr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}function WV(e,t){let{agentSkillsDoc:r,...n}=e,i=t?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new ue(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function rv(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return t}var nAe=J(()=>{"use strict";it();tr()});async function gi(e,t,r){let n=await e.get(`/api/v1/${KV[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function XV(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),i.attachmentType&&o.append("attachmentType",i.attachmentType),e.postMultipart(`/api/v1/${KV[r]}/${n}/attachments`,o)}async function ZV(e,t,r,n){return e.delete(`/api/v1/${KV[t]}/${r}/attachments/${n}`)}var KV,el,XB,nA=J(()=>{"use strict";KV={invoices:"invoices",bills:"bills",journals:"journals",scheduled_journals:"scheduled/journals","customer-credit-notes":"customer-credit-notes","supplier-credit-notes":"supplier-credit-notes","sale-quotes":"sale-quotes","sale-orders":"sale-orders","purchase-requests":"purchase-requests","purchase-orders":"purchase-orders","fixed-assets":"fixed-assets",deferrals:"deferrals",leases:"leases",loans:"loans","cash-in-entries":"cash-in-entries","cash-out-entries":"cash-out-entries","cash-transfers":"cash-transfers"},el=Object.keys(KV),XB=["sale-quotes","sale-orders","purchase-requests","purchase-orders","fixed-assets","deferrals","leases","loans","cash-in-entries","cash-out-entries","cash-transfers"]});function Gwr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&Jwr.some(n=>r.startsWith(n)))}async function ap(e){try{return await e}catch(t){throw t instanceof gr&&t.status===401&&Gwr(t)&&(t.refusal=zwr),t}}function Zst(e,t,r){return Xi(e,t,r),e.toLowerCase()}function nv(e,t){return{type:Sc(iAe,e,"entityType"),record:Zst(t,"entityId",qwr)}}function ZB(e){FZ(e,"threadId",Ywr)}function eat(e){FZ(e,"commentId",Hwr)}function iv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:Zst(e.bankAccountResourceId,"bankAccountResourceId",jwr)}}async function tat(e,t,r,n={}){let{type:i,record:o}=nv(t,r),s={...iv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return ap(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function rat(e,t,r,n,i={}){let{type:o,record:s}=nv(t,r),a={...iv(i),limit:i.limit,offset:i.offset};return ZB(n),ap(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function nat(e,t,r,n,i){let{type:o,record:s}=nv(t,r),a=iv(i);return n.threadId!==void 0&&ZB(n.threadId),(await ap(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...eNe,query:a}))).data}async function iat(e,t,r,n,i,o,s){let{type:a,record:c}=nv(t,r),u=iv(s);return ZB(n),eat(i),(await ap(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function oat(e,t,r,n,i,o){let{type:s,record:a}=nv(t,r),c=iv(o);return ZB(n),eat(i),(await ap(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function sat(e,t,r,n,i){let{type:o,record:s}=nv(t,r),a=iv(i);return ZB(n),(await ap(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function aat(e,t={}){return ap(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function cat(e,t,r){return tBe(t,"Get it from list_notifications."),(await ap(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function lat(e){return(await ap(e.post("/api/v1/collaboration/notifications/read-all"))).data}var iAe,qwr,jwr,Ywr,Hwr,zwr,Jwr,uat=J(()=>{"use strict";Vi();it();tr();iAe=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],qwr="Pass the resourceId of the bill, invoice, credit note or bank record.",jwr="Pass the resourceId of the bank account that holds the bank record.",Ywr="Get it from list_comment_threads.",Hwr="Get it from list_comments or list_comment_threads.",zwr={code:"USER_CREDENTIAL_REQUIRED",hint:"Comments and notifications act as a user, so the credential must name an active member of the organization. A service or organization key with no user is refused with this 401. Use a user credential: sign in with `clio auth login`, a personal access token, or an API key a member created."},Jwr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Lo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var ov=J(()=>{"use strict"});async function e8(e,t){return e.post("/api/v1/claims/conversion/preview",t,et)}async function t8(e,t){if(t.idempotencyKey&&/^CONV[:-]/.test(t.idempotencyKey))throw new ue('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return e.post("/api/v1/claims/conversion/commit",t,t.idempotencyKey?void 0:yP)}var eO,oAe=J(()=>{"use strict";it();tr();eO=["POST","POST_AND_RECORD"]});async function r8(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,Jke)}async function n8(e,t){return e.search("/api/v1/employees/payouts/search",t)}var dat,sAe=J(()=>{"use strict";it();tr();dat=["REIMBURSEMENT","ADVANCE"]});async function i8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var aAe=J(()=>{"use strict"});function cAe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}function lAe(e){let t=e.summary;if(t.uploadable>0)return{};let r={...t.skippedExtensions,...t.skippedReasons},n=Object.keys(t.skippedReasons??{}).length;if(t.total===0)return{hint:`No files found in ${e.source}. Check the folder or link is not empty.`};if(t.needClassification>0){let u=e.folders.filter(f=>f.documentType==="UNKNOWN").map(f=>`${f.folder||"(root)"}/ (${f.count})`).join(", "),d=t.skipped>0?` ${t.skipped} other file(s) were skipped: ${fat(r)}.`:"";return{hint:`${t.needClassification} file(s) are in folders I could not classify \u2014 ${u}. Pass \`type\` to force one type for all of them, or rename the folders to invoices/, bills/, credit-notes/, quotes/, sales-orders/, purchase-requests/, purchase-orders/, bank-statements/.${d}`}}let i=Object.keys(t.skippedExtensions??{}),o=i.filter(u=>Mu.has(u)),s=i.filter(u=>!Mu.has(u)&&Rc.has(u)),a=[`Nothing here can be extracted: found ${fat(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=aOe[u];d&&a.push(d)}return o.length>0&&a.push(`${nU(o)} are accepted, but not for the type their folder implies \u2014 move them to a matching folder (bank-statements/ for CSV/OFX, invoices/ or bills/ for PDF and images), or pass \`type\` to force one.`),s.length>0&&a.push(`${nU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Mu.has(u)&&!Rc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${nU([...Mu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function fat(e){let t=Object.entries(e??{}).sort((r,n)=>n[1]-r[1]);return t.length>0?t.map(([r,n])=>`${n} ${r}`).join(", "):"no readable files"}var pat=J(()=>{"use strict";Uu()});function o8(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function tO(e={}){let t=[...e.acceptsAttachmentId===!1?[]:["upload it in the Jaz dashboard and pass the attachmentId"],"share it from Dropbox / Google Drive / OneDrive and pass that link",e.fetchedBy==="agent"?"pass any https URL this agent can reach":"pass any https URL the Jaz server can reach"];return e.acceptsLocalPath!==!1&&o8()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function vE(e,t){return{error:e,hint:t,...uAe}}function hat(e={}){return{error:"The Jaz server fetches the document itself, so the source has to be something it can reach. A path on the machine running this agent is not reachable from there, and this process is a shared server whose filesystem is not yours.",hint:`Use one of: ${tO(e)}.`,...uAe}}function SE(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function iA(e,t){let r=u=>{let d=u[u.length-1];return u.length>2?`${u.slice(0,-1).join(", ")}, or ${d}`:u.length===2?`${u[0]} or ${d}`:d},n=u=>u.length>2?`${u.slice(0,-1).join(", ")}, and ${u[u.length-1]}`:u.join(" and "),i=t.provided,s=i.length+(t.hostFileAttached?1:0)===0,a=e.length===1?`Provide \`${e[0]}\``:`Provide exactly one of ${r(e)}`,c=t.hostFileAvailable?", or attach the file to this call and pass none of them":"";return{error:s?`No document source. ${a}${c}.`:t.hostFileAttached?`More than one document source: a file is attached to this call and ${n(i)} ${i.length===1?"was":"were"} also passed. Provide exactly one.`:`More than one document source: ${n(i)} were both passed. ${a}.`,hint:s?`Use one of: ${tO({acceptsLocalPath:t.acceptsLocalPath,acceptsAttachmentId:t.acceptsAttachmentId,fetchedBy:t.fetchedBy})}.`:t.hostFileAttached?"Send the call again with no source named, to use the attached file \u2014 or without the attachment, to use the named one.":"Send the call again naming only the source you want used.",...uAe,...s&&t.importDestination?{repair:{tool:"navigate",arguments:{destination:t.importDestination},reason:"Open the import screen to upload the document, then pass what it gives you."}}:{}}}var uAe,mat=J(()=>{"use strict";uAe={kind:"validation",retriable:!1}});import{randomUUID as Vwr}from"node:crypto";import{rmSync as Wwr}from"node:fs";function fAe(e){for(let t of e.tempDirs??[])try{Wwr(t,{recursive:!0,force:!0})}catch{}}function gat(e){for(let[t,r]of DE)e-r.createdAt>Aat&&(fAe(r.plan),DE.delete(t))}function Xwr(){dAe||(dAe=setInterval(()=>gat(Date.now()),Kwr),dAe.unref?.())}function pAe(e,t){let r=Date.now();gat(r),Xwr();let n=`dc_${Vwr()}`;return DE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function hAe(e,t){let r=DE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>Aat?(fAe(r.plan),DE.delete(e),null):r.plan}function yat(e,t){let r=DE.get(e);!r||r.ownerKey!==t||(fAe(r.plan),DE.delete(e))}var Aat,Kwr,DE,dAe,Eat=J(()=>{"use strict";Aat=1800*1e3,Kwr=300*1e3,DE=new Map});function Zwr(e){if(!e||typeof e!="object")return{};let t=e,r=t.validFiles?.[0],n=r?.workflowResourceId??t.workflowResourceId;return{...n?{workflowId:n}:{},...r?.backgroundJobId?{backgroundJobId:r.backgroundJobId}:{},...r?.subscriptionFBPath?{subscriptionFBPath:r.subscriptionFBPath}:{},...r?.backgroundJobFBPath?{backgroundJobFBPath:r.backgroundJobFBPath}:{}}}function bat(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>_g(i.documentType)&&r.has(i.documentType))}))}}async function Iat(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?bat(t,i):t;if(!n&&evr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");SD(o);let a=await yU({plan:s,client:r,bankAccountId:n,internalNotes:o}),c=a.results.map(d=>({file:d.file,type:d.type,status:d.status,...d.status==="uploaded"?Zwr(d.response):{},error:d.error})),u=c.map(d=>d.workflowId).filter(d=>!!d);return{total:a.total,uploaded:a.success,skipped:c.filter(d=>d.status==="skipped").length,failed:a.failed,workflowIds:u,files:c}}function Cat(e,t){return(t&&t.length>0?bat(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>_g(o.documentType)).length,0)}function evr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var _at=J(()=>{"use strict";dee();Uu();yf()});function tvr(e){switch(e){case 401:return"Sign-in or API key is missing, expired, or revoked. Local: sign in again with `clio auth login`, or check the API key (`clio auth add`, JAZ_API_KEY). Hosted connector: reconnect it.";case 402:return"Not included in this organization's plan. Retrying will not help: a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found: check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict: resource may have been modified. Re-fetch and retry.";case 422:return"Validation error: check field values against the tool description.";case 429:return"Rate limited: wait a moment and retry.";default:return""}}function nvr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function ivr(e,t){if(e!==rvr)return;let r=nvr(t);if(r)return wat.get(r)??wat.get(r.replace(/_ERROR$/,""))}function s8(e){let t={};if(e.retryAfterMs!==void 0&&(t.retryAfterSeconds=Math.ceil(e.retryAfterMs/1e3)),e.status===429&&e.body&&typeof e.body=="object"){let{reason:r,limitKey:n}=e.body;typeof r=="string"&&r.trim()!==""&&(t.reason=r),typeof n=="string"&&n.trim()!==""&&(t.limitKey=n)}return t}function ovr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=s8(e);if(t===void 0&&r===void 0)return;let i=n?` (limit: ${n})`:"",o=r==="concurrency"?`Too many requests were in flight at once${i}. Send fewer at a time.`:`Rate limited${i}.`,s=t!==void 0?` Wait ${t} second${t===1?"":"s"} before retrying.`:" Wait before retrying.";return o+s}function mAe(e){return ivr(e.status,e.body)??e.refusal?.hint??ovr(e)}function RE(e,t=300){let r=e instanceof Error?e.message:typeof e=="string"?e:(()=>{try{return JSON.stringify(e)??"unknown error"}catch{return"unknown error"}})();return r.length>t?`${r.slice(0,t-3)}...`:r}function a8(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function rO(e,t={}){let r=t.readOnly===!1&&MD()?GFe:"";if(e instanceof gr){let o=[mAe(e)??tvr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...s8(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=c8(e,t.toolName,t.input);a&&(s.repair=a)}return s}if(e?.unconfirmed===!0){let o=e;return{error:o.message,endpoint:o.endpoint,kind:"unconfirmed",retriable:!1,hint:[o.readBack,r].filter(Boolean).join(" ")}}let n=e instanceof Error?e.message:String(e),i=e instanceof nt;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var rvr,wat,TE=J(()=>{"use strict";Vi();Wi();l8();_U();rvr=422,wat=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help: preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying: the same call will keep failing with this code."]])});async function Ad(e,t,r){if(!t)return e;let n=svr(e);if(!n)return e;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return e&&typeof e=="object"?{...e,_hydration:s}:{result:e,_hydration:s}}}async function gd(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${RE(i)}`],...n}}}function svr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}function cp(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var vat=J(()=>{"use strict";TE()});async function u8(e,t){return e.list("/api/v1/bank-rules",t)}async function nO(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function d8(e,t){return e.search("/api/v1/bank-rules/search",t)}async function f8(e,t){return e.post("/api/v1/bank-rules",t)}async function p8(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function h8(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var AAe=J(()=>{"use strict"});async function m8(e,t){return e.list("/api/v1/fixed-assets",t)}async function xE(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function iO(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function A8(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},fZ)}function Dat(e,t){let r={};for(let n of avr){let i=e[n];if(i==null)continue;let o=cvr.has(n)?uf(i):i;o!==void 0&&(r[n]=o)}for(let[n,i]of Object.entries(t))i!==void 0&&n!=="resourceId"&&(r[n]=i);return r}async function g8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw ct(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await xE(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,Dat(i,r))}async function y8(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function E8(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},AP)}async function oO(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,AP)}async function b8(e,t){return e.post("/api/v1/transfer-fixed-assets",t,fZ)}async function I8(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},AP)}async function C8(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},pZ)}async function _8(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},pZ)}async function lvr(e,t){let r=new Map;for(let i=0;i<t.length;i+=Sat){let o=t.slice(i,i+Sat),s=await iO(e,{filter:{resourceId:{in:o}},limit:o.length});for(let a of s.data)r.set(a.resourceId,a)}let n=t.filter(i=>!r.has(i));if(n.length>0)throw ct(new ue(`No fixed asset found for ${n.length} resourceId${n.length===1?"":"s"}: ${n.join(", ")}. Nothing was submitted; fix or remove those rows and retry.`));return r}async function w8(e,t){ht(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=zS(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw ct(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw ct(new ue(`resourceId ${u} appears more than once in fixedAssets; put all of an asset's changes in one row. Nothing was submitted.`));return r.add(u),u}),i=t.map((a,c)=>Ui(a.tags,`fixedAssets[${c}].tags`)),o=await lvr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...Dat(u,{...a,tags:d&&Ki(u.tags,d)})}});return En(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function v8(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function S8(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function D8(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,et)}async function R8(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},et)}async function T8(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function x8(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function k8(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function dvr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function fvr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=dvr(i);if(o.length===0)return;let s=typeof i.reference=="string"&&i.reference?` (${i.reference})`:"";t.push(`row ${n}${s}: ${o.map(a=>`${a} (${uvr[a]})`).join(", ")}`)}),t.length>0)throw ct(new ue(`Every fixed asset row needs its reference, registrationType and depreciationStartDate; the import job rejects a row without them. Missing: ${t.join("; ")}. Nothing was sent.`))}async function N8(e,t){return ht(t,"fixedAssets",500,"fixed assets"),LNe(t,["purchaseDate","depreciationStartDate"]),fvr(t),En(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var oA,avr,cvr,Sat,uvr,B8=J(()=>{"use strict";an();XS();tr();it();Nl();oA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];avr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],cvr=new Set(["purchaseDate","depreciationStartDate"]);Sat=100;uvr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function O8(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function kE(e,t){return e.get(`/api/v1/leases/${t}`)}async function F8(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},Wke)}async function L8(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names lease ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await kE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function Q8(e,t){await e.delete(`/api/v1/leases/${t}`)}async function P8(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},jS)}async function M8(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},jS)}async function U8(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},jS)}async function $8(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},et)}async function q8(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},jS)}async function j8(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function Y8(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function H8(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function z8(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,et)}async function J8(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,et)}async function G8(e,t){return ht(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ct(new ue(`leases[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that lease. Bulk update does not take tags: change them with update_lease (clio leases update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/leases/bulk-update","leases",t)}var gAe=J(()=>{"use strict";an();it();tr()});async function V8(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function NE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function W8(e,t){return e.post("/api/v1/scheduled/subscriptions",t,Jp)}async function K8(e,t,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.invoice==null)throw new Error("Subscription updates need the transaction template: pass `data` (CLI: `invoice` in the --input body) with reference, valueDate, dueDate, contactResourceId and lineItems, as on create. Without it the API rejects every update.");if(n.status===void 0){let i;try{i=(await NE(e,t)).data?.status}catch(o){let s=o instanceof Error?o.message:String(o);throw new Error(`Refusing to update: could not read the subscription to keep its status, and an update without \`status\` makes a paused (INACTIVE) subscription ACTIVE. Retry, or pass \`status\` (ACTIVE or INACTIVE) explicitly. Cause: ${s}`)}if(i!=="ACTIVE"&&i!=="INACTIVE")throw pvr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function pvr(e){return typeof e!="string"||e===""?new Error("Refusing to update: the subscription has no readable stored status to keep. Pass `status` (ACTIVE or INACTIVE) explicitly."):e==="CANCELLED"?new Error("Refusing to update: the subscription is CANCELLED. A cancelled subscription cannot be updated or restarted; create a new subscription instead."):new Error(`Refusing to update: the subscription's stored status is ${e}, which an update cannot keep (it accepts only ACTIVE or INACTIVE). Check the subscription in Jaz before changing it.`)}async function X8(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function Z8(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function eW(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var tW=J(()=>{"use strict";tr()});async function rW(e,t){return e.list("/api/v1/contact-groups",t)}async function nW(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function iW(e,t){return e.search("/api/v1/contact-groups/search",t)}async function oW(e,t){return e.post("/api/v1/contact-groups",t)}async function sW(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,xI(r,CZ))}async function aW(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var yAe=J(()=>{"use strict";an()});async function cW(e,t){return e.list("/api/v1/inventory-items",t)}async function lW(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function uW(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function fW(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof gr&&n.status===404&&hvr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var dW,hvr,EAe=J(()=>{"use strict";Vi();dW=["ALL","AVAILABLE","FULLY_DRAWN"],hvr=/Inventory balance Not Found/i});async function pW(e,t){return e.list("/api/v1/custom-fields",t)}async function sO(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function hW(e,t){return e.search("/api/v1/custom-fields/search",t)}async function mW(e,t){return e.post("/api/v1/custom-fields",t)}function Avr(e){return e!==void 0&&mvr.every(t=>e[t]!==void 0)}function gvr(e){let t=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:t(e.applyToSales),bills:t(e.applyToPurchase),customerCredits:t(e.applyToSaleCreditNote??e.applyToCreditNote),supplierCredits:t(e.applyToPurchaseCreditNote??e.applyToCreditNote),payments:t(e.applyToPayment)}}function yvr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function AW(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!Avr(n.appliesTo)){let i=await sO(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??yvr(i.data),n.appliesTo={...gvr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function gW(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var mvr,bAe=J(()=>{"use strict";mvr=["invoices","bills","customerCredits","supplierCredits","payments"]});var tl,BE,Evr,bvr,IAe,yW,EW,Ivr,Ta,iu,OE,sv,FE,CAe=J(()=>{"use strict";tl={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange rate quote token. Leave out to use a custom rate; a token fetches the platform rate."},rateFunctionalToSource:{type:"number",description:"Exchange rate from the organization's base currency to the source currency."},sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217). Required whenever this settings object is sent."}},required:["sourceCurrencyCode"]},BE={type:"object",properties:{actualValue:{type:"string",description:"Value set on this record."},appliesToFixedAssets:{type:"string",description:"NULL = does not apply to fixed assets; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},appliesToItems:{type:"string",description:"NULL = does not apply to items; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToContact:{type:"string",description:"NULL = does not apply to contact; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToCreditNote:{type:"string",description:"NULL = does not apply to credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPayment:{type:"string",description:"NULL = does not apply to payment; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchase:{type:"string",description:"NULL = does not apply to purchase; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToPurchaseCreditNote:{type:"string",description:"NULL = does not apply to purchase credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSaleCreditNote:{type:"string",description:"NULL = does not apply to sale credit note; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},applyToSales:{type:"string",description:"NULL = does not apply to sales; SHOW = applies but not printable; PRINT = applies and printable on PDF.",enum:["NULL","SHOW","PRINT"]},customFieldName:{type:"string",description:"Display name of the custom field. Required unless resourceId is given; when resourceId is given, the organization's own name for that field is stored instead of this one."},datatypeCode:{type:"string",description:"Data type code (TEXT, LIST, DATE)."},defaultValue:{type:"string",description:"Default value to populate."},description:{type:"string",description:"Description of the custom field."},entityResourceId:{type:"string",description:"Resource ID of the record chosen, when the options come from a record list. actualValue then holds the name as of the time the record was saved."},format:{type:"string",description:"Where the options come from. CUSTOM means the options are typed by hand. Any other value draws them from that record list, and entityResourceId identifies the record chosen.",enum:["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]},listOptions:{type:"array",description:"Available options for LIST type fields. Empty when the options come from a record list.",items:{type:"string"}},resourceId:{type:"string",description:"Resource ID of the custom field definition. Required unless customFieldName is given. When omitted, the field is matched by customFieldName (case-insensitive) and linked only if exactly one active custom field in the organization has that name."}}},Evr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},bvr={type:"object",properties:{exchangeRate:{type:"number",description:"Exchange rate from the organization's base currency to the transaction currency."},sourceCurrency:{type:"string",description:"Transaction currency code (ISO 4217)."}},required:["sourceCurrency"]},IAe={type:"object",properties:{addressLine1:{type:"string",description:"Street address line 1."},addressLine2:{type:"string",description:"Street address line 2."},city:{type:"string",description:"City or locality name."},country:{type:"string",description:"Two-letter country code (ISO 3166-1 alpha-2)."},postalCode:{type:"string",description:"Postal or ZIP code."},state:{type:"string",description:"State or province name."}},required:["addressLine1"]},yW={type:"object",properties:{billingAddress:{...IAe,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},EW={type:"object",properties:{billingAddress:{...IAe,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...IAe,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},Ivr={type:"object",properties:{className:{type:"string",description:"Name of the selected class."},entityResourceId:{type:"string",description:"Resource ID of the selected record, when the classifier draws its options from customers, suppliers, contacts, employees, or users. Send this instead of resourceId."},resourceId:{type:"string",description:"Resource ID of the selected class. Required when the classifier lists its own classes."}},required:["className"]},Ta={type:"object",properties:{deleted:{type:"boolean",description:"When true, removes this classifier from the line item, and only resourceId is needed. When false or left out, type, printable and at least one selected class are required."},printable:{type:"boolean",description:"When true, the classifier appears on printed and PDF documents. Required unless deleted is true."},resourceId:{type:"string",description:"Resource ID of the classifier."},selectedClasses:{type:"array",description:"Classes selected within the classifier. Required unless deleted is true.",items:Ivr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},iu={type:"object",properties:{rateType:{type:"string",description:"Discount calculation method.",enum:["PERCENTAGE","FLAT"]},rateValue:{type:"number",description:"Discount value (percentage 0-100 or flat amount)."}}},OE={type:"object",properties:{code:{type:"string",description:"Withholding tax code."},description:{type:"string",description:"Description of the withholding tax."},rate:{type:"number",description:"Withholding tax rate."},rateType:{type:"string",description:"Rate type (PERCENTAGE or FLAT)."},type:{type:"string",description:"Tax type."}},required:["code","rate","rateType","type"]},sv={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this bill.",items:BE},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the bill. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Bill date, in YYYY-MM-DD format (organization timezone)."}},"cash-entries":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the entry."},currencySetting:{...Evr,description:"Source currency exchange settings for cash entries."},organizationAccountResourceId:{type:"string",description:"UUID of the bank/cash account for this entry."},reference:{type:"string",description:"Reference number or external identifier."},tags:{type:"array",description:"Tags to apply to the cash entry.",items:{type:"string"}},taxCurrencySettings:{...bvr,description:"Tax currency exchange settings."},valueDate:{type:"string",description:"Entry date, in YYYY-MM-DD format (organization timezone)."}},"customer-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this credit note."},creditFrom:{...yW,description:"Issuer identity and billing address (credit from)."},creditTo:{...EW,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},notes:{type:"string",description:"Notes printed on the credit note PDF."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}},invoices:{billFrom:{...yW,description:"Seller identity and billing address."},billTo:{...EW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for this invoice."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this invoice.",items:BE},deliverySlipTemplateResourceId:{type:"string",description:"UUID of the delivery slip PDF template."},dueDate:{type:"string",description:"Payment due date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},invoiceNotes:{type:"string",description:"Notes printed on the invoice PDF."},tags:{type:"array",description:"Tags to apply to the invoice. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."},valueDate:{type:"string",description:"Invoice date, in YYYY-MM-DD format (organization timezone)."}},"journal-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with generated journals."},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated journals.",items:{type:"string"}}},journals:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact associated with the journal."},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the journal.",items:{type:"string"}},valueDate:{type:"string",description:"Journal date, in YYYY-MM-DD format (organization timezone)."}},"purchase-schedules":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for generated bills."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated bills.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},tags:{type:"array",description:"Tags to apply to generated bills.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...yW,description:"Seller identity and billing address."},billTo:{...EW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"subscription-schedules":{billFrom:{...yW,description:"Seller identity and billing address."},billTo:{...EW,description:"Buyer identity, billing and shipping address."},capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (customer) for generated invoices."},customFields:{type:"array",description:"Custom field values for generated invoices.",items:BE},endDate:{type:"string",description:"Schedule end date, in YYYY-MM-DD format (organization timezone)."},interval:{type:"string",description:"Recurrence interval for the schedule.",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"]},invoiceNotes:{type:"string",description:"Notes printed on generated invoices."},tags:{type:"array",description:"Tags to apply to generated invoices.",items:{type:"string"}},templateResourceId:{type:"string",description:"UUID of the PDF report template."}},"supplier-credit-notes":{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this credit note."},currencySettings:{...tl,description:"Source currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},customFields:{type:"array",description:"Custom field values for this credit note.",items:BE},internalNotes:{type:"string",description:"Internal notes (not printed, for internal reference only)."},tags:{type:"array",description:"Tags to apply to the credit note. Together they can total at most 1000 characters.",items:{type:"string"}},taxCurrencySettings:{...tl,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."},valueDate:{type:"string",description:"Credit note date, in YYYY-MM-DD format (organization timezone)."}}},FE={bills:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"cash-entries":{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"customer-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},invoices:{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"journal-schedules":{entryKeys:["lineItemResourceId"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes","lineItemResourceId"],fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},itemResourceId:{type:"string",description:"UUID of the catalog item."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},pricePerUnit:{type:"number",description:"Price per unit before tax."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."}}},journals:{fields:{amount:{type:"number",description:"Debit or credit amount for this line."},classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."}}},"purchase-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-requests":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}},"purchase-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"sale-orders":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-quotes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for revenue recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."}}},"sale-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"subscription-schedules":{entryKeys:["arrayIndex"],updateKeys:["schedulerResourceId"],updateRequired:["lineItemUpdates","schedulerResourceId"],entryRequired:["attributes"],fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},description:{type:"string",description:"Line item description or memo."},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry."},quantity:{type:"number",description:"Quantity of units."},sku:{type:"string",description:"Stock-keeping unit identifier."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details (purchase-side schedules only)."}}},"supplier-credit-notes":{fields:{classifierConfig:{type:"array",description:"Classifiers to set or remove on each line item. Classifiers not listed are left as they are, and an empty list changes none.",items:Ta},discount:{...iu,description:"Discount to apply to this line item."},itemResourceId:{type:"string",description:"UUID of the catalog item."},name:{type:"string",description:"Line item display name."},organizationAccountResourceId:{type:"string",description:"UUID of the chart-of-accounts entry for expense recognition."},quantity:{type:"number",description:"Quantity of units."},taxProfileResourceId:{type:"string",description:"UUID of the tax profile to apply."},unit:{type:"string",description:"Unit of measure (e.g. pcs, kg, hrs)."},unitPrice:{type:"number",description:"Price per unit before discount and tax."},withholdingTax:{...OE,description:"Withholding tax details for this line item."}}}}});function wAe(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function vAe(e){let t=e.updated??[],r=wAe(e.failed);return{...t.length===0&&r.length>0?{error:wvr}:{},updated:t,failed:r}}function Tat(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function xat(e,t,r=""){let n=[];for(let[i,o]of Object.entries(e)){let s=Object.hasOwn(t,i)?t[i]:void 0;if(!s){n.push({path:r+i,accepted:Object.keys(t)});continue}let a=Tat(s);if(a)for(let c of Array.isArray(o)?o:[o])Sh(c)&&n.push(...xat(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function vvr(e){return Object.entries(e).map(([t,r])=>{let n=Tat(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function SAe(e,t,r){if(!Sh(t))return;let n=xat(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw ct(new nt(`${e} has no field ${i.join("; ")}. Fields: ${vvr(r)}. Nothing was changed.`))}function Svr(e){let t=sv[e];if(!t)throw new Error(`quick-fix-fields.ts has no transaction table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function Dvr(e){let t=FE[e];if(!t)throw new Error(`quick-fix-fields.ts has no line item table for ${e}: run npx tsx scripts/gen-quick-fix-fields.ts`);return t}function Rvr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!Sh(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw ct(new nt(`${e} schedulerUpdates entries take { ${i.join(", ")} }: ${s.map(a=>`"${a}"`).join(", ")} is not one. A schedule's own fields go through the transaction-level quick fix. Nothing was changed.`));if(Array.isArray(o.lineItemUpdates))for(let a of o.lineItemUpdates){if(!Sh(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw ct(new nt(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));SAe(`${e} line items`,a.attributes,t.fields)}}}function kat(e){if(av.includes(e))return;let t=IW.includes(e);throw ct(new nt(t?`${e} can be quick-fixed at line-item level only (quick_fix_line_items, or clio quick-fix ${e} --line-items). To change one order's own fields, use update_sale_order / update_purchase_order, or clio sale-orders|purchase-orders fast-fix.`:`${e} has no quick fix route. Transaction-level entities: ${av.join(", ")}.`))}async function lv(e,t,r){kat(t),SAe(`${t} quick fix`,r.attributes,Svr(t));let n=await e.post(`/api/v1/quick-fix/${Sc(av,t)}`,r);return vAe(n)}async function Tvr(e,t){try{return await IE(e,t)}catch(r){if(r instanceof gr&&r.status===404)return CE(e,t);throw r}}async function Nat(e,t,r,n){kat(t);let i=DAe[t],o=async d=>i.tags(await Yo(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=Rat)s.push(...await Promise.all(r.resourceIds.slice(d,d+Rat).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=Ki(s[f],n),h=JSON.stringify(p);a.set(h,{tags:p,resourceIds:[...a.get(h)?.resourceIds??[],d]})});let c=[],u=[];for(let{tags:d,resourceIds:f}of a.values())try{let p=await lv(e,t,{resourceIds:f,attributes:{...r.attributes,tags:d}});c.push(...p.updated),u.push(...p.failed)}catch(p){if(c.length===0)throw p;u.push(...f.map(h=>({resourceId:h,error:p instanceof Error?p.message:String(p)})))}return vAe({updated:c,failed:u})}async function aO(e,t,r){let n=Sc(cv,t),i=Dvr(t);i.entryKeys?Rvr(t,i,r.schedulerUpdates):SAe(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return vAe(o)}var Cvr,_vr,bW,IW,av,cv,wvr,LE,_Ae,DAe,Rat,CW=J(()=>{"use strict";Vi();it();Wi();CAe();Nl();zg();lf();zx();Xx();Jg();rV();hV();tW();Hre();Cvr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],_vr=["journals","cash-entries"],bW=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],IW=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],av=[...Cvr,..._vr,...bW],cv=[...av,...IW],wvr="Nothing changed: every record failed. See failed for each reason.";LE=e=>e?.tags,_Ae=e=>e?.data?.tags,DAe={invoices:{noun:"invoice",get:(e,t)=>go(e,t),tags:LE},bills:{noun:"bill",get:(e,t)=>fo(e,t),tags:LE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>Ws(e,t),tags:LE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>Ks(e,t),tags:LE},journals:{noun:"journal",get:(e,t)=>vs(e,t),tags:LE},"cash-entries":{noun:"cash entry",get:(e,t)=>Tvr(e,t),tags:LE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>Ww(e,t),tags:_Ae},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Kw(e,t),tags:_Ae},"subscription-schedules":{noun:"subscription",get:(e,t)=>NE(e,t),tags:_Ae},"journal-schedules":{noun:"journal schedule",get:(e,t)=>Xw(e,t),tags:LE}},Rat=10});function _W(e,t=1,r=!0){let n={type:e.type};e.description&&r&&(n.description=e.description),e.enum&&(n.enum=[...e.enum]),e.items&&(n.items=_W(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<kvr&&i.length<=Nvr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,_W(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function Oat(e,t,r){let n=Bvr(t);if(!n)return[];let i=Ovr(r);if(!i){if(Bat[e])return[];let o=(t.properties?t.required:t.items?.required)??[];return[[e,`{${Object.keys(n).map(s=>o.includes(s)?`${s} (required)`:s).join(", ")}}`]]}return Object.entries(n).flatMap(([o,s])=>i[o]?Oat(o,s,i[o]):[])}function Fvr(e,t){if(e.length===t.length)return;let r=t.filter(n=>!e.includes(n));return r.length<e.length?`Not: ${r.join(", ")}.`:`Only: ${e.join(", ")}.`}function RAe(e,t,r={}){let n=Object.keys(e),i=[...new Set(n.flatMap(c=>Object.keys(e[c])))].sort(),o={},s=new Map;for(let c of i){let u=n.filter(y=>e[y][c]),d=new Map;for(let y of u){let b=Lvr(e[y][c]);d.set(b,[...d.get(b)??[],y])}let[[,f],...p]=[...d].sort((y,b)=>b[1].length-y[1].length),{description:h,...m}=r[c]??_W(e[f[0]][c]),A=p.length&&m.properties&&!r[c]?{...m,required:void 0,properties:Object.assign({},...[f,...p.map(([,y])=>y)].map(y=>_W(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[Bat[c],Fvr(u,n),...p.map(([,y])=>{let b=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(b.properties??b.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[b,E]of Oat(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(b))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function Pat(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>xvr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var xvr,Bat,kvr,Nvr,Bvr,Ovr,Lvr,Qvr,Pvr,uv,Fat,Lat,Qat,Mat,Uat,$at,TAe=J(()=>{"use strict";CAe();Nl();xvr={valueDate:"date",dueDate:"due date",endDate:"end date",interval:"repeat interval",contactResourceId:"contact",capsuleResourceId:"capsule",tags:"tags",customFields:"custom fields",currencySettings:"currency and exchange rate",currencySetting:"exchange rate",taxCurrencySettings:"tax currency",reference:"reference",notes:"notes",invoiceNotes:"notes",internalNotes:"internal notes",templateResourceId:"template",deliverySlipTemplateResourceId:"delivery slip template",billFrom:"billing address",billTo:"billing and shipping address",creditFrom:"billing address",creditTo:"billing and shipping address",organizationAccountResourceId:"account",name:"line name",description:"description",sku:"SKU",itemResourceId:"item",quantity:"quantity",unit:"unit",unitPrice:"unit price",pricePerUnit:"unit price",amount:"amount",discount:"discount",taxProfileResourceId:"tax profile",withholdingTax:"withholding tax",classifierConfig:"tracking classes"},Bat={currencySettings:"sourceCurrencyCode alone takes the platform rate (not on schedules); add rateFunctionalToSource to set one.",taxCurrencySettings:"Cash entries: sourceCurrency; every other record: sourceCurrencyCode, always sent.",tags:`${jo.description}. Max 50 tags, 50 characters each.`,customFields:"Rows: {customFieldName or resourceId, actualValue}.",notes:"Printed; the form calls it Credit Notes.",internalNotes:'Not printed. The user says just "notes" and the record has printed notes too: ask which.'},kvr=2,Nvr=8;Bvr=e=>e.properties??e.items?.properties,Ovr=e=>e.properties??e.items?.properties;Lvr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),Qvr={tags:jo};Pvr=Object.entries(FE).filter(([,e])=>!e.entryKeys),uv=Object.entries(FE).filter(([,e])=>e.entryKeys),Fat=RAe({...sv},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",Qvr),Lat=RAe(Object.fromEntries(Pvr.map(([e,t])=>[e,t.fields])),"With lineItemResourceIds: the fields to change on every listed line; a field the entity does not take is refused."),Qat=(()=>{let e=n=>uv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=uv[0],r=[...new Set(uv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>uv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${uv.map(([n])=>n).join(", ")}), instead of lineItemResourceIds + attributes.`,items:{type:"object",...t.updateRequired?.length?{required:[...t.updateRequired]}:{},properties:{schedulerResourceId:{type:"string",description:"The schedule."},lineItemUpdates:{type:"array",description:"One entry per line to change.",items:{type:"object",...r.length?{required:r}:{},properties:{arrayIndex:{type:"number",description:`0-based line position. ${e("arrayIndex").join(", ")}.`},lineItemResourceId:{type:"string",description:`Line resourceId. ${e("lineItemResourceId").join(", ")}.`},attributes:RAe(Object.fromEntries(uv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Mat=[...new Set([...Object.keys(sv),...Object.keys(FE)])].map(e=>e.replace(/-/g," ")).join(", "),Uat=Pat(Object.values(sv)),$at=Pat(Object.values(FE).map(e=>e.fields))});function wW(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var xAe=J(()=>{"use strict"});function SW(){return sA.map(e=>`${e} sets ${fv[e].change.join(", ")}`).join("; ")}function Vat(e){let t={};for(let r of e)t[r]=Object.hasOwn(jat,r)?jat[r]:$vr.find(([n])=>n.test(r))?.[1]??qvr;return Object.keys(t).length>0?t:void 0}function Wat(e){if(!(e instanceof gr)||!e.endpoint.startsWith(Uvr))return;let t=e.body?.error,r=t?.error_details,n=typeof r?.code=="string"?r.code:e.status===400&&t?.error_type==="invalid_filter"?"invalid_filter":void 0;if(n===void 0||!Object.hasOwn(Yat,n))return;let{hint:i,repairTool:o,command:s}=Yat[n],a=Array.isArray(t?.errors)?t.errors.join(" "):e.message,c=/"([^"]+)" is not a supported (field|operator)/.exec(a),u=typeof r?.resourceId=="string"?r.resourceId:/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.exec(a)?.[0],d={...typeof r?.count=="number"?{count:r.count}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...c?{key:c[1],noun:c[2]}:{},...u?{resourceId:u}:{},unit:e.endpoint===Jat.LINE_ITEMS?"line items":"records",...e.endpoint===vW?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function Hvr(e,t,r){if(r!==0)return;let n=t.filter;if(!n||typeof n!="object"||Array.isArray(n))return;let i=n.reference;if(!i||typeof i!="object"||Array.isArray(i))return;let o=i.eq;if(!(typeof o!="string"||!o))return{tool:"preview_ledger_find_fix",arguments:{level:e,filter:{...n,reference:{startWith:o}},change:t.change},reason:`reference.eq matches a WHOLE reference only, and "${o}" matched zero records. Real references often carry a suffix (e.g. "${o}-INV-1"). This is not necessarily "no matching records" \u2014 retry with startWith or contains instead of eq (the suggested arguments above use startWith) before telling the user none were found.`}}function zvr(e){return typeof e=="string"&&sA.includes(e)}function Jvr(e,t){if(!zvr(e))throw new nt(`level must be one of ${sA.join(", ")}.`);let r=sA.find(i=>i!==e),n=[];for(let i of["filter","change"]){let o=t[i];if(!(!o||typeof o!="object"||Array.isArray(o)))for(let s of Object.keys(o))fv[e][i].includes(s)||n.push(fv[r][i].includes(s)?`${i}.${s} is a ${r} field: preview that level separately`:i==="change"?`change.${s} is not a Ledger Find & Fix field: use quick_fix_transactions or quick_fix_line_items`:`filter.${s} is not a filter condition`)}if(n.length>0){let{filter:i,change:o}=fv[e];throw new nt(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function Hat(e,t){let r=t;if(typeof t=="string")try{r=JSON.parse(t)}catch{r=void 0}if(t===void 0||r!==null&&typeof r=="object"&&!Array.isArray(r))return r;let n=typeof t=="string"?"a string that does not hold one":Array.isArray(t)?"a list":String(t);throw new nt(`${e} must be a JSON object, not ${n}.`)}async function RW(e,t,r){let n={filter:Hat("filter",r.filter),change:Hat("change",r.change)};Jvr(t,n);let i;try{i=await e.post(Jat[t],{filter:n.filter,change:n.change},et)}catch(u){throw Wat(u),u}let{data:o,...s}=i,a=Vat([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=Hvr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function NAe(e,t){return{error:`${t} ${Xat}`,outcome:"UNKNOWN",previewId:e,next:Kat}}function Wvr(e,t){let r=Array.isArray(t?.updated)?t.updated:void 0,n=Array.isArray(t?.failed)?t.failed:void 0;if(!r||!n||r.length+n.length===0)return NAe(e,"The apply answered without a per-record result.");let i=wAe(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=Vat(Object.keys(o)),a=o[jvr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:Vvr}:a==="UNKNOWN"?{error:Xat}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Kat:Gvr},failed:i.slice(0,kAe),...i.length>kAe?{failedNotShown:i.length-kAe}:{},data:r}}async function TW(e,t,r=Yvr){let n;try{n=await e.post(vW,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof gr){let s=Wat(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw ct(i);return NAe(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof zp)throw ct(i);let o=i instanceof Error?i.message:String(i);return NAe(t,`No answer arrived from the apply (${o}).`)}return Wvr(t,n)}var zat,sA,Jat,vW,Uvr,Gat,qat,fv,jat,$vr,qvr,jvr,Yvr,DW,kAe,pv,Ton,dv,Yat,Kat,Gvr,Vvr,Xat,BAe=J(()=>{"use strict";Vi();CW();dP();it();Wi();tr();xAe();zat=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],sA=["TRANSACTIONS","LINE_ITEMS"],Jat={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},vW="/api/v1/ledger/find-fix/apply",Uvr=vW.slice(0,vW.lastIndexOf("/")+1),Gat={reference:{eq:"one",in:"list",contains:"one",startWith:"one"},valueDate:{eq:"one",gte:"one",lte:"one",between:"list"},contactResourceId:{eq:"one",in:"list"},organizationAccountResourceId:{eq:"one",in:"list"}},qat=["types","resourceIds","reference","valueDate","contactResourceId"],fv={TRANSACTIONS:{filter:qat,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...qat,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};jat={NOT_FOUND:"A listed resource ID matched no record of the listed types. At LINE_ITEMS level resource IDs are line item IDs, not document IDs: filter a document's lines by its reference instead. JOURNAL matches manual and cashflow journals only; transfer and trial-balance journals and cash transfers are never matched.",VOID:"The record, or the line's document, is void.",NO_CHANGE:"Every field the change sets already has that value.",BLOCKED:"Every field the change sets is blocked on this record; its blocked list says why.",CONTACT_NOT_CUSTOMER:"The new contact is not a customer, and this document needs one.",CONTACT_NOT_SUPPLIER:"The new contact is not a supplier, and this document needs one.",HAS_CREDIT_OFFSETS:"Credits applied to the document would stay with the old contact.",FOREIGN_CURRENCY_VALUE_DATE:"A new date on a foreign currency record would take a new exchange rate.",VALUE_DATE_AFTER_DUE_DATE:"The new date is after the document's due date.",TOO_MANY_TAGS:"The record would end with more than 50 tags.",TAGS_TOO_LONG:`The record's tags, joined with "|", would total more than 1000 characters (invoices, bills and credit notes).`,CONTROL_LINE:"The journal line is on a bank, cash or control account, so its account cannot change.",OUTCOME_UNKNOWN:"The answer for this record was lost, so it may or may not have changed.",NOT_ATTEMPTED:"The apply reached its 3-minute limit before sending this record, so it did not change.",UPSTREAM_REJECTED:"The platform refused the update before this record changed.",UNSUPPORTED_RECORD_TYPE:"The stored preview names a record type this version cannot change.",UNKNOWN_ERROR:"The platform reported a failure without a code; read the record's error.",INPUT_EXCHANGE_RATE_INVALID:"The platform refused the record's exchange rate, so it did not change."},$vr=[[/LOCK_DATE/,"The record falls in a locked period, so it did not change."],[/_NOT_EXIST$|_DOES_NOT_EXIST$/,"The record no longer exists; it may have been deleted since the preview."],[/could not execute statement|\bSQL\b/,"The platform hit a database error on this record; preview again before retrying it."]],qvr="Not described by this client version; read the records that carry it.";jvr="OUTCOME_UNKNOWN",Yvr=25e3,DW=3e5,kAe=50,pv=12,Ton=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${pv}}(?![A-Za-z0-9_-])`,"i"),dv=e=>e.resourceId?` (${e.resourceId})`:"",Yat={PREVIEW_NOT_FOUND:{hint:"The preview expired (30 minutes), was already applied or is being applied, or belongs to another user or key. Never apply this previewId again. Run a new preview, show the user its counts, and apply only after they confirm.",command:"clio ledger-find-fix preview"},TOO_MANY_RECORDS:{hint:e=>`${e.count!==void 0?`At least ${e.count} ${e.unit} match the filter.`:`Too many ${e.unit} match the filter.`}${e.limit!==void 0?` One preview can change at most ${e.limit}.`:""} Narrow it (a date range, a reference, a contact or fewer types), or split the work into several previews.`},TOO_MANY_CALLS:{hint:e=>`The change needs ${e.count??"too many"} separate updates${e.limit!==void 0?` and the limit is ${e.limit}`:""}: records whose resulting values differ, usually their tags, need separate updates. Narrow the filter, or change tags in a separate preview.`},CONTACT_NOT_FOUND:{hint:e=>`The contact the change sets${dv(e)} does not exist. Find it by name, then preview again with its resourceId.`,repairTool:"search_contacts"},CAPSULE_NOT_FOUND:{hint:e=>`The capsule the change sets${dv(e)} does not exist. Find it, then preview again with its resourceId.`,repairTool:"search_capsules"},ACCOUNT_NOT_FOUND:{hint:e=>`The account the change sets${dv(e)} does not exist or is inactive. Find an active account, then preview again with its resourceId.`,repairTool:"search_accounts"},ACCOUNT_NOT_ALLOWED:{hint:e=>`The account the change sets${dv(e)} is a bank, cash or control account, which Ledger Find & Fix cannot set. Choose another account, then preview again.`,repairTool:"search_accounts"},CLASSIFIER_NOT_FOUND:{hint:e=>`A classifier the change sets${dv(e)} does not exist in this organization. Only a set entry is checked: removing a classifier the organization no longer has is allowed. Find the classifier, then preview again with its resourceId.`,repairTool:"search_nano_classifiers"},CLASS_NOT_FOUND:{hint:e=>`A class a set entry selects${dv(e)} is not a current class of that classifier. Look up the classes of that classifier, then preview again with one of them.`,repairTool:"search_nano_classifiers"},invalid_filter:{hint:e=>`The API does not take ${e.key?`the ${e.noun??"key"} "${e.key}"`:"a key"} in this preview. Correct or remove it, then preview again.`},PREVIEW_STORE_UNAVAILABLE:{hint:e=>e.apply?"Previews cannot be saved or read right now, and nothing was applied. The preview may already be used up: try again shortly, and preview again if the apply answers PREVIEW_NOT_FOUND.":"Previews cannot be saved right now, so this preview has no previewId and nothing changed. Run the same preview again shortly."}};Kat="If the connection dropped, the apply keeps running for up to 4 minutes. Wait that long, then preview again or re-read the records to see the result. Never apply this previewId again, and do not preview and apply the same records before then: the first apply's remaining updates would undo the new change.",Gvr="Records under failed were reported unchanged, but one whose save finished before a later step failed can still be listed. Run a new preview before retrying any of them: it lists only what still differs.",Vvr="Nothing changed: every record in the preview failed.",Xat="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function xW(e,t){return e.list("/api/v1/nano-classifiers",t)}async function QE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function kW(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function cO(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function lO(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function NW(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await Kvr(e,t):{};let{data:n}=await QE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:ect(n)}async function Kvr(e,t){let{data:r}=await QE(e,t);return ect(r)}function ect(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function BW(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}function tct(e,t="classifierConfig"){if(e==null)return;if(!(Array.isArray(e)&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.resourceId=="string")))throw ct(new nt(`${t} takes a list of classifiers, each with its resourceId: an entry sets that classifier, { resourceId, deleted: true } removes it, and classifiers it does not name stay. Nothing was changed.`));return e.length>0?e:void 0}function rct(e,t){let r=new Map((Array.isArray(e)?e:[]).map(n=>[n?.resourceId,DP(n)]));for(let n of t)n.deleted===!0?r.delete(n.resourceId):r.set(n.resourceId,DP(n));return[...r.values()]}var Zat,OAe=J(()=>{"use strict";Wi();it();af();Zat=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function OW(e,t){return e.post("/api/v1/export-records",t,et)}async function FW(e,t){return e.post("/api/v1/export-records/preview",t,et)}async function LW(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var FAe=J(()=>{"use strict";tr()});function QW(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function sct(e,t,r,n=!1){if(!Array.isArray(e))throw new ue(`${r}: resourceIds must be an array, not a ${typeof e}`);if(e.length===0)throw new ue(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(e).size!==e.length)throw new ue(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(e.length>t)throw new ue(`${r}: ${e.length} ids exceeds the ${t}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${t} or fewer.`)}function PW(e){if(!Array.isArray(e)||e.length===0)return{state:"unconfirmed"};let t=e.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return t?{state:"refused",reason:t.failureReason||t.errorCode||"refused without a stated reason"}:{state:"approved"}}async function MW(e,t,r){return QW(t,ict),Xi(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Sc(lp,t)}/${encodeURIComponent(r)}/approve`,void 0,Yke)}async function UW(e,t,r){return QW(t,ict),sct(r,Xvr,"bulk approve",!0),r.forEach(n=>Xi(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Sc(lp,t)}/bulk-approve`,{resourceIds:r},Hke)}async function $W(e,t,r,n){QW(t,oct),Xi(r,"resourceId","Pass the document resourceId."),act(n);let i=await e.post(`/api/v1/${Sc(PE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:t0r(i)}}}async function qW(e,t,r,n){return QW(t,oct),act(n),sct(r,Zvr,"bulk request changes"),r.forEach(i=>Xi(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(e0r(t),{resourceIds:r,message:n})}function e0r(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Sc(nct,e)}/bulk-request-changes`}function act(e){if(!e||e.trim().length===0)throw new ue("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function t0r(e){let t=e?.data??e;if(!t||typeof t!="object")return[];let r=t.records;if(Array.isArray(r))return r;let n=t.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var lp,nct,PE,ict,oct,Xvr,Zvr,LAe=J(()=>{"use strict";it();tr();lp=["invoices","bills","customer-credit-notes","supplier-credit-notes"],nct=[...lp,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],PE=[...nct,"claims"],ict=new Set(lp),oct=new Set(PE);Xvr=100,Zvr=500});function r0r(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${cct(t)}:${cct(r)}:${n}`}function cct(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function QAe(e){if(!lct.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...lct].join(", ")}`)}async function uct(e,t,r){return QAe(t),Xi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function dct(e,t,r,n){return QAe(t),Xi(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function fct(e,t,r,n,i){if(QAe(t),Xi(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new ue('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Restoring it deletes the document, so the API refuses it (422) and so does this client. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return e.post(`/api/v1/rollback/${encodeURIComponent(t)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??r0r(t,r,n)}})}async function pct(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var lct,hct=J(()=>{"use strict";it();lct=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function n0r({fromPeriod:e,toPeriod:t},r){for(let[n,i]of[["fromPeriod",e],["toPeriod",t]])if(i!==void 0){if(!Number.isInteger(i)||i<1)throw new nt(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new nt("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new nt(`${n} ${i} is past the last period (${r}). Send a period from 1 to ${r}.`)}if(e!==void 0&&t!==void 0&&e>t)throw new nt(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function jW(e,t,r){let n=e.length;if(n0r(t,e[n-1]),n===0)return{start:0,end:0,window:{totalPeriods:0}};let i=t.fromPeriod===void 0?0:e.filter(u=>u<t.fromPeriod).length,o=t.toPeriod===void 0?n:e.filter(u=>u<=t.toPeriod).length,s=o===0&&t.toPeriod!==void 0,a=s?Math.min(t.toPeriod-(t.fromPeriod??1)+1,n,r):Math.min(o,i+r);if(a<=i)throw new nt(`No period falls in that range: the schedule runs from period ${e[0]} to ${e[n-1]}.`);let c={totalPeriods:n,fromPeriod:e[i],toPeriod:e[a-1]};if(i>0||a<n){let u=[`Showing periods ${e[i]} to ${e[a-1]} of ${n}.`];a<n&&u.push(`Periods ${e[a]} to ${e[n-1]} are not shown: call again with fromPeriod ${e[a]} to read the next range (at most ${r} periods come back per call).`),i>0&&u.push(`Periods ${e[0]} to ${e[i-1]} are not shown: call again with fromPeriod ${e[0]} to read them.`),c.note=u.join(" ")}return s&&(c.note=`Periods ${t.fromPeriod??1} to ${t.toPeriod} come before this schedule, which starts at period ${e[0]}. Showing the first periods instead. ${c.note??""}`.trim()),{start:i,end:a,window:c}}function hv(e,t={},r=uO){let n=e.data,i=ME(n.rows),{start:o,end:s,window:a}=jW(PAe(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function YW(e,t={},r=uO){let n=e.data,i=ME(n.rows),o=h=>h.rowType==="PERIOD",s=i.findIndex(o),a=i.map(o).lastIndexOf(!0),c=s===-1?[]:i.slice(s,a+1),{start:u,end:d,window:f}=jW(PAe(c),t,r);if(s===-1)return{...e,data:{...f,...n}};let p=[...u===0?i.slice(0,s):[],...c.slice(u,d),...d===c.length?i.slice(a+1):[]];return{...e,data:{...f,...n,rows:p}}}function mct(e,t,r,n,i){let o=e.data,s=ME(o[t]),a=s.reduce((h,m)=>h+ME(m[r]).length,0),{start:c,end:u,window:d}=jW(Array.from({length:a},(h,m)=>m+1),n,i);if(a===0)return{...e,data:{...d,...o}};let f=0,p=[];for(let h of s){let m=ME(h[r]),A=m.slice(Math.max(c-f,0),Math.max(u-f,0));A.length>0&&p.push({...h,[r]:A}),f+=m.length}return{...e,data:{...d,...o,[t]:p}}}function yd(e,t={},r=uO){let n=e.data,i=ME(n.periods),{start:o,end:s,window:a}=jW(PAe(i,"period"),t,r);if(i.length===0)return{...e,data:{...a,...n}};let c=i[o].startDate,u=i[s-1].endDate,d=f=>typeof f.toDate!="string"||typeof f.fromDate!="string"||typeof c!="string"||typeof u!="string"||f.toDate>=c&&f.fromDate<=u;return typeof a.note=="string"&&(a.note+=" The timeline lists only the segments that touch these periods."),{...e,data:{...a,...n,periods:i.slice(o,s),timeline:ME(n.timeline).filter(d)}}}var uO,ME,PAe,HW,zW,mv=J(()=>{"use strict";Wi();uO=60;ME=e=>Array.isArray(e)?e:[],PAe=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);HW=(e,t={},r=uO)=>mct(e,"depreciationScheduled","depreciation",t,r),zW=(e,t={},r=uO)=>mct(e,"amortizationScheduled","amortization",t,r)});async function UE(e,t){return e.get(`/api/v1/loans/${t}`)}async function JW(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function GW(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function VW(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},Kke)}async function WW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names loan ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let i={resourceId:t};for(let[o,s]of Object.entries(r))s!==void 0&&o!=="resourceId"&&(i[o]=s);return i.reference===void 0&&(i.reference=(n??(await UE(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function KW(e,t){await e.delete(`/api/v1/loans/${t}`)}async function XW(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},hZ)}async function ZW(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},hZ)}async function e4(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function t4(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function r4(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function n4(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function i4(e,t){return e.post("/api/v1/loans/preview-schedule",t,et)}async function o4(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,et)}async function s4(e,t){return ht(t,"loans",500,"loans"),qo(t,Act),En(e,"/api/v1/loans/bulk-upsert","loans",t)}async function a4(e,t){return ht(t,"loans",500,"loans"),qo(t,i0r),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw ct(new ue(`loans[${n}]${typeof i=="string"?` (${i})`:""} has tags, which would replace every tag on that loan. Bulk update does not take tags: change them with update_loan (clio loans update), which keeps the tags you do not name. Nothing was changed.`))}}),En(e,"/api/v1/loans/bulk-update","loans",t)}async function c4(e,t,r,n,i){let o=dO[t];if(i){if(!o.calculate)throw new Error(`Loan event ${t} has no preview.`);let s=Object.fromEntries(Object.entries(n).filter(([a])=>!o.recordOnly?.includes(a)));return e.post(o.calculate,{...s,resourceId:r},et)}return e.post(o.record(r),{...n,resourceId:r},Xke)}var Act,i0r,dO,MAe=J(()=>{"use strict";an();it();tr();Act=["drawdownDate","trackingStartDate","firstRepaymentDate"],i0r=[...Act,"capitalizationStartDate","capitalizationEndDate"];dO={drawdown:{calculate:"/api/v1/loans/calculate-drawdown",record:e=>`/api/v1/record-drawdown/loans/${e}`},prepayment:{calculate:"/api/v1/loans/calculate-prepayment",record:e=>`/api/v1/prepay/loans/${e}`},rateChange:{calculate:"/api/v1/loans/calculate-rate-change",record:e=>`/api/v1/change-rate/loans/${e}`},capitalization:{calculate:"/api/v1/loans/calculate-capitalization",record:e=>`/api/v1/capitalize-interest/loans/${e}`},paymentHoliday:{calculate:"/api/v1/loans/calculate-payment-holiday",record:e=>`/api/v1/payment-holiday/loans/${e}`},restructure:{calculate:"/api/v1/loans/calculate-restructure",record:e=>`/api/v1/restructure/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},settlement:{calculate:"/api/v1/loans/calculate-settlement",record:e=>`/api/v1/settle/loans/${e}`},forgiveness:{calculate:"/api/v1/loans/calculate-forgiveness",record:e=>`/api/v1/forgive/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},conversion:{calculate:"/api/v1/loans/calculate-conversion",record:e=>`/api/v1/convert-to-shares/loans/${e}`,recordOnly:["gainLossAccountResourceId"]},refinance:{record:e=>`/api/v1/refinance/loans/${e}`},reclassifyAsCurrent:{record:e=>`/api/v1/reclassify-as-current/loans/${e}`},undo:{record:e=>`/api/v1/undo-event/loans/${e}`}}});function Av(e){ht(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new ue(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(!jFe(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!o0r.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new ue(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function l4(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},et);return{data:a0r(r.data)}}function s0r(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function a0r(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(s0r),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function u4(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function d4(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var o0r,UAe=J(()=>{"use strict";it();fee();an();tr();o0r=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function bct(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new ue("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function $Ae(e,t){if(!e||typeof e!="object")throw new ue(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new ue(`${t}.lineItems array is empty.`);if(n.length>500)throw new ue(`max 500 ${t}.lineItems per call.`);qo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&qo([i],["valueDate"])}async function p4(e,t,r=qAe){return e.post("/api/v1/search-magic-reconciliation",t,{...et,timeoutMs:r})}function f4(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function d0r(e){let t=f4(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=f4(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function f0r(e){return e?e.value>=(e.from==="confidenceScore"?c0r:l0r)?"high":e.value>=u0r?"medium":"low":"low"}function h0r(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(gct,t))return;let r=gct[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function aA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function yct(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function m0r(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>yct({account:aA(n?.account),taxProfile:aA(n?.taxProfile),description:typeof n?.description=="string"&&n.description!==""?n.description:void 0,amount:t(n?.amount),amountPercentage:t(n?.amountPercentage)})).filter(n=>n!==void 0);if(!(!aA(e.contact)&&!aA(e.account)&&!aA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return yct({contact:aA(e.contact),account:aA(e.account),taxProfile:aA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function Ict(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,checkpointReason:"NO_RECOMMENDATION",alternativeCount:0});continue}let d=u.map(h=>b0r(c,h??{},u.length-1,t)).sort(A0r),f=d.filter(h=>h.passesGates),p=f[0];p?.suggestion.autoCommitEligible&&f.some(h=>h.score===p.score&&h.tieKey!==p.tieKey)&&(p.suggestion={...p.suggestion,autoCommitEligible:!1,checkpointReason:"AMBIGUOUS_TIE"}),o.push((p?.suggestion.autoCommitEligible?p:d[0]).suggestion)}return o}function A0r(e,t){let r=e.score??-1/0,n=t.score??-1/0;return r!==n?n-r:e.tieKey<t.tieKey?-1:e.tieKey>t.tieKey?1:0}function g0r(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return vc.test(t)?t:void 0}function y0r(e){let{recommendationId:t,...r}=e;return r}function E0r(e,t,r){return!t||!r?t:e===$E.learnedPrediction?{...t,recommendationId:r}:e===$E.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function b0r(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=f4(t.matchScore),s=f4(t.confidenceScore),a=d0r(t),c=typeof t.isCrossCurrency=="boolean"?t.isCrossCurrency:void 0,u=typeof t.lifecycleStatus=="string"?t.lifecycleStatus:void 0,d=typeof t.cftBtResourceId=="string"?t.cftBtResourceId:void 0,f=Array.isArray(t.cftBtResourceIds)?t.cftBtResourceIds:[],p=t.isBatch===!0||f.length>1,h=typeof t.cftAmount=="number"?t.cftAmount:void 0,m,A;switch(i){case"MAGIC_MATCH":{p&&f.length>0?(m=$E.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=$E.withPayments,A={bankStatementEntryResourceId:e,businessTransactionPayments:[{cashflowTransactionResourceId:d,...h!==void 0?{transactionAmount:h}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let F=typeof t.learnedPredictionResourceId=="string"?t.learnedPredictionResourceId:void 0,G=typeof t.predictedPayload=="string"?t.predictedPayload:void 0,j=typeof t.predictedPayloadSchemaVersion=="string"?t.predictedPayloadSchemaVersion:void 0;F&&G&&j&&(m=$E.learnedPrediction,A={bankStatementEntryResourceId:e,learnedPredictionResourceId:F,predictedPayload:G,predictedPayloadSchemaVersion:j});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let F=t.actionShortcut??{},G=typeof F.resourceId=="string"?F.resourceId:void 0;G&&(m=$E.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=E0r(m,A,g0r(t)),y=m?f0r(a):"low",b=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||b&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==$E.withPayments||b,T=h0r(t),D=!m||!g?"NO_PLAN":T?p0r[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!b?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",k=m0r(t);return{suggestion:{bankStatementEntryResourceId:e,recommendationType:i,matchScore:o,confidenceScore:s,isCrossCurrency:c,...u!==void 0?{lifecycleStatus:u}:{},recommendedTool:m,execute:g,confidenceTier:y,autoCommitEligible:D===void 0,...D?{checkpointReason:D}:{},...k?{proposedPosting:k}:{},alternativeCount:r,matchAmount:h,matchedTransactionResourceId:d??f[0],matchedTransactionCount:f.length||(d?1:void 0)},passesGates:T===void 0,score:a?.value,tieKey:A?`0${JSON.stringify(A)}`:`1${JSON.stringify(y0r(t))}`}}function I0r(e,t,r,n){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,...e.checkpointReason?{checkpointReason:e.checkpointReason}:{},recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,...n?{bankLine:t}:{},match:r}}async function C0r(e,t,r,n){let i=t.matchedTransactionResourceId,o=t.matchedTransactionCount;if(!i)return t.matchAmount===void 0&&!t.proposedPosting?null:{type:"transaction",amount:t.matchAmount,count:o,...t.proposedPosting?{proposedPosting:t.proposedPosting}:{}};let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await fo(e,i):await go(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${RE(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function Cct(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,Ect);if(i.length===0)return{items:[]};let o=new Map,s=[];n.length>i.length&&s.push(`review detail: ${n.length} lines need review and review lists the first ${i.length}; re-call with the other entries' ids for the rest`);let a=!1;if(t)try{let u=i.map(p=>p.bankStatementEntryResourceId).filter(Boolean),d=await iC(e,t,{filter:{resourceId:{in:u}},limit:Ect}),f=Array.isArray(d)?d:d?.data??[];for(let p of f)o.set(p.resourceId,p);a=!0}catch(u){s.push(`bank-line detail: ${RE(u)}`)}else s.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(i.map(async u=>{let d=o.get(u.bankStatementEntryResourceId),f=d?{valueDate:d.valueDate,netAmount:d.netAmount,currencyCode:d.currencyCode,currencySymbol:d.currencySymbol,description:d.description,counterparty:d.extContactName}:null;return I0r(u,f,await C0r(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function h4(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,zs)}async function m4(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,zs)}async function A4(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,zs)}async function g4(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,zs)}async function y4(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,zs)}async function E4(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,zs)}async function b4(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,zs)}async function I4(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,zs)}async function C4(e,t){return e.post("/api/v1/reconciliations/with-payments",t,zs)}async function _4(e,t){return e.post("/api/v1/reconciliations/match-to-transaction",t,zs)}async function w4(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,zs)}async function v4(e,t){return e.post("/api/v1/reconciliations/magic-match",t,zs)}async function S4(e,t){return e.post("/api/v1/reconciliations/reset",t)}var $E,qAe,c0r,l0r,u0r,p0r,gct,Ect,D4=J(()=>{"use strict";Rg();TE();it();lf();an();zg();tr();$E={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},qAe=6e4;c0r=.9,l0r=.95,u0r=.7;p0r={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},gct={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};Ect=25});function oa(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let o=e[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Qo(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:jAe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=jAe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=jAe(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=e[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(w=>w.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,b=a.debitAmount,E=a.creditAmount,C=a.type??(typeof b=="number"&&b>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||C||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function jAe(e,t,r,n,i){let o=i.find(s=>s.field===t);if(!o){let s=e[t];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(e)){let s=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function ts(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=oa(e,t,n),a=Qo(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var xa,rl,_o,ou,_ct=J(()=>{"use strict";xa=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],rl=[...xa],_o=xa.filter(e=>e.field!=="dueDate"),ou=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function Ed(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let o=_c(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function R4(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let o=OI(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var wct=J(()=>{"use strict";af()});var YAe=J(()=>{"use strict";_ct();af();wct()});var fO,T4,rs,io,HAe=J(()=>{"use strict";fO="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",T4=["find & fix","find and fix","find & recode","find and recode","recode","reclassify","bulk edit","change all","move these to account","retag","re-date","change the contact on all","fix the account on every"],rs="If the result says it runs in the background, do not poll: its result arrives by itself.",io=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${rs} PARTIAL_SUCCESS: errorDetails.`});function Sct(e){return _0r.get(e)}function Dct(e,t=5){let r=e.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_]+/).flatMap(o=>{let s=o.split("-");return s.length===1?s:s.filter(a=>a.length>=3)}).filter(o=>o.length>=2&&!x4.has(o));return n.length===0?[]:Li.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,t).map(o=>o.ns)}var Li,vct,x4,_0r,bd=J(()=>{"use strict";HAe();TAe();Li=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, accept a quote, confirm an order, void, delete a draft. A Sale Order links to its quote via saleQuoteResourceId; the quote must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (convert_sale_order_to_invoice).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, accept a request, confirm an order, void, delete a draft. A Purchase Order links to its request via purchaseRequestResourceId; the request must be issued (not DRAFT/VOID). Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (convert_purchase_order_to_bill).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry (write side). Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments, the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Fourteen endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), match_to_transaction (several entries to ONE open document), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction / unapplied_payment (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side, except match_to_transaction, which needs transactionAmount + currencySettings with a rate when the document and bank account currencies differ or the bank account is not in the base currency. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created; it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace; switch there or call by name).",groups:["financial_reports"]},{name:"report_templates",title:"Report Templates",description:"Report templates: the saved layout of a report (title, fonts, rows, columns, period) and report packs (several reports in one document). List, read, search, create, edit, set the default, delete. Customize or rename a P&L, balance sheet, cash flow, trial balance, GL, GST/VAT ledger or aging layout; change which template a report uses by default. Render a template with download_export.",groups:["report_templates"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights. Fixed asset register reports are in register_reports.",groups:["operational_reports","exports"]},{name:"register_reports",title:"Register Reports",description:"Register reports: fixed asset register summary by account, type, category or active/closed-out/disposed state (asset register roll-forward over a period), fixed asset register vs general ledger reconciliation (does the register agree with the GL), deferrals summary (prepaid and deferred revenue roll-forward) and deferrals reconciliation (does the prepaid register agree with the GL), lease register summary (IFRS 16 lease note, lease liability roll-forward) and lease register vs general ledger reconciliation (rent coded to the lease liability account). Loan reports: borrowings note summary, loan roll-forward, related-party (director, shareholder) loan balances, loan interest cost, maturity analysis (liquidity note), loan register vs ledger reconciliation.",groups:["register_reports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema), sync preview (\u2264100 rows) and polling a CSV export (get_pseudo_sql_export). Use when search_* / download_export canonical reports don't cover the question. To export a query as CSV, use pseudo_sql_exports.",groups:["pseudo_sql"]},{name:"pseudo_sql_exports",title:"Ad-hoc Query Exports (SQL)",description:"Export a pseudo-SQL query result as a CSV file: start an async export (then poll get_pseudo_sql_export in pseudo_sql), or run and download in one call. Write and preview the query with pseudo_sql first.",groups:["pseudo_sql_exports"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Contact signals: usual values and billing rhythm. Bulk upsert contacts from CSV / spreadsheet imports: async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs: named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tracking tags (tags): transaction-level labels for filtering reports. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"tracking_categories",title:"Tracking Categories",description:"Nano classifiers: dimensions (department, cost center, project) per line item, or on a register record as a whole. List, search, create, update, delete classifiers and their classes. Used for dimensional reporting. Not tracking tags (use the tags_and_custom_fields namespace). Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts, including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes. Search tax return filings (BIR, GST F5).",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules: how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via create_claim, document attachment or conversion; the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only, no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once; asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); link or unlink a login user; and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"transaction_groups",title:"Transaction Groups (Capsules)",description:"Transaction groups (capsules): group related transactions (a loan and its repayments, a prepaid bill and its amortization journals). Create, get, update, delete, search capsules; list and create capsule types; move transactions between capsules.",groups:["capsules"]},{name:"calculators",title:"Financial Calculators",description:"Offline financial calculators: amortization, depreciation, deferred revenue, prepaid amortization, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal, accruals, leave accrual, dividends. Returns the schedule and journal lines; posts nothing. For what-if questions and topics with no register; to keep a lease, loan, prepaid or deferred revenue use its register. Keywords: calculate, what-if, monthly payment, provision, schedule, expected credit loss, revaluation, amortize, recipe, prepaid-expense, accrued-expense.",groups:["calculators"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate, set up to repeat every month.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). Agent context bundle. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",groups:["organization","org_users","modules"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets: CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_transaction_from_document, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork ("create docs from this Dropbox folder link", a pile/batch of invoices and bills) into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"],channelToolsDescription:"Check the progress of background tasks a request started, add to a waiting one, or cancel it."},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update (one or bulk), discard, sell, transfer, undo disposal, close out (stop depreciating, keep the asset) and reopen. Also: depreciation, asset register. Depreciation schedules, totals, eligible bill lines and asset types are in fixed_asset_schedules.",groups:["fixed_assets"]},{name:"fixed_asset_schedules",title:"Fixed Asset Schedules & Totals",description:"Read-only fixed asset views. Show one asset's depreciation by month and year, net book value, asset register totals as at a date, disposal totals (gain/loss), eligible bill lines to register as assets, asset types. Check custom depreciation ranges; calculate disposal (accumulated depreciation, net book value) before selling or discarding.",groups:["fixed_asset_schedules"]},{name:"deferrals",title:"Deferrals (Prepaid & Deferred Revenue)",description:"Deferrals register: prepaid expense, prepayment, deferred revenue, unearned revenue. Spread a bill over months, recognise an invoice over months (amortization, release schedule). Search, create, update, delete, stop amortising early (close out) and undo it, totals as at a date, schedule, eligible bill or invoice lines, deferral types and deferral accounts (mark the accounts first), bulk create and update.",groups:["deferrals"]},{name:"leases",title:"Leases (IFRS 16)",description:"Leases under IFRS 16: put an office rent lease on the books (right-of-use asset, ROU, and lease liability, current and non-current), hire purchase (flat rate to monthly discount rate), short-term or low-value exemption. Search, create, update, delete, close out, terminate lease (preview the gain or loss first) and undo either; lease schedule, liability totals as at a date, rent schedule preview, lease types.",groups:["leases"]},{name:"loans",title:"Loans (Borrowings)",description:"Loans and borrowings register: record a new bank loan, loan, borrowing, bank loan, term loan, director's loan (revolving credit and loans given are not in the register), instalment / installment loan. Search, create, update (one or bulk), delete, close out. What do we owe a lender or the bank: outstanding principal, current and non-current at a date, the repayment schedule, an on-demand loan ledger (an on-demand loan has no schedule, is all current and posts no interest), loan types, preview the monthly payment. Loan changes (drawdown, prepay, rate change, settle) are in loan_events; loan reports are in register_reports.",groups:["loans"]},{name:"loan_events",title:"Loan Events",description:"Events on an existing loan: drawdown, prepay or extra repayment, rate change, payment holiday, capitalize interest, restructure, refinance, settle / payoff, forgive / write off a loan, convert loan to shares, covenant breach (reclassify as current), undo loan event, balance after a missed payment. preview: true calculates the figures and saves nothing.",groups:["loan_events"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Record a withholding tax certificate from a customer (BIR Form 2307, CWT). Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"unapplied_payments",title:"Unapplied Payments",description:"Cash received or paid before it is applied to invoices or bills: record (or draft and finalize), search, apply to documents, attach existing payments, remove an application, edit, delete. Also: unallocated receipts, customer deposits, advances, prepayments, payments on account. To record one straight from a bank record, use reconcile_unapplied_payment in reconciliations.",groups:["unapplied_payments"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve invoices, bills and credit notes awaiting approval, or send documents back for changes (also orders, quotes, requests, claims). Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:`Quick Fix: bulk-update or set fields on transactions or line items in one call, on ${Mat}. On a record: ${Uat}. On lines: ${$at}. Ledger Find & Fix: preview one change to records found by filter across those types, run it once the user confirms. Also: batch update, mass edit, ${T4.join(", ")}.`,groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions: both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK: one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"collab",title:"Collaboration",description:"Comment threads on bills, invoices, credit notes and bank records: list threads and comments, add a reply or start a thread, mention a teammate, update or delete your own comment, resolve a thread. Notifications: list unread mentions and comments, mark one read or unread, mark all read.",groups:["collaboration"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user, including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see (for invoices, bills, reports, settings, or a specific transaction).",groups:["navigation"]}],vct=[{name:"dashboard_page",title:"Dashboard Page",description:"The dashboard page the user is viewing, in their browser.",groups:["page"],channelToolsDescription:"Read what it shows and act on it."}],x4=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),_0r=new Map(Li.flatMap(e=>e.groups.map(t=>[t,e.name])))});function Id(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function w0r(e){let t=Rct.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(Id(r),n);for(let r of e.enum??[])t.set(Id(r),r);Rct.set(e,t)}return t}function Tct(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=Id(e);if(!r)return null;let n=w0r(t).get(r);return n!==void 0&&n!==e?n:null}function v0r(e){let t=xct.get(e);return t||(t=new Map(Object.keys(e).map(r=>[Id(r),r])),xct.set(e,t)),t}function S0r(e){let t=e.trim();if(!t.startsWith("[")||!t.endsWith("]"))return null;try{let r=JSON.parse(t);return Array.isArray(r)?r:null}catch{return null}}function D0r(e){let t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{let r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function zAe(e,t,r,n){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let i=e,o=null,s=()=>o??=Object.assign(Object.create(null),i),a=v0r(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=Id(c),g=A?a.get(A):void 0;g&&!(g in i)&&!(g in(o??{}))&&(f=g,s()[g]=d,delete s()[c],n.push({path:`${r}${g}`,from:c,to:g,kind:"name"}))}if(d==null)continue;let p=t[f];if(!p)continue;if((p.type==="array"||p.type==="object")&&typeof d=="string"){let A=p.type==="array"?S0r(d):D0r(d);A&&(n.push({path:`${r}${f}`,from:d.length>80?`${d.slice(0,77)}...`:d,to:p.type==="array"?"a list":"an object",kind:"shape"}),s()[f]=A,d=A)}let h=Tct(d,p);if(h!==null){n.push({path:`${r}${f}`,from:d,to:h,kind:"value"}),s()[f]=h;continue}if(p.type==="array"&&Array.isArray(d)&&p.items?.enum){let A=!1,g=d.map((y,b)=>{let E=Tct(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${b}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=bee(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let b=zAe(y,m.schema,`${r}${f}[].`,n);return b!==y&&(A=!0),b});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=zAe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function kct(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:zAe(t,e.params,"",r),coercions:r}}function Nct(e){return e.map(t=>t.kind==="name"?`Param "${t.from}" is not declared; it was read as "${t.to}". Prefer "${t.to}" \u2014 it is the documented name.`:t.kind==="shape"?`"${t.path}" was sent as JSON text; it was read as the ${t.to==="a list"?"list":"object"} it contains. Send ${t.to}, not a string.`:`"${t.path}": sent "${t.from}", accepted as "${t.to}". Use "${t.to}" \u2014 it is the declared value.`)}var Rct,xct,JAe=J(()=>{"use strict";FU();Rct=new WeakMap;xct=new WeakMap});function gv(e){let t=new Set,r=[];for(let n of e)for(let i of su(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function pO(){return Li.map(e=>{let t=gv(e.groups),r=t.filter(i=>i.isDestructive??!1).length,n=t.filter(i=>i.readOnly).length;return{namespace:e.name,operations:t.length,read:n,write:t.length-n-r,destructive:r,summary:(e.description.split(".")[0]??"").trim()}})}function R0r(e,t,r){let n=e==="namespace"?`Each entry in your tool list is a namespace router: ${t} entries, ${r} operations. Every tool's description lists its own operations.`:e==="meta"?`Your tool list holds discovery tools, not the catalogue: ${t} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${t} entries for ${r} operations.`;return{shape:e,this_connector_lists:t,operations:r,note:n}}function T0r(e){return{shape:"operations",operations:e,note:`Your tool list shows chosen operations as their own tools; call those by name. Any namespace router in it reaches the rest of the ${e} operations with { operation, arguments }.`}}function cA(e,t=!1){let r=lA(void 0).length,n=Li.length,i=e==="namespace"?n+(t?1:0):e==="flat"?r+(t?1:0):e==="meta"?3+(t?1:0):void 0;return{operations:r,namespaces:n,...e==="operations"?{packaging:T0r(r)}:e&&i!==void 0?{packaging:R0r(e,i,r)}:{},map:pO(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var k4=J(()=>{"use strict";bd();au()});function N4(e){let t={type:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.enum),e.type==="array"&&e.items&&(t.items=N4(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=N4(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function cu(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=N4(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function hO(e){return{name:e.name,description:e.description,input_schema:cu(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var yv=J(()=>{"use strict"});function mO(e){if(typeof e!="string")return e.isDestructive??!1;let t=e;return t.startsWith("delete_")||t.startsWith("pay_")||t.startsWith("finalize_")||t.includes("refund")||t==="remove_org_user"}function GAe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function B4(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&mO(e),idempotentHint:e.readOnly,openWorldHint:GAe(e)}}function k0r(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function N0r(e){let t=k0r(e);return!t||x0r.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!x4.has(n)).length===0}function VAe(e){return e===void 0||e==="flat"?"Call the operation by its own name.":e==="operations"?"Call the operation by its own name if your tool list has it; otherwise through this namespace tool with { operation, arguments }.":"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}function WAe(e,t=""){return Object.entries(e).flatMap(([r,n])=>{let i=t+r,o=n.properties??n.items?.properties;return[n.description?`${i}: ${n.description}`:i,...o?WAe(o,`${i}.`):[]]})}function O0r(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
663
663
|
`)[0]}`.toLowerCase(),n=[...e.description.split(`
|
|
664
664
|
`).slice(1),...WAe(e.params)].map(i=>i.trim()).filter(Boolean);for(let i of t){if(r.includes(i))continue;let o=n.find(s=>s.replace(/\b(Only|Not): [^.]*\./g,"").toLowerCase().includes(i));if(o)return o.length>Bct?`${o.slice(0,Bct-1)}\u2026`:o}}function O4(e,t="meta"){let r=t==="meta"?"search_tools with an empty query":"describe_capabilities with no arguments";if(N0r(e)){if(t!=="meta")return cA(t);let{next:a,...c}=cA();return{...c,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let n=xl(e.trim());if(n)return{matches:[],hint:n};let i=Dct(e,5);if(i.length===0){let{operations:a,namespaces:c}=cA();return{matches:[],hint:`No operation matches "${e}". Jaz has ${a} operations across ${c} namespaces \u2014 call ${r} for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let s=e.toLowerCase().split(/\s+/).filter(Boolean);return{matches:i.map(a=>{let c=a.groups.flatMap(m=>su(m)),u=c.map(m=>`${m.name} ${(m.aliases??[]).join(" ")} ${m.searchHint??""} ${m.description} ${WAe(m.params).join(" ")}`.toLowerCase()),d=new Map(s.map(m=>{let A=u.filter(g=>g.includes(m)).length;return[m,Math.log((c.length+1)/(A+1))]})),f=s.slice(1).map((m,A)=>`${s[A]} ${m}`),p=c.map((m,A)=>{let g=u[A],y=s.reduce((b,E)=>g.includes(E)?b+(d.get(E)??0):b,0)+f.filter(b=>g.includes(b)).length;return{tool:m,score:y}}).sort((m,A)=>A.score-m.score),h=[...d].filter(([m,A])=>A>0&&m.length>=3&&!x4.has(m)&&!B0r.has(m)).sort((m,A)=>A[1]-m[1]).map(([m])=>m);return{namespace:a.name,description:a.description,tools:p.map(m=>{let A=m.score>0?O0r(m.tool,h):void 0;return{name:m.tool.name,description:m.tool.description.split(`
|
|
665
665
|
`)[0],...m.tool.searchHint?{searchHint:m.tool.searchHint}:{},...A?{matched:A}:{}}})}}),hint:t==="meta"?"Call describe_tools with the tool names you need, then execute_tool to run them.":`These are summaries. Before concluding something is unsupported, open the namespace with describe_capabilities({ namespace }) for every operation and its parameters. ${VAe(t)}`}}function Oct(e){if(!Array.isArray(e)||!e.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(e.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let t=[],r=[];for(let n of e){let i=AO(n);if(!i){r.push(n);continue}t.push({...hO(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&mO(i),group:i.group})}return{tools:t,...r.length>0?{notFound:r,hint:r.map(xl).find(Boolean)??`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var x0r,Bct,B0r,F0r,L0r,Q0r,Ev,uA,qE=J(()=>{"use strict";bd();k4();au();yv();hg();x0r=new Set(["capabilities","capability","overview","everything","catalog","catalogue","menu","features","feature list","functions","tool list","all tools","all operations","list tools","list all tools","list operations","full list","full catalog","full catalogue","whats available","what is available","whats possible","show everything","show me everything","what else can you do","how many tools","how many operations"]);Bct=160,B0r=new Set(["change","changes","changing","update","updates","updating","edit","modify","set","make","existing","new","add","create","remove","delete","all","every","each","these","those","record","records","want","need","keep","keeping","remaining","unchanged","while","only"]);F0r={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:cu({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};L0r={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:cu({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},Q0r={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:cu({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},Ev={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs to pass as org_id on other tool calls.",inputSchema:cu({},[])},uA=[F0r,L0r,Q0r]});function $0r(e){if(!(ka in e))return{cleanedInput:e};let{[ka]:t,...r}=e;return{jotText:typeof t=="string"&&t.trim()!==""?t.trim():void 0,cleanedInput:r}}function gO(e){return!e.readOnly&&!e.params[ka]&&e.group!=="jots"}function Qct(e,t){if(e.params[ka])return{cleanedInput:t};let{jotText:r,cleanedInput:n}=$0r(t);return gO(e)?{jotText:r,cleanedInput:n}:{cleanedInput:n}}function q0r(e){let t=M0r.exec(e);return t?{kind:t[1],call:e.slice(t[0].length)||e}:{call:e}}function Y0r(e){let t=e.toLowerCase();for(let[r,n]of j0r)if(n.test(t))return r}function H0r(e,t){let r=Y0r(e),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=Fct||a>U0r||!s||typeof s!="object")){if(Array.isArray(s)){for(let c of s)o(c,a+1);return}for(let[c,u]of Object.entries(s)){if(n.length>=Fct)return;c==="resourceId"&&typeof u=="string"&&u&&!i.has(u)?(i.add(u),n.push(u)):o(u,a+1)}}};return o(t,0),n.map(s=>({id:s,...r?{relation:r}:{}}))}function F4(e,t,r,n){let{kind:i,call:o}=q0r(r),s=H0r(t,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${t}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};Zw(e,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(AD(),mD)).then(({log:d})=>d.error({tool:t,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${t}): ${u}
|
|
@@ -761,14 +761,14 @@ bulk_finalize_drafts only handles invoices/bills/credit-notes; journals need thi
|
|
|
761
761
|
|
|
762
762
|
Each row: resourceId plus any of reference, valueDate, notes, tags, saveAsDraft; omitted fields keep their value. Drafts only: rows send no lines, which a recorded (ACTIVE) journal requires; edit those with quick_fix_transactions or update_journal.
|
|
763
763
|
|
|
764
|
-
Response: { updated: [{resourceId}], failed: [{resourceId, error, errorCode, status}], updatedCount, failedCount }. Per-row execution: partial results are normal; retry only failed[].resourceId. errorCode + status come from the underlying JazApiError when available.`,params:{items:{type:"array",description:"Journal updates (max 500). Each row needs resourceId; other fields optional.",items:{type:"object",properties:{resourceId:{type:"string",description:"Journal resourceId"},reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD"},notes:{type:"string"},tags:jo,saveAsDraft:{type:"boolean",description:"false = finalize (lift DRAFT to ACTIVE)"}},required:["resourceId"]}}},required:["items"],group:"journals",readOnly:!1,isDestructive:!0,searchHint:"bulk update finalize multiple draft journals at once batch promote",execute:async(e,t)=>{let r=t.items;ht(r,"items",500,"journal updates");let n=[],i=[];for(let o of r)try{let s=Ui(o.tags,"items[].tags"),a=s&&await Yo("journal",o.resourceId,()=>vs(e.client,o.resourceId));await FC(e.client,o.resourceId,{reference:o.reference,valueDate:o.valueDate,internalNotes:o.notes,tags:s&&Ki(a?.tags,s),saveAsDraft:o.saveAsDraft},a),n.push({resourceId:o.resourceId})}catch(s){let a=s instanceof Error?s.message:String(s),c={resourceId:o.resourceId,error:a};if(s instanceof gr){c.status=s.status;let u=s.body;if(u&&typeof u=="object"){let d=u.errorCode;typeof d=="string"&&(c.errorCode=d)}}i.push(c)}return{updated:n,failed:i,updatedCount:n.length,failedCount:i.length}}},{name:"import_bank_statement",description:`Import a bank statement from a URL or an attached file (max 10 MB). Processing is async; check magic workflows for status. ${rs}`,params:{accountResourceId:{type:"string",description:"Bank account resourceId to import into"},sourceUrl:{type:"string",description:"URL of the bank statement file"}},required:["accountResourceId"],acceptsHostFile:!0,group:"bank",readOnly:!1,searchHint:"import bank statement CSV OFX file upload",backgroundJob:dge("BANK_STATEMENT","sourceUrl","bank statement"),execute:async(e,t)=>{let r=SE({sourceUrl:t.sourceUrl});return[...r,...e.file_blob?["file"]:[]].length!==1?iA(["sourceUrl"],{provided:r,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1,importDestination:"bank-reconciliation.modal.import-bank-feed"}):oC(e.client,{businessTransactionType:"BANK_STATEMENT",accountResourceId:t.accountResourceId,sourceUrl:t.sourceUrl,sourceFile:e.file_blob?.data,sourceFileName:e.file_blob?.fileName})}},{name:"add_bank_records",description:`Create bank statement entries via JSON POST (1-100 records per call). For CSV/OFX file imports, use import_bank_statement instead.
|
|
764
|
+
Response: { updated: [{resourceId}], failed: [{resourceId, error, errorCode, status}], updatedCount, failedCount }. Per-row execution: partial results are normal; retry only failed[].resourceId. errorCode + status come from the underlying JazApiError when available.`,params:{items:{type:"array",description:"Journal updates (max 500). Each row needs resourceId; other fields optional.",items:{type:"object",properties:{resourceId:{type:"string",description:"Journal resourceId"},reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD"},notes:{type:"string"},tags:jo,saveAsDraft:{type:"boolean",description:"false = finalize (lift DRAFT to ACTIVE)"}},required:["resourceId"]}}},required:["items"],group:"journals",readOnly:!1,isDestructive:!0,searchHint:"bulk update finalize multiple draft journals at once batch promote",execute:async(e,t)=>{let r=t.items;ht(r,"items",500,"journal updates");let n=[],i=[];for(let o of r)try{let s=Ui(o.tags,"items[].tags"),a=s&&await Yo("journal",o.resourceId,()=>vs(e.client,o.resourceId));await FC(e.client,o.resourceId,{reference:o.reference,valueDate:o.valueDate,internalNotes:o.notes,tags:s&&Ki(a?.tags,s),saveAsDraft:o.saveAsDraft},a),n.push({resourceId:o.resourceId})}catch(s){let a=s instanceof Error?s.message:String(s),c={resourceId:o.resourceId,error:a};if(s instanceof gr){c.status=s.status;let u=s.body;if(u&&typeof u=="object"){let d=u.errorCode;typeof d=="string"&&(c.errorCode=d)}}i.push(c)}return{updated:n,failed:i,updatedCount:n.length,failedCount:i.length}}},{name:"import_bank_statement",description:`Import a bank statement from a URL or an attached file (max 10 MB). Processing is async; check magic workflows for status. ${rs}`,params:{accountResourceId:{type:"string",description:"Bank account resourceId to import into"},sourceUrl:{type:"string",description:"URL of the bank statement file"}},required:["accountResourceId"],acceptsHostFile:!0,group:"bank",readOnly:!1,fetchesCallerUrl:!0,searchHint:"import bank statement CSV OFX file upload",backgroundJob:dge("BANK_STATEMENT","sourceUrl","bank statement"),execute:async(e,t)=>{let r=SE({sourceUrl:t.sourceUrl});return[...r,...e.file_blob?["file"]:[]].length!==1?iA(["sourceUrl"],{provided:r,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1,importDestination:"bank-reconciliation.modal.import-bank-feed"}):oC(e.client,{businessTransactionType:"BANK_STATEMENT",accountResourceId:t.accountResourceId,sourceUrl:t.sourceUrl,sourceFile:e.file_blob?.data,sourceFileName:e.file_blob?.fileName})}},{name:"add_bank_records",description:`Create bank statement entries via JSON POST (1-100 records per call). For CSV/OFX file imports, use import_bank_statement instead.
|
|
765
765
|
|
|
766
766
|
Fields per record:
|
|
767
767
|
- amount (required): positive = cash-in, negative = cash-out
|
|
768
768
|
- transactionDate (required): YYYY-MM-DD
|
|
769
769
|
- description, payerOrPayee, reference: optional strings
|
|
770
770
|
|
|
771
|
-
Returns {data: {errors: []}} on success. accountResourceId must be a bank-type CoA account (find via list_bank_accounts).`,params:{accountResourceId:{type:"string",description:"Bank account resourceId (from list_bank_accounts)"},records:{type:"array",items:{type:"object",properties:{amount:{type:"number",description:"Positive = cash-in, negative = cash-out"},transactionDate:{type:"string",description:"Date (YYYY-MM-DD)"},description:{type:"string",description:"Description"},payerOrPayee:{type:"string",description:"Payer or payee name"},reference:{type:"string",description:"Reference"}},required:["amount","transactionDate"]},description:"Array of 1-100 bank records"}},required:["accountResourceId","records"],group:"bank",readOnly:!1,searchHint:"add manual bank transaction records entries",execute:async(e,t)=>gU(e.client,t.accountResourceId,t.records)},{name:"create_transaction_from_document",description:`Create a business transaction (invoice/bill/credit note/quote/order/purchase request) from a SINGLE file (max 10 MB), a URL, or raw HTML (e.g. an email body) using AI extraction. Processing is async: the result is a workflow id, not the record. ${rs} Quotes/orders land DRAFT/PENDING: relay the result \`next\`. When the host conversation provides a file with the call, omit all source arguments; the file is used automatically. For a FOLDER, a .zip, a Dropbox/Drive/OneDrive folder share link, or several/mixed documents at once, use classify_documents (then extract_documents) instead, not this per-file.`,params:{businessTransactionType:{type:"string",enum:[...qZ],description:"Type of transaction to create"},sourceUrl:{type:"string",description:"URL the Jaz server fetches, or a Telegram file link (downloaded here)."},attachmentId:{type:"string",description:'Pass "email-body" to use the inbound email body (email channel). No other attachment-id source.'},html:{type:"string",description:"Raw HTML (e.g. email body), rendered to PDF then extracted."},internalNotes:{type:"string",description:"Internal notes on the record (max 3000 chars)."}},required:["businessTransactionType"],group:"magic",readOnly:!1,acceptsHostFile:!0,searchHint:"create transaction from attachment URL or email HTML AI extraction",backgroundJob:dge("MAGIC_WORKFLOW","sourceUrl","document"),execute:async(e,t)=>{let r=t.businessTransactionType,n=t.internalNotes;if(t.attachmentId==="email-body"){let a=SE({sourceUrl:t.sourceUrl,html:t.html});if(a.length>0||e.file_blob)return iA(["attachmentId (email-body)","sourceUrl","html"],{provided:["attachmentId (email-body)",...a],hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1});let c=e.html_blob;return c?uge(r,await gf(e.client,{businessTransactionType:r,html:c,internalNotes:n})):vE('attachmentId "email-body" requires an inbound email body, and this run has none.',"That value only works on the email channel. Pass sourceUrl or html instead.")}if(t.attachmentId)return vE('This tool has no attachment-id source. "email-body" is the only accepted value, and only on the email channel.',`Use one of: ${tO({acceptsLocalPath:!1,acceptsAttachmentId:!1})}.`);let i=SE({sourceUrl:t.sourceUrl,html:t.html}),o=i.length+(e.file_blob?1:0);if(o===1&&e.file_blob)return uge(r,await gf(e.client,{businessTransactionType:r,sourceFile:e.file_blob.data,sourceFileName:e.file_blob.fileName,internalNotes:n}));if(o!==1)return iA(["sourceUrl","html"],{provided:i,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1,importDestination:GSr[r]??"purchases.modal.import-bills"});let s=t.sourceUrl;return uge(r,await gf(e.client,{businessTransactionType:r,sourceUrl:s,html:t.html,internalNotes:n}))}},{name:"get_magic_workflow_status",description:"Get the current status of specific magic workflow(s) by resourceId(s). Returns workflow details including status, document type, and results.",params:{workflowIds:{type:"array",items:{type:"string"},description:"One or more workflow resourceIds to check"}},required:["workflowIds"],group:"magic",readOnly:!0,searchHint:"check AI extraction workflow status progress",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=t.workflowIds;if(r.length===0)throw new Error("workflowIds must be non-empty");return Nlt(e,r,n=>RD(e.client,{filter:{resourceId:{in:n}},limit:n.length}))}},{name:"wait_for_magic_workflows",description:"Poll magic extraction workflow(s) until each reaches a terminal state (transaction created (a draft is ready), OCR succeeded/failed, or errored) or until the wait budget elapses. Use after create_transaction_from_document / extract_documents to know when drafts are ready; a workflow whose result said it runs in the background answers with that note instead. Returns each workflow's current status plus the still-pending ids; if any are still pending after the budget, call again to keep waiting. Batched into one request per poll.",params:{workflowIds:{type:"array",items:{type:"string"},description:"One or more magic workflow resourceIds to wait on."},maxWaitSeconds:{type:"number",description:"Maximum seconds to wait before returning current status (default 120). Returns immediately once all workflows are terminal."},pollIntervalSeconds:{type:"number",description:"Seconds between polls (default 5)."}},required:["workflowIds"],group:"magic",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"wait for AI extraction workflows to finish poll until done",execute:async(e,t)=>{let r=t.workflowIds;if(!Array.isArray(r))throw new Error("workflowIds must be an array");if(r.length===0)return{allTerminal:!0,pending:[],timedOut:!1,workflows:[]};let n=(s,a,c)=>Math.min(c,Math.max(a,s)),i=n(typeof t.maxWaitSeconds=="number"?t.maxWaitSeconds:120,1,600),o=n(typeof t.pollIntervalSeconds=="number"?t.pollIntervalSeconds:5,2,60);return Nlt(e,r,async s=>{let a=await KZ(e.client,s,{timeout:i*1e3,interval:o*1e3});return{allTerminal:a.pending.length===0,pending:a.pending,timedOut:a.timedOut,workflows:a.workflows}})}},...DU,{name:"create_claim_from_attachment",description:`Create an employee-expense claim DRAFT from a receipt via AI extraction: from a SINGLE file, a URL (sourceURL), or raw HTML (e.g. an email body). When the host conversation provides a file with the call, omit all source arguments; the file is used automatically. On the email channel, pass attachmentId "email-body" to use the inbound email body. The draft is born BOUND to the uploader's own employee automatically; to file for someone else pass employeeResourceId (server requires a claims Manager/Admin). Optional contact, claim profile, currency, value date. Returns a workflow handle; the claim appears in Drafts asynchronously (no manual bind step). ${rs}`,params:{sourceURL:{type:"string",description:"URL of the receipt, or a Telegram file link (downloaded here)."},attachmentId:{type:"string",description:'Pass "email-body" to use the inbound email body (email channel). No other attachment-id source.'},html:{type:"string",description:"Raw HTML (e.g. email body), rendered to PDF then extracted."},contactResourceId:{type:"string",description:"Vendor/merchant contact to pre-bind (UUID)"},claimProfileResourceId:{type:"string",description:"Claim profile to bind on the draft (UUID)"},employeeResourceId:{type:"string",description:"Employee to file the claim for (UUIDv4). Omit to auto-bind the uploader's own employee; naming another requires a claims Manager/Admin."},currencyCode:{type:"string",description:"Currency override (ISO 4217)"},valueDate:{type:"string",description:"Value date override (YYYY-MM-DD)"},internalNotes:{type:"string",description:"Internal notes override"}},required:[],group:"magic",readOnly:!1,acceptsHostFile:!0,searchHint:"create claim draft from receipt attachment OCR extraction email body html",backgroundJob:dge("MAGIC_CLAIM","sourceURL","receipt"),execute:async(e,t)=>{let r={contactResourceId:t.contactResourceId,claimProfileResourceId:t.claimProfileResourceId,employeeResourceId:t.employeeResourceId,currencyCode:t.currencyCode,valueDate:t.valueDate,internalNotes:t.internalNotes};if(t.attachmentId==="email-body"){let o=SE({sourceURL:t.sourceURL,html:t.html});if(o.length>0||e.file_blob)return iA(["attachmentId (email-body)","sourceURL","html"],{provided:["attachmentId (email-body)",...o],hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1});let s=e.html_blob;return s?KI(e.client,{html:s,...r}):vE('attachmentId "email-body" requires an inbound email body, and this run has none.',"That value only works on the email channel. Pass sourceURL or html instead.")}if(t.attachmentId)return vE('Claims have no attachment-id source. "email-body" is the only accepted value, and only on the email channel.',`Use one of: ${tO({acceptsLocalPath:!1,acceptsAttachmentId:!1})}.`);let n=SE({sourceURL:t.sourceURL,html:t.html}),i=n.length+(e.file_blob?1:0);return i===1&&e.file_blob?KI(e.client,{sourceFile:e.file_blob.data,sourceFileName:e.file_blob.fileName,...r}):i!==1?iA(["sourceURL","html"],{provided:n,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1,importDestination:"employees.modal.import-claims"}):KI(e.client,{sourceURL:t.sourceURL,html:t.html,...r})}},{name:"classify_documents",description:'Use this when the user points at a FOLDER, a .zip, a Dropbox / Google Drive / OneDrive folder share link, or a pile/batch of mixed documents. Sort a ZIP or share link of MIXED accounting documents: classifies each file into invoice / bill / customer credit note / supplier credit note / quote / order / purchase request / bank statement by its FOLDER NAME within the source (e.g. files under an "invoices/" folder become invoices), WITHOUT creating anything. Returns a manifest (per-file type + confidence + counts) plus a collectionId. If nothing is extractable it returns `hint` (why + what to do) and `summary.skippedExtensions`: relay it, do NOT call extract_documents; review it, then call extract_documents with that collectionId to create the drafts. The source is FETCHED BY THE JAZ SERVER: a direct .zip/file link, or a Dropbox / Google Drive / OneDrive share link. A local path works only when this tool runs on your own machine.',params:{source:{type:"string",description:"Fetched by the Jaz server: a direct .zip/file link or a Dropbox/Drive/OneDrive share link."},type:{type:"string",enum:[...tU],valueAliases:rU,description:"Optional: force every file to this type instead of auto-classifying by folder."}},acceptsHostFile:!0,required:[],group:"magic",readOnly:!1,searchHint:"classify auto-sort a Dropbox Google Drive OneDrive folder share link or zip or a pile batch of mixed invoices bills documents create docs from a folder link before extraction",maxResultSizeChars:2e4,execute:async(e,t)=>{if(t.source&&e.file_blob)return vE("Two sources: a `source` and an attached file. Provide exactly one.","Drop `source` to use the attached file, or omit the attachment to use `source`.");if(!t.source&&e.file_blob){let o=e.file_blob.fileName;if(!(oSr(o).toLowerCase()===".zip"||e.file_blob.data.type==="application/zip"))return vE(`classify_documents sorts a .zip or folder of many documents; "${o}" is a single file.`,"For one document use create_transaction_from_document with the same attached file.");let c=rSr(Yct(aSr(),"clio-hostfile-"));try{let u=Yct(c,"upload.zip");if(!Hct(u).startsWith(Hct(c)+sSr))throw new Error("refusing to write outside the temp directory");nSr(u,Buffer.from(await e.file_blob.data.arrayBuffer()));let d=await FD({source:c,type:t.type?eh(t.type)??void 0:void 0});return{...lAe(d),collectionId:pAe(d,e.client.scopeKey),...cAe(d)}}finally{try{iSr(c,{recursive:!0,force:!0})}catch{}}}let r=t.source;if(!r)return iA(["source"],{provided:[],hostFileAvailable:ih(e.mcpSurface),acceptsAttachmentId:!1});if(!/^https:\/\//i.test(r)&&!o8())return hat({acceptsAttachmentId:!1});let n=await FD({source:r,type:t.type?eh(t.type)??void 0:void 0}),i=pAe(n,e.client.scopeKey);return{...lAe(n),collectionId:i,...cAe(n)}}},{name:"extract_documents",description:`Create draft transactions from a classified document collection (see classify_documents). Uploads each file to the right AI-extraction endpoint (invoices/bills/credit notes via business-transaction extraction, bank statements via statement import), de-duplicates identical files, and returns the workflow ids (wait_for_magic_workflows reads them). Processing is async; drafts appear once the workflows reach a terminal state. ${rs} Pass the collectionId from classify_documents. Returns \`whereToSee[]\`: the screen each landed type appears on + its uploaded/failed split (+ \`next\` for quotes/orders): relay those links (no \`navigate\`) and, unless the result says it runs in the background, say drafts are still arriving. An unbuildable link is omitted, named in \`partialFailures\`.`,params:{collectionId:{type:"string",description:"The collectionId returned by classify_documents."},documentTypes:{type:"array",items:{type:"string",enum:[...tU],valueAliases:rU},description:"Optional: only extract these document types (default: every uploadable file in the collection)."},bankAccountId:{type:"string",description:"Bank account resourceId for bank-statement imports, required if the collection contains bank statements."},internalNotes:{type:"string",description:"Internal notes on every draft (max 3000 chars), e.g. the collectionId."}},required:["collectionId"],group:"magic",readOnly:!1,searchHint:"extract create drafts from a classified document collection invoices bills credit notes",maxResultSizeChars:2e4,backgroundJob:eDr,execute:async(e,t)=>{let{documentTypes:r,unresolved:n}=jlt(t);if(n.length>0)return{error:`Unrecognized documentTypes: ${n.join(", ")}.`,hint:`Use one or more of: ${tU.join(", ")}. Omit documentTypes entirely to extract everything in the collection.`};let i=e.client.scopeKey,o=t.collectionId,s=hAe(o,i);if(!s)throw new Error(`Collection "${o}" not found or expired; re-run classify_documents.`);let a=t.bankAccountId,c=await Iat({plan:s,client:e.client,bankAccountId:a,documentTypes:r,internalNotes:t.internalNotes});c.failed===0&&yat(o,i);let u=[...new Set(c.files.filter(p=>p.status==="uploaded").map(p=>p.type))],d=[],f=[];if(u.length>0){let{dashboardUrl:p}=$D(e.platform??"jaz");for(let h of u)try{let m=sOe[h];if(!m){f.push(`link for ${h} unavailable: no destination mapped`);continue}let A=m.key===null?void 0:qD(m.key,void 0,{dashboardUrl:p,orgResourceId:e.org?.resourceId}).url;d.push({type:h,label:m.label,...A?{url:A}:{},...m.next?{next:m.next}:{},uploaded:c.files.filter(g=>g.type===h&&g.status==="uploaded").length,failed:c.files.filter(g=>g.type===h&&g.status==="failed").length,...h==="BANK_STATEMENT"&&a?{bankAccountId:a}:{}})}catch(m){f.push(`link for ${h} unavailable: ${RE(m)}`)}}return{...f.length>0?{partialFailures:f}:{},...d.length>0?{whereToSee:d}:{},...c}}},{name:"get_attachments",description:`Get attachments for a record (${tge}).`,params:{transactionType:rge,transactionId:{type:"string",description:"Record resourceId"}},required:["transactionType","transactionId"],group:"attachments",readOnly:!0,searchHint:"list attachments files on a transaction",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>gi(e.client,t.transactionType,t.transactionId)},{name:"add_attachment",description:`Add an attachment to a record (${tge}). Provide EXACTLY ONE source: sourceUrl (downloaded here, uploaded as bytes), attachmentId (links existing), or a file attached to the call. Two is refused.`,params:{transactionType:rge,transactionId:{type:"string",description:"Record resourceId"},attachmentId:{type:"string",description:"Attachment ID to link (alternative to sourceUrl). Only: invoices, bills, journals, scheduled_journals, customer-credit-notes, supplier-credit-notes."},sourceUrl:{type:"string",description:"Source file URL, downloaded and uploaded as multipart file"},attachmentType:{type:"string",enum:["INTERNAL","EXTERNAL"],description:"Only: invoices, customer-credit-notes, sale-quotes, sale-orders, purchase-requests, purchase-orders."}},required:["transactionType","transactionId"],group:"attachments",readOnly:!1,acceptsHostFile:!0,searchHint:"upload attach file to a transaction",execute:async(e,t)=>{let r=SE({attachmentId:t.attachmentId,sourceUrl:t.sourceUrl});if(r.length+(e.file_blob?1:0)!==1){let s=t.transactionType;return iA(["attachmentId","sourceUrl"],{provided:r,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!XB.includes(s),fetchedBy:"agent"})}let n=t.transactionType;if(t.attachmentId&&XB.includes(n))return{error:`link-by-id (attachmentId) is not supported on ${n}.`,status:422,hint:`${n} accept file uploads only; pass sourceUrl instead of attachmentId.`,repair:{tool:"add_attachment",arguments:{transactionType:n,transactionId:t.transactionId},reason:"This record takes a file or a sourceUrl, not a link-by-id; re-send with one of those."}};let i,o;if(t.sourceUrl){let s=await df(t.sourceUrl),a=await wc(s,{timeoutMs:GI,maxBytes:wM});if(!a.ok)throw new Error(`Failed to download ${t.sourceUrl}: ${a.status}`);let c=await a.arrayBuffer(),u=a.headers.get("content-type")??"application/octet-stream";i=new Blob([c],{type:u}),o=th(t.sourceUrl,"attachment")}else!t.attachmentId&&e.file_blob&&(i=e.file_blob.data,o=e.file_blob.fileName);return XV(e.client,{businessTransactionType:t.transactionType,businessTransactionResourceId:t.transactionId,file:i,fileName:o,attachmentId:t.attachmentId,attachmentType:t.attachmentType})}},{name:"delete_attachment",description:`Delete an attachment from a record (${tge}).`,params:{transactionType:rge,transactionId:{type:"string",description:"Record resourceId"},attachmentResourceId:{type:"string",description:"Attachment resourceId (from get_attachments response)"}},required:["transactionType","transactionId","attachmentResourceId"],group:"attachments",readOnly:!1,searchHint:"delete remove attachment file from transaction",isDestructive:!0,execute:async(e,t)=>{let r=t.transactionId,n=t.attachmentResourceId;Xi(r,"transactionId","Nothing was deleted. Source the transaction resourceId from a search_* result."),Xi(n,"attachmentResourceId","Nothing was deleted. Source the attachment resourceId from get_attachments.");let i=await ZV(e.client,t.transactionType,r,n);return Ult(i,"deleted","attachmentResourceId",n)}},{name:"read_spreadsheet_rows",description:"Parse rows from a CSV/Excel URL. Returns rows as JSON objects keyed by header (max 500/call, paginatable via offset/limit). Excel response includes availableSheets[]; re-call with sheetIndex if the first sheet is Instructions. Use BEFORE bulk_upsert_* when the user attaches a tabular file.",params:{sourceUrl:{type:"string",description:"URL of the CSV or Excel attachment."},offset:{type:"number",description:"0-based row offset. Default 0."},limit:{type:"number",description:"Rows to return (1-500). Default 200."},kind:{type:"string",description:"csv | excel. Auto-detected from URL/Content-Type if omitted.",enum:["csv","excel"]},sheetIndex:{type:"number",description:"Excel only: 0-based sheet index. Default 0. Response lists availableSheets[]."}},required:["sourceUrl"],group:"attachments",readOnly:!0,searchHint:"read parse csv excel xlsx file content rows columns from attachment url for bulk import upload spreadsheet",isConcurrencySafe:!0,maxResultSizeChars:6e4,execute:async(e,t)=>dst({sourceUrl:t.sourceUrl,offset:t.offset,limit:t.limit,kind:t.kind,sheetIndex:t.sheetIndex})},{name:"list_comment_threads",description:"List the comment threads on a bill, invoice, supplier credit note, customer credit note or bank record. A record has at most one open thread. Each thread returns its newest commentLimit comments, oldest first: 5 by default, 0 for counts only. commentsTruncated says when older ones exist; read them with list_comments. Times (createdAt, updatedAt, resolvedAt) are epoch milliseconds in UTC. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,bankAccountResourceId:Sv,limit:{type:"number",description:"Threads per page, 1 to 50. Default 20."},offset:fge,commentLimit:{type:"number",description:"Newest comments returned per thread, 0 to 50. Default 5; 0 returns counts only. Older ones: list_comments."}},required:["entityType","entityId"],group:"collaboration",readOnly:!0,noCache:!0,searchHint:"comment threads discussion on a bill invoice credit note bank record, open or resolved, who said what, replies, mentions",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=mA(t);return tat(e.client,r.entityType,r.entityId,{bankAccountResourceId:r.bankAccountResourceId,limit:r.limit,offset:r.offset,commentLimit:r.commentLimit})}},{name:"list_comments",description:"Read the comments of one thread on a record, newest first, a page at a time. Use it for comments older than the ones list_comment_threads returned. Times (createdAt, updatedAt) are epoch milliseconds in UTC. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,bankAccountResourceId:Sv,limit:{type:"number",description:"Comments per page, 1 to 50. Default 20."},offset:fge},required:["entityType","entityId","threadId"],group:"collaboration",readOnly:!0,noCache:!0,searchHint:"read older comments of one thread newest first, page through a long comment thread on a bill invoice credit note bank record",isConcurrencySafe:!0,execute:async(e,t)=>{let r=mA(t);return rat(e.client,r.entityType,r.entityId,r.threadId,{bankAccountResourceId:r.bankAccountResourceId,limit:r.limit,offset:r.offset})}},{name:"add_comment",description:"Post a comment on a bill, invoice, supplier credit note, customer credit note or bank record. The caller is the author, and the text is published under the caller's name as their own words to teammates: write it as the caller would, in the first person, never naming the caller or calling them the user, and never mentioning Clio or its permissions, rules or confirmations. Anything to ask the caller goes in the reply to the caller, not in a comment. A record has one open thread: without threadId the comment joins it or starts one, and a resolved thread accepts none. To mention someone, write <@userResourceId> in content where the name belongs, with the userResourceId from search_org_users (not the org-user record id); the saved text fills in the name. Only members whose own status is ACTIVE can be mentioned (the row's top-level status from search_org_users, not user.status; an invited member who has not joined is PENDING and cannot), at most 20: any other id refuses the whole comment. A plain @Name is just text and notifies no one. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,content:{type:"string",description:"Comment text, 1 to 4000 characters. Mentions are <@userResourceId> markup."},threadId:{type:"string",description:"Open thread to reply in. Omit it to join the open thread of the record, or start one."},bankAccountResourceId:Sv},required:["entityType","entityId","content"],group:"collaboration",readOnly:!1,searchHint:"add post write comment reply start thread mention a teammate on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return nat(e.client,r.entityType,r.entityId,{content:r.content,threadId:r.threadId},{bankAccountResourceId:r.bankAccountResourceId})}},{name:"update_comment",description:"Edit a comment the caller wrote, replacing its whole text, which stays the caller's own words to teammates: first person, never naming the caller or calling them the user, never mentioning Clio or its permissions, rules or confirmations. Anything to ask the caller goes in the reply to the caller, not in a comment. Only the author can, and only while its thread is open: a resolved thread refuses changes. Mentions work as in add_comment: write <@userResourceId> to add one, and keep the <Name@userResourceId> markup from content (text shows only @Name) for each mention to keep; leaving it out removes the mention. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,commentId:Blt,content:{type:"string",description:"New comment text, 1 to 4000 characters."},bankAccountResourceId:Sv},required:["entityType","entityId","threadId","commentId","content"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"edit change fix my own comment text on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return iat(e.client,r.entityType,r.entityId,r.threadId,r.commentId,{content:r.content},{bankAccountResourceId:r.bankAccountResourceId})}},{name:"delete_comment",description:"Delete a comment the caller wrote. Only the author can, and only while its thread is open: a resolved thread refuses changes. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,commentId:Blt,bankAccountResourceId:Sv},required:["entityType","entityId","threadId","commentId"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"delete remove my own comment from a thread on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return oat(e.client,r.entityType,r.entityId,r.threadId,r.commentId,{bankAccountResourceId:r.bankAccountResourceId})}},{name:"mark_thread_resolved",description:"Resolve a comment thread on a record. A resolved thread accepts no new comments: the next comment without threadId starts a new thread. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,bankAccountResourceId:Sv},required:["entityType","entityId","threadId"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"resolve close thread mark discussion done on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return sat(e.client,r.entityType,r.entityId,r.threadId,{bankAccountResourceId:r.bankAccountResourceId})}},{name:"list_notifications",description:"Notifications addressed to the caller: comments and mentions on records, newest first, unread by default. The Jaz API reads the newest 500 items of the last 365 days; truncated says when older ones exist. Each item names its record and threadId. Times (createdAt, readAt) are epoch milliseconds in UTC.",params:{status:{type:"string",enum:["unread","all"],description:"unread (default) or all."},limit:{type:"number",description:"Notifications per page, 1 to 50. Default 20."},offset:fge},required:[],group:"collaboration",readOnly:!0,noCache:!0,searchHint:"notifications unread mentions comments on my records inbox what did I miss, newest first",isConcurrencySafe:!0,execute:async(e,t)=>{let r=mA(t);return aat(e.client,{status:r.status,limit:r.limit,offset:r.offset})}},{name:"mark_notification_read",description:"Mark one notification read, or unread with read set to false.",params:{notificationId:{type:"string",description:"Notification id from list_notifications."},read:{type:"boolean",description:"true marks it read (default), false marks it unread."}},required:["notificationId"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"mark one notification read or unread, dismiss a mention or comment notification",execute:async(e,t)=>{let r=mA(t);return cat(e.client,r.notificationId,r.read!==!1)}},{name:"mark_all_notifications_read",description:"Mark every unread notification of the caller read. Returns marked and more: when more is true, call again.",params:{},required:[],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"mark all notifications read, clear the inbox, dismiss every unread mention and comment",execute:async e=>lat(e.client)},{name:"validate_invoice_draft",description:"Check if an invoice draft is ready to finalize. Returns missing fields, structured validation report, and ready status. Use before finalize_invoice to prevent errors.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"drafts",readOnly:!0,searchHint:"validate invoice draft readiness for finalization",isConcurrencySafe:!0,execute:async(e,t)=>{let r=t.resourceId,n=await go(e.client,r),i=await gi(e.client,"invoices",r);return ts(n.data,rl,i.data.length)}},{name:"validate_bill_draft",description:"Check if a bill draft is ready to finalize. Returns missing fields, structured validation report, and ready status. Use before finalize_bill to prevent errors.",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"drafts",readOnly:!0,searchHint:"validate bill draft readiness for finalization",isConcurrencySafe:!0,execute:async(e,t)=>{let r=t.resourceId,n=await fo(e.client,r),i=await gi(e.client,"bills",r);return ts(n.data,xa,i.data.length)}},{name:"validate_journal_draft",description:"Check if a journal draft is ready to finalize. Returns missing fields (accounts, amounts, date), structured validation, and ready status.",params:{resourceId:{type:"string",description:"Journal resourceId"}},required:["resourceId"],group:"drafts",readOnly:!0,searchHint:"validate journal draft readiness for posting",isConcurrencySafe:!0,execute:async(e,t)=>{let r=await vs(e.client,t.resourceId);return ts(r.data,ou,0,"journalEntries")}},{name:"validate_credit_note_draft",description:"Check if a credit note draft (customer or supplier) is ready to finalize. Returns missing fields, structured validation, and ready status.",params:{resourceId:{type:"string",description:"Credit note resourceId"},type:{type:"string",enum:["customer","supplier"],description:'Credit note type: "customer" or "supplier"'}},required:["resourceId","type"],group:"drafts",readOnly:!0,searchHint:"validate credit note draft readiness for finalization",isConcurrencySafe:!0,execute:async(e,t)=>{let r=t.resourceId,n=t.type,i=n==="customer"?await Ws(e.client,r):await Ks(e.client,r),o=n==="customer"?"customer-credit-notes":"supplier-credit-notes",s=await gi(e.client,o,r);return ts(i.data,_o,s.data.length)}},br("list_bank_rules","List bank reconciliation rules (action shortcuts). Shows rule name, action type, and target bank account.","bank_rules",(e,t,r)=>u8(e,{limit:r,offset:t}),"list automatic bank reconciliation rules"),ri("get_bank_rule","Get full bank rule details including configuration (allocation percentages, accounts, tax settings).","bank_rules",(e,t)=>nO(e,t),"get bank rule details conditions actions"),Nt({name:"search_bank_rules",description:"Search bank rules.",group:"bank_rules",fields:fx,defaults:px,fetcher:d8,searchHint:"find bank rules auto-reconciliation matching criteria by name"}),{name:"create_bank_rule",description:`Bank reconciliation rule: auto-matches bank records. Use directly on request; don't just list existing.
|
|
771
|
+
Returns {data: {errors: []}} on success. accountResourceId must be a bank-type CoA account (find via list_bank_accounts).`,params:{accountResourceId:{type:"string",description:"Bank account resourceId (from list_bank_accounts)"},records:{type:"array",items:{type:"object",properties:{amount:{type:"number",description:"Positive = cash-in, negative = cash-out"},transactionDate:{type:"string",description:"Date (YYYY-MM-DD)"},description:{type:"string",description:"Description"},payerOrPayee:{type:"string",description:"Payer or payee name"},reference:{type:"string",description:"Reference"}},required:["amount","transactionDate"]},description:"Array of 1-100 bank records"}},required:["accountResourceId","records"],group:"bank",readOnly:!1,searchHint:"add manual bank transaction records entries",execute:async(e,t)=>gU(e.client,t.accountResourceId,t.records)},{name:"create_transaction_from_document",description:`Create a business transaction (invoice/bill/credit note/quote/order/purchase request) from a SINGLE file (max 10 MB), a URL, or raw HTML (e.g. an email body) using AI extraction. Processing is async: the result is a workflow id, not the record. ${rs} Quotes/orders land DRAFT/PENDING: relay the result \`next\`. When the host conversation provides a file with the call, omit all source arguments; the file is used automatically. For a FOLDER, a .zip, a Dropbox/Drive/OneDrive folder share link, or several/mixed documents at once, use classify_documents (then extract_documents) instead, not this per-file.`,params:{businessTransactionType:{type:"string",enum:[...qZ],description:"Type of transaction to create"},sourceUrl:{type:"string",description:"URL the Jaz server fetches, or a Telegram file link (downloaded here)."},attachmentId:{type:"string",description:'Pass "email-body" to use the inbound email body (email channel). No other attachment-id source.'},html:{type:"string",description:"Raw HTML (e.g. email body), rendered to PDF then extracted."},internalNotes:{type:"string",description:"Internal notes on the record (max 3000 chars)."}},required:["businessTransactionType"],group:"magic",readOnly:!1,fetchesCallerUrl:!0,acceptsHostFile:!0,searchHint:"create transaction from attachment URL or email HTML AI extraction",backgroundJob:dge("MAGIC_WORKFLOW","sourceUrl","document"),execute:async(e,t)=>{let r=t.businessTransactionType,n=t.internalNotes;if(t.attachmentId==="email-body"){let a=SE({sourceUrl:t.sourceUrl,html:t.html});if(a.length>0||e.file_blob)return iA(["attachmentId (email-body)","sourceUrl","html"],{provided:["attachmentId (email-body)",...a],hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1});let c=e.html_blob;return c?uge(r,await gf(e.client,{businessTransactionType:r,html:c,internalNotes:n})):vE('attachmentId "email-body" requires an inbound email body, and this run has none.',"That value only works on the email channel. Pass sourceUrl or html instead.")}if(t.attachmentId)return vE('This tool has no attachment-id source. "email-body" is the only accepted value, and only on the email channel.',`Use one of: ${tO({acceptsLocalPath:!1,acceptsAttachmentId:!1})}.`);let i=SE({sourceUrl:t.sourceUrl,html:t.html}),o=i.length+(e.file_blob?1:0);if(o===1&&e.file_blob)return uge(r,await gf(e.client,{businessTransactionType:r,sourceFile:e.file_blob.data,sourceFileName:e.file_blob.fileName,internalNotes:n}));if(o!==1)return iA(["sourceUrl","html"],{provided:i,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1,importDestination:GSr[r]??"purchases.modal.import-bills"});let s=t.sourceUrl;return uge(r,await gf(e.client,{businessTransactionType:r,sourceUrl:s,html:t.html,internalNotes:n}))}},{name:"get_magic_workflow_status",description:"Get the current status of specific magic workflow(s) by resourceId(s). Returns workflow details including status, document type, and results.",params:{workflowIds:{type:"array",items:{type:"string"},description:"One or more workflow resourceIds to check"}},required:["workflowIds"],group:"magic",readOnly:!0,searchHint:"check AI extraction workflow status progress",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=t.workflowIds;if(r.length===0)throw new Error("workflowIds must be non-empty");return Nlt(e,r,n=>RD(e.client,{filter:{resourceId:{in:n}},limit:n.length}))}},{name:"wait_for_magic_workflows",description:"Poll magic extraction workflow(s) until each reaches a terminal state (transaction created (a draft is ready), OCR succeeded/failed, or errored) or until the wait budget elapses. Use after create_transaction_from_document / extract_documents to know when drafts are ready; a workflow whose result said it runs in the background answers with that note instead. Returns each workflow's current status plus the still-pending ids; if any are still pending after the budget, call again to keep waiting. Batched into one request per poll.",params:{workflowIds:{type:"array",items:{type:"string"},description:"One or more magic workflow resourceIds to wait on."},maxWaitSeconds:{type:"number",description:"Maximum seconds to wait before returning current status (default 120). Returns immediately once all workflows are terminal."},pollIntervalSeconds:{type:"number",description:"Seconds between polls (default 5)."}},required:["workflowIds"],group:"magic",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"wait for AI extraction workflows to finish poll until done",execute:async(e,t)=>{let r=t.workflowIds;if(!Array.isArray(r))throw new Error("workflowIds must be an array");if(r.length===0)return{allTerminal:!0,pending:[],timedOut:!1,workflows:[]};let n=(s,a,c)=>Math.min(c,Math.max(a,s)),i=n(typeof t.maxWaitSeconds=="number"?t.maxWaitSeconds:120,1,600),o=n(typeof t.pollIntervalSeconds=="number"?t.pollIntervalSeconds:5,2,60);return Nlt(e,r,async s=>{let a=await KZ(e.client,s,{timeout:i*1e3,interval:o*1e3});return{allTerminal:a.pending.length===0,pending:a.pending,timedOut:a.timedOut,workflows:a.workflows}})}},...DU,{name:"create_claim_from_attachment",description:`Create an employee-expense claim DRAFT from a receipt via AI extraction: from a SINGLE file, a URL (sourceURL), or raw HTML (e.g. an email body). When the host conversation provides a file with the call, omit all source arguments; the file is used automatically. On the email channel, pass attachmentId "email-body" to use the inbound email body. The draft is born BOUND to the uploader's own employee automatically; to file for someone else pass employeeResourceId (server requires a claims Manager/Admin). Optional contact, claim profile, currency, value date. Returns a workflow handle; the claim appears in Drafts asynchronously (no manual bind step). ${rs}`,params:{sourceURL:{type:"string",description:"URL of the receipt, or a Telegram file link (downloaded here)."},attachmentId:{type:"string",description:'Pass "email-body" to use the inbound email body (email channel). No other attachment-id source.'},html:{type:"string",description:"Raw HTML (e.g. email body), rendered to PDF then extracted."},contactResourceId:{type:"string",description:"Vendor/merchant contact to pre-bind (UUID)"},claimProfileResourceId:{type:"string",description:"Claim profile to bind on the draft (UUID)"},employeeResourceId:{type:"string",description:"Employee to file the claim for (UUIDv4). Omit to auto-bind the uploader's own employee; naming another requires a claims Manager/Admin."},currencyCode:{type:"string",description:"Currency override (ISO 4217)"},valueDate:{type:"string",description:"Value date override (YYYY-MM-DD)"},internalNotes:{type:"string",description:"Internal notes override"}},required:[],group:"magic",readOnly:!1,fetchesCallerUrl:!0,acceptsHostFile:!0,searchHint:"create claim draft from receipt attachment OCR extraction email body html",backgroundJob:dge("MAGIC_CLAIM","sourceURL","receipt"),execute:async(e,t)=>{let r={contactResourceId:t.contactResourceId,claimProfileResourceId:t.claimProfileResourceId,employeeResourceId:t.employeeResourceId,currencyCode:t.currencyCode,valueDate:t.valueDate,internalNotes:t.internalNotes};if(t.attachmentId==="email-body"){let o=SE({sourceURL:t.sourceURL,html:t.html});if(o.length>0||e.file_blob)return iA(["attachmentId (email-body)","sourceURL","html"],{provided:["attachmentId (email-body)",...o],hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1});let s=e.html_blob;return s?KI(e.client,{html:s,...r}):vE('attachmentId "email-body" requires an inbound email body, and this run has none.',"That value only works on the email channel. Pass sourceURL or html instead.")}if(t.attachmentId)return vE('Claims have no attachment-id source. "email-body" is the only accepted value, and only on the email channel.',`Use one of: ${tO({acceptsLocalPath:!1,acceptsAttachmentId:!1})}.`);let n=SE({sourceURL:t.sourceURL,html:t.html}),i=n.length+(e.file_blob?1:0);return i===1&&e.file_blob?KI(e.client,{sourceFile:e.file_blob.data,sourceFileName:e.file_blob.fileName,...r}):i!==1?iA(["sourceURL","html"],{provided:n,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!1,importDestination:"employees.modal.import-claims"}):KI(e.client,{sourceURL:t.sourceURL,html:t.html,...r})}},{name:"classify_documents",description:'Use this when the user points at a FOLDER, a .zip, a Dropbox / Google Drive / OneDrive folder share link, or a pile/batch of mixed documents. Sort a ZIP or share link of MIXED accounting documents: classifies each file into invoice / bill / customer credit note / supplier credit note / quote / order / purchase request / bank statement by its FOLDER NAME within the source (e.g. files under an "invoices/" folder become invoices), WITHOUT creating anything. Returns a manifest (per-file type + confidence + counts) plus a collectionId. If nothing is extractable it returns `hint` (why + what to do) and `summary.skippedExtensions`: relay it, do NOT call extract_documents; review it, then call extract_documents with that collectionId to create the drafts. The source is FETCHED BY THE JAZ SERVER: a direct .zip/file link, or a Dropbox / Google Drive / OneDrive share link. A local path works only when this tool runs on your own machine.',params:{source:{type:"string",description:"Fetched by the Jaz server: a direct .zip/file link or a Dropbox/Drive/OneDrive share link."},type:{type:"string",enum:[...tU],valueAliases:rU,description:"Optional: force every file to this type instead of auto-classifying by folder."}},acceptsHostFile:!0,required:[],group:"magic",readOnly:!1,searchHint:"classify auto-sort a Dropbox Google Drive OneDrive folder share link or zip or a pile batch of mixed invoices bills documents create docs from a folder link before extraction",maxResultSizeChars:2e4,execute:async(e,t)=>{if(t.source&&e.file_blob)return vE("Two sources: a `source` and an attached file. Provide exactly one.","Drop `source` to use the attached file, or omit the attachment to use `source`.");if(!t.source&&e.file_blob){let o=e.file_blob.fileName;if(!(oSr(o).toLowerCase()===".zip"||e.file_blob.data.type==="application/zip"))return vE(`classify_documents sorts a .zip or folder of many documents; "${o}" is a single file.`,"For one document use create_transaction_from_document with the same attached file.");let c=rSr(Yct(aSr(),"clio-hostfile-"));try{let u=Yct(c,"upload.zip");if(!Hct(u).startsWith(Hct(c)+sSr))throw new Error("refusing to write outside the temp directory");nSr(u,Buffer.from(await e.file_blob.data.arrayBuffer()));let d=await FD({source:c,type:t.type?eh(t.type)??void 0:void 0});return{...lAe(d),collectionId:pAe(d,e.client.scopeKey),...cAe(d)}}finally{try{iSr(c,{recursive:!0,force:!0})}catch{}}}let r=t.source;if(!r)return iA(["source"],{provided:[],hostFileAvailable:ih(e.mcpSurface),acceptsAttachmentId:!1});if(!/^https:\/\//i.test(r)&&!o8())return hat({acceptsAttachmentId:!1});let n=await FD({source:r,type:t.type?eh(t.type)??void 0:void 0}),i=pAe(n,e.client.scopeKey);return{...lAe(n),collectionId:i,...cAe(n)}}},{name:"extract_documents",description:`Create draft transactions from a classified document collection (see classify_documents). Uploads each file to the right AI-extraction endpoint (invoices/bills/credit notes via business-transaction extraction, bank statements via statement import), de-duplicates identical files, and returns the workflow ids (wait_for_magic_workflows reads them). Processing is async; drafts appear once the workflows reach a terminal state. ${rs} Pass the collectionId from classify_documents. Returns \`whereToSee[]\`: the screen each landed type appears on + its uploaded/failed split (+ \`next\` for quotes/orders): relay those links (no \`navigate\`) and, unless the result says it runs in the background, say drafts are still arriving. An unbuildable link is omitted, named in \`partialFailures\`.`,params:{collectionId:{type:"string",description:"The collectionId returned by classify_documents."},documentTypes:{type:"array",items:{type:"string",enum:[...tU],valueAliases:rU},description:"Optional: only extract these document types (default: every uploadable file in the collection)."},bankAccountId:{type:"string",description:"Bank account resourceId for bank-statement imports, required if the collection contains bank statements."},internalNotes:{type:"string",description:"Internal notes on every draft (max 3000 chars), e.g. the collectionId."}},required:["collectionId"],group:"magic",readOnly:!1,searchHint:"extract create drafts from a classified document collection invoices bills credit notes",maxResultSizeChars:2e4,backgroundJob:eDr,execute:async(e,t)=>{let{documentTypes:r,unresolved:n}=jlt(t);if(n.length>0)return{error:`Unrecognized documentTypes: ${n.join(", ")}.`,hint:`Use one or more of: ${tU.join(", ")}. Omit documentTypes entirely to extract everything in the collection.`};let i=e.client.scopeKey,o=t.collectionId,s=hAe(o,i);if(!s)throw new Error(`Collection "${o}" not found or expired; re-run classify_documents.`);let a=t.bankAccountId,c=await Iat({plan:s,client:e.client,bankAccountId:a,documentTypes:r,internalNotes:t.internalNotes});c.failed===0&&yat(o,i);let u=[...new Set(c.files.filter(p=>p.status==="uploaded").map(p=>p.type))],d=[],f=[];if(u.length>0){let{dashboardUrl:p}=$D(e.platform??"jaz");for(let h of u)try{let m=sOe[h];if(!m){f.push(`link for ${h} unavailable: no destination mapped`);continue}let A=m.key===null?void 0:qD(m.key,void 0,{dashboardUrl:p,orgResourceId:e.org?.resourceId}).url;d.push({type:h,label:m.label,...A?{url:A}:{},...m.next?{next:m.next}:{},uploaded:c.files.filter(g=>g.type===h&&g.status==="uploaded").length,failed:c.files.filter(g=>g.type===h&&g.status==="failed").length,...h==="BANK_STATEMENT"&&a?{bankAccountId:a}:{}})}catch(m){f.push(`link for ${h} unavailable: ${RE(m)}`)}}return{...f.length>0?{partialFailures:f}:{},...d.length>0?{whereToSee:d}:{},...c}}},{name:"get_attachments",description:`Get attachments for a record (${tge}).`,params:{transactionType:rge,transactionId:{type:"string",description:"Record resourceId"}},required:["transactionType","transactionId"],group:"attachments",readOnly:!0,searchHint:"list attachments files on a transaction",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>gi(e.client,t.transactionType,t.transactionId)},{name:"add_attachment",description:`Add an attachment to a record (${tge}). Provide EXACTLY ONE source: sourceUrl (downloaded here, uploaded as bytes), attachmentId (links existing), or a file attached to the call. Two is refused.`,params:{transactionType:rge,transactionId:{type:"string",description:"Record resourceId"},attachmentId:{type:"string",description:"Attachment ID to link (alternative to sourceUrl). Only: invoices, bills, journals, scheduled_journals, customer-credit-notes, supplier-credit-notes."},sourceUrl:{type:"string",description:"Source file URL, downloaded and uploaded as multipart file"},attachmentType:{type:"string",enum:["INTERNAL","EXTERNAL"],description:"Only: invoices, customer-credit-notes, sale-quotes, sale-orders, purchase-requests, purchase-orders."}},required:["transactionType","transactionId"],group:"attachments",readOnly:!1,fetchesCallerUrl:!0,acceptsHostFile:!0,searchHint:"upload attach file to a transaction",execute:async(e,t)=>{let r=SE({attachmentId:t.attachmentId,sourceUrl:t.sourceUrl});if(r.length+(e.file_blob?1:0)!==1){let s=t.transactionType;return iA(["attachmentId","sourceUrl"],{provided:r,hostFileAttached:!!e.file_blob,hostFileAvailable:ih(e.mcpSurface),acceptsLocalPath:!1,acceptsAttachmentId:!XB.includes(s),fetchedBy:"agent"})}let n=t.transactionType;if(t.attachmentId&&XB.includes(n))return{error:`link-by-id (attachmentId) is not supported on ${n}.`,status:422,hint:`${n} accept file uploads only; pass sourceUrl instead of attachmentId.`,repair:{tool:"add_attachment",arguments:{transactionType:n,transactionId:t.transactionId},reason:"This record takes a file or a sourceUrl, not a link-by-id; re-send with one of those."}};let i,o;if(t.sourceUrl){let s=await df(t.sourceUrl),a=await wc(s,{timeoutMs:GI,maxBytes:wM});if(!a.ok)throw new Error(`Failed to download ${t.sourceUrl}: ${a.status}`);let c=await a.arrayBuffer(),u=a.headers.get("content-type")??"application/octet-stream";i=new Blob([c],{type:u}),o=th(t.sourceUrl,"attachment")}else!t.attachmentId&&e.file_blob&&(i=e.file_blob.data,o=e.file_blob.fileName);return XV(e.client,{businessTransactionType:t.transactionType,businessTransactionResourceId:t.transactionId,file:i,fileName:o,attachmentId:t.attachmentId,attachmentType:t.attachmentType})}},{name:"delete_attachment",description:`Delete an attachment from a record (${tge}).`,params:{transactionType:rge,transactionId:{type:"string",description:"Record resourceId"},attachmentResourceId:{type:"string",description:"Attachment resourceId (from get_attachments response)"}},required:["transactionType","transactionId","attachmentResourceId"],group:"attachments",readOnly:!1,searchHint:"delete remove attachment file from transaction",isDestructive:!0,execute:async(e,t)=>{let r=t.transactionId,n=t.attachmentResourceId;Xi(r,"transactionId","Nothing was deleted. Source the transaction resourceId from a search_* result."),Xi(n,"attachmentResourceId","Nothing was deleted. Source the attachment resourceId from get_attachments.");let i=await ZV(e.client,t.transactionType,r,n);return Ult(i,"deleted","attachmentResourceId",n)}},{name:"read_spreadsheet_rows",description:"Parse rows from a CSV/Excel URL. Returns rows as JSON objects keyed by header (max 500/call, paginatable via offset/limit). Excel response includes availableSheets[]; re-call with sheetIndex if the first sheet is Instructions. Use BEFORE bulk_upsert_* when the user attaches a tabular file.",params:{sourceUrl:{type:"string",description:"URL of the CSV or Excel attachment."},offset:{type:"number",description:"0-based row offset. Default 0."},limit:{type:"number",description:"Rows to return (1-500). Default 200."},kind:{type:"string",description:"csv | excel. Auto-detected from URL/Content-Type if omitted.",enum:["csv","excel"]},sheetIndex:{type:"number",description:"Excel only: 0-based sheet index. Default 0. Response lists availableSheets[]."}},required:["sourceUrl"],group:"attachments",readOnly:!0,fetchesCallerUrl:!0,searchHint:"read parse csv excel xlsx file content rows columns from attachment url for bulk import upload spreadsheet",isConcurrencySafe:!0,maxResultSizeChars:6e4,execute:async(e,t)=>dst({sourceUrl:t.sourceUrl,offset:t.offset,limit:t.limit,kind:t.kind,sheetIndex:t.sheetIndex})},{name:"list_comment_threads",description:"List the comment threads on a bill, invoice, supplier credit note, customer credit note or bank record. A record has at most one open thread. Each thread returns its newest commentLimit comments, oldest first: 5 by default, 0 for counts only. commentsTruncated says when older ones exist; read them with list_comments. Times (createdAt, updatedAt, resolvedAt) are epoch milliseconds in UTC. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,bankAccountResourceId:Sv,limit:{type:"number",description:"Threads per page, 1 to 50. Default 20."},offset:fge,commentLimit:{type:"number",description:"Newest comments returned per thread, 0 to 50. Default 5; 0 returns counts only. Older ones: list_comments."}},required:["entityType","entityId"],group:"collaboration",readOnly:!0,noCache:!0,searchHint:"comment threads discussion on a bill invoice credit note bank record, open or resolved, who said what, replies, mentions",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=mA(t);return tat(e.client,r.entityType,r.entityId,{bankAccountResourceId:r.bankAccountResourceId,limit:r.limit,offset:r.offset,commentLimit:r.commentLimit})}},{name:"list_comments",description:"Read the comments of one thread on a record, newest first, a page at a time. Use it for comments older than the ones list_comment_threads returned. Times (createdAt, updatedAt) are epoch milliseconds in UTC. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,bankAccountResourceId:Sv,limit:{type:"number",description:"Comments per page, 1 to 50. Default 20."},offset:fge},required:["entityType","entityId","threadId"],group:"collaboration",readOnly:!0,noCache:!0,searchHint:"read older comments of one thread newest first, page through a long comment thread on a bill invoice credit note bank record",isConcurrencySafe:!0,execute:async(e,t)=>{let r=mA(t);return rat(e.client,r.entityType,r.entityId,r.threadId,{bankAccountResourceId:r.bankAccountResourceId,limit:r.limit,offset:r.offset})}},{name:"add_comment",description:"Post a comment on a bill, invoice, supplier credit note, customer credit note or bank record. The caller is the author, and the text is published under the caller's name as their own words to teammates: write it as the caller would, in the first person, never naming the caller or calling them the user, and never mentioning Clio or its permissions, rules or confirmations. Anything to ask the caller goes in the reply to the caller, not in a comment. A record has one open thread: without threadId the comment joins it or starts one, and a resolved thread accepts none. To mention someone, write <@userResourceId> in content where the name belongs, with the userResourceId from search_org_users (not the org-user record id); the saved text fills in the name. Only members whose own status is ACTIVE can be mentioned (the row's top-level status from search_org_users, not user.status; an invited member who has not joined is PENDING and cannot), at most 20: any other id refuses the whole comment. A plain @Name is just text and notifies no one. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,content:{type:"string",description:"Comment text, 1 to 4000 characters. Mentions are <@userResourceId> markup."},threadId:{type:"string",description:"Open thread to reply in. Omit it to join the open thread of the record, or start one."},bankAccountResourceId:Sv},required:["entityType","entityId","content"],group:"collaboration",readOnly:!1,searchHint:"add post write comment reply start thread mention a teammate on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return nat(e.client,r.entityType,r.entityId,{content:r.content,threadId:r.threadId},{bankAccountResourceId:r.bankAccountResourceId})}},{name:"update_comment",description:"Edit a comment the caller wrote, replacing its whole text, which stays the caller's own words to teammates: first person, never naming the caller or calling them the user, never mentioning Clio or its permissions, rules or confirmations. Anything to ask the caller goes in the reply to the caller, not in a comment. Only the author can, and only while its thread is open: a resolved thread refuses changes. Mentions work as in add_comment: write <@userResourceId> to add one, and keep the <Name@userResourceId> markup from content (text shows only @Name) for each mention to keep; leaving it out removes the mention. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,commentId:Blt,content:{type:"string",description:"New comment text, 1 to 4000 characters."},bankAccountResourceId:Sv},required:["entityType","entityId","threadId","commentId","content"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"edit change fix my own comment text on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return iat(e.client,r.entityType,r.entityId,r.threadId,r.commentId,{content:r.content},{bankAccountResourceId:r.bankAccountResourceId})}},{name:"delete_comment",description:"Delete a comment the caller wrote. Only the author can, and only while its thread is open: a resolved thread refuses changes. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,commentId:Blt,bankAccountResourceId:Sv},required:["entityType","entityId","threadId","commentId"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"delete remove my own comment from a thread on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return oat(e.client,r.entityType,r.entityId,r.threadId,r.commentId,{bankAccountResourceId:r.bankAccountResourceId})}},{name:"mark_thread_resolved",description:"Resolve a comment thread on a record. A resolved thread accepts no new comments: the next comment without threadId starts a new thread. Bank records need bankAccountResourceId.",params:{entityType:wv,entityId:vv,threadId:e3,bankAccountResourceId:Sv},required:["entityType","entityId","threadId"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"resolve close thread mark discussion done on a bill invoice credit note bank record",execute:async(e,t)=>{let r=mA(t);return sat(e.client,r.entityType,r.entityId,r.threadId,{bankAccountResourceId:r.bankAccountResourceId})}},{name:"list_notifications",description:"Notifications addressed to the caller: comments and mentions on records, newest first, unread by default. The Jaz API reads the newest 500 items of the last 365 days; truncated says when older ones exist. Each item names its record and threadId. Times (createdAt, readAt) are epoch milliseconds in UTC.",params:{status:{type:"string",enum:["unread","all"],description:"unread (default) or all."},limit:{type:"number",description:"Notifications per page, 1 to 50. Default 20."},offset:fge},required:[],group:"collaboration",readOnly:!0,noCache:!0,searchHint:"notifications unread mentions comments on my records inbox what did I miss, newest first",isConcurrencySafe:!0,execute:async(e,t)=>{let r=mA(t);return aat(e.client,{status:r.status,limit:r.limit,offset:r.offset})}},{name:"mark_notification_read",description:"Mark one notification read, or unread with read set to false.",params:{notificationId:{type:"string",description:"Notification id from list_notifications."},read:{type:"boolean",description:"true marks it read (default), false marks it unread."}},required:["notificationId"],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"mark one notification read or unread, dismiss a mention or comment notification",execute:async(e,t)=>{let r=mA(t);return cat(e.client,r.notificationId,r.read!==!1)}},{name:"mark_all_notifications_read",description:"Mark every unread notification of the caller read. Returns marked and more: when more is true, call again.",params:{},required:[],group:"collaboration",readOnly:!1,isDestructive:!0,searchHint:"mark all notifications read, clear the inbox, dismiss every unread mention and comment",execute:async e=>lat(e.client)},{name:"validate_invoice_draft",description:"Check if an invoice draft is ready to finalize. Returns missing fields, structured validation report, and ready status. Use before finalize_invoice to prevent errors.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"drafts",readOnly:!0,searchHint:"validate invoice draft readiness for finalization",isConcurrencySafe:!0,execute:async(e,t)=>{let r=t.resourceId,n=await go(e.client,r),i=await gi(e.client,"invoices",r);return ts(n.data,rl,i.data.length)}},{name:"validate_bill_draft",description:"Check if a bill draft is ready to finalize. Returns missing fields, structured validation report, and ready status. Use before finalize_bill to prevent errors.",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"drafts",readOnly:!0,searchHint:"validate bill draft readiness for finalization",isConcurrencySafe:!0,execute:async(e,t)=>{let r=t.resourceId,n=await fo(e.client,r),i=await gi(e.client,"bills",r);return ts(n.data,xa,i.data.length)}},{name:"validate_journal_draft",description:"Check if a journal draft is ready to finalize. Returns missing fields (accounts, amounts, date), structured validation, and ready status.",params:{resourceId:{type:"string",description:"Journal resourceId"}},required:["resourceId"],group:"drafts",readOnly:!0,searchHint:"validate journal draft readiness for posting",isConcurrencySafe:!0,execute:async(e,t)=>{let r=await vs(e.client,t.resourceId);return ts(r.data,ou,0,"journalEntries")}},{name:"validate_credit_note_draft",description:"Check if a credit note draft (customer or supplier) is ready to finalize. Returns missing fields, structured validation, and ready status.",params:{resourceId:{type:"string",description:"Credit note resourceId"},type:{type:"string",enum:["customer","supplier"],description:'Credit note type: "customer" or "supplier"'}},required:["resourceId","type"],group:"drafts",readOnly:!0,searchHint:"validate credit note draft readiness for finalization",isConcurrencySafe:!0,execute:async(e,t)=>{let r=t.resourceId,n=t.type,i=n==="customer"?await Ws(e.client,r):await Ks(e.client,r),o=n==="customer"?"customer-credit-notes":"supplier-credit-notes",s=await gi(e.client,o,r);return ts(i.data,_o,s.data.length)}},br("list_bank_rules","List bank reconciliation rules (action shortcuts). Shows rule name, action type, and target bank account.","bank_rules",(e,t,r)=>u8(e,{limit:r,offset:t}),"list automatic bank reconciliation rules"),ri("get_bank_rule","Get full bank rule details including configuration (allocation percentages, accounts, tax settings).","bank_rules",(e,t)=>nO(e,t),"get bank rule details conditions actions"),Nt({name:"search_bank_rules",description:"Search bank rules.",group:"bank_rules",fields:fx,defaults:px,fetcher:d8,searchHint:"find bank rules auto-reconciliation matching criteria by name"}),{name:"create_bank_rule",description:`Bank reconciliation rule: auto-matches bank records. Use directly on request; don't just list existing.
|
|
772
772
|
|
|
773
773
|
Required: name, appliesToReconciliationAccount (bank account UUID, no "ResourceId" suffix), configuration.
|
|
774
774
|
|
|
@@ -802,7 +802,7 @@ accountResourceId + taxProfileResourceId apply to ALL line items (immutable). in
|
|
|
802
802
|
|
|
803
803
|
Dynamic strings (reference/lineItem name/notes): ${fO}, relative to transaction date.`,params:{interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Billing interval, sent as `repeat`. QUARTERLY is rejected with 422."},startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD, optional for ongoing)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference (REQUIRED). Supports dynamic strings: {{Month}}, {{Year}}, etc."},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},accountResourceId:{type:"string",description:"Revenue account resourceId (applied to ALL line items; must be same)"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId (applied to ALL line items; must be same)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"}},required:["name","unitPrice","quantity"]},description:"Line items (name, unitPrice, quantity only; account/tax set at top level)"},proratedConfig:{type:"object",description:"Optional prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"Prorated window start (YYYY-MM-DD). Defaults to subscription startDate."},proratedAdjustmentLineText:{type:"string",description:'Adjustment line label on the prorated invoice (default "Prorated adjustment").'},itemResourceId:{type:"string",description:"Non-inventory item resourceId (UUIDv4) for the prorated adjustment line. Defaults to the subscription's first line item."},includeNextPeriod:{type:"boolean",description:"If true: bundle the next full period at 2x quantity AND advance nextScheduleDate by one extra interval. Response carries bundledPeriodEndDate + bundledAmount."}}}},required:["interval","startDate","contactResourceId","lineItems","accountResourceId","valueDate","dueDate","reference"],group:"subscriptions",readOnly:!1,searchHint:"create new recurring subscription billing schedule with proration",execute:async(e,t)=>{let{interval:r,startDate:n,endDate:i,contactResourceId:o,reference:s,valueDate:a,dueDate:c,accountResourceId:u,taxProfileResourceId:d,lineItems:f,proratedConfig:p}=t,h=f.map(A=>({...A,accountResourceId:u,...d?{taxProfileResourceId:d}:{}})),m={repeat:r,startDate:n,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment",...p??{}},invoice:{contactResourceId:o,reference:s||Lo("SUB"),valueDate:a,dueDate:c,lineItems:h,saveAsDraft:!1}};return i&&(m.endDate=i),W8(e.client,m)}},{name:"update_subscription",description:"Update a subscription (interval, end date, status, template, proratedConfig). `data` is required on every update, even end-date-only: create shape (reference, valueDate, dueDate, contactResourceId, lineItems with accountResourceId), not get_subscription's `data`. Omitted status is kept. Line accounts and tax profiles are immutable: cancel and recreate.",params:{resourceId:{type:"string",description:"Subscription id"},interval:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Sent as `repeat`"},endDate:{type:"string",description:"New end date (YYYY-MM-DD)"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"INACTIVE pauses"},proratedConfig:{type:"object",description:"Prorated-period settings, all optional",properties:{proratedStartDate:{type:"string",description:"YYYY-MM-DD"},proratedAdjustmentLineText:{type:"string"},itemResourceId:{type:"string",description:"UUIDv4"},includeNextPeriod:{type:"boolean"}}},data:{type:"object",description:"Transaction template (replaces the stored one)"}},required:["resourceId","data"],group:"subscriptions",readOnly:!1,isDestructive:!0,searchHint:"update subscription schedule amount proration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return K8(e.client,r,n)}},Ur("delete_subscription","Delete a subscription. Removes the recurring schedule.","subscriptions",(e,t)=>X8(e,t),"permanently delete a subscription schedule"),{name:"cancel_subscription",description:"Cancel an active subscription. Prorates remaining period and stops future billing. Safe to call; subscriptions can be reactivated after cancellation. Always use this tool when the user asks to cancel a subscription. Must cancel before delete.",params:{resourceId:{type:"string",description:"Subscription resourceId"},cancelDateType:{type:"string",enum:["END_OF_CURRENT_PERIOD","END_OF_LAST_PERIOD","CUSTOM_DATE"],description:"When to end (default: END_OF_CURRENT_PERIOD)"},endDate:{type:"string",description:"Custom cancel date YYYY-MM-DD (only with CUSTOM_DATE)"},proratedAdjustmentLineText:{type:"string",description:'Label for proration line item (default: "Prorated adjustment")'}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"cancel stop a recurring subscription",isDestructive:!0,execute:async(e,t)=>Z8(e.client,t.resourceId,{cancelDateType:t.cancelDateType,endDate:t.endDate,proratedAdjustmentLineText:t.proratedAdjustmentLineText})},Nt({name:"search_scheduled_transactions",description:"Search scheduled transactions (subscriptions / recurring invoices / journals / cash entries).",group:"subscriptions",fields:CT,defaults:_T,fetcher:eW,searchHint:"find scheduled recurring transactions subscriptions schedulers by type status interval contact"}),{name:"generate_vat_ledger",description:"Generate VAT/GST ledger report showing all tax transactions for the period.",params:{startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD)"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate VAT GST tax ledger report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Sq(e.client,{startDate:t.startDate,endDate:t.endDate})},{name:"generate_equity_movement",description:"Generate equity movement report (statement of changes in equity).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},compareWith:{type:"string",description:"Comparison period unit; compareCount sets how many",enum:["PREVIOUS_MONTHS","PREVIOUS_DAYS","PREVIOUS_QUARTERS","PREVIOUS_YEARS"]},compareCount:{type:"number",description:"Number of comparison periods"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"financial_reports",readOnly:!0,searchHint:"generate equity movement statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Dq(e.client,t)},{name:"generate_bank_balance_summary",description:"Generate bank balance summary report: snapshot of all bank account balances at a point in time.",params:{primarySnapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["primarySnapshotDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank account balance summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Rq(e.client,{primarySnapshotDate:t.primarySnapshotDate,currencyCode:t.currencyCode})},{name:"generate_bank_reconciliation_summary",description:"Generate bank reconciliation summary for a specific bank account. Essential for month-end close; call this for each in-scope bank account for the current entity and reporting period. Use for bank recon status, unreconciled items count, or reconciliation summaries.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Tq(e.client,t)},{name:"generate_bank_reconciliation_details",description:"Generate detailed bank reconciliation report showing matched/unmatched items.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},filter:{type:"object",description:"Report filter. valueDate is required.",properties:{valueDate:{type:"object",description:"Report window.",properties:{range:{type:"array",items:{type:"string"},description:"Inclusive [from, to], YYYY-MM-DD. The only accepted operator."}},required:["range"]},reconciliationStatus:{type:"string",description:"Reconciliation status (no published enum)."}},required:["valueDate"]},currencyCode:{type:"string",description:"Currency code"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate","filter"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation detailed report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>xq(e.client,t)},{name:"generate_fixed_assets_summary",description:"Generate fixed assets summary report grouped by account, type, category, or status.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["ACCOUNT","TYPE","CATEGORY","STATUS"],description:"Grouping dimension"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate","groupBy"],group:"register_reports",readOnly:!0,searchHint:"generate fixed asset summary depreciation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>kq(e.client,t)},{name:"generate_fixed_assets_reconciliation_summary",description:"Generate fixed assets reconciliation summary: reconciles asset register with general ledger.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate fixed asset reconciliation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Nq(e.client,t)},{name:"generate_deferrals_summary",description:"Generate the deferrals roll-forward for a period: deferral amount, opening remaining, amortized in period, closing remaining. Sections never mix categories (prepaid vs deferred revenue).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["CATEGORY","TYPE","ACCOUNT","STATUS"],description:"Default CATEGORY"},filter:dSr,currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate deferrals summary prepaid roll-forward amortized in period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Bq(e.client,t)},{name:"generate_deferrals_reconciliation_summary",description:"Generate the deferrals reconciliation: does the deferral register agree with the general ledger, per deferral account and per category. A difference usually means a line on the account not yet deferred.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Deferral account ids from search_deferral_accounts (max 500). Omit for all."},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate deferrals reconciliation prepaid register agree general ledger",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Oq(e.client,t)},{name:"generate_leases_summary",description:"Generate the lease register (the IFRS 16 lease note) for a period: opening liability, additions, interest, payments, terminations, closing, current and non-current, right-of-use asset, grouped by type, status or account. The maturity analysis is a sheet of the download_export leases-register file.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["TYPE","STATUS","ACCOUNT"],description:"Grouping dimension (default TYPE)"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate lease register IFRS 16 note lease liability roll-forward",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>i$e(e.client,t)},{name:"generate_leases_reconciliation_summary",description:"Reconcile the lease register to the general ledger per lease account, counting scheduled rent as debits to the current lease liability. A liability difference almost always means a rent bill coded elsewhere, posted in another month, or not booked.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Lease account resourceIds (max 500). Default: all lease accounts."},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate lease register vs general ledger reconciliation rent coding",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>o$e(e.client,t)},vO("generate_loans_summary","loans-summary","Borrowings note: per loan opening balance, drawdowns, repayments, interest, closing balance, current and non-current portion and accrued interest, grouped by type, status, account or lender. Positions are the register's; movements read the ledger, so an unrecorded repayment shows here.","generate loans summary borrowings note by lender type"),vO("generate_loans_roll_forward","loans-roll-forward","Loan roll-forward over a period: opening + drawdowns + repayments + interest + fees + non-cash = closing, tying to the balance sheet. Drawdowns and repayments are the user's own postings, so a missing repayment shows as a gap.","generate loans roll forward movement borrowings"),vO("generate_loans_related_party","loans-related-party","Related-party loan balances by contact: loans of type DIRECTOR, SHAREHOLDER, RELATED_PARTY and INTERCOMPANY, for the audit.","generate related party director shareholder loans balances audit"),vO("generate_loans_interest","loans-interest","Interest cost per loan for the period: interest, interest added to principal, interest to an asset, fees amortized and total finance cost.","generate loan interest cost finance cost per loan"),vO("generate_loans_maturity_analysis","loans-maturity-analysis","Liquidity note as at the end date: per term loan the undiscounted installments still due within one year, one to two, two to five and over five years, plus future interest and principal outstanding. On-demand balances fall within one year.","generate loan maturity analysis liquidity undiscounted installments buckets"),{name:"generate_loans_reconciliation_summary",description:"Loan register vs general ledger per account, in two groups: loan liability accounts and unamortized transaction cost accounts. The register side includes what the user is expected to post, so a non-zero difference means a missed, late, partial or mis-coded installment: name the account and amount and check that month. Debit minus credit, so liabilities read negative.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Loan account resourceIds (max 500); omit for all"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"register_reports",readOnly:!0,searchHint:"generate loan reconciliation register vs ledger month end difference",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>Bx(e.client,"loans-recon-summary",t)},J4("generate_aged_receivables_summary","receivables","summary"),J4("generate_aged_payables_summary","payables","summary"),{name:"get_ledger_highlights",description:"Get ledger highlights, summary metadata about the org general ledger: transaction counts by type, date range, active accounts, active currencies, and cross-currency detection. No parameters needed.",params:{},required:[],group:"operational_reports",readOnly:!0,searchHint:"get ledger highlights key metrics for period",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>Qq(e.client)},br("list_contact_groups","List contact groups with their associated contacts. Used to segment customers/suppliers.","contact_groups",(e,t,r)=>rW(e,{limit:r,offset:t}),"list contact groups customer supplier categories"),ri("get_contact_group","Get contact group details including all associated contacts.","contact_groups",(e,t)=>nW(e,t),"get contact group details members"),Nt({name:"search_contact_groups",description:"Search contact groups.",group:"contact_groups",fields:cx,defaults:lx,fetcher:iW,searchHint:"find contact groups segments categories by name"}),{name:"create_contact_group",description:'Create a new contact group for segmenting contacts (e.g., "VIP Customers", "Government", "Overdue > 90 Days").',params:{name:{type:"string",description:"Group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to add to the group"}},required:["name"],group:"contact_groups",readOnly:!1,searchHint:"create new contact group category",execute:async(e,t)=>oW(e.client,{name:t.name,contactResourceIds:t.contactResourceIds})},{name:"update_contact_group",description:"Update a contact group name or members. Membership replaces the existing set.",params:{resourceId:{type:"string",description:"Contact group resourceId"},name:{type:"string",description:"New group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to set as group members, max 50 (replaces existing). Sent as associatedContactResourceIds."}},required:["resourceId"],group:"contact_groups",readOnly:!1,isDestructive:!0,searchHint:"update contact group name details",execute:async(e,t)=>sW(e.client,t.resourceId,{name:t.name,contactResourceIds:t.contactResourceIds})},Ur("delete_contact_group","Delete a contact group. Does not delete the contacts themselves.","contact_groups",(e,t)=>aW(e,t),"permanently delete a contact group"),br("list_custom_fields","List custom fields defined for the organization. Custom fields add extra data to invoices, bills, credit notes, and payments.","custom_fields",(e,t,r)=>pW(e,{limit:r,offset:t}),"list custom fields metadata on transactions"),{name:"get_custom_field",description:"Get a custom field by resourceId. Returns full definition including appliesTo flags and list options.",params:{resourceId:{type:"string",description:"Custom field resourceId"}},required:["resourceId"],group:"custom_fields",readOnly:!0,searchHint:"get custom field definition details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>sO(e.client,t.resourceId)},Nt({name:"search_custom_fields",description:"Search custom fields.",group:"custom_fields",fields:sx,defaults:ax,fetcher:hW,searchHint:"find custom fields user-defined attributes by name data type"}),{name:"create_custom_field",description:`Create a new custom field. Custom fields appear on transactions (invoices, bills, credit notes, payments).
|
|
804
804
|
- appliesTo controls which transaction types show this field. Omit it and it shows on none.
|
|
805
|
-
- printOnDocuments controls whether the field appears on PDFs.`,params:{name:{type:"string",description:'Field name (e.g., "PO Number", "Cost Center")'},description:{type:"string",description:"Field description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents (default false)"},appliesTo:{type:"object",description:"Which transaction types: { invoices: true, bills: true, customerCredits: true, supplierCredits: true, payments: true }"},format:Zct},required:["name"],group:"custom_fields",readOnly:!1,searchHint:"create new custom field for transactions",execute:async(e,t)=>mW(e.client,{...t,printOnDocuments:t.printOnDocuments??!1})},{name:"update_custom_field",description:"Update a custom field definition. Omitted fields keep their current values.",params:{resourceId:{type:"string",description:"Custom field resourceId"},name:{type:"string",description:"New field name"},description:{type:"string",description:"New description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents"},appliesTo:{type:"object",description:"Which transaction types: { invoices, bills, customerCredits, supplierCredits, payments }"},format:Zct},required:["resourceId"],group:"custom_fields",readOnly:!1,isDestructive:!0,searchHint:"update custom field name type settings",execute:async(e,t)=>{let{resourceId:r,...n}=t;return AW(e.client,r,n)}},Ur("delete_custom_field","Delete a custom field. Removes it from all future transactions.","custom_fields",(e,t)=>gW(e,t),"permanently delete a custom field definition"),br("list_withholding_codes","List withholding codes (BIR ATCs, PH): code, rate, type, description. A row feeds a bill or supplier credit note line's withholdingTax (EWT) and, by its resourceId, a Withholding Tax Certificate (BIR Form 2307, CWT) allocation. limit max 100.","tax_profiles",(e,t,r,n,i)=>eM(e,{offset:t,limit:r},i),"withholding codes WHT ATC EWT CWT expanded creditable withholding tax BIR 2307",{filters:{countryCode:{type:"string",description:"e.g. PH"},code:{type:"string",description:'Contains match; codes have a space ("WC 158"; "WC158" matches nothing)'},type:{type:"string",enum:["corp","ind","final","wvat"]}}}),Nt({name:"search_tax_profiles",description:"Search tax profiles. Use appliesToSale / appliesToPurchase filters to scope by transaction type.",group:"tax_profiles",fields:rx,defaults:nx,fetcher:jI,searchHint:"find tax profiles GST VAT WHT by name tax type code applicability sale purchase"}),Nt({name:"search_filing_submissions",description:"Search tax return filings (PH BIR 2550Q, SG GST F5): period, due date, tax due, status.",group:"tax_profiles",fields:DT,defaults:RT,fetcher:i8,searchHint:"BIR GST filings"}),ri("get_tax_profile","Get full tax profile details including tax rate, type code, and status.","tax_profiles",(e,t)=>oD(e,t),"get tax profile details rate code"),{name:"update_tax_profile",description:"Update an existing tax profile. Omitted fields keep their current values; status is not updatable.",params:{resourceId:{type:"string",description:"Tax profile resourceId"},name:sge,description:{type:"string"},vatValue:{type:"number",description:"Tax rate % (0-100)"},taxType:{type:"string",description:"Tax type code (list_tax_types)"}},required:["resourceId"],group:"tax_profiles",readOnly:!1,isDestructive:!0,searchHint:"update tax profile name rate details",execute:async(e,t)=>ZP(e.client,t.resourceId,{name:t.name,description:t.description,vatValue:t.vatValue,taxType:t.taxType})},{name:"create_claim_type",description:"Create a claim type (expense category for employee claims). Dedups by name. expenseAccountResourceId is server-required.",params:{name:{type:"string",description:"Claim type name (unique per org)"},expenseAccountResourceId:{type:"string",description:'Expense CoA resourceId, REQUIRED server-side (search_accounts; accountType is a display label e.g. "Operating Expense")'},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Magic OCR classifier defaults (JSON string)"}},required:["name"],group:"claim_types",readOnly:!1,searchHint:"create claim type expense category",execute:async(e,t)=>{let r=t.name,n=await UM(e.client,r);return n?{_guard:"duplicate_skipped",message:`Claim type "${r}" already exists.`,existing:n}:aM(e.client,{name:r,expenseAccountResourceId:t.expenseAccountResourceId,taxProfileResourceId:t.taxProfileResourceId,classifierConfig:t.classifierConfig})}},{name:"update_claim_type",description:"Update a claim type. Omitted fields unchanged; clearFields NULLs optional fields.",params:{resourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"New name"},expenseAccountResourceId:{type:"string",description:"Default expense CoA resourceId"},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Classifier defaults (JSON string)"},clearFields:{type:"array",items:{type:"string",enum:[...cD]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_types",readOnly:!1,isDestructive:!0,searchHint:"update claim type",execute:async(e,t)=>cM(e.client,t.resourceId,{name:t.name,expenseAccountResourceId:t.expenseAccountResourceId,taxProfileResourceId:t.taxProfileResourceId,classifierConfig:t.classifierConfig,...bg(t.clearFields,cD)})},Nt({name:"search_claim_types",description:"Search claim types.",group:"claim_types",fields:qT,defaults:jT,fetcher:HI,searchHint:"find claim types by name default expense account tax profile"}),br("list_claim_types","List claim types (alphabetical).","claim_types",(e,t,r)=>oM(e,{offset:t,limit:r}),"list claim types"),ri("get_claim_type","Get a claim type incl. nested expense account + tax profile.","claim_types",(e,t)=>sM(e,t),"get claim type details"),Ur("delete_claim_type","Soft-delete a claim type (name becomes reusable).","claim_types",(e,t)=>lM(e,t),"delete claim type"),{name:"create_claim_profile",description:"Create a claim profile (per-employee policy bundle: approver, limits, visible types, balance account). Dedups by name. taxMode EXCLUSIVE is rejected.",params:{name:{type:"string",description:"Profile name (unique per org)"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (free-text vendors always allowed)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (null = no restriction)"},minClaimAmount:{type:"number",description:"Min claim total (<= max)"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap (requires perPeriod)"},perPeriod:{type:"string",enum:[...lD],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Per-employee liability (CURRENT_LIABILITY) CoA resourceId; required for reimbursement conversion"},taxMode:{type:"string",enum:[..._Z],description:"Tax policy (NO_TAX or INCLUSIVE)"}},required:["name"],group:"claim_profiles",readOnly:!1,searchHint:"create claim profile policy approver limits",execute:async(e,t)=>{let r=t.name,n=await $M(e.client,r);return n?{_guard:"duplicate_skipped",message:`Claim profile "${r}" already exists.`,existing:n}:pM(e.client,{name:r,approverUserResourceId:t.approverUserResourceId,visibleClaimTypeIds:t.visibleClaimTypeIds,visibleTaxProfileIds:t.visibleTaxProfileIds,visibleClassifierIds:t.visibleClassifierIds,visibleVendorResourceIds:t.visibleVendorResourceIds,allowedCurrencies:t.allowedCurrencies,minClaimAmount:t.minClaimAmount,maxClaimAmount:t.maxClaimAmount,maxPerPeriodAmount:t.maxPerPeriodAmount,perPeriod:t.perPeriod,employeeBalanceAccountResourceId:t.employeeBalanceAccountResourceId,taxMode:t.taxMode})}},{name:"update_claim_profile",description:"Update a claim profile. Omitted fields unchanged; clearFields NULLs optional fields. Balance account cannot change while an employee has a non-zero balance.",params:{resourceId:{type:"string",description:"Claim profile resourceId"},name:{type:"string",description:"New name"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs (replaces)"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs (replaces)"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs (replaces)"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (replaces)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (replaces)"},minClaimAmount:{type:"number",description:"Min claim total"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap"},perPeriod:{type:"string",enum:[...lD],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Employee balance CoA resourceId"},taxMode:{type:"string",enum:[..._Z],description:"Tax policy (NO_TAX or INCLUSIVE)"},clearFields:{type:"array",items:{type:"string",enum:[...uD]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_profiles",readOnly:!1,isDestructive:!0,searchHint:"update claim profile policy limits",execute:async(e,t)=>hM(e.client,t.resourceId,{name:t.name,approverUserResourceId:t.approverUserResourceId,visibleClaimTypeIds:t.visibleClaimTypeIds,visibleTaxProfileIds:t.visibleTaxProfileIds,visibleClassifierIds:t.visibleClassifierIds,visibleVendorResourceIds:t.visibleVendorResourceIds,allowedCurrencies:t.allowedCurrencies,minClaimAmount:t.minClaimAmount,maxClaimAmount:t.maxClaimAmount,maxPerPeriodAmount:t.maxPerPeriodAmount,perPeriod:t.perPeriod,employeeBalanceAccountResourceId:t.employeeBalanceAccountResourceId,taxMode:t.taxMode,...bg(t.clearFields,uD)})},Nt({name:"search_claim_profiles",description:"Search claim profiles.",group:"claim_profiles",fields:YT,defaults:HT,fetcher:zI,searchHint:"find claim profiles by name approver default limits balance account"}),br("list_claim_profiles","List claim profiles (alphabetical).","claim_profiles",(e,t,r)=>dM(e,{offset:t,limit:r}),"list claim profiles"),ri("get_claim_profile","Get a claim profile incl. nested balance account.","claim_profiles",(e,t)=>fM(e,t),"get claim profile details"),Ur("delete_claim_profile","Soft-delete a claim profile.","claim_profiles",(e,t)=>mM(e,t),"delete claim profile"),{name:"create_posting_rule",description:"Create a posting rule (how approved claims group into journals at conversion). outerAxis + innerAxis + lineDescriptionTemplate required. Dedups by name.",params:{name:{type:"string",description:"Rule name (unique per org)"},outerAxis:{type:"string",enum:[...fD],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...pD],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:'Handlebars line template, e.g. "{employeeName} - {claimType}"'},journalReferenceTemplate:{type:"string",description:"Optional Handlebars journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank (Cash/Bank) account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["name","outerAxis","innerAxis","lineDescriptionTemplate"],group:"posting_rules",readOnly:!1,searchHint:"create posting rule claim conversion grouping",execute:async(e,t)=>{let r=t.name,n=await qM(e.client,r);return n?{_guard:"duplicate_skipped",message:`Posting rule "${r}" already exists.`,existing:n}:yM(e.client,{name:r,outerAxis:t.outerAxis,innerAxis:t.innerAxis,lineDescriptionTemplate:t.lineDescriptionTemplate,journalReferenceTemplate:t.journalReferenceTemplate,defaultBankAccountResourceId:t.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:t.defaultIncludeReimbursementPayout,isDefault:t.isDefault})}},{name:"update_posting_rule",description:"Update a posting rule. Omitted fields unchanged.",params:{resourceId:{type:"string",description:"Posting rule resourceId"},name:{type:"string",description:"New name"},outerAxis:{type:"string",enum:[...fD],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...pD],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:"Handlebars line template"},journalReferenceTemplate:{type:"string",description:"Journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["resourceId"],group:"posting_rules",readOnly:!1,isDestructive:!0,searchHint:"update posting rule",execute:async(e,t)=>EM(e.client,t.resourceId,{name:t.name,outerAxis:t.outerAxis,innerAxis:t.innerAxis,lineDescriptionTemplate:t.lineDescriptionTemplate,journalReferenceTemplate:t.journalReferenceTemplate,defaultBankAccountResourceId:t.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:t.defaultIncludeReimbursementPayout,isDefault:t.isDefault})},Nt({name:"search_posting_rules",description:"Search posting rules.",group:"posting_rules",fields:zT,defaults:JT,fetcher:JI,searchHint:"find posting rules by name axis default bank reimbursement"}),br("list_posting_rules","List posting rules (alphabetical).","posting_rules",(e,t,r)=>AM(e,{offset:t,limit:r}),"list posting rules"),ri("get_posting_rule","Get a posting rule.","posting_rules",(e,t)=>gM(e,t),"get posting rule details"),Ur("delete_posting_rule","Delete a posting rule. The org default cannot be deleted while default (set another default first).","posting_rules",(e,t)=>bM(e,t),"delete posting rule"),Nt({name:"search_claims",description:'Search/list employee-expense claims. Status: DRAFT|SUBMITTED|APPROVED|CONVERTED|REJECTED|CANCELLED (CONVERTED = "Processed"). Claims are born via create_claim, attachment, or conversion (no bare list; use search).',group:"claims",fields:PT,defaults:MT,fetcher:r2,searchHint:"find employee expense claims by status employee contact reference date amount"}),ri("get_claim","Get a claim incl. line items, employee, amounts, status.","claims",(e,t)=>LT(e,t),"get claim details line items"),{name:"create_claim",description:"Create an employee-expense claim directly (bare create, no attachment). Vendor is EITHER contactResourceId OR vendorName, never both. saveAsDraft defaults to true (lands DRAFT with relaxed line validation); set false to validate + submit in one call (lands SUBMITTED). reference is REQUIRED when submitting (saveAsDraft=false): omitting it returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT; a DRAFT saves without one.",params:{valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},saveAsDraft:{type:"boolean",description:"true (default) creates DRAFT; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId the claim is filed for"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},reference:{type:"string",description:"User reference"},autoReference:uu,currencySymbol:{type:"string",description:"Currency symbol override"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:{type:"array",items:{type:"string"},description:"Header-level tags"},internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId (defaults to org default)"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Tn,claimItems:llt},required:["valueDate","currencyCode"],group:"claims",readOnly:!1,searchHint:"create new employee expense claim draft vendor employee line items submit",execute:async(e,t)=>n2(e.client,{valueDate:t.valueDate,currencyCode:t.currencyCode,saveAsDraft:t.saveAsDraft,employeeResourceId:t.employeeResourceId,contactResourceId:t.contactResourceId,vendorName:t.vendorName,reference:await bU(e.client,"CLAIM",t.reference,t.autoReference),currencySymbol:t.currencySymbol,taxInclusion:t.taxInclusion,tags:t.tags,internalNotes:t.internalNotes,claimProfileResourceId:t.claimProfileResourceId,approverUserResourceId:t.approverUserResourceId,customFields:t.customFields,claimItems:t.claimItems})},{name:"update_claim",description:"Update a DRAFT claim (partial: omitted fields unchanged). claimItems non-empty REPLACES all lines, [] clears. Set saveAsDraft=false to validate + submit in one call: reference is REQUIRED at submit (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT); a DRAFT save needs none. Only DRAFT claims are editable.",params:{resourceId:{type:"string",description:"Claim resourceId"},saveAsDraft:{type:"boolean",description:"true (default) keeps editing; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},reference:{type:"string",description:"User reference"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:jo,internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Tn,claimItems:llt},required:["resourceId"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"edit draft claim line items employee reference submit",execute:async(e,t)=>{let r=t.resourceId,n=Ui(t.tags),i=n&&await Yo("claim",r,()=>LT(e.client,r));return i2(e.client,r,{saveAsDraft:t.saveAsDraft,employeeResourceId:t.employeeResourceId,contactResourceId:t.contactResourceId,vendorName:t.vendorName,valueDate:t.valueDate,reference:t.reference,currencyCode:t.currencyCode,taxInclusion:t.taxInclusion,tags:n&&Ki(i?.tags,n),internalNotes:t.internalNotes,claimProfileResourceId:t.claimProfileResourceId,approverUserResourceId:t.approverUserResourceId,customFields:t.customFields,claimItems:t.claimItems})}},Ur("delete_claim","Delete a claim. Only DRAFT / REJECTED / CANCELLED claims are deletable (else 422).","claims",(e,t)=>o2(e,t),"delete remove claim record"),{name:"delete_claim_attachment",description:"Remove one attachment (receipt) from a claim. Returns the updated claim.",params:{resourceId:{type:"string",description:"Claim resourceId"},attachmentResourceId:{type:"string",description:"Attachment resourceId"}},required:["resourceId","attachmentResourceId"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"remove delete claim attachment receipt",execute:async(e,t)=>s2(e.client,t.resourceId,t.attachmentResourceId)},lge("submit_claim","Submit a DRAFT claim for approval (DRAFT \u2192 SUBMITTED). Server enforces the transition. The claim must carry a reference; a referenceless DRAFT returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (set it via update_claim first).","claims",(e,t)=>a2(e,t),{destructive:!0,searchHint:"submit draft claim for approval"}),lge("approve_claim","Approve a SUBMITTED claim (SUBMITTED \u2192 APPROVED). Approved claims become convertible to journals.","claims",(e,t)=>c2(e,t),{destructive:!0,searchHint:"approve submitted claim"}),{name:"reject_claim",description:"Reject a SUBMITTED/APPROVED claim with a reason (\u2192 REJECTED).",params:{resourceId:{type:"string",description:"Claim resourceId"},rejectionReason:{type:"string",description:"Rejection reason (1-1000 chars)"}},required:["resourceId","rejectionReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"reject claim with reason",execute:async(e,t)=>l2(e.client,t.resourceId,t.rejectionReason)},{name:"cancel_claim",description:"Cancel a DRAFT/SUBMITTED claim with a reason (\u2192 CANCELLED).",params:{resourceId:{type:"string",description:"Claim resourceId"},cancellationReason:{type:"string",description:"Cancellation reason (1-1000 chars)"}},required:["resourceId","cancellationReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"cancel claim with reason",execute:async(e,t)=>u2(e.client,t.resourceId,t.cancellationReason)},lge("unpost_claim","Unpost a CONVERTED claim: voids its journal, back to APPROVED. Re-unpost: 200 no-op. Aggregated claims unpost together. Ignores payouts (employee balance can go negative).","claims",(e,t)=>d2(e,t),{destructive:!0,searchHint:"unpost reverse converted claim conversion"}),{name:"bulk_submit_claims",description:`Bulk-submit DRAFT claims (ASYNC). Returns the final job if it finished, else a job handle {jobId,...} to poll with search_background_jobs by jobId for per-item results. ${rs} Max 500 ids. Each claim must have a reference; referenceless claims fail per-item with CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (check the job result).`,params:{resourceIds:_O},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk submit many claims async job",backgroundJob:Mn("Submit","claim","claims","resourceIds"),execute:async(e,t)=>f2(e.client,t.resourceIds)},{name:"bulk_approve_claims",description:`Bulk-approve SUBMITTED claims (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk approve many claims async job",backgroundJob:Mn("Approve","claim","claims","resourceIds"),execute:async(e,t)=>p2(e.client,t.resourceIds)},{name:"bulk_reject_claims",description:`Bulk-reject claims with one shared reason (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O,rejectionReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","rejectionReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk reject many claims async job reason",backgroundJob:Mn("Reject","claim","claims","resourceIds"),execute:async(e,t)=>m2(e.client,t.resourceIds,t.rejectionReason)},{name:"bulk_cancel_claims",description:`Bulk-cancel claims with one shared reason (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O,cancellationReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","cancellationReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk cancel many claims async job reason",backgroundJob:Mn("Cancel","claim","claims","resourceIds"),execute:async(e,t)=>A2(e.client,t.resourceIds,t.cancellationReason)},{name:"bulk_delete_claims",description:`Bulk-delete claims (ASYNC; only DRAFT/REJECTED/CANCELLED are deletable). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk delete many claims async job",backgroundJob:Mn("Delete","claim","claims","resourceIds"),execute:async(e,t)=>h2(e.client,t.resourceIds)},{name:"get_claim_tracking_tags",description:"List the tracking-tag values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim tracking tags picker",execute:async e=>g2(e.client)},{name:"get_claim_custom_field_values",description:"List the custom-field values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim custom field values picker",execute:async e=>y2(e.client)},{name:"preview_claims_conversion",description:"Preview the journals an APPROVED claim batch would produce at conversion, no write. Returns expenseSubTotal, previewJournals, and reimbursement DCE counts; non-APPROVED claims come back under erroredClaims (check it is empty before converting). Needs a default posting rule or an explicit postingRuleResourceId.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},payoutFlow:{type:"string",enum:[...eO],description:"POST (journals only) or POST_AND_RECORD (+ books-only reimbursement DCE)"},includeReimbursementPayout:{type:"boolean",description:"Include per-employee reimbursement DCE lines"},bankAccountResourceId:{type:"string",description:"Reimbursement bank account for preview validation"}},required:["claimResourceIds"],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview claim conversion journals before posting",execute:async(e,t)=>e8(e.client,{claimResourceIds:t.claimResourceIds,postingRuleResourceId:t.postingRuleResourceId,payoutFlow:t.payoutFlow,includeReimbursementPayout:t.includeReimbursementPayout,bankAccountResourceId:t.bankAccountResourceId})},{name:"convert_claims_to_journal",description:"Convert an APPROVED claim batch into journals (atomic write). valueDate (YYYY-MM-DD) required. Preview first and confirm erroredClaims is empty. idempotencyKey is auto-generated for safe retries (pass your own to dedup across calls). includeReimbursementPayout adds a books-only reimbursement DCE; real-money disburse is intentionally not exposed.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},valueDate:{type:"string",description:"Journal value date (YYYY-MM-DD)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},includeReimbursementPayout:{type:"boolean",description:"Create books-only reimbursement DCEs"},bankAccountResourceIdOverride:{type:"string",description:"Override the rule default reimbursement bank account"},contactResourceId:{type:"string",description:"Clearing contact for the reimbursement DCE cash-out"},idempotencyKey:{type:"string",description:"Optional retry-dedup token (must not start with CONV: / CONV-); auto-generated if omitted"}},required:["claimResourceIds","valueDate"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"convert post approved claims to journal entries",execute:async(e,t)=>t8(e.client,{claimResourceIds:t.claimResourceIds,valueDate:t.valueDate,postingRuleResourceId:t.postingRuleResourceId,includeReimbursementPayout:t.includeReimbursementPayout,bankAccountResourceIdOverride:t.bankAccountResourceIdOverride,contactResourceId:t.contactResourceId,idempotencyKey:t.idempotencyKey||tSr()})},{name:"record_employee_payout",description:"Record a books-only employee payout (reimbursement or advance): a DCE, no real-money transfer. amount, paymentAccountResourceId and valueDate are required; reference auto-generated if omitted.",params:{employeeResourceId:{type:"string",description:"Employee resourceId"},amount:{type:"number",description:"Payout amount (> 0)"},paymentAccountResourceId:{type:"string",description:"Bank/cash account the DCE credits"},valueDate:{type:"string",description:"Value date (YYYY-MM-DD)"},payoutFor:{type:"string",enum:[...dat],description:"Classification (null \u2192 ADVANCE)"},currencyCode:{type:"string",description:"Settle currency (ISO 4217; omit \u2192 payment account currency)"},reference:{type:"string",description:"Payout reference (auto-generated if omitted)"},description:{type:"string",description:"Line description on the DCE"},internalNotes:{type:"string",description:"Internal notes"}},required:["employeeResourceId","amount","paymentAccountResourceId","valueDate"],group:"claim_processing",readOnly:!1,searchHint:"record employee reimbursement advance payout books-only DCE",execute:async(e,t)=>r8(e.client,{employeeResourceId:t.employeeResourceId,amount:t.amount,paymentAccountResourceId:t.paymentAccountResourceId,valueDate:t.valueDate,payoutFor:t.payoutFor,currencyCode:t.currencyCode,reference:t.reference||Lo("EP"),description:t.description,internalNotes:t.internalNotes})},Nt({name:"search_employee_payouts",description:"Search recorded employee payouts (reimbursements + advances).",group:"claim_processing",fields:UT,defaults:$T,fetcher:n8,searchHint:"find employee payouts reimbursements advances by employee reference status type"}),{name:"add_employee",description:"Create an employee (expense-claim member). claimProfileResourceId is REQUIRED (carries the employee balance account; the org default is NOT auto-applied). userResourceId is optional: omit for an offline employee with no login. Dedups by email.",params:{name:{type:"string",description:"Employee display name"},userResourceId:{type:"string",description:"Login user's resourceId to link: the userResourceId field from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND). Optional"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId, REQUIRED (carries the employee balance account; org default NOT auto-applied \u2192 EMPLOYEE_CLAIM_PROFILE_REQUIRED). search_claim_profiles"},email:{type:"string",description:"Work email (per-org unique)"},phone:{type:"string",description:"Phone (per-org unique)"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},active:{type:"boolean",description:"Active flag (default true)"},employmentType:{type:"string",enum:[...Ig],description:"Employment classification"}},required:["name","claimProfileResourceId"],group:"employees",readOnly:!1,searchHint:"create add employee claim member bind user",execute:async(e,t)=>{let r=t.email;if(r){let n=await jM(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Employee with email "${r}" already exists.`,existing:n}}return DM(e.client,{name:t.name,userResourceId:t.userResourceId,claimProfileResourceId:t.claimProfileResourceId,email:r,phone:t.phone,managerEmployeeResourceId:t.managerEmployeeResourceId,active:t.active,employmentType:t.employmentType})}},{name:"update_employee",description:"Update an employee (partial; omitted or null = no change). Clear only via clearFields (userResourceId = unlink). To ARCHIVE, set active=false (reversible, prefer over delete_employee).",params:{resourceId:{type:"string",description:"Employee resourceId"},name:{type:"string",description:"New name"},email:{type:"string",description:"Work email"},phone:{type:"string",description:"Phone"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},active:{type:"boolean",description:"Active flag, set false to archive"},employmentType:{type:"string",enum:[...Ig],description:"Employment classification"},userResourceId:{type:"string",description:"Login user to link/relink (search_org_users userResourceId)"},clearFields:{type:"array",items:{type:"string",enum:[...TZ]},description:"Fields to clear"}},required:["resourceId"],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"update edit archive employee active claim profile",execute:async(e,t)=>RM(e.client,t.resourceId,{name:t.name,email:t.email,phone:t.phone,managerEmployeeResourceId:t.managerEmployeeResourceId,claimProfileResourceId:t.claimProfileResourceId,active:t.active,employmentType:t.employmentType,userResourceId:t.userResourceId,clearFields:t.clearFields})},Nt({name:"search_employees",description:"Search employees by name, email, phone, manager, claim profile, active, currency.",group:"employees",fields:GT,defaults:VT,fetcher:VI,searchHint:"find employees claim members by name email manager profile active"}),Nt({name:"search_employee_balances",description:"Search the employee-balance directory (per-currency reimbursement balances owed).",group:"employees",fields:WT,defaults:KT,fetcher:vM,searchHint:"employee reimbursement balances owed by currency employment type"}),ri("get_employee","Get an employee incl. claim profile + user binding.","employees",(e,t)=>SM(e,t),"get employee details binding balance"),Ur("delete_employee","Delete an employee (server validates they are settled). Prefer update_employee active=false to archive reversibly.","employees",(e,t)=>TM(e,t),"delete remove employee"),{name:"bind_employee_user",description:"Bind a login user to an OFFLINE employee (no user bound yet, e.g. imported without a binding email). Refused once bound: relink or unlink via update_employee.",params:{resourceId:{type:"string",description:"Employee resourceId"},userResourceId:{type:"string",description:"Login user's resourceId: the userResourceId FIELD from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND)"}},required:["resourceId","userResourceId"],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bind link login user to employee",execute:async(e,t)=>xM(e.client,t.resourceId,t.userResourceId)},{name:"preprocess_employees_file",description:"Preprocess an uploaded employee import sheet (CSV/XLSX); returns a parsed row preview to review before import_employees. Provide the sheet fileUrl.",params:{fileUrl:{type:"string",description:"URL of the uploaded employee sheet"},fileName:{type:"string",description:"Display file name"},fileType:{type:"string",enum:["CSV","EML","HEIC","JPEG","JPG","PDF","PNG","TEXT","XLS","XLSX"],description:"File type (use CSV / XLS / XLSX for employee sheets)"}},required:["fileUrl"],group:"employees",readOnly:!0,isConcurrencySafe:!0,searchHint:"preprocess preview employee import sheet csv xlsx",execute:async(e,t)=>kM(e.client,{fileUrl:t.fileUrl,fileName:t.fileName,fileType:t.fileType})},{name:"import_employees",description:`Bulk create/update/delete employees (max 100 rows per array). Rows validate synchronously (422 row errors), then an async job queues: the result is the final job if it finished, else poll search_background_jobs by jobId. ${rs} Create rows need name + claimProfileResourceId (userResourceId optional).`,params:{create:{type:"array",description:"Create rows",items:{type:"object",properties:{name:{type:"string"},email:{type:"string"},userResourceId:{type:"string"},claimProfileResourceId:{type:"string"},employmentType:{type:"string",enum:[...Ig]},managerEmployeeResourceId:{type:"string"},active:{type:"boolean"}},required:["name"]}},update:{type:"array",description:"Update rows",items:{type:"object",properties:{employeeResourceId:{type:"string"},name:{type:"string"},email:{type:"string"},employmentType:{type:"string",enum:[...Ig]},active:{type:"boolean"}},required:["employeeResourceId"]}},delete:{type:"array",description:"Delete rows",items:{type:"object",properties:{employeeResourceId:{type:"string"}},required:["employeeResourceId"]}}},required:[],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bulk import employees create update delete sheet async",backgroundJob:Mn("Import","employee change","employee changes","create","update","delete"),execute:async(e,t)=>NM(e.client,{create:t.create,update:t.update,delete:t.delete})},br("list_inventory_items","List inventory-tracked items with stock details, COGS accounts, and purchase/sale accounts.","inventory",(e,t,r)=>cW(e,{limit:r,offset:t}),"list inventory items stock levels quantities"),{name:"get_inventory_balance",description:"Get current inventory balance for a specific item: quantity on hand, average cost, base unit.",params:{itemResourceId:{type:"string",description:"Item resourceId"}},required:["itemResourceId"],group:"inventory",readOnly:!0,searchHint:"get inventory balance stock level for item",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>uW(e.client,t.itemResourceId)},{name:"list_inventory_balances",description:"List stock on hand, average cost and value per inventory item. One item: get_inventory_balance.",params:{status:{type:"string",enum:[...dW],description:"Default ALL"},...FO},required:[],group:"inventory",readOnly:!0,searchHint:"stock on hand all items",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>{let{limit:r,offset:n}=QO(t),i=t.status??"ALL";return ch((o,s)=>fW(e.client,i,{limit:s,offset:o}),r,n,100)}},{name:"create_inventory_item",description:"Create a new inventory-tracked item. Requires itemCode, name, unit, costingMethod (FIXED or WAC) and three account links. Use --input for full JSON body.",params:{itemCode:{type:"string",description:"Unique item code (SKU)"},name:{type:"string",description:"Item name"},unit:{type:"string",description:'Unit of measure, e.g. "pcs"'},costingMethod:{type:"string",enum:["FIXED","WAC"],description:"Costing method: FIXED or WAC"},cogsResourceId:{type:"string",description:"COGS account resourceId (Direct Costs type)"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId (Inventory type)"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},blockInsufficientDeductions:{type:"boolean",description:"Block transactions when insufficient stock (default: false)"}},required:["itemCode","name","unit","costingMethod","cogsResourceId","purchaseAccountResourceId","saleAccountResourceId"],group:"inventory",readOnly:!1,searchHint:"create new inventory tracked stock item",execute:async(e,t)=>lW(e.client,{itemCode:t.itemCode,name:t.name,unit:t.unit,costingMethod:t.costingMethod,cogsResourceId:t.cogsResourceId,purchaseAccountResourceId:t.purchaseAccountResourceId,saleAccountResourceId:t.saleAccountResourceId,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:t.blockInsufficientDeductions??!1})},Ur("delete_contact","Delete a contact. Cannot delete contacts with existing transactions.","contacts",(e,t)=>vP(e,t),"permanently delete a customer supplier contact"),Ur("delete_account","Delete a chart of accounts entry. Cannot delete accounts with existing transactions.","accounts",(e,t)=>HP(e,t),"permanently delete a chart of accounts entry"),ri("get_cash_transfer","Fetch a cash transfer by cashflow-transaction resourceId (search_cashflow_transactions) or the parentEntityResourceId create returns.","cash_transfers",(e,t)=>iV(e,t),"get cash transfer details between accounts"),TO("download_credit_note_pdf","customer credit note","customer_credit_notes",(e,t)=>cj(e,t)),{name:"get_transaction_summary",description:`Get a complete summary of any transaction: fetches the transaction, its attachments, and payment history in one call.
|
|
805
|
+
- printOnDocuments controls whether the field appears on PDFs.`,params:{name:{type:"string",description:'Field name (e.g., "PO Number", "Cost Center")'},description:{type:"string",description:"Field description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents (default false)"},appliesTo:{type:"object",description:"Which transaction types: { invoices: true, bills: true, customerCredits: true, supplierCredits: true, payments: true }"},format:Zct},required:["name"],group:"custom_fields",readOnly:!1,searchHint:"create new custom field for transactions",execute:async(e,t)=>mW(e.client,{...t,printOnDocuments:t.printOnDocuments??!1})},{name:"update_custom_field",description:"Update a custom field definition. Omitted fields keep their current values.",params:{resourceId:{type:"string",description:"Custom field resourceId"},name:{type:"string",description:"New field name"},description:{type:"string",description:"New description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents"},appliesTo:{type:"object",description:"Which transaction types: { invoices, bills, customerCredits, supplierCredits, payments }"},format:Zct},required:["resourceId"],group:"custom_fields",readOnly:!1,isDestructive:!0,searchHint:"update custom field name type settings",execute:async(e,t)=>{let{resourceId:r,...n}=t;return AW(e.client,r,n)}},Ur("delete_custom_field","Delete a custom field. Removes it from all future transactions.","custom_fields",(e,t)=>gW(e,t),"permanently delete a custom field definition"),br("list_withholding_codes","List withholding codes (BIR ATCs, PH): code, rate, type, description. A row feeds a bill or supplier credit note line's withholdingTax (EWT) and, by its resourceId, a Withholding Tax Certificate (BIR Form 2307, CWT) allocation. limit max 100.","tax_profiles",(e,t,r,n,i)=>eM(e,{offset:t,limit:r},i),"withholding codes WHT ATC EWT CWT expanded creditable withholding tax BIR 2307",{filters:{countryCode:{type:"string",description:"e.g. PH"},code:{type:"string",description:'Contains match; codes have a space ("WC 158"; "WC158" matches nothing)'},type:{type:"string",enum:["corp","ind","final","wvat"]}}}),Nt({name:"search_tax_profiles",description:"Search tax profiles. Use appliesToSale / appliesToPurchase filters to scope by transaction type.",group:"tax_profiles",fields:rx,defaults:nx,fetcher:jI,searchHint:"find tax profiles GST VAT WHT by name tax type code applicability sale purchase"}),Nt({name:"search_filing_submissions",description:"Search tax return filings (PH BIR 2550Q, SG GST F5): period, due date, tax due, status.",group:"tax_profiles",fields:DT,defaults:RT,fetcher:i8,searchHint:"BIR GST filings"}),ri("get_tax_profile","Get full tax profile details including tax rate, type code, and status.","tax_profiles",(e,t)=>oD(e,t),"get tax profile details rate code"),{name:"update_tax_profile",description:"Update an existing tax profile. Omitted fields keep their current values; status is not updatable.",params:{resourceId:{type:"string",description:"Tax profile resourceId"},name:sge,description:{type:"string"},vatValue:{type:"number",description:"Tax rate % (0-100)"},taxType:{type:"string",description:"Tax type code (list_tax_types)"}},required:["resourceId"],group:"tax_profiles",readOnly:!1,isDestructive:!0,searchHint:"update tax profile name rate details",execute:async(e,t)=>ZP(e.client,t.resourceId,{name:t.name,description:t.description,vatValue:t.vatValue,taxType:t.taxType})},{name:"create_claim_type",description:"Create a claim type (expense category for employee claims). Dedups by name. expenseAccountResourceId is server-required.",params:{name:{type:"string",description:"Claim type name (unique per org)"},expenseAccountResourceId:{type:"string",description:'Expense CoA resourceId, REQUIRED server-side (search_accounts; accountType is a display label e.g. "Operating Expense")'},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Magic OCR classifier defaults (JSON string)"}},required:["name"],group:"claim_types",readOnly:!1,searchHint:"create claim type expense category",execute:async(e,t)=>{let r=t.name,n=await UM(e.client,r);return n?{_guard:"duplicate_skipped",message:`Claim type "${r}" already exists.`,existing:n}:aM(e.client,{name:r,expenseAccountResourceId:t.expenseAccountResourceId,taxProfileResourceId:t.taxProfileResourceId,classifierConfig:t.classifierConfig})}},{name:"update_claim_type",description:"Update a claim type. Omitted fields unchanged; clearFields NULLs optional fields.",params:{resourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"New name"},expenseAccountResourceId:{type:"string",description:"Default expense CoA resourceId"},taxProfileResourceId:{type:"string",description:"Default tax profile resourceId"},classifierConfig:{type:"string",description:"Classifier defaults (JSON string)"},clearFields:{type:"array",items:{type:"string",enum:[...cD]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_types",readOnly:!1,isDestructive:!0,searchHint:"update claim type",execute:async(e,t)=>cM(e.client,t.resourceId,{name:t.name,expenseAccountResourceId:t.expenseAccountResourceId,taxProfileResourceId:t.taxProfileResourceId,classifierConfig:t.classifierConfig,...bg(t.clearFields,cD)})},Nt({name:"search_claim_types",description:"Search claim types.",group:"claim_types",fields:qT,defaults:jT,fetcher:HI,searchHint:"find claim types by name default expense account tax profile"}),br("list_claim_types","List claim types (alphabetical).","claim_types",(e,t,r)=>oM(e,{offset:t,limit:r}),"list claim types"),ri("get_claim_type","Get a claim type incl. nested expense account + tax profile.","claim_types",(e,t)=>sM(e,t),"get claim type details"),Ur("delete_claim_type","Soft-delete a claim type (name becomes reusable).","claim_types",(e,t)=>lM(e,t),"delete claim type"),{name:"create_claim_profile",description:"Create a claim profile (per-employee policy bundle: approver, limits, visible types, balance account). Dedups by name. taxMode EXCLUSIVE is rejected.",params:{name:{type:"string",description:"Profile name (unique per org)"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (free-text vendors always allowed)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (null = no restriction)"},minClaimAmount:{type:"number",description:"Min claim total (<= max)"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap (requires perPeriod)"},perPeriod:{type:"string",enum:[...lD],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Per-employee liability (CURRENT_LIABILITY) CoA resourceId; required for reimbursement conversion"},taxMode:{type:"string",enum:[..._Z],description:"Tax policy (NO_TAX or INCLUSIVE)"}},required:["name"],group:"claim_profiles",readOnly:!1,searchHint:"create claim profile policy approver limits",execute:async(e,t)=>{let r=t.name,n=await $M(e.client,r);return n?{_guard:"duplicate_skipped",message:`Claim profile "${r}" already exists.`,existing:n}:pM(e.client,{name:r,approverUserResourceId:t.approverUserResourceId,visibleClaimTypeIds:t.visibleClaimTypeIds,visibleTaxProfileIds:t.visibleTaxProfileIds,visibleClassifierIds:t.visibleClassifierIds,visibleVendorResourceIds:t.visibleVendorResourceIds,allowedCurrencies:t.allowedCurrencies,minClaimAmount:t.minClaimAmount,maxClaimAmount:t.maxClaimAmount,maxPerPeriodAmount:t.maxPerPeriodAmount,perPeriod:t.perPeriod,employeeBalanceAccountResourceId:t.employeeBalanceAccountResourceId,taxMode:t.taxMode})}},{name:"update_claim_profile",description:"Update a claim profile. Omitted fields unchanged; clearFields NULLs optional fields. Balance account cannot change while an employee has a non-zero balance.",params:{resourceId:{type:"string",description:"Claim profile resourceId"},name:{type:"string",description:"New name"},approverUserResourceId:{type:"string",description:"Default approver user resourceId"},visibleClaimTypeIds:{type:"array",items:{type:"string"},description:"Allowed claim type IDs (replaces)"},visibleTaxProfileIds:{type:"array",items:{type:"string"},description:"Allowed tax profile IDs (replaces)"},visibleClassifierIds:{type:"array",items:{type:"string"},description:"Allowed classifier IDs (replaces)"},visibleVendorResourceIds:{type:"array",items:{type:"string"},description:"Allowed vendor contact IDs (replaces)"},allowedCurrencies:{type:"array",items:{type:"string"},description:"Allowed ISO currency codes (replaces)"},minClaimAmount:{type:"number",description:"Min claim total"},maxClaimAmount:{type:"number",description:"Max claim total"},maxPerPeriodAmount:{type:"number",description:"Per-period spend cap"},perPeriod:{type:"string",enum:[...lD],description:"Per-period window"},employeeBalanceAccountResourceId:{type:"string",description:"Employee balance CoA resourceId"},taxMode:{type:"string",enum:[..._Z],description:"Tax policy (NO_TAX or INCLUSIVE)"},clearFields:{type:"array",items:{type:"string",enum:[...uD]},description:"Optional fields to NULL (clear)"}},required:["resourceId"],group:"claim_profiles",readOnly:!1,isDestructive:!0,searchHint:"update claim profile policy limits",execute:async(e,t)=>hM(e.client,t.resourceId,{name:t.name,approverUserResourceId:t.approverUserResourceId,visibleClaimTypeIds:t.visibleClaimTypeIds,visibleTaxProfileIds:t.visibleTaxProfileIds,visibleClassifierIds:t.visibleClassifierIds,visibleVendorResourceIds:t.visibleVendorResourceIds,allowedCurrencies:t.allowedCurrencies,minClaimAmount:t.minClaimAmount,maxClaimAmount:t.maxClaimAmount,maxPerPeriodAmount:t.maxPerPeriodAmount,perPeriod:t.perPeriod,employeeBalanceAccountResourceId:t.employeeBalanceAccountResourceId,taxMode:t.taxMode,...bg(t.clearFields,uD)})},Nt({name:"search_claim_profiles",description:"Search claim profiles.",group:"claim_profiles",fields:YT,defaults:HT,fetcher:zI,searchHint:"find claim profiles by name approver default limits balance account"}),br("list_claim_profiles","List claim profiles (alphabetical).","claim_profiles",(e,t,r)=>dM(e,{offset:t,limit:r}),"list claim profiles"),ri("get_claim_profile","Get a claim profile incl. nested balance account.","claim_profiles",(e,t)=>fM(e,t),"get claim profile details"),Ur("delete_claim_profile","Soft-delete a claim profile.","claim_profiles",(e,t)=>mM(e,t),"delete claim profile"),{name:"create_posting_rule",description:"Create a posting rule (how approved claims group into journals at conversion). outerAxis + innerAxis + lineDescriptionTemplate required. Dedups by name.",params:{name:{type:"string",description:"Rule name (unique per org)"},outerAxis:{type:"string",enum:[...fD],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...pD],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:'Handlebars line template, e.g. "{employeeName} - {claimType}"'},journalReferenceTemplate:{type:"string",description:"Optional Handlebars journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank (Cash/Bank) account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["name","outerAxis","innerAxis","lineDescriptionTemplate"],group:"posting_rules",readOnly:!1,searchHint:"create posting rule claim conversion grouping",execute:async(e,t)=>{let r=t.name,n=await qM(e.client,r);return n?{_guard:"duplicate_skipped",message:`Posting rule "${r}" already exists.`,existing:n}:yM(e.client,{name:r,outerAxis:t.outerAxis,innerAxis:t.innerAxis,lineDescriptionTemplate:t.lineDescriptionTemplate,journalReferenceTemplate:t.journalReferenceTemplate,defaultBankAccountResourceId:t.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:t.defaultIncludeReimbursementPayout,isDefault:t.isDefault})}},{name:"update_posting_rule",description:"Update a posting rule. Omitted fields unchanged.",params:{resourceId:{type:"string",description:"Posting rule resourceId"},name:{type:"string",description:"New name"},outerAxis:{type:"string",enum:[...fD],description:"Outer grouping axis"},innerAxis:{type:"string",enum:[...pD],description:"Inner line-aggregation axis"},lineDescriptionTemplate:{type:"string",description:"Handlebars line template"},journalReferenceTemplate:{type:"string",description:"Journal-header reference template"},defaultBankAccountResourceId:{type:"string",description:"Default reimbursement bank account resourceId"},defaultIncludeReimbursementPayout:{type:"boolean",description:"Create reimbursement DCE by default"},isDefault:{type:"boolean",description:"Make org default rule"}},required:["resourceId"],group:"posting_rules",readOnly:!1,isDestructive:!0,searchHint:"update posting rule",execute:async(e,t)=>EM(e.client,t.resourceId,{name:t.name,outerAxis:t.outerAxis,innerAxis:t.innerAxis,lineDescriptionTemplate:t.lineDescriptionTemplate,journalReferenceTemplate:t.journalReferenceTemplate,defaultBankAccountResourceId:t.defaultBankAccountResourceId,defaultIncludeReimbursementPayout:t.defaultIncludeReimbursementPayout,isDefault:t.isDefault})},Nt({name:"search_posting_rules",description:"Search posting rules.",group:"posting_rules",fields:zT,defaults:JT,fetcher:JI,searchHint:"find posting rules by name axis default bank reimbursement"}),br("list_posting_rules","List posting rules (alphabetical).","posting_rules",(e,t,r)=>AM(e,{offset:t,limit:r}),"list posting rules"),ri("get_posting_rule","Get a posting rule.","posting_rules",(e,t)=>gM(e,t),"get posting rule details"),Ur("delete_posting_rule","Delete a posting rule. The org default cannot be deleted while default (set another default first).","posting_rules",(e,t)=>bM(e,t),"delete posting rule"),Nt({name:"search_claims",description:'Search/list employee-expense claims. Status: DRAFT|SUBMITTED|APPROVED|CONVERTED|REJECTED|CANCELLED (CONVERTED = "Processed"). Claims are born via create_claim, attachment, or conversion (no bare list; use search).',group:"claims",fields:PT,defaults:MT,fetcher:r2,searchHint:"find employee expense claims by status employee contact reference date amount"}),ri("get_claim","Get a claim incl. line items, employee, amounts, status.","claims",(e,t)=>LT(e,t),"get claim details line items"),{name:"create_claim",description:"Create an employee-expense claim directly (bare create, no attachment). Vendor is EITHER contactResourceId OR vendorName, never both. saveAsDraft defaults to true (lands DRAFT with relaxed line validation); set false to validate + submit in one call (lands SUBMITTED). reference is REQUIRED when submitting (saveAsDraft=false): omitting it returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT; a DRAFT saves without one.",params:{valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},saveAsDraft:{type:"boolean",description:"true (default) creates DRAFT; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId the claim is filed for"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},reference:{type:"string",description:"User reference"},autoReference:uu,currencySymbol:{type:"string",description:"Currency symbol override"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:{type:"array",items:{type:"string"},description:"Header-level tags"},internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId (defaults to org default)"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Tn,claimItems:llt},required:["valueDate","currencyCode"],group:"claims",readOnly:!1,searchHint:"create new employee expense claim draft vendor employee line items submit",execute:async(e,t)=>n2(e.client,{valueDate:t.valueDate,currencyCode:t.currencyCode,saveAsDraft:t.saveAsDraft,employeeResourceId:t.employeeResourceId,contactResourceId:t.contactResourceId,vendorName:t.vendorName,reference:await bU(e.client,"CLAIM",t.reference,t.autoReference),currencySymbol:t.currencySymbol,taxInclusion:t.taxInclusion,tags:t.tags,internalNotes:t.internalNotes,claimProfileResourceId:t.claimProfileResourceId,approverUserResourceId:t.approverUserResourceId,customFields:t.customFields,claimItems:t.claimItems})},{name:"update_claim",description:"Update a DRAFT claim (partial: omitted fields unchanged). claimItems non-empty REPLACES all lines, [] clears. Set saveAsDraft=false to validate + submit in one call: reference is REQUIRED at submit (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT); a DRAFT save needs none. Only DRAFT claims are editable.",params:{resourceId:{type:"string",description:"Claim resourceId"},saveAsDraft:{type:"boolean",description:"true (default) keeps editing; false validates + submits"},employeeResourceId:{type:"string",description:"Employee resourceId"},contactResourceId:{type:"string",description:"Vendor contact resourceId (mutually exclusive with vendorName)"},vendorName:{type:"string",description:"Free-text vendor name (mutually exclusive with contactResourceId)"},valueDate:{type:"string",description:"Business-transaction date (YYYY-MM-DD)"},reference:{type:"string",description:"User reference"},currencyCode:{type:"string",description:"Claim currency (ISO 4217)"},taxInclusion:{type:"boolean",description:"Line amounts are tax-inclusive"},tags:jo,internalNotes:{type:"string",description:"Internal notes (max 1000)"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},approverUserResourceId:{type:"string",description:"Approver user resourceId"},customFields:Tn,claimItems:llt},required:["resourceId"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"edit draft claim line items employee reference submit",execute:async(e,t)=>{let r=t.resourceId,n=Ui(t.tags),i=n&&await Yo("claim",r,()=>LT(e.client,r));return i2(e.client,r,{saveAsDraft:t.saveAsDraft,employeeResourceId:t.employeeResourceId,contactResourceId:t.contactResourceId,vendorName:t.vendorName,valueDate:t.valueDate,reference:t.reference,currencyCode:t.currencyCode,taxInclusion:t.taxInclusion,tags:n&&Ki(i?.tags,n),internalNotes:t.internalNotes,claimProfileResourceId:t.claimProfileResourceId,approverUserResourceId:t.approverUserResourceId,customFields:t.customFields,claimItems:t.claimItems})}},Ur("delete_claim","Delete a claim. Only DRAFT / REJECTED / CANCELLED claims are deletable (else 422).","claims",(e,t)=>o2(e,t),"delete remove claim record"),{name:"delete_claim_attachment",description:"Remove one attachment (receipt) from a claim. Returns the updated claim.",params:{resourceId:{type:"string",description:"Claim resourceId"},attachmentResourceId:{type:"string",description:"Attachment resourceId"}},required:["resourceId","attachmentResourceId"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"remove delete claim attachment receipt",execute:async(e,t)=>s2(e.client,t.resourceId,t.attachmentResourceId)},lge("submit_claim","Submit a DRAFT claim for approval (DRAFT \u2192 SUBMITTED). Server enforces the transition. The claim must carry a reference; a referenceless DRAFT returns 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (set it via update_claim first).","claims",(e,t)=>a2(e,t),{destructive:!0,searchHint:"submit draft claim for approval"}),lge("approve_claim","Approve a SUBMITTED claim (SUBMITTED \u2192 APPROVED). Approved claims become convertible to journals.","claims",(e,t)=>c2(e,t),{destructive:!0,searchHint:"approve submitted claim"}),{name:"reject_claim",description:"Reject a SUBMITTED/APPROVED claim with a reason (\u2192 REJECTED).",params:{resourceId:{type:"string",description:"Claim resourceId"},rejectionReason:{type:"string",description:"Rejection reason (1-1000 chars)"}},required:["resourceId","rejectionReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"reject claim with reason",execute:async(e,t)=>l2(e.client,t.resourceId,t.rejectionReason)},{name:"cancel_claim",description:"Cancel a DRAFT/SUBMITTED claim with a reason (\u2192 CANCELLED).",params:{resourceId:{type:"string",description:"Claim resourceId"},cancellationReason:{type:"string",description:"Cancellation reason (1-1000 chars)"}},required:["resourceId","cancellationReason"],group:"claims",readOnly:!1,isDestructive:!0,searchHint:"cancel claim with reason",execute:async(e,t)=>u2(e.client,t.resourceId,t.cancellationReason)},lge("unpost_claim","Unpost a CONVERTED claim: voids its journal, back to APPROVED. Re-unpost: 200 no-op. Aggregated claims unpost together. Ignores payouts (employee balance can go negative).","claims",(e,t)=>d2(e,t),{destructive:!0,searchHint:"unpost reverse converted claim conversion"}),{name:"bulk_submit_claims",description:`Bulk-submit DRAFT claims (ASYNC). Returns the final job if it finished, else a job handle {jobId,...} to poll with search_background_jobs by jobId for per-item results. ${rs} Max 500 ids. Each claim must have a reference; referenceless claims fail per-item with CLAIM_REFERENCE_REQUIRED_AT_SUBMIT (check the job result).`,params:{resourceIds:_O},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk submit many claims async job",backgroundJob:Mn("Submit","claim","claims","resourceIds"),execute:async(e,t)=>f2(e.client,t.resourceIds)},{name:"bulk_approve_claims",description:`Bulk-approve SUBMITTED claims (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk approve many claims async job",backgroundJob:Mn("Approve","claim","claims","resourceIds"),execute:async(e,t)=>p2(e.client,t.resourceIds)},{name:"bulk_reject_claims",description:`Bulk-reject claims with one shared reason (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O,rejectionReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","rejectionReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk reject many claims async job reason",backgroundJob:Mn("Reject","claim","claims","resourceIds"),execute:async(e,t)=>m2(e.client,t.resourceIds,t.rejectionReason)},{name:"bulk_cancel_claims",description:`Bulk-cancel claims with one shared reason (ASYNC). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O,cancellationReason:{type:"string",description:"Reason applied to the whole batch (1-1000 chars)"}},required:["resourceIds","cancellationReason"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk cancel many claims async job reason",backgroundJob:Mn("Cancel","claim","claims","resourceIds"),execute:async(e,t)=>A2(e.client,t.resourceIds,t.cancellationReason)},{name:"bulk_delete_claims",description:`Bulk-delete claims (ASYNC; only DRAFT/REJECTED/CANCELLED are deletable). Returns the final job if it finished, else a job handle to poll with search_background_jobs by jobId. ${rs} Max 500 ids.`,params:{resourceIds:_O},required:["resourceIds"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk delete many claims async job",backgroundJob:Mn("Delete","claim","claims","resourceIds"),execute:async(e,t)=>h2(e.client,t.resourceIds)},{name:"get_claim_tracking_tags",description:"List the tracking-tag values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim tracking tags picker",execute:async e=>g2(e.client)},{name:"get_claim_custom_field_values",description:"List the custom-field values available across claims (picker; returns a bare array).",params:{},required:[],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"list claim custom field values picker",execute:async e=>y2(e.client)},{name:"preview_claims_conversion",description:"Preview the journals an APPROVED claim batch would produce at conversion, no write. Returns expenseSubTotal, previewJournals, and reimbursement DCE counts; non-APPROVED claims come back under erroredClaims (check it is empty before converting). Needs a default posting rule or an explicit postingRuleResourceId.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},payoutFlow:{type:"string",enum:[...eO],description:"POST (journals only) or POST_AND_RECORD (+ books-only reimbursement DCE)"},includeReimbursementPayout:{type:"boolean",description:"Include per-employee reimbursement DCE lines"},bankAccountResourceId:{type:"string",description:"Reimbursement bank account for preview validation"}},required:["claimResourceIds"],group:"claim_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview claim conversion journals before posting",execute:async(e,t)=>e8(e.client,{claimResourceIds:t.claimResourceIds,postingRuleResourceId:t.postingRuleResourceId,payoutFlow:t.payoutFlow,includeReimbursementPayout:t.includeReimbursementPayout,bankAccountResourceId:t.bankAccountResourceId})},{name:"convert_claims_to_journal",description:"Convert an APPROVED claim batch into journals (atomic write). valueDate (YYYY-MM-DD) required. Preview first and confirm erroredClaims is empty. idempotencyKey is auto-generated for safe retries (pass your own to dedup across calls). includeReimbursementPayout adds a books-only reimbursement DCE; real-money disburse is intentionally not exposed.",params:{claimResourceIds:{type:"array",items:{type:"string"},description:"APPROVED claim resourceIds (1-500)"},valueDate:{type:"string",description:"Journal value date (YYYY-MM-DD)"},postingRuleResourceId:{type:"string",description:"Posting rule resourceId (null \u2192 org default rule)"},includeReimbursementPayout:{type:"boolean",description:"Create books-only reimbursement DCEs"},bankAccountResourceIdOverride:{type:"string",description:"Override the rule default reimbursement bank account"},contactResourceId:{type:"string",description:"Clearing contact for the reimbursement DCE cash-out"},idempotencyKey:{type:"string",description:"Optional retry-dedup token (must not start with CONV: / CONV-); auto-generated if omitted"}},required:["claimResourceIds","valueDate"],group:"claim_processing",readOnly:!1,isDestructive:!0,searchHint:"convert post approved claims to journal entries",execute:async(e,t)=>t8(e.client,{claimResourceIds:t.claimResourceIds,valueDate:t.valueDate,postingRuleResourceId:t.postingRuleResourceId,includeReimbursementPayout:t.includeReimbursementPayout,bankAccountResourceIdOverride:t.bankAccountResourceIdOverride,contactResourceId:t.contactResourceId,idempotencyKey:t.idempotencyKey||tSr()})},{name:"record_employee_payout",description:"Record a books-only employee payout (reimbursement or advance): a DCE, no real-money transfer. amount, paymentAccountResourceId and valueDate are required; reference auto-generated if omitted.",params:{employeeResourceId:{type:"string",description:"Employee resourceId"},amount:{type:"number",description:"Payout amount (> 0)"},paymentAccountResourceId:{type:"string",description:"Bank/cash account the DCE credits"},valueDate:{type:"string",description:"Value date (YYYY-MM-DD)"},payoutFor:{type:"string",enum:[...dat],description:"Classification (null \u2192 ADVANCE)"},currencyCode:{type:"string",description:"Settle currency (ISO 4217; omit \u2192 payment account currency)"},reference:{type:"string",description:"Payout reference (auto-generated if omitted)"},description:{type:"string",description:"Line description on the DCE"},internalNotes:{type:"string",description:"Internal notes"}},required:["employeeResourceId","amount","paymentAccountResourceId","valueDate"],group:"claim_processing",readOnly:!1,searchHint:"record employee reimbursement advance payout books-only DCE",execute:async(e,t)=>r8(e.client,{employeeResourceId:t.employeeResourceId,amount:t.amount,paymentAccountResourceId:t.paymentAccountResourceId,valueDate:t.valueDate,payoutFor:t.payoutFor,currencyCode:t.currencyCode,reference:t.reference||Lo("EP"),description:t.description,internalNotes:t.internalNotes})},Nt({name:"search_employee_payouts",description:"Search recorded employee payouts (reimbursements + advances).",group:"claim_processing",fields:UT,defaults:$T,fetcher:n8,searchHint:"find employee payouts reimbursements advances by employee reference status type"}),{name:"add_employee",description:"Create an employee (expense-claim member). claimProfileResourceId is REQUIRED (carries the employee balance account; the org default is NOT auto-applied). userResourceId is optional: omit for an offline employee with no login. Dedups by email.",params:{name:{type:"string",description:"Employee display name"},userResourceId:{type:"string",description:"Login user's resourceId to link: the userResourceId field from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND). Optional"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId, REQUIRED (carries the employee balance account; org default NOT auto-applied \u2192 EMPLOYEE_CLAIM_PROFILE_REQUIRED). search_claim_profiles"},email:{type:"string",description:"Work email (per-org unique)"},phone:{type:"string",description:"Phone (per-org unique)"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},active:{type:"boolean",description:"Active flag (default true)"},employmentType:{type:"string",enum:[...Ig],description:"Employment classification"}},required:["name","claimProfileResourceId"],group:"employees",readOnly:!1,searchHint:"create add employee claim member bind user",execute:async(e,t)=>{let r=t.email;if(r){let n=await jM(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Employee with email "${r}" already exists.`,existing:n}}return DM(e.client,{name:t.name,userResourceId:t.userResourceId,claimProfileResourceId:t.claimProfileResourceId,email:r,phone:t.phone,managerEmployeeResourceId:t.managerEmployeeResourceId,active:t.active,employmentType:t.employmentType})}},{name:"update_employee",description:"Update an employee (partial; omitted or null = no change). Clear only via clearFields (userResourceId = unlink). To ARCHIVE, set active=false (reversible, prefer over delete_employee).",params:{resourceId:{type:"string",description:"Employee resourceId"},name:{type:"string",description:"New name"},email:{type:"string",description:"Work email"},phone:{type:"string",description:"Phone"},managerEmployeeResourceId:{type:"string",description:"Manager employee resourceId"},claimProfileResourceId:{type:"string",description:"Claim profile resourceId"},active:{type:"boolean",description:"Active flag, set false to archive"},employmentType:{type:"string",enum:[...Ig],description:"Employment classification"},userResourceId:{type:"string",description:"Login user to link/relink (search_org_users userResourceId)"},clearFields:{type:"array",items:{type:"string",enum:[...TZ]},description:"Fields to clear"}},required:["resourceId"],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"update edit archive employee active claim profile",execute:async(e,t)=>RM(e.client,t.resourceId,{name:t.name,email:t.email,phone:t.phone,managerEmployeeResourceId:t.managerEmployeeResourceId,claimProfileResourceId:t.claimProfileResourceId,active:t.active,employmentType:t.employmentType,userResourceId:t.userResourceId,clearFields:t.clearFields})},Nt({name:"search_employees",description:"Search employees by name, email, phone, manager, claim profile, active, currency.",group:"employees",fields:GT,defaults:VT,fetcher:VI,searchHint:"find employees claim members by name email manager profile active"}),Nt({name:"search_employee_balances",description:"Search the employee-balance directory (per-currency reimbursement balances owed).",group:"employees",fields:WT,defaults:KT,fetcher:vM,searchHint:"employee reimbursement balances owed by currency employment type"}),ri("get_employee","Get an employee incl. claim profile + user binding.","employees",(e,t)=>SM(e,t),"get employee details binding balance"),Ur("delete_employee","Delete an employee (server validates they are settled). Prefer update_employee active=false to archive reversibly.","employees",(e,t)=>TM(e,t),"delete remove employee"),{name:"bind_employee_user",description:"Bind a login user to an OFFLINE employee (no user bound yet, e.g. imported without a binding email). Refused once bound: relink or unlink via update_employee.",params:{resourceId:{type:"string",description:"Employee resourceId"},userResourceId:{type:"string",description:"Login user's resourceId: the userResourceId FIELD from search_org_users, NOT the org-user record id (else EMPLOYEE_USER_NOT_FOUND)"}},required:["resourceId","userResourceId"],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bind link login user to employee",execute:async(e,t)=>xM(e.client,t.resourceId,t.userResourceId)},{name:"preprocess_employees_file",description:"Preprocess an uploaded employee import sheet (CSV/XLSX); returns a parsed row preview to review before import_employees. Provide the sheet fileUrl.",params:{fileUrl:{type:"string",description:"URL of the uploaded employee sheet"},fileName:{type:"string",description:"Display file name"},fileType:{type:"string",enum:["CSV","EML","HEIC","JPEG","JPG","PDF","PNG","TEXT","XLS","XLSX"],description:"File type (use CSV / XLS / XLSX for employee sheets)"}},required:["fileUrl"],group:"employees",readOnly:!0,fetchesCallerUrl:!0,isConcurrencySafe:!0,searchHint:"preprocess preview employee import sheet csv xlsx",execute:async(e,t)=>kM(e.client,{fileUrl:t.fileUrl,fileName:t.fileName,fileType:t.fileType})},{name:"import_employees",description:`Bulk create/update/delete employees (max 100 rows per array). Rows validate synchronously (422 row errors), then an async job queues: the result is the final job if it finished, else poll search_background_jobs by jobId. ${rs} Create rows need name + claimProfileResourceId (userResourceId optional).`,params:{create:{type:"array",description:"Create rows",items:{type:"object",properties:{name:{type:"string"},email:{type:"string"},userResourceId:{type:"string"},claimProfileResourceId:{type:"string"},employmentType:{type:"string",enum:[...Ig]},managerEmployeeResourceId:{type:"string"},active:{type:"boolean"}},required:["name"]}},update:{type:"array",description:"Update rows",items:{type:"object",properties:{employeeResourceId:{type:"string"},name:{type:"string"},email:{type:"string"},employmentType:{type:"string",enum:[...Ig]},active:{type:"boolean"}},required:["employeeResourceId"]}},delete:{type:"array",description:"Delete rows",items:{type:"object",properties:{employeeResourceId:{type:"string"}},required:["employeeResourceId"]}}},required:[],group:"employees",readOnly:!1,isDestructive:!0,searchHint:"bulk import employees create update delete sheet async",backgroundJob:Mn("Import","employee change","employee changes","create","update","delete"),execute:async(e,t)=>NM(e.client,{create:t.create,update:t.update,delete:t.delete})},br("list_inventory_items","List inventory-tracked items with stock details, COGS accounts, and purchase/sale accounts.","inventory",(e,t,r)=>cW(e,{limit:r,offset:t}),"list inventory items stock levels quantities"),{name:"get_inventory_balance",description:"Get current inventory balance for a specific item: quantity on hand, average cost, base unit.",params:{itemResourceId:{type:"string",description:"Item resourceId"}},required:["itemResourceId"],group:"inventory",readOnly:!0,searchHint:"get inventory balance stock level for item",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>uW(e.client,t.itemResourceId)},{name:"list_inventory_balances",description:"List stock on hand, average cost and value per inventory item. One item: get_inventory_balance.",params:{status:{type:"string",enum:[...dW],description:"Default ALL"},...FO},required:[],group:"inventory",readOnly:!0,searchHint:"stock on hand all items",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>{let{limit:r,offset:n}=QO(t),i=t.status??"ALL";return ch((o,s)=>fW(e.client,i,{limit:s,offset:o}),r,n,100)}},{name:"create_inventory_item",description:"Create a new inventory-tracked item. Requires itemCode, name, unit, costingMethod (FIXED or WAC) and three account links. Use --input for full JSON body.",params:{itemCode:{type:"string",description:"Unique item code (SKU)"},name:{type:"string",description:"Item name"},unit:{type:"string",description:'Unit of measure, e.g. "pcs"'},costingMethod:{type:"string",enum:["FIXED","WAC"],description:"Costing method: FIXED or WAC"},cogsResourceId:{type:"string",description:"COGS account resourceId (Direct Costs type)"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId (Inventory type)"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},blockInsufficientDeductions:{type:"boolean",description:"Block transactions when insufficient stock (default: false)"}},required:["itemCode","name","unit","costingMethod","cogsResourceId","purchaseAccountResourceId","saleAccountResourceId"],group:"inventory",readOnly:!1,searchHint:"create new inventory tracked stock item",execute:async(e,t)=>lW(e.client,{itemCode:t.itemCode,name:t.name,unit:t.unit,costingMethod:t.costingMethod,cogsResourceId:t.cogsResourceId,purchaseAccountResourceId:t.purchaseAccountResourceId,saleAccountResourceId:t.saleAccountResourceId,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:t.blockInsufficientDeductions??!1})},Ur("delete_contact","Delete a contact. Cannot delete contacts with existing transactions.","contacts",(e,t)=>vP(e,t),"permanently delete a customer supplier contact"),Ur("delete_account","Delete a chart of accounts entry. Cannot delete accounts with existing transactions.","accounts",(e,t)=>HP(e,t),"permanently delete a chart of accounts entry"),ri("get_cash_transfer","Fetch a cash transfer by cashflow-transaction resourceId (search_cashflow_transactions) or the parentEntityResourceId create returns.","cash_transfers",(e,t)=>iV(e,t),"get cash transfer details between accounts"),TO("download_credit_note_pdf","customer credit note","customer_credit_notes",(e,t)=>cj(e,t)),{name:"get_transaction_summary",description:`Get a complete summary of any transaction: fetches the transaction, its attachments, and payment history in one call.
|
|
806
806
|
Works for invoices, bills, customer credit notes, supplier credit notes, and journals. Invoices and bills carry payments, credit notes refunds, journals neither. A failed leg omits its keys and is named in 'partialFailures'.`,params:{transactionType:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note","journal"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["transactionType","resourceId"],group:"search",readOnly:!0,searchHint:"transaction summary attachments payments refunds",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=t.resourceId,n=n3[t.transactionType]??n3.journal,[i,o,s]=await Promise.allSettled([n.get(e.client,r),gi(e.client,n.attachType,r),n.settlements?n.settlements(e.client,r):Promise.resolve(void 0)]);if(i.status==="rejected")throw i.reason;let a=p=>{let h=p.reason instanceof Error?p.reason.message:typeof p.reason=="string"?p.reason:(()=>{try{return JSON.stringify(p.reason)??"unknown error"}catch{return"unknown error"}})();return h.length>300?`${h.slice(0,297)}...`:h},c=[];o.status==="rejected"&&c.push(`attachments: ${a(o)}`),s.status==="rejected"&&c.push(`${n.settlementKey}: ${a(s)}`);let u=p=>Array.isArray(p)?p:Array.isArray(p?.data)?p.data:void 0,d=o.status==="fulfilled"?u(o.value):void 0,f=s.status==="fulfilled"?u(s.value):void 0;return{...c.length?{partialFailures:c}:{},transaction:i.value.data,...d?{attachments:d,attachmentCount:d.length}:{},...f?{[n.settlementKey]:f,[n.settlementCountKey]:f.length}:{}}}},{name:"bulk_finalize_drafts",description:"Finalize multiple draft transactions in one call. Attempts finalization for each item and returns per-item pass/fail results. Supports invoices, bills, and credit notes.",params:{items:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["type","resourceId"]},description:"Array of {type, resourceId} to finalize"}},required:["items"],group:"drafts",readOnly:!1,searchHint:"bulk finalize approve multiple draft transactions",isDestructive:!0,execute:async(e,t)=>{let r=t.items,n=[];for(let i of r){let o=mge.includes(i.type)?typeof i.resourceId!="string"||i.resourceId.trim()===""?"resourceId is required":void 0:`type must be one of ${mge.join(", ")}`;if(o){let s="btResourceId"in i||"btType"in i?" A validate_drafts result names them btType and btResourceId: map btType SALE to invoice, PURCHASE to bill, SALE_CREDIT_NOTE to customer_credit_note, PURCHASE_CREDIT_NOTE to supplier_credit_note, and btResourceId to resourceId.":"";n.push({...i,success:!1,error:`${o}.${s}`});continue}try{let s=await xO(e.client,i.type,i.resourceId,{});i.type==="invoice"?await Ex(e.client,i.resourceId,s):i.type==="bill"?await GS(e.client,i.resourceId,s):i.type==="customer_credit_note"?await jx(e.client,i.resourceId,s):i.type==="supplier_credit_note"&&await Vx(e.client,i.resourceId,s),n.push({...i,success:!0})}catch(s){n.push({...i,success:!1,error:s instanceof Error?s.message:String(s)})}}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_invite_org_users",description:"Invite multiple users to the organization in one call. Accepts an array of user objects. Each user follows the same contract as invite_org_user. Returns per-user pass/fail results.",params:{users:{type:"array",items:{type:"object",properties:{email:{type:"string",description:"User email"},firstName:{type:"string",description:"First name"},lastName:{type:"string",description:"Last name"},userType:{type:"string",enum:[...Bg],description:"ADMIN = full access (moduleRoles ignored). CUSTOM_USER = per-module access via moduleRoles."},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",enum:[...uC]},roleCode:{type:"string",enum:[...Ng]}},required:["moduleName","roleCode"]},description:"Use when userType is CUSTOM_USER; ignored for ADMIN."}},required:["email","firstName","lastName","userType"]},description:"Array of users to invite"}},required:["users"],group:"org_users",readOnly:!1,openWorld:!0,searchHint:"bulk invite multiple users to organization",execute:async(e,t)=>{let r=t.users,n=[];for(let i of r)try{ff({userType:i.userType,moduleRoles:i.moduleRoles});let o=await ev(e.client,i);n.push({email:i.email,success:!0,resourceId:o.data?.resourceId})}catch(o){n.push({email:i.email,success:!1,error:o instanceof Error?o.message:String(o)})}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_create_contacts",description:`Create multiple contacts in one call. Deduplicates against existing contacts (exact name match).
|
|
807
807
|
Returns per-contact result: created, skipped (duplicate), or failed.`,params:{contacts:{type:"array",items:{type:"object",properties:{billingName:{type:"string",description:"Official billing name"},name:{type:"string",description:"Display name"},email:{type:"string",description:"Primary email"},customer:{type:"boolean",description:"Is a customer"},supplier:{type:"boolean",description:"Is a supplier"}},required:["billingName"]},description:"Array of contacts to create"},skipDuplicates:{type:"boolean",description:"Skip contacts that match existing names (default true)"}},required:["contacts"],group:"contacts",readOnly:!1,searchHint:"bulk create multiple customer supplier contacts",execute:async(e,t)=>{let r=t.contacts,n=t.skipDuplicates??!0,i=[];for(let o of r)try{if(n){let a=await bD(e.client,o.name??o.billingName);if(a){i.push({billingName:o.billingName,status:"skipped",resourceId:a.resourceId});continue}}let s=await NI(e.client,{billingName:o.billingName,name:o.name??o.billingName,emails:o.email?[o.email]:void 0,customer:o.customer??!0,supplier:o.supplier??!1});i.push({billingName:o.billingName,status:"created",resourceId:s.data.resourceId})}catch(s){i.push({billingName:o.billingName,status:"failed",error:s instanceof Error?s.message:String(s)})}return{total:r.length,created:i.filter(o=>o.status==="created").length,skipped:i.filter(o=>o.status==="skipped").length,failed:i.filter(o=>o.status==="failed").length,results:i}}},...$Sr,{name:"quick_fix_transactions",description:`One record, or other fields on many records of one type. Contact/date/capsule/tags on several: preview_ledger_find_fix.
|
|
808
808
|
|