jaz-clio 9.8.2 → 9.8.4
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/api/references/endpoints.md +2 -2
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/cli/references/command-catalog.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 +3 -3
- package/package.json +1 -1
package/cli.mjs
CHANGED
|
@@ -659,7 +659,7 @@ actual: `+e._bytesWritten),OV.prototype._finish.call(e)}});var fge=b((Vsn,Sat)=>
|
|
|
659
659
|
Unsupported type: `+e.type,"ENOTSUP");e._finish()})};sl.prototype._stat=function(e){var t=this,r=t.props,n=r.follow?"stat":"lstat",i=t._proxy||t;e?o(null,e):ol[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 pge(t);t._old=a;var c=Tat(a);if(c!==t.type||t.type==="File"&&a.nlink>1)return r0r(t._path,function(u){if(u)return t.error(u);t._old=null,pge(t)});pge(t)}};function pge(e){n0r(EB.dirname(e._path),sl.dirmode,function(t,r){return t?e.error(t):(e._madeDir=r,e._create())})}function kat(e,t,r,n,i){var o=t.mode,s=t.follow||e.type!=="SymbolicLink"?"chmod":"lchmod";if(!ol[s]||typeof o!="number")return i();var a=r.mode&parseInt("0777",8);if(o=o&parseInt("0777",8),o===a)return i();ol[s](n,o,i)}function Nat(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(!ol[o])return i();typeof t.uid!="number"&&(t.uid=r.uid),typeof t.gid!="number"&&(t.gid=r.gid),ol[o](n,t.uid,t.gid,i)}function Oat(e,t,r,n,i){if(!ol.utimes||process.platform==="win32")return i();var o=t.follow||e.type!=="SymbolicLink"?"utimes":"lutimes";if(o==="lutimes"&&!ol[o]&&(o="utimes"),!ol[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),Dat(c)||(c=new Date(c)),Dat(u)||(c=new Date(u)),c.getTime()===s.getTime()&&u.getTime()===a.getTime())return i();ol[o](n,c,u,i)}sl.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";ol[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,kat(e,e.props,a,e._path,s("chmod")),Nat(e,e.props,a,e._path,s("chown")),Oat(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)Bat(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 Bat(e,t,r){var n=e._madeDir,i=EB.dirname(t);c0r(e,i,function(o){if(o)return r(o);if(i===n)return r();Bat(e,i,r)})}function c0r(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;ol.stat(t,function(a,c){if(a)return r(o=a);kat(e,n,c,t,s),Nat(e,n,c,t,s),Oat(e,n,c,t,s)});function s(a){if(!o){if(a)return r(o=a);if(--i===0)return r()}}}sl.prototype.pipe=function(){this.error("Can't pipe from writable stream")};sl.prototype.add=function(){this.error("Can't add to non-Directory type")};sl.prototype.write=function(){return!0};function l0r(e){return Object.prototype.toString.call(e)}function Dat(e){return typeof e=="object"&&l0r(e)==="[object Date]"}});var hge=b(qr=>{qr.Abstract=SV();qr.Reader=TE();qr.Writer=uv();qr.File={Reader:KAe(),Writer:uge()};qr.Dir={Reader:WAe(),Writer:cge()};qr.Link={Reader:GAe(),Writer:lge()};qr.Proxy={Reader:ZAe(),Writer:fge()};qr.Reader.Dir=qr.DirReader=qr.Dir.Reader;qr.Reader.File=qr.FileReader=qr.File.Reader;qr.Reader.Link=qr.LinkReader=qr.Link.Reader;qr.Reader.Proxy=qr.ProxyReader=qr.Proxy.Reader;qr.Writer.Dir=qr.DirWriter=qr.Dir.Writer;qr.Writer.File=qr.FileWriter=qr.File.Writer;qr.Writer.Link=qr.LinkWriter=qr.Link.Writer;qr.Writer.Proxy=qr.ProxyWriter=qr.Proxy.Writer;qr.collect=kV()});var Pat=b((Xsn,Lat)=>{Lat.exports=m0r;var u0r=vV(),d0r=hge().Writer,mge=z("path"),f0r=z("stream"),p0r=HAe(),h0r=oA();function m0r(e){e.path=mge.resolve(mge.normalize(e.path));var t=new u0r(e),r=new f0r.Writable({objectMode:!0});r._write=function(i,o,s){if(i.type=="Directory")return s();var a=mge.join(e.path,i.path);if(a.indexOf(e.path)!=0)return s();let c=e.getWriter?e.getWriter({path:a}):d0r({path:a});i.pipe(c).on("error",s).on("close",s)};var n=p0r(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 h0r(function(i,o){n.on("close",i),n.on("error",o)})},n}});var Qat=b((Zsn,BV)=>{var Co=(function(e){"use strict";var t=1e7,r=7,n=9007199254740992,i=p(n),o="0123456789abcdefghijklmnopqrstuvwxyz",s=typeof BigInt=="function";function a(v,k,Q,H){return typeof v>"u"?a[0]:typeof k<"u"?+k==10&&!Q?le(v):Ke(v,k,Q,H):le(v)}function c(v,k){this.value=v,this.sign=k,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 k=v.length;if(k<4&&V(v,i)<0)switch(k){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 k=v.length;v[--k]===0;);v.length=k+1}function A(v){for(var k=new Array(v),Q=-1;++Q<v;)k[Q]=0;return k}function g(v){return v>0?Math.floor(v):Math.ceil(v)}function y(v,k){var Q=v.length,H=k.length,ie=new Array(Q),re=0,ae=t,de,ye;for(ye=0;ye<H;ye++)de=v[ye]+k[ye]+re,re=de>=ae?1:0,ie[ye]=de-re*ae;for(;ye<Q;)de=v[ye]+re,re=de===ae?1:0,ie[ye++]=de-re*ae;return re>0&&ie.push(re),ie}function I(v,k){return v.length>=k.length?y(v,k):y(k,v)}function E(v,k){var Q=v.length,H=new Array(Q),ie=t,re,ae;for(ae=0;ae<Q;ae++)re=v[ae]-ie+k,k=Math.floor(re/ie),H[ae]=re-k*ie,k+=1;for(;k>0;)H[ae++]=k%ie,k=Math.floor(k/ie);return H}c.prototype.add=function(v){var k=le(v);if(this.sign!==k.sign)return this.subtract(k.negate());var Q=this.value,H=k.value;return k.isSmall?new c(E(Q,Math.abs(H)),this.sign):new c(I(Q,H),this.sign)},c.prototype.plus=c.prototype.add,u.prototype.add=function(v){var k=le(v),Q=this.value;if(Q<0!==k.sign)return this.subtract(k.negate());var H=k.value;if(k.isSmall){if(f(Q+H))return new u(Q+H);H=p(Math.abs(H))}return new c(E(H,Math.abs(Q)),Q<0)},u.prototype.plus=u.prototype.add,d.prototype.add=function(v){return new d(this.value+le(v).value)},d.prototype.plus=d.prototype.add;function C(v,k){var Q=v.length,H=k.length,ie=new Array(Q),re=0,ae=t,de,ye;for(de=0;de<H;de++)ye=v[de]-re-k[de],ye<0?(ye+=ae,re=1):re=0,ie[de]=ye;for(de=H;de<Q;de++){if(ye=v[de]-re,ye<0)ye+=ae;else{ie[de++]=ye;break}ie[de]=ye}for(;de<Q;de++)ie[de]=v[de];return m(ie),ie}function w(v,k,Q){var H;return V(v,k)>=0?H=C(v,k):(H=C(k,v),Q=!Q),H=h(H),typeof H=="number"?(Q&&(H=-H),new u(H)):new c(H,Q)}function T(v,k,Q){var H=v.length,ie=new Array(H),re=-k,ae=t,de,ye;for(de=0;de<H;de++)ye=v[de]+re,re=Math.floor(ye/ae),ye%=ae,ie[de]=ye<0?ye+ae:ye;return ie=h(ie),typeof ie=="number"?(Q&&(ie=-ie),new u(ie)):new c(ie,Q)}c.prototype.subtract=function(v){var k=le(v);if(this.sign!==k.sign)return this.add(k.negate());var Q=this.value,H=k.value;return k.isSmall?T(Q,Math.abs(H),this.sign):w(Q,H,this.sign)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(v){var k=le(v),Q=this.value;if(Q<0!==k.sign)return this.add(k.negate());var H=k.value;return k.isSmall?new u(Q-H):T(H,Math.abs(Q),Q>=0)},u.prototype.minus=u.prototype.subtract,d.prototype.subtract=function(v){return new d(this.value-le(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,k=new u(-this.value);return k.sign=!v,k},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,k){var Q=v.length,H=k.length,ie=Q+H,re=A(ie),ae=t,de,ye,Me,Ve,pt;for(Me=0;Me<Q;++Me){Ve=v[Me];for(var rr=0;rr<H;++rr)pt=k[rr],de=Ve*pt+re[Me+rr],ye=Math.floor(de/ae),re[Me+rr]=de-ye*ae,re[Me+rr+1]+=ye}return m(re),re}function N(v,k){var Q=v.length,H=new Array(Q),ie=t,re=0,ae,de;for(de=0;de<Q;de++)ae=v[de]*k+re,re=Math.floor(ae/ie),H[de]=ae-re*ie;for(;re>0;)H[de++]=re%ie,re=Math.floor(re/ie);return H}function F(v,k){for(var Q=[];k-- >0;)Q.push(0);return Q.concat(v)}function G(v,k){var Q=Math.max(v.length,k.length);if(Q<=30)return D(v,k);Q=Math.ceil(Q/2);var H=v.slice(Q),ie=v.slice(0,Q),re=k.slice(Q),ae=k.slice(0,Q),de=G(ie,ae),ye=G(H,re),Me=G(I(ie,H),I(ae,re)),Ve=I(I(de,F(C(C(Me,de),ye),Q)),F(ye,2*Q));return m(Ve),Ve}function j(v,k){return-.012*v-.012*k+15e-6*v*k>0}c.prototype.multiply=function(v){var k=le(v),Q=this.value,H=k.value,ie=this.sign!==k.sign,re;if(k.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(N(Q,re),ie);H=p(re)}return j(Q.length,H.length)?new c(G(Q,H),ie):new c(D(Q,H),ie)},c.prototype.times=c.prototype.multiply;function R(v,k,Q){return v<t?new c(N(k,v),Q):new c(D(k,p(v)),Q)}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 le(v)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,d.prototype.multiply=function(v){return new d(this.value*le(v).value)},d.prototype.times=d.prototype.multiply;function B(v){var k=v.length,Q=A(k+k),H=t,ie,re,ae,de,ye;for(ae=0;ae<k;ae++){de=v[ae],re=0-de*de;for(var Me=ae;Me<k;Me++)ye=v[Me],ie=2*(de*ye)+Q[ae+Me]+re,re=Math.floor(ie/H),Q[ae+Me]=ie-re*H;Q[ae+k]=re}return m(Q),Q}c.prototype.square=function(){return new c(B(this.value),!1)},u.prototype.square=function(){var v=this.value*this.value;return f(v)?new u(v):new c(B(p(Math.abs(this.value))),!1)},d.prototype.square=function(v){return new d(this.value*this.value)};function U(v,k){var Q=v.length,H=k.length,ie=t,re=A(k.length),ae=k[H-1],de=Math.ceil(ie/(2*ae)),ye=N(v,de),Me=N(k,de),Ve,pt,rr,Rn,ci,uo,Il;for(ye.length<=Q&&ye.push(0),Me.push(0),ae=Me[H-1],pt=Q-H;pt>=0;pt--){for(Ve=ie-1,ye[pt+H]!==ae&&(Ve=Math.floor((ye[pt+H]*ie+ye[pt+H-1])/ae)),rr=0,Rn=0,uo=Me.length,ci=0;ci<uo;ci++)rr+=Ve*Me[ci],Il=Math.floor(rr/ie),Rn+=ye[pt+ci]-(rr-Il*ie),rr=Il,Rn<0?(ye[pt+ci]=Rn+ie,Rn=-1):(ye[pt+ci]=Rn,Rn=0);for(;Rn!==0;){for(Ve-=1,rr=0,ci=0;ci<uo;ci++)rr+=ye[pt+ci]-ie+Me[ci],rr<0?(ye[pt+ci]=rr+ie,rr=0):(ye[pt+ci]=rr,rr=1);Rn+=rr}re[pt]=Ve}return ye=O(ye,de)[0],[h(re),h(ye)]}function W(v,k){for(var Q=v.length,H=k.length,ie=[],re=[],ae=t,de,ye,Me,Ve,pt;Q;){if(re.unshift(v[--Q]),m(re),V(re,k)<0){ie.push(0);continue}ye=re.length,Me=re[ye-1]*ae+re[ye-2],Ve=k[H-1]*ae+k[H-2],ye>H&&(Me=(Me+1)*ae),de=Math.ceil(Me/Ve);do{if(pt=N(k,de),V(pt,re)<=0)break;de--}while(de);ie.push(de),re=C(re,pt)}return ie.reverse(),[h(ie),h(re)]}function O(v,k){var Q=v.length,H=A(Q),ie=t,re,ae,de,ye;for(de=0,re=Q-1;re>=0;--re)ye=de*ie+v[re],ae=g(ye/k),de=ye-ae*k,H[re]=ae|0;return[H,de|0]}function Y(v,k){var Q,H=le(k);if(s)return[new d(v.value/H.value),new d(v.value%H.value)];var ie=v.value,re=H.value,ae;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 de=Math.abs(re);if(de<t){Q=O(ie,de),ae=h(Q[0]);var ye=Q[1];return v.sign&&(ye=-ye),typeof ae=="number"?(v.sign!==H.sign&&(ae=-ae),[new u(ae),new u(ye)]):[new c(ae,v.sign!==H.sign),new u(ye)]}re=p(de)}var Me=V(ie,re);if(Me===-1)return[a[0],v];if(Me===0)return[a[v.sign===H.sign?1:-1],a[0]];ie.length+re.length<=200?Q=U(ie,re):Q=W(ie,re),ae=Q[0];var Ve=v.sign!==H.sign,pt=Q[1],rr=v.sign;return typeof ae=="number"?(Ve&&(ae=-ae),ae=new u(ae)):ae=new c(ae,Ve),typeof pt=="number"?(rr&&(pt=-pt),pt=new u(pt)):pt=new c(pt,rr),[ae,pt]}c.prototype.divmod=function(v){var k=Y(this,v);return{quotient:k[0],remainder:k[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/le(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%le(v).value)},u.prototype.remainder=u.prototype.mod=c.prototype.remainder=c.prototype.mod,c.prototype.pow=function(v){var k=le(v),Q=this.value,H=k.value,ie,re,ae;if(H===0)return a[1];if(Q===0)return a[0];if(Q===1)return a[1];if(Q===-1)return k.isEven()?a[1]:a[-1];if(k.sign)return a[0];if(!k.isSmall)throw new Error("The exponent "+k.toString()+" is too large.");if(this.isSmall&&f(ie=Math.pow(Q,H)))return new u(g(ie));for(re=this,ae=a[1];H&!0&&(ae=ae.times(re),--H),H!==0;)H/=2,re=re.square();return ae},u.prototype.pow=c.prototype.pow,d.prototype.pow=function(v){var k=le(v),Q=this.value,H=k.value,ie=BigInt(0),re=BigInt(1),ae=BigInt(2);if(H===ie)return a[1];if(Q===ie)return a[0];if(Q===re)return a[1];if(Q===BigInt(-1))return k.isEven()?a[1]:a[-1];if(k.isNegative())return new d(ie);for(var de=this,ye=a[1];(H&re)===re&&(ye=ye.times(de),--H),H!==ie;)H/=ae,de=de.square();return ye},c.prototype.modPow=function(v,k){if(v=le(v),k=le(k),k.isZero())throw new Error("Cannot take modPow with modulus 0");var Q=a[1],H=this.mod(k);for(v.isNegative()&&(v=v.multiply(a[-1]),H=H.modInv(k));v.isPositive();){if(H.isZero())return a[0];v.isOdd()&&(Q=Q.multiply(H).mod(k)),v=v.divide(2),H=H.square().mod(k)}return Q},d.prototype.modPow=u.prototype.modPow=c.prototype.modPow;function V(v,k){if(v.length!==k.length)return v.length>k.length?1:-1;for(var Q=v.length-1;Q>=0;Q--)if(v[Q]!==k[Q])return v[Q]>k[Q]?1:-1;return 0}c.prototype.compareAbs=function(v){var k=le(v),Q=this.value,H=k.value;return k.isSmall?1:V(Q,H)},u.prototype.compareAbs=function(v){var k=le(v),Q=Math.abs(this.value),H=k.value;return k.isSmall?(H=Math.abs(H),Q===H?0:Q>H?1:-1):-1},d.prototype.compareAbs=function(v){var k=this.value,Q=le(v).value;return k=k>=0?k:-k,Q=Q>=0?Q:-Q,k===Q?0:k>Q?1:-1},c.prototype.compare=function(v){if(v===1/0)return-1;if(v===-1/0)return 1;var k=le(v),Q=this.value,H=k.value;return this.sign!==k.sign?k.sign?1:-1:k.isSmall?this.sign?-1:1:V(Q,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 k=le(v),Q=this.value,H=k.value;return k.isSmall?Q==H?0:Q>H?1:-1:Q<0!==k.sign?Q<0?-1:1:Q<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 k=this.value,Q=le(v).value;return k===Q?0:k>Q?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 k=le(v);return k.isZero()?!1:k.isUnit()?!0:k.compareAbs(2)===0?this.isEven():this.mod(k).isZero()},d.prototype.isDivisibleBy=u.prototype.isDivisibleBy=c.prototype.isDivisibleBy;function Z(v){var k=v.abs();if(k.isUnit())return!1;if(k.equals(2)||k.equals(3)||k.equals(5))return!0;if(k.isEven()||k.isDivisibleBy(3)||k.isDivisibleBy(5))return!1;if(k.lesser(49))return!0}function se(v,k){for(var Q=v.prev(),H=Q,ie=0,re,ae,de,ye;H.isEven();)H=H.divide(2),ie++;e:for(de=0;de<k.length;de++)if(!v.lesser(k[de])&&(ye=Co(k[de]).modPow(H,v),!(ye.isUnit()||ye.equals(Q)))){for(re=ie-1;re!=0;re--){if(ye=ye.square().mod(v),ye.isUnit())return!1;if(ye.equals(Q))continue e}return!1}return!0}c.prototype.isPrime=function(v){var k=Z(this);if(k!==e)return k;var Q=this.abs(),H=Q.bitLength();if(H<=64)return se(Q,[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),ae=[],de=0;de<re;de++)ae.push(Co(de+2));return se(Q,ae)},d.prototype.isPrime=u.prototype.isPrime=c.prototype.isPrime,c.prototype.isProbablePrime=function(v,k){var Q=Z(this);if(Q!==e)return Q;for(var H=this.abs(),ie=v===e?5:v,re=[],ae=0;ae<ie;ae++)re.push(Co.randBetween(2,H.minus(2),k));return se(H,re)},d.prototype.isProbablePrime=u.prototype.isProbablePrime=c.prototype.isProbablePrime,c.prototype.modInv=function(v){for(var k=Co.zero,Q=Co.one,H=le(v),ie=this.abs(),re,ae,de;!ie.isZero();)re=H.divide(ie),ae=k,de=H,k=Q,H=ie,Q=ae.subtract(re.multiply(Q)),ie=de.subtract(re.multiply(ie));if(!H.isUnit())throw new Error(this.toString()+" and "+v.toString()+" are not co-prime");return k.compare(0)===-1&&(k=k.add(v)),this.isNegative()?k.negate():k},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 Ne=Ee.length,Se=Ee[Ne-1];function Et(v){return Math.abs(v)<=t}c.prototype.shiftLeft=function(v){var k=le(v).toJSNumber();if(!Et(k))throw new Error(String(k)+" is too large for shifting.");if(k<0)return this.shiftRight(-k);var Q=this;if(Q.isZero())return Q;for(;k>=Ne;)Q=Q.multiply(Se),k-=Ne-1;return Q.multiply(Ee[k])},d.prototype.shiftLeft=u.prototype.shiftLeft=c.prototype.shiftLeft,c.prototype.shiftRight=function(v){var k,Q=le(v).toJSNumber();if(!Et(Q))throw new Error(String(Q)+" is too large for shifting.");if(Q<0)return this.shiftLeft(-Q);for(var H=this;Q>=Ne;){if(H.isZero()||H.isNegative()&&H.isUnit())return H;k=Y(H,Se),H=k[1].isNegative()?k[0].prev():k[0],Q-=Ne-1}return k=Y(H,Ee[Q]),k[1].isNegative()?k[0].prev():k[0]},d.prototype.shiftRight=u.prototype.shiftRight=c.prototype.shiftRight;function Be(v,k,Q){k=le(k);for(var H=v.isNegative(),ie=k.isNegative(),re=H?v.not():v,ae=ie?k.not():k,de=0,ye=0,Me=null,Ve=null,pt=[];!re.isZero()||!ae.isZero();)Me=Y(re,Se),de=Me[1].toJSNumber(),H&&(de=Se-1-de),Ve=Y(ae,Se),ye=Ve[1].toJSNumber(),ie&&(ye=Se-1-ye),re=Me[0],ae=Ve[0],pt.push(Q(de,ye));for(var rr=Q(H?1:0,ie?1:0)!==0?Co(-1):Co(0),Rn=pt.length-1;Rn>=0;Rn-=1)rr=rr.multiply(Se).add(Co(pt[Rn]));return rr}c.prototype.not=function(){return this.negate().prev()},d.prototype.not=u.prototype.not=c.prototype.not,c.prototype.and=function(v){return Be(this,v,function(k,Q){return k&Q})},d.prototype.and=u.prototype.and=c.prototype.and,c.prototype.or=function(v){return Be(this,v,function(k,Q){return k|Q})},d.prototype.or=u.prototype.or=c.prototype.or,c.prototype.xor=function(v){return Be(this,v,function(k,Q){return k^Q})},d.prototype.xor=u.prototype.xor=c.prototype.xor;var Ue=1<<30,ge=(t&-t)*(t&-t)|Ue;function fe(v){var k=v.value,Q=typeof k=="number"?k|Ue:typeof k=="bigint"?k|BigInt(Ue):k[0]+k[1]*t|ge;return Q&-Q}function ve(v,k){if(k.compareTo(v)<=0){var Q=ve(v,k.square(k)),H=Q.p,ie=Q.e,re=H.multiply(k);return re.compareTo(v)<=0?{p:re,e:ie*2+1}:{p:H,e:ie*2}}return{p:Co(1),e:0}}c.prototype.bitLength=function(){var v=this;return v.compareTo(Co(0))<0&&(v=v.negate().subtract(Co(1))),v.compareTo(Co(0))===0?Co(0):Co(ve(v,Co(2)).e).add(Co(1))},d.prototype.bitLength=u.prototype.bitLength=c.prototype.bitLength;function Pe(v,k){return v=le(v),k=le(k),v.greater(k)?v:k}function Je(v,k){return v=le(v),k=le(k),v.lesser(k)?v:k}function Jt(v,k){if(v=le(v).abs(),k=le(k).abs(),v.equals(k))return v;if(v.isZero())return k;if(k.isZero())return v;for(var Q=a[1],H,ie;v.isEven()&&k.isEven();)H=Je(fe(v),fe(k)),v=v.divide(H),k=k.divide(H),Q=Q.multiply(H);for(;v.isEven();)v=v.divide(fe(v));do{for(;k.isEven();)k=k.divide(fe(k));v.greater(k)&&(ie=k,k=v,v=ie),k=k.subtract(v)}while(!k.isZero());return Q.isUnit()?v:v.multiply(Q)}function Ut(v,k){return v=le(v).abs(),k=le(k).abs(),v.divide(Jt(v,k)).multiply(k)}function Ar(v,k,Q){v=le(v),k=le(k);var H=Q||Math.random,ie=Je(v,k),re=Pe(v,k),ae=re.subtract(ie).add(1);if(ae.isSmall)return ie.add(Math.floor(H()*ae));for(var de=$e(ae,t).value,ye=[],Me=!0,Ve=0;Ve<de.length;Ve++){var pt=Me?de[Ve]+(Ve+1<de.length?de[Ve+1]/t:0):t,rr=g(H()*pt);ye.push(rr),rr<de[Ve]&&(Me=!1)}return ie.add(a.fromArray(ye,t,!1))}var Ke=function(v,k,Q,H){Q=Q||o,v=String(v),H||(v=v.toLowerCase(),Q=Q.toLowerCase());var ie=v.length,re,ae=Math.abs(k),de={};for(re=0;re<Q.length;re++)de[Q[re]]=re;for(re=0;re<ie;re++){var ye=v[re];if(ye!=="-"&&ye in de&&de[ye]>=ae){if(ye==="1"&&ae===1)continue;throw new Error(ye+" is not a valid digit in base "+k+".")}}k=le(k);var Me=[],Ve=v[0]==="-";for(re=Ve?1:0;re<v.length;re++){var ye=v[re];if(ye in de)Me.push(le(de[ye]));else if(ye==="<"){var pt=re;do re++;while(v[re]!==">"&&re<v.length);Me.push(le(v.slice(pt+1,re)))}else throw new Error(ye+" is not a valid character")}return Ye(Me,k,Ve)};function Ye(v,k,Q){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(k);return Q?H.negate():H}function St(v,k){return k=k||o,v<k.length?k[v]:"<"+v+">"}function $e(v,k){if(k=Co(k),k.isZero()){if(v.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(k.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 Q=Array.apply(null,Array(v.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return Q.unshift([1]),{value:[].concat.apply([],Q),isNegative:!1}}var H=!1;if(v.isNegative()&&k.isPositive()&&(H=!0,v=v.abs()),k.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,ae;re.isNegative()||re.compareAbs(k)>=0;){ae=re.divmod(k),re=ae.quotient;var de=ae.remainder;de.isNegative()&&(de=k.minus(de).abs(),re=re.next()),ie.push(de.toJSNumber())}return ie.push(re.toJSNumber()),{value:ie.reverse(),isNegative:H}}function tt(v,k,Q){var H=$e(v,k);return(H.isNegative?"-":"")+H.value.map(function(ie){return St(ie,Q)}).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,k){if(v===e&&(v=10),v!==10||k)return tt(this,v,k);for(var Q=this.value,H=Q.length,ie=String(Q[--H]),re="0000000",ae;--H>=0;)ae=String(Q[H]),ie+=re.slice(ae.length)+ae;var de=this.sign?"-":"";return de+ie},u.prototype.toString=function(v,k){return v===e&&(v=10),v!=10||k?tt(this,v,k):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 st(v){if(f(+v)){var k=+v;if(k===g(k))return s?new d(BigInt(k)):new u(k);throw new Error("Invalid integer: "+v)}var Q=v[0]==="-";Q&&(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],ae=re.indexOf(".");if(ae>=0&&(ie-=re.length-ae-1,re=re.slice(0,ae)+re.slice(ae+1)),ie<0)throw new Error("Cannot include negative exponent part for integers");re+=new Array(ie+1).join("0"),v=re}var de=/^([0-9][0-9]*)$/.test(v);if(!de)throw new Error("Invalid integer: "+v);if(s)return new d(BigInt(Q?"-"+v:v));for(var ye=[],Me=v.length,Ve=r,pt=Me-Ve;Me>0;)ye.push(+v.slice(pt,Me)),pt-=Ve,pt<0&&(pt=0),Me-=Ve;return m(ye),new c(ye,Q)}function ot(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 st(v.toString())}function le(v){return typeof v=="number"?ot(v):typeof v=="string"?st(v):typeof v=="bigint"?new d(v):v}for(var ee=0;ee<1e3;ee++)a[ee]=le(ee),ee>0&&(a[-ee]=le(-ee));return a.one=a[1],a.zero=a[0],a.minusOne=a[-1],a.max=Pe,a.min=Je,a.gcd=Jt,a.lcm=Ut,a.isInstance=function(v){return v instanceof c||v instanceof u||v instanceof d},a.randBetween=Ar,a.fromArray=function(v,k,Q){return Ye(v.map(le),le(k||10),Q)},a})();typeof BV<"u"&&BV.hasOwnProperty("exports")&&(BV.exports=Co);typeof define=="function"&&define.amd&&define(function(){return Co})});var $at=b((ean,Uat)=>{var uA=Qat(),FV=z("stream");(!FV.Writable||!FV.Writable.prototype.destroy)&&(FV=Da());var LV;function A0r(){var e=3988292384,t,r,n;for(LV=[],r=0;r<256;r++){for(t=r,n=0;n<8;n++)t=t&1?e^t>>>1:t=t>>>1;LV[r]=t>>>0}}function Mat(e,t){return LV||A0r(),e.charCodeAt&&(e=e.charCodeAt(0)),uA(t).shiftRight(8).and(16777215).xor(LV[uA(t).xor(e).and(255)]).value}function dv(){if(!(this instanceof dv))return new dv;this.key0=305419896,this.key1=591751049,this.key2=878082192}dv.prototype.update=function(e){this.key0=Mat(e,this.key0),this.key1=uA(this.key0).and(255).and(4294967295).add(this.key1),this.key1=uA(this.key1).multiply(134775813).add(1).and(4294967295).value,this.key2=Mat(uA(this.key1).shiftRight(24).and(255),this.key2)};dv.prototype.decryptByte=function(e){var t=uA(this.key2).or(2);return e=e^uA(t).multiply(uA(t^1)).shiftRight(8).and(255),this.update(e),e};dv.prototype.stream=function(){var e=FV.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};Uat.exports=dv});var jat=b((tan,qat)=>{var g0r=oA(),y0r=$at(),E0r=IV(),IB=z("stream"),I0r=sB(),b0r=z("zlib"),_0r=CV(),C0r=ov(),w0r=wV();(!IB.Writable||!IB.Writable.prototype.destroy)&&(IB=Da());qat.exports=function(t,r,n,i){var o=E0r(),s=IB.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=I0r.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=w0r(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=_0r(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=y0r();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})),g0r.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?b0r.createInflateRaw():IB.PassThrough();u?(s.size=c.uncompressedSize,d=c.compressedSize):(d=C0r.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 zat=b((ran,Hat)=>{var CB=sB(),_B=IV(),v0r=jat(),bB=oA(),S0r=_V(),D0r=CV(),R0r=ov(),Age=z("path"),T0r=hge().Writer,x0r=wV(),Yat=R0r.alloc(4);Yat.writeUInt32LE(101010256,0);function k0r(e){var t=e.stream(0).pipe(_B());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=CB.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 N0r(e,t){var r=CB.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=_B();return e.stream(r.offsetToStartOfCentralDirectory).pipe(n),n.pull(56)}function O0r(e){var t=CB.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}Hat.exports=function(t,r){var n=_B(),i=_B(),o=r&&r.tailSize||80,s,a,c,u;return r&&r.crx&&(a=k0r(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(Yat)}).then(function(){return bB.props({directory:n.pull(22),crxHeader:a})}).then(function(d){var f=d.directory;if(c=d.crxHeader&&d.crxHeader.size||0,u=CB.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=_B();return t.stream(h).pipe(m),m.pull(20).then(function(A){return N0r(t,A)}).then(function(A){u=O0r(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=Age.resolve(Age.normalize(d.path)),u.files.then(function(f){return bB.map(f,function(p){if(p.type!="Directory"){var h=Age.join(d.path,p.path);if(h.indexOf(d.path)==0){var m=d.getWriter?d.getWriter({path:h}):T0r({path:h});return new bB(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=bB.mapSeries(Array(u.numberOfRecords),function(){return i.pull(46).then(function(d){var f=CB.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=x0r(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=D0r(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 v0r(t,f.offsetToLocalFileHeader,h,f)},f.buffer=function(h){return S0r(f.stream(h))},f})})}),bB.props(u)})}});var Vat=b((nan,Gat)=>{var Jat=Oa(),PV=oA(),wB=zat(),QV=z("stream");(!QV.Writable||!QV.Writable.prototype.destroy)&&(QV=Da());Gat.exports={buffer:function(e,t){var r={stream:function(n,i){var o=QV.PassThrough();return o.end(e.slice(n,i)),o},size:function(){return PV.resolve(e.length)}};return wB(r,t)},file:function(e,t){var r={stream:function(n,i){return Jat.createReadStream(e,{start:n,end:i&&n+i})},size:function(){return new PV(function(n,i){Jat.stat(e,function(o,s){o?i(o):n(s.size)})})}};return wB(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 PV(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 wB(n,r)},s3:function(e,t,r){var n={size:function(){return new PV(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 wB(n,r)},custom:function(e,t){return wB(e,t)}}});var Wat=b(vB=>{"use strict";kit();Fit();ase();vB.Parse=vV();vB.ParseOne=Ust();vB.Extract=Pat();vB.Open=Vat()});var hct=b((oan,mp)=>{var gn=z("fs"),UV=z("os"),wo=z("path"),Kat=z("crypto"),Sd={fs:gn.constants,os:UV.constants},Xat="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",rct=/XXXXXX/,B0r=3,nct=(Sd.O_CREAT||Sd.fs.O_CREAT)|(Sd.O_EXCL||Sd.fs.O_EXCL)|(Sd.O_RDWR||Sd.fs.O_RDWR),F0r=UV.platform()==="win32",L0r=Sd.EBADF||Sd.os.errno.EBADF,P0r=Sd.ENOENT||Sd.os.errno.ENOENT,ict=448,oct=384,Q0r="exit",fv=[],sct=gn.rmdirSync.bind(gn),act=!1;function M0r(e,t){return gn.rm(e,{recursive:!0},t)}function cct(e){return gn.rmSync(e,{recursive:!0})}function Ige(e,t){let r=pv(e,t),n=r[0],i=r[1];V0r(n,function(o,s){if(o)return i(o);let a=s.tries;(function c(){try{let u=uct(s);gn.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 bge(e){let t=pv(e),r=t[0],n=W0r(r),i=n.tries;do{let o=uct(n);try{gn.statSync(o)}catch{return o}}while(i-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function U0r(e,t){let r=pv(e,t),n=r[0],i=r[1];Ige(n,function(s,a){if(s)return i(s);gn.open(a,nct,n.mode||oct,function(u,d){if(u)return i(u);if(n.discardDescriptor)return gn.close(d,function(p){return i(p,a,void 0,yge(a,-1,n,!1))});{let f=n.discardDescriptor||n.detachDescriptor;i(null,a,d,yge(a,f?-1:d,n,!1))}})})}function $0r(e){let t=pv(e),r=t[0],n=r.discardDescriptor||r.detachDescriptor,i=bge(r),o=gn.openSync(i,nct,r.mode||oct);return r.discardDescriptor&&(gn.closeSync(o),o=void 0),{name:i,fd:o,removeCallback:yge(i,n?-1:o,r,!0)}}function q0r(e,t){let r=pv(e,t),n=r[0],i=r[1];Ige(n,function(s,a){if(s)return i(s);gn.mkdir(a,n.mode||ict,function(u){if(u)return i(u);i(null,a,lct(a,n,!1))})})}function j0r(e){let t=pv(e),r=t[0],n=bge(r);return gn.mkdirSync(n,r.mode||ict),{name:n,removeCallback:lct(n,r,!0)}}function Y0r(e,t){let r=function(n){if(n&&!Ege(n))return t(n);t()};0<=e[0]?gn.close(e[0],function(){gn.unlink(e[1],r)}):gn.unlink(e[1],r)}function H0r(e){let t=null;try{0<=e[0]&&gn.closeSync(e[0])}catch(r){if(!K0r(r)&&!Ege(r))throw r}finally{try{gn.unlinkSync(e[1])}catch(r){Ege(r)||(t=r)}}if(t!==null)throw t}function yge(e,t,r,n){let i=MV(H0r,[t,e],n),o=MV(Y0r,[t,e],n,i);return r.keep||fv.unshift(i),n?i:o}function lct(e,t,r){let n=t.unsafeCleanup?M0r:gn.rmdir.bind(gn),i=t.unsafeCleanup?cct:sct,o=MV(i,e,r),s=MV(n,e,r,o);return t.keep||fv.unshift(o),r?o:s}function MV(e,t,r,n){let i=!1;return function o(s){if(!i){let a=n||o,c=fv.indexOf(a);return c>=0&&fv.splice(c,1),i=!0,r||e===sct||e===cct?e(t):e(t,s||function(){})}}}function z0r(){if(act)for(;fv.length;)try{fv[0]()}catch{}}function Zat(e){let t=[],r=null;try{r=Kat.randomBytes(e)}catch{r=Kat.pseudoRandomBytes(e)}for(let n=0;n<e;n++)t.push(Xat[r[n]%Xat.length]);return t.join("")}function Ba(e){return typeof e>"u"}function pv(e,t){if(typeof e=="function")return[{},e];if(Ba(e))return[{},t];let r={};for(let n of Object.getOwnPropertyNames(e))r[n]=e[n];return[r,t]}function J0r(e,t,r){let n=wo.isAbsolute(e)?e:wo.join(t,e);gn.stat(n,function(i){i?gn.realpath(wo.dirname(n),function(o,s){if(o)return r(o);r(null,wo.join(s,wo.basename(n)))}):gn.realpath(n,r)})}function G0r(e,t){let r=wo.isAbsolute(e)?e:wo.join(t,e);try{return gn.statSync(r),gn.realpathSync(r)}catch{let i=gn.realpathSync(wo.dirname(r));return wo.join(i,wo.basename(r))}}function uct(e){let t=e.tmpdir;if(!Ba(e.name))return wo.join(t,e.dir,e.name);if(!Ba(e.template))return wo.join(t,e.dir,e.template).replace(rct,Zat(6));let r=[e.prefix?e.prefix:"tmp","-",process.pid,"-",Zat(12),e.postfix?"-"+e.postfix:""].join("");return wo.join(t,e.dir,r)}function gge(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 dct(e){if(!Ba(e.name)){let t=e.name;if(wo.isAbsolute(t))throw new Error(`name option must not contain an absolute path, found "${t}".`);let r=wo.basename(t);if(r===".."||r==="."||r!==t)throw new Error(`name option must not contain a path, found "${t}".`)}if(!Ba(e.template)){if(typeof e.template!="string")throw new Error(`template option must be a string, got "${typeof e.template}".`);if(!e.template.match(rct))throw new Error(`Invalid template, found "${e.template}".`)}if(!Ba(e.tries)&&isNaN(e.tries)||e.tries<0)throw new Error(`Invalid tries, found "${e.tries}".`);e.tries=Ba(e.name)?e.tries||B0r:1,e.keep=!!e.keep,e.detachDescriptor=!!e.detachDescriptor,e.discardDescriptor=!!e.discardDescriptor,e.unsafeCleanup=!!e.unsafeCleanup,e.prefix=Ba(e.prefix)?"":gge("prefix",e.prefix),e.postfix=Ba(e.postfix)?"":gge("postfix",e.postfix),e.template=Ba(e.template)?void 0:gge("template",e.template)}function ect(e,t,r,n){if(Ba(t))return n(null);J0r(t,r,function(i,o){if(i)return n(i);let s=wo.relative(r,o);if(s.startsWith("..")||wo.isAbsolute(s))return n(new Error(`${e} option must be relative to "${r}", found "${s}".`));n(null,s)})}function tct(e,t,r){if(Ba(t))return;let n=G0r(t,r),i=wo.relative(r,n);if(i.startsWith("..")||wo.isAbsolute(i))throw new Error(`${e} option must be relative to "${r}", found "${i}".`);return i}function V0r(e,t){Z0r(e,function(r,n){if(r)return t(r);e.tmpdir=n;try{dct(e,n)}catch(i){return t(i)}ect("dir",e.dir,n,function(i,o){if(i)return t(i);e.dir=Ba(o)?"":o,ect("template",e.template,n,function(s,a){if(s)return t(s);e.template=a,t(null,e)})})})}function W0r(e){let t=e.tmpdir=pct(e);dct(e,t);let r=tct("dir",e.dir,t);return e.dir=Ba(r)?"":r,e.template=tct("template",e.template,t),e}function K0r(e){return fct(e,-L0r,"EBADF")}function Ege(e){return fct(e,-P0r,"ENOENT")}function fct(e,t,r){return F0r?e.code===r:e.code===r&&e.errno===t}function X0r(){act=!0}function Z0r(e,t){return gn.realpath(e&&e.tmpdir||UV.tmpdir(),t)}function pct(e){return gn.realpathSync(e&&e.tmpdir||UV.tmpdir())}process.addListener(Q0r,z0r);Object.defineProperty(mp.exports,"tmpdir",{enumerable:!0,configurable:!1,get:function(){return pct()}});mp.exports.dir=q0r;mp.exports.dirSync=j0r;mp.exports.file=U0r;mp.exports.fileSync=$0r;mp.exports.tmpName=Ige;mp.exports.tmpNameSync=bge;mp.exports.setGracefulCleanup=X0r});var Act=b((san,mct)=>{mct.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([eSr(t,"data"),i])):(t.pause(),yield r.shift()),s)throw s;n()};function eSr(e,t){return new Promise(r=>{let n=!1,i=()=>{n||(n=!0,e.removeListener(t,i),r())};e.addListener(t,i)})}});var Ict=b((aan,Ect)=>{var{EventEmitter:tSr}=z("events"),rSr=LN(),nSr=Ti(),$V=Ns(),gct=hi(),iSr=$f(),oSr=EY(),yct=IY(),_ge=class extends tSr{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 iSr}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=gct.l2n(t)}if(this._columns||(this._columns=[]),t>this._columns.length){let r=this._columns.length+1;for(;r<=t;)this._columns.push(new yct(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){nSr.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 rSr(t)){let y=[];for(let{eventType:I,value:E}of g)if(I==="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 oSr(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(I==="text")n&&A&&(A.text+=E);else if(I==="closetag"){let C=E;if(n)switch(C.name){case"cols":u=!1,this._columns=yct.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=gct.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=$V.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=$V.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:$V.isDateFmt(T.numFmt)?T.value=$V.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)}}};Ect.exports=_ge});var _ct=b((can,bct)=>{var{EventEmitter:sSr}=z("events"),aSr=LN(),cSr=tu(),lSr=lm(),Cge=class extends sSr{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 aSr(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 lSr.Hyperlink:{let d={type:cSr.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)}}};bct.exports=Cge});var Sct=b((lan,vct)=>{var wge=z("fs"),{EventEmitter:uSr}=z("events"),{PassThrough:dSr,Readable:fSr}=kN(),pSr=z("stream"),hSr=Wat(),wct=hct(),OE=Act(),mSr=LN(),Cct=XH(),ASr=iz(),gSr=rz(),ySr=Ict(),ESr=_ct();wct.setGracefulCleanup();var qV=class extends uSr{constructor(t,r={}){super(),this.input=t,this.options={worksheets:"emit",sharedStrings:"cache",hyperlinks:"ignore",styles:"ignore",entries:"ignore",...r},this.styles=new Cct,this.styles.init()}_getStream(t){if(t instanceof pSr.Readable||t instanceof fSr)return t;if(typeof t=="string")return wge.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=hSr.Parse({forceStream:!0});n.pipe(i);let o=[];for await(let s of OE(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(OE(s),c):await new Promise((u,d)=>{wct.file((f,p,h,m)=>{if(f)return d(f);o.push({sheetNo:c,path:p,tempFileCleanupCallback:m});let A=wge.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(OE(s),c));break}s.autodrain()}for(let{sheetNo:s,path:a,tempFileCleanupCallback:c}of o){let u=wge.createReadStream(a);u[Symbol.asyncIterator]||(u=u.pipe(new dSr)),yield*this._parseWorksheet(u,s),c()}}_emitEntry(t){this.options.entries==="emit"&&this.emit("entry",t)}async _parseRels(t){let r=new gSr;this.workbookRels=await r.parseStream(OE(t))}async _parseWorkbook(t){this._emitEntry({type:"workbook"});let r=new ASr;await r.parseStream(OE(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 mSr(OE(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 Cct,await this.styles.parseStream(OE(t)))}*_parseWorksheet(t,r){this._emitEntry({type:"worksheet",id:r});let n=new ySr({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 ESr({workbook:this,id:r,iterator:t,options:this.options});this.options.hyperlinks==="emit"&&(yield{eventType:"hyperlinks",value:n})}};qV.Options={worksheets:["emit","ignore"],sharedStrings:["cache","emit","ignore"],hyperlinks:["cache","emit","ignore"],styles:["cache","ignore"],entries:["emit","ignore"]};vct.exports=qV});var Tct=b((uan,Rct)=>{var Dct={Workbook:D5e(),ModelContainer:T5e(),stream:{xlsx:{WorkbookWriter:Tit(),WorkbookReader:Sct()}}};Object.assign(Dct,tu());Rct.exports=Dct});var kct=b((dan,xct)=>{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");xct.exports=Tct()});function Bct(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 _Sr(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 CSr(e){let r=(await Promise.resolve().then(()=>fo(cje(),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());Bct(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 vge(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?vge(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 wSr(e){let t=(await Promise.resolve().then(()=>fo(Jte(),1))).default,n=new t(Buffer.from(e)).getEntries().reduce((i,o)=>i+o.header.size,0);if(n>Nct)throw new Error(`XLSX uncompressed size ${n} bytes exceeds ${Nct}-byte safety cap`)}function Fct(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(vge(s)??"").trim()))}),{headerRowNum:t,columns:r}}function Oct(e){let{headerRowNum:t,columns:r}=Fct(e);if(!t)return{columns:[],rows:[]};Bct(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]]=vge(s[c]);n.push(a)}),{columns:r,rows:n}}async function vSr(e,t,r){await wSr(e);let n=await Promise.resolve().then(()=>fo(kct(),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{...Oct(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(Fct(d).headerRowNum!==0)try{return{...Oct(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 Lct(e){let t=Math.max(0,e.offset??0),r=Math.min(ISr,Math.max(1,e.limit??bSr)),n=e.sheetIndex??0,i=await _f(e.sourceUrl),o=await kc(i,{timeoutMs:d_,maxBytes:gU});if(!o.ok)throw new Error(`fetch ${e.sourceUrl}: ${o.status} ${o.statusText}`);let s=await o.arrayBuffer(),a=e.kind??_Sr(e.sourceUrl,o.headers.get("content-type")),c,u,d,f,p=n;if(a==="csv"){let A=await CSr(new TextDecoder("utf-8").decode(s));c=A.columns,u=A.rows}else{let A=await vSr(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 ISr,bSr,Nct,Pct=J(()=>{"use strict";zu();ISr=500,bSr=200,Nct=100*1024*1024});function SSr(e){if(e.internalNotes!==void 0)throw rt(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 rt(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 Qct(e){return{create:(t,r)=>t.post(`/api/v1/${hv[e]}`,{saveAsDraft:!1,...r,currency:Zt(r.currency),taxCurrency:Zt(r.taxCurrency)},Ki),list:(t,r)=>t.list(`/api/v1/${hv[e]}`,r),get:(t,r)=>t.get(`/api/v1/${hv[e]}/${r}`),update:async(t,r,n,i)=>{SSr(n);let o={...n,resourceId:r};if(!o.accountResourceId){let s=i??(await t.get(`/api/v1/${hv[e]}/${r}`)).data;if(o.accountResourceId=s.organizationAccountResourceId??s.account?.resourceId,!o.accountResourceId)throw new Error(`accountResourceId required for ${hv[e]} update and could not be derived from existing entry`)}return o.currency&&(o.currency=Zt(o.currency)),t.put(`/api/v1/${hv[e]}/${r}`,o)}}}var hv,jV,YV,HV,zV,BE,JV,GV,VV,FE,WV,KV=J(()=>{"use strict";Ht();it();hv={IN:"cash-in-entries",OUT:"cash-out-entries"};jV=Qct("IN"),YV=Qct("OUT"),HV=jV.create,zV=jV.list,BE=jV.get,JV=jV.update,GV=YV.create,VV=YV.list,FE=YV.get,WV=YV.update});async function SB(e,t){return e.post("/api/v1/cash-transfers",{saveAsDraft:!1,...t},Ki)}async function XV(e,t){return e.list("/api/v1/cash-transfers",t)}async function ZV(e,t){return e.get(`/api/v1/cash-transfers/${t}`)}var Sge=J(()=>{"use strict";Ht();en()});async function e8(e,t){return e.list("/api/v1/scheduled/invoices",t)}async function t8(e,t){return e.list("/api/v1/scheduled/bills",t)}async function r8(e,t){return e.list("/api/v1/scheduled/journals",t)}async function mv(e,t){return e.get(`/api/v1/scheduled/invoices/${t}`)}async function n8(e,t,r){return e.put(`/api/v1/scheduled/invoices/${t}`,r)}async function i8(e,t){await e.delete(`/api/v1/scheduled/invoices/${t}`)}async function Av(e,t){return e.get(`/api/v1/scheduled/bills/${t}`)}async function o8(e,t,r){return e.put(`/api/v1/scheduled/bills/${t}`,r)}async function s8(e,t){await e.delete(`/api/v1/scheduled/bills/${t}`)}async function gv(e,t){return e.get(`/api/v1/scheduled/journals/${t}`)}async function a8(e,t,r){let{currency:n,...i}=DSr(r);return e.put(`/api/v1/scheduled/journals/${t}`,n===void 0?i:{...i,currency:Zt(n)})}function DSr(e){let t={...e};SU(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 rt(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 c8(e,t){await e.delete(`/api/v1/scheduled/journals/${t}`)}var l8=J(()=>{"use strict";it()});import{statSync as Mct}from"node:fs";function Uct(e){for(let t of e)try{if(Mct(t).isFile())return t}catch{}return null}function $ct(e){for(let t of e)try{if(Mct(t).isDirectory())return t}catch{}return null}var Dge=J(()=>{"use strict"});import{readFileSync as Tge}from"node:fs";import{dirname as Hct,join as dA}from"node:path";import{fileURLToPath as zct}from"node:url";function Jct(e){let t=new Set(e);for(let r of e){let n=xSr.get(r);if(n)for(let i of n)t.add(i)}return Array.from(t)}function Gct(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&&!TSr.has(n))}function DB(e){let t=e??FSr();if(u8&&Yct===t)return u8;let r=Tge(t,"utf-8");return u8=JSON.parse(r),Yct=t,u8}function Vct(){let e=zct(import.meta.url),t=Hct(e),r=[dA(t,"..","..","..","help-center-mirror","help-center-index.json"),dA(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-index.json"),dA(t,"help-center-mirror","help-center-index.json")];return Uct(r)??void 0}function FSr(){let e=Vct();if(!e)throw new Error("Help center index not found. Run the help center sync or reinstall the package.");return e}function RB(){return Rge===null&&(Rge=Vct()!==void 0),Rge}function LE(e,t,r={}){let n=r.limit??5,i=Gct(t);if(i.length===0)return[];let o=Jct(i).slice(0,OSr),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>=NSr){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>=BSr))break}if(m===0)continue;f.push(g?`${h}*`:h);let y=m*(qct+1),I=m+qct*(1-jct+jct*(c.tokenCount/e.avgDocLen)),E=A*(y/I);g&&(E*=kSr),p.includes(h)&&(E*=RSr),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 xge(e,t){let r=t??LSr();if(!r)return null;try{let n=dA(r,`${e.section}.md`),i=Tge(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 LSr(){let e=zct(import.meta.url),t=Hct(e),r=[dA(t,"..","..","..","help-center-mirror"),dA(t,"..","..","..","assets","skills","api","help-center-mirror"),dA(t,"help-center-mirror")];for(let n of r)try{return Tge(dA(n,"index.md"),"utf-8"),n}catch{}return null}var qct,jct,RSr,TSr,xSr,kSr,NSr,OSr,BSr,u8,Yct,Rge,TB=J(()=>{"use strict";Dge();$g();qct=1.2,jct=.75,RSr=1.5,TSr=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"]),xSr=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"]]]);kSr=.7,NSr=3,OSr=32,BSr=5;u8=null,Yct=null;Rge=null});import{existsSync as PSr,readFileSync as QSr}from"node:fs";import{dirname as MSr,join as kge}from"node:path";import{fileURLToPath as USr}from"node:url";function xB(e){let t=e??HSr();if(!t)return null;if(d8&&Kct===t)return d8;try{let r=QSr(t,"utf-8");return d8=JSON.parse(r),Kct=t,d8}catch{return null}}function HSr(){let e=USr(import.meta.url),t=MSr(e),r=[kge(t,"..","..","..","help-center-mirror","help-center-embeddings.json"),kge(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),kge(t,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(PSr(n))return n;return null}function elt(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 tlt(){return f8!==null?f8:(f8=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",f8||null)}async function Nge(e){let t=tlt();if(!t)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),qSr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:$Sr,input:e}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Xct&&(Xct=!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 kB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??jSr,c=n.minBm25??YSr;if(i==="bm25"||!t)return LE(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Nge(r);return m?Zct(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):LE(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Nge(r),Promise.resolve(LE(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Zct(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return rlt(p,h,o)}function Zct(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=elt(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 rlt(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Wct+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/(Wct+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 Oge(e){return e!==null&&!!tlt()}var $Sr,qSr,Wct,jSr,YSr,d8,Kct,f8,Xct,p8=J(()=>{"use strict";TB();$Sr="text-embedding-3-small",qSr=2e3,Wct=60,jSr=.3,YSr=1.5,d8=null,Kct=null,f8=null,Xct=!1});async function nlt(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=DB();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:xB(),u=await kB(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=(xge(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 ilt(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:zSr}async function h8(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(ilt())}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(JSr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return GSr(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 GSr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Bge(e,t={}){return process.env.CLIO_DAEMON==="1"||RB()?nlt(e,t):h8(e,t)}var zSr,JSr,olt=J(()=>{"use strict";TB();p8();zSr="https://mcp.jaz.ai/help-center/search",JSr=4e3});var Fge=J(()=>{"use strict";TB();p8();olt();TB()});async function fA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function pA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var NB=J(()=>{"use strict";en()});async function m8(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Zt(t.currency),taxCurrency:Zt(t.taxCurrency)},EBe)}var Lge=J(()=>{"use strict";it();Ht()});async function A8(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function g8(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function OB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function y8(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Pge=J(()=>{"use strict"});function VSr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function yv(e,t){return e.post("/api/v1/jots",{entries:t.map(VSr)})}async function E8(e,t){return e.post("/api/v1/jots/search",t,Ge)}async function slt(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var I8=J(()=>{"use strict";Ht()});async function alt(e,t){return e.post("/api/v1/agents/memories",t)}async function Qge(e,t){return e.post("/api/v1/agents/memories/forget",t)}var clt=J(()=>{"use strict";Ht()});function b8(){return process.env.ENABLE_MEMORY==="true"}function Mge(){return process.env.ENABLE_MEMORY_CHAT==="true"}function llt(e){return!b8()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Uge=J(()=>{"use strict"});import{createHash as WSr}from"node:crypto";function aDr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:flt.some(r=>t.includes(r))?[null,"directive_invalid"]:dlt.test(t)?[null,"directive_invalid"]:rDr.test(t)?[null,"directive_contains_url"]:nDr.test(t)?[null,"directive_contains_email"]:[t,null]}function cDr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>iDr?[null,"match_condition_too_long"]:flt.some(r=>t.includes(r))?[null,"match_condition_invalid"]:dlt.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function lDr(e){return e==null?[null,null]:Number.isInteger(e)?e<oDr||e>sDr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function uDr(e,t,r,n,i,o,s,a){if(e)return WSr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function dDr(e){Promise.resolve().then(()=>(QD(),PD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Alt(e,t,r){let n=t.action,i=t.category,o=eDr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(dDr({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=llt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>KSr||!tDr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[I,E]=aDr(t.directive);if(E)return u(E);p=I;let[C,w]=lDr(t.importance);if(w)return u(w);h=C}let[m,A]=cDr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=XSr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let I={gtid:g};d.quote&&(I.quote=d.quote.slice(0,ZSr));let E=uDr(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:I,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await $ge(()=>alt(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let I={category:i,key:s,scope:o};y=await $ge(()=>Qge(e.client,I))}else{let I={forgetAll:!0};y=await $ge(()=>Qge(e.client,I))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function $ge(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 sr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var dlt,flt,KSr,XSr,ZSr,plt,hlt,mlt,eDr,tDr,rDr,nDr,iDr,oDr,sDr,glt=J(()=>{"use strict";clt();qi();Uge();Uge();dlt=/[\x00-\x1f\x7f]/,flt=["{{","}}","```","<",">"],KSr=120,XSr=3,ZSr=140,plt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],hlt=["set","forget","forget_all"],mlt=["this_org","all_orgs"],eDr={this_org:"ORG_USER",all_orgs:"USER"},tDr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,rDr=/https?:\/\//i,nDr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,iDr=255,oDr=0,sDr=100});async function _8(e,t){return e.list("/api/v1/organization-users",t)}async function C8(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 w8(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function v8(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var qge=J(()=>{"use strict"});async function S8(e,t){return e.get(`/api/v1/payments/${t}`)}async function D8(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Zt(r.currency)})}async function R8(e,t){await e.delete(`/api/v1/payments/${t}`)}function T8(e){return(t,r)=>t.post(`/api/v1/${fDr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Zt(n.currency)}))},nBe)}var fDr,hcn,ylt,mcn,Acn,jge=J(()=>{"use strict";it();Ht();fDr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};hcn=T8("saleBulk"),ylt=T8("saleBatch"),mcn=T8("purchaseBulk"),Acn=T8("purchaseBatch")});async function Ap(e,t,r,n,i,o=yBe){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 sr?c.status<500&&c.status!==401?rt(c):new Dc(`${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 ih?rt(c):c}let a=s?.data;if(!i(a))throw new Dc(`${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 k8(e,t,r){try{eo(e,t,r)}catch(n){throw rt(n)}}function PE(e){return k8(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function N8(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function O8(e,t){return Ap(e,"POST",pDr,t,hA)}async function B8(e,t,r){return Ap(e,"PUT",`/api/v1/unapplied-payments/${PE(t)}`,r,hA)}async function F8(e,t,r){return Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/activate`,{hash:r},hA)}async function L8(e,t,r,n){return Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/attributions`,{hash:r,attributions:n},hA)}async function P8(e,t,r,n){return k8(n,"paymentResourceId","Pass the payment record resourceId."),Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/payments`,{hash:r,paymentResourceId:n},hA)}async function Q8(e,t,r,n){return k8(r,"childResourceId","Pass the payment record resourceId from the children list."),Ap(e,"DELETE",`/api/v1/unapplied-payments/${PE(t)}/children/${encodeURIComponent(r)}`,{hash:n},hA)}async function M8(e,t,r){return Ap(e,"DELETE",`/api/v1/unapplied-payments/${PE(t)}`,{hash:r},hA)}async function U8(e,t,r){return Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/unbatch`,{hash:r},hA)}async function $8(e,t){return k8(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),Ap(e,"POST",hDr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,Ks)}var pDr,hDr,x8,Elt,Ilt,hA,Yge=J(()=>{"use strict";qi();Ht();rM();it();pDr="/api/v1/unapplied-payments",hDr="/api/v1/reconciliations/unapplied-payment",x8=["SALE","PURCHASE"],Elt=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ilt=["AMOUNT","PERCENTAGE"];hA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function q8(e,t,r={},n=Hge){let i=mDr.has(t)?`/api/v1/${Oc(blt,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=iy.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...iy.keys()].join(", ")}.`);let A=await Mf(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...Ge,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: ${[...BB].join(", ")}.`}:d}var blt,mDr,Hge,BB,_lt,zge=J(()=>{"use strict";Ht();it();wk();rd();blt=["statement-of-account-export"],mDr=new Set(blt),Hge=9e4,BB=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"]),_lt={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as ADr}from"node:crypto";import{writeFile as gDr,mkdir as yDr}from"node:fs/promises";import{dirname as EDr,isAbsolute as IDr,join as bDr}from"node:path";async function j8(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},Ge)}async function FB(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 Iv(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Clt(e){return`query-export-${e.slice(0,8)}.csv`}function Jge(e){return ADr("sha256").update(e).digest("hex").slice(0,16)}async function Y8(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Jge(t),o=await FB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await Iv(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await Iv(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&&!IDr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??bDr(f,"Downloads",`pseudo-sql-${s}.csv`);return await yDr(EDr(p),{recursive:!0}),await gDr(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 H8(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 bv(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 Gge=J(()=>{"use strict";it();Ht()});async function yi(e,t,r){let n=await e.get(`/api/v1/${z8[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function J8(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/${z8[r]}/${n}/attachments`,o)}async function G8(e,t,r,n){return e.delete(`/api/v1/${z8[t]}/${r}/attachments/${n}`)}var z8,al,LB,mA=J(()=>{"use strict";z8={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"},al=Object.keys(z8),LB=["sale-quotes","sale-orders","purchase-requests","purchase-orders","fixed-assets","deferrals","leases","loans","cash-in-entries","cash-out-entries","cash-transfers"]});function RDr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&DDr.some(n=>r.startsWith(n)))}async function gp(e){try{return await e}catch(t){throw t instanceof sr&&t.status===401&&RDr(t)&&(t.refusal=SDr),t}}function wlt(e,t,r){return eo(e,t,r),e.toLowerCase()}function _v(e,t){return{type:Oc(Vge,e,"entityType"),record:wlt(t,"entityId",_Dr)}}function PB(e){vte(e,"threadId",wDr)}function vlt(e){vte(e,"commentId",vDr)}function Cv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:wlt(e.bankAccountResourceId,"bankAccountResourceId",CDr)}}async function Slt(e,t,r,n={}){let{type:i,record:o}=_v(t,r),s={...Cv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return gp(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Dlt(e,t,r,n,i={}){let{type:o,record:s}=_v(t,r),a={...Cv(i),limit:i.limit,offset:i.offset};return PB(n),gp(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Rlt(e,t,r,n,i){let{type:o,record:s}=_v(t,r),a=Cv(i);return n.threadId!==void 0&&PB(n.threadId),(await gp(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...gBe,query:a}))).data}async function Tlt(e,t,r,n,i,o,s){let{type:a,record:c}=_v(t,r),u=Cv(s);return PB(n),vlt(i),(await gp(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function xlt(e,t,r,n,i,o){let{type:s,record:a}=_v(t,r),c=Cv(o);return PB(n),vlt(i),(await gp(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function klt(e,t,r,n,i){let{type:o,record:s}=_v(t,r),a=Cv(i);return PB(n),(await gp(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function Nlt(e,t={}){return gp(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function Olt(e,t,r){return yFe(t,"Get it from list_notifications."),(await gp(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function Blt(e){return(await gp(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Vge,_Dr,CDr,wDr,vDr,SDr,DDr,Flt=J(()=>{"use strict";qi();it();Ht();Vge=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],_Dr="Pass the resourceId of the bill, invoice, credit note or bank record.",CDr="Pass the resourceId of the bank account that holds the bank record.",wDr="Get it from list_comment_threads.",vDr="Get it from list_comments or list_comment_threads.",SDr={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."},DDr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Qo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var wv=J(()=>{"use strict"});async function V8(e,t){return e.post("/api/v1/claims/conversion/preview",t,Ge)}async function W8(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:dM)}var QB,Wge=J(()=>{"use strict";it();Ht();QB=["POST","POST_AND_RECORD"]});async function K8(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,iBe)}async function X8(e,t){return e.search("/api/v1/employees/payouts/search",t)}var Llt,Kge=J(()=>{"use strict";it();Ht();Llt=["REIMBURSEMENT","ADVANCE"]});async function Z8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Xge=J(()=>{"use strict"});function Zge(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 eye(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: ${Plt(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=>Gu.has(u)),s=i.filter(u=>!Gu.has(u)&&Fc.has(u)),a=[`Nothing here can be extracted: found ${Plt(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=wLe[u];d&&a.push(d)}return o.length>0&&a.push(`${WU(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(`${WU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Gu.has(u)&&!Fc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${WU([...Gu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function Plt(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 Qlt=J(()=>{"use strict";Vu()});function eW(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function MB(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&&eW()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function QE(e,t){return{error:e,hint:t,...tye}}function Mlt(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: ${MB(e)}.`,...tye}}function ME(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function AA(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: ${MB({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.",...tye,...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 tye,Ult=J(()=>{"use strict";tye={kind:"validation",retriable:!1}});import{randomUUID as TDr}from"node:crypto";import{rmSync as xDr}from"node:fs";function nye(e){for(let t of e.tempDirs??[])try{xDr(t,{recursive:!0,force:!0})}catch{}}function qlt(e){for(let[t,r]of UE)e-r.createdAt>$lt&&(nye(r.plan),UE.delete(t))}function NDr(){rye||(rye=setInterval(()=>qlt(Date.now()),kDr),rye.unref?.())}function iye(e,t){let r=Date.now();qlt(r),NDr();let n=`dc_${TDr()}`;return UE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function oye(e,t){let r=UE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>$lt?(nye(r.plan),UE.delete(e),null):r.plan}function jlt(e,t){let r=UE.get(e);!r||r.ownerKey!==t||(nye(r.plan),UE.delete(e))}var $lt,kDr,UE,rye,Ylt=J(()=>{"use strict";$lt=1800*1e3,kDr=300*1e3,UE=new Map});function ODr(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 Hlt(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>Fg(i.documentType)&&r.has(i.documentType))}))}}async function zlt(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?Hlt(t,i):t;if(!n&&BDr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");GD(o);let a=await d$({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"?ODr(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 Jlt(e,t){return(t&&t.length>0?Hlt(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>Fg(o.documentType)).length,0)}function BDr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var Glt=J(()=>{"use strict";tre();Vu();Tf()});function FDr(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 PDr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function QDr(e,t){if(e!==LDr)return;let r=PDr(t);if(r)return Vlt.get(r)??Vlt.get(r.replace(/_ERROR$/,""))}function tW(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 MDr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=tW(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 sye(e){return QDr(e.status,e.body)??e.refusal?.hint??MDr(e)}function cl(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 rW(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function UB(e,t={}){let r=t.readOnly===!1&&aR()?d1e:"";if(e instanceof sr){let o=[sye(e)??FDr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...tW(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=nW(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 at;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var LDr,Vlt,yp=J(()=>{"use strict";qi();Xi();iW();A$();LDr=422,Vlt=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 Dd(e,t,r){if(!t)return e;let n=UDr(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 Rd(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${cl(i)}`],...n}}}function UDr(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 Ep(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var Wlt=J(()=>{"use strict";yp()});async function oW(e,t){return e.list("/api/v1/bank-rules",t)}async function $B(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 sW(e,t){return e.search("/api/v1/bank-rules/search",t)}async function aW(e,t){return e.post("/api/v1/bank-rules",t)}async function cW(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function lW(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var aye=J(()=>{"use strict"});async function uW(e,t){return e.list("/api/v1/fixed-assets",t)}async function $E(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function qB(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function dW(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},tte)}function Xlt(e,t){let r={};for(let n of $Dr){let i=e[n];if(i==null)continue;let o=qDr.has(n)?bf(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 fW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw rt(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await $E(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,Xlt(i,r))}async function pW(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function hW(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},aM)}async function jB(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,aM)}async function mW(e,t){return e.post("/api/v1/transfer-fixed-assets",t,tte)}async function AW(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},aM)}async function gW(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},rte)}async function yW(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},rte)}async function jDr(e,t){let r=new Map;for(let i=0;i<t.length;i+=Klt){let o=t.slice(i,i+Klt),s=await qB(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 rt(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 EW(e,t){ut(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=hD(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw rt(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw rt(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)=>ji(a.tags,`fixedAssets[${c}].tags`)),o=await jDr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...Xlt(u,{...a,tags:d&&Zi(u.tags,d)})}});return bn(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function IW(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function bW(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function _W(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,Ge)}async function CW(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},Ge)}async function wW(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function vW(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function SW(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function HDr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function zDr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=HDr(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} (${YDr[a]})`).join(", ")}`)}),t.length>0)throw rt(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 DW(e,t){return ut(t,"fixedAssets",500,"fixed assets"),ZBe(t,["purchaseDate","depreciationStartDate"]),zDr(t),bn(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var gA,$Dr,qDr,Klt,YDr,RW=J(()=>{"use strict";en();ID();Ht();it();Ul();gA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];$Dr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],qDr=new Set(["purchaseDate","depreciationStartDate"]);Klt=100;YDr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function TW(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function qE(e,t){return e.get(`/api/v1/leases/${t}`)}async function xW(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},cBe)}async function kW(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 qE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function NW(e,t){await e.delete(`/api/v1/leases/${t}`)}async function OW(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},dD)}async function BW(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},dD)}async function FW(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},dD)}async function LW(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},Ge)}async function PW(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},dD)}async function QW(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function MW(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function UW(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function $W(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,Ge)}async function qW(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,Ge)}async function jW(e,t){return ut(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw rt(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.`))}}),bn(e,"/api/v1/leases/bulk-update","leases",t)}var cye=J(()=>{"use strict";en();it();Ht()});function jE(e,t,r){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names ${e} ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let n={};for(let[i,o]of Object.entries(r))o!==void 0&&i!=="resourceId"&&(n[i]=o);return n}async function lye(e,t,r,n){return e.search(t,{...r,sort:r.sort??{sortBy:[n],order:"ASC"}})}async function YW(e,t){return lye(e,"/api/v1/pay-types/search",t,"name")}async function HW(e,t){return e.get(`/api/v1/pay-types/${t}`)}async function zW(e,t){return e.post("/api/v1/pay-types",t,lM)}async function JW(e,t,r){return e.put(`/api/v1/pay-types/${t}`,jE("pay type",t,r))}async function GW(e,t){return e.delete(`/api/v1/pay-types/${t}`)}async function VW(e,t){return lye(e,"/api/v1/payrun-posting-rules/search",t,"name")}async function WW(e,t){return e.get(`/api/v1/payrun-posting-rules/${t}`)}async function KW(e,t){return e.post("/api/v1/payrun-posting-rules",t,lM)}async function XW(e,t,r){return e.put(`/api/v1/payrun-posting-rules/${t}`,jE("payrun posting rule",t,r))}async function ZW(e,t){return e.delete(`/api/v1/payrun-posting-rules/${t}`)}async function e4(e,t){return lye(e,"/api/v1/pay-profiles/search",t,"name")}async function t4(e,t){return e.get(`/api/v1/pay-profiles/${t}`)}async function r4(e,t){return e.post("/api/v1/pay-profiles",t,lM)}async function n4(e,t,r){return e.put(`/api/v1/pay-profiles/${t}`,jE("pay profile",t,r))}async function i4(e,t){return e.delete(`/api/v1/pay-profiles/${t}`)}var YB=J(()=>{"use strict";it();Ht()});async function o4(e,t){return e.search("/api/v1/employee-pay-details/search",{...t,sort:t.sort??{sortBy:["effectiveFromDate"],order:"DESC"}})}async function s4(e,t){return e.post("/api/v1/employee-pay-details",t,nte)}async function a4(e,t){return ut(t,"employeePayDetails",500,"employee pay details"),e.post("/api/v1/employee-pay-details/bulk-create",{employeePayDetails:t},nte)}async function c4(e,t,r){return e.put(`/api/v1/employee-pay-details/${t}`,jE("employee pay detail",t,r))}var uye=J(()=>{"use strict";en();Ht();YB()});async function l4(e,t){return e.search("/api/v1/payruns/search",{...t,sort:t.sort??{sortBy:["periodStartDate"],order:"DESC"}})}async function vv(e,t){return e.get(`/api/v1/payruns/${t}`)}async function JDr(e,t){let r=t.idempotencyKey;if(!r)return e.post("/api/v1/payruns",t,lBe);try{return await e.post("/api/v1/payruns",t)}catch(n){throw n instanceof sr&&n.status>=400&&n.status<500&&n.status!==408?n:new Dc(n instanceof Dc?n.message:`POST /api/v1/payruns: the create may or may not have happened (${n.message}).`,"/api/v1/payruns",`Create it again with idempotencyKey ${String(r)}: the same key returns the payrun already created instead of a second one.`,{cause:n})}}function Zlt(e){return{employeeResourceId:e.employeeResourceId,...e.employee!==void 0?{employee:e.employee}:{},...dye(e)?{}:{errorCode:GDr}}}function dye(e){return typeof e.payProfileResourceId=="string"&&e.payProfileResourceId!==""}function HB(e){let t=e.added??[],r=t.filter(i=>!dye(i)).map(Zlt),n=e.skipped!==void 0||r.length>0?[...e.skipped??[],...r]:void 0;return{added:t.filter(dye),skipped:n}}async function u4(e,t){let r=await JDr(e,t);if(t.populate!==!0)return r;try{let{data:n}=await zB(e,r.data.resourceId),i=[...n.skipped??[]],o=new Set(i.map(s=>s.employeeResourceId));for(let s of n.added??[])o.has(s.employeeResourceId)||(o.add(s.employeeResourceId),i.push(Zlt(s)));return{skipped:i,...i.length>0?{note:"The fill left these employees out. Say so in the reply and name each one with its reason (errorCode); where one reason covers many, give the reason with its count and offer the names (search_employees names one by employeeResourceId)."}:{},...r}}catch(n){return{partialFailures:[`The run was created and filled, but reading who the fill left out failed: ${cl(n)}. preview_populate_payrun lists them.`],...r}}}async function d4(e,t,r){return e.put(`/api/v1/payruns/${t}`,jE("payrun",t,r))}async function f4(e,t){return e.delete(`/api/v1/payruns/${t}`)}async function p4(e,t){return e.post("/api/v1/payruns/bulk/delete",{resourceIds:t},uBe)}async function h4(e,t,r){return e.post(`/api/v1/payruns/${t}/employees`,{employeeResourceIds:r},sh)}async function m4(e,t,r){return e.post(`/api/v1/payruns/${t}/employees/remove`,{employeeResourceIds:r},sh)}async function A4(e,t,r){return e.put(`/api/v1/payruns/${t}/lines`,{payslips:r})}async function g4(e,t){return e.post(`/api/v1/payruns/${t}/populate`,void 0,sh)}async function zB(e,t){return e.post(`/api/v1/payruns/${t}/populate/preview`,void 0,Ge)}var GDr,JB=J(()=>{"use strict";qi();Ht();YB();yp();GDr="PAYRUN_EMPLOYEE_NO_PAY_PROFILE"});function KDr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eut(e,t){let r={};for(let n of t)e[n]!==void 0&&(r[n]=e[n]);return r}function tut(e,t){let r=e;if(e.payslips!==void 0&&!(Array.isArray(e.payslips)&&e.payslips.length>0&&e.payslips.every(KDr)))throw new ue("The payslips list is empty, is not a list, or has an entry that is not a payslip object. Name the payslips to pay, or leave payslips out to pay every payslip still owed.");let n=e.payslips?.map(i=>eut(i,VDr));return{...eut(r,WDr),...n?{payslips:n}:{},...t&&e.hash?{hash:e.hash}:{},payoutMethod:"RECORD"}}async function y4(e,t,r){return e.post(`/api/v1/payruns/${t}/validate`,r?{journalValueDate:r}:{},Ge)}async function E4(e,t,r){return e.post(`/api/v1/payruns/${t}/preview-journal`,r?{journalValueDate:r}:{},Ge)}async function I4(e,t,r){return e.post(`/api/v1/payruns/${t}/finalize`,r?{journalValueDate:r}:{},uM)}async function b4(e,t){return e.post("/api/v1/payruns/bulk/finalize",{payruns:t},dBe)}async function _4(e,t){return e.post(`/api/v1/payruns/${t}/unpost`,void 0,uM)}async function C4(e,t,r){return e.post(`/api/v1/payruns/${t}/void`,{voidReason:r},uM)}async function w4(e,t,r){return e.post(`/api/v1/payruns/${t}/payouts/preview`,tut(r,!1),Ge)}async function v4(e,t,r){return e.post(`/api/v1/payruns/${t}/payouts`,tut(r,!0),fBe)}async function S4(e,t,r){return e.post(`/api/v1/payruns/payouts/${t}/void`,{voidReason:r},pBe)}var VDr,WDr,fye=J(()=>{"use strict";it();Ht();VDr=["payslipResourceId","amount","reference"],WDr=["paymentAccountResourceId","valueDate","reference","internalNotes"]});async function D4(e,t){return e.search("/api/v1/payslips/search",{...t,sort:t.sort??{sortBy:["payrun.periodEndDate"],order:"DESC"}})}async function GB(e,t){return e.get(`/api/v1/payslips/${t}`)}async function pye(e,t){return e.post(`/api/v1/payslips/${t}/refresh`,void 0,sh)}function rut(e){return e===void 0||e.length===0?{}:{payslipResourceIds:e}}async function hye(e,t,r){return e.post(`/api/v1/payruns/${t}/payslips/refresh`,rut(r),sh)}async function R4(e,t,r){return e.post(`/api/v1/payruns/${t}/payslips/generate`,rut(r),sh)}async function nut(e,t){let r=[],n=async a=>{try{let{data:c}=await GB(e,t);if(typeof c!="object"||c===null)throw new Error("the reply carried no payslip");return c}catch(c){r.push(`Reading the payslip ${a} the refresh failed: ${cl(c)}. get_payslip reads its lines now.`);return}},i=await n("before"),o=await pye(e,t),s=await n("after");return{...r.length>0?{partialFailures:r}:{},...o,...i?{before:i}:{},...s?{after:s}:{}}}async function iut(e,t,r){let n=[],i=r!==void 0&&r.length>0?new Set(r):void 0,o=m=>{if(!i)return m;let A=m.filter(g=>i.has(g?.resourceId));return A.length===i.size&&new Set(A.map(g=>g.resourceId)).size===i.size?A:null},s=async m=>{try{let{payslips:A}=(await vv(e,t)).data;if(!Array.isArray(A))throw new Error("the run carried no payslip rows");let g=o(A);if(!g)throw new Error("the run does not hold each payslip refreshed exactly once");return g}catch(A){n.push(`Reading the run's payslips ${m} the refresh failed: ${cl(A)}. get_payrun reads them now.`);return}},a=await s("before"),c=await hye(e,t,r),u=c.data.payrun?.payslips,d=i??(a?new Set(a.map(m=>m?.resourceId)):void 0),f=Array.isArray(u)&&u.length>0&&d!==void 0&&d.size>0&&[...d].every(m=>typeof m=="string")?o(u)??void 0:void 0,p=f!==void 0&&(i!==void 0||[...d??[]].every(m=>f.some(A=>A.resourceId===m))),h=a===void 0?void 0:p?f:await s("after");return{...n.length>0?{partialFailures:n}:{},...c,...a?{before:a}:{},...h?{after:h}:{}}}var mye=J(()=>{"use strict";Ht();JB();yp()});function VB(e){let t=e<0?"-":"",r=Math.abs(e),[n,i="00"]=r.toFixed(2).split("."),o=n.replace(/\B(?=(\d{3})+(?!\d))/g,",");return`${t}${o}.${i}`}var out=J(()=>{"use strict"});function Ip(e,t){let r={};for(let n of t)e[n]!==void 0&&(r[n]=e[n]);return r}function _ye(e){let t={};for(let[r,n]of Object.entries(e))r==="deleted"||r==="organizationResourceId"||r==="idempotencyKey"||/By$/.test(r)&&typeof n=="string"||(t[r]=n);return t}function rRr(e){let t=Ps(e.payTypeSnapshot)?e.payTypeSnapshot:{};return{...Ip(e,["resourceId","payTypeId"]),...t.name!==void 0?{payTypeName:t.name}:{},...t.category!==void 0?{category:t.category}:{},...Ip(e,["amount","origin","description"])}}function Cye(e){let t=Array.isArray(e.lines)?e.lines:void 0;return{...Ip(e,tRr),...typeof e.inProgressAmount=="number"&&e.inProgressAmount>0?{inProgressAmount:e.inProgressAmount}:{},...t?{lineCount:t.length}:{}}}function lut(e){let{employee:t,payProfile:r,...n}=e,i=Ps(t)?t.name:void 0;return i!==void 0&&n.employeeName===void 0?{...n,employeeName:i}:n}function wye(e){let t={};for(let r of e){let n=yye(r);n&&(t[n]=(t[n]??0)+1)}return t}function vye(e,t=lut){if(e.length===0)return[];let r=wye(e);return{totalElements:e.length,...Object.keys(r).length>0?{byErrorCode:r}:{},data:e.map(t)}}function k4(e,t){if(t.length===0)return e;let r={...e},n=Ip(r,sut);for(let i of sut)delete r[i];return{...n,note:t.join(" "),...r}}function uut(e,t,r){let n={};for(let[i,o]of Object.entries(_ye(e)))i==="payslips"&&Array.isArray(o)&&t==="payslips"?(n.payslips=x4(ua(o).map(Cye)),o.length>0&&r.push(ZDr)):i==="payslips"&&Array.isArray(o)?t==="payouts"?r.push(eRr):r.push(XDr):i==="removedPayslips"&&Array.isArray(o)?n.removedPayslipCount=o.length:i==="payouts"&&Array.isArray(o)?t==="payouts"?n.payouts=x4(ua(o).map(nRr)):n.payoutCount=o.length:n[i]=o;return n}function Sye(e,t){let r=[],n={};for(let[i,o]of Object.entries(e))i==="data"&&Ps(o)?n.data=uut(o,t,r):i==="skipped"&&Array.isArray(o)?n.skipped=vye(ua(o)):i==="note"&&typeof o=="string"?r.unshift(o):n[i]=o;return k4(n,r)}function WB(e,t,r,n={}){let i=Ps(e.data)?e.data:{},o=[...Eye(e)],s=Object.fromEntries(Object.entries(i).filter(([a])=>a!==t&&a!==r&&a!=="payrun"));return k4({data:{...Array.isArray(i[t])?{[t]:vye(ua(i[t]))}:{},...Array.isArray(i[r])?{[`${r}Count`]:i[r].length}:{},...n,...Ps(i.payrun)?{payrun:uut(i.payrun,"none",o)}:{},...s}},o)}function aRr(e){let{added:t,skipped:r}=HB({added:ua(e.added),skipped:e.skipped!==void 0?ua(e.skipped):void 0});return{skipped:r,adding:t}}function put(e,t=!1){let r=Ps(e.data)?e.data:{},{skipped:n,adding:i}=aRr(r);if(!t){let d={...r,...n!==void 0?{skipped:n}:{},...r.added!==void 0?{added:i}:{}};return WB({...e,data:d,note:[...Eye(e),iRr].join(" ")},"skipped","added")}let o=wye(n??[]),{skipped:s,added:a,payrun:c,...u}=r;return k4({data:{...n!==void 0?{skippedCount:n.length,...Object.keys(o).length>0?{byErrorCode:o}:{}}:{},addedCount:i.length,...u,...r.added!==void 0?{added:x4(i.map(sRr))}:{}}},[...Eye(e),oRr])}function uRr(e,t){let r=new Map(t.map(c=>[c.resourceId,c])),n=new Set(e.map(c=>c.resourceId)),i=e.filter(c=>!r.has(c.resourceId)),o=t.filter(c=>!n.has(c.resourceId)),s=e.filter(c=>r.has(c.resourceId)).map(c=>[c,r.get(c.resourceId)]),a=[];for(let c of i){let u=gye(c);if(typeof c.payTypeId!="string"||typeof c.origin!="string"){a.push(c);continue}let d=i.filter(p=>gye(p)===u),f=o.filter(p=>gye(p)===u);d.length===1&&f.length===1?(s.push([c,f[0]]),o.splice(o.indexOf(f[0]),1)):a.push(c)}return{changedLines:s.filter(([c,u])=>c.amount!==u.amount).map(([c,u])=>hut(Aye(u),c.amount,u.amount)),removedLines:a.map(c=>`${Aye(c)}: ${VB(c.amount)} removed`),addedLines:o.map(c=>`${Aye(c)}: ${VB(c.amount)} added`)}}function gut(e){let{data:t}=T4({data:e.data});if(!Ps(t))return e;let r=a=>KB(a===void 0?e:bye(e,a),{data:{...t,refresh:Sv}}),n=["before","after"].map(a=>({when:a,read:e[a]}));for(let{when:a,read:c}of n){if(!Ps(c))return Array.isArray(e.partialFailures)&&e.partialFailures.length>0?r():r(`The payslip was not read ${a} the refresh, so what changed is not shown. get_payslip reads its lines now.`);if(!Array.isArray(c.lines))return r(`The payslip read ${a} the refresh carried no lines, so what changed is not shown. get_payslip reads its lines now.`);if(!c.lines.every(cRr)||new Set(c.lines.map(u=>u.resourceId)).size!==c.lines.length)return r(`The payslip read ${a} the refresh has a line without a unique id or a numeric amount, so what changed is not shown. get_payslip reads its lines now.`)}let i=T4({data:e.before}).data,o=T4({data:e.after}).data;if(!mut(i,o))return r("The payslip amounts read before and after the refresh cannot be compared (one is missing or not a number), so what changed is not shown. get_payslip reads them now.");let s={...uRr(ua(i.lines),ua(o.lines)),amounts:Aut(i,o)};return KB(e,{data:{...t,refresh:Sv,changes:s}})}function yut(e){let t=u=>KB(e,WB(e,"failed","refreshed",{refresh:Sv,...u})),r=t({}),n=Array.isArray(e.partialFailures)&&e.partialFailures.length>0;if(!Array.isArray(e.before)||!Array.isArray(e.after))return n?r:KB(bye(e,"The run's payslips were not read before and after the refresh, so which payslips changed is not shown. get_payrun lists their amounts now."),WB(e,"failed","refreshed",{refresh:Sv}));let i=pRr(e.before,e.after);if(typeof i=="string")return KB(bye(e,i),WB(e,"failed","refreshed",{refresh:Sv}));if(i.length===0)return t({changedPayslips:[]});let o=Dye-JSON.stringify(r,null,2).length-dRr,s=[],a=0;for(let u of i){if(a+=JSON.stringify(u).length+fRr,a>o)break;s.push(u)}let c=i.length-s.length;return t({changedPayslips:{totalElements:i.length,...c>0?{notShown:c,note:`${c} more payslips changed, but the earlier amounts of those are not shown and cannot be read again after this refresh. get_payrun lists their amounts as they are now.`}:{},rows:s}})}function pRr(e,t){let r="The payslips read before and after the refresh cannot be compared (a row without a unique id, a payslip in only one read, or an amount that is missing or not a number), so which payslips changed is not shown. get_payrun lists their amounts now.",n=s=>Ps(s)&&typeof s.resourceId=="string"?s.resourceId:void 0;if(!e.every(s=>n(s)!==void 0)||!t.every(s=>n(s)!==void 0))return r;let i=new Map(e.map(s=>[s.resourceId,s])),o=t;return i.size!==e.length||new Set(o.map(s=>s.resourceId)).size!==o.length||i.size!==o.length||!o.every(s=>i.has(s.resourceId))||!o.every(s=>mut(i.get(s.resourceId),s))?r:o.flatMap(s=>{let a=Aut(i.get(s.resourceId),s,""),c=typeof s.employeeName=="string"&&s.employeeName!==""?s.employeeName:s.resourceId;return a.length>0?[`${c}: ${a.join("; ")}`]:[]})}function Eut(e){return{note:"The payslips named, as rows without lines: get_payslip reads one with its lines and line ids.",data:ua(e.data).map(Cye)}}function Iut(e){let t=T4(e);if(!Ps(t.data)||!Ps(t.data.payrun)||t.data.payrun.status!=="DRAFT")return t;let{lines:r,...n}=t.data;return{data:{...n,onRefresh:Sv,...r!==void 0?{lines:r}:{}}}}function T4(e){if(!Ps(e.data))return e;let{lines:t,...r}=_ye(e.data);return{data:{...r,...Array.isArray(t)?{lines:ua(t).map(rRr)}:{}}}}function but(e){return e.data.length===0?e:{note:"Rows have no lines: get_payslip reads one with its lines and line ids.",...e,data:ua(e.data).map(t=>({...Cye(t),...Ip(t,["payrunResourceId","payProfileResourceId"]),...Ps(t.payrun)?{payrun:Ip(t.payrun,["name","payrunType","status","periodStartDate","periodEndDate","paymentDate","currencyCode"])}:{},...Array.isArray(t.generatedDocuments)?{generatedDocuments:t.generatedDocuments}:{}}))}}function O4(e){if(!Ps(e.data))return e;let t=ua(e.data.errors),r=[],n={};for(let[i,o]of Object.entries(e.data))i==="errors"?n.errors=vye(t,s=>s):i==="payouts"&&Array.isArray(o)?t.length>0?n.payoutCount=o.length:(n.payouts=x4(ua(o).map(s=>Ip(s,["payslipResourceId","employeeResourceId","employeeName","netPayAmount","paidAmount","owedAmount","payoutAmount"]))),r.push(typeof e.data.paymentAccountName=="string"?"Each payout debits netPayAccountName and credits paymentAccountName for payoutAmount.":"Each payout debits netPayAccountName for payoutAmount. No payment account was named: its checks wait for one.")):n[i]=o;return k4({data:n},r)}function Cut(e){let t=ua(e.data).map((i,o)=>({rowIndex:o+1,...i})),r=t.filter(i=>yye(i)!==void 0),n=t.filter(i=>yye(i)===void 0);return{createdCount:n.length,failedCount:r.length,...r.length>0?{byErrorCode:wye(r)}:{},data:[...r,...n]}}var XB,yA,cut,XDr,ZDr,eRr,Ps,ua,x4,tRr,nRr,yye,sut,Eye,N4,dut,HE,fut,iRr,oRr,sRr,aut,Sv,KB,YE,hut,Iye,mut,Aut,cRr,lRr,Aye,gye,bye,Dye,dRr,fRr,_ut,wut=J(()=>{"use strict";JB();out();XB="result exceeded the size cap; search_payslips with payrunResourceId and offset pages the payslips, get_payslip reads one with its lines",yA="result exceeded the size cap; the counts by error code cover every row, and search_employees names one by employeeResourceId",cut="result exceeded the size cap; the counts cover every employee, and search_employees names one by employeeResourceId",XDr="Payslip rows are not listed here: get_payrun has them.",ZDr="Payslips are rows without lines: get_payslip reads one with its lines and line ids.",eRr="Payouts are listed instead of payslips: get_payrun without payouts lists the payslips. A payout's journalResourceId is a cash-out record, not a journal: get_cash_out reads it and names the account it was paid from, until the payout is voided.",Ps=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ua=e=>Array.isArray(e)?e.filter(Ps):[];x4=e=>({totalElements:e.length,data:e});tRr=["resourceId","employeeResourceId","employeeName","grossAmount","deductionAmount","netPayAmount","employerContributionAmount","paidAmount","payoutStatus","prorated"];nRr=e=>Ip(e,["journalResourceId","employeeResourceId","employeeName","amount","valueDate","status","voidable"]);yye=e=>typeof e.errorCode=="string"?e.errorCode:typeof e.code=="string"?e.code:void 0;sut=["partialFailures","skipped"];Eye=e=>typeof e.note=="string"?[e.note]:[];N4=e=>Sye(e,"payslips"),dut=e=>Sye(e,"payouts"),HE=e=>Sye(e,"none");fut=e=>WB(e,"skipped","added"),iRr="The employees that would be added are only counted here: preview_populate_payrun with added true lists them.",oRr="Skipped employees are only counted here: preview_populate_payrun without added lists them. The employees listed under added are the ones populate_payrun would add.",sRr=e=>Ip(lut(e),["employeeResourceId","employeeName","payProfileResourceId"]);aut={paySetupLines:"Rebuilt from current pay (origin PROFILE). An amount changed by hand on one is replaced, and nothing marks a hand edit.",linesAddedByHand:"Kept as they are (origin MANUAL)."},Sv={paySetupLines:{effect:aut.paySetupLines},linesAddedByHand:{effect:aut.linesAddedByHand}},KB=(e,t)=>Array.isArray(e.partialFailures)&&e.partialFailures.length>0?{partialFailures:e.partialFailures,...t}:t,YE=e=>typeof e=="number"&&Number.isFinite(e),hut=(e,t,r,n=":")=>`${e}${n} ${VB(t)} to ${VB(r)}`,Iye=[["netPayAmount","Net pay"],["grossAmount","Gross pay"],["deductionAmount","Deductions"],["employerContributionAmount","Employer contribution"]],mut=(e,t)=>Iye.every(([r])=>e[r]===void 0&&t[r]===void 0||YE(e[r])&&YE(t[r]))&&Iye.some(([r])=>YE(e[r])&&YE(t[r])),Aut=(e,t,r=":")=>Iye.flatMap(([n,i])=>{let o=e[n],s=t[n];return YE(o)&&YE(s)&&o!==s?[hut(i,o,s,r)]:[]}),cRr=e=>Ps(e)&&typeof e.resourceId=="string"&&YE(e.amount),lRr={PROFILE:"pay setup",MANUAL:"added by hand"},Aye=e=>{let t=typeof e.origin=="string"?lRr[e.origin]:void 0,r=[typeof e.description=="string"&&e.description!==""?e.description:void 0,t].filter(Boolean).join(", ");return`${typeof e.payTypeName=="string"&&e.payTypeName!==""?e.payTypeName:"Line"}${r?` (${r})`:""}`},gye=e=>JSON.stringify([e.payTypeId,e.origin,e.description]);bye=(e,t)=>({...e,partialFailures:[...Array.isArray(e.partialFailures)?e.partialFailures:[],t]});Dye=5e4,dRr=1500,fRr=8;_ut=e=>({...e,data:ua(e.data).map(_ye)})});async function B4(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function zE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function F4(e,t){return e.post("/api/v1/scheduled/subscriptions",t,oh)}async function L4(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 zE(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 hRr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function hRr(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 P4(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function Q4(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 M4(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var U4=J(()=>{"use strict";Ht()});async function $4(e,t){return e.list("/api/v1/contact-groups",t)}async function q4(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function j4(e,t){return e.search("/api/v1/contact-groups/search",t)}async function Y4(e,t){return e.post("/api/v1/contact-groups",t)}async function H4(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,Jb(r,fte))}async function z4(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var Rye=J(()=>{"use strict";en()});async function J4(e,t){return e.list("/api/v1/inventory-items",t)}async function G4(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function V4(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function K4(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof sr&&n.status===404&&mRr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var W4,mRr,Tye=J(()=>{"use strict";qi();W4=["ALL","AVAILABLE","FULLY_DRAWN"],mRr=/Inventory balance Not Found/i});async function X4(e,t){return e.list("/api/v1/custom-fields",t)}async function ZB(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function Z4(e,t){return e.search("/api/v1/custom-fields/search",t)}async function e3(e,t){return e.post("/api/v1/custom-fields",t)}function gRr(e){return e!==void 0&&ARr.every(t=>e[t]!==void 0)}function yRr(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 ERr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function t3(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!gRr(n.appliesTo)){let i=await ZB(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??ERr(i.data),n.appliesTo={...yRr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function r3(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var ARr,xye=J(()=>{"use strict";ARr=["invoices","bills","customerCredits","supplierCredits","payments"]});var ll,JE,IRr,bRr,kye,n3,i3,_Rr,Fa,pu,GE,Dv,VE,Nye=J(()=>{"use strict";ll={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"]},JE={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."}}},IRr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},bRr={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"]},kye={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"]},n3={type:"object",properties:{billingAddress:{...kye,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},i3={type:"object",properties:{billingAddress:{...kye,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...kye,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},_Rr={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"]},Fa={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:_Rr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},pu={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)."}}},GE={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"]},Dv={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...ll,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:JE},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:{...ll,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:{...IRr,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:{...bRr,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:{...n3,description:"Issuer identity and billing address (credit from)."},creditTo:{...i3,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...ll,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:JE},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:{...ll,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:{...n3,description:"Seller identity and billing address."},billTo:{...i3,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:{...ll,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:JE},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:{...ll,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:{...ll,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:JE},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:{...ll,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...n3,description:"Seller identity and billing address."},billTo:{...i3,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:{...ll,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:JE},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:{...ll,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:{...n3,description:"Seller identity and billing address."},billTo:{...i3,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:JE},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:{...ll,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:JE},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:{...ll,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)."}}},VE={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:Fa},discount:{...pu,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:{...GE,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:Fa},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:Fa},discount:{...pu,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:Fa},discount:{...pu,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:Fa},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:Fa},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:Fa},discount:{...pu,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:{...GE,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:Fa},discount:{...pu,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:{...GE,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:Fa},description:{type:"string",description:"Line item description or memo."},discount:{...pu,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:{...GE,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:Fa},discount:{...pu,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:Fa},discount:{...pu,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:Fa},description:{type:"string",description:"Line item description or memo."},discount:{...pu,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:{...GE,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:Fa},description:{type:"string",description:"Line item description or memo."},discount:{...pu,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:{...GE,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:Fa},discount:{...pu,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:{...GE,description:"Withholding tax details for this line item."}}}}});function Bye(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function Fye(e){let t=e.updated??[],r=Bye(e.failed);return{...t.length===0&&r.length>0?{error:vRr}:{},updated:t,failed:r}}function Sut(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function Dut(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=Sut(s);if(a)for(let c of Array.isArray(o)?o:[o])Qh(c)&&n.push(...Dut(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function SRr(e){return Object.entries(e).map(([t,r])=>{let n=Sut(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function Lye(e,t,r){if(!Qh(t))return;let n=Dut(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw rt(new at(`${e} has no field ${i.join("; ")}. Fields: ${SRr(r)}. Nothing was changed.`))}function DRr(e){let t=Dv[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 RRr(e){let t=VE[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 TRr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!Qh(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw rt(new at(`${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(!Qh(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw rt(new at(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));Lye(`${e} line items`,a.attributes,t.fields)}}}function Rut(e){if(Rv.includes(e))return;let t=s3.includes(e);throw rt(new at(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: ${Rv.join(", ")}.`))}async function xv(e,t,r){Rut(t),Lye(`${t} quick fix`,r.attributes,DRr(t));let n=await e.post(`/api/v1/quick-fix/${Oc(Rv,t)}`,r);return Fye(n)}async function xRr(e,t){try{return await BE(e,t)}catch(r){if(r instanceof sr&&r.status===404)return FE(e,t);throw r}}async function Tut(e,t,r,n){Rut(t);let i=Pye[t],o=async d=>i.tags(await zo(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=vut)s.push(...await Promise.all(r.resourceIds.slice(d,d+vut).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=Zi(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 xv(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 Fye({updated:c,failed:u})}async function eF(e,t,r){let n=Oc(Tv,t),i=RRr(t);i.entryKeys?TRr(t,i,r.schedulerUpdates):Lye(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return Fye(o)}var CRr,wRr,o3,s3,Rv,Tv,vRr,WE,Oye,Pye,vut,a3=J(()=>{"use strict";qi();it();Xi();Nye();Ul();oy();If();xk();Lk();sy();KV();l8();U4();Lie();CRr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],wRr=["journals","cash-entries"],o3=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],s3=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],Rv=[...CRr,...wRr,...o3],Tv=[...Rv,...s3],vRr="Nothing changed: every record failed. See failed for each reason.";WE=e=>e?.tags,Oye=e=>e?.data?.tags,Pye={invoices:{noun:"invoice",get:(e,t)=>Eo(e,t),tags:WE},bills:{noun:"bill",get:(e,t)=>po(e,t),tags:WE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>ta(e,t),tags:WE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>ra(e,t),tags:WE},journals:{noun:"journal",get:(e,t)=>Rs(e,t),tags:WE},"cash-entries":{noun:"cash entry",get:(e,t)=>xRr(e,t),tags:WE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>mv(e,t),tags:Oye},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Av(e,t),tags:Oye},"subscription-schedules":{noun:"subscription",get:(e,t)=>zE(e,t),tags:Oye},"journal-schedules":{noun:"journal schedule",get:(e,t)=>gv(e,t),tags:WE}},vut=10});function c3(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=c3(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<NRr&&i.length<=ORr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,c3(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function kut(e,t,r){let n=BRr(t);if(!n)return[];let i=FRr(r);if(!i){if(xut[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]?kut(o,s,i[o]):[])}function LRr(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 Qye(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 I=PRr(e[y][c]);d.set(I,[...d.get(I)??[],y])}let[[,f],...p]=[...d].sort((y,I)=>I[1].length-y[1].length),{description:h,...m}=r[c]??c3(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=>c3(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[xut[c],LRr(u,n),...p.map(([,y])=>{let I=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(I.properties??I.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[I,E]of kut(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(I))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function Fut(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>kRr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var kRr,xut,NRr,ORr,BRr,FRr,PRr,QRr,MRr,kv,Nut,Out,But,Lut,Put,Qut,Mye=J(()=>{"use strict";Nye();Ul();kRr={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"},xut={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:`${Ho.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.'},NRr=2,ORr=8;BRr=e=>e.properties??e.items?.properties,FRr=e=>e.properties??e.items?.properties;PRr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),QRr={tags:Ho};MRr=Object.entries(VE).filter(([,e])=>!e.entryKeys),kv=Object.entries(VE).filter(([,e])=>e.entryKeys),Nut=Qye({...Dv},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",QRr),Out=Qye(Object.fromEntries(MRr.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."),But=(()=>{let e=n=>kv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=kv[0],r=[...new Set(kv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>kv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${kv.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:Qye(Object.fromEntries(kv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Lut=[...new Set([...Object.keys(Dv),...Object.keys(VE)])].map(e=>e.replace(/-/g," ")).join(", "),Put=Fut(Object.values(Dv)),Qut=Fut(Object.values(VE).map(e=>e.fields))});function l3(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var Uye=J(()=>{"use strict"});function d3(){return EA.map(e=>`${e} sets ${Ov[e].change.join(", ")}`).join("; ")}function zut(e){let t={};for(let r of e)t[r]=Object.hasOwn(Uut,r)?Uut[r]:qRr.find(([n])=>n.test(r))?.[1]??jRr;return Object.keys(t).length>0?t:void 0}function Jut(e){if(!(e instanceof sr)||!e.endpoint.startsWith($Rr))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($ut,n))return;let{hint:i,repairTool:o,command:s}=$ut[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===Yut.LINE_ITEMS?"line items":"records",...e.endpoint===u3?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function zRr(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 JRr(e){return typeof e=="string"&&EA.includes(e)}function GRr(e,t){if(!JRr(e))throw new at(`level must be one of ${EA.join(", ")}.`);let r=EA.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))Ov[e][i].includes(s)||n.push(Ov[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}=Ov[e];throw new at(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function qut(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 at(`${e} must be a JSON object, not ${n}.`)}async function p3(e,t,r){let n={filter:qut("filter",r.filter),change:qut("change",r.change)};GRr(t,n);let i;try{i=await e.post(Yut[t],{filter:n.filter,change:n.change},Ge)}catch(u){throw Jut(u),u}let{data:o,...s}=i,a=zut([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=zRr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function qye(e,t){return{error:`${t} ${Vut}`,outcome:"UNKNOWN",previewId:e,next:Gut}}function KRr(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 qye(e,"The apply answered without a per-record result.");let i=Bye(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=zut(Object.keys(o)),a=o[YRr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:WRr}:a==="UNKNOWN"?{error:Vut}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Gut:VRr},failed:i.slice(0,$ye),...i.length>$ye?{failedNotShown:i.length-$ye}:{},data:r}}async function h3(e,t,r=HRr){let n;try{n=await e.post(u3,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof sr){let s=Jut(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw rt(i);return qye(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof ih)throw rt(i);let o=i instanceof Error?i.message:String(i);return qye(t,`No answer arrived from the apply (${o}).`)}return KRr(t,n)}var jut,EA,Yut,u3,$Rr,Hut,Mut,Ov,Uut,qRr,jRr,YRr,HRr,f3,$ye,Bv,vun,Nv,$ut,Gut,VRr,WRr,Vut,jye=J(()=>{"use strict";qi();a3();rM();it();Xi();Ht();Uye();jut=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],EA=["TRANSACTIONS","LINE_ITEMS"],Yut={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},u3="/api/v1/ledger/find-fix/apply",$Rr=u3.slice(0,u3.lastIndexOf("/")+1),Hut={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"}},Mut=["types","resourceIds","reference","valueDate","contactResourceId"],Ov={TRANSACTIONS:{filter:Mut,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Mut,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Uut={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."},qRr=[[/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."]],jRr="Not described by this client version; read the records that carry it.";YRr="OUTCOME_UNKNOWN",HRr=25e3,f3=3e5,$ye=50,Bv=12,vun=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${Bv}}(?![A-Za-z0-9_-])`,"i"),Nv=e=>e.resourceId?` (${e.resourceId})`:"",$ut={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${Nv(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${Nv(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${Nv(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${Nv(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${Nv(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${Nv(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."}};Gut="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.",VRr="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.",WRr="Nothing changed: every record in the preview failed.",Vut="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function m3(e,t){return e.list("/api/v1/nano-classifiers",t)}async function KE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function A3(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function tF(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function rF(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function g3(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await XRr(e,t):{};let{data:n}=await KE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Kut(n)}async function XRr(e,t){let{data:r}=await KE(e,t);return Kut(r)}function Kut(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function y3(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}function Xut(e,t="classifierConfig"){if(e==null)return;if(!(Array.isArray(e)&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.resourceId=="string")))throw rt(new at(`${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 Zut(e,t){let r=new Map((Array.isArray(e)?e:[]).map(n=>[n?.resourceId,IM(n)]));for(let n of t)n.deleted===!0?r.delete(n.resourceId):r.set(n.resourceId,IM(n));return[...r.values()]}var Wut,Yye=J(()=>{"use strict";Xi();it();yf();Wut=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function E3(e,t){return e.post("/api/v1/export-records",t,Ge)}async function I3(e,t){return e.post("/api/v1/export-records/preview",t,Ge)}async function b3(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var Hye=J(()=>{"use strict";Ht()});function _3(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function ndt(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 C3(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 w3(e,t,r){return _3(t,tdt),eo(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Oc(bp,t)}/${encodeURIComponent(r)}/approve`,void 0,tBe)}async function v3(e,t,r){return _3(t,tdt),ndt(r,ZRr,"bulk approve",!0),r.forEach(n=>eo(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Oc(bp,t)}/bulk-approve`,{resourceIds:r},rBe)}async function S3(e,t,r,n){_3(t,rdt),eo(r,"resourceId","Pass the document resourceId."),idt(n);let i=await e.post(`/api/v1/${Oc(XE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:rTr(i)}}}async function D3(e,t,r,n){return _3(t,rdt),idt(n),ndt(r,eTr,"bulk request changes"),r.forEach(i=>eo(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(tTr(t),{resourceIds:r,message:n})}function tTr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Oc(edt,e)}/bulk-request-changes`}function idt(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 rTr(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 bp,edt,XE,tdt,rdt,ZRr,eTr,zye=J(()=>{"use strict";it();Ht();bp=["invoices","bills","customer-credit-notes","supplier-credit-notes"],edt=[...bp,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],XE=[...edt,"claims"],tdt=new Set(bp),rdt=new Set(XE);ZRr=100,eTr=500});function nTr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${odt(t)}:${odt(r)}:${n}`}function odt(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function Jye(e){if(!sdt.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...sdt].join(", ")}`)}async function adt(e,t,r){return Jye(t),eo(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function cdt(e,t,r,n){return Jye(t),eo(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function ldt(e,t,r,n,i){if(Jye(t),eo(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??nTr(t,r,n)}})}async function udt(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var sdt,ddt=J(()=>{"use strict";it();sdt=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function iTr({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 at(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new at("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new at(`${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 at(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function R3(e,t,r){let n=e.length;if(iTr(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 at(`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 Fv(e,t={},r=nF){let n=e.data,i=ZE(n.rows),{start:o,end:s,window:a}=R3(Gye(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function T3(e,t={},r=nF){let n=e.data,i=ZE(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}=R3(Gye(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 fdt(e,t,r,n,i){let o=e.data,s=ZE(o[t]),a=s.reduce((h,m)=>h+ZE(m[r]).length,0),{start:c,end:u,window:d}=R3(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=ZE(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 Td(e,t={},r=nF){let n=e.data,i=ZE(n.periods),{start:o,end:s,window:a}=R3(Gye(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:ZE(n.timeline).filter(d)}}}var nF,ZE,Gye,x3,k3,Lv=J(()=>{"use strict";Xi();nF=60;ZE=e=>Array.isArray(e)?e:[],Gye=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);x3=(e,t={},r=nF)=>fdt(e,"depreciationScheduled","depreciation",t,r),k3=(e,t={},r=nF)=>fdt(e,"amortizationScheduled","amortization",t,r)});async function N3(e,t,r={}){return pdt(t,"depositContactType"),e.list("/api/v1/deposit-accounts",r,{depositContactType:t})}async function O3(e,t){return t.forEach((r,n)=>{if(!r||typeof r!="object"||!("depositContactType"in r))throw rt(new ue(`accounts[${n}].depositContactType is required: CUSTOMER, SUPPLIER, or null to unflag the account. Nothing was changed.`));if(r.depositContactType===null){if(r.restrictPaymentOverdraft===!0)throw rt(new ue(`accounts[${n}].restrictPaymentOverdraft can only be true when depositContactType is CUSTOMER or SUPPLIER. Nothing was changed.`));return}if(pdt(r.depositContactType,`accounts[${n}].depositContactType`),typeof r.restrictPaymentOverdraft!="boolean")throw rt(new ue(`accounts[${n}].restrictPaymentOverdraft is required (true or false) when flagging: the platform overwrites the stored value on every call. Nothing was changed.`))}),e.put("/api/v1/deposit-accounts",{accounts:t},sBe)}function pdt(e,t){if(!Pv.includes(e))throw rt(new ue(`${t} must be CUSTOMER or SUPPLIER, got ${JSON.stringify(e)}. Nothing was changed.`))}var Pv,Vye=J(()=>{"use strict";it();Ht();Pv=["CUSTOMER","SUPPLIER"]});async function eI(e,t){return e.get(`/api/v1/loans/${t}`)}async function B3(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function F3(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function L3(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},hBe)}async function P3(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 eI(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function Q3(e,t){await e.delete(`/api/v1/loans/${t}`)}async function M3(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},ite)}async function U3(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},ite)}async function $3(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function q3(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function j3(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function Y3(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function H3(e,t){return e.post("/api/v1/loans/preview-schedule",t,Ge)}async function z3(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,Ge)}async function J3(e,t){return ut(t,"loans",500,"loans"),Yo(t,hdt),bn(e,"/api/v1/loans/bulk-upsert","loans",t)}async function G3(e,t){return ut(t,"loans",500,"loans"),Yo(t,oTr),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw rt(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.`))}}),bn(e,"/api/v1/loans/bulk-update","loans",t)}async function V3(e,t,r,n,i){let o=iF[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},Ge)}return e.post(o.record(r),{...n,resourceId:r},mBe)}var hdt,oTr,iF,Wye=J(()=>{"use strict";en();it();Ht();hdt=["drawdownDate","trackingStartDate","firstRepaymentDate"],oTr=[...hdt,"capitalizationStartDate","capitalizationEndDate"];iF={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 Qv(e){ut(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(!s1e(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!sTr.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 W3(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},Ge);return{data:cTr(r.data)}}function aTr(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 cTr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(aTr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function K3(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function X3(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var sTr,Kye=J(()=>{"use strict";it();rre();en();Ht();sTr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function ydt(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 Xye(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.`);Yo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&Yo([i],["valueDate"])}async function e9(e,t,r=Zye){return e.post("/api/v1/search-magic-reconciliation",t,{...Ge,timeoutMs:r})}function Z3(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function fTr(e){let t=Z3(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=Z3(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function pTr(e){return e?e.value>=(e.from==="confidenceScore"?lTr:uTr)?"high":e.value>=dTr?"medium":"low":"low"}function mTr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(mdt,t))return;let r=mdt[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function IA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function Adt(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function ATr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>Adt({account:IA(n?.account),taxProfile:IA(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(!(!IA(e.contact)&&!IA(e.account)&&!IA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return Adt({contact:IA(e.contact),account:IA(e.account),taxProfile:IA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function Edt(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=>bTr(c,h??{},u.length-1,t)).sort(gTr),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 gTr(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 yTr(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return Nc.test(t)?t:void 0}function ETr(e){let{recommendationId:t,...r}=e;return r}function ITr(e,t,r){return!t||!r?t:e===tI.learnedPrediction?{...t,recommendationId:r}:e===tI.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function bTr(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=Z3(t.matchScore),s=Z3(t.confidenceScore),a=fTr(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=tI.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=tI.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=tI.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=tI.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=ITr(m,A,yTr(t)),y=m?pTr(a):"low",I=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||I&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==tI.withPayments||I,T=mTr(t),D=!m||!g?"NO_PLAN":T?hTr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!I?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",N=ATr(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}:{},...N?{proposedPosting:N}:{},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(ETr(t))}`}}function _Tr(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 CTr(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 po(e,i):await Eo(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${cl(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function Idt(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,gdt);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 b_(e,t,{filter:{resourceId:{in:u}},limit:gdt}),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: ${cl(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 _Tr(u,f,await CTr(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function t9(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,Ks)}async function r9(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,Ks)}async function n9(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,Ks)}async function i9(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,Ks)}async function o9(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,Ks)}async function s9(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,Ks)}async function a9(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,Ks)}async function c9(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,Ks)}async function l9(e,t){return e.post("/api/v1/reconciliations/with-payments",t,Ks)}async function u9(e,t){return e.post("/api/v1/reconciliations/match-to-transaction",t,Ks)}async function d9(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,Ks)}async function f9(e,t){return e.post("/api/v1/reconciliations/magic-match",t,Ks)}async function p9(e,t){return e.post("/api/v1/reconciliations/reset",t)}var tI,Zye,lTr,uTr,dTr,hTr,mdt,gdt,h9=J(()=>{"use strict";Ug();yp();it();If();en();oy();Ht();tI={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Zye=6e4;lTr=.9,uTr=.95,dTr=.7;hTr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},mdt={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};gdt=25});function da(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 Mo(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:eEe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=eEe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=eEe(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,I=a.debitAmount,E=a.creditAmount,C=a.type??(typeof I=="number"&&I>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 eEe(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 rs(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=da(e,t,n),a=Mo(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 La,ul,vo,hu,bdt=J(()=>{"use strict";La=[{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}],ul=[...La],vo=La.filter(e=>e.field!=="dueDate"),hu=[{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 xd(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=xc(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function m9(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=Kb(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var _dt=J(()=>{"use strict";yf()});var tEe=J(()=>{"use strict";bdt();yf();_dt()});var oF,A9,Ji,so,rEe=J(()=>{"use strict";oF="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",A9=["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"],Ji="If the result says it runs in the background, do not poll: its result arrives by itself.",so=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${Ji} PARTIAL_SUCCESS: errorDetails.`});function wdt(e){return wTr.get(e)}function vdt(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&&!g9.has(o));return n.length===0?[]:Pi.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 Pi,Cdt,g9,wTr,kd=J(()=>{"use strict";rEe();Mye();Pi=[{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. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). To find specific transfers, use cashflow transaction search (payments_and_search namespace). 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). Deposit accounts: list and flag customer or supplier deposit accounts. 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 (expense claims only, not payroll; payrun posting rules are in payrun_settings): 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 (not payroll, see payrun_processing): 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, and the people on pay runs): 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 ${Lut}. On a record: ${Put}. On lines: ${Qut}. 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, ${A9.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"]},{name:"payrun_settings",title:"Payrun Settings",description:"Payrun setup for employee payroll: pay types (what is paid or deducted on a payslip: salary, overtime, allowance, bonus, deduction, employee or employer tax and contribution, each with its accounts), payrun posting rules (how a payrun books its journal: net pay account, grouping, journal date, reference; one default) and pay profiles (shared pay templates: pay frequency, currency, posting rule, pro-rate method, pay type lines with amounts or left per employee). Search, create, update, delete each; get one. Not claim posting rules (posting_rules) and not expense claims.",groups:["pay_types","payrun_posting_rules","pay_profiles"]},{name:"employee_pay",title:"Employee Pay",description:"Employee pay details: put an employee on a pay profile from a date with their own pay figures (salary), one or many at once. A raise is a new pay detail from the new date, not an edit. Search pay details and pay history, in force on a day; correct one in place or end an employee's pay.",groups:["employee_pay_details"]},{name:"payruns",title:"Payruns",description:"Employee pay runs: one run for a period, one pay frequency and one currency, holding a payslip per employee. Create (REGULAR or OFF_CYCLE, fill from pay profiles at once or later), search, get, edit and delete a draft, delete several drafts at once, add or remove employees, fill from pay profiles (with a preview), and save a payslip's lines by hand. Not expense claims.",groups:["payruns"]},{name:"payslips",title:"Payslips",description:"Payslips of employee pay runs: search across runs (an employee's payslips, a run's payslips), get one with its lines and PDF link, rebuild one or several draft payslips from current pay, and make the PDFs of a finalized run again. Lines are edited with save_payrun_lines.",groups:["payslips"]},{name:"payrun_processing",title:"Payrun Processing",description:"Process employee pay runs: validate a draft and preview its journal, finalize payruns (posts one journal each; one or several at once), unpost a finalized run back to draft to correct it, void a run for good with a reason, and record payouts already paid outside Jaz (preview first; part amounts allowed; books only, no money moves) and void a recorded payout. Not expense claims.",groups:["payrun_processing"]}],Cdt=[{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."}],g9=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"]),wTr=new Map(Pi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function Nd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function vTr(e){let t=Sdt.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(Nd(r),n);for(let r of e.enum??[])t.set(Nd(r),r);Sdt.set(e,t)}return t}function Ddt(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=Nd(e);if(!r)return null;let n=vTr(t).get(r);return n!==void 0&&n!==e?n:null}function STr(e){let t=Rdt.get(e);return t||(t=new Map(Object.keys(e).map(r=>[Nd(r),r])),Rdt.set(e,t)),t}function DTr(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 RTr(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 nEe(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=STr(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=Nd(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"?DTr(d):RTr(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=Ddt(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,I)=>{let E=Ddt(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${I}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=ure(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let I=nEe(y,m.schema,`${r}${f}[].`,n);return I!==y&&(A=!0),I});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=nEe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Tdt(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:nEe(t,e.params,"",r),coercions:r}}function xdt(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 Sdt,Rdt,iEe=J(()=>{"use strict";R$();Sdt=new WeakMap;Rdt=new WeakMap});function Mv(e){let t=new Set,r=[];for(let n of e)for(let i of mu(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function sF(){return Pi.map(e=>{let t=Mv(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 TTr(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 xTr(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 bA(e,t=!1){let r=_A(void 0).length,n=Pi.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:xTr(r)}:e&&i!==void 0?{packaging:TTr(e,i,r)}:{},map:sF(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var y9=J(()=>{"use strict";kd();Au()});function E9(e){let t={type:e.nullable?[e.type,"null"]:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.nullable?[...e.enum,null]:e.enum),e.type==="array"&&e.items&&(t.items=E9(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=E9(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function gu(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=E9(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function aF(e){return{name:e.name,description:e.description,input_schema:gu(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var Uv=J(()=>{"use strict"});function cF(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 oEe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function I9(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&cF(e),idempotentHint:e.readOnly,openWorldHint:oEe(e)}}function NTr(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function OTr(e){let t=NTr(e);return!t||kTr.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!g9.has(n)).length===0}function sEe(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 aEe(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?aEe(o,`${i}.`):[]]})}function FTr(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
662
|
+
`)),null)}catch{return null}}async function kB(e,t,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??jSr,c=n.minBm25??YSr;if(i==="bm25"||!t)return LE(e,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Nge(r);return m?Zct(e,t,m,{limit:o,section:s}).filter(g=>g.score>=a):LE(e,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Nge(r),Promise.resolve(LE(e,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Zct(e,t,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return rlt(p,h,o)}function Zct(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=elt(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 rlt(e,t,r){let n=new Map;for(let o=0;o<e.length;o++){let s=e[o],a=1/(Wct+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/(Wct+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 Oge(e){return e!==null&&!!tlt()}var $Sr,qSr,Wct,jSr,YSr,d8,Kct,f8,Xct,p8=J(()=>{"use strict";TB();$Sr="text-embedding-3-small",qSr=2e3,Wct=60,jSr=.3,YSr=1.5,d8=null,Kct=null,f8=null,Xct=!1});async function nlt(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=DB();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:xB(),u=await kB(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=(xge(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 ilt(){let e=process.env.CLIO_HELP_CENTER_URL?.trim();return e&&e.length>0?e:zSr}async function h8(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(ilt())}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(JSr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return GSr(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 GSr(e){if(typeof e!="object"||e===null)return!1;let t=e;return Array.isArray(t.results)?!0:typeof t.error=="string"}async function Bge(e,t={}){return process.env.CLIO_DAEMON==="1"||RB()?nlt(e,t):h8(e,t)}var zSr,JSr,olt=J(()=>{"use strict";TB();p8();zSr="https://mcp.jaz.ai/help-center/search",JSr=4e3});var Fge=J(()=>{"use strict";TB();p8();olt();TB()});async function fA(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function pA(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var NB=J(()=>{"use strict";en()});async function m8(e,t){return e.post("/api/v1/transfer-trial-balance",{...t,currency:Zt(t.currency),taxCurrency:Zt(t.taxCurrency)},EBe)}var Lge=J(()=>{"use strict";it();Ht()});async function A8(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function g8(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function OB(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function y8(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var Pge=J(()=>{"use strict"});function VSr(e){let{refs:t,...r}=e;return t?{...r,refs:t.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function yv(e,t){return e.post("/api/v1/jots",{entries:t.map(VSr)})}async function E8(e,t){return e.post("/api/v1/jots/search",t,Ge)}async function slt(e,t,r){return e.post(`/api/v1/jots/${t}/disposition`,r)}var I8=J(()=>{"use strict";Ht()});async function alt(e,t){return e.post("/api/v1/agents/memories",t)}async function Qge(e,t){return e.post("/api/v1/agents/memories/forget",t)}var clt=J(()=>{"use strict";Ht()});function b8(){return process.env.ENABLE_MEMORY==="true"}function Mge(){return process.env.ENABLE_MEMORY_CHAT==="true"}function llt(e){return!b8()||!e||!e.progressive?"memory_disabled":e.isInboxOwner?null:"not_owner"}var Uge=J(()=>{"use strict"});import{createHash as WSr}from"node:crypto";function aDr(e){if(!e||!e.trim())return[null,"directive_required"];let t=e.normalize("NFKC").trim();return t.length>300?[null,"directive_too_long"]:flt.some(r=>t.includes(r))?[null,"directive_invalid"]:dlt.test(t)?[null,"directive_invalid"]:rDr.test(t)?[null,"directive_contains_url"]:nDr.test(t)?[null,"directive_contains_email"]:[t,null]}function cDr(e){if(e==null)return[null,null];let t=e.normalize("NFKC").trim();return t?t.length>iDr?[null,"match_condition_too_long"]:flt.some(r=>t.includes(r))?[null,"match_condition_invalid"]:dlt.test(t)?[null,"match_condition_invalid"]:[t,null]:[null,"match_condition_invalid"]}function lDr(e){return e==null?[null,null]:Number.isInteger(e)?e<oDr||e>sDr?[null,"invalid_importance"]:[e,null]:[null,"invalid_importance"]}function uDr(e,t,r,n,i,o,s,a){if(e)return WSr("sha256").update(`${e}:${t}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function dDr(e){Promise.resolve().then(()=>(QD(),PD)).then(({log:t})=>t.info(e,"memory_tool.call")).catch(()=>{})}async function Alt(e,t,r){let n=t.action,i=t.category,o=eDr[t.scope??"this_org"]??"ORG_USER",s=typeof t.key=="string"?t.key.trim():"",a=null,c=d=>(dDr({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=llt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>KSr||!tDr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[I,E]=aDr(t.directive);if(E)return u(E);p=I;let[C,w]=lDr(t.importance);if(w)return u(w);h=C}let[m,A]=cDr(t.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=XSr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let I={gtid:g};d.quote&&(I.quote=d.quote.slice(0,ZSr));let E=uDr(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:I,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await $ge(()=>alt(e.client,C)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let I={category:i,key:s,scope:o};y=await $ge(()=>Qge(e.client,I))}else{let I={forgetAll:!0};y=await $ge(()=>Qge(e.client,I))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function $ge(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 sr?t.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${t.status}`}:{ok:!1,reason:"network_error"}}}var dlt,flt,KSr,XSr,ZSr,plt,hlt,mlt,eDr,tDr,rDr,nDr,iDr,oDr,sDr,glt=J(()=>{"use strict";clt();qi();Uge();Uge();dlt=/[\x00-\x1f\x7f]/,flt=["{{","}}","```","<",">"],KSr=120,XSr=3,ZSr=140,plt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],hlt=["set","forget","forget_all"],mlt=["this_org","all_orgs"],eDr={this_org:"ORG_USER",all_orgs:"USER"},tDr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,rDr=/https?:\/\//i,nDr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,iDr=255,oDr=0,sDr=100});async function _8(e,t){return e.list("/api/v1/organization-users",t)}async function C8(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 w8(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function v8(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var qge=J(()=>{"use strict"});async function S8(e,t){return e.get(`/api/v1/payments/${t}`)}async function D8(e,t,r){return e.put(`/api/v1/payments/${t}`,{...r,currency:Zt(r.currency)})}async function R8(e,t){await e.delete(`/api/v1/payments/${t}`)}function T8(e){return(t,r)=>t.post(`/api/v1/${fDr[e]}`,{...r,transactions:r.transactions.map(n=>({...n,currency:Zt(n.currency)}))},nBe)}var fDr,hcn,ylt,mcn,Acn,jge=J(()=>{"use strict";it();Ht();fDr={saleBulk:"sales/bulk-payments",saleBatch:"sales/batch-payments",purchaseBulk:"purchases/bulk-payments",purchaseBatch:"purchases/batch-payments"};hcn=T8("saleBulk"),ylt=T8("saleBatch"),mcn=T8("purchaseBulk"),Acn=T8("purchaseBatch")});async function Ap(e,t,r,n,i,o=yBe){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 sr?c.status<500&&c.status!==401?rt(c):new Dc(`${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 ih?rt(c):c}let a=s?.data;if(!i(a))throw new Dc(`${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 k8(e,t,r){try{eo(e,t,r)}catch(n){throw rt(n)}}function PE(e){return k8(e,"resourceId","Pass the unapplied payment resourceId from search_unapplied_payments."),encodeURIComponent(e)}async function N8(e,t){return e.search("/api/v1/batch-payments/search",{...t,origin:["UNAPPLIED"]})}async function O8(e,t){return Ap(e,"POST",pDr,t,hA)}async function B8(e,t,r){return Ap(e,"PUT",`/api/v1/unapplied-payments/${PE(t)}`,r,hA)}async function F8(e,t,r){return Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/activate`,{hash:r},hA)}async function L8(e,t,r,n){return Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/attributions`,{hash:r,attributions:n},hA)}async function P8(e,t,r,n){return k8(n,"paymentResourceId","Pass the payment record resourceId."),Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/payments`,{hash:r,paymentResourceId:n},hA)}async function Q8(e,t,r,n){return k8(r,"childResourceId","Pass the payment record resourceId from the children list."),Ap(e,"DELETE",`/api/v1/unapplied-payments/${PE(t)}/children/${encodeURIComponent(r)}`,{hash:n},hA)}async function M8(e,t,r){return Ap(e,"DELETE",`/api/v1/unapplied-payments/${PE(t)}`,{hash:r},hA)}async function U8(e,t,r){return Ap(e,"POST",`/api/v1/unapplied-payments/${PE(t)}/unbatch`,{hash:r},hA)}async function $8(e,t){return k8(t?.bankStatementEntryResourceId,"bankStatementEntryResourceId","Pass the bank record resourceId."),Ap(e,"POST",hDr,t,r=>typeof r?.unappliedPaymentResourceId=="string"&&r.unappliedPaymentResourceId.length>0,Ks)}var pDr,hDr,x8,Elt,Ilt,hA,Yge=J(()=>{"use strict";qi();Ht();rM();it();pDr="/api/v1/unapplied-payments",hDr="/api/v1/reconciliations/unapplied-payment",x8=["SALE","PURCHASE"],Elt=["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],Ilt=["AMOUNT","PERCENTAGE"];hA=e=>typeof e?.resourceId=="string"&&e.resourceId.length>0});async function q8(e,t,r={},n=Hge){let i=mDr.has(t)?`/api/v1/${Oc(blt,t)}`:`/api/v1/data-exports/${t}`,{template:o,...s}=r,a=iy.get(t);if(o!==void 0){if(!a)throw new ue(`${t} does not take a report template. Templates apply to: ${[...iy.keys()].join(", ")}.`);let A=await Mf(e,o,{reportType:a});s.templateResourceId=A.resourceId}let c=await e.post(i,s,{...Ge,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: ${[...BB].join(", ")}.`}:d}var blt,mDr,Hge,BB,_lt,zge=J(()=>{"use strict";Ht();it();wk();rd();blt=["statement-of-account-export"],mDr=new Set(blt),Hge=9e4,BB=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"]),_lt={"balance-sheet":{end:"snapshotDate"},cashflow:{start:"primaryStartDate",end:"primaryEndDate"},"equity-movement":{start:"primaryStartDate",end:"primaryEndDate"},"bank-closing-balance":{end:"reportDate"}}});import{createHash as ADr}from"node:crypto";import{writeFile as gDr,mkdir as yDr}from"node:fs/promises";import{dirname as EDr,isAbsolute as IDr,join as bDr}from"node:path";async function j8(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t},Ge)}async function FB(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 Iv(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function Clt(e){return`query-export-${e.slice(0,8)}.csv`}function Jge(e){return ADr("sha256").update(e).digest("hex").slice(0,16)}async function Y8(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Jge(t),o=await FB(e,t,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await Iv(e,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await Iv(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&&!IDr(r.outPath))throw new ue(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??bDr(f,"Downloads",`pseudo-sql-${s}.csv`);return await yDr(EDr(p),{recursive:!0}),await gDr(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 H8(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 bv(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 Gge=J(()=>{"use strict";it();Ht()});async function yi(e,t,r){let n=await e.get(`/api/v1/${z8[t]}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function J8(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/${z8[r]}/${n}/attachments`,o)}async function G8(e,t,r,n){return e.delete(`/api/v1/${z8[t]}/${r}/attachments/${n}`)}var z8,al,LB,mA=J(()=>{"use strict";z8={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"},al=Object.keys(z8),LB=["sale-quotes","sale-orders","purchase-requests","purchase-orders","fixed-assets","deferrals","leases","loans","cash-in-entries","cash-out-entries","cash-transfers"]});function RDr(e){let t=e.body?.error;return t?.error_type==="forbidden"&&Array.isArray(t.errors)&&t.errors.some(r=>typeof r=="string"&&DDr.some(n=>r.startsWith(n)))}async function gp(e){try{return await e}catch(t){throw t instanceof sr&&t.status===401&&RDr(t)&&(t.refusal=SDr),t}}function wlt(e,t,r){return eo(e,t,r),e.toLowerCase()}function _v(e,t){return{type:Oc(Vge,e,"entityType"),record:wlt(t,"entityId",_Dr)}}function PB(e){vte(e,"threadId",wDr)}function vlt(e){vte(e,"commentId",vDr)}function Cv(e){return e?.bankAccountResourceId===void 0?{}:{bankAccountResourceId:wlt(e.bankAccountResourceId,"bankAccountResourceId",CDr)}}async function Slt(e,t,r,n={}){let{type:i,record:o}=_v(t,r),s={...Cv(n),limit:n.limit,offset:n.offset,commentLimit:n.commentLimit};return gp(e.get(`/api/v1/collaboration/${i}/${o}/threads`,s))}async function Dlt(e,t,r,n,i={}){let{type:o,record:s}=_v(t,r),a={...Cv(i),limit:i.limit,offset:i.offset};return PB(n),gp(e.get(`/api/v1/collaboration/${o}/${s}/threads/${n}/comments`,a))}async function Rlt(e,t,r,n,i){let{type:o,record:s}=_v(t,r),a=Cv(i);return n.threadId!==void 0&&PB(n.threadId),(await gp(e.post(`/api/v1/collaboration/${o}/${s}/comments`,{content:n.content,threadId:n.threadId},{...gBe,query:a}))).data}async function Tlt(e,t,r,n,i,o,s){let{type:a,record:c}=_v(t,r),u=Cv(s);return PB(n),vlt(i),(await gp(e.put(`/api/v1/collaboration/${a}/${c}/threads/${n}/comments/${i}`,{content:o.content},{query:u}))).data}async function xlt(e,t,r,n,i,o){let{type:s,record:a}=_v(t,r),c=Cv(o);return PB(n),vlt(i),(await gp(e.delete(`/api/v1/collaboration/${s}/${a}/threads/${n}/comments/${i}`,c))).data}async function klt(e,t,r,n,i){let{type:o,record:s}=_v(t,r),a=Cv(i);return PB(n),(await gp(e.post(`/api/v1/collaboration/${o}/${s}/threads/${n}/resolve`,void 0,{query:a}))).data}async function Nlt(e,t={}){return gp(e.get("/api/v1/collaboration/notifications",{status:t.status,limit:t.limit,offset:t.offset}))}async function Olt(e,t,r){return yFe(t,"Get it from list_notifications."),(await gp(e.put(`/api/v1/collaboration/notifications/${encodeURIComponent(t)}`,{isRead:r}))).data}async function Blt(e){return(await gp(e.post("/api/v1/collaboration/notifications/read-all"))).data}var Vge,_Dr,CDr,wDr,vDr,SDr,DDr,Flt=J(()=>{"use strict";qi();it();Ht();Vge=["bills","invoices","supplier-credit-notes","customer-credit-notes","bank-records"],_Dr="Pass the resourceId of the bill, invoice, credit note or bank record.",CDr="Pass the resourceId of the bank account that holds the bank record.",wDr="Get it from list_comment_threads.",vDr="Get it from list_comments or list_comment_threads.",SDr={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."},DDr=["This endpoint acts as a user.","The caller identity could not be resolved."]});function Qo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var wv=J(()=>{"use strict"});async function V8(e,t){return e.post("/api/v1/claims/conversion/preview",t,Ge)}async function W8(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:dM)}var QB,Wge=J(()=>{"use strict";it();Ht();QB=["POST","POST_AND_RECORD"]});async function K8(e,t){if(!(t.amount>0))throw new ue("amount must be greater than 0.");return e.post("/api/v1/claims/payouts/record",t,iBe)}async function X8(e,t){return e.search("/api/v1/employees/payouts/search",t)}var Llt,Kge=J(()=>{"use strict";it();Ht();Llt=["REIMBURSEMENT","ADVANCE"]});async function Z8(e,t){return e.search("/api/v1/filing-submissions/search",t)}var Xge=J(()=>{"use strict"});function Zge(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 eye(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: ${Plt(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=>Gu.has(u)),s=i.filter(u=>!Gu.has(u)&&Fc.has(u)),a=[`Nothing here can be extracted: found ${Plt(r)}.`];for(let u of Object.keys(t.skippedReasons??{})){let d=wLe[u];d&&a.push(d)}return o.length>0&&a.push(`${WU(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(`${WU(s)} are not read by this route, but create_transaction_from_document accepts them one file at a time.`),(i.filter(u=>!Gu.has(u)&&!Fc.has(u)).length>0||i.length===0&&n===0)&&a.push(`Accepted here: ${WU([...Gu])} \u2014 convert or unpack the rest and share again.`),{hint:a.join(" ")}}function Plt(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 Qlt=J(()=>{"use strict";Vu()});function eW(){return process.env.CLIO_LOCAL_FS==="1"&&process.env.CLIO_DAEMON!=="1"}function MB(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&&eW()&&t.push("or pass a local folder or .zip path \u2014 this process is running on your own machine"),t.join("; ")}function QE(e,t){return{error:e,hint:t,...tye}}function Mlt(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: ${MB(e)}.`,...tye}}function ME(e){return Object.entries(e).filter(([,t])=>!!t).map(([t])=>t)}function AA(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: ${MB({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.",...tye,...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 tye,Ult=J(()=>{"use strict";tye={kind:"validation",retriable:!1}});import{randomUUID as TDr}from"node:crypto";import{rmSync as xDr}from"node:fs";function nye(e){for(let t of e.tempDirs??[])try{xDr(t,{recursive:!0,force:!0})}catch{}}function qlt(e){for(let[t,r]of UE)e-r.createdAt>$lt&&(nye(r.plan),UE.delete(t))}function NDr(){rye||(rye=setInterval(()=>qlt(Date.now()),kDr),rye.unref?.())}function iye(e,t){let r=Date.now();qlt(r),NDr();let n=`dc_${TDr()}`;return UE.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function oye(e,t){let r=UE.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>$lt?(nye(r.plan),UE.delete(e),null):r.plan}function jlt(e,t){let r=UE.get(e);!r||r.ownerKey!==t||(nye(r.plan),UE.delete(e))}var $lt,kDr,UE,rye,Ylt=J(()=>{"use strict";$lt=1800*1e3,kDr=300*1e3,UE=new Map});function ODr(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 Hlt(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>Fg(i.documentType)&&r.has(i.documentType))}))}}async function zlt(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i,internalNotes:o}=e,s=i&&i.length>0?Hlt(t,i):t;if(!n&&BDr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");GD(o);let a=await d$({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"?ODr(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 Jlt(e,t){return(t&&t.length>0?Hlt(e,t):e).folders.reduce((n,i)=>n+i.files.filter(o=>Fg(o.documentType)).length,0)}function BDr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var Glt=J(()=>{"use strict";tre();Vu();Tf()});function FDr(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 PDr(e){let r=e?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function QDr(e,t){if(e!==LDr)return;let r=PDr(t);if(r)return Vlt.get(r)??Vlt.get(r.replace(/_ERROR$/,""))}function tW(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 MDr(e){if(e.status!==429)return;let{retryAfterSeconds:t,reason:r,limitKey:n}=tW(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 sye(e){return QDr(e.status,e.body)??e.refusal?.hint??MDr(e)}function cl(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 rW(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.error=="string"}function UB(e,t={}){let r=t.readOnly===!1&&aR()?d1e:"";if(e instanceof sr){let o=[sye(e)??FDr(e.status),r].filter(Boolean).join(" "),s={error:e.message,status:e.status,endpoint:e.endpoint,...e.refusal?{code:e.refusal.code}:{},...tW(e),...o?{hint:o}:{}};if(t.toolName&&t.input){let a=nW(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 at;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var LDr,Vlt,yp=J(()=>{"use strict";qi();Xi();iW();A$();LDr=422,Vlt=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 Dd(e,t,r){if(!t)return e;let n=UDr(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 Rd(e,t,r){let n=e;try{return{...n,...await r()}}catch(i){return{partialFailures:[`Updated, but reading the ${t} back failed: ${cl(i)}`],...n}}}function UDr(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 Ep(e,t){return!t||!e||typeof e!="object"?e:{_fx:t,...e}}var Wlt=J(()=>{"use strict";yp()});async function oW(e,t){return e.list("/api/v1/bank-rules",t)}async function $B(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 sW(e,t){return e.search("/api/v1/bank-rules/search",t)}async function aW(e,t){return e.post("/api/v1/bank-rules",t)}async function cW(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function lW(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var aye=J(()=>{"use strict"});async function uW(e,t){return e.list("/api/v1/fixed-assets",t)}async function $E(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function qB(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function dW(e,t){return e.post("/api/v1/fixed-assets",{...t,saveAsDraft:t.saveAsDraft??!0},tte)}function Xlt(e,t){let r={};for(let n of $Dr){let i=e[n];if(i==null)continue;let o=qDr.has(n)?bf(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 fW(e,t,r,n){if(r.resourceId!==void 0&&r.resourceId!==t)throw rt(new ue(`resourceId ${String(r.resourceId)} in the update body differs from the asset being updated (${t}). Nothing was sent.`));let i=n??(await $E(e,t)).data;return e.put(`/api/v1/fixed-assets/${t}`,Xlt(i,r))}async function pW(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function hW(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t},aM)}async function jB(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t,aM)}async function mW(e,t){return e.post("/api/v1/transfer-fixed-assets",t,tte)}async function AW(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{},aM)}async function gW(e,t,r){return e.post(`/api/v1/close-out/fixed-assets/${t}`,{closeOutDate:r,resourceId:t},rte)}async function yW(e,t){return e.post(`/api/v1/reopen/fixed-assets/${t}`,{},rte)}async function jDr(e,t){let r=new Map;for(let i=0;i<t.length;i+=Klt){let o=t.slice(i,i+Klt),s=await qB(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 rt(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 EW(e,t){ut(t,"fixedAssets",500,"fixed assets");let r=new Set,n=t.map((a,c)=>{let u=hD(a,"fixedAssets",c).resourceId;if(typeof u!="string"||u==="")throw rt(new ue(`fixedAssets[${c}].resourceId is required. Nothing was submitted.`));if(r.has(u))throw rt(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)=>ji(a.tags,`fixedAssets[${c}].tags`)),o=await jDr(e,n),s=t.map((a,c)=>{let u=o.get(n[c]),d=i[c];return{resourceId:n[c],...Xlt(u,{...a,tags:d&&Zi(u.tags,d)})}});return bn(e,"/api/v1/fixed-assets/bulk-update","fixedAssets",s)}async function IW(e,t){return e.get("/api/v1/fixed-assets/totals",{endDate:t})}async function bW(e,t){return e.get("/api/v1/fixed-assets/disposal-totals",{endDate:t})}async function _W(e,t){return e.post("/api/v1/fixed-assets/preview-custom-schedule",t,Ge)}async function CW(e,t,r){return e.post("/api/v1/fixed-assets/calculate-disposal",{resourceId:t,depreciationEndDate:r},Ge)}async function wW(e,t,r){return e.get(`/api/v1/fixed-assets/${t}/schedule`,{viewDate:r})}async function vW(e,t){return e.search("/api/v1/fixed-assets/eligible-lines/search",{...t,sort:t.sort??{sortBy:["valueDate"],order:"DESC"}})}async function SW(e,t){return e.search("/api/v1/fixed-assets-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}function HDr(e){let t=["reference","registrationType"];return e.depreciationMethod!=="NO_DEPRECIATION"&&t.push("depreciationStartDate"),t.filter(r=>e[r]==null||e[r]==="")}function zDr(e){let t=[];if(e.forEach((r,n)=>{if(!r||typeof r!="object")return;let i=r,o=HDr(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} (${YDr[a]})`).join(", ")}`)}),t.length>0)throw rt(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 DW(e,t){return ut(t,"fixedAssets",500,"fixed assets"),ZBe(t,["purchaseDate","depreciationStartDate"]),zDr(t),bn(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var gA,$Dr,qDr,Klt,YDr,RW=J(()=>{"use strict";en();ID();Ht();it();Ul();gA=["PURCHASE","SALE","JOURNAL_MANUAL","JOURNAL_CASHFLOW","JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"];$Dr=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","capsuleResourceId"],qDr=new Set(["purchaseDate","depreciationStartDate"]);Klt=100;YDr={reference:"the natural key",registrationType:"NEW or TRANSFER",depreciationStartDate:"epoch milliseconds, usually the purchaseDate"}});async function TW(e,t){return e.search("/api/v1/leases/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function qE(e,t){return e.get(`/api/v1/leases/${t}`)}async function xW(e,t){return e.post("/api/v1/leases",{...t,saveAsDraft:t.saveAsDraft??!0},cBe)}async function kW(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 qE(e,t)).data).reference),e.put(`/api/v1/leases/${t}`,i)}async function NW(e,t){await e.delete(`/api/v1/leases/${t}`)}async function OW(e,t,r){return e.post(`/api/v1/close-out/leases/${t}`,{closeOutDate:r,resourceId:t},dD)}async function BW(e,t){return e.post(`/api/v1/reopen/leases/${t}`,{},dD)}async function FW(e,t,r){return e.post(`/api/v1/terminate/leases/${t}`,{...r,resourceId:t},dD)}async function LW(e,t,r){return e.post("/api/v1/leases/calculate-termination",{resourceId:t,terminationDate:r},Ge)}async function PW(e,t){return e.post(`/api/v1/undo-termination/leases/${t}`,{},dD)}async function QW(e,t){return e.get("/api/v1/leases/totals",{endDate:t})}async function MW(e,t,r){return e.get(`/api/v1/leases/${t}/schedule`,{viewDate:r})}async function UW(e,t){return e.search("/api/v1/lease-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function $W(e,t){return e.post("/api/v1/leases/preview-rent-schedule",t,Ge)}async function qW(e,t){return e.post("/api/v1/leases/calculate-flat-rate",t,Ge)}async function jW(e,t){return ut(t,"leases",500,"leases"),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw rt(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.`))}}),bn(e,"/api/v1/leases/bulk-update","leases",t)}var cye=J(()=>{"use strict";en();it();Ht()});function jE(e,t,r){if(r.resourceId!==void 0&&r.resourceId!==t)throw new ue(`The body names ${e} ${String(r.resourceId)} but the update is for ${t}. Remove resourceId from the body or fix the id. Nothing was changed.`);let n={};for(let[i,o]of Object.entries(r))o!==void 0&&i!=="resourceId"&&(n[i]=o);return n}async function lye(e,t,r,n){return e.search(t,{...r,sort:r.sort??{sortBy:[n],order:"ASC"}})}async function YW(e,t){return lye(e,"/api/v1/pay-types/search",t,"name")}async function HW(e,t){return e.get(`/api/v1/pay-types/${t}`)}async function zW(e,t){return e.post("/api/v1/pay-types",t,lM)}async function JW(e,t,r){return e.put(`/api/v1/pay-types/${t}`,jE("pay type",t,r))}async function GW(e,t){return e.delete(`/api/v1/pay-types/${t}`)}async function VW(e,t){return lye(e,"/api/v1/payrun-posting-rules/search",t,"name")}async function WW(e,t){return e.get(`/api/v1/payrun-posting-rules/${t}`)}async function KW(e,t){return e.post("/api/v1/payrun-posting-rules",t,lM)}async function XW(e,t,r){return e.put(`/api/v1/payrun-posting-rules/${t}`,jE("payrun posting rule",t,r))}async function ZW(e,t){return e.delete(`/api/v1/payrun-posting-rules/${t}`)}async function e4(e,t){return lye(e,"/api/v1/pay-profiles/search",t,"name")}async function t4(e,t){return e.get(`/api/v1/pay-profiles/${t}`)}async function r4(e,t){return e.post("/api/v1/pay-profiles",t,lM)}async function n4(e,t,r){return e.put(`/api/v1/pay-profiles/${t}`,jE("pay profile",t,r))}async function i4(e,t){return e.delete(`/api/v1/pay-profiles/${t}`)}var YB=J(()=>{"use strict";it();Ht()});async function o4(e,t){return e.search("/api/v1/employee-pay-details/search",{...t,sort:t.sort??{sortBy:["effectiveFromDate"],order:"DESC"}})}async function s4(e,t){return e.post("/api/v1/employee-pay-details",t,nte)}async function a4(e,t){return ut(t,"employeePayDetails",500,"employee pay details"),e.post("/api/v1/employee-pay-details/bulk-create",{employeePayDetails:t},nte)}async function c4(e,t,r){return e.put(`/api/v1/employee-pay-details/${t}`,jE("employee pay detail",t,r))}var uye=J(()=>{"use strict";en();Ht();YB()});async function l4(e,t){return e.search("/api/v1/payruns/search",{...t,sort:t.sort??{sortBy:["periodStartDate"],order:"DESC"}})}async function vv(e,t){return e.get(`/api/v1/payruns/${t}`)}async function JDr(e,t){let r=t.idempotencyKey;if(!r)return e.post("/api/v1/payruns",t,lBe);try{return await e.post("/api/v1/payruns",t)}catch(n){throw n instanceof sr&&n.status>=400&&n.status<500&&n.status!==408?n:new Dc(n instanceof Dc?n.message:`POST /api/v1/payruns: the create may or may not have happened (${n.message}).`,"/api/v1/payruns",`Create it again with idempotencyKey ${String(r)}: the same key returns the payrun already created instead of a second one.`,{cause:n})}}function Zlt(e){return{employeeResourceId:e.employeeResourceId,...e.employee!==void 0?{employee:e.employee}:{},...dye(e)?{}:{errorCode:GDr}}}function dye(e){return typeof e.payProfileResourceId=="string"&&e.payProfileResourceId!==""}function HB(e){let t=e.added??[],r=t.filter(i=>!dye(i)).map(Zlt),n=e.skipped!==void 0||r.length>0?[...e.skipped??[],...r]:void 0;return{added:t.filter(dye),skipped:n}}async function u4(e,t){let r=await JDr(e,t);if(t.populate!==!0)return r;try{let{data:n}=await zB(e,r.data.resourceId),i=[...n.skipped??[]],o=new Set(i.map(s=>s.employeeResourceId));for(let s of n.added??[])o.has(s.employeeResourceId)||(o.add(s.employeeResourceId),i.push(Zlt(s)));return{skipped:i,...i.length>0?{note:"The fill left these employees out. Say so in the reply and name each one with its reason (errorCode); where one reason covers many, give the reason with its count and offer the names (search_employees names one by employeeResourceId)."}:{},...r}}catch(n){return{partialFailures:[`The run was created and filled, but reading who the fill left out failed: ${cl(n)}. preview_populate_payrun lists them.`],...r}}}async function d4(e,t,r){return e.put(`/api/v1/payruns/${t}`,jE("payrun",t,r))}async function f4(e,t){return e.delete(`/api/v1/payruns/${t}`)}async function p4(e,t){return e.post("/api/v1/payruns/bulk/delete",{resourceIds:t},uBe)}async function h4(e,t,r){return e.post(`/api/v1/payruns/${t}/employees`,{employeeResourceIds:r},sh)}async function m4(e,t,r){return e.post(`/api/v1/payruns/${t}/employees/remove`,{employeeResourceIds:r},sh)}async function A4(e,t,r){return e.put(`/api/v1/payruns/${t}/lines`,{payslips:r})}async function g4(e,t){return e.post(`/api/v1/payruns/${t}/populate`,void 0,sh)}async function zB(e,t){return e.post(`/api/v1/payruns/${t}/populate/preview`,void 0,Ge)}var GDr,JB=J(()=>{"use strict";qi();Ht();YB();yp();GDr="PAYRUN_EMPLOYEE_NO_PAY_PROFILE"});function KDr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eut(e,t){let r={};for(let n of t)e[n]!==void 0&&(r[n]=e[n]);return r}function tut(e,t){let r=e;if(e.payslips!==void 0&&!(Array.isArray(e.payslips)&&e.payslips.length>0&&e.payslips.every(KDr)))throw new ue("The payslips list is empty, is not a list, or has an entry that is not a payslip object. Name the payslips to pay, or leave payslips out to pay every payslip still owed.");let n=e.payslips?.map(i=>eut(i,VDr));return{...eut(r,WDr),...n?{payslips:n}:{},...t&&e.hash?{hash:e.hash}:{},payoutMethod:"RECORD"}}async function y4(e,t,r){return e.post(`/api/v1/payruns/${t}/validate`,r?{journalValueDate:r}:{},Ge)}async function E4(e,t,r){return e.post(`/api/v1/payruns/${t}/preview-journal`,r?{journalValueDate:r}:{},Ge)}async function I4(e,t,r){return e.post(`/api/v1/payruns/${t}/finalize`,r?{journalValueDate:r}:{},uM)}async function b4(e,t){return e.post("/api/v1/payruns/bulk/finalize",{payruns:t},dBe)}async function _4(e,t){return e.post(`/api/v1/payruns/${t}/unpost`,void 0,uM)}async function C4(e,t,r){return e.post(`/api/v1/payruns/${t}/void`,{voidReason:r},uM)}async function w4(e,t,r){return e.post(`/api/v1/payruns/${t}/payouts/preview`,tut(r,!1),Ge)}async function v4(e,t,r){return e.post(`/api/v1/payruns/${t}/payouts`,tut(r,!0),fBe)}async function S4(e,t,r){return e.post(`/api/v1/payruns/payouts/${t}/void`,{voidReason:r},pBe)}var VDr,WDr,fye=J(()=>{"use strict";it();Ht();VDr=["payslipResourceId","amount","reference"],WDr=["paymentAccountResourceId","valueDate","reference","internalNotes"]});async function D4(e,t){return e.search("/api/v1/payslips/search",{...t,sort:t.sort??{sortBy:["payrun.periodEndDate"],order:"DESC"}})}async function GB(e,t){return e.get(`/api/v1/payslips/${t}`)}async function pye(e,t){return e.post(`/api/v1/payslips/${t}/refresh`,void 0,sh)}function rut(e){return e===void 0||e.length===0?{}:{payslipResourceIds:e}}async function hye(e,t,r){return e.post(`/api/v1/payruns/${t}/payslips/refresh`,rut(r),sh)}async function R4(e,t,r){return e.post(`/api/v1/payruns/${t}/payslips/generate`,rut(r),sh)}async function nut(e,t){let r=[],n=async a=>{try{let{data:c}=await GB(e,t);if(typeof c!="object"||c===null)throw new Error("the reply carried no payslip");return c}catch(c){r.push(`Reading the payslip ${a} the refresh failed: ${cl(c)}. get_payslip reads its lines now.`);return}},i=await n("before"),o=await pye(e,t),s=await n("after");return{...r.length>0?{partialFailures:r}:{},...o,...i?{before:i}:{},...s?{after:s}:{}}}async function iut(e,t,r){let n=[],i=r!==void 0&&r.length>0?new Set(r):void 0,o=m=>{if(!i)return m;let A=m.filter(g=>i.has(g?.resourceId));return A.length===i.size&&new Set(A.map(g=>g.resourceId)).size===i.size?A:null},s=async m=>{try{let{payslips:A}=(await vv(e,t)).data;if(!Array.isArray(A))throw new Error("the run carried no payslip rows");let g=o(A);if(!g)throw new Error("the run does not hold each payslip refreshed exactly once");return g}catch(A){n.push(`Reading the run's payslips ${m} the refresh failed: ${cl(A)}. get_payrun reads them now.`);return}},a=await s("before"),c=await hye(e,t,r),u=c.data.payrun?.payslips,d=i??(a?new Set(a.map(m=>m?.resourceId)):void 0),f=Array.isArray(u)&&u.length>0&&d!==void 0&&d.size>0&&[...d].every(m=>typeof m=="string")?o(u)??void 0:void 0,p=f!==void 0&&(i!==void 0||[...d??[]].every(m=>f.some(A=>A.resourceId===m))),h=a===void 0?void 0:p?f:await s("after");return{...n.length>0?{partialFailures:n}:{},...c,...a?{before:a}:{},...h?{after:h}:{}}}var mye=J(()=>{"use strict";Ht();JB();yp()});function VB(e){let t=e<0?"-":"",r=Math.abs(e),[n,i="00"]=r.toFixed(2).split("."),o=n.replace(/\B(?=(\d{3})+(?!\d))/g,",");return`${t}${o}.${i}`}var out=J(()=>{"use strict"});function Ip(e,t){let r={};for(let n of t)e[n]!==void 0&&(r[n]=e[n]);return r}function _ye(e){let t={};for(let[r,n]of Object.entries(e))r==="deleted"||r==="organizationResourceId"||r==="idempotencyKey"||/By$/.test(r)&&typeof n=="string"||(t[r]=n);return t}function rRr(e){let t=Ps(e.payTypeSnapshot)?e.payTypeSnapshot:{};return{...Ip(e,["resourceId","payTypeId"]),...t.name!==void 0?{payTypeName:t.name}:{},...t.category!==void 0?{category:t.category}:{},...Ip(e,["amount","origin","description"])}}function Cye(e){let t=Array.isArray(e.lines)?e.lines:void 0;return{...Ip(e,tRr),...typeof e.inProgressAmount=="number"&&e.inProgressAmount>0?{inProgressAmount:e.inProgressAmount}:{},...t?{lineCount:t.length}:{}}}function lut(e){let{employee:t,payProfile:r,...n}=e,i=Ps(t)?t.name:void 0;return i!==void 0&&n.employeeName===void 0?{...n,employeeName:i}:n}function wye(e){let t={};for(let r of e){let n=yye(r);n&&(t[n]=(t[n]??0)+1)}return t}function vye(e,t=lut){if(e.length===0)return[];let r=wye(e);return{totalElements:e.length,...Object.keys(r).length>0?{byErrorCode:r}:{},data:e.map(t)}}function k4(e,t){if(t.length===0)return e;let r={...e},n=Ip(r,sut);for(let i of sut)delete r[i];return{...n,note:t.join(" "),...r}}function uut(e,t,r){let n={};for(let[i,o]of Object.entries(_ye(e)))i==="payslips"&&Array.isArray(o)&&t==="payslips"?(n.payslips=x4(ua(o).map(Cye)),o.length>0&&r.push(ZDr)):i==="payslips"&&Array.isArray(o)?t==="payouts"?r.push(eRr):r.push(XDr):i==="removedPayslips"&&Array.isArray(o)?n.removedPayslipCount=o.length:i==="payouts"&&Array.isArray(o)?t==="payouts"?n.payouts=x4(ua(o).map(nRr)):n.payoutCount=o.length:n[i]=o;return n}function Sye(e,t){let r=[],n={};for(let[i,o]of Object.entries(e))i==="data"&&Ps(o)?n.data=uut(o,t,r):i==="skipped"&&Array.isArray(o)?n.skipped=vye(ua(o)):i==="note"&&typeof o=="string"?r.unshift(o):n[i]=o;return k4(n,r)}function WB(e,t,r,n={}){let i=Ps(e.data)?e.data:{},o=[...Eye(e)],s=Object.fromEntries(Object.entries(i).filter(([a])=>a!==t&&a!==r&&a!=="payrun"));return k4({data:{...Array.isArray(i[t])?{[t]:vye(ua(i[t]))}:{},...Array.isArray(i[r])?{[`${r}Count`]:i[r].length}:{},...n,...Ps(i.payrun)?{payrun:uut(i.payrun,"none",o)}:{},...s}},o)}function aRr(e){let{added:t,skipped:r}=HB({added:ua(e.added),skipped:e.skipped!==void 0?ua(e.skipped):void 0});return{skipped:r,adding:t}}function put(e,t=!1){let r=Ps(e.data)?e.data:{},{skipped:n,adding:i}=aRr(r);if(!t){let d={...r,...n!==void 0?{skipped:n}:{},...r.added!==void 0?{added:i}:{}};return WB({...e,data:d,note:[...Eye(e),iRr].join(" ")},"skipped","added")}let o=wye(n??[]),{skipped:s,added:a,payrun:c,...u}=r;return k4({data:{...n!==void 0?{skippedCount:n.length,...Object.keys(o).length>0?{byErrorCode:o}:{}}:{},addedCount:i.length,...u,...r.added!==void 0?{added:x4(i.map(sRr))}:{}}},[...Eye(e),oRr])}function uRr(e,t){let r=new Map(t.map(c=>[c.resourceId,c])),n=new Set(e.map(c=>c.resourceId)),i=e.filter(c=>!r.has(c.resourceId)),o=t.filter(c=>!n.has(c.resourceId)),s=e.filter(c=>r.has(c.resourceId)).map(c=>[c,r.get(c.resourceId)]),a=[];for(let c of i){let u=gye(c);if(typeof c.payTypeId!="string"||typeof c.origin!="string"){a.push(c);continue}let d=i.filter(p=>gye(p)===u),f=o.filter(p=>gye(p)===u);d.length===1&&f.length===1?(s.push([c,f[0]]),o.splice(o.indexOf(f[0]),1)):a.push(c)}return{changedLines:s.filter(([c,u])=>c.amount!==u.amount).map(([c,u])=>hut(Aye(u),c.amount,u.amount)),removedLines:a.map(c=>`${Aye(c)}: ${VB(c.amount)} removed`),addedLines:o.map(c=>`${Aye(c)}: ${VB(c.amount)} added`)}}function gut(e){let{data:t}=T4({data:e.data});if(!Ps(t))return e;let r=a=>KB(a===void 0?e:bye(e,a),{data:{...t,refresh:Sv}}),n=["before","after"].map(a=>({when:a,read:e[a]}));for(let{when:a,read:c}of n){if(!Ps(c))return Array.isArray(e.partialFailures)&&e.partialFailures.length>0?r():r(`The payslip was not read ${a} the refresh, so what changed is not shown. get_payslip reads its lines now.`);if(!Array.isArray(c.lines))return r(`The payslip read ${a} the refresh carried no lines, so what changed is not shown. get_payslip reads its lines now.`);if(!c.lines.every(cRr)||new Set(c.lines.map(u=>u.resourceId)).size!==c.lines.length)return r(`The payslip read ${a} the refresh has a line without a unique id or a numeric amount, so what changed is not shown. get_payslip reads its lines now.`)}let i=T4({data:e.before}).data,o=T4({data:e.after}).data;if(!mut(i,o))return r("The payslip amounts read before and after the refresh cannot be compared (one is missing or not a number), so what changed is not shown. get_payslip reads them now.");let s={...uRr(ua(i.lines),ua(o.lines)),amounts:Aut(i,o)};return KB(e,{data:{...t,refresh:Sv,changes:s}})}function yut(e){let t=u=>KB(e,WB(e,"failed","refreshed",{refresh:Sv,...u})),r=t({}),n=Array.isArray(e.partialFailures)&&e.partialFailures.length>0;if(!Array.isArray(e.before)||!Array.isArray(e.after))return n?r:KB(bye(e,"The run's payslips were not read before and after the refresh, so which payslips changed is not shown. get_payrun lists their amounts now."),WB(e,"failed","refreshed",{refresh:Sv}));let i=pRr(e.before,e.after);if(typeof i=="string")return KB(bye(e,i),WB(e,"failed","refreshed",{refresh:Sv}));if(i.length===0)return t({changedPayslips:[]});let o=Dye-JSON.stringify(r,null,2).length-dRr,s=[],a=0;for(let u of i){if(a+=JSON.stringify(u).length+fRr,a>o)break;s.push(u)}let c=i.length-s.length;return t({changedPayslips:{totalElements:i.length,...c>0?{notShown:c,note:`${c} more payslips changed, but the earlier amounts of those are not shown and cannot be read again after this refresh. get_payrun lists their amounts as they are now.`}:{},rows:s}})}function pRr(e,t){let r="The payslips read before and after the refresh cannot be compared (a row without a unique id, a payslip in only one read, or an amount that is missing or not a number), so which payslips changed is not shown. get_payrun lists their amounts now.",n=s=>Ps(s)&&typeof s.resourceId=="string"?s.resourceId:void 0;if(!e.every(s=>n(s)!==void 0)||!t.every(s=>n(s)!==void 0))return r;let i=new Map(e.map(s=>[s.resourceId,s])),o=t;return i.size!==e.length||new Set(o.map(s=>s.resourceId)).size!==o.length||i.size!==o.length||!o.every(s=>i.has(s.resourceId))||!o.every(s=>mut(i.get(s.resourceId),s))?r:o.flatMap(s=>{let a=Aut(i.get(s.resourceId),s,""),c=typeof s.employeeName=="string"&&s.employeeName!==""?s.employeeName:s.resourceId;return a.length>0?[`${c}: ${a.join("; ")}`]:[]})}function Eut(e){return{note:"The payslips named, as rows without lines: get_payslip reads one with its lines and line ids.",data:ua(e.data).map(Cye)}}function Iut(e){let t=T4(e);if(!Ps(t.data)||!Ps(t.data.payrun)||t.data.payrun.status!=="DRAFT")return t;let{lines:r,...n}=t.data;return{data:{...n,onRefresh:Sv,...r!==void 0?{lines:r}:{}}}}function T4(e){if(!Ps(e.data))return e;let{lines:t,...r}=_ye(e.data);return{data:{...r,...Array.isArray(t)?{lines:ua(t).map(rRr)}:{}}}}function but(e){return e.data.length===0?e:{note:"Rows have no lines: get_payslip reads one with its lines and line ids.",...e,data:ua(e.data).map(t=>({...Cye(t),...Ip(t,["payrunResourceId","payProfileResourceId"]),...Ps(t.payrun)?{payrun:Ip(t.payrun,["name","payrunType","status","periodStartDate","periodEndDate","paymentDate","currencyCode"])}:{},...Array.isArray(t.generatedDocuments)?{generatedDocuments:t.generatedDocuments}:{}}))}}function O4(e){if(!Ps(e.data))return e;let t=ua(e.data.errors),r=[],n={};for(let[i,o]of Object.entries(e.data))i==="errors"?n.errors=vye(t,s=>s):i==="payouts"&&Array.isArray(o)?t.length>0?n.payoutCount=o.length:(n.payouts=x4(ua(o).map(s=>Ip(s,["payslipResourceId","employeeResourceId","employeeName","netPayAmount","paidAmount","owedAmount","payoutAmount"]))),r.push(typeof e.data.paymentAccountName=="string"?"Each payout debits netPayAccountName and credits paymentAccountName for payoutAmount.":"Each payout debits netPayAccountName for payoutAmount. No payment account was named: its checks wait for one.")):n[i]=o;return k4({data:n},r)}function Cut(e){let t=ua(e.data).map((i,o)=>({rowIndex:o+1,...i})),r=t.filter(i=>yye(i)!==void 0),n=t.filter(i=>yye(i)===void 0);return{createdCount:n.length,failedCount:r.length,...r.length>0?{byErrorCode:wye(r)}:{},data:[...r,...n]}}var XB,yA,cut,XDr,ZDr,eRr,Ps,ua,x4,tRr,nRr,yye,sut,Eye,N4,dut,HE,fut,iRr,oRr,sRr,aut,Sv,KB,YE,hut,Iye,mut,Aut,cRr,lRr,Aye,gye,bye,Dye,dRr,fRr,_ut,wut=J(()=>{"use strict";JB();out();XB="result exceeded the size cap; search_payslips with payrunResourceId and offset pages the payslips, get_payslip reads one with its lines",yA="result exceeded the size cap; the counts by error code cover every row, and search_employees names one by employeeResourceId",cut="result exceeded the size cap; the counts cover every employee, and search_employees names one by employeeResourceId",XDr="Payslip rows are not listed here: get_payrun has them.",ZDr="Payslips are rows without lines: get_payslip reads one with its lines and line ids.",eRr="Payouts are listed instead of payslips: get_payrun without payouts lists the payslips. A payout's journalResourceId is a cash-out record, not a journal: get_cash_out reads it and names the account it was paid from, until the payout is voided.",Ps=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ua=e=>Array.isArray(e)?e.filter(Ps):[];x4=e=>({totalElements:e.length,data:e});tRr=["resourceId","employeeResourceId","employeeName","grossAmount","deductionAmount","netPayAmount","employerContributionAmount","paidAmount","payoutStatus","prorated"];nRr=e=>Ip(e,["journalResourceId","employeeResourceId","employeeName","amount","valueDate","status","voidable"]);yye=e=>typeof e.errorCode=="string"?e.errorCode:typeof e.code=="string"?e.code:void 0;sut=["partialFailures","skipped"];Eye=e=>typeof e.note=="string"?[e.note]:[];N4=e=>Sye(e,"payslips"),dut=e=>Sye(e,"payouts"),HE=e=>Sye(e,"none");fut=e=>WB(e,"skipped","added"),iRr="The employees that would be added are only counted here: preview_populate_payrun with added true lists them.",oRr="Skipped employees are only counted here: preview_populate_payrun without added lists them. The employees listed under added are the ones populate_payrun would add.",sRr=e=>Ip(lut(e),["employeeResourceId","employeeName","payProfileResourceId"]);aut={paySetupLines:"Rebuilt from current pay (origin PROFILE), each replacing every line of its pay type: an amount changed by hand, or a line added by hand or imported with that pay type, is replaced, and nothing marks a hand edit.",linesAddedByHand:"Kept as they are when their pay type is not in the pay setup (origin MANUAL, or IMPORTED from a payrun import); one whose pay type is in the pay setup is replaced."},Sv={paySetupLines:{effect:aut.paySetupLines},linesAddedByHand:{effect:aut.linesAddedByHand}},KB=(e,t)=>Array.isArray(e.partialFailures)&&e.partialFailures.length>0?{partialFailures:e.partialFailures,...t}:t,YE=e=>typeof e=="number"&&Number.isFinite(e),hut=(e,t,r,n=":")=>`${e}${n} ${VB(t)} to ${VB(r)}`,Iye=[["netPayAmount","Net pay"],["grossAmount","Gross pay"],["deductionAmount","Deductions"],["employerContributionAmount","Employer contribution"]],mut=(e,t)=>Iye.every(([r])=>e[r]===void 0&&t[r]===void 0||YE(e[r])&&YE(t[r]))&&Iye.some(([r])=>YE(e[r])&&YE(t[r])),Aut=(e,t,r=":")=>Iye.flatMap(([n,i])=>{let o=e[n],s=t[n];return YE(o)&&YE(s)&&o!==s?[hut(i,o,s,r)]:[]}),cRr=e=>Ps(e)&&typeof e.resourceId=="string"&&YE(e.amount),lRr={PROFILE:"pay setup",MANUAL:"added by hand",IMPORTED:"imported"},Aye=e=>{let t=typeof e.origin=="string"?lRr[e.origin]:void 0,r=[typeof e.description=="string"&&e.description!==""?e.description:void 0,t].filter(Boolean).join(", ");return`${typeof e.payTypeName=="string"&&e.payTypeName!==""?e.payTypeName:"Line"}${r?` (${r})`:""}`},gye=e=>JSON.stringify([e.payTypeId,e.origin,e.description]);bye=(e,t)=>({...e,partialFailures:[...Array.isArray(e.partialFailures)?e.partialFailures:[],t]});Dye=5e4,dRr=1500,fRr=8;_ut=e=>({...e,data:ua(e.data).map(_ye)})});async function B4(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function zE(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function F4(e,t){return e.post("/api/v1/scheduled/subscriptions",t,oh)}async function L4(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 zE(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 hRr(i);n.status=i}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}function hRr(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 P4(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function Q4(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 M4(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var U4=J(()=>{"use strict";Ht()});async function $4(e,t){return e.list("/api/v1/contact-groups",t)}async function q4(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function j4(e,t){return e.search("/api/v1/contact-groups/search",t)}async function Y4(e,t){return e.post("/api/v1/contact-groups",t)}async function H4(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,Jb(r,fte))}async function z4(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var Rye=J(()=>{"use strict";en()});async function J4(e,t){return e.list("/api/v1/inventory-items",t)}async function G4(e,t){return e.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...t})}async function V4(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function K4(e,t,r){try{return await e.list(`/api/v1/inventory-balances/${t}`,r)}catch(n){if(n instanceof sr&&n.status===404&&mRr.test(JSON.stringify(n.body??"")))return{data:[],totalElements:0,totalPages:0};throw n}}var W4,mRr,Tye=J(()=>{"use strict";qi();W4=["ALL","AVAILABLE","FULLY_DRAWN"],mRr=/Inventory balance Not Found/i});async function X4(e,t){return e.list("/api/v1/custom-fields",t)}async function ZB(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function Z4(e,t){return e.search("/api/v1/custom-fields/search",t)}async function e3(e,t){return e.post("/api/v1/custom-fields",t)}function gRr(e){return e!==void 0&&ARr.every(t=>e[t]!==void 0)}function yRr(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 ERr(e){return[e.applyToSales,e.applyToPurchase,e.applyToSaleCreditNote,e.applyToPurchaseCreditNote,e.applyToPayment,e.applyToCreditNote].some(t=>t==="PRINT")}async function t3(e,t,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!gRr(n.appliesTo)){let i=await ZB(e,t);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??ERr(i.data),n.appliesTo={...yRr(i.data),...r.appliesTo}}return e.put(`/api/v1/custom-fields/${t}`,n)}async function r3(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var ARr,xye=J(()=>{"use strict";ARr=["invoices","bills","customerCredits","supplierCredits","payments"]});var ll,JE,IRr,bRr,kye,n3,i3,_Rr,Fa,pu,GE,Dv,VE,Nye=J(()=>{"use strict";ll={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"]},JE={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."}}},IRr={type:"object",properties:{exchangeToken:{type:"string",description:"Exchange token for rate lookup."},rateFunctionalToSource:{type:"number",description:"Exchange rate from functional to source currency."}}},bRr={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"]},kye={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"]},n3={type:"object",properties:{billingAddress:{...kye,description:"Seller billing address."},name:{type:"string",description:"Seller display name."},taxId:{type:"string",description:"Seller tax identification number."}},required:["billingAddress","name"]},i3={type:"object",properties:{billingAddress:{...kye,description:"Buyer billing address."},name:{type:"string",description:"Buyer display name."},shippingAddress:{...kye,description:"Buyer shipping address."},taxId:{type:"string",description:"Buyer tax identification number."}},required:["billingAddress","name","shippingAddress"]},_Rr={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"]},Fa={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:_Rr},type:{type:"string",description:"Transaction type the classifier applies to. Required unless deleted is true.",enum:["bill","invoice"]}},required:["resourceId"]},pu={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)."}}},GE={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"]},Dv={bills:{capsuleResourceId:{type:"string",description:"UUID of the capsule to associate."},contactResourceId:{type:"string",description:"UUID of the contact (supplier) for this bill."},currencySettings:{...ll,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:JE},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:{...ll,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:{...IRr,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:{...bRr,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:{...n3,description:"Issuer identity and billing address (credit from)."},creditTo:{...i3,description:"Recipient identity, billing and shipping address (credit to)."},currencySettings:{...ll,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:JE},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:{...ll,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:{...n3,description:"Seller identity and billing address."},billTo:{...i3,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:{...ll,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:JE},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:{...ll,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:{...ll,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:JE},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:{...ll,description:"Tax currency exchange settings. sourceCurrencyCode is required, also when only the rate changes."}},"sale-schedules":{billFrom:{...n3,description:"Seller identity and billing address."},billTo:{...i3,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:{...ll,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:JE},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:{...ll,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:{...n3,description:"Seller identity and billing address."},billTo:{...i3,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:JE},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:{...ll,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:JE},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:{...ll,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)."}}},VE={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:Fa},discount:{...pu,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:{...GE,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:Fa},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:Fa},discount:{...pu,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:Fa},discount:{...pu,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:Fa},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:Fa},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:Fa},discount:{...pu,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:{...GE,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:Fa},discount:{...pu,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:{...GE,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:Fa},description:{type:"string",description:"Line item description or memo."},discount:{...pu,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:{...GE,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:Fa},discount:{...pu,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:Fa},discount:{...pu,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:Fa},description:{type:"string",description:"Line item description or memo."},discount:{...pu,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:{...GE,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:Fa},description:{type:"string",description:"Line item description or memo."},discount:{...pu,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:{...GE,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:Fa},discount:{...pu,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:{...GE,description:"Withholding tax details for this line item."}}}}});function Bye(e){return(e??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}function Fye(e){let t=e.updated??[],r=Bye(e.failed);return{...t.length===0&&r.length>0?{error:vRr}:{},updated:t,failed:r}}function Sut(e){return e.type==="object"?e.properties:e.type==="array"?e.items?.properties:void 0}function Dut(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=Sut(s);if(a)for(let c of Array.isArray(o)?o:[o])Qh(c)&&n.push(...Dut(c,a,`${r}${i}.`))}return n.filter((i,o)=>n.findIndex(s=>s.path===i.path)===o)}function SRr(e){return Object.entries(e).map(([t,r])=>{let n=Sut(r);return n?`${t}{${Object.keys(n).join(",")}}`:t}).join(", ")}function Lye(e,t,r){if(!Qh(t))return;let n=Dut(t,r);if(n.length===0)return;let i=n.map(o=>`"${o.path}" (accepted here: ${o.accepted.join(", ")})`);throw rt(new at(`${e} has no field ${i.join("; ")}. Fields: ${SRr(r)}. Nothing was changed.`))}function DRr(e){let t=Dv[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 RRr(e){let t=VE[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 TRr(e,t,r){if(!Array.isArray(r))return;let n=t.entryKeys??[],i=[...t.updateKeys??[],"lineItemUpdates"];for(let o of r){if(!Qh(o))continue;let s=Object.keys(o).filter(a=>!i.includes(a));if(s.length)throw rt(new at(`${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(!Qh(a))continue;let c=Object.keys(a).filter(u=>u!=="attributes"&&!n.includes(u));if(c.length)throw rt(new at(`${e} line item updates take { ${n.join(", ")}, attributes: { ... } }: ${c.map(u=>`"${u}"`).join(", ")} must sit inside attributes. Nothing was changed.`));Lye(`${e} line items`,a.attributes,t.fields)}}}function Rut(e){if(Rv.includes(e))return;let t=s3.includes(e);throw rt(new at(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: ${Rv.join(", ")}.`))}async function xv(e,t,r){Rut(t),Lye(`${t} quick fix`,r.attributes,DRr(t));let n=await e.post(`/api/v1/quick-fix/${Oc(Rv,t)}`,r);return Fye(n)}async function xRr(e,t){try{return await BE(e,t)}catch(r){if(r instanceof sr&&r.status===404)return FE(e,t);throw r}}async function Tut(e,t,r,n){Rut(t);let i=Pye[t],o=async d=>i.tags(await zo(i.noun,d,()=>i.get(e,d))),s=[];for(let d=0;d<r.resourceIds.length;d+=vut)s.push(...await Promise.all(r.resourceIds.slice(d,d+vut).map(o)));let a=new Map;r.resourceIds.forEach((d,f)=>{let p=Zi(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 xv(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 Fye({updated:c,failed:u})}async function eF(e,t,r){let n=Oc(Tv,t),i=RRr(t);i.entryKeys?TRr(t,i,r.schedulerUpdates):Lye(`${t} line items`,r.attributes,i.fields);let o=await e.post(`/api/v1/quick-fix/${n}/line-items`,r);return Fye(o)}var CRr,wRr,o3,s3,Rv,Tv,vRr,WE,Oye,Pye,vut,a3=J(()=>{"use strict";qi();it();Xi();Nye();Ul();oy();If();xk();Lk();sy();KV();l8();U4();Lie();CRr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],wRr=["journals","cash-entries"],o3=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],s3=["sale-orders","sale-quotes","purchase-orders","purchase-requests"],Rv=[...CRr,...wRr,...o3],Tv=[...Rv,...s3],vRr="Nothing changed: every record failed. See failed for each reason.";WE=e=>e?.tags,Oye=e=>e?.data?.tags,Pye={invoices:{noun:"invoice",get:(e,t)=>Eo(e,t),tags:WE},bills:{noun:"bill",get:(e,t)=>po(e,t),tags:WE},"customer-credit-notes":{noun:"customer credit note",get:(e,t)=>ta(e,t),tags:WE},"supplier-credit-notes":{noun:"supplier credit note",get:(e,t)=>ra(e,t),tags:WE},journals:{noun:"journal",get:(e,t)=>Rs(e,t),tags:WE},"cash-entries":{noun:"cash entry",get:(e,t)=>xRr(e,t),tags:WE},"sale-schedules":{noun:"sale schedule",get:(e,t)=>mv(e,t),tags:Oye},"purchase-schedules":{noun:"purchase schedule",get:(e,t)=>Av(e,t),tags:Oye},"subscription-schedules":{noun:"subscription",get:(e,t)=>zE(e,t),tags:Oye},"journal-schedules":{noun:"journal schedule",get:(e,t)=>gv(e,t),tags:WE}},vut=10});function c3(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=c3(e.items,t,!1));let i=e.properties?Object.entries(e.properties):[];return i.length&&t<NRr&&i.length<=ORr&&(n.properties=Object.fromEntries(i.map(([o,s])=>[o,c3(s,t+1,e.required?.includes(o)??!1)])),e.required?.length&&(n.required=[...e.required])),n}function kut(e,t,r){let n=BRr(t);if(!n)return[];let i=FRr(r);if(!i){if(xut[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]?kut(o,s,i[o]):[])}function LRr(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 Qye(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 I=PRr(e[y][c]);d.set(I,[...d.get(I)??[],y])}let[[,f],...p]=[...d].sort((y,I)=>I[1].length-y[1].length),{description:h,...m}=r[c]??c3(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=>c3(e[y[0]][c]).properties))}:m;A.required||delete A.required;let g=[xut[c],LRr(u,n),...p.map(([,y])=>{let I=e[y[0]][c];return`${y.join(", ")}: {${Object.keys(I.properties??I.items?.properties??{}).join(", ")}}.`})].filter(Boolean);o[c]=g.length?{...A,description:g.join(" ")}:A;for(let y of u)for(let[I,E]of kut(c,e[y][c],A))s.set(E,(s.get(E)??new Set).add(I))}let a=[...s].map(([c,u])=>`${[...u].join(", ")}: ${c}.`);return{type:"object",description:[t,...a].join(" "),properties:o}}function Fut(e){let t=[...new Set(e.flatMap(n=>Object.keys(n)))],r=[...new Set(t.map(n=>kRr[n]).filter(Boolean))];return r.filter(n=>!r.some(i=>i!==n&&i.includes(n))).join(", ")}var kRr,xut,NRr,ORr,BRr,FRr,PRr,QRr,MRr,kv,Nut,Out,But,Lut,Put,Qut,Mye=J(()=>{"use strict";Nye();Ul();kRr={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"},xut={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:`${Ho.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.'},NRr=2,ORr=8;BRr=e=>e.properties??e.items?.properties,FRr=e=>e.properties??e.items?.properties;PRr=e=>JSON.stringify([e.type,Object.keys(e.properties??e.items?.properties??{})]),QRr={tags:Ho};MRr=Object.entries(VE).filter(([,e])=>!e.entryKeys),kv=Object.entries(VE).filter(([,e])=>e.entryKeys),Nut=Qye({...Dv},"REQUIRED. Only fields sent change; one the entity does not take is refused. billFrom/billTo/creditFrom/creditTo replace what is stored: resend unchanged fields.",QRr),Out=Qye(Object.fromEntries(MRr.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."),But=(()=>{let e=n=>kv.filter(([,i])=>i.entryKeys.includes(n)).map(([i])=>i),[,t]=kv[0],r=[...new Set(kv.flatMap(([,n])=>n.entryRequired??[]))].filter(n=>kv.every(([,i])=>i.entryRequired?.includes(n)));return{type:"array",description:`Schedules only (${kv.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:Qye(Object.fromEntries(kv.map(([n,i])=>[n,i.fields])),"The fields to change on this line; they sit here, never beside the locator.")}}}}}}})();Lut=[...new Set([...Object.keys(Dv),...Object.keys(VE)])].map(e=>e.replace(/-/g," ")).join(", "),Put=Fut(Object.values(Dv)),Qut=Fut(Object.values(VE).map(e=>e.fields))});function l3(e,t){return e.toolCalls!==void 0||e.mcpTransport==="hosted"?Math.min(25e3,t):e.mcpTransport==="stdio"?Math.min(55e3,t):t}var Uye=J(()=>{"use strict"});function d3(){return EA.map(e=>`${e} sets ${Ov[e].change.join(", ")}`).join("; ")}function zut(e){let t={};for(let r of e)t[r]=Object.hasOwn(Uut,r)?Uut[r]:qRr.find(([n])=>n.test(r))?.[1]??jRr;return Object.keys(t).length>0?t:void 0}function Jut(e){if(!(e instanceof sr)||!e.endpoint.startsWith($Rr))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($ut,n))return;let{hint:i,repairTool:o,command:s}=$ut[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===Yut.LINE_ITEMS?"line items":"records",...e.endpoint===u3?{apply:!0}:{}};return e.refusal={code:n,hint:typeof i=="function"?i(d):i,...o?{repairTool:o}:{},...s?{command:s}:{}},e.refusal}function zRr(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 JRr(e){return typeof e=="string"&&EA.includes(e)}function GRr(e,t){if(!JRr(e))throw new at(`level must be one of ${EA.join(", ")}.`);let r=EA.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))Ov[e][i].includes(s)||n.push(Ov[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}=Ov[e];throw new at(`${n.join(". ")}. ${e} filter: ${i.join(", ")}. ${e} change: ${o.join(", ")}.`)}}function qut(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 at(`${e} must be a JSON object, not ${n}.`)}async function p3(e,t,r){let n={filter:qut("filter",r.filter),change:qut("change",r.change)};GRr(t,n);let i;try{i=await e.post(Yut[t],{filter:n.filter,change:n.change},Ge)}catch(u){throw Jut(u),u}let{data:o,...s}=i,a=zut([...Object.keys(i.counts?.excludedByCode??{}),...Object.keys(i.counts?.blockedByCode??{})]),c=zRr(t,n,i.counts?.matched??0);return{...s,...a?{reasons:a}:{},...c?{filterNotes:[c]}:{},data:o??[]}}function qye(e,t){return{error:`${t} ${Vut}`,outcome:"UNKNOWN",previewId:e,next:Gut}}function KRr(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 qye(e,"The apply answered without a per-record result.");let i=Bye(n),o={};for(let c of i)o[c.errorCode]=(o[c.errorCode]??0)+1;let s=zut(Object.keys(o)),a=o[YRr]?"UNKNOWN":i.length===0?"SUCCESS":r.length===0?"FAILED":"PARTIAL";return{...a==="FAILED"?{error:WRr}:a==="UNKNOWN"?{error:Vut}:{},outcome:a,previewId:e,counts:{updated:r.length,failed:i.length},failedByCode:o,...s?{reasons:s}:{},...a==="SUCCESS"?{}:{next:a==="UNKNOWN"?Gut:VRr},failed:i.slice(0,$ye),...i.length>$ye?{failedNotShown:i.length-$ye}:{},data:r}}async function h3(e,t,r=HRr){let n;try{n=await e.post(u3,{previewId:t},{timeoutMs:r,retryNetworkErrors:!1})}catch(i){if(i instanceof sr){let s=Jut(i),a=i.status===503&&s?.code==="PREVIEW_STORE_UNAVAILABLE";if(i.status<500||a)throw rt(i);return qye(t,`The apply answered ${i.status} without saying which records changed.`)}if(i instanceof ih)throw rt(i);let o=i instanceof Error?i.message:String(i);return qye(t,`No answer arrived from the apply (${o}).`)}return KRr(t,n)}var jut,EA,Yut,u3,$Rr,Hut,Mut,Ov,Uut,qRr,jRr,YRr,HRr,f3,$ye,Bv,vun,Nv,$ut,Gut,VRr,WRr,Vut,jye=J(()=>{"use strict";qi();a3();rM();it();Xi();Ht();Uye();jut=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","JOURNAL","CASH_ENTRY"],EA=["TRANSACTIONS","LINE_ITEMS"],Yut={TRANSACTIONS:"/api/v1/ledger/find-fix/transactions/preview",LINE_ITEMS:"/api/v1/ledger/find-fix/line-items/preview"},u3="/api/v1/ledger/find-fix/apply",$Rr=u3.slice(0,u3.lastIndexOf("/")+1),Hut={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"}},Mut=["types","resourceIds","reference","valueDate","contactResourceId"],Ov={TRANSACTIONS:{filter:Mut,change:["contactResourceId","valueDate","capsuleResourceId","tags"]},LINE_ITEMS:{filter:[...Mut,"organizationAccountResourceId"],change:["organizationAccountResourceId","classifierConfig"]}};Uut={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."},qRr=[[/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."]],jRr="Not described by this client version; read the records that carry it.";YRr="OUTCOME_UNKNOWN",HRr=25e3,f3=3e5,$ye=50,Bv=12,vun=new RegExp(`preview\\s?id\\W{0,6}[A-Za-z0-9_-]{${Bv}}(?![A-Za-z0-9_-])`,"i"),Nv=e=>e.resourceId?` (${e.resourceId})`:"",$ut={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${Nv(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${Nv(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${Nv(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${Nv(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${Nv(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${Nv(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."}};Gut="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.",VRr="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.",WRr="Nothing changed: every record in the preview failed.",Vut="The outcome is unknown: the apply may keep running for up to 4 minutes."});async function m3(e,t){return e.list("/api/v1/nano-classifiers",t)}async function KE(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function A3(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function tF(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function rF(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,{...r,resourceId:t})}async function g3(e,t,r){if(r.classes&&r.classes.length>0)return{classes:r.classes};if(r.format)return r.format==="CUSTOM"?await XRr(e,t):{};let{data:n}=await KE(e,t);return n?.format&&n.format!=="CUSTOM"?{format:n.format}:Kut(n)}async function XRr(e,t){let{data:r}=await KE(e,t);return Kut(r)}function Kut(e){let t=(e?.classes??[]).find(r=>!r.deleted&&r.resourceId);return t?{classes:[{className:t.className,resourceId:t.resourceId}]}:{}}async function y3(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}function Xut(e,t="classifierConfig"){if(e==null)return;if(!(Array.isArray(e)&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.resourceId=="string")))throw rt(new at(`${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 Zut(e,t){let r=new Map((Array.isArray(e)?e:[]).map(n=>[n?.resourceId,IM(n)]));for(let n of t)n.deleted===!0?r.delete(n.resourceId):r.set(n.resourceId,IM(n));return[...r.values()]}var Wut,Yye=J(()=>{"use strict";Xi();it();yf();Wut=["CUSTOM","ALL_CUSTOMERS","ALL_SUPPLIERS","ALL_CONTACTS","ALL_EMPLOYEES","ALL_USERS"]});async function E3(e,t){return e.post("/api/v1/export-records",t,Ge)}async function I3(e,t){return e.post("/api/v1/export-records/preview",t,Ge)}async function b3(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var Hye=J(()=>{"use strict";Ht()});function _3(e,t){if(!t.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...t].join(", ")}`)}function ndt(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 C3(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 w3(e,t,r){return _3(t,tdt),eo(r,"resourceId","Pass the document resourceId."),e.post(`/api/v1/${Oc(bp,t)}/${encodeURIComponent(r)}/approve`,void 0,tBe)}async function v3(e,t,r){return _3(t,tdt),ndt(r,ZRr,"bulk approve",!0),r.forEach(n=>eo(n,"resourceIds[]","Every id must be a document resourceId.")),e.post(`/api/v1/${Oc(bp,t)}/bulk-approve`,{resourceIds:r},rBe)}async function S3(e,t,r,n){_3(t,rdt),eo(r,"resourceId","Pass the document resourceId."),idt(n);let i=await e.post(`/api/v1/${Oc(XE,t)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:rTr(i)}}}async function D3(e,t,r,n){return _3(t,rdt),idt(n),ndt(r,eTr,"bulk request changes"),r.forEach(i=>eo(i,"resourceIds[]","Every id must be a document resourceId.")),e.post(tTr(t),{resourceIds:r,message:n})}function tTr(e){return e==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${Oc(edt,e)}/bulk-request-changes`}function idt(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 rTr(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 bp,edt,XE,tdt,rdt,ZRr,eTr,zye=J(()=>{"use strict";it();Ht();bp=["invoices","bills","customer-credit-notes","supplier-credit-notes"],edt=[...bp,"purchase-orders","purchase-requests","sale-orders","sale-quotes"],XE=[...edt,"claims"],tdt=new Set(bp),rdt=new Set(XE);ZRr=100,eTr=500});function nTr(e,t,r){let n=Math.random().toString(36).slice(2,10);return`restore:${e}:${odt(t)}:${odt(r)}:${n}`}function odt(e){return e.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function Jye(e){if(!sdt.has(e))throw new ue(`unknown entity "${e}" \u2014 expected one of ${[...sdt].join(", ")}`)}async function adt(e,t,r){return Jye(t),eo(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}`)}async function cdt(e,t,r,n){return Jye(t),eo(r,"resourceId","Pass the document resourceId."),e.get(`/api/v1/rollback/${encodeURIComponent(t)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function ldt(e,t,r,n,i){if(Jye(t),eo(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??nTr(t,r,n)}})}async function udt(e,t,r){return e.get(`/api/v1/organization/currencies/${encodeURIComponent(t)}/effective-rate`,r?{date:r}:void 0)}var sdt,ddt=J(()=>{"use strict";it();sdt=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function iTr({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 at(`${n} must be a whole number of 1 or more (got ${i}).`);if(r===void 0)throw new at("This schedule has no periods, so there is no range to read.");if(n==="fromPeriod"&&i>r)throw new at(`${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 at(`fromPeriod ${e} is after toPeriod ${t}. Send the earlier period as fromPeriod.`)}function R3(e,t,r){let n=e.length;if(iTr(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 at(`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 Fv(e,t={},r=nF){let n=e.data,i=ZE(n.rows),{start:o,end:s,window:a}=R3(Gye(i),t,r);return{...e,data:{...a,...n,rows:i.slice(o,s)}}}function T3(e,t={},r=nF){let n=e.data,i=ZE(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}=R3(Gye(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 fdt(e,t,r,n,i){let o=e.data,s=ZE(o[t]),a=s.reduce((h,m)=>h+ZE(m[r]).length,0),{start:c,end:u,window:d}=R3(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=ZE(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 Td(e,t={},r=nF){let n=e.data,i=ZE(n.periods),{start:o,end:s,window:a}=R3(Gye(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:ZE(n.timeline).filter(d)}}}var nF,ZE,Gye,x3,k3,Lv=J(()=>{"use strict";Xi();nF=60;ZE=e=>Array.isArray(e)?e:[],Gye=(e,t="periodNumber")=>e.map((r,n)=>typeof r[t]=="number"?r[t]:n+1);x3=(e,t={},r=nF)=>fdt(e,"depreciationScheduled","depreciation",t,r),k3=(e,t={},r=nF)=>fdt(e,"amortizationScheduled","amortization",t,r)});async function N3(e,t,r={}){return pdt(t,"depositContactType"),e.list("/api/v1/deposit-accounts",r,{depositContactType:t})}async function O3(e,t){return t.forEach((r,n)=>{if(!r||typeof r!="object"||!("depositContactType"in r))throw rt(new ue(`accounts[${n}].depositContactType is required: CUSTOMER, SUPPLIER, or null to unflag the account. Nothing was changed.`));if(r.depositContactType===null){if(r.restrictPaymentOverdraft===!0)throw rt(new ue(`accounts[${n}].restrictPaymentOverdraft can only be true when depositContactType is CUSTOMER or SUPPLIER. Nothing was changed.`));return}if(pdt(r.depositContactType,`accounts[${n}].depositContactType`),typeof r.restrictPaymentOverdraft!="boolean")throw rt(new ue(`accounts[${n}].restrictPaymentOverdraft is required (true or false) when flagging: the platform overwrites the stored value on every call. Nothing was changed.`))}),e.put("/api/v1/deposit-accounts",{accounts:t},sBe)}function pdt(e,t){if(!Pv.includes(e))throw rt(new ue(`${t} must be CUSTOMER or SUPPLIER, got ${JSON.stringify(e)}. Nothing was changed.`))}var Pv,Vye=J(()=>{"use strict";it();Ht();Pv=["CUSTOMER","SUPPLIER"]});async function eI(e,t){return e.get(`/api/v1/loans/${t}`)}async function B3(e,t){return e.search("/api/v1/loans/search",{...t,sort:t.sort??{sortBy:["createdAt"],order:"DESC"}})}async function F3(e,t){return e.search("/api/v1/loan-types/search",{...t,sort:t.sort??{sortBy:["typeName"],order:"ASC"}})}async function L3(e,t){return e.post("/api/v1/loans",{...t,saveAsDraft:t.saveAsDraft??!0},hBe)}async function P3(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 eI(e,t)).data).reference),e.put(`/api/v1/loans/${t}`,i)}async function Q3(e,t){await e.delete(`/api/v1/loans/${t}`)}async function M3(e,t,r){return e.post(`/api/v1/close-out/loans/${t}`,{closeOutDate:r,resourceId:t},ite)}async function U3(e,t){return e.post(`/api/v1/reopen/loans/${t}`,{},ite)}async function $3(e,t){return e.get("/api/v1/loans/totals",{endDate:t})}async function q3(e,t,r){return e.get(`/api/v1/loans/${t}/schedule`,{viewDate:r})}async function j3(e,t,r={}){return e.list(`/api/v1/loans/${t}/events`,r)}async function Y3(e,t,r={}){return e.list(`/api/v1/loans/${t}/ledger`,r,{endDate:r.endDate})}async function H3(e,t){return e.post("/api/v1/loans/preview-schedule",t,Ge)}async function z3(e,t){return e.post("/api/v1/loans/calculate-opening-balance",t,Ge)}async function J3(e,t){return ut(t,"loans",500,"loans"),Yo(t,hdt),bn(e,"/api/v1/loans/bulk-upsert","loans",t)}async function G3(e,t){return ut(t,"loans",500,"loans"),Yo(t,oTr),t.forEach((r,n)=>{if(r&&typeof r=="object"&&"tags"in r){let i=r.reference;throw rt(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.`))}}),bn(e,"/api/v1/loans/bulk-update","loans",t)}async function V3(e,t,r,n,i){let o=iF[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},Ge)}return e.post(o.record(r),{...n,resourceId:r},mBe)}var hdt,oTr,iF,Wye=J(()=>{"use strict";en();it();Ht();hdt=["drawdownDate","trackingStartDate","firstRepaymentDate"],oTr=[...hdt,"capitalizationStartDate","capitalizationEndDate"];iF={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 Qv(e){ut(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(!s1e(n.btResourceId))throw new ue(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!sTr.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 W3(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t},Ge);return{data:cTr(r.data)}}function aTr(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 cTr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(aTr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function K3(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function X3(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var sTr,Kye=J(()=>{"use strict";it();rre();en();Ht();sTr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function ydt(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 Xye(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.`);Yo([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&Yo([i],["valueDate"])}async function e9(e,t,r=Zye){return e.post("/api/v1/search-magic-reconciliation",t,{...Ge,timeoutMs:r})}function Z3(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function fTr(e){let t=Z3(e.confidenceScore);if(t!==void 0)return{value:t,from:"confidenceScore"};let r=Z3(e.matchScore);return r!==void 0?{value:r,from:"matchScore"}:void 0}function pTr(e){return e?e.value>=(e.from==="confidenceScore"?lTr:uTr)?"high":e.value>=dTr?"medium":"low":"low"}function mTr(e){let t=e.recommendationType;if(typeof t!="string"||!Object.hasOwn(mdt,t))return;let r=mdt[t]??{};return Object.keys(r).find(n=>{let i=r[n]??[],o=e[n];return typeof o!="string"||!i.includes(o)})}function IA(e){let t=e?.name;return typeof t=="string"&&t!==""?t:void 0}function Adt(e){let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));return Object.keys(t).length>0?t:void 0}function ATr(e){let t=n=>typeof n=="number"&&!Number.isNaN(n)?n:void 0,r=(Array.isArray(e.entryLines)?e.entryLines:[]).map(n=>Adt({account:IA(n?.account),taxProfile:IA(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(!(!IA(e.contact)&&!IA(e.account)&&!IA(e.taxProfile)&&!r.some(n=>n.account||n.taxProfile)))return Adt({contact:IA(e.contact),account:IA(e.account),taxProfile:IA(e.taxProfile),reference:typeof e.reference=="string"&&e.reference!==""?e.reference:void 0,lines:r.length>0?r:void 0})}function Edt(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=>bTr(c,h??{},u.length-1,t)).sort(gTr),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 gTr(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 yTr(e){let t=typeof e.recommendationId=="string"?e.recommendationId.trim():"";return Nc.test(t)?t:void 0}function ETr(e){let{recommendationId:t,...r}=e;return r}function ITr(e,t,r){return!t||!r?t:e===tI.learnedPrediction?{...t,recommendationId:r}:e===tI.magicMatch&&Array.isArray(t.entries)?{...t,entries:t.entries.map(n=>({...n,recommendationId:r}))}:t}function bTr(e,t,r,n){let i=typeof t.recommendationType=="string"?t.recommendationType:void 0,o=Z3(t.matchScore),s=Z3(t.confidenceScore),a=fTr(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=tI.magicMatch,A={...n.bankAccountResourceId?{bankAccountResourceId:n.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:e,matchedBusinessTransactions:f}]}):d&&(m=tI.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=tI.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=tI.applyBankRule,A={actionShortcutResourceId:G,businessTransactionResourceIds:[e]});break}default:break}let g=ITr(m,A,yTr(t)),y=m?pTr(a):"low",I=typeof h=="number"&&!Number.isNaN(h),E=n.autoCommitMaxAmount!==void 0,C=!E||I&&Math.abs(h)<=n.autoCommitMaxAmount,w=m!==tI.withPayments||I,T=mTr(t),D=!m||!g?"NO_PLAN":T?hTr[T]:y!=="high"?"BELOW_THRESHOLD":!w||E&&!I?"AMOUNT_UNKNOWN":C?void 0:"ABOVE_AMOUNT_CAP",N=ATr(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}:{},...N?{proposedPosting:N}:{},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(ETr(t))}`}}function _Tr(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 CTr(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 po(e,i):await Eo(e,i);return{type:a,reference:c.reference,amount:t.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${cl(c)}`)}return{type:"transaction",amount:t.matchAmount,count:o,resourceId:i}}async function Idt(e,t,r){let n=r.filter(u=>u.recommendedTool&&!u.autoCommitEligible),i=n.slice(0,gdt);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 b_(e,t,{filter:{resourceId:{in:u}},limit:gdt}),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: ${cl(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 _Tr(u,f,await CTr(e,u,f?.netAmount,s),a)})),...s.length?{partialFailures:s}:{}}}async function t9(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t,Ks)}async function r9(e,t){return e.post("/api/v1/reconciliations/bank-rule",t,Ks)}async function n9(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t,Ks)}async function i9(e,t){return e.post("/api/v1/reconciliations/cash-journal",t,Ks)}async function o9(e,t){return e.post("/api/v1/reconciliations/manual-journal",t,Ks)}async function s9(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t,Ks)}async function a9(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t,Ks)}async function c9(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t,Ks)}async function l9(e,t){return e.post("/api/v1/reconciliations/with-payments",t,Ks)}async function u9(e,t){return e.post("/api/v1/reconciliations/match-to-transaction",t,Ks)}async function d9(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t,Ks)}async function f9(e,t){return e.post("/api/v1/reconciliations/magic-match",t,Ks)}async function p9(e,t){return e.post("/api/v1/reconciliations/reset",t)}var tI,Zye,lTr,uTr,dTr,hTr,mdt,gdt,h9=J(()=>{"use strict";Ug();yp();it();If();en();oy();Ht();tI={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Zye=6e4;lTr=.9,uTr=.95,dTr=.7;hTr={lifecycleStatus:"LIFECYCLE_NOT_ACTIVE"},mdt={MAGIC_RECONCILE_WITH_CASH_IN_OUT:{lifecycleStatus:["ACTIVE"]}};gdt=25});function da(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 Mo(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),o={valueDate:eEe(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=eEe(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=eEe(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,I=a.debitAmount,E=a.creditAmount,C=a.type??(typeof I=="number"&&I>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 eEe(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 rs(e,t,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=da(e,t,n),a=Mo(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 La,ul,vo,hu,bdt=J(()=>{"use strict";La=[{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}],ul=[...La],vo=La.filter(e=>e.field!=="dueDate"),hu=[{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 xd(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=xc(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),t.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=t.taxProfile),o})}return r}function m9(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=Kb(i);return t.account&&!o.accountResourceId&&(o.accountResourceId=t.account),o})}return r}var _dt=J(()=>{"use strict";yf()});var tEe=J(()=>{"use strict";bdt();yf();_dt()});var oF,A9,Ji,so,rEe=J(()=>{"use strict";oF="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",A9=["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"],Ji="If the result says it runs in the background, do not poll: its result arrives by itself.",so=`Async: returns the final job if it finished, else a jobId \u2192 poll search_background_jobs by resourceId. ${Ji} PARTIAL_SUCCESS: errorDetails.`});function wdt(e){return wTr.get(e)}function vdt(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&&!g9.has(o));return n.length===0?[]:Pi.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 Pi,Cdt,g9,wTr,kd=J(()=>{"use strict";rEe();Mye();Pi=[{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. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). To find specific transfers, use cashflow transaction search (payments_and_search namespace). 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). Deposit accounts: list and flag customer or supplier deposit accounts. 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 (expense claims only, not payroll; payrun posting rules are in payrun_settings): 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 (not payroll, see payrun_processing): 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, and the people on pay runs): 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 ${Lut}. On a record: ${Put}. On lines: ${Qut}. 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, ${A9.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"]},{name:"payrun_settings",title:"Payrun Settings",description:"Payrun setup for employee payroll: pay types (what is paid or deducted on a payslip: salary, overtime, allowance, bonus, deduction, employee or employer tax and contribution, each with its accounts), payrun posting rules (how a payrun books its journal: net pay account, grouping, journal date, reference; one default) and pay profiles (shared pay templates: pay frequency, currency, posting rule, pro-rate method, pay type lines with amounts or left per employee). Search, create, update, delete each; get one. Not claim posting rules (posting_rules) and not expense claims.",groups:["pay_types","payrun_posting_rules","pay_profiles"]},{name:"employee_pay",title:"Employee Pay",description:"Employee pay details: put an employee on a pay profile from a date with their own pay figures (salary), one or many at once. A raise is a new pay detail from the new date, not an edit. Search pay details and pay history, in force on a day; correct one in place or end an employee's pay.",groups:["employee_pay_details"]},{name:"payruns",title:"Payruns",description:"Employee pay runs: one run for a period, one pay frequency and one currency, holding a payslip per employee. Create (REGULAR or OFF_CYCLE, fill from pay profiles at once or later), search, get, edit and delete a draft, delete several drafts at once, add or remove employees, fill from pay profiles (with a preview), and save a payslip's lines by hand. Not expense claims.",groups:["payruns"]},{name:"payslips",title:"Payslips",description:"Payslips of employee pay runs: search across runs (an employee's payslips, a run's payslips), get one with its lines and PDF link, rebuild one or several draft payslips from current pay, and make the PDFs of a finalized run again. Lines are edited with save_payrun_lines.",groups:["payslips"]},{name:"payrun_processing",title:"Payrun Processing",description:"Process employee pay runs: validate a draft and preview its journal, finalize payruns (posts one journal each; one or several at once), unpost a finalized run back to draft to correct it, void a run for good with a reason, and record payouts already paid outside Jaz (preview first; part amounts allowed; books only, no money moves) and void a recorded payout. Not expense claims.",groups:["payrun_processing"]}],Cdt=[{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."}],g9=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"]),wTr=new Map(Pi.flatMap(e=>e.groups.map(t=>[t,e.name])))});function Nd(e){return e.trim().toLowerCase().replace(/[\s\-_]+/g,"")}function vTr(e){let t=Sdt.get(e);if(!t){t=new Map;for(let[r,n]of Object.entries(e.valueAliases??{}))e.enum?.includes(n)&&t.set(Nd(r),n);for(let r of e.enum??[])t.set(Nd(r),r);Sdt.set(e,t)}return t}function Ddt(e,t){if(typeof e!="string"||!t.enum||t.enum.includes(e))return null;let r=Nd(e);if(!r)return null;let n=vTr(t).get(r);return n!==void 0&&n!==e?n:null}function STr(e){let t=Rdt.get(e);return t||(t=new Map(Object.keys(e).map(r=>[Nd(r),r])),Rdt.set(e,t)),t}function DTr(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 RTr(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 nEe(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=STr(t);for(let[c,u]of Object.entries(i)){let d=u,f=c;if(c!=="__proto__"&&!t[c]){let A=Nd(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"?DTr(d):RTr(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=Ddt(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,I)=>{let E=Ddt(y,p.items);return E===null?y:(n.push({path:`${r}${f}[${I}]`,from:y,to:E,kind:"value"}),A=!0,E)});A&&(s()[f]=g);continue}let m=ure(p,d);if(m?.kind==="array"){let A=!1,g=m.rows.map(y=>{let I=nEe(y,m.schema,`${r}${f}[].`,n);return I!==y&&(A=!0),I});A&&(s()[f]=g)}else if(m?.kind==="object"){let A=nEe(m.value,m.schema,`${r}${f}.`,n);A!==m.value&&(s()[f]=A)}}return o??e}function Tdt(e,t){if(e.readOnly)return{input:t,coercions:[]};let r=[];return{input:nEe(t,e.params,"",r),coercions:r}}function xdt(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 Sdt,Rdt,iEe=J(()=>{"use strict";R$();Sdt=new WeakMap;Rdt=new WeakMap});function Mv(e){let t=new Set,r=[];for(let n of e)for(let i of mu(n))t.has(i.name)||(t.add(i.name),r.push(i));return r}function sF(){return Pi.map(e=>{let t=Mv(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 TTr(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 xTr(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 bA(e,t=!1){let r=_A(void 0).length,n=Pi.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:xTr(r)}:e&&i!==void 0?{packaging:TTr(e,i,r)}:{},map:sF(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var y9=J(()=>{"use strict";kd();Au()});function E9(e){let t={type:e.nullable?[e.type,"null"]:e.type};if(e.description&&(t.description=e.description),e.enum&&(t.enum=e.nullable?[...e.enum,null]:e.enum),e.type==="array"&&e.items&&(t.items=E9(e.items)),e.type==="object"&&e.properties){let r={};for(let[n,i]of Object.entries(e.properties))r[n]=E9(i);t.properties=r,e.required?.length&&(t.required=[...e.required])}return t}function gu(e,t){let r={};for(let[n,i]of Object.entries(e))r[n]=E9(i);return{type:"object",properties:r,...t.length>0?{required:t}:{}}}function aF(e){return{name:e.name,description:e.description,input_schema:gu(e.params,e.required),...e.searchHint?{searchHint:e.searchHint}:{}}}var Uv=J(()=>{"use strict"});function cF(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 oEe(e){return e.openWorld??(e.acceptsHostFile===!0||Object.keys(e.params).some(t=>/url$/i.test(t)))}function I9(e){return{readOnlyHint:e.readOnly,destructiveHint:!e.readOnly&&cF(e),idempotentHint:e.readOnly,openWorldHint:oEe(e)}}function NTr(e){return e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function OTr(e){let t=NTr(e);return!t||kTr.has(t)?!0:t.split(" ").filter(n=>n.length>=2&&!g9.has(n)).length===0}function sEe(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 aEe(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?aEe(o,`${i}.`):[]]})}function FTr(e,t){let r=`${e.name} ${e.searchHint??""} ${e.description.split(`
|
|
663
663
|
`)[0]}`.toLowerCase(),n=[...e.description.split(`
|
|
664
664
|
`).slice(1),...aEe(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>kdt?`${o.slice(0,kdt-1)}\u2026`:o}}function b9(e,t="meta"){let r=t==="meta"?"search_tools with an empty query":"describe_capabilities with no arguments";if(OTr(e)){if(t!=="meta")return bA(t);let{next:a,...c}=bA();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=Ql(e.trim());if(n)return{matches:[],hint:n};let i=vdt(e,5);if(i.length===0){let{operations:a,namespaces:c}=bA();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=>mu(m)),u=c.map(m=>`${m.name} ${(m.aliases??[]).join(" ")} ${m.searchHint??""} ${m.description} ${aEe(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((I,E)=>g.includes(E)?I+(d.get(E)??0):I,0)+f.filter(I=>g.includes(I)).length;return{tool:m,score:y}}).sort((m,A)=>A.score-m.score),h=[...d].filter(([m,A])=>A>0&&m.length>=3&&!g9.has(m)&&!BTr.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?FTr(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. ${sEe(t)}`}}function Ndt(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=lF(n);if(!i){r.push(n);continue}t.push({...aF(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&cF(i),group:i.group})}return{tools:t,...r.length>0?{notFound:r,hint:r.map(Ql).find(Boolean)??`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var kTr,kdt,BTr,LTr,PTr,QTr,$v,CA,rI=J(()=>{"use strict";kd();y9();Au();Uv();Dg();kTr=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"]);kdt=160,BTr=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"]);LTr={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:gu({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};PTr={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:gu({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},QTr={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:gu({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"])},$v={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:gu({},[])},CA=[LTr,PTr,QTr]});function qTr(e){if(!(Pa in e))return{cleanedInput:e};let{[Pa]:t,...r}=e;return{jotText:typeof t=="string"&&t.trim()!==""?t.trim():void 0,cleanedInput:r}}function uF(e){return!e.readOnly&&!e.params[Pa]&&e.group!=="jots"}function Fdt(e,t){if(e.params[Pa])return{cleanedInput:t};let{jotText:r,cleanedInput:n}=qTr(t);return uF(e)?{jotText:r,cleanedInput:n}:{cleanedInput:n}}function jTr(e){let t=UTr.exec(e);return t?{kind:t[1],call:e.slice(t[0].length)||e}:{call:e}}function HTr(e){let t=e.toLowerCase();for(let[r,n]of YTr)if(n.test(t))return r}function zTr(e,t){let r=HTr(e),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=Odt||a>$Tr||!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>=Odt)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 _9(e,t,r,n){let{kind:i,call:o}=jTr(r),s=zTr(t,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${t}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};yv(e,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(QD(),PD)).then(({log:d})=>d.error({tool:t,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${t}): ${u}
|
|
@@ -804,7 +804,7 @@ A draft needs only reference; saveAsDraft: false also needs the lines, typeCode,
|
|
|
804
804
|
- Give a payTypeInputs figure for every profile line left without an amount: a payrun skips the employee until then. A pay type not on the profile is an extra for this employee.
|
|
805
805
|
- Several employees: bulk_create_employee_pay_details.`,params:{...lft},required:["employeeResourceId","payProfileResourceId","effectiveFromDate"],group:"employee_pay_details",readOnly:!1,searchHint:"create employee pay detail salary raise",execute:async(e,t)=>s4(e.client,t)},{name:"bulk_create_employee_pay_details",description:"Put up to 500 employees on pay profiles. Rows save separately; refusals do not fail the call. Reply: createdCount, failedCount, byErrorCode, then a result per row, refused first, each with its 1-based rowIndex in the request. Report refusals by employee.",params:{employeePayDetails:{type:"array",description:"Pay details to add (max 500)",items:{type:"object",properties:{...lft},required:["employeeResourceId","payProfileResourceId","effectiveFromDate"]}}},required:["employeePayDetails"],group:"employee_pay_details",readOnly:!1,searchHint:"bulk create employee pay details",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>Cut(await a4(e.client,t.employeePayDetails))},{name:"update_employee_pay_detail",description:"Correct a pay detail in place, or end the employee's pay with effectiveToDate (the last day). Partial. Not for a raise: create a new pay detail. payTypeInputs replaces EVERY figure. Dates change on the employee's latest pay detail only.",params:{resourceId:{type:"string",description:"Employee pay detail resourceId"},effectiveFromDate:{type:"string",description:"YYYY-MM-DD. Corrected first day"},effectiveToDate:{type:"string",description:"YYYY-MM-DD. Last day the pay applies"},notes:{type:"string",description:"Notes (max 500)"},payTypeInputs:qft,clearEffectiveToDate:{type:"boolean",description:"true removes the end date"},clearNotes:{type:"boolean",description:"true empties the notes"}},required:["resourceId"],group:"employee_pay_details",readOnly:!1,isDestructive:!0,searchHint:"update end employee pay detail",execute:async(e,t)=>{let{resourceId:r,...n}=t;return c4(e.client,r,n)}},yt({name:"search_payruns",description:"Search payruns (employee pay runs) by status, payout status, payment date, period, size. No query: use the filters. Rows are headers and totals: get_payrun has the payslips.",group:"payruns",fields:tx,defaults:rx,fetcher:async(e,t)=>_ut(await l4(e,t)),extraParams:nx,searchHint:"find payruns pay runs payroll period status net pay"}),{name:"get_payrun",description:"Get one payrun: a row per payslip (lines: get_payslip), journal, attachments. payouts true: payout rows instead.",params:{resourceId:{type:"string",description:"Payrun resourceId"},payouts:{type:"boolean",description:"true: payout rows"}},required:["resourceId"],group:"payruns",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,truncationHint:XB,searchHint:"get payrun payslips totals",execute:async(e,t)=>{let r=await vv(e.client,t.resourceId);return t.payouts===!0?dut(r):N4(r)}},{name:"create_payrun",description:`Create a DRAFT payrun: a run for one period, pay frequency and currency, with a payslip per employee. Those three and the type cannot change later.
|
|
806
806
|
- REGULAR is the run for a period; OFF_CYCLE is an extra one (bonus, correction). Several drafts per period are fine; only one REGULAR run per frequency, currency and period can be finalized (finalize_payrun, after validate_payrun).
|
|
807
|
-
- populate true fills it from pay profiles now; skipped in the result lists who was left out; else it starts empty.`,params:{...uft,payrunType:{type:"string",enum:[...x_],description:"Default REGULAR"},payFrequency:{type:"string",enum:[...zl],description:"Only employees on a pay profile with this frequency join"},currencyCode:{type:"string",description:"ISO 4217, base or active. Only employees on a pay profile in it join"},periodStartDate:{type:"string",description:"YYYY-MM-DD, first day paid for"},periodEndDate:{type:"string",description:"YYYY-MM-DD, last day paid, on or after the start"},populate:{type:"boolean",description:"true fills it from pay profiles now"},idempotencyKey:{type:"string",description:"Up to 255. Auto-generated; pass your own to dedup across calls"}},required:["name","payFrequency","currencyCode","periodStartDate","periodEndDate","paymentDate"],group:"payruns",readOnly:!1,searchHint:"create payrun pay run payroll period",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>HE(await u4(e.client,{...t,idempotencyKey:t.idempotencyKey||fEe()}))},{name:"update_payrun",description:"Edit a DRAFT payrun's header. Partial; a clear flag true empties that field. A finalized run takes only its payslip template, sent alone; generate_payslips remakes the PDFs. Any other change, or any to a void run, is refused (PAYRUN_NOT_DRAFT): unpost_payrun first. Changing the period leaves existing payslips as they are: refresh_payslips rebuilds them for it.",params:{resourceId:{type:"string",description:"Payrun resourceId"},...uft,periodStartDate:{type:"string",description:"YYYY-MM-DD"},periodEndDate:{type:"string",description:"YYYY-MM-DD"},clearReference:{type:"boolean",description:"true empties the reference"},clearInternalNotes:{type:"boolean",description:"true empties the internal notes"},clearPayrunPostingRuleResourceId:{type:"boolean",description:"true: back to the rule the payslips' pay profiles use"},clearTemplateResourceId:{type:"boolean",description:"true: back to the default payslip template"}},required:["resourceId"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"edit payrun draft period payment date reference",maxResultSizeChars:2e4,execute:async(e,t)=>{let{resourceId:r,...n}=t;return HE(await d4(e.client,r,n))}},gr("delete_payrun","Delete a new DRAFT payrun and its payslips. A finalized run is refused (PAYRUN_NOT_DRAFT), so is one finalized then unposted (PAYRUN_ALREADY_POSTED): void_payrun it. A finalized run: unpost_payrun then edit. Several: bulk_delete_payruns. "+ns,"payruns",(e,t)=>f4(e,t),"delete payrun draft"),{name:"bulk_delete_payruns",description:`Delete several new DRAFT payruns, each on its own (ASYNC): one that cannot go (finalized, posted before: void_payrun, not found) fails in errorDetails, the rest are deleted. A run listed twice is refused (PAYRUN_DUPLICATE). ${Ji} ${ns}`,params:{resourceIds:{type:"array",items:{type:"string"},description:"Payrun resourceIds, each once"}},required:["resourceIds"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"bulk delete many draft payruns",backgroundJob:vn("Delete","payrun","payruns","resourceIds"),execute:async(e,t)=>p4(e.client,t.resourceIds)},{name:"add_payrun_employees",description:"Add employees to a DRAFT payrun. One removed earlier gets their old payslip back; others get a payslip made from their pay in the period. An active employee with no pay in the period gets an empty payslip: fill it with save_payrun_lines. The first employee who cannot be added (inactive, other frequency or currency, missing figure) refuses the whole call.",params:{resourceId:{type:"string",description:"Payrun resourceId"},employeeResourceIds:pft},required:["resourceId","employeeResourceIds"],group:"payruns",readOnly:!1,searchHint:"add employees to payrun payslip",maxResultSizeChars:5e4,truncationHint:XB,execute:async(e,t)=>N4(await h4(e.client,t.resourceId,t.employeeResourceIds))},{name:"remove_payrun_employees",description:"Remove employees' payslips from a DRAFT payrun. One not in the run is ignored. They stay out when the run is filled again: add_payrun_employees brings the payslip back.",params:{resourceId:{type:"string",description:"Payrun resourceId"},employeeResourceIds:pft},required:["resourceId","employeeResourceIds"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"remove employees from payrun payslip",maxResultSizeChars:5e4,truncationHint:XB,execute:async(e,t)=>N4(await m4(e.client,t.resourceId,t.employeeResourceIds))},{name:"save_payrun_lines",description:"Set the lines of payslips in a DRAFT payrun. A payslip's lines list replaces the whole list: a line with resourceId is kept or changed, one without is added, one left out is removed. Amounts 0 or more, 2 decimals; pay types ACTIVE. Any refusal changes nothing; payslips not named are untouched. Lines added by hand are never pro-rated and survive a refresh. Reply: the payslips named, no lines (get_payslip).",params:{resourceId:{type:"string",description:"Payrun resourceId"},payslips:{type:"array",description:"Payslips to change, each once",items:{type:"object",properties:{payslipResourceId:{type:"string",description:"Payslip resourceId"},lines:{type:"array",description:"Every line the payslip ends up with, in order. [] removes all. Omit to keep",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line to keep or change; omit to add"},payTypeId:{type:"string",description:"Pay type resourceId"},amount:{type:"number",description:"0 or more, 2 decimals"},description:{type:"string",description:"Max 500"}},required:["payTypeId","amount"]}},notes:{type:"string",description:"Printed on the payslip (max 500)"},clearNotes:{type:"boolean",description:"true empties the notes"}},required:["payslipResourceId"]}}},required:["resourceId","payslips"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"save payslip lines manual amounts bonus payrun",maxResultSizeChars:5e4,truncationHint:XB,execute:async(e,t)=>Eut(await A4(e.client,t.resourceId,t.payslips))},{name:"populate_payrun",description:"Fill a DRAFT payrun from pay profiles: adds every employee not yet in it whose pay overlaps the period on an active profile with the run's frequency and currency, pro-rated where pay changes. Existing payslips are never changed (refresh_payslips does). Removed employees stay out. Reply: skipped first (byErrorCode), addedCount, the run header. Someone with no pay: add_payrun_employees.",params:{resourceId:{type:"string",description:"Payrun resourceId"}},required:["resourceId"],group:"payruns",readOnly:!1,searchHint:"populate fill payrun from pay profiles",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>fut(await g4(e.client,t.resourceId))},{name:"preview_populate_payrun",description:"Preview populate_payrun on a DRAFT payrun, saving nothing. skipped first (byErrorCode), including who has no pay set up (add_payrun_employees gives them an empty payslip). addedCount is who it would add. added true lists them, skipped only counted. Employees already in the run are not listed.",params:{resourceId:{type:"string",description:"Payrun resourceId"},added:{type:"boolean",description:"true lists who would be added"}},required:["resourceId"],group:"payruns",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview populate who would be added",maxResultSizeChars:5e4,truncationHint:cut,execute:async(e,t)=>put(await zB(e.client,t.resourceId),t.added===!0)},yt({name:"search_payslips",description:"Search payslips across payruns: a row each with payout status, no lines (get_payslip). No query: use the filters. An employee's, newest first: employeeResourceId and payrunStatus FINALIZED. A run's: payrunResourceId.",group:"payslips",fields:ix,defaults:ox,fetcher:async(e,t)=>but(await D4(e,t)),searchHint:"find payslips by employee payrun payout status"}),{name:"get_payslip",description:"Get one payslip: every line with its id (what save_payrun_lines needs), amounts, payout status, employee, pay profile, its payrun's period and payment date, and generatedDocuments (the PDF link, once made).",params:{resourceId:{type:"string",description:"Payslip resourceId"}},required:["resourceId"],group:"payslips",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"get payslip lines pdf",execute:async(e,t)=>Iut(await GB(e.client,t.resourceId))},{name:"refresh_payslip",description:`Rebuild one DRAFT payrun payslip from current pay: pay-setup lines are replaced (hand edits lost), lines added by hand stay. No pay in period: refused, unchanged (PAYRUN_EMPLOYEE_NO_PAY_PROFILE). Several: refresh_payslips. ${ns}`,params:{resourceId:{type:"string",description:"Payslip resourceId"}},required:["resourceId"],group:"payslips",readOnly:!1,isDestructive:!0,searchHint:"refresh payslip current pay",execute:async(e,t)=>gut(await nut(e.client,t.resourceId))},{name:"refresh_payslips",description:`Rebuild payslips of a DRAFT payrun from current pay: pay-setup lines are replaced (hand edits lost), lines added by hand stay. One that cannot be refreshed stays unchanged, listed in failed with errorCode. Reply: failed first, refreshedCount, payslips changed, the run header. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},payslipResourceIds:{type:"array",items:{type:"string"},description:"Payslips of this run, each once. Omit for all"}},required:["resourceId"],group:"payslips",readOnly:!1,isDestructive:!0,searchHint:"refresh all payslips payrun current pay",maxResultSizeChars:Dye,truncationHint:yA,execute:async(e,t)=>yut(await iut(e.client,t.resourceId,t.payslipResourceIds))},{name:"generate_payslips",description:`Make the payslip PDFs of a FINALIZED payrun again (ASYNC), for payslips named or all: one that failed, or after a template change. finalize_payrun makes them once itself. A new link replaces the old in generatedDocuments (get_payslip). ${Ji}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},payslipResourceIds:{type:"array",items:{type:"string"},description:"Payslips of this run, each once. Omit for all"}},required:["resourceId"],group:"payslips",readOnly:!1,searchHint:"generate payslip pdf again finalized payrun async job",backgroundJob:lI(e=>`Make payslip PDFs${Array.isArray(e.payslipResourceIds)&&e.payslipResourceIds.length?` for ${cI(e.payslipResourceIds.length,"payslip","payslips")}`:""}`),execute:async(e,t)=>R4(e.client,t.resourceId,t.payslipResourceIds)},{name:"validate_payrun",description:"Check a DRAFT payrun as finalize_payrun would, listing every problem at once; writes nothing. valid true: finalize would go ahead. errors (absent when none): each has a code (PAYSLIP_NO_LINES, PAYRUN_NET_PAY_NEGATIVE, PAYRUN_PERIOD_LOCKED), a message and what it is about.",params:{resourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["resourceId"],group:"payrun_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"validate payrun before finalize",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>O4(await y4(e.client,t.resourceId,t.journalValueDate))},{name:"preview_payrun_journal",description:"Preview the journal finalize_payrun would post for a DRAFT payrun, with validate_payrun's errors; writes nothing. Debits first, one net pay credit last: totals must match and valid be true.",params:{resourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["resourceId"],group:"payrun_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview payrun journal",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>O4(await E4(e.client,t.resourceId,t.journalValueDate))},{name:"finalize_payrun",description:`Finalize ONE DRAFT payrun (several: bulk_finalize_payruns): posts ONE balanced journal and makes the payslip PDFs. A ledger write: validate_payrun and preview_payrun_journal first. Blocked by a payslip with no lines, negative net pay, a journal date on or before the lock date, or another finalized REGULAR run for its frequency, currency and period. A FINALIZED run comes back unchanged. A mistake: unpost_payrun. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["resourceId"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"finalize payrun post journal payslips pdf",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await I4(e.client,t.resourceId,t.journalValueDate))},{name:"bulk_finalize_payruns",description:`Finalize several DRAFT payruns, each as finalize_payrun does and on its own (ASYNC): one that cannot go fails in errorDetails, the rest are finalized (PARTIAL_SUCCESS). A run listed twice is refused (PAYRUN_DUPLICATE). Validate each first. ${Ji} ${ns}`,params:{payruns:{type:"array",description:"Payruns to finalize, each once",items:{type:"object",properties:{payrunResourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["payrunResourceId"]}}},required:["payruns"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk finalize payruns",backgroundJob:vn("Finalize","payrun","payruns","payruns"),execute:async(e,t)=>b4(e.client,t.payruns)},{name:"unpost_payrun",description:`Unpost a FINALIZED payrun to correct it: its journal is voided and it goes back to DRAFT; finalize_payrun again posts a new one. Refused while a payout is live (PAYRUN_PAYOUT_LINKED: void_payrun_payout first) and into a locked period. Wrong amount, not paid: unpost, fix, finalize. Employee got too much: deduct in a later run; too little: an off-cycle run. Cancel for good: void_payrun. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"}},required:["resourceId"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"unpost payrun back to draft",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await _4(e.client,t.resourceId))},{name:"void_payrun",description:`Void a payrun for good, with a reason: a FINALIZED run's journal is voided and its period is free for a new REGULAR run. Same refusals as unpost_payrun (live payouts, locked period). A draft never posted is refused (PAYRUN_VOID_NEVER_POSTED): delete_payrun it. A run unposted earlier cannot be deleted: void it. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},voidReason:{type:"string",description:"The cause the user gave, up to 500 characters"}},required:["resourceId","voidReason"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"void cancel payrun reason finalized",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await C4(e.client,t.resourceId,t.voidReason))},{name:"preview_payrun_payouts",description:"Preview recording payouts for a FINALIZED payrun; writes nothing. Per payslip: netPayAmount, paidAmount, owedAmount, payoutAmount. errors lists every problem (PAYRUN_PAYOUT_EXCEEDS_OWED, PAYRUN_PAYOUT_ACCOUNT_INVALID_TYPE), no rows then. Records only: no money moves.",params:fft,required:["resourceId"],group:"payrun_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview payrun payouts",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>O4(await w4(e.client,t.resourceId,dft(t)))},{name:"record_payrun_payouts",description:`Record a FINALIZED payrun's net pay as paid OUTSIDE Jaz, e.g. by bank transfer (ASYNC): one journal per payslip, debiting net pay and crediting the bank or cash account. It moves no money and pays no one. Payslips left out: all still owed, in full; or name payslips, a part amount allowed. Payslips go UNPAID, PARTIALLY_PAID, PAID. preview_payrun_payouts first. hash dedups only while the job runs (a later re-send records again): read get_payrun before retrying. Undo: void_payrun_payout. ${Ji} ${ns}`,params:{...fft,hash:{type:"string",description:"Auto-generated. Same hash and request while the job runs returns that job"}},required:["resourceId","paymentAccountResourceId"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"record payrun payouts paid outside",backgroundJob:lI(e=>`Record payrun payouts${Array.isArray(e.payslips)&&e.payslips.length?` for ${cI(e.payslips.length,"payslip","payslips")}`:""}`),execute:async(e,t)=>v4(e.client,t.resourceId,{...dft(t),paymentAccountResourceId:t.paymentAccountResourceId,hash:t.hash||fEe()})},{name:"void_payrun_payout",description:`Void one recorded payrun payout, with a reason: the payslip owes that amount again. journalResourceId: a get_payrun payouts row. Needed before unpost_payrun or void_payrun on a paid run. Refused into a locked period. Answers the payrun. ${ns}`,params:{journalResourceId:{type:"string",description:"Payout journal resourceId, from get_payrun payouts"},voidReason:{type:"string",description:"The cause the user gave, in their words or briefly summarised, up to 500 characters; none given: ask once, never invent one"}},required:["journalResourceId","voidReason"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"void payrun payout",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await S4(e.client,t.journalResourceId,t.voidReason))},yt({name:"search_loans",description:"Search loans (borrowings: term loans and director, shareholder, related-party or intercompany accounts). Each row carries outstandingPrincipal, currentPortion, nextDueDate and nextDueAmount as at endDate (default today). No free-text query: use the named filters, then get_loan.",group:"loans",fields:$T,defaults:qT,fetcher:B3,extraParams:jT,searchHint:"find loans borrowings bank loan balance what do we owe lender by status reference type"}),wn("get_loan","Get a loan with its terms, accounts and figures as of today: outstandingPrincipal, accruedInterest, currentPortion, nonCurrentPortion, nextDueDate. Schedule: get_loan_schedule; changes: list_loan_events.","loans",(e,t)=>eI(e,t),"get loan details outstanding principal terms accounts"),{name:"create_loan",description:`Record a borrowing after preview_loan_schedule; several: bulk_upsert_loans. The register books interest every month-end and the current/non-current split. It never posts cash: the user records the drawdown receipt and EVERY installment IN FULL themselves, to the accounts named in the params.
|
|
807
|
+
- populate true fills it from pay profiles now; skipped in the result lists who was left out; else it starts empty.`,params:{...uft,payrunType:{type:"string",enum:[...x_],description:"Default REGULAR"},payFrequency:{type:"string",enum:[...zl],description:"Only employees on a pay profile with this frequency join"},currencyCode:{type:"string",description:"ISO 4217, base or active. Only employees on a pay profile in it join"},periodStartDate:{type:"string",description:"YYYY-MM-DD, first day paid for"},periodEndDate:{type:"string",description:"YYYY-MM-DD, last day paid, on or after the start"},populate:{type:"boolean",description:"true fills it from pay profiles now"},idempotencyKey:{type:"string",description:"Up to 255. Auto-generated; pass your own to dedup across calls"}},required:["name","payFrequency","currencyCode","periodStartDate","periodEndDate","paymentDate"],group:"payruns",readOnly:!1,searchHint:"create payrun pay run payroll period",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>HE(await u4(e.client,{...t,idempotencyKey:t.idempotencyKey||fEe()}))},{name:"update_payrun",description:"Edit a DRAFT payrun's header. Partial; a clear flag true empties that field. A finalized run takes only its payslip template, sent alone; generate_payslips remakes the PDFs. Any other change, or any to a void run, is refused (PAYRUN_NOT_DRAFT): unpost_payrun first. Changing the period leaves existing payslips as they are: refresh_payslips rebuilds them for it.",params:{resourceId:{type:"string",description:"Payrun resourceId"},...uft,periodStartDate:{type:"string",description:"YYYY-MM-DD"},periodEndDate:{type:"string",description:"YYYY-MM-DD"},clearReference:{type:"boolean",description:"true empties the reference"},clearInternalNotes:{type:"boolean",description:"true empties the internal notes"},clearPayrunPostingRuleResourceId:{type:"boolean",description:"true: back to the rule the payslips' pay profiles use"},clearTemplateResourceId:{type:"boolean",description:"true: back to the default payslip template"}},required:["resourceId"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"edit payrun draft period payment date reference",maxResultSizeChars:2e4,execute:async(e,t)=>{let{resourceId:r,...n}=t;return HE(await d4(e.client,r,n))}},gr("delete_payrun","Delete a new DRAFT payrun and its payslips. A finalized run is refused (PAYRUN_NOT_DRAFT), so is one finalized then unposted (PAYRUN_ALREADY_POSTED): void_payrun it. A finalized run: unpost_payrun then edit. Several: bulk_delete_payruns. "+ns,"payruns",(e,t)=>f4(e,t),"delete payrun draft"),{name:"bulk_delete_payruns",description:`Delete several new DRAFT payruns, each on its own (ASYNC): one that cannot go (finalized, posted before: void_payrun, not found) fails in errorDetails, the rest are deleted. A run listed twice is refused (PAYRUN_DUPLICATE). ${Ji} ${ns}`,params:{resourceIds:{type:"array",items:{type:"string"},description:"Payrun resourceIds, each once"}},required:["resourceIds"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"bulk delete many draft payruns",backgroundJob:vn("Delete","payrun","payruns","resourceIds"),execute:async(e,t)=>p4(e.client,t.resourceIds)},{name:"add_payrun_employees",description:"Add employees to a DRAFT payrun. One removed earlier gets their old payslip back; others get a payslip made from their pay in the period. An active employee with no pay in the period gets an empty payslip: fill it with save_payrun_lines. The first employee who cannot be added (inactive, other frequency or currency, missing figure) refuses the whole call.",params:{resourceId:{type:"string",description:"Payrun resourceId"},employeeResourceIds:pft},required:["resourceId","employeeResourceIds"],group:"payruns",readOnly:!1,searchHint:"add employees to payrun payslip",maxResultSizeChars:5e4,truncationHint:XB,execute:async(e,t)=>N4(await h4(e.client,t.resourceId,t.employeeResourceIds))},{name:"remove_payrun_employees",description:"Remove employees' payslips from a DRAFT payrun. One not in the run is ignored. They stay out when the run is filled again: add_payrun_employees brings the payslip back.",params:{resourceId:{type:"string",description:"Payrun resourceId"},employeeResourceIds:pft},required:["resourceId","employeeResourceIds"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"remove employees from payrun payslip",maxResultSizeChars:5e4,truncationHint:XB,execute:async(e,t)=>N4(await m4(e.client,t.resourceId,t.employeeResourceIds))},{name:"save_payrun_lines",description:"Set the lines of payslips in a DRAFT payrun. A payslip's lines list replaces the whole list: a line with resourceId is kept or changed, one without is added, one left out is removed. Amounts 0 or more, 2 decimals; pay types ACTIVE. Any refusal changes nothing; payslips not named are untouched. Hand lines are never pro-rated; refresh replaces those whose pay type is in the pay setup. Reply: the payslips named, no lines (get_payslip).",params:{resourceId:{type:"string",description:"Payrun resourceId"},payslips:{type:"array",description:"Payslips to change, each once",items:{type:"object",properties:{payslipResourceId:{type:"string",description:"Payslip resourceId"},lines:{type:"array",description:"Every line the payslip ends up with, in order. [] removes all. Omit to keep",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line to keep or change; omit to add"},payTypeId:{type:"string",description:"Pay type resourceId"},amount:{type:"number",description:"0 or more, 2 decimals"},description:{type:"string",description:"Max 500"}},required:["payTypeId","amount"]}},notes:{type:"string",description:"Printed on the payslip (max 500)"},clearNotes:{type:"boolean",description:"true empties the notes"}},required:["payslipResourceId"]}}},required:["resourceId","payslips"],group:"payruns",readOnly:!1,isDestructive:!0,searchHint:"save payslip lines manual amounts bonus payrun",maxResultSizeChars:5e4,truncationHint:XB,execute:async(e,t)=>Eut(await A4(e.client,t.resourceId,t.payslips))},{name:"populate_payrun",description:"Fill a DRAFT payrun from pay profiles: adds every employee not yet in it whose pay overlaps the period on an active profile with the run's frequency and currency, pro-rated where pay changes. Existing payslips are never changed (refresh_payslips does). Removed employees stay out. Reply: skipped first (byErrorCode), addedCount, the run header. Someone with no pay: add_payrun_employees.",params:{resourceId:{type:"string",description:"Payrun resourceId"}},required:["resourceId"],group:"payruns",readOnly:!1,searchHint:"populate fill payrun from pay profiles",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>fut(await g4(e.client,t.resourceId))},{name:"preview_populate_payrun",description:"Preview populate_payrun on a DRAFT payrun, saving nothing. skipped first (byErrorCode), including who has no pay set up (add_payrun_employees gives them an empty payslip). addedCount is who it would add. added true lists them, skipped only counted. Employees already in the run are not listed.",params:{resourceId:{type:"string",description:"Payrun resourceId"},added:{type:"boolean",description:"true lists who would be added"}},required:["resourceId"],group:"payruns",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview populate who would be added",maxResultSizeChars:5e4,truncationHint:cut,execute:async(e,t)=>put(await zB(e.client,t.resourceId),t.added===!0)},yt({name:"search_payslips",description:"Search payslips across payruns: a row each with payout status, no lines (get_payslip). No query: use the filters. An employee's, newest first: employeeResourceId and payrunStatus FINALIZED. A run's: payrunResourceId.",group:"payslips",fields:ix,defaults:ox,fetcher:async(e,t)=>but(await D4(e,t)),searchHint:"find payslips by employee payrun payout status"}),{name:"get_payslip",description:"Get one payslip: every line with its id (what save_payrun_lines needs), amounts, payout status, employee, pay profile, its payrun's period and payment date, and generatedDocuments (the PDF link, once made).",params:{resourceId:{type:"string",description:"Payslip resourceId"}},required:["resourceId"],group:"payslips",readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,searchHint:"get payslip lines pdf",execute:async(e,t)=>Iut(await GB(e.client,t.resourceId))},{name:"refresh_payslip",description:`Rebuild one DRAFT payrun payslip from current pay: a pay-setup line replaces every line of its pay type (hand edits, hand lines of it lost); others stay. No pay in period: refused, unchanged (PAYRUN_EMPLOYEE_NO_PAY_PROFILE). Several: refresh_payslips. ${ns}`,params:{resourceId:{type:"string",description:"Payslip resourceId"}},required:["resourceId"],group:"payslips",readOnly:!1,isDestructive:!0,searchHint:"refresh payslip current pay",execute:async(e,t)=>gut(await nut(e.client,t.resourceId))},{name:"refresh_payslips",description:`Rebuild payslips of a DRAFT payrun from current pay: a pay-setup line replaces every line of its pay type (hand edits, hand lines of it lost); others stay. One that cannot be refreshed stays unchanged, listed in failed with errorCode. Reply: failed first, refreshedCount, payslips changed, the run header. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},payslipResourceIds:{type:"array",items:{type:"string"},description:"Payslips of this run, each once. Omit for all"}},required:["resourceId"],group:"payslips",readOnly:!1,isDestructive:!0,searchHint:"refresh all payslips payrun current pay",maxResultSizeChars:Dye,truncationHint:yA,execute:async(e,t)=>yut(await iut(e.client,t.resourceId,t.payslipResourceIds))},{name:"generate_payslips",description:`Make the payslip PDFs of a FINALIZED payrun again (ASYNC), for payslips named or all: one that failed, or after a template change. finalize_payrun makes them once itself. A new link replaces the old in generatedDocuments (get_payslip). ${Ji}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},payslipResourceIds:{type:"array",items:{type:"string"},description:"Payslips of this run, each once. Omit for all"}},required:["resourceId"],group:"payslips",readOnly:!1,searchHint:"generate payslip pdf again finalized payrun async job",backgroundJob:lI(e=>`Make payslip PDFs${Array.isArray(e.payslipResourceIds)&&e.payslipResourceIds.length?` for ${cI(e.payslipResourceIds.length,"payslip","payslips")}`:""}`),execute:async(e,t)=>R4(e.client,t.resourceId,t.payslipResourceIds)},{name:"validate_payrun",description:"Check a DRAFT payrun as finalize_payrun would, listing every problem at once; writes nothing. valid true: finalize would go ahead. errors (absent when none): each has a code (PAYSLIP_NO_LINES, PAYRUN_NET_PAY_NEGATIVE, PAYRUN_PERIOD_LOCKED), a message and what it is about.",params:{resourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["resourceId"],group:"payrun_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"validate payrun before finalize",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>O4(await y4(e.client,t.resourceId,t.journalValueDate))},{name:"preview_payrun_journal",description:"Preview the journal finalize_payrun would post for a DRAFT payrun, with validate_payrun's errors; writes nothing. Debits first, one net pay credit last: totals must match and valid be true.",params:{resourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["resourceId"],group:"payrun_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview payrun journal",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>O4(await E4(e.client,t.resourceId,t.journalValueDate))},{name:"finalize_payrun",description:`Finalize ONE DRAFT payrun (several: bulk_finalize_payruns): posts ONE balanced journal and makes the payslip PDFs. A ledger write: validate_payrun and preview_payrun_journal first. Blocked by a payslip with no lines, negative net pay, a journal date on or before the lock date, or another finalized REGULAR run for its frequency, currency and period. A FINALIZED run comes back unchanged. A mistake: unpost_payrun. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["resourceId"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"finalize payrun post journal payslips pdf",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await I4(e.client,t.resourceId,t.journalValueDate))},{name:"bulk_finalize_payruns",description:`Finalize several DRAFT payruns, each as finalize_payrun does and on its own (ASYNC): one that cannot go fails in errorDetails, the rest are finalized (PARTIAL_SUCCESS). A run listed twice is refused (PAYRUN_DUPLICATE). Validate each first. ${Ji} ${ns}`,params:{payruns:{type:"array",description:"Payruns to finalize, each once",items:{type:"object",properties:{payrunResourceId:{type:"string",description:"Payrun resourceId"},journalValueDate:B9},required:["payrunResourceId"]}}},required:["payruns"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"bulk finalize payruns",backgroundJob:vn("Finalize","payrun","payruns","payruns"),execute:async(e,t)=>b4(e.client,t.payruns)},{name:"unpost_payrun",description:`Unpost a FINALIZED payrun to correct it: its journal is voided and it goes back to DRAFT; finalize_payrun again posts a new one. Refused while a payout is live (PAYRUN_PAYOUT_LINKED: void_payrun_payout first) and into a locked period. Wrong amount, not paid: unpost, fix, finalize. Employee got too much: deduct in a later run; too little: an off-cycle run. Cancel for good: void_payrun. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"}},required:["resourceId"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"unpost payrun back to draft",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await _4(e.client,t.resourceId))},{name:"void_payrun",description:`Void a payrun for good, with a reason: a FINALIZED run's journal is voided and its period is free for a new REGULAR run. Same refusals as unpost_payrun (live payouts, locked period). A draft never posted is refused (PAYRUN_VOID_NEVER_POSTED): delete_payrun it. A run unposted earlier cannot be deleted: void it. ${ns}`,params:{resourceId:{type:"string",description:"Payrun resourceId"},voidReason:{type:"string",description:"The cause the user gave, up to 500 characters"}},required:["resourceId","voidReason"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"void cancel payrun reason finalized",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await C4(e.client,t.resourceId,t.voidReason))},{name:"preview_payrun_payouts",description:"Preview recording payouts for a FINALIZED payrun; writes nothing. Per payslip: netPayAmount, paidAmount, owedAmount, payoutAmount. errors lists every problem (PAYRUN_PAYOUT_EXCEEDS_OWED, PAYRUN_PAYOUT_ACCOUNT_INVALID_TYPE), no rows then. Records only: no money moves.",params:fft,required:["resourceId"],group:"payrun_processing",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview payrun payouts",maxResultSizeChars:5e4,truncationHint:yA,execute:async(e,t)=>O4(await w4(e.client,t.resourceId,dft(t)))},{name:"record_payrun_payouts",description:`Record a FINALIZED payrun's net pay as paid OUTSIDE Jaz, e.g. by bank transfer (ASYNC): one journal per payslip, debiting net pay and crediting the bank or cash account. It moves no money and pays no one. Payslips left out: all still owed, in full; or name payslips, a part amount allowed. Payslips go UNPAID, PARTIALLY_PAID, PAID. preview_payrun_payouts first. hash dedups only while the job runs (a later re-send records again): read get_payrun before retrying. Undo: void_payrun_payout. ${Ji} ${ns}`,params:{...fft,hash:{type:"string",description:"Auto-generated. Same hash and request while the job runs returns that job"}},required:["resourceId","paymentAccountResourceId"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"record payrun payouts paid outside",backgroundJob:lI(e=>`Record payrun payouts${Array.isArray(e.payslips)&&e.payslips.length?` for ${cI(e.payslips.length,"payslip","payslips")}`:""}`),execute:async(e,t)=>v4(e.client,t.resourceId,{...dft(t),paymentAccountResourceId:t.paymentAccountResourceId,hash:t.hash||fEe()})},{name:"void_payrun_payout",description:`Void one recorded payrun payout, with a reason: the payslip owes that amount again. journalResourceId: a get_payrun payouts row. Needed before unpost_payrun or void_payrun on a paid run. Refused into a locked period. Answers the payrun. ${ns}`,params:{journalResourceId:{type:"string",description:"Payout journal resourceId, from get_payrun payouts"},voidReason:{type:"string",description:"The cause the user gave, in their words or briefly summarised, up to 500 characters; none given: ask once, never invent one"}},required:["journalResourceId","voidReason"],group:"payrun_processing",readOnly:!1,isDestructive:!0,searchHint:"void payrun payout",maxResultSizeChars:2e4,execute:async(e,t)=>HE(await S4(e.client,t.journalResourceId,t.voidReason))},yt({name:"search_loans",description:"Search loans (borrowings: term loans and director, shareholder, related-party or intercompany accounts). Each row carries outstandingPrincipal, currentPortion, nextDueDate and nextDueAmount as at endDate (default today). No free-text query: use the named filters, then get_loan.",group:"loans",fields:$T,defaults:qT,fetcher:B3,extraParams:jT,searchHint:"find loans borrowings bank loan balance what do we owe lender by status reference type"}),wn("get_loan","Get a loan with its terms, accounts and figures as of today: outstandingPrincipal, accruedInterest, currentPortion, nonCurrentPortion, nextDueDate. Schedule: get_loan_schedule; changes: list_loan_events.","loans",(e,t)=>eI(e,t),"get loan details outstanding principal terms accounts"),{name:"create_loan",description:`Record a borrowing after preview_loan_schedule; several: bulk_upsert_loans. The register books interest every month-end and the current/non-current split. It never posts cash: the user records the drawdown receipt and EVERY installment IN FULL themselves, to the accounts named in the params.
|
|
808
808
|
- saveAsDraft defaults to true (posts nothing). false activates (Admin only): needs kind, typeCode, name, principalAmount, drawdownDate, the current liability account and, for a term loan, shape, rate, day count and term.
|
|
809
809
|
- Existing loan: send trackingStartDate + openingPrincipalAmount. Its opening balance stays in the user's opening balances.
|
|
810
810
|
- Hire purchase is not a loan: use the leases register.
|
|
@@ -1093,7 +1093,7 @@ Dynamic Strings (usable in name, reference \u2014 any free text field):
|
|
|
1093
1093
|
{{bankPayee}} Payer/payee name (e.g., Fruit Planet)
|
|
1094
1094
|
{{bankDescription}} Transaction description (e.g., QR Payment)
|
|
1095
1095
|
Strings are replaced with actual bank record values during reconciliation.`);lo({parent:t,description:"List bank rules",columns:Jbt,label:"Fetching bank rules",title:"Bank Rules",fetch:(r,n)=>oW(r,n)}),t.command("get <resourceId>").description("Get a bank rule").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await $B(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(S("Name:"),o.data.name),console.log(S("Action:"),o.data.actionType),console.log(S("ID:"),o.data.resourceId);let s=o.data.searchFilter;if(s){let a=typeof s.raw=="string"?s.raw:"";console.log(S("Condition:"),a!==""?a:M("(no one-line form)")),console.log(S("Matches:"),s.parsed?JSON.stringify(s.parsed):M("(not returned)"))}else console.log(S("Condition:"),K("none \u2014 never suggested by auto-reconciliation"))})(n)),Oe({parent:t,fields:Wx,defaults:Kx,fetcher:sW,columns:Jbt,label:"Searching bank rules",positionalArg:"name",positionalFilter:r=>({name:{contains:r}})}),t.command("create").description("Create a bank reconciliation rule").option("--jot <text>",ce).option("--name <name>","Rule name (required)").option("--account <resourceId>","Bank account resourceId this rule applies to (required)").option("--config <json>","Rule configuration as JSON (nested under reconcileWithDirectCashEntry key)").option("--search-filter <json>","Condition deciding which bank lines the rule applies to. Without one the rule is never suggested").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);if(!i){if((!n.name||!n.account)&&(console.error(K("Required: --name, --account")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,appliesToReconciliationAccount:n.account},n.config)try{i.configuration=JSON.parse(n.config)}catch{console.error(K("Invalid --config JSON")),process.exit(1)}if(n.searchFilter)try{i.searchFilter=JSON.parse(n.searchFilter)}catch{console.error(K("Invalid --search-filter JSON")),process.exit(1)}}if(i&&i.searchFilter==null){let s;try{s=nc(n)}catch{s=!0}s||console.error(M("No condition set: the rule will apply by hand, but reconciliation will never suggest it."))}let o=await aW(r,i);if(oe(r,"create_bank_rule",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L("Bank rule created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a bank rule (FULL REPLACEMENT \u2014 reads current state, merges changes, writes back)").option("--jot <text>",ce).option("--name <name>","New name").option("--account <resourceId>","Bank account resourceId (required \u2014 PUT is full replacement)").option("--config <json>","Updated configuration as JSON (full replacement)").option("--search-filter <json>","Replace the condition. Omit to keep the stored one").option("--clear-search-filter","Remove the condition, which stops the rule being suggested").option("--input <file>","Read full update body from JSON file (overrides flags; not combinable with the condition flags)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(n.clearSearchFilter&&n.searchFilter){console.error(K("--search-filter and --clear-search-filter are mutually exclusive")),process.exitCode=1;return}if(n.input&&(n.searchFilter||n.clearSearchFilter)){console.error(K("--input carries the whole body; --search-filter and --clear-search-filter cannot be combined with it")),console.error(M("Put searchFilter in the file instead (null clears it, omitting the key keeps the stored one).")),process.exitCode=1;return}let o=he(n),s;if(o)s={resourceId:r,...o};else{if(!n.account){console.error(K("--account is required for update (PUT is full replacement \u2014 GET does not return the UUID)")),console.error(M("Use: clio bank-rules update <id> --account <bank-account-uuid> [--name ...] [--config ...]")),process.exitCode=1;return}let u=(await $B(i,r)).data;if(s={resourceId:r,name:n.name??u.name,appliesToReconciliationAccount:n.account,configuration:u.configuration},n.config)try{s.configuration=JSON.parse(n.config)}catch{console.error(K("Invalid --config JSON")),process.exit(1)}if(n.clearSearchFilter)s.searchFilter=null;else if(n.searchFilter)try{s.searchFilter=JSON.parse(n.searchFilter)}catch{console.error(K("Invalid --search-filter JSON")),process.exit(1)}}let a=await cW(i,r,s);if(oe(i,"update_bank_rule",n,a.data),n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L(`Bank rule ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a bank rule").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await lW(i,r),oe(i,"delete_bank_rule",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Bank rule ${r} deleted.`))})(n))}ke();h9();et();ft();function Vbt(e){let t=e.command("reconciliations").alias("recon").description("Apply reconciliation decisions to bank statement entries");t.command("quick-reconcile").description("Async, bulk: match bank entries to journals (max 500). Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(n,i)=>{let o=he(i);o||(console.error("Error: --input <file> is required (JSON with bankAccountResourceId + journalsForReconciliation[])"),process.exit(1));let s=await t9(n,o);i.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Quick reconcile started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bank-rule").description("Async, bulk: apply a bank rule to a batch of bank entries (max 500). Returns a jobId.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(n,i)=>{let o=he(i);o||(console.error("Error: --input <file> is required (JSON with actionShortcutResourceId + businessTransactionResourceIds[])"),process.exit(1));let s=await r9(n,o);i.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Apply bank rule started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("magic-match").description("Sync, bulk: accept magic suggestions (MAGIC_MATCH to EXISTING transactions/payments, or MAGIC_RECONCILE_WITH_CASH_IN_OUT learned predictions; max 500). Returns { reconciled[], failed[] }, either possibly absent or empty; a non-empty failed[] is a partial success and exits 1. A failed entry may still have posted: re-read its line before any retry.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(n,i)=>{let o=he(i);o||(console.error("Error: --input <file> is required (JSON with bankAccountResourceId + entries[])"),process.exit(1));let s=await f9(n,o),a=s.data.reconciled?.length??0,c=s.data.failed?.length??0;if(c>0&&(process.exitCode=1),i.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L(`Magic match: ${a} reconciled, ${c} failed.`));for(let u of s.data.failed??[]){let d=u.errors?.[0]?.errorCode??"UNKNOWN",f=u.errors?.[0]?.errorMessage??"";console.log(De(` \u2717 ${u.bankStatementEntryResourceId}: ${d}${f?` \u2014 ${f}`:""}`))}})),t.command("match-to-transaction").description("Sync: settle several bank entries (1-100, same account, all money in or all money out) against ONE existing open invoice, bill or credit note: one payment per entry, all or nothing. For one entry against an invoice or bill, use with-payments; one entry against a credit note takes this command too. A retry after success is refused (already reconciled).").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(n,i)=>{let o=he(i);o||(console.error("Error: --input <file> is required (JSON with bankAccountResourceId + bankStatementEntryResourceIds[] + cashflowTransactionResourceId + paymentAmount)"),process.exit(1));let s=await u9(n,o);if(i.json){console.log(JSON.stringify(s.data,null,2));return}let a=s.data;console.log(L(`Reconciled ${a.reconciled.length} entries against ${a.businessTransactionType??"document"} ${a.businessTransactionResourceId??""} \u2192 status ${a.businessTransactionStatus??"?"}, open balance ${a.balanceAmount??"?"}`)),a.reconciled.forEach((c,u)=>{console.log(De(` \u2713 ${c.bankStatementEntryResourceId} \u2192 ${c.status} (payment ${a.paymentResourceIds[u]??"?"})`))})}));let r=[{name:"direct-cash-entry",description:"Sync: reconcile a bank entry with a single cash-in / cash-out line. Direction inferred from the entry sign. NOT idempotent.",fn:n9},{name:"cash-journal",description:"Sync: reconcile a bank entry with a multi-line cashflow journal (max 200 lines). NOT idempotent.",fn:i9},{name:"manual-journal",description:"Sync: reconcile a bank entry with a double-entry manual journal. Bank-side leg auto-added by API. NOT idempotent.",fn:o9},{name:"cash-transfer",description:"Sync: reconcile a bank entry with an inter-account transfer. NOT idempotent.",fn:s9},{name:"invoice-receipt",description:"Sync (AR): CREATE an invoice and auto-reconcile it to a bank entry. To match an EXISTING invoice, use with-payments. NOT idempotent.",fn:a9},{name:"bill-receipt",description:"Sync (AP): CREATE a bill and auto-reconcile it to a bank entry. To match an EXISTING bill, use with-payments. NOT idempotent.",fn:c9},{name:"with-payments",description:"Sync: match a bank entry to an EXISTING open bill/invoice/payment (creates the payment + reconciles in one call). FX resolved server-side. NOT idempotent.",fn:l9},{name:"learned-prediction",description:"Sync: accept an ML learned-prediction suggestion (predictedPayload passed through from view_auto_reconciliation). NOT idempotent.",fn:d9}];for(let n of r)t.command(n.name).description(n.description).option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(i,o)=>{let s=he(o);s||(console.error(`Error: --input <file> is required (JSON body for ${n.name})`),process.exit(1));let a=await n.fn(i,s);if(o.json)console.log(JSON.stringify(a.data,null,2));else{let c=a.data;console.log(L(`Reconciled. Entry ${c.bankStatementEntryResourceId} \u2192 status ${c.status}${c.reference?` (ref: ${c.reference})`:""}`))}}));t.command("undo").description("Unlink bank entries from what they were reconciled against. Does NOT delete the record that was matched; prints its id so you can delete it separately.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(n,i)=>{let o=he(i);o||(console.error("Error: --input <file> is required (JSON body with bankStatementEntryResourceIds)"),process.exit(1));let s=await p9(n,o);if(i.json){console.log(JSON.stringify(s.data,null,2));return}let a=s.data.resetReconciliationResponse??[],c=a.filter(m=>m.status==="SUCCESS"),u=a.filter(m=>m.status!=="SUCCESS"),d=o.bankStatementEntryResourceIds??[];console.log(L(`Unlinked ${c.length}/${d.length} entries.`));let f=new Set(a.map(m=>m.bankStatementEntryResourceId)),p=d.filter(m=>!f.has(m));for(let m of p)console.log(De(` ? ${m}: not found (no result returned for this id)`));for(let m of u){let A=m.errorCode??"FAILED";console.log(De(` \u2717 ${m.bankStatementEntryResourceId}: ${A}${m.errorMessage?` (${m.errorMessage})`:""}`))}let h=s.data.linkedRecords??[];if(h.length>0){console.log(De(`
|
|
1096
|
-
${h.length} record(s) were left in place and are NOT deleted:`));let m=new Set(["JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"]);for(let A of h){let g=A.businessTransactionType??"UNKNOWN_TYPE",y=m.has(g),I=(y?A.parentEntityResourceId:A.businessTransactionResourceId)??"(id not returned)";console.log(` ${g} ${I}${y?" [delete by parentEntityResourceId]":""} (was on ${A.bankStatementEntryResourceId??"?"})`)}console.log(De(" Delete them with the matching delete command if they were created by the reconcile call."))}}))}ke();Kye();et();ft();function Wbt(e){let t=e.command("drafts").description("Bulk-action server-side draft lifecycle (max 500 per call, mixed BT types): validate, convert to active, submit for approval");t.command("validate").description("BULK validate (sync) \u2014 up to 500 drafts in ONE call, mixing any combination of invoices/bills/credit notes. Returns per-item errors inline. No state change.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=CCe(n),o=await W3(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):console.log(L(`Validated ${i.length} draft(s). See JSON for per-item details (--json).`))})),t.command("convert-to-active").description("BULK promote drafts to ACTIVE (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`. NOT idempotent \u2014 filter by status: DRAFT before submitting.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=CCe(n),o=await K3(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(L(`Convert started. Job ID: ${o.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${o.data.jobId}`)))})),t.command("submit-for-approval").description("BULK submit drafts for approval (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId. NOT idempotent on drafts with an in-flight approval.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=CCe(n),o=await X3(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(L(`Submit started. Job ID: ${o.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${o.data.jobId}`)))}))}function CCe(e){let t=he(e);t||(console.error('Error: --input <file> is required (JSON with { "items": [{btResourceId, btType}] } or a bare array)'),process.exit(1));let r=t.items??t;try{Qv(r)}catch(n){console.error(`Error: ${n.message}`),process.exit(1)}return r}pn();ke();RW();Lv();Ul();et();ft();Qt();bt();var Kbt=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"status",header:"Status"},{key:"purchasePrice",header:"Cost",align:"right",format:kr}],y$r=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Supplier"},{key:"documentResourceId",header:"Document ID",format:we}],E$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}];function Xbt(e,t){return e.saveAsDraft===!1?`Fixed asset ${t} and registered. It is active.`:`Fixed asset ${t} and saved as a draft. Nothing is posted until it is registered; use --finalize to register it at once.`}function Zbt(e){let t=e.command("fixed-assets").alias("fa").description("Manage fixed assets");lo({parent:t,description:"List fixed assets",columns:Kbt,label:"Fetching fixed assets",title:"Fixed Assets",fetch:(r,n)=>uW(r,n)}),t.command("get <resourceId>").description("Get fixed asset details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await $E(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.status),console.log(S("Type:"),s.typeName),console.log(S("Purchase:"),s.purchaseAmount),console.log(S("NBV:"),s.netBookValueAmount),console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:IT,defaults:bT,fetcher:qB,columns:Kbt,label:"Searching fixed assets"}),t.command("create").description("Register a new fixed asset").option("--jot <text>",ce).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Buildings", "Vehicles", "Furniture")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",Ct).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",pe).option("--residual <n>","Residual/salvage value",Ct).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").addOption(new qe("--purchase-bt-type <type>","Linked purchase BT type (PURCHASE = bill)").choices([...gA])).option("--purchase-bt-id <id>","Linked purchase BT resourceId (required for ACTIVE assets)").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(K("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.purchaseBtType&&(i.purchaseBusinessTransactionType=n.purchaseBtType),n.purchaseBtId&&(i.purchaseBusinessTransactionResourceId=n.purchaseBtId),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])),n.finalize&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=_r(n.customFields));let o=await dW(r,i);if(oe(r,"create_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(Xbt(i,"created"))),console.log(S("ID:"),o.data.resourceId)})),t.command("delete <resourceId>").description("Delete a draft fixed asset").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await pW(i,r),oe(i,"delete_fixed_asset",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Fixed asset ${r} deleted.`))})(n)),t.command("update <resourceId>").description("Update a fixed asset").option("--jot <text>",ce).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",pe).option("--tag <name>","Add this tag; the asset keeps its other tags").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n),s;o?s=o:(s={},n.name!==void 0&&(s.name=n.name),n.notes!==void 0&&(s.internalNotes=n.notes),n.depreciationMethod&&(s.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(s.effectiveLife=n.effectiveLife),n.tag&&(s.tags={add:[n.tag]})),n.customFields&&(s.customFields=_r(n.customFields));let{tags:a,...c}=s,u=ji(a),d=u&&await zo("fixed asset",r,()=>$E(i,r)),f=await fW(i,r,{...c,...u&&{tags:Zi(d?.tags,u)}},d||void 0);if(oe(i,"update_fixed_asset",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(L(s.isDraftToActive===!0?`Fixed asset ${r} activated and registered. It is active.`:`Fixed asset ${r} updated.`))})(n)),t.command("sell").description("Mark a fixed asset as sold").option("--jot <text>",ce).option("--id <resourceId>","Fixed asset resourceId").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").addOption(new qe("--sale-type <type>","Sale BT type (SALE = invoice)").choices([...gA])).option("--sale-item <id>","Sale item resourceId").option("--input <file>","Read full body from JSON file").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);if(i){let s=await jB(r,i);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L("Fixed asset marked as sold."));return}(!n.id||!n.depreciationEndDate||!n.gainLossAccount||!n.saleType||!n.saleItem)&&(console.error(K("Required: --id, --depreciation-end-date, --gain-loss-account, --sale-type, --sale-item")),process.exit(1));let o=await jB(r,{resourceId:n.id,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount,saleBusinessTransactionType:n.saleType,saleItemResourceId:n.saleItem});if(oe(r,"mark_fixed_asset_sold",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${n.id} marked as sold.`))})),t.command("transfer").description("Register a pre-existing fixed asset with accumulated depreciation (no linked purchase transaction)").option("--jot <text>",ce).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Computers and Electronics")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",Ct).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",pe).option("--accumulated-depreciation <n>","Depreciation already incurred",Ct).option("--residual <n>","Residual/salvage value",Ct).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--input <file>","Read full transfer body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(K("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.accumulatedDepreciation!==void 0&&(i.bookValueAccumulatedDepreciationAmount=n.accumulatedDepreciation),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.notes&&(i.internalNotes=n.notes)),n.finalize&&(i.saveAsDraft=!1);let o=await mW(r,i);if(oe(r,"transfer_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(Xbt(i,"transferred")))})),t.command("discard <resourceId>").description("Discard (write off) a fixed asset").option("--jot <text>",ce).option("--disposal-date <date>","Disposal date (YYYY-MM-DD)").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{(!n.disposalDate||!n.depreciationEndDate)&&(console.error(K("--disposal-date and --depreciation-end-date are required.")),process.exit(1));let o=await hW(i,r,{disposalDate:n.disposalDate,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount});if(oe(i,"discard_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${r} discarded.`))})(n)),t.command("undo-disposal <resourceId>").description("Undo a fixed asset disposal").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await AW(i,r);if(oe(i,"undo_fixed_asset_disposal",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Disposal undone for ${r}.`))})(n)),t.command("close-out <resourceId>").description("Stop depreciating from a month while keeping the asset (reverse with reopen)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Last month to depreciate (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await gW(i,r,n.date);if(oe(i,"close_out_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out fixed asset").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await yW(i,r);if(oe(i,"reopen_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${r} reopened.`))})(n)),t.command("totals").description("Asset register totals (purchase amount, accumulated depreciation, net book value)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await IW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("disposal-totals").description("Disposed asset totals (book value, sale proceeds, gain/loss; positive = loss)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await bW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One asset's depreciation schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await wW(i,r,n.viewDate);console.log(JSON.stringify(x3(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("preview-schedule").description("Check a custom depreciation schedule and show its timeline; saves nothing (save only when status is FULLY_SCHEDULED with no errors)").option("--input <file>","JSON body: { depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule: [{ fromPeriod, toPeriod, amount }] }").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error(K("--input <file> is required (JSON with depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule).")),process.exit(1));let o=await _W(r,i);console.log(JSON.stringify(Td(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("calculate-disposal <resourceId>").description("Accumulated depreciation at disposal, before mark-sold or discard; saves nothing").option("--depreciation-end-date <YYYY-MM-DD>","Final depreciation date (the one you will send to sell or discard)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.depreciationEndDate||(console.error(K("--depreciation-end-date is required.")),process.exit(1));let o=await CW(i,r,n.depreciationEndDate);console.log(JSON.stringify(o.data,null,2))})(n)),Oe({parent:t,commandName:"eligible-lines",fields:_T,defaults:CT,fetcher:vW,columns:y$r,label:"Searching bill lines eligible to register as assets"}),Oe({parent:t,commandName:"types",fields:wT,defaults:vT,fetcher:SW,columns:E$r,label:"Searching asset types"}),t.command("bulk-upsert").description("Create or update fixed assets in bulk (max 500). Natural key: reference. Each row requires reference, registrationType (NEW | TRANSFER), a typeCode and a depreciationStartDate (epoch ms). Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await DW(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk upsert started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update fixed assets in bulk (max 500). Each row is resourceId plus only the fields to change; the stored asset is merged in first (tags take { add, remove }). Unknown or repeated resourceIds fail the whole call. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await EW(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}pn();en();Ul();ke();fj();Lv();et();ft();Qt();bt();var I$r=[{key:"resourceId",header:"ID",format:we},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"deferralAmount",header:"Amount",align:"right",format:kr},{key:"remainingAmount",header:"Remaining",align:"right",format:kr}],b$r=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Contact"},{key:"documentResourceId",header:"Document ID",format:we}],_$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}],C$r=[{key:"accountResourceId",header:"ID",format:we},{key:"accountCode",header:"Code"},{key:"accountName",header:"Name"},{key:"category",header:"Category"}];function e_t(e){let t=e.command("deferrals").description("Manage deferrals: prepaid expenses and deferred revenue released over months");t.command("get <resourceId>").description("Get deferral details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await ay(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Category:"),s.category),console.log(S("Amount:"),s.deferralAmount),console.log(S("Remaining:"),s.remainingAmount),console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:ST,defaults:DT,fetcher:Wq,columns:I$r,label:"Searching deferrals",extraParams:RT}),t.command("create").description("Create a deferral over eligible bill, invoice or journal lines (a draft unless --activate)").option("--jot <text>",ce).option("--ref <reference>","Reference (required; see `clio references next DEFERRAL`)").option("--line <id...>","sourceLineResourceId from `clio deferrals eligible-lines` (one document, one account; required with --activate)").option("--type <typeCode>","Type code from `clio deferrals types`").option("--name <name>","Deferral name").option("--start <YYYY-MM-DD>","Amortization start date (on or after the document date)").option("--months <n>","Effective life in whole months",pe).option("--amortization-account <id>","Expense (prepaid) or Revenue (deferred revenue) account resourceId").option("--notes <text>","Internal notes").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--activate","Post the whole schedule now (saveAsDraft: false); needs --line, --type, --name, --start, --months and --amortization-account").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);if(!i){let a=(n.activate?[["--ref",n.ref],["--line",n.line],["--type",n.type],["--name",n.name],["--start",n.start],["--months",n.months],["--amortization-account",n.amortizationAccount]]:[["--ref",n.ref]]).filter(([,u])=>u===void 0).map(([u])=>u);a.length>0&&(console.error(K(`Required${n.activate?" with --activate":""}: ${a.join(", ")}`)),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let c={reference:n.ref,sourceLineResourceIds:n.line,typeCode:n.type,name:n.name,amortizationStartDate:n.start,effectiveLife:n.months,amortizationAccountResourceId:n.amortizationAccount};i=Object.fromEntries(Object.entries(c).filter(([,u])=>u!==void 0)),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])}n.activate&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=_r(n.customFields));let o=await Kq(r,i);if(oe(r,"create_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(o.data.status==="DRAFT"?"Deferral saved as a draft (nothing posted).":"Deferral created, active and posted: the whole schedule is on the books.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a deferral (partial) or activate a draft").option("--jot <text>",ce).option("--ref <reference>","Reference (default: the stored one)").option("--name <name>","New name").option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",pe).option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n),s;o?s=o:(s={},n.ref!==void 0&&(s.reference=n.ref),n.name!==void 0&&(s.name=n.name),n.start!==void 0&&(s.amortizationStartDate=n.start),n.months&&(s.effectiveLife=n.months),n.notes!==void 0&&(s.internalNotes=n.notes),n.activate&&(s.isDraftToActive=!0)),n.customFields&&(s.customFields=_r(n.customFields));let{tags:a,...c}=s,u=ji(a),d=u&&await zo("deferral",r,()=>ay(i,r)),f=await Xq(i,r,{...c,...u&&{tags:Zi(d?.tags,u)}},d||void 0);if(oe(i,"update_deferral",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(L(s.isDraftToActive===!0?`Deferral ${r} activated: its schedule is posted.`:`Deferral ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a deferral of any status (removes every posted row, frees the lines)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await Zq(i,r),oe(i,"delete_deferral",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Deferral ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop releasing after a date. Posts nothing: the remaining balance stays on the deferral account (reverse with reopen)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Close-out date, used as given").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await ej(i,r,n.date);if(oe(i,"close_out_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Deferral ${r} closed out. The remaining balance stays on the deferral account.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out deferral").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await tj(i,r);if(oe(i,"reopen_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Deferral ${r} reopened.`))})(n)),t.command("totals").description("Register totals for one category as at a date (never add the two categories together)").addOption(new qe("--category <cat>","Category").choices([...Gq]).makeOptionMandatory()).option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await rj(n,{category:r.category,endDate:r.endDate});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One deferral's release schedule (posted rows only: a draft has none)").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await nj(i,r,n.viewDate);console.log(JSON.stringify(k3(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Oe({parent:t,commandName:"eligible-lines",fields:TT,defaults:xT,fetcher:ij,columns:b$r,label:"Searching bill, invoice and journal lines eligible to defer"}),Oe({parent:t,commandName:"types",fields:kT,defaults:NT,fetcher:oj,columns:_$r,label:"Searching deferral types"}),Oe({parent:t,commandName:"accounts",fields:OT,defaults:BT,fetcher:sj,columns:C$r,label:"Searching deferral accounts",extraParams:FT}),t.command("mark-accounts").description("Mark or unmark chart-of-accounts entries as deferral accounts (changes org setup)").option("--jot <text>",ce).option("--account <id...>","Chart of accounts resourceId(s)").option("--unmark","Unmark instead of mark").option("--input <file>",'Read { "accounts": [{ organizationAccountResourceId, deferralAccount }] } from file').option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n),o=i?i.accounts??i:n.account?.map(f=>({organizationAccountResourceId:f,deferralAccount:!n.unmark}));Array.isArray(o)||(console.error(K("Required: --account <id...> or --input <file>")),process.exit(1)),ut(o,"accounts",500,"accounts");let s=await aj(r,o);if(oe(r,"mark_deferral_accounts",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}let a=o.map(f=>f?.deferralAccount),c=a.filter(f=>f===!0).length,u=a.filter(f=>f===!1).length,d=[c>0&&`${c} account(s) marked as deferral accounts`,u>0&&(c>0?`${u} unmarked`:`${u} account(s) unmarked as deferral accounts`)].filter(Boolean);console.log(L(`${d.length>0?d.join(", "):`${o.length} account(s) submitted`}.`))})),t.command("preview-schedule").description("Check custom release ranges without saving").option("--amount <n>","Deferral amount (sum of the eligible line amounts)",Ct).option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",pe).option("--schedule <json>","JSON array of { fromPeriod, toPeriod, amount }").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((n.amount===void 0||!n.start||!n.months||!n.schedule)&&(console.error(K("Required: --amount, --start, --months, --schedule")),process.exit(1)),i={deferralAmount:n.amount,amortizationStartDate:n.start,effectiveLife:n.months,customSchedule:JSON.parse(n.schedule)});let o=await cj(r,i);console.log(JSON.stringify(Td(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("bulk-upsert").description("Create deferrals in bulk (max 500). Creates only, always ACTIVE, STRAIGHT_LINE, dates YYYY-MM-DD. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await lj(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk create started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update deferrals in bulk (max 500). Each row is partial; resourceId and reference are required per row. Not for tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await uj(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}pn();Ul();ke();cye();Lv();et();ft();Qt();bt();var w$r=[{key:"resourceId",header:"ID",format:we},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status",format:e=>Fr(e)},{key:"leaseLiabilityRemaining",header:"Liability",align:"right",format:kr},{key:"rouNetBookValue",header:"ROU NBV",align:"right",format:kr}],v$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"}];function S$r(e){return(!/^\d+(\.\d{1,4})?$/.test(e)||Number(e)>=100)&&(console.error(K(`Error: invalid discount rate: ${e} (% per MONTH, below 100, max 4 decimal places; 6% a year is 0.5)`)),process.exit(1)),Number(e)}function t_t(e){let t=e.command("leases").description("Manage IFRS 16 leases and hire purchase (the register never posts rent: code rent bills to the current lease liability account)");t.command("get <resourceId>").description("Get lease details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await qE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Type:"),s.typeName),console.log(S("Liability:"),s.leaseLiabilityRemaining),console.log(S("ROU NBV:"),s.rouNetBookValue),console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:LT,defaults:PT,fetcher:TW,columns:w$r,label:"Searching leases",extraParams:QT}),t.command("create").description("Put a lease on the books (a draft unless --finalize). Rent is flat with --rent, stepped with --input.").option("--jot <text>",ce).option("--reference <ref>","Lease reference (required; see `clio references next --type LEASE`)").option("--name <name>","Lease name").option("--type <typeCode>","Lease type code (see `clio leases types`; HIRE_PURCHASE for hire purchase)").option("--lessor <contactResourceId>","Lessor contact resourceId").option("--start <YYYY-MM-DD>","Commencement date").option("--term <months>","Lease term in months (1-600)",pe).option("--rent <n>","Rent per month for the whole term",Ct).addOption(new qe("--payment-timing <timing>","ADVANCE (start of month) or ARREARS (end)").choices([...yh])).option("--discount-rate <n>","Discount rate in % per MONTH (6% a year is 0.5)",S$r).option("--rou-account <id>","Right-of-Use Asset account resourceId").option("--accumulated-depreciation-account <id>","Accumulated Depreciation account resourceId").option("--depreciation-expense-account <id>","Depreciation Expense account resourceId").option("--liability-account <id>","Current Lease Liability account resourceId (rent is coded here)").option("--non-current-liability-account <id>","Non-current Lease Liability account resourceId").option("--interest-account <id>","Interest Expense account resourceId (Finance Cost type)").option("--exempt","Short-term or low-value lease exemption (posts nothing)").option("--notes <text>","Internal notes").option("--finalize","Post the lease now (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags); needed for stepped rent, prepaid rent, restoration and ownership").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(n.reference||(console.error(K("Required: --reference")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),n.rent!==void 0&&!n.term&&(console.error(K("--rent needs --term: the rent is entered for every month of the term.")),process.exit(1)),i={reference:n.reference},n.name&&(i.name=n.name),n.type&&(i.typeCode=n.type),n.lessor&&(i.contactResourceId=n.lessor),n.start&&(i.commencementDate=n.start),n.term&&(i.leaseTerm=n.term),n.rent!==void 0&&(i.customSchedule=[{fromPeriod:1,toPeriod:n.term,amount:n.rent}]),n.paymentTiming&&(i.paymentTiming=n.paymentTiming),n.discountRate!==void 0&&(i.discountRate=n.discountRate),n.rouAccount&&(i.rouAssetAccountResourceId=n.rouAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.liabilityAccount&&(i.leaseLiabilityAccountResourceId=n.liabilityAccount),n.nonCurrentLiabilityAccount&&(i.leaseLiabilityNonCurrentAccountResourceId=n.nonCurrentLiabilityAccount),n.interestAccount&&(i.interestExpenseAccountResourceId=n.interestAccount),n.exempt&&(i.exemptionType="EXEMPT"),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])),n.finalize&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=_r(n.customFields));let o=await xW(r,i);if(oe(r,"create_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}let s=i.exemptionType==="EXEMPT";console.log(L(i.saveAsDraft!==!1?"Lease saved as a draft. Nothing is posted until it is activated.":s?"Lease registered as exempt. Nothing is posted.":"Lease created, active and posted.")),console.log(S("ID:"),o.data.resourceId),console.log(S("Liability:"),o.data.leaseLiabilityAmount??M("-")),console.log(S("ROU asset:"),o.data.rouAssetAmount??M("-"))})),t.command("update <resourceId>").description("Edit or activate a lease (partial). A schedule change on an ACTIVE lease rewrites every entry from the start date.").option("--jot <text>",ce).option("--reference <ref>","Reference (default: the stored one)").option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read the update body from JSON file (overrides flags); needed for schedule fields. tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let s=he(n)??{...n.reference!==void 0&&{reference:n.reference},...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}};n.customFields&&(s.customFields=_r(n.customFields));let{tags:a,...c}=s,u=ji(a),d=u&&await zo("lease",r,()=>qE(i,r)),f=await kW(i,r,{...c,...u&&{tags:Zi(d?.tags,u)}},d||void 0);if(oe(i,"update_lease",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(L(s.isDraftToActive!==!0?`Lease ${r} updated.`:f.data.exemptionType==="EXEMPT"?`Lease ${r} is now active as exempt. Nothing is posted.`:`Lease ${r} is now active and posted.`))})(n)),t.command("delete <resourceId>").description("Delete a lease of any status (removes every posted entry)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await NW(i,r),oe(i,"delete_lease",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Lease ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting after a month while the liability and right-of-use asset stay on the books (not an exit: use terminate)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Last month to post (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await OW(i,r,n.date);if(oe(i,"close_out_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Lease ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out lease").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await BW(i,r);if(oe(i,"reopen_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Lease ${r} reopened.`))})(n)),t.command("calculate-termination <resourceId>").description("Preview a termination: liability and right-of-use value removed, and the gain or loss (positive = gain). Saves nothing.").option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await LW(i,r,n.date);console.log(JSON.stringify(o.data,null,2))})(n)),t.command("terminate <resourceId>").description("Take a lease off the books at a month-end, posting the gain or loss (run calculate-termination first)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--gain-loss-account <id>","Gain/loss account resourceId (required when the gain or loss is not 0)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await FW(i,r,{terminationDate:n.date,terminationGainLossAccountResourceId:n.gainLossAccount});if(oe(i,"terminate_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Lease ${r} terminated.`))})(n)),t.command("undo-termination <resourceId>").description("Undo a termination").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await PW(i,r);if(oe(i,"undo_lease_termination",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Termination undone for ${r}.`))})(n)),t.command("totals").description("Lease liability (current and non-current) and right-of-use net book value as at a date, from the schedule").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await QW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One lease's schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First month to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await MW(i,r,n.viewDate);console.log(JSON.stringify(T3(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Oe({parent:t,commandName:"types",fields:MT,defaults:UT,fetcher:UW,columns:v$r,label:"Searching lease types"}),t.command("preview-rent").description("Check rent ranges against the term (COMPLETE or INCOMPLETE). Body: { commencementDate, leaseTerm, customSchedule }.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error("Error: --input <file> is required (JSON with commencementDate, leaseTerm, customSchedule)"),process.exit(1));let o=await $W(r,i);console.log(JSON.stringify(Td(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("flat-rate").description("Hire purchase: convert a flat annual rate into the monthly discount rate and instalments. Saves nothing.").requiredOption("--rate <n>","Flat rate, % per year",Number).requiredOption("--financed <n>","Financed amount (cash price less down payment)",Ct).requiredOption("--term <months>","Term in months (1-600)",pe).addOption(new qe("--payment-timing <timing>","ADVANCE or ARREARS (default ARREARS)").choices([...yh])).option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await qW(n,{flatRate:r.rate,financedAmount:r.financed,leaseTerm:r.term,paymentTiming:r.paymentTiming});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("bulk-update").description("Update leases in bulk (max 500): each row is partial and needs resourceId and reference. Not for rent or tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "leases": [...] })'),process.exit(1));let o=i.leases??i;Array.isArray(o)||(console.error('Error: expected { "leases": [...] }'),process.exit(1));let s=await jW(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}pn();ke();YB();et();J9();ft();Qt();bt();var D$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"code",header:"Code"},{key:"category",header:"Category"},{key:"status",header:"Status",format:e=>Fr(e)}],R$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"isDefault",header:"Default",format:e=>e?"yes":""},{key:"innerAxis",header:"Grouping"},{key:"journalDatePolicy",header:"Journal date"}],T$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"payFrequency",header:"Frequency"},{key:"currencyCode",header:"Currency"},{key:"status",header:"Status",format:e=>Fr(e)}];function x$r(e){let[t,r,...n]=e.split("="),i=r===void 0?void 0:gf(r);return(!t||n.length>0||i!==void 0&&(!Number.isFinite(i)||i<0))&&(console.error(K(`Error: invalid --line: ${e} (use <payTypeId> or <payTypeId>=<amount>, amount 0 or more)`)),process.exit(1)),i===void 0?{payTypeId:t}:{payTypeId:t,amount:i}}function js(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function jL(e,t){e.command("get <resourceId>").description(`Get a ${t.noun}`).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await t.get(i,r);console.log(JSON.stringify(o.data,null,2))})(n)),e.command("delete <resourceId>").description(`Delete a ${t.noun}. ${t.deleteHint}`).option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if((await t.remove(i,r))?.data?.deleted===!1){let s=`${t.noun} ${r} was not deleted: it is already gone or is not in this organization. Nothing was deleted.`;n.json?console.error(JSON.stringify({error:{code:"NOT_DELETED",message:s,resourceId:r}})):console.error(dI(s)),process.exitCode=2;return}if(oe(i,`delete_${t.toolPrefix}`,n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`${t.noun} ${r} deleted.`))})(n))}function k$r(e){let t=e.command("pay-types").description("Manage pay types: one thing paid to or deducted from employees on a payslip");jL(t,{noun:"pay type",toolPrefix:"pay_type",get:HW,remove:GW,deleteHint:"Refused while a pay profile, pay detail or payslip uses it (set it inactive instead)."}),Oe({parent:t,fields:zT,defaults:JT,fetcher:YW,columns:D$r,label:"Searching pay types"}),t.command("create").description("Create a pay type. Earning, overtime, allowance and additional payment need a debit account; deduction, employee contribution and employee tax a credit account; employer contribution and employer tax both.").option("--jot <text>",ce).option("--name <name>","Pay type name (unique)").addOption(new qe("--category <category>","Pay type category").choices([...zg])).option("--code <code>","Short code (unique)").option("--description <text>","Description").option("--debit-account <id>","Debit account resourceId").option("--credit-account <id>","Credit account resourceId").addOption(new qe("--status <status>","Default ACTIVE").choices([...Ku])).option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((!n.name||!n.category)&&(console.error(K("Required: --name and --category")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),i=js({name:n.name,category:n.category,code:n.code,description:n.description,debitAccountResourceId:n.debitAccount,creditAccountResourceId:n.creditAccount,status:n.status}));let o=await zW(r,i);if(oe(r,"create_pay_type",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L("Pay type created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Edit a pay type (partial). The category is locked once a payslip uses the pay type.").option("--jot <text>",ce).option("--name <name>","New name").addOption(new qe("--category <category>","New category (set the account it needs and clear the one it no longer uses)").choices([...zg])).option("--code <code>","New code").option("--description <text>","New description").option("--debit-account <id>","Debit account resourceId").option("--credit-account <id>","Credit account resourceId").addOption(new qe("--status <status>","ACTIVE or INACTIVE").choices([...Ku])).option("--clear-code","Empty the code").option("--clear-description","Empty the description").option("--clear-debit-account","Empty the debit account").option("--clear-credit-account","Empty the credit account").option("--input <file>","Read the update body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n)??js({name:n.name,category:n.category,code:n.code,description:n.description,debitAccountResourceId:n.debitAccount,creditAccountResourceId:n.creditAccount,status:n.status,clearCode:n.clearCode,clearDescription:n.clearDescription,clearDebitAccountResourceId:n.clearDebitAccount,clearCreditAccountResourceId:n.clearCreditAccount}),s=await JW(i,r,o);if(oe(i,"update_pay_type",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L(`Pay type ${r} updated.`))})(n))}function N$r(e){let t=e.command("payrun-posting-rules").description("Manage payrun posting rules: how a payrun books its journal (not claim posting rules: see posting-rules)");jL(t,{noun:"payrun posting rule",toolPrefix:"payrun_posting_rule",get:WW,remove:ZW,deleteHint:"The default rule, and one a pay profile or payrun names, are refused."}),Oe({parent:t,fields:GT,defaults:VT,fetcher:VW,columns:R$r,label:"Searching payrun posting rules"});let r=i=>i.option("--jot <text>",ce).option("--net-pay-account <id>","Account net pay is credited to (Payroll Payable)").addOption(new qe("--inner-axis <axis>","How journal lines merge (default BY_PAY_TYPE)").choices([...R_])).addOption(new qe("--journal-date-policy <policy>","The journal date (default PAYMENT_DATE)").choices([...T_])).option("--reference-template <text>","Journal reference, max 255, e.g. PAYRUN-{period}-{payrunName}").option("--line-template <text>","Journal line description, e.g. {payType} {account}").option("--default","Make this the default rule").option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output"),n=i=>js({name:i.name,netPayAccountResourceId:i.netPayAccount,innerAxis:i.innerAxis,journalDatePolicy:i.journalDatePolicy,journalReferenceTemplate:i.referenceTemplate,lineDescriptionTemplate:i.lineTemplate,isDefault:i.default});r(t.command("create").description("Create a payrun posting rule. The first rule in the organization is its default.").option("--name <name>","Rule name (unique)")).action(x(async(i,o)=>{let s=he(o);!s&&(!o.name||!o.netPayAccount)&&(console.error(K("Required: --name and --net-pay-account")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let a=await KW(i,s??n(o));if(oe(i,"create_payrun_posting_rule",o,a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L("Payrun posting rule created.")),console.log(S("ID:"),a.data.resourceId)})),r(t.command("update <resourceId>").description("Edit a payrun posting rule (partial). --default makes it the default; the default cannot be unset.").option("--name <name>","New name")).action((i,o)=>x(async s=>{let a=await XW(s,i,he(o)??n(o));if(oe(s,"update_payrun_posting_rule",o,a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L(`Payrun posting rule ${i} updated.`))})(o))}function O$r(e){let t=e.command("pay-profiles").description("Manage pay profiles: shared pay templates (frequency, currency, posting rule, pay type lines)");jL(t,{noun:"pay profile",toolPrefix:"pay_profile",get:t4,remove:i4,deleteHint:"Refused while any employee is or was on it (set it inactive instead)."}),Oe({parent:t,fields:WT,defaults:KT,fetcher:e4,columns:T$r,label:"Searching pay profiles"});let r=i=>i.option("--jot <text>",ce).option("--description <text>","Description").addOption(new qe("--frequency <frequency>","How often employees are paid").choices([...zl])).option("--currency <code>","Currency code (ISO 4217)").option("--line <payTypeId[=amount]>","A pay type line, repeatable. No amount means the figure is set per employee. On update the lines replace every line",gs,[]).option("--posting-rule <id>","Payrun posting rule resourceId (default: the organization's default)").addOption(new qe("--proration <type>","How a part-period is pro-rated").choices([...L$])).option("--work-week <days>","Days worked a week: 5, 5.5 or 6 (WORKING_DAYS, FIXED_DAYS)",Number).option("--days-per-month <n>","Days a month a line is divided by, 1 to 31 (FIXED_DAYS)",pe).addOption(new qe("--status <status>","ACTIVE or INACTIVE").choices([...Ku])).option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output"),n=i=>js({name:i.name,description:i.description,payFrequency:i.frequency,currencyCode:i.currency,payTypeLines:i.line.length>0?i.line.map(x$r):void 0,payrunPostingRuleResourceId:i.postingRule,prorationType:i.proration,workWeek:i.workWeek,daysPerMonth:i.daysPerMonth,status:i.status});r(t.command("create").description("Create a pay profile").option("--name <name>","Pay profile name (unique)")).action(x(async(i,o)=>{let s=he(o);!s&&(!o.name||!o.frequency||!o.currency)&&(console.error(K("Required: --name, --frequency and --currency")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let a=await r4(i,s??n(o));if(oe(i,"create_pay_profile",o,a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L("Pay profile created.")),console.log(S("ID:"),a.data.resourceId)})),r(t.command("update <resourceId>").description("Edit a pay profile (partial). --line replaces every line. Frequency and currency lock once employees are on it.").option("--name <name>","New name").option("--clear-description","Empty the description").option("--clear-posting-rule","Put the profile back on the default posting rule")).action((i,o)=>x(async s=>{let a=he(o)??{...n(o),...js({clearDescription:o.clearDescription,clearPayrunPostingRuleResourceId:o.clearPostingRule})},c=await n4(s,i,a);if(oe(s,"update_pay_profile",o,c.data),o.json){console.log(JSON.stringify(c.data,null,2));return}console.log(L(`Pay profile ${i} updated.`))})(o))}function r_t(e){k$r(e),N$r(e),O$r(e)}ke();uye();et();ft();Qt();bt();var B$r=[{key:"resourceId",header:"ID",format:we},{key:"employee.name",header:"Employee"},{key:"payProfile.name",header:"Pay profile"},{key:"effectiveFromDate",header:"From",format:vs},{key:"effectiveToDate",header:"To",format:vs}];function F$r(e){let[t,r,...n]=e.split("="),i=gf(r??"");return(!t||r===void 0||n.length>0||!Number.isFinite(i)||i<0)&&(console.error(K(`Error: invalid --figure: ${e} (use <payTypeId>=<amount>, amount 0 or more)`)),process.exit(1)),{payTypeId:t,amount:i}}function n_t(e){return e.length>0?e.map(F$r):void 0}function i_t(e){let t=e.command("employee-pay-details").description("Manage employee pay details: an employee's pay record on a pay profile from a date. A raise is a new pay detail from the new date, not an update.");Oe({parent:t,fields:XT,defaults:ZT,fetcher:o4,columns:B$r,label:"Searching employee pay details",extraParams:ex}),t.command("create").description("Put an employee on a pay profile from a date. The previous pay detail ends the day before.").option("--jot <text>",ce).option("--employee <id>","Employee resourceId (active)").option("--pay-profile <id>","Pay profile resourceId (active)").option("--from <YYYY-MM-DD>","First day this applies").option("--figure <payTypeId=amount>","The employee's own amount for one pay period, repeatable",gs,[]).option("--notes <text>","Notes").option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);!i&&(!n.employee||!n.payProfile||!n.from)&&(console.error(K("Required: --employee, --pay-profile and --from")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let o=await s4(r,i??js({employeeResourceId:n.employee,payProfileResourceId:n.payProfile,effectiveFromDate:n.from,payTypeInputs:n_t(n.figure),notes:n.notes}));if(oe(r,"create_employee_pay_detail",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L("Employee pay detail created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("bulk-create").description('Put up to 500 employees on pay profiles from a JSON file: { "employeePayDetails": [...] }. Each row is saved on its own; refused rows are listed and the exit code is 1.').option("--jot <text>",ce).option("--input <file>","JSON file of pay details (required)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let o=he(n)?.employeePayDetails;Array.isArray(o)||(console.error(K("Required: --input <file> holding employeePayDetails (an array of pay details).")),process.exit(1));let s=await a4(r,o);oe(r,"bulk_create_employee_pay_details",n,s.data);let a=(s.data??[]).filter(c=>c.errorCode);if(n.json)console.log(JSON.stringify(s.data,null,2));else{console.log(L(`${(s.data??[]).length-a.length} of ${(s.data??[]).length} employee pay details created.`));for(let c of a)console.error(K(`${c.employeeResourceId??"row"}: ${c.errorCode} ${c.errorMessage??""}`.trim()))}a.length>0&&(process.exitCode=1)})),t.command("update <resourceId>").description("Correct a pay detail in place, or end the employee's pay with --to. Not for a raise: create a new pay detail from the new date.").option("--jot <text>",ce).option("--from <YYYY-MM-DD>","Corrected first day (latest pay detail only)").option("--to <YYYY-MM-DD>","Last day the pay applies (latest pay detail only)").option("--figure <payTypeId=amount>","The employee's own amount, repeatable. The figures replace every figure",gs,[]).option("--notes <text>","Notes").option("--clear-to","Remove the end date").option("--clear-notes","Empty the notes").option("--input <file>","Read the update body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await c4(i,r,he(n)??js({effectiveFromDate:n.from,effectiveToDate:n.to,payTypeInputs:n_t(n.figure),notes:n.notes,clearEffectiveToDate:n.clearTo,clearNotes:n.clearNotes}));if(oe(i,"update_employee_pay_detail",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Employee pay detail ${r} updated.`))})(n))}pn();ke();JB();et();import{randomUUID as Q$r}from"node:crypto";ft();ke();fye();et();import{randomUUID as L$r}from"node:crypto";ft();function P$r(e){let[t,r,...n]=e.split("="),i=r===void 0?void 0:gf(r);return(!t||n.length>0||i!==void 0&&!(Number.isFinite(i)&&i>0))&&(console.error(K(`Error: invalid --payslip: ${e} (use <payslipId> or <payslipId>=<amount>, amount more than 0)`)),process.exit(1)),i===void 0?{payslipResourceId:t}:{payslipResourceId:t,amount:i}}function o_t(e){let t=e.errors??[];console.log(e.valid?L("Valid."):K(`${t.length} problem(s):`));for(let r of t)console.log(M(` - ${r.code}: ${r.message??""}`.trimEnd()))}function s_t(e){e.valid||(process.exitCode=1)}function a_t(e){return e.option("--account <id>","Bank or cash account the money was paid from, in the payrun currency (required to record)").option("--value-date <YYYY-MM-DD>","Day it was paid (default: the payrun payment date)").option("--ref <reference>","Reference for payouts whose payslip gives none").option("--notes <text>","Internal notes on each payout journal").option("--payslip <id[=amount]>","A payslip to pay, repeatable; amount for a part payment (default: every payslip still owed, in full)",gs,[]).option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output")}function c_t(e,t){let r=he(e);if(r)return r;t&&Le(e,[{flag:"--account",key:"account"}]);let n=e.payslip.map(P$r);return{...js({paymentAccountResourceId:e.account,valueDate:e.valueDate,reference:e.ref,internalNotes:e.notes}),...n.length>0?{payslips:n}:{}}}function l_t(e){for(let[t,r,n]of[["validate","Check a DRAFT payrun as finalize would, listing every problem; saves nothing",y4],["preview-journal","Show the journal finalize would post, with the same problems; saves nothing",E4]])e.command(`${t} <resourceId>`).description(r).option("--journal-date <YYYY-MM-DD>","Journal date (default: the posting rule's date)").option("--api-key <key>","API key").option("--json","JSON output").action((i,o)=>x(async s=>{let a=await n(s,i,o.journalDate);if(s_t(a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}o_t(a.data),t==="preview-journal"&&console.log(S("Total debit / credit:"),a.data.totalDebitAmount,"/",a.data.totalCreditAmount)})(o));e.command("finalize <resourceId>").description("Finalize a DRAFT payrun: posts one journal and makes the payslip PDFs. Run validate and preview-journal first. Finalizing a finalized run changes nothing.").option("--jot <text>",ce).option("--journal-date <YYYY-MM-DD>","Journal date (default: the posting rule's date)").option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{let i=await I4(n,t,r.journalDate);if(oe(n,"finalize_payrun",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payrun ${t} is ${i.data.status??"finalized"}.`))})(r)),e.command("bulk-finalize").description("Finalize several DRAFT payruns (async); each on its own. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--ids <list>","Payrun resourceIds (comma-separated, each once)").option("--journal-date <YYYY-MM-DD>","Journal date for every run (default: the posting rule's date)").option("--input <file>",'Read { "payruns": [{ "payrunResourceId", "journalValueDate" }] } from a JSON file (overrides flags)').option("--api-key <key>","API key").option("--json","JSON output").action(x(async(t,r)=>{let n=he(r);n||Le(r,[{flag:"--ids",key:"ids"}]);let i=n?.payruns??(In(r.ids)??[]).map(s=>({payrunResourceId:s,...js({journalValueDate:r.journalDate})})),o=await b4(t,i);if(oe(t,"bulk_finalize_payruns",r,o.data),r.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Queued bulk-finalize: jobId ${o.data.jobId??"?"}`))})),e.command("unpost <resourceId>").description("Unpost a FINALIZED payrun: its journal is voided and it goes back to DRAFT. Refused while a payout is live: void-payout first.").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{let i=await _4(n,t);if(oe(n,"unpost_payrun",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payrun ${t} is ${i.data.status??"back to draft"}.`))})(r)),e.command("void <resourceId>").description("Void a payrun for good, with a reason. Same refusals as unpost. A draft never posted is refused: delete it.").option("--jot <text>",ce).option("--reason <text>","Why, up to 500 characters").option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{Le(r,[{flag:"--reason",key:"reason"}]);let i=await C4(n,t,r.reason);if(oe(n,"void_payrun",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payrun ${t} is ${i.data.status??"void"}.`))})(r)),a_t(e.command("preview-payouts <resourceId>").description("Show what record-payouts would book per payslip, with every problem; saves nothing and moves no money")).action((t,r)=>x(async n=>{let i=await w4(n,t,c_t(r,!1));if(s_t(i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}o_t(i.data),console.log(S("Total payout:"),i.data.totalPayoutAmount)})(r)),a_t(e.command("record-payouts <resourceId>").description("Record that a FINALIZED payrun was paid OUTSIDE Jaz (async): one journal per payslip. Moves no money. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--hash <key>","Retry key (default: generated)")).action((t,r)=>x(async n=>{let i=c_t(r,!0),o=await v4(n,t,{...i,hash:r.hash??i.hash??L$r()});if(oe(n,"record_payrun_payouts",r,o.data),r.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Queued record-payouts: jobId ${o.data.jobId??"?"}`))})(r)),e.command("void-payout <journalResourceId>").description("Void one recorded payout by its journal id (see the payrun's payouts), with a reason; the payslip owes it again").option("--jot <text>",ce).option("--reason <text>","Why, up to 500 characters").option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{Le(r,[{flag:"--reason",key:"reason"}]);let i=await S4(n,t,r.reason);if(oe(n,"void_payrun_payout",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payout ${t} voided.`))})(r))}Qt();bt();var M$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"payrunType",header:"Type"},{key:"periodStartDate",header:"From",format:vs},{key:"periodEndDate",header:"To",format:vs},{key:"status",header:"Status",format:e=>Fr(e)},{key:"employeeCount",header:"Employees"},{key:"totalNetPayAmount",header:"Net pay"}];function U$r(e){let[t,r,...n]=e.split("="),i=gf(r??"");return(!t||!r||n.length>0||!Number.isFinite(i)||i<0)&&(console.error(K(`Error: invalid --line: ${e} (use <payTypeId>=<amount>, amount 0 or more)`)),process.exit(1)),{payTypeId:t,amount:i}}function u_t(e){return e.option("--jot <text>",ce).option("--name <name>","Display name").option("--payment-date <YYYY-MM-DD>","Payment date, the default date of the journal").option("--ref <reference>","Reference (unique, case ignored)").option("--posting-rule <id>","Payrun posting rule resourceId (default: the rule the payslips' pay profiles use)").option("--template <id>","Payslip PDF template resourceId (default: the default template)").option("--notes <text>","Internal notes").option("--custom-fields <json>",'Custom field values: [{"customFieldName":"...","actualValue":"..."}]').option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output")}function d_t(e){return js({name:e.name,paymentDate:e.paymentDate,reference:e.ref,payrunPostingRuleResourceId:e.postingRule,templateResourceId:e.template,internalNotes:e.notes,customFields:typeof e.customFields=="string"?_r(e.customFields):void 0})}function f_t(e,t,r,n){let i=t==="add-employees"?"add_payrun_employees":"remove_payrun_employees";e.command(`${t} <resourceId>`).description(r).option("--jot <text>",ce).option("--employees <list>","Employee resourceIds (comma-separated)").option("--api-key <key>","API key").option("--json","JSON output").action((o,s)=>x(async a=>{Le(s,[{flag:"--employees",key:"employees"}]);let c=await n(a,o,In(s.employees)??[]);if(oe(a,i,s,c.data),s.json){console.log(JSON.stringify(c.data,null,2));return}console.log(L(`Payrun ${o} now has ${c.data.employeeCount??"?"} employee(s).`))})(s))}function p_t(e,t){let{added:r,skipped:n}=t?HB(e.data):{added:e.data.added??[],skipped:e.data.skipped};console.log(L(`${r.length} employee(s) ${t?"could be added":"added"}, ${n?.length??0} skipped.`));for(let i of r)console.log(` + ${i.employee?.name??i.employeeResourceId}`);h_t(n??[],console.log,M)}function $$r(e){return` - ${e.employee?.name??e.employeeResourceId}: ${e.errorCode??""} ${e.errorMessage??""}`.trimEnd()}function h_t(e,t,r){let n=new Map;for(let i of e){let o=typeof i.errorCode=="string"?i.errorCode:"NO_ERROR_CODE";n.set(o,(n.get(o)??0)+1)}for(let[i,o]of n)t(r(` ${o} x ${i}`));for(let i of e)t(r($$r(i)))}function q$r(e,t,r){if(r?.length){for(let n of r)console.error(Re(n));console.error(Re(`Run: clio payruns preview-populate ${e}`));return}t?.length&&(console.error(Re(`${t.length} employee(s) skipped by the fill:`)),h_t(t,console.error,Re))}function m_t(e){let t=e.command("payruns").description("Manage employee payruns: one run for a period, one pay frequency and one currency, with a payslip per employee");jL(t,{noun:"payrun",toolPrefix:"payrun",get:vv,remove:f4,deleteHint:"New drafts only. A finalized run is refused; one finalized then unposted must be voided (payruns void)."}),Oe({parent:t,fields:tx,defaults:rx,fetcher:l4,columns:M$r,label:"Searching payruns",extraParams:nx}),u_t(t.command("create").description("Create a DRAFT payrun. --populate fills it from pay profiles at once. Type, frequency and currency cannot change later.").addOption(new qe("--type <type>","Default REGULAR. OFF_CYCLE is an extra run beside it").choices([...x_])).addOption(new qe("--frequency <frequency>","Pay frequency").choices([...zl])).option("--currency <code>","Currency code (ISO 4217)").option("--from <YYYY-MM-DD>","First day paid for").option("--to <YYYY-MM-DD>","Last day paid for").option("--populate","Fill from pay profiles now").option("--idempotency-key <key>","Retry key (default: generated)")).action(x(async(r,n)=>{let i=he(n);!i&&(!n.name||!n.frequency||!n.currency||!n.from||!n.to||!n.paymentDate)&&(console.error(K("Required: --name, --frequency, --currency, --from, --to and --payment-date")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let o=await u4(r,{...i??{...d_t(n),...js({payrunType:n.type,payFrequency:n.frequency,currencyCode:n.currency,periodStartDate:n.from,periodEndDate:n.to,populate:n.populate})},idempotencyKey:n.idempotencyKey??i?.idempotencyKey??Q$r()}),{data:s}=o,a=o.skipped,c=o.partialFailures;if(oe(r,"create_payrun",n,s),n.json){console.log(JSON.stringify({...s,...a?{skipped:a}:{},...c?{partialFailures:c}:{}},null,2));return}console.log(L(`Payrun created with ${s.employeeCount??0} employee(s).`)),console.log(S("ID:"),s.resourceId),q$r(s.resourceId,a,c)})),u_t(t.command("update <resourceId>").description("Edit a DRAFT payrun header (partial); a finalized run takes only its payslip template, sent alone. Changing the period leaves payslips as they are: run payslips refresh-payrun to rebuild them.").option("--from <YYYY-MM-DD>","First day paid for").option("--to <YYYY-MM-DD>","Last day paid for").option("--clear-ref","Empty the reference").option("--clear-notes","Empty the internal notes").option("--clear-posting-rule","Back to the rule the payslips' pay profiles use").option("--clear-template","Back to the default payslip template")).action((r,n)=>x(async i=>{let o=await d4(i,r,he(n)??{...d_t(n),...js({periodStartDate:n.from,periodEndDate:n.to,clearReference:n.clearRef,clearInternalNotes:n.clearNotes,clearPayrunPostingRuleResourceId:n.clearPostingRule,clearTemplateResourceId:n.clearTemplate})});if(oe(i,"update_payrun",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Payrun ${r} updated.`))})(n)),t.command("bulk-delete").description("Delete several new DRAFT payruns (async); each on its own. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--ids <list>","Payrun resourceIds (comma-separated, each once)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{Le(n,[{flag:"--ids",key:"ids"}]);let i=await p4(r,In(n.ids)??[]);if(oe(r,"bulk_delete_payruns",n,i.data),n.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Queued bulk-delete: jobId ${i.data.jobId??"?"}`))})),f_t(t,"add-employees","Add employees to a DRAFT payrun. One with no pay in the period gets an empty payslip: give it lines with save-lines.",h4),f_t(t,"remove-employees","Remove employees' payslips from a DRAFT payrun. They stay out when it is filled again.",m4),t.command("save-lines <resourceId>").description(`Set a payslip's lines in a DRAFT payrun. The lines REPLACE the payslip's whole list. For several payslips or to keep a line, use --input { "payslips": [...] }.`).option("--jot <text>",ce).option("--payslip <id>","Payslip resourceId").option("--line <payTypeId=amount>","A line, repeatable. Every line the payslip ends up with",gs,[]).option("--notes <text>","Notes printed on the payslip").option("--clear-notes","Empty the notes").option("--input <file>",'Read { "payslips": [...] } from a JSON file (overrides flags)').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n);!o&&(!n.payslip||n.line.length===0)&&(console.error(K("Required: --payslip and at least one --line")),console.error(M('Or use --input <file> to provide { "payslips": [...] }.')),process.exit(1));let s=o?.payslips??[js({payslipResourceId:n.payslip,lines:n.line.map(U$r),notes:n.notes,clearNotes:n.clearNotes})],a=await A4(i,r,s);if(oe(i,"save_payrun_lines",n,a.data),n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L(`Lines saved on ${s.length} payslip(s) of payrun ${r}.`))})(n)),t.command("populate <resourceId>").description("Fill a DRAFT payrun from pay profiles: adds every employee not yet in it with pay in the period. Existing payslips are not changed.").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await g4(i,r);if(oe(i,"populate_payrun",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}p_t(o,!1)})(n)),t.command("preview-populate <resourceId>").description("Show who populate would add and who would be skipped, saving nothing").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await zB(i,r);if(n.json){let{added:s,skipped:a}=HB(o.data);console.log(JSON.stringify({...o.data,added:s,...a!==void 0?{skipped:a}:{}},null,2));return}p_t(o,!0)})(n)),l_t(t)}ke();mye();et();ft();Qt();bt();var j$r=[{key:"resourceId",header:"ID",format:we},{key:"employeeName",header:"Employee"},{key:"payrun.name",header:"Payrun"},{key:"payrun.periodEndDate",header:"Period end",format:vs},{key:"netPayAmount",header:"Net pay"},{key:"payoutStatus",header:"Payout"}];function A_t(e){let t=e.command("payslips").description("Employee payslips of payruns: search, read, rebuild draft payslips from current pay, make PDFs again");t.command("get <resourceId>").description("Get a payslip with its lines, amounts and PDF link (generatedDocuments)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{console.log(JSON.stringify((await GB(i,r)).data,null,2))})(n)),Oe({parent:t,fields:ix,defaults:ox,fetcher:D4,columns:j$r,label:"Searching payslips"}),t.command("refresh <resourceId>").description("Rebuild one payslip of a DRAFT payrun from the employee's current pay. Hand-added lines stay; edits on pay-setup lines are replaced.").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await pye(i,r);if(oe(i,"refresh_payslip",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Payslip ${r} refreshed.`))})(n)),t.command("refresh-payrun <payrunResourceId>").description("Rebuild payslips of a DRAFT payrun from current pay: --payslips lists them, none means every payslip. Ones that cannot be refreshed are listed and the exit code is 1.").option("--jot <text>",ce).option("--payslips <list>","Payslip resourceIds (comma-separated). Default: all").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await hye(i,r,In(n.payslips));oe(i,"refresh_payslips",n,o.data);let s=o.data.failed??[];if(n.json)console.log(JSON.stringify(o.data,null,2));else{console.log(L(`${(o.data.refreshed??[]).length} payslip(s) refreshed, ${s.length} unchanged.`));for(let a of s)console.error(Re(`${a.employeeResourceId??"payslip"}: ${a.errorCode??""} ${a.errorMessage??""}`.trimEnd()))}s.length>0&&(process.exitCode=1)})(n)),t.command("generate <payrunResourceId>").description("Make the payslip PDFs of a FINALIZED payrun again (async): --payslips lists them, none means every payslip. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--payslips <list>","Payslip resourceIds (comma-separated). Default: all").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await R4(i,r,In(n.payslips));if(oe(i,"generate_payslips",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Queued payslip PDFs: jobId ${o.data.jobId??"?"}`)),console.log(M("Each new link replaces the old in the payslip's generatedDocuments."))})(n))}ke();Wye();Lv();Ul();et();ft();An();Qt();zt();bt();var Y$r=[{key:"resourceId",header:"ID",format:we},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"outstandingPrincipal",header:"Outstanding",align:"right",format:kr}],H$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"status",header:"Status"}],g_t="TERM or INSTALLMENT",k0=["--opening-balance <n>","Principal you confirm on the date after a missed, late or partial payment","openingBalance",Ct],z$r=[{name:"drawdown",event:"drawdown",tool:"record_loan_drawdown",description:"Raise the principal of a term loan on a date (a second tranche)",flags:[["--date <YYYY-MM-DD>","Drawdown date","drawdownDate"],["--amount <n>","Amount drawn","amount",Ct],["--keep <keep>",`${g_t} (default TERM)`,"keep"],k0],required:["drawdownDate","amount"]},{name:"prepay",event:"prepayment",tool:"prepay_loan",description:"Reduce principal with an extra repayment; the register posts no cash",flags:[["--date <YYYY-MM-DD>","Prepayment date","prepaymentDate"],["--amount <n>","Amount prepaid","amount",Ct],["--keep <keep>","INSTALLMENT keeps the monthly payment (term shortens), TERM keeps the term","keep"],k0],required:["prepaymentDate","amount","keep"]},{name:"change-rate",event:"rateChange",tool:"change_loan_rate",description:"The lender changed the rate from a date (never use update for this)",flags:[["--date <YYYY-MM-DD>","Effective date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR (7.25 = 7.25% a year)","annualInterestRate",Number],["--keep <keep>",g_t,"keep"],k0],required:["effectiveDate","annualInterestRate","keep"]},{name:"capitalize",event:"capitalization",tool:"capitalize_loan_interest",description:"Add one installment's whole interest to the principal",flags:[["--date <YYYY-MM-DD>","An installment due date","capitalizationDate"],k0],required:["capitalizationDate"]},{name:"payment-holiday",event:"paymentHoliday",tool:"record_loan_payment_holiday",description:"Skip installments (skipped interest is added to the balance)",flags:[["--from-period <n>","First skipped installment (periodNumber)","fromPeriod",pe],["--to-period <n>","Last skipped installment","toPeriod",pe],["--treatment <t>","ADD_INTEREST_TO_BALANCE (end date stays) or EXTEND_TERM","treatment"],k0],required:["fromPeriod","toPeriod","treatment"]},{name:"restructure",event:"restructure",tool:"restructure_loan",description:"New terms from an installment due date; 10% or more ends the loan and creates a new one",flags:[["--date <YYYY-MM-DD>","An installment due date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR","annualInterestRate",Number],["--term <months>","Installments left after the date","loanTerm",pe],["--installment <n>","The lender's new installment","installmentOverride",Ct],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"],k0],required:["effectiveDate"]},{name:"settle",event:"settlement",tool:"settle_loan",description:"End a loan early; use --preview for the payoff figure",flags:[["--date <YYYY-MM-DD>","Settlement date","settlementDate"],["--penalty <n>","Lender's penalty (quoted only)","penaltyAmount",Ct]],required:["settlementDate"]},{name:"forgive",event:"forgiveness",tool:"forgive_loan",description:"Write off the whole loan (gain above 0)",flags:[["--date <YYYY-MM-DD>","Forgiveness date","forgivenessDate"],["--amount <n>","The whole outstanding principal","amount",Ct],["--forgiven-by <who>","LENDER or SHAREHOLDER","forgivenBy"],["--equity-account <id>","Equity account, for SHAREHOLDER","equityAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["forgivenessDate","amount","forgivenBy"]},{name:"convert",event:"conversion",tool:"convert_loan_to_shares",description:"Convert the whole loan into shares (IFRIC 19)",flags:[["--date <YYYY-MM-DD>","Conversion date","conversionDate"],["--fair-value <n>","Fair value of the shares","fairValue",Ct],["--share-capital-account <id>","Shareholders Equity account","shareCapitalAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["conversionDate","fairValue","shareCapitalAccountResourceId"]},{name:"refinance",event:"refinance",tool:"refinance_loan",description:"Settle the loan and create a new active one; returns the NEW loan. --input: { refinanceDate, newLoan: {...} }",flags:[["--date <YYYY-MM-DD>","Refinance date","refinanceDate"]],required:["refinanceDate","newLoan"]},{name:"reclassify-current",event:"reclassifyAsCurrent",tool:"reclassify_loan_as_current",description:"Make the whole balance current from a covenant breach date (IAS 1.74)",flags:[["--date <YYYY-MM-DD>","Breach date","reclassificationDate"],["--waiver-date <YYYY-MM-DD>","Date the bank waived it","waiverDate"]],required:["reclassificationDate"]},{name:"undo",event:"undo",tool:"undo_loan_event",description:"Reverse the latest event (see `clio loans events` for the id and canUndo)",flags:[["--event <resourceId>","The latest event resourceId","eventResourceId"]],required:["eventResourceId"]}];function k5(e){console.error(K(e)),process.exit(1)}var y_t=e=>e.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(t,r)=>r.toUpperCase());function J$r(e,t){let r="calculate"in iF[t.event],n=e.command(`${t.name} <resourceId>`).description(r?`${t.description}. --preview shows the figures and saves nothing`:t.description);n.option("--jot <text>",ce);for(let[i,o]of t.flags)n.option(i,o);r&&n.option("--preview","Calculate only: nothing is saved"),n.option("--input <file>","Read the whole event body from JSON file (not with the event flags)").option("--api-key <key>","API key").option("--json","JSON output").action((i,o)=>x(async s=>{let a=o.preview===!0;a&&o.jot!==void 0&&k5("--jot records the judgment behind a recorded event; a preview records nothing.");let c=he(o),u=t.flags.filter(([p])=>o[y_t(p)]!==void 0).map(([p])=>p.split(" ")[0]);if(c&&u.length>0&&k5(`${u.join(", ")} would be ignored: --input supplies the whole body. Use the flags or --input, not both.`),!c){c={};for(let[p,,h,m]of t.flags){let A=o[y_t(p)];A!==void 0&&(c[h]=m?m(A):A)}}let d=t.required.filter(p=>c[p]===void 0);d.length>0&&(console.error(K(`Required: ${d.join(", ")}`)),console.error(M("Pass the flags, or --input <file> with the full JSON body.")),process.exit(1));let f=await V3(s,t.event,i,c,a);if(a||oe(s,t.tool,o,f.data),o.json){console.log(JSON.stringify(f.data,null,2));return}console.log(a?De("Preview only, nothing saved."):L(`${t.name}: recorded on loan ${i}.`)),console.log(JSON.stringify(f.data,null,2))})(o))}function E_t(e){let t=e.command("loans").description("Manage loans (borrowings): term and on demand, with their events");Oe({parent:t,fields:$T,defaults:qT,fetcher:B3,columns:Y$r,label:"Searching loans",extraParams:jT}),Oe({parent:t,commandName:"types",fields:YT,defaults:HT,fetcher:F3,columns:H$r,label:"Searching loan types"}),t.command("get <resourceId>").description("Get a loan with its figures as of today").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await eI(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Kind:"),s.kind),console.log(S("Rate (% a year):"),s.annualInterestRate),console.log(S("Outstanding principal:"),s.outstandingPrincipal),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a loan (a draft that posts nothing unless --activate). The register posts no cash: record the drawdown and every installment yourself. Body is a JSON file; run `loans preview-schedule` first.").option("--jot <text>",ce).option("--input <file>","JSON body: reference, kind, typeCode, name, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, accounts...").option("--activate","Activate immediately (saveAsDraft: false)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error(K("--input <file> is required (JSON with reference and the loan terms).")),process.exit(1)),n.activate&&(i.saveAsDraft=!1);let o=await L3(r,i);if(oe(r,"create_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(i.saveAsDraft===!1?"Loan created, active and posted. The register posts no cash: record the drawdown and every installment yourself.":"Loan saved as a draft. Nothing is posted until it is activated.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a loan (partial). A term, fee or account change on an ACTIVE loan rewrites the whole schedule: use an event for a mid-life change").option("--jot <text>",ce).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--input <file>",'Read the whole update body from JSON file (not with --name, --notes or --activate). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o={...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}},s=he(n);s&&Object.keys(o).length>0&&k5("--name, --notes and --activate would be ignored: --input supplies the whole body. Use the flags or --input, not both.");let a=s??o;Object.keys(a).length===0&&k5("Nothing to update: pass --name, --notes, --activate or --input.");let{tags:c,...u}=a,d=ji(c),f=d&&await zo("loan",r,()=>eI(i,r)),p=await P3(i,r,{...u,...d&&{tags:Zi(f?.tags,d)}},f||void 0);if(oe(i,"update_loan",n,p.data),n.json){console.log(JSON.stringify(p.data,null,2));return}console.log(L(a.isDraftToActive===!0?`Loan ${r} activated: its schedule is posted.`:`Loan ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a loan in any status (its own ledger rows go; your bank postings stay)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await Q3(i,r),oe(i,"delete_loan",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Loan ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting from a month-end; balances stay. Not an exit (use settle). Reverse with reopen").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Close-out date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await M3(i,r,n.date);if(oe(i,"close_out_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Loan ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out loan (earlier events can no longer be undone afterwards)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await U3(i,r);if(oe(i,"reopen_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Loan ${r} reopened.`))})(n)),t.command("totals").description("What we owe in total: outstanding principal, current, non-current, accrued interest").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await $3(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("A term loan's repayment schedule").option("--view-date <YYYY-MM-DD>","Rows posted as at this date (default today)").option("--from-period <n>","First installment number to print (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await q3(i,r,n.viewDate);console.log(JSON.stringify(Fv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("events <resourceId>").description("A loan's events, latest first (canUndo marks the one that can be undone)").option("--limit <n>","Max results",pe).option("--offset <n>","Page number (0-indexed)",nt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",pe).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await ct(n,({limit:s,offset:a})=>j3(i,r,{limit:s,offset:a}),{label:"Fetching loan events",defaultLimit:20});Xe(o,[{key:"resourceId",header:"ID",format:we},{key:"eventType",header:"Event"},{key:"effectiveDate",header:"Date"},{key:"canUndo",header:"Can undo"}],n,"Loan events")})(n)),t.command("ledger <resourceId>").description("On-demand loans only: advances and repayments with the balance").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--limit <n>","Max results",pe).option("--offset <n>","Page number (0-indexed)",nt).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await Y3(i,r,{endDate:n.endDate,limit:n.limit,offset:n.offset});console.log(JSON.stringify(o,null,2))})(n)),t.command("preview-schedule").description("The schedule these terms would produce; saves nothing").option("--input <file>","JSON body: kind, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, fees...").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error(K("--input <file> is required (JSON with kind, principalAmount, drawdownDate and the terms).")),process.exit(1));let o=await H3(r,i);console.log(JSON.stringify(Fv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("opening-balance <resourceId>").description("Suggest an --opening-balance for an event after a missed, late or partial payment; saves nothing").option("--event-type <type>","DRAWDOWN, PREPAYMENT, RATE_CHANGE, CAPITALIZE_INTEREST, PAYMENT_HOLIDAY or RESTRUCTURE").option("--date <YYYY-MM-DD>","Event date (for a holiday, the first skipped due date)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{(!n.eventType||!n.date)&&(console.error(K("Required: --event-type, --date")),process.exit(1));let o=await z3(i,{resourceId:r,eventType:n.eventType,date:n.date});console.log(JSON.stringify(o.data,null,2))})(n));for(let r of z$r)J$r(t,r);for(let[r,n,i]of[["bulk-upsert","Create ACTIVE loans in bulk (max 500; creates only, dates YYYY-MM-DD, no CUSTOM shape or fees)",J3],["bulk-update","Update loans in bulk (max 500; update per row, reference required on each). Not for tag changes (use update)",G3]])t.command(r).description(`${n}. Returns a jobId; poll with \`clio background-jobs get <jobId>\`.`).option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(o,s)=>{let a=he(s);a||(console.error('Error: --input <file> is required (JSON with { "loans": [...] })'),process.exit(1));let c=a.loans??a;Array.isArray(c)||(console.error('Error: expected { "loans": [...] }'),process.exit(1));let u=await i(o,c);s.json?console.log(JSON.stringify(u.data,null,2)):(console.log(L(`${r} started. Job ID: ${u.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${u.data.jobId}`)))}))}ke();U4();et();ID();ft();bt();Qt();var G$r=[{key:"resourceId",header:"ID",format:we},{key:"status",header:"Status",format:e=>String(e)==="ACTIVE"?L(String(e)):M(String(e))},{key:"interval",header:"Interval"},{key:"totalAmount",header:"Amount",align:"right"},{key:"businessTransactionType",header:"Type"}],V$r=[{key:"resourceId",header:"ID",format:we},{key:"scheduledTransactionType",header:"Type"},{key:"status",header:"Status",format:e=>M(String(e??""))}];function I_t(e){let t=e.command("subscriptions").alias("subs").description("Manage recurring subscriptions");lo({parent:t,description:"List subscriptions",columns:G$r,label:"Fetching subscriptions",title:"Subscriptions",fetch:(r,n)=>B4(r,n)}),t.command("get <resourceId>").description("Get subscription details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await zE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Status:"),s.status),console.log(S("Interval:"),s.interval),console.log(S("Amount:"),s.totalAmount),console.log(S("Next:"),bf(s.nextScheduleDate)??"N/A"),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a recurring subscription (invoices only, with proration)").option("--jot <text>",ce).option("--interval <interval>","WEEKLY, MONTHLY, QUARTERLY, or YEARLY (required)").option("--start-date <YYYY-MM-DD>","Start date (required)").option("--end-date <YYYY-MM-DD>","End date (optional, omit for ongoing)").option("--contact <name|resourceId>","Customer contact (required)").option("--ref <reference>","Invoice reference").option("--date <YYYY-MM-DD>","Invoice date").option("--due <YYYY-MM-DD>","Due date").option("--account <name|resourceId>","Revenue account \u2014 applied to ALL line items (required)").option("--tax-profile <name|resourceId>","Tax profile \u2014 applied to ALL line items").option("--lines <json>","Line items as JSON array (name, unitPrice, quantity)").option("--amount <n>","Single line item amount (shorthand)",Ct).option("--line-name <name>","Line item name (used with --amount)").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);if(!i){(!n.interval||!n.startDate)&&(console.error(K("Required: --interval, --start-date")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let s;if(n.lines)try{s=JSON.parse(n.lines)}catch{console.error(K("Invalid --lines JSON")),process.exit(1)}else n.amount!==void 0&&(s=[{name:n.lineName??"Subscription",unitPrice:n.amount,quantity:1}]);s&&(n.account||n.taxProfile)&&(s=s.map(a=>({...a,...n.account&&!a.accountResourceId?{accountResourceId:n.account}:{},...n.taxProfile&&!a.taxProfileResourceId?{taxProfileResourceId:n.taxProfile}:{}}))),i={repeat:n.interval,startDate:n.startDate,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment"},invoice:{contactResourceId:n.contact,reference:n.ref,valueDate:n.date,dueDate:n.due,lineItems:s,saveAsDraft:!1}},n.endDate&&(i.endDate=n.endDate)}let o=await F4(r,i);if(oe(r,"create_subscription",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L("Subscription created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a subscription (the body must carry the invoice template; status is kept when omitted)").option("--jot <text>",ce).option("--input <file>","Read full update body from JSON file: `invoice` template required (create shape), optional endDate, repeat, status, proratedConfig").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n);o||(console.error(K("Use --input <file> to provide update data.")),process.exit(1));let s=await L4(i,r,o);if(oe(i,"update_subscription",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L(`Subscription ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a subscription").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await P4(i,r),oe(i,"delete_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Subscription ${r} deleted.`))})(n)),t.command("cancel <resourceId>").description("Cancel an active subscription (prorates remaining period)").option("--jot <text>",ce).option("--cancel-date-type <type>","END_OF_CURRENT_PERIOD, END_OF_LAST_PERIOD, or CUSTOM_DATE","END_OF_CURRENT_PERIOD").option("--end-date <YYYY-MM-DD>","Custom cancel date (only with CUSTOM_DATE)").option("--prorated-text <text>","Prorated adjustment line text","Prorated adjustment").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await Q4(i,r,{cancelDateType:n.cancelDateType,proratedAdjustmentLineText:n.proratedText,endDate:n.endDate}),oe(i,"cancel_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({cancelled:!0,resourceId:r}));return}console.log(L(`Subscription ${r} cancelled.`))})(n)),Oe({parent:t,commandName:"search-scheduled",fields:sx,defaults:ax,fetcher:M4,columns:V$r,label:"Searching scheduled transactions"})}ke();Rye();et();ft();bt();Qt();var b_t=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"}];function __t(e){let t=e.command("contact-groups").description("Manage contact groups");lo({parent:t,description:"List contact groups",columns:b_t,label:"Fetching contact groups",title:"Contact Groups",fetch:(r,n)=>$4(r,n)}),t.command("get <resourceId>").description("Get contact group details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await q4(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Contacts:"),s.associatedContacts?.length??0);for(let a of s.associatedContacts??[])console.log(` ${De(a.resourceId)} ${a.name}`);console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:zx,defaults:Jx,fetcher:j4,columns:b_t,label:"Searching contact groups",positionalArg:"name",positionalFilter:r=>({name:{contains:r}})}),t.command("create").description("Create a contact group").option("--jot <text>",ce).option("--name <name>","Group name").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let i=await Y4(r,{name:n.name});if(oe(r,"create_contact_group",n,i.data),n.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Contact group "${n.name}" created.`)),console.log(S("ID:"),i.data.resourceId)})),t.command("update <resourceId>").description("Update a contact group").option("--name <name>","New group name").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o={};n.name&&(o.name=n.name);let s=await H4(i,r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L("Contact group updated.")),console.log(S("ID:"),s.data.resourceId)})(n)),t.command("delete <resourceId>").description("Delete a contact group").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await z4(i,r),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Contact group ${r} deleted.`))})(n))}pn();Tye();et();ft();An();zt();bt();ke();var W$r=[{key:"resourceId",header:"ID",format:we},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"itemCode",header:"Code",format:e=>M(String(e??""))}],K$r=[{key:"itemCode",header:"Code",format:e=>M(String(e??""))},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"totalQuantity",header:"Qty",format:e=>String(e??"")},{key:"baseUnit",header:"Unit",format:e=>String(e??"")},{key:"averageCostAmount",header:"Avg Cost",format:e=>String(e??"")},{key:"balanceAmount",header:"Value",format:e=>String(e??"")}];function C_t(e){let t=e.command("inventory").alias("inv").description("Inventory management");t.command("items").description("List inventory-tracked items").option("--limit <n>","Max results",pe).option("--offset <n>","Page number offset (0-indexed)",nt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",pe).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=await ct(n,o=>J4(r,o),{label:"Fetching inventory items"});Xe(i,W$r,n,"Inventory Items")})),t.command("balance <itemResourceId>").description("Get inventory balance for an item").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await V4(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Item:"),s.itemResourceId),console.log(S("Qty:"),`${s.baseQty} ${s.baseUnit}`),console.log(S("Avg Cost:"),s.latestAverageCostAmount)})(n)),t.command("balances").description("List inventory balances across items, by balance status").addOption(new qe("--status <status>","Balance status").choices([...W4]).default("ALL")).option("--limit <n>","Max results",pe).option("--offset <n>","Page number offset (0-indexed)",nt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",pe).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=n.status,o=await ct(n,s=>K4(r,i,s),{label:"Fetching inventory balances"});Xe(o,K$r,n,"Inventory Balances")})),t.command("create").description("Create an inventory-tracked item (use --input for full JSON body)").option("--item-code <code>","Item code (SKU) (required)").option("--name <name>","Item name (required)").option("--unit <unit>","Unit of measure (required)").option("--costing-method <method>","FIXED or WAC (required)").option("--cogs-account <resourceId>","COGS account resourceId, Direct Costs type (required)").option("--purchase-account <resourceId>","Purchase account resourceId, Inventory type (required)").option("--sale-account <resourceId>","Sale account resourceId (required)").option("--block-insufficient","Block transactions when stock is insufficient").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||Le(n,[{flag:"--item-code",key:"itemCode"},{flag:"--name",key:"name"},{flag:"--unit",key:"unit"},{flag:"--costing-method",key:"costingMethod"},{flag:"--cogs-account",key:"cogsAccount"},{flag:"--purchase-account",key:"purchaseAccount"},{flag:"--sale-account",key:"saleAccount"}]);let o=i??{itemCode:n.itemCode,name:n.name,unit:n.unit,costingMethod:n.costingMethod,cogsResourceId:n.cogsAccount,purchaseAccountResourceId:n.purchaseAccount,saleAccountResourceId:n.saleAccount,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:!!n.blockInsufficient},s=await G4(r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L("Inventory item created.")),console.log(S("ID:"),s.data.resourceId)}))}ke();xye();et();ft();bt();Qt();var w_t=[{key:"resourceId",header:"ID",format:we},{key:"customFieldName",header:"Name"}];function v_t(e){let t=e.command("custom-fields").description("Manage custom fields");lo({parent:t,description:"List custom fields",columns:w_t,label:"Fetching custom fields",title:"Custom Fields",fetch:(r,n)=>X4(r,n)}),t.command("get <resourceId>").description("Get a custom field by resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let s=(await ZB(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Name:"),s.customFieldName||s.name||"(unnamed)"),console.log(S("ID:"),s.resourceId),console.log(S("Type:"),s.datatypeCode||s.fieldType||"\u2014"),s.description&&console.log(S("Description:"),s.description),s.defaultValue&&console.log(S("Default:"),s.defaultValue),s.listOptions?.length&&console.log(S("Options:"),s.listOptions.join(", "));let a=u=>u==="SHOW"||u==="PRINT",c=[];a(s.applyToSales)&&c.push("invoices"),a(s.applyToPurchase)&&c.push("bills"),a(s.applyToSaleCreditNote)&&c.push("customer CNs"),a(s.applyToPurchaseCreditNote)&&c.push("supplier CNs"),a(s.applyToPayment)&&c.push("payments"),a(s.appliesToFixedAssets)&&c.push("fixed assets"),c.length&&console.log(S("Applies to:"),c.join(", "))})(n)),Oe({parent:t,fields:Yx,defaults:Hx,fetcher:Z4,columns:w_t,label:"Searching custom fields"}),t.command("create").description("Create a custom field").option("--jot <text>",ce).option("--name <name>","Field name").option("--description <text>","Field description").option("--print-on-documents","Print this field on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--field-format <fmt>","CUSTOM (default, free text) or ALL_CUSTOMERS / ALL_SUPPLIERS / ALL_CONTACTS / ALL_EMPLOYEES / ALL_USERS for a picklist of that population").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let o=n.invoices||n.bills||n.customerCredits||n.supplierCredits||n.payments?{invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1}:void 0,s=await e3(r,{name:n.name,description:n.description,printOnDocuments:n.printOnDocuments??!1,appliesTo:o,format:n.fieldFormat});if(oe(r,"create_custom_field",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L(`Custom field "${n.name}" created.`)),console.log(S("ID:"),s.data.resourceId)})),t.command("update <resourceId>").description("Update a custom field").option("--name <name>","New field name").option("--description <text>","New description").option("--print-on-documents","Print on PDF documents").option("--no-print-on-documents","Do not print on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.description!==void 0&&(o.description=n.description),n.printOnDocuments!==void 0&&(o.printOnDocuments=n.printOnDocuments),(n.invoices!==void 0||n.bills!==void 0||n.customerCredits!==void 0||n.supplierCredits!==void 0||n.payments!==void 0)&&(o.appliesTo={invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1});let a=await t3(i,r,o);if(n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L(`Custom field ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a custom field").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await r3(i,r),oe(i,"delete_custom_field",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Custom field ${r} deleted.`))})(n))}pn();ke();zye();et();ft();zt();function S_t(e){let t=In(e)??[];if(t.length===0)throw new Gt("--ids must contain at least one resourceId (comma-separated).");return t}function D_t(e,t){if(!e||typeof e!="object")throw new Error(`${t}: the API returned no job handle. The batch may still have been accepted \u2014 check \`clio background-jobs search\` before resending.`);return e}function R_t(e){return JSON.stringify({...e,pollWith:e.jobId?`clio background-jobs get ${e.jobId}`:"clio background-jobs search",note:"Bulk is async. Per-record outcomes exist ONLY in the job, never in this response."},null,2)}function T_t(e,t){console.log(L(`${t} queued.`)),e.jobId&&console.log(S("Job ID:"),e.jobId),e.totalRecords!==void 0&&console.log(S("Records:"),String(e.totalRecords)),console.log(De(` Poll progress: clio background-jobs get ${e.jobId??"<jobId>"}`))}function x_t(e,t,r){let n=C3(e);if(t.json){let i=n.state==="approved"?!0:n.state==="refused"?!1:null;console.log(JSON.stringify({entity:r.entity,resourceId:r.resourceId,[r.jsonKey]:i,records:e},null,2))}else n.state==="refused"?console.log(K(`Not ${r.doneVerb}: ${r.entity} ${r.resourceId} \u2014 ${n.reason}`)):n.state==="unconfirmed"?console.log(K(`UNCONFIRMED: ${r.entity} ${r.resourceId} \u2014 the API returned no per-record outcome, so this neither succeeded nor failed provably. Re-read the document before recording it.`)):(console.log(L(`${r.entity} ${r.resourceId} ${r.doneVerb}.`)),e?.[0]&&r.extra?.(e[0]));return n.state!=="approved"?(process.exitCode=1,!1):!0}function k_t(e){let t=e.command("approvals").description("Approve documents or send them back for changes"),r=n=>new qe("-e, --entity <entity>","Document family").choices([...n]).makeOptionMandatory();t.command("approve <resourceId>").description("Approve one document \u2014 posts its ledger entries and makes it live").addOption(r(bp)).option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>x(async o=>{let s=await w3(o,i.entity,n);x_t(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"approved",doneVerb:"approved",extra:c=>{c.status&&console.log(S("Status:"),c.status)}})&&oe(o,"approve_documents",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-approve").description("Approve up to 100 documents (async \u2014 returns a job)").addOption(r(bp)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-100)").option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>x(async i=>{let o=S_t(n.ids),s=await v3(i,n.entity,o),a=D_t(s?.data,"bulk approve");n.json?console.log(R_t(a)):T_t(a,`Approval of ${o.length} ${n.entity}`),oe(i,"bulk_approve_documents",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n)),t.command("request-changes <resourceId>").description("Send one document back for changes instead of approving it").addOption(r(XE)).requiredOption("-m, --message <text>","Why it is sent back \u2014 opens a thread and is the only record of the reason").option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>x(async o=>{let s=await S3(o,i.entity,n,i.message);x_t(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"sentBack",doneVerb:"sent back for changes",extra:c=>{let u=c.collaborationThreadPath;u&&console.log(S("Thread:"),u)}})&&oe(o,"request_document_changes",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-request-changes").description("Send up to 500 documents back for changes with one message (async \u2014 returns a job)").addOption(r(XE)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-500)").requiredOption("-m, --message <text>","Why they are sent back \u2014 the only record of the reason").option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>x(async i=>{let o=S_t(n.ids),s=await D3(i,n.entity,o,n.message),a=D_t(s?.data,"bulk request changes");n.json?console.log(R_t(a)):T_t(a,`Request-changes on ${o.length} ${n.entity}`),oe(i,"bulk_request_document_changes",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n))}ke();xie();et();Qt();bt();var N_t=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"reference",header:"Reference"},{key:"currencyCode",header:"Currency"}];function O_t(e){let t=e.command("purchase-items").description("Browse the purchase-side catalog (read-only)");lo({parent:t,description:"List purchase items",columns:N_t,label:"Fetching purchase items",title:"Purchase Items",offsetMode:ty.offsetMode,fetch:(r,n)=>gq(r,n)}),t.command("get <resourceId>").description("Get a purchase item by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let s=(await yq(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("ID:"),s.resourceId);for(let[a,c]of[["Name","name"],["Reference","reference"],["Currency","currencyCode"]]){let u=s[c];u!=null&&u!==""&&console.log(S(`${a}:`),String(u))}})(n)),Oe({parent:t,fields:ux,defaults:ty,columns:N_t,label:"Searching purchase items",fetcher:Eq})}Gge();et();G_();ke();ft();zt();import{readFileSync as B_t}from"node:fs";import{isAbsolute as X$r}from"node:path";function F_t(e,t){if(e!==void 0&&t)throw new Gt("Pass the query as an argument OR --input <file>, not both.");if(t){let n;try{n=B_t(t,"utf-8")}catch{throw new Gt(`Cannot read --input file: ${t}`)}let i=n.trim();if(!i)throw new Gt(`--input file is empty: ${t}`);return i}let r=e?.trim();if(r)return r;if(!process.stdin.isTTY){let n=B_t(0,"utf-8").trim();if(n)return n}throw new Gt("A query is required. Pass it as an argument, --input <file>, or on stdin.")}var Z$r=new Set(["numeric","int","int8","bigint","float8","double precision"]);function e2r(e){return e.map((t,r)=>({key:String(r),header:t.name,align:Z$r.has(t.type)?"right":"left"}))}function t2r(e,t){return t.map(r=>Object.fromEntries(e.map((n,i)=>[String(i),r[n.name]])))}function L_t(e){let t=e.command("pseudo-sql").alias("sql").description("Read-only queries over Jaz's curated reporting tables (a restricted SQL subset, not your database)");t.command("preview [query]").description("Run a SELECT and print up to 100 rows").option("--input <file>","Read the query from a file instead of an argument").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let s=(await j8(i,F_t(r,n.input))).data;if(n.json){console.log(JSON.stringify(s,null,2));return}for(let u of s.warnings??[])console.error(Re("Warning:"),u);if(!Array.isArray(s.rows)||!Array.isArray(s.columns))throw new Error("pseudo-sql preview: upstream returned no rows/columns array");if(s.rows.length===0){console.log(M("No rows."));return}let c=s.columns.slice(0,8);console.log(ea(t2r(c,s.rows),e2r(c))),s.columns.length>c.length&&console.log(M(`Showing ${c.length} of ${s.columns.length} columns \u2014 use --json for all`)),console.log(M(`${s.rowCount} row(s)${s.truncated?" \u2014 `clio sql export` returns the full set":""}`))})(n)),t.command("export [query]").description("Export a SELECT to CSV (waits for the job by default)").option("--input <file>","Read the query from a file instead of an argument").option("--out <path>","Absolute path to write the CSV to (implies download)").option("--download","Download the CSV to ~/Downloads instead of printing the URL").option("--no-wait","Return the jobId immediately; poll with `export-status`").option("--timeout <seconds>","How long to wait for the job (default 25, max 90)",pe).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let o=F_t(r,n.input);if(n.wait===!1){let u=[["--out",n.out],["--download",n.download],["--timeout",n.timeout]].filter(([,d])=>d!==void 0).map(([d])=>d);if(u.length)throw new Gt(`--no-wait cannot be combined with ${u.join(", ")} \u2014 it returns before the export runs. Drop --no-wait, or poll with \`clio sql export-status <jobId>\`.`)}if(n.out&&!X$r(n.out))throw new Gt(`--out must be an absolute path; got "${n.out}".`);if(n.wait===!1){let u=await FB(i,o,{idempotencyKey:Jge(o)});if(n.json){console.log(JSON.stringify(u.data,null,2));return}console.log(L("Export started")),console.log(S("Job:"),u.data.jobId,M(`(${u.data.status})`)),console.log(M(`Poll with: clio sql export-status ${u.data.jobId}`));return}typeof n.timeout=="number"&&n.timeout>90&&console.error(Re(`--timeout ${n.timeout} exceeds the 90s ceiling; waiting 90s. Use --no-wait for a longer job.`));let s=!!(n.download||n.out),c=(await Y8(i,o,{timeoutSeconds:n.timeout,downloadToFile:s,outPath:n.out})).data;if(n.json){let{buffer:u,...d}=c;console.log(JSON.stringify(d,null,2));return}if(c.status==="TIMED_OUT"){console.error(Re("Still running."),M(`Poll with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(c.status!=="COMPLETED"){console.error(K(`Export ${c.status}`),c.error??""),process.exitCode=1;return}if(c.error){console.error(K("Export completed but the download failed:"),c.error),console.error(M(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(!c.localPath&&!c.downloadUrl){console.error(K("Export reported COMPLETED but returned no file and no URL.")),console.error(M(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}console.log(L("Export ready")),c.rowCount!==void 0&&console.log(S("Rows:"),String(c.rowCount)+(c.truncated?M(" \u2014 more rows match than the LIMIT returned"):"")),c.localPath?console.log(S("Saved:"),c.localPath):c.downloadUrl&&console.log(S("URL:"),c.downloadUrl,M("(expires in ~15 min)"))})(n)),t.command("export-status <jobId>").description("Poll an export job").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let s=(await Iv(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Status:"),s.status),s.rowCount!==void 0&&console.log(S("Rows:"),String(s.rowCount)),s.downloadUrl&&console.log(S("URL:"),s.downloadUrl,M("(expires in ~15 min)")),s.error?(console.error(K("Error:"),s.error),process.exitCode=1):(s.status==="FAILED"||s.status==="EXPIRED")&&(process.exitCode=1)})(n)),t.command("schema [table]").description("Show the curated catalog: tables, columns, joins").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let{data:o}=await bv(i),s=H8(o,r),a=s.scopedTo?.toLowerCase();if(n.json){console.log(JSON.stringify(s,null,2));return}if(a){let c=s.tables[0];if(console.log(S(c.name),M(c.label??"")),console.log(ea((c.columns??[]).map(u=>({column:u.name,type:u.type})),[{key:"column",header:"Column"},{key:"type",header:"Type"}])),s.joins.length){console.log(`
|
|
1096
|
+
${h.length} record(s) were left in place and are NOT deleted:`));let m=new Set(["JOURNAL_DIRECT_CASH_IN","JOURNAL_DIRECT_CASH_OUT","JOURNAL_CASH_TRANSFER"]);for(let A of h){let g=A.businessTransactionType??"UNKNOWN_TYPE",y=m.has(g),I=(y?A.parentEntityResourceId:A.businessTransactionResourceId)??"(id not returned)";console.log(` ${g} ${I}${y?" [delete by parentEntityResourceId]":""} (was on ${A.bankStatementEntryResourceId??"?"})`)}console.log(De(" Delete them with the matching delete command if they were created by the reconcile call."))}}))}ke();Kye();et();ft();function Wbt(e){let t=e.command("drafts").description("Bulk-action server-side draft lifecycle (max 500 per call, mixed BT types): validate, convert to active, submit for approval");t.command("validate").description("BULK validate (sync) \u2014 up to 500 drafts in ONE call, mixing any combination of invoices/bills/credit notes. Returns per-item errors inline. No state change.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=CCe(n),o=await W3(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):console.log(L(`Validated ${i.length} draft(s). See JSON for per-item details (--json).`))})),t.command("convert-to-active").description("BULK promote drafts to ACTIVE (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`. NOT idempotent \u2014 filter by status: DRAFT before submitting.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=CCe(n),o=await K3(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(L(`Convert started. Job ID: ${o.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${o.data.jobId}`)))})),t.command("submit-for-approval").description("BULK submit drafts for approval (async) \u2014 up to 500 in ONE call, mixing any combination of invoices/bills/credit notes. Returns a jobId. NOT idempotent on drafts with an in-flight approval.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=CCe(n),o=await X3(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(L(`Submit started. Job ID: ${o.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${o.data.jobId}`)))}))}function CCe(e){let t=he(e);t||(console.error('Error: --input <file> is required (JSON with { "items": [{btResourceId, btType}] } or a bare array)'),process.exit(1));let r=t.items??t;try{Qv(r)}catch(n){console.error(`Error: ${n.message}`),process.exit(1)}return r}pn();ke();RW();Lv();Ul();et();ft();Qt();bt();var Kbt=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"status",header:"Status"},{key:"purchasePrice",header:"Cost",align:"right",format:kr}],y$r=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Supplier"},{key:"documentResourceId",header:"Document ID",format:we}],E$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}];function Xbt(e,t){return e.saveAsDraft===!1?`Fixed asset ${t} and registered. It is active.`:`Fixed asset ${t} and saved as a draft. Nothing is posted until it is registered; use --finalize to register it at once.`}function Zbt(e){let t=e.command("fixed-assets").alias("fa").description("Manage fixed assets");lo({parent:t,description:"List fixed assets",columns:Kbt,label:"Fetching fixed assets",title:"Fixed Assets",fetch:(r,n)=>uW(r,n)}),t.command("get <resourceId>").description("Get fixed asset details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await $E(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.status),console.log(S("Type:"),s.typeName),console.log(S("Purchase:"),s.purchaseAmount),console.log(S("NBV:"),s.netBookValueAmount),console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:IT,defaults:bT,fetcher:qB,columns:Kbt,label:"Searching fixed assets"}),t.command("create").description("Register a new fixed asset").option("--jot <text>",ce).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Buildings", "Vehicles", "Furniture")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",Ct).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",pe).option("--residual <n>","Residual/salvage value",Ct).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").addOption(new qe("--purchase-bt-type <type>","Linked purchase BT type (PURCHASE = bill)").choices([...gA])).option("--purchase-bt-id <id>","Linked purchase BT resourceId (required for ACTIVE assets)").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(K("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.purchaseBtType&&(i.purchaseBusinessTransactionType=n.purchaseBtType),n.purchaseBtId&&(i.purchaseBusinessTransactionResourceId=n.purchaseBtId),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])),n.finalize&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=_r(n.customFields));let o=await dW(r,i);if(oe(r,"create_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(Xbt(i,"created"))),console.log(S("ID:"),o.data.resourceId)})),t.command("delete <resourceId>").description("Delete a draft fixed asset").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await pW(i,r),oe(i,"delete_fixed_asset",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Fixed asset ${r} deleted.`))})(n)),t.command("update <resourceId>").description("Update a fixed asset").option("--jot <text>",ce).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",pe).option("--tag <name>","Add this tag; the asset keeps its other tags").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n),s;o?s=o:(s={},n.name!==void 0&&(s.name=n.name),n.notes!==void 0&&(s.internalNotes=n.notes),n.depreciationMethod&&(s.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(s.effectiveLife=n.effectiveLife),n.tag&&(s.tags={add:[n.tag]})),n.customFields&&(s.customFields=_r(n.customFields));let{tags:a,...c}=s,u=ji(a),d=u&&await zo("fixed asset",r,()=>$E(i,r)),f=await fW(i,r,{...c,...u&&{tags:Zi(d?.tags,u)}},d||void 0);if(oe(i,"update_fixed_asset",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(L(s.isDraftToActive===!0?`Fixed asset ${r} activated and registered. It is active.`:`Fixed asset ${r} updated.`))})(n)),t.command("sell").description("Mark a fixed asset as sold").option("--jot <text>",ce).option("--id <resourceId>","Fixed asset resourceId").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").addOption(new qe("--sale-type <type>","Sale BT type (SALE = invoice)").choices([...gA])).option("--sale-item <id>","Sale item resourceId").option("--input <file>","Read full body from JSON file").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);if(i){let s=await jB(r,i);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L("Fixed asset marked as sold."));return}(!n.id||!n.depreciationEndDate||!n.gainLossAccount||!n.saleType||!n.saleItem)&&(console.error(K("Required: --id, --depreciation-end-date, --gain-loss-account, --sale-type, --sale-item")),process.exit(1));let o=await jB(r,{resourceId:n.id,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount,saleBusinessTransactionType:n.saleType,saleItemResourceId:n.saleItem});if(oe(r,"mark_fixed_asset_sold",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${n.id} marked as sold.`))})),t.command("transfer").description("Register a pre-existing fixed asset with accumulated depreciation (no linked purchase transaction)").option("--jot <text>",ce).option("--name <name>","Asset name (required)").option("--type <typeName>",'Asset type (e.g., "Computers and Electronics")').option("--category <cat>","TANGIBLE or INTANGIBLE").option("--amount <n>","Purchase cost (required)",Ct).option("--date <YYYY-MM-DD>","Purchase date (required)").option("--depreciation-start <YYYY-MM-DD>","Depreciation start date (required)").option("--asset-account <id>","Asset account resourceId (required)").option("--depreciation-method <method>","STRAIGHT_LINE, NO_DEPRECIATION or CUSTOM_SCHEDULE (CUSTOM_SCHEDULE also needs customSchedule in --input)").option("--effective-life <months>","Effective life in months",pe).option("--accumulated-depreciation <n>","Depreciation already incurred",Ct).option("--residual <n>","Residual/salvage value",Ct).option("--depreciation-expense-account <id>","Depreciation expense account resourceId").option("--accumulated-depreciation-account <id>","Accumulated depreciation account resourceId").option("--notes <text>","Internal notes").option("--draft","Save as draft (default: true)").option("--finalize","Activate immediately (saveAsDraft: false)").option("--input <file>","Read full transfer body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((!n.name||n.amount===void 0||!n.date||!n.assetAccount||!n.depreciationStart)&&(console.error(K("Required: --name, --amount, --date, --depreciation-start, --asset-account")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),i={name:n.name,purchaseAmount:n.amount,purchaseDate:n.date,depreciationStartDate:n.depreciationStart,purchaseAssetAccountResourceId:n.assetAccount},n.type&&(i.typeName=n.type),n.category&&(i.category=n.category),n.depreciationMethod&&(i.depreciationMethod=n.depreciationMethod),n.effectiveLife&&(i.effectiveLife=n.effectiveLife),n.accumulatedDepreciation!==void 0&&(i.bookValueAccumulatedDepreciationAmount=n.accumulatedDepreciation),n.residual!==void 0&&(i.depreciableValueResidualAmount=n.residual),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.notes&&(i.internalNotes=n.notes)),n.finalize&&(i.saveAsDraft=!1);let o=await mW(r,i);if(oe(r,"transfer_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(Xbt(i,"transferred")))})),t.command("discard <resourceId>").description("Discard (write off) a fixed asset").option("--jot <text>",ce).option("--disposal-date <date>","Disposal date (YYYY-MM-DD)").option("--depreciation-end-date <date>","Final depreciation date (YYYY-MM-DD)").option("--gain-loss-account <id>","Gain/loss account resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{(!n.disposalDate||!n.depreciationEndDate)&&(console.error(K("--disposal-date and --depreciation-end-date are required.")),process.exit(1));let o=await hW(i,r,{disposalDate:n.disposalDate,depreciationEndDate:n.depreciationEndDate,assetDisposalGainLossAccountResourceId:n.gainLossAccount});if(oe(i,"discard_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${r} discarded.`))})(n)),t.command("undo-disposal <resourceId>").description("Undo a fixed asset disposal").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await AW(i,r);if(oe(i,"undo_fixed_asset_disposal",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Disposal undone for ${r}.`))})(n)),t.command("close-out <resourceId>").description("Stop depreciating from a month while keeping the asset (reverse with reopen)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Last month to depreciate (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await gW(i,r,n.date);if(oe(i,"close_out_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out fixed asset").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await yW(i,r);if(oe(i,"reopen_fixed_asset",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Fixed asset ${r} reopened.`))})(n)),t.command("totals").description("Asset register totals (purchase amount, accumulated depreciation, net book value)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await IW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("disposal-totals").description("Disposed asset totals (book value, sale proceeds, gain/loss; positive = loss)").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await bW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One asset's depreciation schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await wW(i,r,n.viewDate);console.log(JSON.stringify(x3(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("preview-schedule").description("Check a custom depreciation schedule and show its timeline; saves nothing (save only when status is FULLY_SCHEDULED with no errors)").option("--input <file>","JSON body: { depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule: [{ fromPeriod, toPeriod, amount }] }").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error(K("--input <file> is required (JSON with depreciableValueAmount, depreciationStartDate, effectiveLife, customSchedule).")),process.exit(1));let o=await _W(r,i);console.log(JSON.stringify(Td(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("calculate-disposal <resourceId>").description("Accumulated depreciation at disposal, before mark-sold or discard; saves nothing").option("--depreciation-end-date <YYYY-MM-DD>","Final depreciation date (the one you will send to sell or discard)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.depreciationEndDate||(console.error(K("--depreciation-end-date is required.")),process.exit(1));let o=await CW(i,r,n.depreciationEndDate);console.log(JSON.stringify(o.data,null,2))})(n)),Oe({parent:t,commandName:"eligible-lines",fields:_T,defaults:CT,fetcher:vW,columns:y$r,label:"Searching bill lines eligible to register as assets"}),Oe({parent:t,commandName:"types",fields:wT,defaults:vT,fetcher:SW,columns:E$r,label:"Searching asset types"}),t.command("bulk-upsert").description("Create or update fixed assets in bulk (max 500). Natural key: reference. Each row requires reference, registrationType (NEW | TRANSFER), a typeCode and a depreciationStartDate (epoch ms). Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await DW(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk upsert started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update fixed assets in bulk (max 500). Each row is resourceId plus only the fields to change; the stored asset is merged in first (tags take { add, remove }). Unknown or repeated resourceIds fail the whole call. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "fixedAssets": [...] })'),process.exit(1));let o=i.fixedAssets??i;Array.isArray(o)||(console.error('Error: expected { "fixedAssets": [...] }'),process.exit(1));let s=await EW(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}pn();en();Ul();ke();fj();Lv();et();ft();Qt();bt();var I$r=[{key:"resourceId",header:"ID",format:we},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"deferralAmount",header:"Amount",align:"right",format:kr},{key:"remainingAmount",header:"Remaining",align:"right",format:kr}],b$r=[{key:"documentType",header:"Type"},{key:"reference",header:"Reference"},{key:"contactName",header:"Contact"},{key:"documentResourceId",header:"Document ID",format:we}],_$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"categoryCode",header:"Category"}],C$r=[{key:"accountResourceId",header:"ID",format:we},{key:"accountCode",header:"Code"},{key:"accountName",header:"Name"},{key:"category",header:"Category"}];function e_t(e){let t=e.command("deferrals").description("Manage deferrals: prepaid expenses and deferred revenue released over months");t.command("get <resourceId>").description("Get deferral details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await ay(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Category:"),s.category),console.log(S("Amount:"),s.deferralAmount),console.log(S("Remaining:"),s.remainingAmount),console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:ST,defaults:DT,fetcher:Wq,columns:I$r,label:"Searching deferrals",extraParams:RT}),t.command("create").description("Create a deferral over eligible bill, invoice or journal lines (a draft unless --activate)").option("--jot <text>",ce).option("--ref <reference>","Reference (required; see `clio references next DEFERRAL`)").option("--line <id...>","sourceLineResourceId from `clio deferrals eligible-lines` (one document, one account; required with --activate)").option("--type <typeCode>","Type code from `clio deferrals types`").option("--name <name>","Deferral name").option("--start <YYYY-MM-DD>","Amortization start date (on or after the document date)").option("--months <n>","Effective life in whole months",pe).option("--amortization-account <id>","Expense (prepaid) or Revenue (deferred revenue) account resourceId").option("--notes <text>","Internal notes").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--activate","Post the whole schedule now (saveAsDraft: false); needs --line, --type, --name, --start, --months and --amortization-account").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);if(!i){let a=(n.activate?[["--ref",n.ref],["--line",n.line],["--type",n.type],["--name",n.name],["--start",n.start],["--months",n.months],["--amortization-account",n.amortizationAccount]]:[["--ref",n.ref]]).filter(([,u])=>u===void 0).map(([u])=>u);a.length>0&&(console.error(K(`Required${n.activate?" with --activate":""}: ${a.join(", ")}`)),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let c={reference:n.ref,sourceLineResourceIds:n.line,typeCode:n.type,name:n.name,amortizationStartDate:n.start,effectiveLife:n.months,amortizationAccountResourceId:n.amortizationAccount};i=Object.fromEntries(Object.entries(c).filter(([,u])=>u!==void 0)),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])}n.activate&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=_r(n.customFields));let o=await Kq(r,i);if(oe(r,"create_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(o.data.status==="DRAFT"?"Deferral saved as a draft (nothing posted).":"Deferral created, active and posted: the whole schedule is on the books.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a deferral (partial) or activate a draft").option("--jot <text>",ce).option("--ref <reference>","Reference (default: the stored one)").option("--name <name>","New name").option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",pe).option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read full update body from JSON file (overrides flags). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n),s;o?s=o:(s={},n.ref!==void 0&&(s.reference=n.ref),n.name!==void 0&&(s.name=n.name),n.start!==void 0&&(s.amortizationStartDate=n.start),n.months&&(s.effectiveLife=n.months),n.notes!==void 0&&(s.internalNotes=n.notes),n.activate&&(s.isDraftToActive=!0)),n.customFields&&(s.customFields=_r(n.customFields));let{tags:a,...c}=s,u=ji(a),d=u&&await zo("deferral",r,()=>ay(i,r)),f=await Xq(i,r,{...c,...u&&{tags:Zi(d?.tags,u)}},d||void 0);if(oe(i,"update_deferral",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(L(s.isDraftToActive===!0?`Deferral ${r} activated: its schedule is posted.`:`Deferral ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a deferral of any status (removes every posted row, frees the lines)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await Zq(i,r),oe(i,"delete_deferral",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Deferral ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop releasing after a date. Posts nothing: the remaining balance stays on the deferral account (reverse with reopen)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Close-out date, used as given").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await ej(i,r,n.date);if(oe(i,"close_out_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Deferral ${r} closed out. The remaining balance stays on the deferral account.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out deferral").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await tj(i,r);if(oe(i,"reopen_deferral",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Deferral ${r} reopened.`))})(n)),t.command("totals").description("Register totals for one category as at a date (never add the two categories together)").addOption(new qe("--category <cat>","Category").choices([...Gq]).makeOptionMandatory()).option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await rj(n,{category:r.category,endDate:r.endDate});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One deferral's release schedule (posted rows only: a draft has none)").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First row to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await nj(i,r,n.viewDate);console.log(JSON.stringify(k3(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Oe({parent:t,commandName:"eligible-lines",fields:TT,defaults:xT,fetcher:ij,columns:b$r,label:"Searching bill, invoice and journal lines eligible to defer"}),Oe({parent:t,commandName:"types",fields:kT,defaults:NT,fetcher:oj,columns:_$r,label:"Searching deferral types"}),Oe({parent:t,commandName:"accounts",fields:OT,defaults:BT,fetcher:sj,columns:C$r,label:"Searching deferral accounts",extraParams:FT}),t.command("mark-accounts").description("Mark or unmark chart-of-accounts entries as deferral accounts (changes org setup)").option("--jot <text>",ce).option("--account <id...>","Chart of accounts resourceId(s)").option("--unmark","Unmark instead of mark").option("--input <file>",'Read { "accounts": [{ organizationAccountResourceId, deferralAccount }] } from file').option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n),o=i?i.accounts??i:n.account?.map(f=>({organizationAccountResourceId:f,deferralAccount:!n.unmark}));Array.isArray(o)||(console.error(K("Required: --account <id...> or --input <file>")),process.exit(1)),ut(o,"accounts",500,"accounts");let s=await aj(r,o);if(oe(r,"mark_deferral_accounts",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}let a=o.map(f=>f?.deferralAccount),c=a.filter(f=>f===!0).length,u=a.filter(f=>f===!1).length,d=[c>0&&`${c} account(s) marked as deferral accounts`,u>0&&(c>0?`${u} unmarked`:`${u} account(s) unmarked as deferral accounts`)].filter(Boolean);console.log(L(`${d.length>0?d.join(", "):`${o.length} account(s) submitted`}.`))})),t.command("preview-schedule").description("Check custom release ranges without saving").option("--amount <n>","Deferral amount (sum of the eligible line amounts)",Ct).option("--start <YYYY-MM-DD>","Amortization start date").option("--months <n>","Effective life in whole months",pe).option("--schedule <json>","JSON array of { fromPeriod, toPeriod, amount }").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((n.amount===void 0||!n.start||!n.months||!n.schedule)&&(console.error(K("Required: --amount, --start, --months, --schedule")),process.exit(1)),i={deferralAmount:n.amount,amortizationStartDate:n.start,effectiveLife:n.months,customSchedule:JSON.parse(n.schedule)});let o=await cj(r,i);console.log(JSON.stringify(Td(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("bulk-upsert").description("Create deferrals in bulk (max 500). Creates only, always ACTIVE, STRAIGHT_LINE, dates YYYY-MM-DD. Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await lj(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk create started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))})),t.command("bulk-update").description("Update deferrals in bulk (max 500). Each row is partial; resourceId and reference are required per row. Not for tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "deferrals": [...] })'),process.exit(1));let o=i.deferrals??i;Array.isArray(o)||(console.error('Error: expected { "deferrals": [...] }'),process.exit(1));let s=await uj(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}pn();Ul();ke();cye();Lv();et();ft();Qt();bt();var w$r=[{key:"resourceId",header:"ID",format:we},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status",format:e=>Fr(e)},{key:"leaseLiabilityRemaining",header:"Liability",align:"right",format:kr},{key:"rouNetBookValue",header:"ROU NBV",align:"right",format:kr}],v$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"}];function S$r(e){return(!/^\d+(\.\d{1,4})?$/.test(e)||Number(e)>=100)&&(console.error(K(`Error: invalid discount rate: ${e} (% per MONTH, below 100, max 4 decimal places; 6% a year is 0.5)`)),process.exit(1)),Number(e)}function t_t(e){let t=e.command("leases").description("Manage IFRS 16 leases and hire purchase (the register never posts rent: code rent bills to the current lease liability account)");t.command("get <resourceId>").description("Get lease details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await qE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Type:"),s.typeName),console.log(S("Liability:"),s.leaseLiabilityRemaining),console.log(S("ROU NBV:"),s.rouNetBookValue),console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:LT,defaults:PT,fetcher:TW,columns:w$r,label:"Searching leases",extraParams:QT}),t.command("create").description("Put a lease on the books (a draft unless --finalize). Rent is flat with --rent, stepped with --input.").option("--jot <text>",ce).option("--reference <ref>","Lease reference (required; see `clio references next --type LEASE`)").option("--name <name>","Lease name").option("--type <typeCode>","Lease type code (see `clio leases types`; HIRE_PURCHASE for hire purchase)").option("--lessor <contactResourceId>","Lessor contact resourceId").option("--start <YYYY-MM-DD>","Commencement date").option("--term <months>","Lease term in months (1-600)",pe).option("--rent <n>","Rent per month for the whole term",Ct).addOption(new qe("--payment-timing <timing>","ADVANCE (start of month) or ARREARS (end)").choices([...yh])).option("--discount-rate <n>","Discount rate in % per MONTH (6% a year is 0.5)",S$r).option("--rou-account <id>","Right-of-Use Asset account resourceId").option("--accumulated-depreciation-account <id>","Accumulated Depreciation account resourceId").option("--depreciation-expense-account <id>","Depreciation Expense account resourceId").option("--liability-account <id>","Current Lease Liability account resourceId (rent is coded here)").option("--non-current-liability-account <id>","Non-current Lease Liability account resourceId").option("--interest-account <id>","Interest Expense account resourceId (Finance Cost type)").option("--exempt","Short-term or low-value lease exemption (posts nothing)").option("--notes <text>","Internal notes").option("--finalize","Post the lease now (saveAsDraft: false)").option("--tag <name>","Tag name").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>","Read full request body from JSON file (overrides flags); needed for stepped rent, prepaid rent, restoration and ownership").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(n.reference||(console.error(K("Required: --reference")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),n.rent!==void 0&&!n.term&&(console.error(K("--rent needs --term: the rent is entered for every month of the term.")),process.exit(1)),i={reference:n.reference},n.name&&(i.name=n.name),n.type&&(i.typeCode=n.type),n.lessor&&(i.contactResourceId=n.lessor),n.start&&(i.commencementDate=n.start),n.term&&(i.leaseTerm=n.term),n.rent!==void 0&&(i.customSchedule=[{fromPeriod:1,toPeriod:n.term,amount:n.rent}]),n.paymentTiming&&(i.paymentTiming=n.paymentTiming),n.discountRate!==void 0&&(i.discountRate=n.discountRate),n.rouAccount&&(i.rouAssetAccountResourceId=n.rouAccount),n.accumulatedDepreciationAccount&&(i.accumulatedDepreciationAccountResourceId=n.accumulatedDepreciationAccount),n.depreciationExpenseAccount&&(i.depreciationExpenseAccountResourceId=n.depreciationExpenseAccount),n.liabilityAccount&&(i.leaseLiabilityAccountResourceId=n.liabilityAccount),n.nonCurrentLiabilityAccount&&(i.leaseLiabilityNonCurrentAccountResourceId=n.nonCurrentLiabilityAccount),n.interestAccount&&(i.interestExpenseAccountResourceId=n.interestAccount),n.exempt&&(i.exemptionType="EXEMPT"),n.notes&&(i.internalNotes=n.notes),n.tag&&(i.tags=[n.tag])),n.finalize&&(i.saveAsDraft=!1),n.customFields&&(i.customFields=_r(n.customFields));let o=await xW(r,i);if(oe(r,"create_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}let s=i.exemptionType==="EXEMPT";console.log(L(i.saveAsDraft!==!1?"Lease saved as a draft. Nothing is posted until it is activated.":s?"Lease registered as exempt. Nothing is posted.":"Lease created, active and posted.")),console.log(S("ID:"),o.data.resourceId),console.log(S("Liability:"),o.data.leaseLiabilityAmount??M("-")),console.log(S("ROU asset:"),o.data.rouAssetAmount??M("-"))})),t.command("update <resourceId>").description("Edit or activate a lease (partial). A schedule change on an ACTIVE lease rewrites every entry from the start date.").option("--jot <text>",ce).option("--reference <ref>","Reference (default: the stored one)").option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--custom-fields <json>","Custom field values as JSON array").option("--input <file>",'Read the update body from JSON file (overrides flags); needed for schedule fields. tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let s=he(n)??{...n.reference!==void 0&&{reference:n.reference},...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}};n.customFields&&(s.customFields=_r(n.customFields));let{tags:a,...c}=s,u=ji(a),d=u&&await zo("lease",r,()=>qE(i,r)),f=await kW(i,r,{...c,...u&&{tags:Zi(d?.tags,u)}},d||void 0);if(oe(i,"update_lease",n,f.data),n.json){console.log(JSON.stringify(f.data,null,2));return}console.log(L(s.isDraftToActive!==!0?`Lease ${r} updated.`:f.data.exemptionType==="EXEMPT"?`Lease ${r} is now active as exempt. Nothing is posted.`:`Lease ${r} is now active and posted.`))})(n)),t.command("delete <resourceId>").description("Delete a lease of any status (removes every posted entry)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await NW(i,r),oe(i,"delete_lease",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Lease ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting after a month while the liability and right-of-use asset stay on the books (not an exit: use terminate)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Last month to post (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await OW(i,r,n.date);if(oe(i,"close_out_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Lease ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out lease").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await BW(i,r);if(oe(i,"reopen_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Lease ${r} reopened.`))})(n)),t.command("calculate-termination <resourceId>").description("Preview a termination: liability and right-of-use value removed, and the gain or loss (positive = gain). Saves nothing.").option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await LW(i,r,n.date);console.log(JSON.stringify(o.data,null,2))})(n)),t.command("terminate <resourceId>").description("Take a lease off the books at a month-end, posting the gain or loss (run calculate-termination first)").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Termination date (moved to month-end)").option("--gain-loss-account <id>","Gain/loss account resourceId (required when the gain or loss is not 0)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await FW(i,r,{terminationDate:n.date,terminationGainLossAccountResourceId:n.gainLossAccount});if(oe(i,"terminate_lease",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Lease ${r} terminated.`))})(n)),t.command("undo-termination <resourceId>").description("Undo a termination").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await PW(i,r);if(oe(i,"undo_lease_termination",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Termination undone for ${r}.`))})(n)),t.command("totals").description("Lease liability (current and non-current) and right-of-use net book value as at a date, from the schedule").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await QW(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("One lease's schedule").option("--view-date <YYYY-MM-DD>","Schedule as at this date (default today)").option("--from-period <n>","First month to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await MW(i,r,n.viewDate);console.log(JSON.stringify(T3(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),Oe({parent:t,commandName:"types",fields:MT,defaults:UT,fetcher:UW,columns:v$r,label:"Searching lease types"}),t.command("preview-rent").description("Check rent ranges against the term (COMPLETE or INCOMPLETE). Body: { commencementDate, leaseTerm, customSchedule }.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error("Error: --input <file> is required (JSON with commencementDate, leaseTerm, customSchedule)"),process.exit(1));let o=await $W(r,i);console.log(JSON.stringify(Td(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("flat-rate").description("Hire purchase: convert a flat annual rate into the monthly discount rate and instalments. Saves nothing.").requiredOption("--rate <n>","Flat rate, % per year",Number).requiredOption("--financed <n>","Financed amount (cash price less down payment)",Ct).requiredOption("--term <months>","Term in months (1-600)",pe).addOption(new qe("--payment-timing <timing>","ADVANCE or ARREARS (default ARREARS)").choices([...yh])).option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await qW(n,{flatRate:r.rate,financedAmount:r.financed,leaseTerm:r.term,paymentTiming:r.paymentTiming});console.log(JSON.stringify(i.data,null,2))})(r)),t.command("bulk-update").description("Update leases in bulk (max 500): each row is partial and needs resourceId and reference. Not for rent or tag changes (use update). Returns a jobId; poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(r,n)=>{let i=he(n);i||(console.error('Error: --input <file> is required (JSON with { "leases": [...] })'),process.exit(1));let o=i.leases??i;Array.isArray(o)||(console.error('Error: expected { "leases": [...] }'),process.exit(1));let s=await jW(r,o);n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(L(`Bulk update started. Job ID: ${s.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${s.data.jobId}`)))}))}pn();ke();YB();et();J9();ft();Qt();bt();var D$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"code",header:"Code"},{key:"category",header:"Category"},{key:"status",header:"Status",format:e=>Fr(e)}],R$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"isDefault",header:"Default",format:e=>e?"yes":""},{key:"innerAxis",header:"Grouping"},{key:"journalDatePolicy",header:"Journal date"}],T$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"payFrequency",header:"Frequency"},{key:"currencyCode",header:"Currency"},{key:"status",header:"Status",format:e=>Fr(e)}];function x$r(e){let[t,r,...n]=e.split("="),i=r===void 0?void 0:gf(r);return(!t||n.length>0||i!==void 0&&(!Number.isFinite(i)||i<0))&&(console.error(K(`Error: invalid --line: ${e} (use <payTypeId> or <payTypeId>=<amount>, amount 0 or more)`)),process.exit(1)),i===void 0?{payTypeId:t}:{payTypeId:t,amount:i}}function js(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function jL(e,t){e.command("get <resourceId>").description(`Get a ${t.noun}`).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await t.get(i,r);console.log(JSON.stringify(o.data,null,2))})(n)),e.command("delete <resourceId>").description(`Delete a ${t.noun}. ${t.deleteHint}`).option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if((await t.remove(i,r))?.data?.deleted===!1){let s=`${t.noun} ${r} was not deleted: it is already gone or is not in this organization. Nothing was deleted.`;n.json?console.error(JSON.stringify({error:{code:"NOT_DELETED",message:s,resourceId:r}})):console.error(dI(s)),process.exitCode=2;return}if(oe(i,`delete_${t.toolPrefix}`,n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`${t.noun} ${r} deleted.`))})(n))}function k$r(e){let t=e.command("pay-types").description("Manage pay types: one thing paid to or deducted from employees on a payslip");jL(t,{noun:"pay type",toolPrefix:"pay_type",get:HW,remove:GW,deleteHint:"Refused while a pay profile, pay detail or payslip uses it (set it inactive instead)."}),Oe({parent:t,fields:zT,defaults:JT,fetcher:YW,columns:D$r,label:"Searching pay types"}),t.command("create").description("Create a pay type. Earning, overtime, allowance and additional payment need a debit account; deduction, employee contribution and employee tax a credit account; employer contribution and employer tax both.").option("--jot <text>",ce).option("--name <name>","Pay type name (unique)").addOption(new qe("--category <category>","Pay type category").choices([...zg])).option("--code <code>","Short code (unique)").option("--description <text>","Description").option("--debit-account <id>","Debit account resourceId").option("--credit-account <id>","Credit account resourceId").addOption(new qe("--status <status>","Default ACTIVE").choices([...Ku])).option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||((!n.name||!n.category)&&(console.error(K("Required: --name and --category")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1)),i=js({name:n.name,category:n.category,code:n.code,description:n.description,debitAccountResourceId:n.debitAccount,creditAccountResourceId:n.creditAccount,status:n.status}));let o=await zW(r,i);if(oe(r,"create_pay_type",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L("Pay type created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Edit a pay type (partial). The category is locked once a payslip uses the pay type.").option("--jot <text>",ce).option("--name <name>","New name").addOption(new qe("--category <category>","New category (set the account it needs and clear the one it no longer uses)").choices([...zg])).option("--code <code>","New code").option("--description <text>","New description").option("--debit-account <id>","Debit account resourceId").option("--credit-account <id>","Credit account resourceId").addOption(new qe("--status <status>","ACTIVE or INACTIVE").choices([...Ku])).option("--clear-code","Empty the code").option("--clear-description","Empty the description").option("--clear-debit-account","Empty the debit account").option("--clear-credit-account","Empty the credit account").option("--input <file>","Read the update body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n)??js({name:n.name,category:n.category,code:n.code,description:n.description,debitAccountResourceId:n.debitAccount,creditAccountResourceId:n.creditAccount,status:n.status,clearCode:n.clearCode,clearDescription:n.clearDescription,clearDebitAccountResourceId:n.clearDebitAccount,clearCreditAccountResourceId:n.clearCreditAccount}),s=await JW(i,r,o);if(oe(i,"update_pay_type",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L(`Pay type ${r} updated.`))})(n))}function N$r(e){let t=e.command("payrun-posting-rules").description("Manage payrun posting rules: how a payrun books its journal (not claim posting rules: see posting-rules)");jL(t,{noun:"payrun posting rule",toolPrefix:"payrun_posting_rule",get:WW,remove:ZW,deleteHint:"The default rule, and one a pay profile or payrun names, are refused."}),Oe({parent:t,fields:GT,defaults:VT,fetcher:VW,columns:R$r,label:"Searching payrun posting rules"});let r=i=>i.option("--jot <text>",ce).option("--net-pay-account <id>","Account net pay is credited to (Payroll Payable)").addOption(new qe("--inner-axis <axis>","How journal lines merge (default BY_PAY_TYPE)").choices([...R_])).addOption(new qe("--journal-date-policy <policy>","The journal date (default PAYMENT_DATE)").choices([...T_])).option("--reference-template <text>","Journal reference, max 255, e.g. PAYRUN-{period}-{payrunName}").option("--line-template <text>","Journal line description, e.g. {payType} {account}").option("--default","Make this the default rule").option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output"),n=i=>js({name:i.name,netPayAccountResourceId:i.netPayAccount,innerAxis:i.innerAxis,journalDatePolicy:i.journalDatePolicy,journalReferenceTemplate:i.referenceTemplate,lineDescriptionTemplate:i.lineTemplate,isDefault:i.default});r(t.command("create").description("Create a payrun posting rule. The first rule in the organization is its default.").option("--name <name>","Rule name (unique)")).action(x(async(i,o)=>{let s=he(o);!s&&(!o.name||!o.netPayAccount)&&(console.error(K("Required: --name and --net-pay-account")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let a=await KW(i,s??n(o));if(oe(i,"create_payrun_posting_rule",o,a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L("Payrun posting rule created.")),console.log(S("ID:"),a.data.resourceId)})),r(t.command("update <resourceId>").description("Edit a payrun posting rule (partial). --default makes it the default; the default cannot be unset.").option("--name <name>","New name")).action((i,o)=>x(async s=>{let a=await XW(s,i,he(o)??n(o));if(oe(s,"update_payrun_posting_rule",o,a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L(`Payrun posting rule ${i} updated.`))})(o))}function O$r(e){let t=e.command("pay-profiles").description("Manage pay profiles: shared pay templates (frequency, currency, posting rule, pay type lines)");jL(t,{noun:"pay profile",toolPrefix:"pay_profile",get:t4,remove:i4,deleteHint:"Refused while any employee is or was on it (set it inactive instead)."}),Oe({parent:t,fields:WT,defaults:KT,fetcher:e4,columns:T$r,label:"Searching pay profiles"});let r=i=>i.option("--jot <text>",ce).option("--description <text>","Description").addOption(new qe("--frequency <frequency>","How often employees are paid").choices([...zl])).option("--currency <code>","Currency code (ISO 4217)").option("--line <payTypeId[=amount]>","A pay type line, repeatable. No amount means the figure is set per employee. On update the lines replace every line",gs,[]).option("--posting-rule <id>","Payrun posting rule resourceId (default: the organization's default)").addOption(new qe("--proration <type>","How a part-period is pro-rated").choices([...L$])).option("--work-week <days>","Days worked a week: 5, 5.5 or 6 (WORKING_DAYS, FIXED_DAYS)",Number).option("--days-per-month <n>","Days a month a line is divided by, 1 to 31 (FIXED_DAYS)",pe).addOption(new qe("--status <status>","ACTIVE or INACTIVE").choices([...Ku])).option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output"),n=i=>js({name:i.name,description:i.description,payFrequency:i.frequency,currencyCode:i.currency,payTypeLines:i.line.length>0?i.line.map(x$r):void 0,payrunPostingRuleResourceId:i.postingRule,prorationType:i.proration,workWeek:i.workWeek,daysPerMonth:i.daysPerMonth,status:i.status});r(t.command("create").description("Create a pay profile").option("--name <name>","Pay profile name (unique)")).action(x(async(i,o)=>{let s=he(o);!s&&(!o.name||!o.frequency||!o.currency)&&(console.error(K("Required: --name, --frequency and --currency")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let a=await r4(i,s??n(o));if(oe(i,"create_pay_profile",o,a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L("Pay profile created.")),console.log(S("ID:"),a.data.resourceId)})),r(t.command("update <resourceId>").description("Edit a pay profile (partial). --line replaces every line. Frequency and currency lock once employees are on it.").option("--name <name>","New name").option("--clear-description","Empty the description").option("--clear-posting-rule","Put the profile back on the default posting rule")).action((i,o)=>x(async s=>{let a=he(o)??{...n(o),...js({clearDescription:o.clearDescription,clearPayrunPostingRuleResourceId:o.clearPostingRule})},c=await n4(s,i,a);if(oe(s,"update_pay_profile",o,c.data),o.json){console.log(JSON.stringify(c.data,null,2));return}console.log(L(`Pay profile ${i} updated.`))})(o))}function r_t(e){k$r(e),N$r(e),O$r(e)}ke();uye();et();ft();Qt();bt();var B$r=[{key:"resourceId",header:"ID",format:we},{key:"employee.name",header:"Employee"},{key:"payProfile.name",header:"Pay profile"},{key:"effectiveFromDate",header:"From",format:vs},{key:"effectiveToDate",header:"To",format:vs}];function F$r(e){let[t,r,...n]=e.split("="),i=gf(r??"");return(!t||r===void 0||n.length>0||!Number.isFinite(i)||i<0)&&(console.error(K(`Error: invalid --figure: ${e} (use <payTypeId>=<amount>, amount 0 or more)`)),process.exit(1)),{payTypeId:t,amount:i}}function n_t(e){return e.length>0?e.map(F$r):void 0}function i_t(e){let t=e.command("employee-pay-details").description("Manage employee pay details: an employee's pay record on a pay profile from a date. A raise is a new pay detail from the new date, not an update.");Oe({parent:t,fields:XT,defaults:ZT,fetcher:o4,columns:B$r,label:"Searching employee pay details",extraParams:ex}),t.command("create").description("Put an employee on a pay profile from a date. The previous pay detail ends the day before.").option("--jot <text>",ce).option("--employee <id>","Employee resourceId (active)").option("--pay-profile <id>","Pay profile resourceId (active)").option("--from <YYYY-MM-DD>","First day this applies").option("--figure <payTypeId=amount>","The employee's own amount for one pay period, repeatable",gs,[]).option("--notes <text>","Notes").option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);!i&&(!n.employee||!n.payProfile||!n.from)&&(console.error(K("Required: --employee, --pay-profile and --from")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let o=await s4(r,i??js({employeeResourceId:n.employee,payProfileResourceId:n.payProfile,effectiveFromDate:n.from,payTypeInputs:n_t(n.figure),notes:n.notes}));if(oe(r,"create_employee_pay_detail",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L("Employee pay detail created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("bulk-create").description('Put up to 500 employees on pay profiles from a JSON file: { "employeePayDetails": [...] }. Each row is saved on its own; refused rows are listed and the exit code is 1.').option("--jot <text>",ce).option("--input <file>","JSON file of pay details (required)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let o=he(n)?.employeePayDetails;Array.isArray(o)||(console.error(K("Required: --input <file> holding employeePayDetails (an array of pay details).")),process.exit(1));let s=await a4(r,o);oe(r,"bulk_create_employee_pay_details",n,s.data);let a=(s.data??[]).filter(c=>c.errorCode);if(n.json)console.log(JSON.stringify(s.data,null,2));else{console.log(L(`${(s.data??[]).length-a.length} of ${(s.data??[]).length} employee pay details created.`));for(let c of a)console.error(K(`${c.employeeResourceId??"row"}: ${c.errorCode} ${c.errorMessage??""}`.trim()))}a.length>0&&(process.exitCode=1)})),t.command("update <resourceId>").description("Correct a pay detail in place, or end the employee's pay with --to. Not for a raise: create a new pay detail from the new date.").option("--jot <text>",ce).option("--from <YYYY-MM-DD>","Corrected first day (latest pay detail only)").option("--to <YYYY-MM-DD>","Last day the pay applies (latest pay detail only)").option("--figure <payTypeId=amount>","The employee's own amount, repeatable. The figures replace every figure",gs,[]).option("--notes <text>","Notes").option("--clear-to","Remove the end date").option("--clear-notes","Empty the notes").option("--input <file>","Read the update body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await c4(i,r,he(n)??js({effectiveFromDate:n.from,effectiveToDate:n.to,payTypeInputs:n_t(n.figure),notes:n.notes,clearEffectiveToDate:n.clearTo,clearNotes:n.clearNotes}));if(oe(i,"update_employee_pay_detail",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Employee pay detail ${r} updated.`))})(n))}pn();ke();JB();et();import{randomUUID as Q$r}from"node:crypto";ft();ke();fye();et();import{randomUUID as L$r}from"node:crypto";ft();function P$r(e){let[t,r,...n]=e.split("="),i=r===void 0?void 0:gf(r);return(!t||n.length>0||i!==void 0&&!(Number.isFinite(i)&&i>0))&&(console.error(K(`Error: invalid --payslip: ${e} (use <payslipId> or <payslipId>=<amount>, amount more than 0)`)),process.exit(1)),i===void 0?{payslipResourceId:t}:{payslipResourceId:t,amount:i}}function o_t(e){let t=e.errors??[];console.log(e.valid?L("Valid."):K(`${t.length} problem(s):`));for(let r of t)console.log(M(` - ${r.code}: ${r.message??""}`.trimEnd()))}function s_t(e){e.valid||(process.exitCode=1)}function a_t(e){return e.option("--account <id>","Bank or cash account the money was paid from, in the payrun currency (required to record)").option("--value-date <YYYY-MM-DD>","Day it was paid (default: the payrun payment date)").option("--ref <reference>","Reference for payouts whose payslip gives none").option("--notes <text>","Internal notes on each payout journal").option("--payslip <id[=amount]>","A payslip to pay, repeatable; amount for a part payment (default: every payslip still owed, in full)",gs,[]).option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output")}function c_t(e,t){let r=he(e);if(r)return r;t&&Le(e,[{flag:"--account",key:"account"}]);let n=e.payslip.map(P$r);return{...js({paymentAccountResourceId:e.account,valueDate:e.valueDate,reference:e.ref,internalNotes:e.notes}),...n.length>0?{payslips:n}:{}}}function l_t(e){for(let[t,r,n]of[["validate","Check a DRAFT payrun as finalize would, listing every problem; saves nothing",y4],["preview-journal","Show the journal finalize would post, with the same problems; saves nothing",E4]])e.command(`${t} <resourceId>`).description(r).option("--journal-date <YYYY-MM-DD>","Journal date (default: the posting rule's date)").option("--api-key <key>","API key").option("--json","JSON output").action((i,o)=>x(async s=>{let a=await n(s,i,o.journalDate);if(s_t(a.data),o.json){console.log(JSON.stringify(a.data,null,2));return}o_t(a.data),t==="preview-journal"&&console.log(S("Total debit / credit:"),a.data.totalDebitAmount,"/",a.data.totalCreditAmount)})(o));e.command("finalize <resourceId>").description("Finalize a DRAFT payrun: posts one journal and makes the payslip PDFs. Run validate and preview-journal first. Finalizing a finalized run changes nothing.").option("--jot <text>",ce).option("--journal-date <YYYY-MM-DD>","Journal date (default: the posting rule's date)").option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{let i=await I4(n,t,r.journalDate);if(oe(n,"finalize_payrun",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payrun ${t} is ${i.data.status??"finalized"}.`))})(r)),e.command("bulk-finalize").description("Finalize several DRAFT payruns (async); each on its own. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--ids <list>","Payrun resourceIds (comma-separated, each once)").option("--journal-date <YYYY-MM-DD>","Journal date for every run (default: the posting rule's date)").option("--input <file>",'Read { "payruns": [{ "payrunResourceId", "journalValueDate" }] } from a JSON file (overrides flags)').option("--api-key <key>","API key").option("--json","JSON output").action(x(async(t,r)=>{let n=he(r);n||Le(r,[{flag:"--ids",key:"ids"}]);let i=n?.payruns??(In(r.ids)??[]).map(s=>({payrunResourceId:s,...js({journalValueDate:r.journalDate})})),o=await b4(t,i);if(oe(t,"bulk_finalize_payruns",r,o.data),r.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Queued bulk-finalize: jobId ${o.data.jobId??"?"}`))})),e.command("unpost <resourceId>").description("Unpost a FINALIZED payrun: its journal is voided and it goes back to DRAFT. Refused while a payout is live: void-payout first.").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{let i=await _4(n,t);if(oe(n,"unpost_payrun",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payrun ${t} is ${i.data.status??"back to draft"}.`))})(r)),e.command("void <resourceId>").description("Void a payrun for good, with a reason. Same refusals as unpost. A draft never posted is refused: delete it.").option("--jot <text>",ce).option("--reason <text>","Why, up to 500 characters").option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{Le(r,[{flag:"--reason",key:"reason"}]);let i=await C4(n,t,r.reason);if(oe(n,"void_payrun",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payrun ${t} is ${i.data.status??"void"}.`))})(r)),a_t(e.command("preview-payouts <resourceId>").description("Show what record-payouts would book per payslip, with every problem; saves nothing and moves no money")).action((t,r)=>x(async n=>{let i=await w4(n,t,c_t(r,!1));if(s_t(i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}o_t(i.data),console.log(S("Total payout:"),i.data.totalPayoutAmount)})(r)),a_t(e.command("record-payouts <resourceId>").description("Record that a FINALIZED payrun was paid OUTSIDE Jaz (async): one journal per payslip. Moves no money. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--hash <key>","Retry key (default: generated)")).action((t,r)=>x(async n=>{let i=c_t(r,!0),o=await v4(n,t,{...i,hash:r.hash??i.hash??L$r()});if(oe(n,"record_payrun_payouts",r,o.data),r.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Queued record-payouts: jobId ${o.data.jobId??"?"}`))})(r)),e.command("void-payout <journalResourceId>").description("Void one recorded payout by its journal id (see the payrun's payouts), with a reason; the payslip owes it again").option("--jot <text>",ce).option("--reason <text>","Why, up to 500 characters").option("--api-key <key>","API key").option("--json","JSON output").action((t,r)=>x(async n=>{Le(r,[{flag:"--reason",key:"reason"}]);let i=await S4(n,t,r.reason);if(oe(n,"void_payrun_payout",r,i.data),r.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Payout ${t} voided.`))})(r))}Qt();bt();var M$r=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"payrunType",header:"Type"},{key:"periodStartDate",header:"From",format:vs},{key:"periodEndDate",header:"To",format:vs},{key:"status",header:"Status",format:e=>Fr(e)},{key:"employeeCount",header:"Employees"},{key:"totalNetPayAmount",header:"Net pay"}];function U$r(e){let[t,r,...n]=e.split("="),i=gf(r??"");return(!t||!r||n.length>0||!Number.isFinite(i)||i<0)&&(console.error(K(`Error: invalid --line: ${e} (use <payTypeId>=<amount>, amount 0 or more)`)),process.exit(1)),{payTypeId:t,amount:i}}function u_t(e){return e.option("--jot <text>",ce).option("--name <name>","Display name").option("--payment-date <YYYY-MM-DD>","Payment date, the default date of the journal").option("--ref <reference>","Reference (unique, case ignored)").option("--posting-rule <id>","Payrun posting rule resourceId (default: the rule the payslips' pay profiles use)").option("--template <id>","Payslip PDF template resourceId (default: the default template)").option("--notes <text>","Internal notes").option("--custom-fields <json>",'Custom field values: [{"customFieldName":"...","actualValue":"..."}]').option("--input <file>","Read the full request body from a JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output")}function d_t(e){return js({name:e.name,paymentDate:e.paymentDate,reference:e.ref,payrunPostingRuleResourceId:e.postingRule,templateResourceId:e.template,internalNotes:e.notes,customFields:typeof e.customFields=="string"?_r(e.customFields):void 0})}function f_t(e,t,r,n){let i=t==="add-employees"?"add_payrun_employees":"remove_payrun_employees";e.command(`${t} <resourceId>`).description(r).option("--jot <text>",ce).option("--employees <list>","Employee resourceIds (comma-separated)").option("--api-key <key>","API key").option("--json","JSON output").action((o,s)=>x(async a=>{Le(s,[{flag:"--employees",key:"employees"}]);let c=await n(a,o,In(s.employees)??[]);if(oe(a,i,s,c.data),s.json){console.log(JSON.stringify(c.data,null,2));return}console.log(L(`Payrun ${o} now has ${c.data.employeeCount??"?"} employee(s).`))})(s))}function p_t(e,t){let{added:r,skipped:n}=t?HB(e.data):{added:e.data.added??[],skipped:e.data.skipped};console.log(L(`${r.length} employee(s) ${t?"could be added":"added"}, ${n?.length??0} skipped.`));for(let i of r)console.log(` + ${i.employee?.name??i.employeeResourceId}`);h_t(n??[],console.log,M)}function $$r(e){return` - ${e.employee?.name??e.employeeResourceId}: ${e.errorCode??""} ${e.errorMessage??""}`.trimEnd()}function h_t(e,t,r){let n=new Map;for(let i of e){let o=typeof i.errorCode=="string"?i.errorCode:"NO_ERROR_CODE";n.set(o,(n.get(o)??0)+1)}for(let[i,o]of n)t(r(` ${o} x ${i}`));for(let i of e)t(r($$r(i)))}function q$r(e,t,r){if(r?.length){for(let n of r)console.error(Re(n));console.error(Re(`Run: clio payruns preview-populate ${e}`));return}t?.length&&(console.error(Re(`${t.length} employee(s) skipped by the fill:`)),h_t(t,console.error,Re))}function m_t(e){let t=e.command("payruns").description("Manage employee payruns: one run for a period, one pay frequency and one currency, with a payslip per employee");jL(t,{noun:"payrun",toolPrefix:"payrun",get:vv,remove:f4,deleteHint:"New drafts only. A finalized run is refused; one finalized then unposted must be voided (payruns void)."}),Oe({parent:t,fields:tx,defaults:rx,fetcher:l4,columns:M$r,label:"Searching payruns",extraParams:nx}),u_t(t.command("create").description("Create a DRAFT payrun. --populate fills it from pay profiles at once. Type, frequency and currency cannot change later.").addOption(new qe("--type <type>","Default REGULAR. OFF_CYCLE is an extra run beside it").choices([...x_])).addOption(new qe("--frequency <frequency>","Pay frequency").choices([...zl])).option("--currency <code>","Currency code (ISO 4217)").option("--from <YYYY-MM-DD>","First day paid for").option("--to <YYYY-MM-DD>","Last day paid for").option("--populate","Fill from pay profiles now").option("--idempotency-key <key>","Retry key (default: generated)")).action(x(async(r,n)=>{let i=he(n);!i&&(!n.name||!n.frequency||!n.currency||!n.from||!n.to||!n.paymentDate)&&(console.error(K("Required: --name, --frequency, --currency, --from, --to and --payment-date")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let o=await u4(r,{...i??{...d_t(n),...js({payrunType:n.type,payFrequency:n.frequency,currencyCode:n.currency,periodStartDate:n.from,periodEndDate:n.to,populate:n.populate})},idempotencyKey:n.idempotencyKey??i?.idempotencyKey??Q$r()}),{data:s}=o,a=o.skipped,c=o.partialFailures;if(oe(r,"create_payrun",n,s),n.json){console.log(JSON.stringify({...s,...a?{skipped:a}:{},...c?{partialFailures:c}:{}},null,2));return}console.log(L(`Payrun created with ${s.employeeCount??0} employee(s).`)),console.log(S("ID:"),s.resourceId),q$r(s.resourceId,a,c)})),u_t(t.command("update <resourceId>").description("Edit a DRAFT payrun header (partial); a finalized run takes only its payslip template, sent alone. Changing the period leaves payslips as they are: run payslips refresh-payrun to rebuild them.").option("--from <YYYY-MM-DD>","First day paid for").option("--to <YYYY-MM-DD>","Last day paid for").option("--clear-ref","Empty the reference").option("--clear-notes","Empty the internal notes").option("--clear-posting-rule","Back to the rule the payslips' pay profiles use").option("--clear-template","Back to the default payslip template")).action((r,n)=>x(async i=>{let o=await d4(i,r,he(n)??{...d_t(n),...js({periodStartDate:n.from,periodEndDate:n.to,clearReference:n.clearRef,clearInternalNotes:n.clearNotes,clearPayrunPostingRuleResourceId:n.clearPostingRule,clearTemplateResourceId:n.clearTemplate})});if(oe(i,"update_payrun",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Payrun ${r} updated.`))})(n)),t.command("bulk-delete").description("Delete several new DRAFT payruns (async); each on its own. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--ids <list>","Payrun resourceIds (comma-separated, each once)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{Le(n,[{flag:"--ids",key:"ids"}]);let i=await p4(r,In(n.ids)??[]);if(oe(r,"bulk_delete_payruns",n,i.data),n.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Queued bulk-delete: jobId ${i.data.jobId??"?"}`))})),f_t(t,"add-employees","Add employees to a DRAFT payrun. One with no pay in the period gets an empty payslip: give it lines with save-lines.",h4),f_t(t,"remove-employees","Remove employees' payslips from a DRAFT payrun. They stay out when it is filled again.",m4),t.command("save-lines <resourceId>").description(`Set a payslip's lines in a DRAFT payrun. The lines REPLACE the payslip's whole list. For several payslips or to keep a line, use --input { "payslips": [...] }.`).option("--jot <text>",ce).option("--payslip <id>","Payslip resourceId").option("--line <payTypeId=amount>","A line, repeatable. Every line the payslip ends up with",gs,[]).option("--notes <text>","Notes printed on the payslip").option("--clear-notes","Empty the notes").option("--input <file>",'Read { "payslips": [...] } from a JSON file (overrides flags)').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n);!o&&(!n.payslip||n.line.length===0)&&(console.error(K("Required: --payslip and at least one --line")),console.error(M('Or use --input <file> to provide { "payslips": [...] }.')),process.exit(1));let s=o?.payslips??[js({payslipResourceId:n.payslip,lines:n.line.map(U$r),notes:n.notes,clearNotes:n.clearNotes})],a=await A4(i,r,s);if(oe(i,"save_payrun_lines",n,a.data),n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L(`Lines saved on ${s.length} payslip(s) of payrun ${r}.`))})(n)),t.command("populate <resourceId>").description("Fill a DRAFT payrun from pay profiles: adds every employee not yet in it with pay in the period. Existing payslips are not changed.").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await g4(i,r);if(oe(i,"populate_payrun",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}p_t(o,!1)})(n)),t.command("preview-populate <resourceId>").description("Show who populate would add and who would be skipped, saving nothing").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await zB(i,r);if(n.json){let{added:s,skipped:a}=HB(o.data);console.log(JSON.stringify({...o.data,added:s,...a!==void 0?{skipped:a}:{}},null,2));return}p_t(o,!0)})(n)),l_t(t)}ke();mye();et();ft();Qt();bt();var j$r=[{key:"resourceId",header:"ID",format:we},{key:"employeeName",header:"Employee"},{key:"payrun.name",header:"Payrun"},{key:"payrun.periodEndDate",header:"Period end",format:vs},{key:"netPayAmount",header:"Net pay"},{key:"payoutStatus",header:"Payout"}];function A_t(e){let t=e.command("payslips").description("Employee payslips of payruns: search, read, rebuild draft payslips from current pay, make PDFs again");t.command("get <resourceId>").description("Get a payslip with its lines, amounts and PDF link (generatedDocuments)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{console.log(JSON.stringify((await GB(i,r)).data,null,2))})(n)),Oe({parent:t,fields:ix,defaults:ox,fetcher:D4,columns:j$r,label:"Searching payslips"}),t.command("refresh <resourceId>").description("Rebuild one payslip of a DRAFT payrun from the employee's current pay. A pay-setup line replaces every line of its pay type (hand edits and hand lines of it too); lines of other pay types stay.").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await pye(i,r);if(oe(i,"refresh_payslip",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Payslip ${r} refreshed.`))})(n)),t.command("refresh-payrun <payrunResourceId>").description("Rebuild payslips of a DRAFT payrun from current pay: --payslips lists them, none means every payslip. Ones that cannot be refreshed are listed and the exit code is 1.").option("--jot <text>",ce).option("--payslips <list>","Payslip resourceIds (comma-separated). Default: all").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await hye(i,r,In(n.payslips));oe(i,"refresh_payslips",n,o.data);let s=o.data.failed??[];if(n.json)console.log(JSON.stringify(o.data,null,2));else{console.log(L(`${(o.data.refreshed??[]).length} payslip(s) refreshed, ${s.length} unchanged.`));for(let a of s)console.error(Re(`${a.employeeResourceId??"payslip"}: ${a.errorCode??""} ${a.errorMessage??""}`.trimEnd()))}s.length>0&&(process.exitCode=1)})(n)),t.command("generate <payrunResourceId>").description("Make the payslip PDFs of a FINALIZED payrun again (async): --payslips lists them, none means every payslip. Poll with: clio background-jobs get <jobId>").option("--jot <text>",ce).option("--payslips <list>","Payslip resourceIds (comma-separated). Default: all").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await R4(i,r,In(n.payslips));if(oe(i,"generate_payslips",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Queued payslip PDFs: jobId ${o.data.jobId??"?"}`)),console.log(M("Each new link replaces the old in the payslip's generatedDocuments."))})(n))}ke();Wye();Lv();Ul();et();ft();An();Qt();zt();bt();var Y$r=[{key:"resourceId",header:"ID",format:we},{key:"reference",header:"Reference"},{key:"name",header:"Name"},{key:"viewStatus",header:"Status"},{key:"outstandingPrincipal",header:"Outstanding",align:"right",format:kr}],H$r=[{key:"typeCode",header:"Code"},{key:"typeName",header:"Name"},{key:"status",header:"Status"}],g_t="TERM or INSTALLMENT",k0=["--opening-balance <n>","Principal you confirm on the date after a missed, late or partial payment","openingBalance",Ct],z$r=[{name:"drawdown",event:"drawdown",tool:"record_loan_drawdown",description:"Raise the principal of a term loan on a date (a second tranche)",flags:[["--date <YYYY-MM-DD>","Drawdown date","drawdownDate"],["--amount <n>","Amount drawn","amount",Ct],["--keep <keep>",`${g_t} (default TERM)`,"keep"],k0],required:["drawdownDate","amount"]},{name:"prepay",event:"prepayment",tool:"prepay_loan",description:"Reduce principal with an extra repayment; the register posts no cash",flags:[["--date <YYYY-MM-DD>","Prepayment date","prepaymentDate"],["--amount <n>","Amount prepaid","amount",Ct],["--keep <keep>","INSTALLMENT keeps the monthly payment (term shortens), TERM keeps the term","keep"],k0],required:["prepaymentDate","amount","keep"]},{name:"change-rate",event:"rateChange",tool:"change_loan_rate",description:"The lender changed the rate from a date (never use update for this)",flags:[["--date <YYYY-MM-DD>","Effective date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR (7.25 = 7.25% a year)","annualInterestRate",Number],["--keep <keep>",g_t,"keep"],k0],required:["effectiveDate","annualInterestRate","keep"]},{name:"capitalize",event:"capitalization",tool:"capitalize_loan_interest",description:"Add one installment's whole interest to the principal",flags:[["--date <YYYY-MM-DD>","An installment due date","capitalizationDate"],k0],required:["capitalizationDate"]},{name:"payment-holiday",event:"paymentHoliday",tool:"record_loan_payment_holiday",description:"Skip installments (skipped interest is added to the balance)",flags:[["--from-period <n>","First skipped installment (periodNumber)","fromPeriod",pe],["--to-period <n>","Last skipped installment","toPeriod",pe],["--treatment <t>","ADD_INTEREST_TO_BALANCE (end date stays) or EXTEND_TERM","treatment"],k0],required:["fromPeriod","toPeriod","treatment"]},{name:"restructure",event:"restructure",tool:"restructure_loan",description:"New terms from an installment due date; 10% or more ends the loan and creates a new one",flags:[["--date <YYYY-MM-DD>","An installment due date","effectiveDate"],["--rate <percent>","New rate, percent per YEAR","annualInterestRate",Number],["--term <months>","Installments left after the date","loanTerm",pe],["--installment <n>","The lender's new installment","installmentOverride",Ct],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"],k0],required:["effectiveDate"]},{name:"settle",event:"settlement",tool:"settle_loan",description:"End a loan early; use --preview for the payoff figure",flags:[["--date <YYYY-MM-DD>","Settlement date","settlementDate"],["--penalty <n>","Lender's penalty (quoted only)","penaltyAmount",Ct]],required:["settlementDate"]},{name:"forgive",event:"forgiveness",tool:"forgive_loan",description:"Write off the whole loan (gain above 0)",flags:[["--date <YYYY-MM-DD>","Forgiveness date","forgivenessDate"],["--amount <n>","The whole outstanding principal","amount",Ct],["--forgiven-by <who>","LENDER or SHAREHOLDER","forgivenBy"],["--equity-account <id>","Equity account, for SHAREHOLDER","equityAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["forgivenessDate","amount","forgivenBy"]},{name:"convert",event:"conversion",tool:"convert_loan_to_shares",description:"Convert the whole loan into shares (IFRIC 19)",flags:[["--date <YYYY-MM-DD>","Conversion date","conversionDate"],["--fair-value <n>","Fair value of the shares","fairValue",Ct],["--share-capital-account <id>","Shareholders Equity account","shareCapitalAccountResourceId"],["--gain-loss-account <id>","Gain or loss account (recorded only)","gainLossAccountResourceId"]],required:["conversionDate","fairValue","shareCapitalAccountResourceId"]},{name:"refinance",event:"refinance",tool:"refinance_loan",description:"Settle the loan and create a new active one; returns the NEW loan. --input: { refinanceDate, newLoan: {...} }",flags:[["--date <YYYY-MM-DD>","Refinance date","refinanceDate"]],required:["refinanceDate","newLoan"]},{name:"reclassify-current",event:"reclassifyAsCurrent",tool:"reclassify_loan_as_current",description:"Make the whole balance current from a covenant breach date (IAS 1.74)",flags:[["--date <YYYY-MM-DD>","Breach date","reclassificationDate"],["--waiver-date <YYYY-MM-DD>","Date the bank waived it","waiverDate"]],required:["reclassificationDate"]},{name:"undo",event:"undo",tool:"undo_loan_event",description:"Reverse the latest event (see `clio loans events` for the id and canUndo)",flags:[["--event <resourceId>","The latest event resourceId","eventResourceId"]],required:["eventResourceId"]}];function k5(e){console.error(K(e)),process.exit(1)}var y_t=e=>e.replace(/^--/,"").split(/[\s<]/)[0].replace(/-([a-z])/g,(t,r)=>r.toUpperCase());function J$r(e,t){let r="calculate"in iF[t.event],n=e.command(`${t.name} <resourceId>`).description(r?`${t.description}. --preview shows the figures and saves nothing`:t.description);n.option("--jot <text>",ce);for(let[i,o]of t.flags)n.option(i,o);r&&n.option("--preview","Calculate only: nothing is saved"),n.option("--input <file>","Read the whole event body from JSON file (not with the event flags)").option("--api-key <key>","API key").option("--json","JSON output").action((i,o)=>x(async s=>{let a=o.preview===!0;a&&o.jot!==void 0&&k5("--jot records the judgment behind a recorded event; a preview records nothing.");let c=he(o),u=t.flags.filter(([p])=>o[y_t(p)]!==void 0).map(([p])=>p.split(" ")[0]);if(c&&u.length>0&&k5(`${u.join(", ")} would be ignored: --input supplies the whole body. Use the flags or --input, not both.`),!c){c={};for(let[p,,h,m]of t.flags){let A=o[y_t(p)];A!==void 0&&(c[h]=m?m(A):A)}}let d=t.required.filter(p=>c[p]===void 0);d.length>0&&(console.error(K(`Required: ${d.join(", ")}`)),console.error(M("Pass the flags, or --input <file> with the full JSON body.")),process.exit(1));let f=await V3(s,t.event,i,c,a);if(a||oe(s,t.tool,o,f.data),o.json){console.log(JSON.stringify(f.data,null,2));return}console.log(a?De("Preview only, nothing saved."):L(`${t.name}: recorded on loan ${i}.`)),console.log(JSON.stringify(f.data,null,2))})(o))}function E_t(e){let t=e.command("loans").description("Manage loans (borrowings): term and on demand, with their events");Oe({parent:t,fields:$T,defaults:qT,fetcher:B3,columns:Y$r,label:"Searching loans",extraParams:jT}),Oe({parent:t,commandName:"types",fields:YT,defaults:HT,fetcher:F3,columns:H$r,label:"Searching loan types"}),t.command("get <resourceId>").description("Get a loan with its figures as of today").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await eI(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Ref:"),s.reference),console.log(S("Status:"),s.viewStatus??s.status),console.log(S("Kind:"),s.kind),console.log(S("Rate (% a year):"),s.annualInterestRate),console.log(S("Outstanding principal:"),s.outstandingPrincipal),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a loan (a draft that posts nothing unless --activate). The register posts no cash: record the drawdown and every installment yourself. Body is a JSON file; run `loans preview-schedule` first.").option("--jot <text>",ce).option("--input <file>","JSON body: reference, kind, typeCode, name, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, accounts...").option("--activate","Activate immediately (saveAsDraft: false)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error(K("--input <file> is required (JSON with reference and the loan terms).")),process.exit(1)),n.activate&&(i.saveAsDraft=!1);let o=await L3(r,i);if(oe(r,"create_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(i.saveAsDraft===!1?"Loan created, active and posted. The register posts no cash: record the drawdown and every installment yourself.":"Loan saved as a draft. Nothing is posted until it is activated.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a loan (partial). A term, fee or account change on an ACTIVE loan rewrites the whole schedule: use an event for a mid-life change").option("--jot <text>",ce).option("--name <name>","New name").option("--notes <text>","Internal notes").option("--activate","Activate a draft (isDraftToActive)").option("--input <file>",'Read the whole update body from JSON file (not with --name, --notes or --activate). tags there is { "add": [...], "remove": [...] }, not a list').option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o={...n.name!==void 0&&{name:n.name},...n.notes!==void 0&&{internalNotes:n.notes},...n.activate&&{isDraftToActive:!0}},s=he(n);s&&Object.keys(o).length>0&&k5("--name, --notes and --activate would be ignored: --input supplies the whole body. Use the flags or --input, not both.");let a=s??o;Object.keys(a).length===0&&k5("Nothing to update: pass --name, --notes, --activate or --input.");let{tags:c,...u}=a,d=ji(c),f=d&&await zo("loan",r,()=>eI(i,r)),p=await P3(i,r,{...u,...d&&{tags:Zi(f?.tags,d)}},f||void 0);if(oe(i,"update_loan",n,p.data),n.json){console.log(JSON.stringify(p.data,null,2));return}console.log(L(a.isDraftToActive===!0?`Loan ${r} activated: its schedule is posted.`:`Loan ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a loan in any status (its own ledger rows go; your bank postings stay)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await Q3(i,r),oe(i,"delete_loan",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Loan ${r} deleted.`))})(n)),t.command("close-out <resourceId>").description("Stop posting from a month-end; balances stay. Not an exit (use settle). Reverse with reopen").option("--jot <text>",ce).option("--date <YYYY-MM-DD>","Close-out date (moved to month-end)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{n.date||(console.error(K("--date is required.")),process.exit(1));let o=await M3(i,r,n.date);if(oe(i,"close_out_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Loan ${r} closed out.`))})(n)),t.command("reopen <resourceId>").description("Reopen a closed-out loan (earlier events can no longer be undone afterwards)").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await U3(i,r);if(oe(i,"reopen_loan",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L(`Loan ${r} reopened.`))})(n)),t.command("totals").description("What we owe in total: outstanding principal, current, non-current, accrued interest").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--api-key <key>","API key").option("--json","JSON output").action(r=>x(async n=>{let i=await $3(n,r.endDate);console.log(JSON.stringify(i.data,null,2))})(r)),t.command("schedule <resourceId>").description("A term loan's repayment schedule").option("--view-date <YYYY-MM-DD>","Rows posted as at this date (default today)").option("--from-period <n>","First installment number to print (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await q3(i,r,n.viewDate);console.log(JSON.stringify(Fv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})(n)),t.command("events <resourceId>").description("A loan's events, latest first (canUndo marks the one that can be undone)").option("--limit <n>","Max results",pe).option("--offset <n>","Page number (0-indexed)",nt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",pe).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await ct(n,({limit:s,offset:a})=>j3(i,r,{limit:s,offset:a}),{label:"Fetching loan events",defaultLimit:20});Xe(o,[{key:"resourceId",header:"ID",format:we},{key:"eventType",header:"Event"},{key:"effectiveDate",header:"Date"},{key:"canUndo",header:"Can undo"}],n,"Loan events")})(n)),t.command("ledger <resourceId>").description("On-demand loans only: advances and repayments with the balance").option("--end-date <YYYY-MM-DD>","As-at date (default today)").option("--limit <n>","Max results",pe).option("--offset <n>","Page number (0-indexed)",nt).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await Y3(i,r,{endDate:n.endDate,limit:n.limit,offset:n.offset});console.log(JSON.stringify(o,null,2))})(n)),t.command("preview-schedule").description("The schedule these terms would produce; saves nothing").option("--input <file>","JSON body: kind, principalAmount, drawdownDate, annualInterestRate (percent per YEAR), dayCount, repaymentShape, loanTerm, fees...").option("--from-period <n>","First period to print, from 1 (default: all)",pe).option("--to-period <n>","Last period to print, inclusive",pe).option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||(console.error(K("--input <file> is required (JSON with kind, principalAmount, drawdownDate and the terms).")),process.exit(1));let o=await H3(r,i);console.log(JSON.stringify(Fv(o,{fromPeriod:n.fromPeriod,toPeriod:n.toPeriod},1/0).data,null,2))})),t.command("opening-balance <resourceId>").description("Suggest an --opening-balance for an event after a missed, late or partial payment; saves nothing").option("--event-type <type>","DRAWDOWN, PREPAYMENT, RATE_CHANGE, CAPITALIZE_INTEREST, PAYMENT_HOLIDAY or RESTRUCTURE").option("--date <YYYY-MM-DD>","Event date (for a holiday, the first skipped due date)").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{(!n.eventType||!n.date)&&(console.error(K("Required: --event-type, --date")),process.exit(1));let o=await z3(i,{resourceId:r,eventType:n.eventType,date:n.date});console.log(JSON.stringify(o.data,null,2))})(n));for(let r of z$r)J$r(t,r);for(let[r,n,i]of[["bulk-upsert","Create ACTIVE loans in bulk (max 500; creates only, dates YYYY-MM-DD, no CUSTOM shape or fees)",J3],["bulk-update","Update loans in bulk (max 500; update per row, reference required on each). Not for tag changes (use update)",G3]])t.command(r).description(`${n}. Returns a jobId; poll with \`clio background-jobs get <jobId>\`.`).option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(x(async(o,s)=>{let a=he(s);a||(console.error('Error: --input <file> is required (JSON with { "loans": [...] })'),process.exit(1));let c=a.loans??a;Array.isArray(c)||(console.error('Error: expected { "loans": [...] }'),process.exit(1));let u=await i(o,c);s.json?console.log(JSON.stringify(u.data,null,2)):(console.log(L(`${r} started. Job ID: ${u.data.jobId}`)),console.log(De(` Poll progress: clio background-jobs get ${u.data.jobId}`)))}))}ke();U4();et();ID();ft();bt();Qt();var G$r=[{key:"resourceId",header:"ID",format:we},{key:"status",header:"Status",format:e=>String(e)==="ACTIVE"?L(String(e)):M(String(e))},{key:"interval",header:"Interval"},{key:"totalAmount",header:"Amount",align:"right"},{key:"businessTransactionType",header:"Type"}],V$r=[{key:"resourceId",header:"ID",format:we},{key:"scheduledTransactionType",header:"Type"},{key:"status",header:"Status",format:e=>M(String(e??""))}];function I_t(e){let t=e.command("subscriptions").alias("subs").description("Manage recurring subscriptions");lo({parent:t,description:"List subscriptions",columns:G$r,label:"Fetching subscriptions",title:"Subscriptions",fetch:(r,n)=>B4(r,n)}),t.command("get <resourceId>").description("Get subscription details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await zE(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Status:"),s.status),console.log(S("Interval:"),s.interval),console.log(S("Amount:"),s.totalAmount),console.log(S("Next:"),bf(s.nextScheduleDate)??"N/A"),console.log(S("ID:"),s.resourceId)})(n)),t.command("create").description("Create a recurring subscription (invoices only, with proration)").option("--jot <text>",ce).option("--interval <interval>","WEEKLY, MONTHLY, QUARTERLY, or YEARLY (required)").option("--start-date <YYYY-MM-DD>","Start date (required)").option("--end-date <YYYY-MM-DD>","End date (optional, omit for ongoing)").option("--contact <name|resourceId>","Customer contact (required)").option("--ref <reference>","Invoice reference").option("--date <YYYY-MM-DD>","Invoice date").option("--due <YYYY-MM-DD>","Due date").option("--account <name|resourceId>","Revenue account \u2014 applied to ALL line items (required)").option("--tax-profile <name|resourceId>","Tax profile \u2014 applied to ALL line items").option("--lines <json>","Line items as JSON array (name, unitPrice, quantity)").option("--amount <n>","Single line item amount (shorthand)",Ct).option("--line-name <name>","Line item name (used with --amount)").option("--input <file>","Read full request body from JSON file (overrides flags)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);if(!i){(!n.interval||!n.startDate)&&(console.error(K("Required: --interval, --start-date")),console.error(M("Or use --input <file> to provide full JSON body.")),process.exit(1));let s;if(n.lines)try{s=JSON.parse(n.lines)}catch{console.error(K("Invalid --lines JSON")),process.exit(1)}else n.amount!==void 0&&(s=[{name:n.lineName??"Subscription",unitPrice:n.amount,quantity:1}]);s&&(n.account||n.taxProfile)&&(s=s.map(a=>({...a,...n.account&&!a.accountResourceId?{accountResourceId:n.account}:{},...n.taxProfile&&!a.taxProfileResourceId?{taxProfileResourceId:n.taxProfile}:{}}))),i={repeat:n.interval,startDate:n.startDate,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment"},invoice:{contactResourceId:n.contact,reference:n.ref,valueDate:n.date,dueDate:n.due,lineItems:s,saveAsDraft:!1}},n.endDate&&(i.endDate=n.endDate)}let o=await F4(r,i);if(oe(r,"create_subscription",n,o.data),n.json){console.log(JSON.stringify(o.data,null,2));return}console.log(L("Subscription created.")),console.log(S("ID:"),o.data.resourceId)})),t.command("update <resourceId>").description("Update a subscription (the body must carry the invoice template; status is kept when omitted)").option("--jot <text>",ce).option("--input <file>","Read full update body from JSON file: `invoice` template required (create shape), optional endDate, repeat, status, proratedConfig").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=he(n);o||(console.error(K("Use --input <file> to provide update data.")),process.exit(1));let s=await L4(i,r,o);if(oe(i,"update_subscription",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L(`Subscription ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a subscription").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await P4(i,r),oe(i,"delete_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Subscription ${r} deleted.`))})(n)),t.command("cancel <resourceId>").description("Cancel an active subscription (prorates remaining period)").option("--jot <text>",ce).option("--cancel-date-type <type>","END_OF_CURRENT_PERIOD, END_OF_LAST_PERIOD, or CUSTOM_DATE","END_OF_CURRENT_PERIOD").option("--end-date <YYYY-MM-DD>","Custom cancel date (only with CUSTOM_DATE)").option("--prorated-text <text>","Prorated adjustment line text","Prorated adjustment").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await Q4(i,r,{cancelDateType:n.cancelDateType,proratedAdjustmentLineText:n.proratedText,endDate:n.endDate}),oe(i,"cancel_subscription",n,{resourceId:r}),n.json){console.log(JSON.stringify({cancelled:!0,resourceId:r}));return}console.log(L(`Subscription ${r} cancelled.`))})(n)),Oe({parent:t,commandName:"search-scheduled",fields:sx,defaults:ax,fetcher:M4,columns:V$r,label:"Searching scheduled transactions"})}ke();Rye();et();ft();bt();Qt();var b_t=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"}];function __t(e){let t=e.command("contact-groups").description("Manage contact groups");lo({parent:t,description:"List contact groups",columns:b_t,label:"Fetching contact groups",title:"Contact Groups",fetch:(r,n)=>$4(r,n)}),t.command("get <resourceId>").description("Get contact group details").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await q4(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Name:"),s.name),console.log(S("Contacts:"),s.associatedContacts?.length??0);for(let a of s.associatedContacts??[])console.log(` ${De(a.resourceId)} ${a.name}`);console.log(S("ID:"),s.resourceId)})(n)),Oe({parent:t,fields:zx,defaults:Jx,fetcher:j4,columns:b_t,label:"Searching contact groups",positionalArg:"name",positionalFilter:r=>({name:{contains:r}})}),t.command("create").description("Create a contact group").option("--jot <text>",ce).option("--name <name>","Group name").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let i=await Y4(r,{name:n.name});if(oe(r,"create_contact_group",n,i.data),n.json){console.log(JSON.stringify(i.data,null,2));return}console.log(L(`Contact group "${n.name}" created.`)),console.log(S("ID:"),i.data.resourceId)})),t.command("update <resourceId>").description("Update a contact group").option("--name <name>","New group name").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o={};n.name&&(o.name=n.name);let s=await H4(i,r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L("Contact group updated.")),console.log(S("ID:"),s.data.resourceId)})(n)),t.command("delete <resourceId>").description("Delete a contact group").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await z4(i,r),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Contact group ${r} deleted.`))})(n))}pn();Tye();et();ft();An();zt();bt();ke();var W$r=[{key:"resourceId",header:"ID",format:we},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"itemCode",header:"Code",format:e=>M(String(e??""))}],K$r=[{key:"itemCode",header:"Code",format:e=>M(String(e??""))},{key:"internalName",header:"Name",format:e=>String(e??"")},{key:"totalQuantity",header:"Qty",format:e=>String(e??"")},{key:"baseUnit",header:"Unit",format:e=>String(e??"")},{key:"averageCostAmount",header:"Avg Cost",format:e=>String(e??"")},{key:"balanceAmount",header:"Value",format:e=>String(e??"")}];function C_t(e){let t=e.command("inventory").alias("inv").description("Inventory management");t.command("items").description("List inventory-tracked items").option("--limit <n>","Max results",pe).option("--offset <n>","Page number offset (0-indexed)",nt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",pe).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=await ct(n,o=>J4(r,o),{label:"Fetching inventory items"});Xe(i,W$r,n,"Inventory Items")})),t.command("balance <itemResourceId>").description("Get inventory balance for an item").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o=await V4(i,r);if(n.json){console.log(JSON.stringify(o.data,null,2));return}let s=o.data;console.log(S("Item:"),s.itemResourceId),console.log(S("Qty:"),`${s.baseQty} ${s.baseUnit}`),console.log(S("Avg Cost:"),s.latestAverageCostAmount)})(n)),t.command("balances").description("List inventory balances across items, by balance status").addOption(new qe("--status <status>","Balance status").choices([...W4]).default("ALL")).option("--limit <n>","Max results",pe).option("--offset <n>","Page number offset (0-indexed)",nt).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",pe).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=n.status,o=await ct(n,s=>K4(r,i,s),{label:"Fetching inventory balances"});Xe(o,K$r,n,"Inventory Balances")})),t.command("create").description("Create an inventory-tracked item (use --input for full JSON body)").option("--item-code <code>","Item code (SKU) (required)").option("--name <name>","Item name (required)").option("--unit <unit>","Unit of measure (required)").option("--costing-method <method>","FIXED or WAC (required)").option("--cogs-account <resourceId>","COGS account resourceId, Direct Costs type (required)").option("--purchase-account <resourceId>","Purchase account resourceId, Inventory type (required)").option("--sale-account <resourceId>","Sale account resourceId (required)").option("--block-insufficient","Block transactions when stock is insufficient").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{let i=he(n);i||Le(n,[{flag:"--item-code",key:"itemCode"},{flag:"--name",key:"name"},{flag:"--unit",key:"unit"},{flag:"--costing-method",key:"costingMethod"},{flag:"--cogs-account",key:"cogsAccount"},{flag:"--purchase-account",key:"purchaseAccount"},{flag:"--sale-account",key:"saleAccount"}]);let o=i??{itemCode:n.itemCode,name:n.name,unit:n.unit,costingMethod:n.costingMethod,cogsResourceId:n.cogsAccount,purchaseAccountResourceId:n.purchaseAccount,saleAccountResourceId:n.saleAccount,appliesToSale:!0,appliesToPurchase:!0,blockInsufficientDeductions:!!n.blockInsufficient},s=await G4(r,o);if(n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L("Inventory item created.")),console.log(S("ID:"),s.data.resourceId)}))}ke();xye();et();ft();bt();Qt();var w_t=[{key:"resourceId",header:"ID",format:we},{key:"customFieldName",header:"Name"}];function v_t(e){let t=e.command("custom-fields").description("Manage custom fields");lo({parent:t,description:"List custom fields",columns:w_t,label:"Fetching custom fields",title:"Custom Fields",fetch:(r,n)=>X4(r,n)}),t.command("get <resourceId>").description("Get a custom field by resourceId").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let s=(await ZB(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Name:"),s.customFieldName||s.name||"(unnamed)"),console.log(S("ID:"),s.resourceId),console.log(S("Type:"),s.datatypeCode||s.fieldType||"\u2014"),s.description&&console.log(S("Description:"),s.description),s.defaultValue&&console.log(S("Default:"),s.defaultValue),s.listOptions?.length&&console.log(S("Options:"),s.listOptions.join(", "));let a=u=>u==="SHOW"||u==="PRINT",c=[];a(s.applyToSales)&&c.push("invoices"),a(s.applyToPurchase)&&c.push("bills"),a(s.applyToSaleCreditNote)&&c.push("customer CNs"),a(s.applyToPurchaseCreditNote)&&c.push("supplier CNs"),a(s.applyToPayment)&&c.push("payments"),a(s.appliesToFixedAssets)&&c.push("fixed assets"),c.length&&console.log(S("Applies to:"),c.join(", "))})(n)),Oe({parent:t,fields:Yx,defaults:Hx,fetcher:Z4,columns:w_t,label:"Searching custom fields"}),t.command("create").description("Create a custom field").option("--jot <text>",ce).option("--name <name>","Field name").option("--description <text>","Field description").option("--print-on-documents","Print this field on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--field-format <fmt>","CUSTOM (default, free text) or ALL_CUSTOMERS / ALL_SUPPLIERS / ALL_CONTACTS / ALL_EMPLOYEES / ALL_USERS for a picklist of that population").option("--api-key <key>","API key").option("--json","JSON output").action(x(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let o=n.invoices||n.bills||n.customerCredits||n.supplierCredits||n.payments?{invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1}:void 0,s=await e3(r,{name:n.name,description:n.description,printOnDocuments:n.printOnDocuments??!1,appliesTo:o,format:n.fieldFormat});if(oe(r,"create_custom_field",n,s.data),n.json){console.log(JSON.stringify(s.data,null,2));return}console.log(L(`Custom field "${n.name}" created.`)),console.log(S("ID:"),s.data.resourceId)})),t.command("update <resourceId>").description("Update a custom field").option("--name <name>","New field name").option("--description <text>","New description").option("--print-on-documents","Print on PDF documents").option("--no-print-on-documents","Do not print on PDF documents").option("--invoices","Apply to invoices").option("--bills","Apply to bills").option("--customer-credits","Apply to customer credit notes").option("--supplier-credits","Apply to supplier credit notes").option("--payments","Apply to payments").option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.description!==void 0&&(o.description=n.description),n.printOnDocuments!==void 0&&(o.printOnDocuments=n.printOnDocuments),(n.invoices!==void 0||n.bills!==void 0||n.customerCredits!==void 0||n.supplierCredits!==void 0||n.payments!==void 0)&&(o.appliesTo={invoices:n.invoices??!1,bills:n.bills??!1,customerCredits:n.customerCredits??!1,supplierCredits:n.supplierCredits??!1,payments:n.payments??!1});let a=await t3(i,r,o);if(n.json){console.log(JSON.stringify(a.data,null,2));return}console.log(L(`Custom field ${r} updated.`))})(n)),t.command("delete <resourceId>").description("Delete a custom field").option("--jot <text>",ce).option("--api-key <key>","API key").option("--json","JSON output").action((r,n)=>x(async i=>{if(await r3(i,r),oe(i,"delete_custom_field",n,{resourceId:r}),n.json){console.log(JSON.stringify({deleted:!0,resourceId:r}));return}console.log(L(`Custom field ${r} deleted.`))})(n))}pn();ke();zye();et();ft();zt();function S_t(e){let t=In(e)??[];if(t.length===0)throw new Gt("--ids must contain at least one resourceId (comma-separated).");return t}function D_t(e,t){if(!e||typeof e!="object")throw new Error(`${t}: the API returned no job handle. The batch may still have been accepted \u2014 check \`clio background-jobs search\` before resending.`);return e}function R_t(e){return JSON.stringify({...e,pollWith:e.jobId?`clio background-jobs get ${e.jobId}`:"clio background-jobs search",note:"Bulk is async. Per-record outcomes exist ONLY in the job, never in this response."},null,2)}function T_t(e,t){console.log(L(`${t} queued.`)),e.jobId&&console.log(S("Job ID:"),e.jobId),e.totalRecords!==void 0&&console.log(S("Records:"),String(e.totalRecords)),console.log(De(` Poll progress: clio background-jobs get ${e.jobId??"<jobId>"}`))}function x_t(e,t,r){let n=C3(e);if(t.json){let i=n.state==="approved"?!0:n.state==="refused"?!1:null;console.log(JSON.stringify({entity:r.entity,resourceId:r.resourceId,[r.jsonKey]:i,records:e},null,2))}else n.state==="refused"?console.log(K(`Not ${r.doneVerb}: ${r.entity} ${r.resourceId} \u2014 ${n.reason}`)):n.state==="unconfirmed"?console.log(K(`UNCONFIRMED: ${r.entity} ${r.resourceId} \u2014 the API returned no per-record outcome, so this neither succeeded nor failed provably. Re-read the document before recording it.`)):(console.log(L(`${r.entity} ${r.resourceId} ${r.doneVerb}.`)),e?.[0]&&r.extra?.(e[0]));return n.state!=="approved"?(process.exitCode=1,!1):!0}function k_t(e){let t=e.command("approvals").description("Approve documents or send them back for changes"),r=n=>new qe("-e, --entity <entity>","Document family").choices([...n]).makeOptionMandatory();t.command("approve <resourceId>").description("Approve one document \u2014 posts its ledger entries and makes it live").addOption(r(bp)).option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>x(async o=>{let s=await w3(o,i.entity,n);x_t(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"approved",doneVerb:"approved",extra:c=>{c.status&&console.log(S("Status:"),c.status)}})&&oe(o,"approve_documents",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-approve").description("Approve up to 100 documents (async \u2014 returns a job)").addOption(r(bp)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-100)").option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>x(async i=>{let o=S_t(n.ids),s=await v3(i,n.entity,o),a=D_t(s?.data,"bulk approve");n.json?console.log(R_t(a)):T_t(a,`Approval of ${o.length} ${n.entity}`),oe(i,"bulk_approve_documents",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n)),t.command("request-changes <resourceId>").description("Send one document back for changes instead of approving it").addOption(r(XE)).requiredOption("-m, --message <text>","Why it is sent back \u2014 opens a thread and is the only record of the reason").option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>x(async o=>{let s=await S3(o,i.entity,n,i.message);x_t(s?.data?.records,i,{entity:i.entity,resourceId:n,jsonKey:"sentBack",doneVerb:"sent back for changes",extra:c=>{let u=c.collaborationThreadPath;u&&console.log(S("Thread:"),u)}})&&oe(o,"request_document_changes",i,{entity:i.entity,resourceId:n})})(i)),t.command("bulk-request-changes").description("Send up to 500 documents back for changes with one message (async \u2014 returns a job)").addOption(r(XE)).requiredOption("--ids <ids>","Comma-separated resourceIds (1-500)").requiredOption("-m, --message <text>","Why they are sent back \u2014 the only record of the reason").option("--jot <text>",ce).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(n=>x(async i=>{let o=S_t(n.ids),s=await D3(i,n.entity,o,n.message),a=D_t(s?.data,"bulk request changes");n.json?console.log(R_t(a)):T_t(a,`Request-changes on ${o.length} ${n.entity}`),oe(i,"bulk_request_document_changes",n,{entity:n.entity,count:o.length,refs:o.map(c=>({resourceId:c}))})})(n))}ke();xie();et();Qt();bt();var N_t=[{key:"resourceId",header:"ID",format:we},{key:"name",header:"Name"},{key:"reference",header:"Reference"},{key:"currencyCode",header:"Currency"}];function O_t(e){let t=e.command("purchase-items").description("Browse the purchase-side catalog (read-only)");lo({parent:t,description:"List purchase items",columns:N_t,label:"Fetching purchase items",title:"Purchase Items",offsetMode:ty.offsetMode,fetch:(r,n)=>gq(r,n)}),t.command("get <resourceId>").description("Get a purchase item by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let s=(await yq(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("ID:"),s.resourceId);for(let[a,c]of[["Name","name"],["Reference","reference"],["Currency","currencyCode"]]){let u=s[c];u!=null&&u!==""&&console.log(S(`${a}:`),String(u))}})(n)),Oe({parent:t,fields:ux,defaults:ty,columns:N_t,label:"Searching purchase items",fetcher:Eq})}Gge();et();G_();ke();ft();zt();import{readFileSync as B_t}from"node:fs";import{isAbsolute as X$r}from"node:path";function F_t(e,t){if(e!==void 0&&t)throw new Gt("Pass the query as an argument OR --input <file>, not both.");if(t){let n;try{n=B_t(t,"utf-8")}catch{throw new Gt(`Cannot read --input file: ${t}`)}let i=n.trim();if(!i)throw new Gt(`--input file is empty: ${t}`);return i}let r=e?.trim();if(r)return r;if(!process.stdin.isTTY){let n=B_t(0,"utf-8").trim();if(n)return n}throw new Gt("A query is required. Pass it as an argument, --input <file>, or on stdin.")}var Z$r=new Set(["numeric","int","int8","bigint","float8","double precision"]);function e2r(e){return e.map((t,r)=>({key:String(r),header:t.name,align:Z$r.has(t.type)?"right":"left"}))}function t2r(e,t){return t.map(r=>Object.fromEntries(e.map((n,i)=>[String(i),r[n.name]])))}function L_t(e){let t=e.command("pseudo-sql").alias("sql").description("Read-only queries over Jaz's curated reporting tables (a restricted SQL subset, not your database)");t.command("preview [query]").description("Run a SELECT and print up to 100 rows").option("--input <file>","Read the query from a file instead of an argument").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let s=(await j8(i,F_t(r,n.input))).data;if(n.json){console.log(JSON.stringify(s,null,2));return}for(let u of s.warnings??[])console.error(Re("Warning:"),u);if(!Array.isArray(s.rows)||!Array.isArray(s.columns))throw new Error("pseudo-sql preview: upstream returned no rows/columns array");if(s.rows.length===0){console.log(M("No rows."));return}let c=s.columns.slice(0,8);console.log(ea(t2r(c,s.rows),e2r(c))),s.columns.length>c.length&&console.log(M(`Showing ${c.length} of ${s.columns.length} columns \u2014 use --json for all`)),console.log(M(`${s.rowCount} row(s)${s.truncated?" \u2014 `clio sql export` returns the full set":""}`))})(n)),t.command("export [query]").description("Export a SELECT to CSV (waits for the job by default)").option("--input <file>","Read the query from a file instead of an argument").option("--out <path>","Absolute path to write the CSV to (implies download)").option("--download","Download the CSV to ~/Downloads instead of printing the URL").option("--no-wait","Return the jobId immediately; poll with `export-status`").option("--timeout <seconds>","How long to wait for the job (default 25, max 90)",pe).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let o=F_t(r,n.input);if(n.wait===!1){let u=[["--out",n.out],["--download",n.download],["--timeout",n.timeout]].filter(([,d])=>d!==void 0).map(([d])=>d);if(u.length)throw new Gt(`--no-wait cannot be combined with ${u.join(", ")} \u2014 it returns before the export runs. Drop --no-wait, or poll with \`clio sql export-status <jobId>\`.`)}if(n.out&&!X$r(n.out))throw new Gt(`--out must be an absolute path; got "${n.out}".`);if(n.wait===!1){let u=await FB(i,o,{idempotencyKey:Jge(o)});if(n.json){console.log(JSON.stringify(u.data,null,2));return}console.log(L("Export started")),console.log(S("Job:"),u.data.jobId,M(`(${u.data.status})`)),console.log(M(`Poll with: clio sql export-status ${u.data.jobId}`));return}typeof n.timeout=="number"&&n.timeout>90&&console.error(Re(`--timeout ${n.timeout} exceeds the 90s ceiling; waiting 90s. Use --no-wait for a longer job.`));let s=!!(n.download||n.out),c=(await Y8(i,o,{timeoutSeconds:n.timeout,downloadToFile:s,outPath:n.out})).data;if(n.json){let{buffer:u,...d}=c;console.log(JSON.stringify(d,null,2));return}if(c.status==="TIMED_OUT"){console.error(Re("Still running."),M(`Poll with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(c.status!=="COMPLETED"){console.error(K(`Export ${c.status}`),c.error??""),process.exitCode=1;return}if(c.error){console.error(K("Export completed but the download failed:"),c.error),console.error(M(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}if(!c.localPath&&!c.downloadUrl){console.error(K("Export reported COMPLETED but returned no file and no URL.")),console.error(M(`Retry with: clio sql export-status ${c.jobId}`)),process.exitCode=1;return}console.log(L("Export ready")),c.rowCount!==void 0&&console.log(S("Rows:"),String(c.rowCount)+(c.truncated?M(" \u2014 more rows match than the LIMIT returned"):"")),c.localPath?console.log(S("Saved:"),c.localPath):c.downloadUrl&&console.log(S("URL:"),c.downloadUrl,M("(expires in ~15 min)"))})(n)),t.command("export-status <jobId>").description("Poll an export job").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let s=(await Iv(i,r)).data;if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("Status:"),s.status),s.rowCount!==void 0&&console.log(S("Rows:"),String(s.rowCount)),s.downloadUrl&&console.log(S("URL:"),s.downloadUrl,M("(expires in ~15 min)")),s.error?(console.error(K("Error:"),s.error),process.exitCode=1):(s.status==="FAILED"||s.status==="EXPIRED")&&(process.exitCode=1)})(n)),t.command("schema [table]").description("Show the curated catalog: tables, columns, joins").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let{data:o}=await bv(i),s=H8(o,r),a=s.scopedTo?.toLowerCase();if(n.json){console.log(JSON.stringify(s,null,2));return}if(a){let c=s.tables[0];if(console.log(S(c.name),M(c.label??"")),console.log(ea((c.columns??[]).map(u=>({column:u.name,type:u.type})),[{key:"column",header:"Column"},{key:"type",header:"Type"}])),s.joins.length){console.log(`
|
|
1097
1097
|
${S("Joins")}`);for(let u of s.joins)console.log(` ${u.leftTable}.${u.leftColumn} = ${u.rightTable}.${u.rightColumn}`)}return}console.log(ea(s.tables.map(c=>({table:c.name,label:c.label,columns:(c.columns??[]).length})),[{key:"table",header:"Table"},{key:"label",header:"Label"},{key:"columns",header:"Cols",align:"right"}])),console.log(M(`${s.tableCount} tables \xB7 ${s.joinCount} joins \xB7 ${s.functionCount} functions \xB7 version ${s.version}`))})(n)),t.command("syntax").description("Print the pseudo-SQL syntax guide").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(r=>x(async n=>{let{data:i}=await bv(n),o=i.agentSkillsDoc;if(r.json){console.log(JSON.stringify(o,null,2));return}console.log(o.content)})(r))}Tie();et();bt();ke();function P_t(e){return Array.isArray(e)?e.length?e.join(", "):"-":e!==null&&typeof e=="object"?JSON.stringify(e):String(e)}var r2r=[{key:"resourceId",header:"ID",format:we},{key:"code",header:"Code"},{key:"privileged",header:"Privileged"},{key:"roleCodes",header:"Roles",format:P_t}];function Q_t(e){let t=e.command("modules").alias("features").description("Show which features are enabled for the organization, and which roles may use them (read-only)");lo({parent:t,description:"List enabled modules",columns:r2r,label:"Fetching modules",title:"Modules",fetch:(r,n)=>mq(r,n)}),t.command("get <resourceId>").description("Get a module by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let s=(await Aq(i,r))?.data;if(!s)throw new Error(`modules get: upstream returned no record for ${r}`);if(n.json){console.log(JSON.stringify(s,null,2));return}console.log(S("ID:"),s.resourceId),H2(s,[["Code","code"],["Privileged","privileged"]]),s.roleCodes!==void 0&&s.roleCodes!==null&&(console.log(S("Roles:"),P_t(s.roleCodes)),console.log(M("A module can be enabled and still deny you \u2014 access is per role.")))})(n))}wk();rd();Hj();Qt();et();zt();ft();bt();ke();import{readFileSync as n2r,writeFileSync as M_t}from"node:fs";var U_t=[{key:"resourceId",header:"ID",format:we},{key:"templateName",header:"Name"},{key:"reportType",header:"Type"},{key:"isDefault",header:"Default"}],N5="<template>",O5="resourceId or exact name";function j_t(e,t){let r;try{r=n2r(e,"utf-8")}catch{throw new Gt(`${t}: cannot read ${e}`)}try{return JSON.parse(r)}catch{throw new Gt(`${t}: ${e} is not valid JSON`)}}function i2r(e){let t=e.indexOf("=");if(t<=0)throw new Gt(`--set takes path=value (got "${e}"), e.g. --set pdfTitleConfigs.title="Monthly P&L"`);let r=e.slice(t+1);return{op:"set",path:e.slice(0,t).trim(),value:r,fromText:!0}}function o2r(e){let t=[];if(e.edits){let r=j_t(e.edits,"--edits");if(!Array.isArray(r))throw new Gt("--edits must be a JSON array of edits");t.push(...r)}for(let r of e.set??[])t.push(i2r(r));for(let r of e.remove??[])t.push({op:"remove",path:r});return t.length>0?t:void 0}function $_t(e){return e.option("--config-file <path>","The whole layout, from a JSON file (e.g. one written by get --config-out)").option("--set <path=value>",'Change one layout value, e.g. pdfTitleConfigs.title="Monthly P&L"; read as the kind already stored there (repeatable)',gs,[]).option("--remove <path>","Remove one layout value (repeatable)",gs,[]).option("--edits <path>",`A JSON file with a list of edits (${rC.join(", ")})`).option("--report <template>","REPORT_PACK: a report in the pack, by resourceId or name (repeat, in order)",gs,[])}function q_t(e){let t=e.report;return{templateConfiguration:e.configFile?j_t(e.configFile,"--config-file"):void 0,edits:o2r(e),packTemplates:t&&t.length>0?t:void 0}}function B5(e,t,r){if(r){console.log(JSON.stringify(t,null,2));return}for(let u of t.partialFailures??[])console.log(Re(u));let n=t.template,i=n?.templateName??t.templateName,o=n?.reportType??t.reportType;console.log(L(`Report template ${e}: ${i?`${i} (${o}), `:""}${t.resourceId}`)),n?.isDefault&&console.log(M(`It is the default ${n.reportType} template.`));let s=t.previousDefault;s&&console.log(M(`Was the default: ${s.templateName} (${s.resourceId}). Undo: clio report-templates set-default ${s.resourceId}`));let a=t.removedFromPacks;a?.length&&console.log(M(`Also removed from: ${a.map(u=>u.templateName).join(", ")}`));let c=t.newDefault;c&&console.log(M(`Default pack is now: ${c.templateName}`)),t.notSaved?.length&&console.log(Re(`Saved, but the server did not keep: ${t.notSaved.join(", ")}. That part of the layout is not something this report type stores.`))}function Y_t(e){let t=e.command("report-templates").description("Report templates: the saved layout of each report, and report packs");t.command("list").description("List every report template (returns all at once; no layouts)").option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(r=>x(async n=>{let i=await zj(n);Xe({data:i.data,totalElements:i.totalElements,totalPages:i.totalPages,truncated:i.totalElements>i.data.length},U_t,r,"Report Templates")})(r)),t.command(`get ${N5}`).description(`Read a report template and its layout (${O5})`).option("--keys <list>","Only these top-level layout keys, comma-separated (e.g. pdfTitleConfigs,columnConfigs)").option("--row <rowId>",`Only this row, children included (${X_.join(", ")})`).option("--config-out <path>","Write the layout to a JSON file, ready to edit and pass back with update --config-file").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON (includes the whole layout)").action((r,n)=>x(async i=>{let o=n.keys?n.keys.split(",").map(c=>c.trim()).filter(Boolean):void 0;if(n.configOut&&(o||n.row))throw new Gt("--config-out writes the WHOLE layout, to edit and pass back with update --config-file; it cannot be combined with --keys or --row.");let s=await Gj(i,r,{keys:o,row:n.row,whole:!0});if(n.row&&!n.json&&!o){console.log(JSON.stringify(s.row,null,2));return}if(n.configOut&&M_t(n.configOut,`${JSON.stringify(s.templateConfiguration??{},null,2)}
|
|
1098
1098
|
`),n.json){console.log(JSON.stringify(s,null,2));return}if(console.log(S("ID:"),s.resourceId),H2(s,[["Name","templateName"],["Type","reportType"],["Category","reportCategory"],["Pack","reportPackType"],["Default","isDefault"]]),s.packTemplates?.length){console.log(S("Reports:"));for(let c of s.packTemplates)console.log(` ${c.templateOrder}. ${c.templateName??c.templateResourceId} (${c.reportType??""})`)}if(o){console.log(JSON.stringify(s.templateConfiguration,null,2));return}let a=Object.keys(s.templateConfiguration??{});console.log(M(`Layout: ${s.configurationChars} characters, keys: ${a.join(", ")}`)),console.log(M(n.configOut?`Layout written to ${n.configOut}`:"Read part of it with --keys, or all of it with --json or --config-out <file>."))})(n)),Oe({parent:t,fields:yx,defaults:Ex,columns:U_t,label:"Searching report templates",fetcher:Jj}),t.command("default-config").description("The system default layout a new template starts from").requiredOption("--type <reportType>",`Report type: ${ry.join(", ")}`).option("--framework <framework>",`For ${ny.join(", ")}; defaults exist for ${Ph.join(" and ")}`).option("--out <path>","Write the layout to a JSON file").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(r=>x(async n=>{let i=await iC(n,r.type,r.framework);if(r.out&&(M_t(r.out,`${JSON.stringify(i.templateConfiguration,null,2)}
|
|
1099
1099
|
`),!r.json)){console.log(L(`Default ${i.reportType} layout written to ${r.out}`));return}console.log(JSON.stringify(r.json?i:i.templateConfiguration,null,2))})(r)),$_t(t.command("create").description("Create a report template from the default layout (or --config-file), with any edits applied. Not made the default.").requiredOption("--name <name>","Template name, unique within its report type").requiredOption("--type <reportType>",`Report type: ${Ds.join(", ")}`).option("--framework <framework>",`For ${ny.join(", ")}; picks the starting layout of ${J2e.join(" and ")} (${Ph.join(" and ")} have one)`)).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(r=>x(async n=>{let i=await Vj(n,{templateName:r.name,reportType:r.type,framework:r.framework,...q_t(r)});B5("created",i,r.json)})(r)),$_t(t.command(`update ${N5}`).description(`Rename a report template, change its layout, or change a pack's reports (${O5})`).option("--name <name>","New name")).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let o=await Wj(i,r,{templateName:n.name,...q_t(n)});B5("updated",o,n.json)})(n)),t.command(`set-default ${N5}`).description(`Make a template the default of its report type, for every export and dashboard view (${O5})`).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let o=await Kj(i,r);if(o.alreadyDefault&&!n.json){console.log(M(`${o.template?.templateName} is already the default ${o.template?.reportType} template. Nothing changed.`));return}B5("set as default",o,n.json)})(n)),t.command(`delete ${N5}`).description(`Delete a report template (${O5}). Refused for a default, and for the last report in a pack.`).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>x(async i=>{let o=await Xj(i,r);B5("deleted",o,n.json)})(n))}pn();hre();dre();G_();zt();ke();var s2r=[{key:"key",header:"Destination"},{key:"label",header:"Label",format:e=>{let t=String(e??"");return t.length>28?`${t.slice(0,27)}\u2026`:t}}];function H_t(e){e.command("navigate [destination]").alias("nav").description("Find a dashboard destination and build a deep link to it (offline)").option("--query <text>","Discovery: match a substring of the key or label").option("--resource <namespace>","Discovery: restrict to one namespace, e.g. sales, purchases").addOption(new qe("--kind <kind>","Discovery: restrict to screens or modals").choices(["screen","modal"])).option("--resource-id <resourceId>","Record to focus \u2014 only with a record-modal destination").option("--org-id <resourceId>","Append org= so the link names the organization explicitly").addOption(new qe("--platform <brand>","Dashboard brand").choices(["jaz","juan"]).default("jaz")).option("--json","Output as JSON").action((t,r)=>{let{dashboardUrl:n}=lR(r.platform);if(e.opts().org)throw new Gt("--org selects a credential profile and this command reads none. Use --org-id <resourceId> to name the organization in the link.");if(!t){if(r.resourceId)throw new Gt("A --resource-id needs a destination. Pass a record-modal destination key, or drop --resource-id to search.");let o=r.resource;if(o){let a=N1e();if(!a.includes(o))throw new Gt(`Unknown --resource '${o}'. Known: ${a.join(", ")}.`)}let s=T$({query:r.query,resource:o,kind:r.kind});if(r.json){console.log(JSON.stringify(s,null,2));return}if(s.results.length===0){console.error(M(s.hint??"No destinations matched."));return}console.log(ea(s.results,s2r)),console.error(M(`${s.results.length} of ${s.total}`)),s.hint&&console.error(Re(s.hint));return}let i=uR(t,r.resourceId,{dashboardUrl:n,orgResourceId:r.orgId});if(r.json){console.log(JSON.stringify(i,null,2));return}console.log(i.url),console.error(M(`${i.label} (${i.kind})`))})}ke();a3();et();import{readFileSync as a2r}from"node:fs";function z_t(e,t){try{return JSON.parse(e)}catch(r){return console.error(K(`Invalid JSON in ${t}: ${r.message}`)),process.exitCode=1,null}}function J_t(e){let t=e.command("quick-fix <entity>").description("Bulk-update transactions or line items in one call").option("--jot <text>",ce).addHelpText("after",`
|