ofpos-shared-core 2.0.0-alpha.0 → 2.0.0-alpha.1

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/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var OFPosSharedCore=(()=>{var ao=Object.create;var jr=Object.defineProperty;var oo=Object.getOwnPropertyDescriptor;var so=Object.getOwnPropertyNames;var uo=Object.getPrototypeOf,co=Object.prototype.hasOwnProperty;var we=(h=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(h,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):h)(function(h){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+h+'" is not supported')});var re=(h,e)=>()=>(e||h((e={exports:{}}).exports,e),e.exports),lo=(h,e)=>{for(var t in e)jr(h,t,{get:e[t],enumerable:!0})},Ci=(h,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of so(e))!co.call(h,n)&&n!==t&&jr(h,n,{get:()=>e[n],enumerable:!(r=oo(e,n))||r.enumerable});return h};var Mt=(h,e,t)=>(t=h!=null?ao(uo(h)):{},Ci(e||!h||!h.__esModule?jr(t,"default",{value:h,enumerable:!0}):t,h)),po=h=>Ci(jr({},"__esModule",{value:!0}),h);var Ei=re(()=>{var wi;(function(h){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:o(),r=n(h);typeof t.Reflect!="undefined"&&(r=n(t.Reflect,r)),e(r,t),typeof t.Reflect=="undefined"&&(t.Reflect=h);function n(s,c){return function(u,l){Object.defineProperty(s,u,{configurable:!0,writable:!0,value:l}),c&&c(u,l)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function o(){return i()||a()}})(function(e,t){var r=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",i=n&&typeof Symbol.toPrimitive!="undefined"?Symbol.toPrimitive:"@@toPrimitive",a=n&&typeof Symbol.iterator!="undefined"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",s={__proto__:[]}instanceof Array,c=!o&&!s,u={create:o?function(){return st(Object.create(null))}:s?function(){return st({__proto__:null})}:function(){return st({})},has:c?function(S,C){return r.call(S,C)}:function(S,C){return C in S},get:c?function(S,C){return r.call(S,C)?S[C]:void 0}:function(S,C){return S[C]}},l=Object.getPrototypeOf(Function),d=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Et(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ot(),f=typeof WeakMap=="function"?WeakMap:lt(),y=n?Symbol.for("@reflect-metadata:registry"):void 0,v=wt(),p=dt(v);function g(S,C,k,N){if(D(k)){if(!Te(S))throw new TypeError;if(!We(C))throw new TypeError;return L(S,C)}else{if(!Te(S))throw new TypeError;if(!X(C))throw new TypeError;if(!X(N)&&!D(N)&&!Z(N))throw new TypeError;return Z(N)&&(N=void 0),k=ve(k),Q(S,C,k,N)}}e("decorate",g);function x(S,C){function k(N,W){if(!X(N))throw new TypeError;if(!D(W)&&!Ye(W))throw new TypeError;U(S,C,N,W)}return k}e("metadata",x);function b(S,C,k,N){if(!X(k))throw new TypeError;return D(N)||(N=ve(N)),U(S,C,k,N)}e("defineMetadata",b);function A(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),T(S,C,k)}e("hasMetadata",A);function I(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),j(S,C,k)}e("hasOwnMetadata",I);function F(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),z(S,C,k)}e("getMetadata",F);function w(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),B(S,C,k)}e("getOwnMetadata",w);function q(S,C){if(!X(S))throw new TypeError;return D(C)||(C=ve(C)),O(S,C)}e("getMetadataKeys",q);function M(S,C){if(!X(S))throw new TypeError;return D(C)||(C=ve(C)),_(S,C)}e("getOwnMetadataKeys",M);function E(S,C,k){if(!X(C))throw new TypeError;if(D(k)||(k=ve(k)),!X(C))throw new TypeError;D(k)||(k=ve(k));var N=ft(C,k,!1);return D(N)?!1:N.OrdinaryDeleteMetadata(S,C,k)}e("deleteMetadata",E);function L(S,C){for(var k=S.length-1;k>=0;--k){var N=S[k],W=N(C);if(!D(W)&&!Z(W)){if(!We(W))throw new TypeError;C=W}}return C}function Q(S,C,k,N){for(var W=S.length-1;W>=0;--W){var me=S[W],be=me(C,k,N);if(!D(be)&&!Z(be)){if(!X(be))throw new TypeError;N=be}}return N}function T(S,C,k){var N=j(S,C,k);if(N)return!0;var W=Ue(C);return Z(W)?!1:T(S,W,k)}function j(S,C,k){var N=ft(C,k,!1);return D(N)?!1:se(N.OrdinaryHasOwnMetadata(S,C,k))}function z(S,C,k){var N=j(S,C,k);if(N)return B(S,C,k);var W=Ue(C);if(!Z(W))return z(S,W,k)}function B(S,C,k){var N=ft(C,k,!1);if(!D(N))return N.OrdinaryGetOwnMetadata(S,C,k)}function U(S,C,k,N){var W=ft(k,N,!0);W.OrdinaryDefineOwnMetadata(S,C,k,N)}function O(S,C){var k=_(S,C),N=Ue(S);if(N===null)return k;var W=O(N,C);if(W.length<=0)return k;if(k.length<=0)return W;for(var me=new m,be=[],ee=0,$=k;ee<$.length;ee++){var V=$[ee],K=me.has(V);K||(me.add(V),be.push(V))}for(var G=0,ne=W;G<ne.length;G++){var V=ne[G],K=me.has(V);K||(me.add(V),be.push(V))}return be}function _(S,C){var k=ft(S,C,!1);return k?k.OrdinaryOwnMetadataKeys(S,C):[]}function R(S){if(S===null)return 1;switch(typeof S){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return S===null?1:6;default:return 6}}function D(S){return S===void 0}function Z(S){return S===null}function te(S){return typeof S=="symbol"}function X(S){return typeof S=="object"?S!==null:typeof S=="function"}function Y(S,C){switch(R(S)){case 0:return S;case 1:return S;case 2:return S;case 3:return S;case 4:return S;case 5:return S}var k=C===3?"string":C===5?"number":"default",N=ut(S,i);if(N!==void 0){var W=N.call(S,k);if(X(W))throw new TypeError;return W}return ye(S,k==="default"?"number":k)}function ye(S,C){if(C==="string"){var k=S.toString;if(pe(k)){var N=k.call(S);if(!X(N))return N}var W=S.valueOf;if(pe(W)){var N=W.call(S);if(!X(N))return N}}else{var W=S.valueOf;if(pe(W)){var N=W.call(S);if(!X(N))return N}var me=S.toString;if(pe(me)){var N=me.call(S);if(!X(N))return N}}throw new TypeError}function se(S){return!!S}function Ne(S){return""+S}function ve(S){var C=Y(S,3);return te(C)?C:Ne(C)}function Te(S){return Array.isArray?Array.isArray(S):S instanceof Object?S instanceof Array:Object.prototype.toString.call(S)==="[object Array]"}function pe(S){return typeof S=="function"}function We(S){return typeof S=="function"}function Ye(S){switch(R(S)){case 3:return!0;case 4:return!0;default:return!1}}function Xe(S,C){return S===C||S!==S&&C!==C}function ut(S,C){var k=S[C];if(k!=null){if(!pe(k))throw new TypeError;return k}}function vt(S){var C=ut(S,a);if(!pe(C))throw new TypeError;var k=C.call(S);if(!X(k))throw new TypeError;return k}function ct(S){return S.value}function qe(S){var C=S.next();return C.done?!1:C}function ke(S){var C=S.return;C&&C.call(S)}function Ue(S){var C=Object.getPrototypeOf(S);if(typeof S!="function"||S===l||C!==l)return C;var k=S.prototype,N=k&&Object.getPrototypeOf(k);if(N==null||N===Object.prototype)return C;var W=N.constructor;return typeof W!="function"||W===S?C:W}function bt(){var S;!D(y)&&typeof t.Reflect!="undefined"&&!(y in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(S=ht(t.Reflect));var C,k,N,W=new f,me={registerProvider:be,getProvider:$,setProvider:K};return me;function be(G){if(!Object.isExtensible(me))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case S===G:break;case D(C):C=G;break;case C===G:break;case D(k):k=G;break;case k===G:break;default:N===void 0&&(N=new m),N.add(G);break}}function ee(G,ne){if(!D(C)){if(C.isProviderFor(G,ne))return C;if(!D(k)){if(k.isProviderFor(G,ne))return C;if(!D(N))for(var de=vt(N);;){var Ie=qe(de);if(!Ie)return;var Ze=ct(Ie);if(Ze.isProviderFor(G,ne))return ke(de),Ze}}}if(!D(S)&&S.isProviderFor(G,ne))return S}function $(G,ne){var de=W.get(G),Ie;return D(de)||(Ie=de.get(ne)),D(Ie)&&(Ie=ee(G,ne),D(Ie)||(D(de)&&(de=new d,W.set(G,de)),de.set(ne,Ie))),Ie}function V(G){if(D(G))throw new TypeError;return C===G||k===G||!D(N)&&N.has(G)}function K(G,ne,de){if(!V(de))throw new Error("Metadata provider not registered.");var Ie=$(G,ne);if(Ie!==de){if(!D(Ie))return!1;var Ze=W.get(G);D(Ze)&&(Ze=new d,W.set(G,Ze)),Ze.set(ne,de)}return!0}}function wt(){var S;return!D(y)&&X(t.Reflect)&&Object.isExtensible(t.Reflect)&&(S=t.Reflect[y]),D(S)&&(S=bt()),!D(y)&&X(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:S}),S}function dt(S){var C=new f,k={isProviderFor:function(V,K){var G=C.get(V);return D(G)?!1:G.has(K)},OrdinaryDefineOwnMetadata:be,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:me,OrdinaryOwnMetadataKeys:ee,OrdinaryDeleteMetadata:$};return v.registerProvider(k),k;function N(V,K,G){var ne=C.get(V),de=!1;if(D(ne)){if(!G)return;ne=new d,C.set(V,ne),de=!0}var Ie=ne.get(K);if(D(Ie)){if(!G)return;if(Ie=new d,ne.set(K,Ie),!S.setProvider(V,K,k))throw ne.delete(K),de&&C.delete(V),new Error("Wrong provider for target.")}return Ie}function W(V,K,G){var ne=N(K,G,!1);return D(ne)?!1:se(ne.has(V))}function me(V,K,G){var ne=N(K,G,!1);if(!D(ne))return ne.get(V)}function be(V,K,G,ne){var de=N(G,ne,!0);de.set(V,K)}function ee(V,K){var G=[],ne=N(V,K,!1);if(D(ne))return G;for(var de=ne.keys(),Ie=vt(de),Ze=0;;){var Ht=qe(Ie);if(!Ht)return G.length=Ze,G;var ni=ct(Ht);try{G[Ze]=ni}catch(zr){try{ke(Ie)}finally{throw zr}}Ze++}}function $(V,K,G){var ne=N(K,G,!1);if(D(ne)||!ne.delete(V))return!1;if(ne.size===0){var de=C.get(K);D(de)||(de.delete(G),de.size===0&&C.delete(de))}return!0}}function ht(S){var C=S.defineMetadata,k=S.hasOwnMetadata,N=S.getOwnMetadata,W=S.getOwnMetadataKeys,me=S.deleteMetadata,be=new f,ee={isProviderFor:function($,V){var K=be.get($);return!D(K)&&K.has(V)?!0:W($,V).length?(D(K)&&(K=new m,be.set($,K)),K.add(V),!0):!1},OrdinaryDefineOwnMetadata:C,OrdinaryHasOwnMetadata:k,OrdinaryGetOwnMetadata:N,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:me};return ee}function ft(S,C,k){var N=v.getProvider(S,C);if(!D(N))return N;if(k){if(v.setProvider(S,C,p))return p;throw new Error("Illegal state.")}}function Et(){var S={},C=[],k=(function(){function ee($,V,K){this._index=0,this._keys=$,this._values=V,this._selector=K}return ee.prototype["@@iterator"]=function(){return this},ee.prototype[a]=function(){return this},ee.prototype.next=function(){var $=this._index;if($>=0&&$<this._keys.length){var V=this._selector(this._keys[$],this._values[$]);return $+1>=this._keys.length?(this._index=-1,this._keys=C,this._values=C):this._index++,{value:V,done:!1}}return{value:void 0,done:!0}},ee.prototype.throw=function($){throw this._index>=0&&(this._index=-1,this._keys=C,this._values=C),$},ee.prototype.return=function($){return this._index>=0&&(this._index=-1,this._keys=C,this._values=C),{value:$,done:!0}},ee})(),N=(function(){function ee(){this._keys=[],this._values=[],this._cacheKey=S,this._cacheIndex=-2}return Object.defineProperty(ee.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ee.prototype.has=function($){return this._find($,!1)>=0},ee.prototype.get=function($){var V=this._find($,!1);return V>=0?this._values[V]:void 0},ee.prototype.set=function($,V){var K=this._find($,!0);return this._values[K]=V,this},ee.prototype.delete=function($){var V=this._find($,!1);if(V>=0){for(var K=this._keys.length,G=V+1;G<K;G++)this._keys[G-1]=this._keys[G],this._values[G-1]=this._values[G];return this._keys.length--,this._values.length--,Xe($,this._cacheKey)&&(this._cacheKey=S,this._cacheIndex=-2),!0}return!1},ee.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=S,this._cacheIndex=-2},ee.prototype.keys=function(){return new k(this._keys,this._values,W)},ee.prototype.values=function(){return new k(this._keys,this._values,me)},ee.prototype.entries=function(){return new k(this._keys,this._values,be)},ee.prototype["@@iterator"]=function(){return this.entries()},ee.prototype[a]=function(){return this.entries()},ee.prototype._find=function($,V){if(!Xe(this._cacheKey,$)){this._cacheIndex=-1;for(var K=0;K<this._keys.length;K++)if(Xe(this._keys[K],$)){this._cacheIndex=K;break}}return this._cacheIndex<0&&V&&(this._cacheIndex=this._keys.length,this._keys.push($),this._values.push(void 0)),this._cacheIndex},ee})();return N;function W(ee,$){return ee}function me(ee,$){return $}function be(ee,$){return[ee,$]}}function Ot(){var S=(function(){function C(){this._map=new d}return Object.defineProperty(C.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),C.prototype.has=function(k){return this._map.has(k)},C.prototype.add=function(k){return this._map.set(k,k),this},C.prototype.delete=function(k){return this._map.delete(k)},C.prototype.clear=function(){this._map.clear()},C.prototype.keys=function(){return this._map.keys()},C.prototype.values=function(){return this._map.keys()},C.prototype.entries=function(){return this._map.entries()},C.prototype["@@iterator"]=function(){return this.keys()},C.prototype[a]=function(){return this.keys()},C})();return S}function lt(){var S=16,C=u.create(),k=N();return(function(){function $(){this._key=N()}return $.prototype.has=function(V){var K=W(V,!1);return K!==void 0?u.has(K,this._key):!1},$.prototype.get=function(V){var K=W(V,!1);return K!==void 0?u.get(K,this._key):void 0},$.prototype.set=function(V,K){var G=W(V,!0);return G[this._key]=K,this},$.prototype.delete=function(V){var K=W(V,!1);return K!==void 0?delete K[this._key]:!1},$.prototype.clear=function(){this._key=N()},$})();function N(){var $;do $="@@WeakMap@@"+ee();while(u.has(C,$));return C[$]=!0,$}function W($,V){if(!r.call($,k)){if(!V)return;Object.defineProperty($,k,{value:u.create()})}return $[k]}function me($,V){for(var K=0;K<V;++K)$[K]=Math.random()*255|0;return $}function be($){if(typeof Uint8Array=="function"){var V=new Uint8Array($);return typeof crypto!="undefined"?crypto.getRandomValues(V):typeof msCrypto!="undefined"?msCrypto.getRandomValues(V):me(V,$),V}return me(new Array($),$)}function ee(){var $=be(S);$[6]=$[6]&79|64,$[8]=$[8]&191|128;for(var V="",K=0;K<S;++K){var G=$[K];(K===4||K===6||K===8)&&(V+="-"),G<16&&(V+="0"),V+=G.toString(16).toLowerCase()}return V}}function st(S){return S.__=void 0,delete S.__,S}})})(wi||(wi={}))});var ae=re((pn,Mi)=>{(function(h,e){typeof pn=="object"?Mi.exports=pn=e():typeof define=="function"&&define.amd?define([],e):h.CryptoJS=e()})(pn,function(){var h=h||(function(e,t){var r;if(typeof window!="undefined"&&window.crypto&&(r=window.crypto),typeof self!="undefined"&&self.crypto&&(r=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof window!="undefined"&&window.msCrypto&&(r=window.msCrypto),!r&&typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof we=="function")try{r=we("crypto")}catch{}var n=function(){if(r){if(typeof r.getRandomValues=="function")try{return r.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof r.randomBytes=="function")try{return r.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},i=Object.create||(function(){function p(){}return function(g){var x;return p.prototype=g,x=new p,p.prototype=null,x}})(),a={},o=a.lib={},s=o.Base=(function(){return{extend:function(p){var g=i(this);return p&&g.mixIn(p),(!g.hasOwnProperty("init")||this.init===g.init)&&(g.init=function(){g.$super.init.apply(this,arguments)}),g.init.prototype=g,g.$super=this,g},create:function(){var p=this.extend();return p.init.apply(p,arguments),p},init:function(){},mixIn:function(p){for(var g in p)p.hasOwnProperty(g)&&(this[g]=p[g]);p.hasOwnProperty("toString")&&(this.toString=p.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),c=o.WordArray=s.extend({init:function(p,g){p=this.words=p||[],g!=t?this.sigBytes=g:this.sigBytes=p.length*4},toString:function(p){return(p||l).stringify(this)},concat:function(p){var g=this.words,x=p.words,b=this.sigBytes,A=p.sigBytes;if(this.clamp(),b%4)for(var I=0;I<A;I++){var F=x[I>>>2]>>>24-I%4*8&255;g[b+I>>>2]|=F<<24-(b+I)%4*8}else for(var w=0;w<A;w+=4)g[b+w>>>2]=x[w>>>2];return this.sigBytes+=A,this},clamp:function(){var p=this.words,g=this.sigBytes;p[g>>>2]&=4294967295<<32-g%4*8,p.length=e.ceil(g/4)},clone:function(){var p=s.clone.call(this);return p.words=this.words.slice(0),p},random:function(p){for(var g=[],x=0;x<p;x+=4)g.push(n());return new c.init(g,p)}}),u=a.enc={},l=u.Hex={stringify:function(p){for(var g=p.words,x=p.sigBytes,b=[],A=0;A<x;A++){var I=g[A>>>2]>>>24-A%4*8&255;b.push((I>>>4).toString(16)),b.push((I&15).toString(16))}return b.join("")},parse:function(p){for(var g=p.length,x=[],b=0;b<g;b+=2)x[b>>>3]|=parseInt(p.substr(b,2),16)<<24-b%8*4;return new c.init(x,g/2)}},d=u.Latin1={stringify:function(p){for(var g=p.words,x=p.sigBytes,b=[],A=0;A<x;A++){var I=g[A>>>2]>>>24-A%4*8&255;b.push(String.fromCharCode(I))}return b.join("")},parse:function(p){for(var g=p.length,x=[],b=0;b<g;b++)x[b>>>2]|=(p.charCodeAt(b)&255)<<24-b%4*8;return new c.init(x,g)}},m=u.Utf8={stringify:function(p){try{return decodeURIComponent(escape(d.stringify(p)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(p){return d.parse(unescape(encodeURIComponent(p)))}},f=o.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new c.init,this._nDataBytes=0},_append:function(p){typeof p=="string"&&(p=m.parse(p)),this._data.concat(p),this._nDataBytes+=p.sigBytes},_process:function(p){var g,x=this._data,b=x.words,A=x.sigBytes,I=this.blockSize,F=I*4,w=A/F;p?w=e.ceil(w):w=e.max((w|0)-this._minBufferSize,0);var q=w*I,M=e.min(q*4,A);if(q){for(var E=0;E<q;E+=I)this._doProcessBlock(b,E);g=b.splice(0,q),x.sigBytes-=M}return new c.init(g,M)},clone:function(){var p=s.clone.call(this);return p._data=this._data.clone(),p},_minBufferSize:0}),y=o.Hasher=f.extend({cfg:s.extend(),init:function(p){this.cfg=this.cfg.extend(p),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(p){return this._append(p),this._process(),this},finalize:function(p){p&&this._append(p);var g=this._doFinalize();return g},blockSize:512/32,_createHelper:function(p){return function(g,x){return new p.init(x).finalize(g)}},_createHmacHelper:function(p){return function(g,x){return new v.HMAC.init(p,x).finalize(g)}}}),v=a.algo={};return a})(Math);return h})});var Or=re((mn,qi)=>{(function(h,e){typeof mn=="object"?qi.exports=mn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(mn,function(h){return(function(e){var t=h,r=t.lib,n=r.Base,i=r.WordArray,a=t.x64={},o=a.Word=n.extend({init:function(c,u){this.high=c,this.low=u}}),s=a.WordArray=n.extend({init:function(c,u){c=this.words=c||[],u!=e?this.sigBytes=u:this.sigBytes=c.length*8},toX32:function(){for(var c=this.words,u=c.length,l=[],d=0;d<u;d++){var m=c[d];l.push(m.high),l.push(m.low)}return i.create(l,this.sigBytes)},clone:function(){for(var c=n.clone.call(this),u=c.words=this.words.slice(0),l=u.length,d=0;d<l;d++)u[d]=u[d].clone();return c}})})(),h})});var Ni=re((hn,Li)=>{(function(h,e){typeof hn=="object"?Li.exports=hn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(hn,function(h){return(function(){if(typeof ArrayBuffer=="function"){var e=h,t=e.lib,r=t.WordArray,n=r.init,i=r.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var o=a.byteLength,s=[],c=0;c<o;c++)s[c>>>2]|=a[c]<<24-c%4*8;n.call(this,s,o)}else n.apply(this,arguments)};i.prototype=r}})(),h.lib.WordArray})});var Ui=re((fn,Qi)=>{(function(h,e){typeof fn=="object"?Qi.exports=fn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(fn,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.enc,i=n.Utf16=n.Utf16BE={stringify:function(o){for(var s=o.words,c=o.sigBytes,u=[],l=0;l<c;l+=2){var d=s[l>>>2]>>>16-l%4*8&65535;u.push(String.fromCharCode(d))}return u.join("")},parse:function(o){for(var s=o.length,c=[],u=0;u<s;u++)c[u>>>1]|=o.charCodeAt(u)<<16-u%2*16;return r.create(c,s*2)}};n.Utf16LE={stringify:function(o){for(var s=o.words,c=o.sigBytes,u=[],l=0;l<c;l+=2){var d=a(s[l>>>2]>>>16-l%4*8&65535);u.push(String.fromCharCode(d))}return u.join("")},parse:function(o){for(var s=o.length,c=[],u=0;u<s;u++)c[u>>>1]|=a(o.charCodeAt(u)<<16-u%2*16);return r.create(c,s*2)}};function a(o){return o<<8&4278255360|o>>>8&16711935}})(),h.enc.Utf16})});var Pt=re((gn,Hi)=>{(function(h,e){typeof gn=="object"?Hi.exports=gn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(gn,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64={stringify:function(o){var s=o.words,c=o.sigBytes,u=this._map;o.clamp();for(var l=[],d=0;d<c;d+=3)for(var m=s[d>>>2]>>>24-d%4*8&255,f=s[d+1>>>2]>>>24-(d+1)%4*8&255,y=s[d+2>>>2]>>>24-(d+2)%4*8&255,v=m<<16|f<<8|y,p=0;p<4&&d+p*.75<c;p++)l.push(u.charAt(v>>>6*(3-p)&63));var g=u.charAt(64);if(g)for(;l.length%4;)l.push(g);return l.join("")},parse:function(o){var s=o.length,c=this._map,u=this._reverseMap;if(!u){u=this._reverseMap=[];for(var l=0;l<c.length;l++)u[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var m=o.indexOf(d);m!==-1&&(s=m)}return a(o,s,u)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function a(o,s,c){for(var u=[],l=0,d=0;d<s;d++)if(d%4){var m=c[o.charCodeAt(d-1)]<<d%4*2,f=c[o.charCodeAt(d)]>>>6-d%4*2,y=m|f;u[l>>>2]|=y<<24-l%4*8,l++}return r.create(u,l)}})(),h.enc.Base64})});var Vi=re((yn,$i)=>{(function(h,e){typeof yn=="object"?$i.exports=yn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(yn,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64url={stringify:function(o,s){s===void 0&&(s=!0);var c=o.words,u=o.sigBytes,l=s?this._safe_map:this._map;o.clamp();for(var d=[],m=0;m<u;m+=3)for(var f=c[m>>>2]>>>24-m%4*8&255,y=c[m+1>>>2]>>>24-(m+1)%4*8&255,v=c[m+2>>>2]>>>24-(m+2)%4*8&255,p=f<<16|y<<8|v,g=0;g<4&&m+g*.75<u;g++)d.push(l.charAt(p>>>6*(3-g)&63));var x=l.charAt(64);if(x)for(;d.length%4;)d.push(x);return d.join("")},parse:function(o,s){s===void 0&&(s=!0);var c=o.length,u=s?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<u.length;d++)l[u.charCodeAt(d)]=d}var m=u.charAt(64);if(m){var f=o.indexOf(m);f!==-1&&(c=f)}return a(o,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function a(o,s,c){for(var u=[],l=0,d=0;d<s;d++)if(d%4){var m=c[o.charCodeAt(d-1)]<<d%4*2,f=c[o.charCodeAt(d)]>>>6-d%4*2,y=m|f;u[l>>>2]|=y<<24-l%4*8,l++}return r.create(u,l)}})(),h.enc.Base64url})});var Ct=re((vn,zi)=>{(function(h,e){typeof vn=="object"?zi.exports=vn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(vn,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[];(function(){for(var m=0;m<64;m++)o[m]=e.abs(e.sin(m+1))*4294967296|0})();var s=a.MD5=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(m,f){for(var y=0;y<16;y++){var v=f+y,p=m[v];m[v]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360}var g=this._hash.words,x=m[f+0],b=m[f+1],A=m[f+2],I=m[f+3],F=m[f+4],w=m[f+5],q=m[f+6],M=m[f+7],E=m[f+8],L=m[f+9],Q=m[f+10],T=m[f+11],j=m[f+12],z=m[f+13],B=m[f+14],U=m[f+15],O=g[0],_=g[1],R=g[2],D=g[3];O=c(O,_,R,D,x,7,o[0]),D=c(D,O,_,R,b,12,o[1]),R=c(R,D,O,_,A,17,o[2]),_=c(_,R,D,O,I,22,o[3]),O=c(O,_,R,D,F,7,o[4]),D=c(D,O,_,R,w,12,o[5]),R=c(R,D,O,_,q,17,o[6]),_=c(_,R,D,O,M,22,o[7]),O=c(O,_,R,D,E,7,o[8]),D=c(D,O,_,R,L,12,o[9]),R=c(R,D,O,_,Q,17,o[10]),_=c(_,R,D,O,T,22,o[11]),O=c(O,_,R,D,j,7,o[12]),D=c(D,O,_,R,z,12,o[13]),R=c(R,D,O,_,B,17,o[14]),_=c(_,R,D,O,U,22,o[15]),O=u(O,_,R,D,b,5,o[16]),D=u(D,O,_,R,q,9,o[17]),R=u(R,D,O,_,T,14,o[18]),_=u(_,R,D,O,x,20,o[19]),O=u(O,_,R,D,w,5,o[20]),D=u(D,O,_,R,Q,9,o[21]),R=u(R,D,O,_,U,14,o[22]),_=u(_,R,D,O,F,20,o[23]),O=u(O,_,R,D,L,5,o[24]),D=u(D,O,_,R,B,9,o[25]),R=u(R,D,O,_,I,14,o[26]),_=u(_,R,D,O,E,20,o[27]),O=u(O,_,R,D,z,5,o[28]),D=u(D,O,_,R,A,9,o[29]),R=u(R,D,O,_,M,14,o[30]),_=u(_,R,D,O,j,20,o[31]),O=l(O,_,R,D,w,4,o[32]),D=l(D,O,_,R,E,11,o[33]),R=l(R,D,O,_,T,16,o[34]),_=l(_,R,D,O,B,23,o[35]),O=l(O,_,R,D,b,4,o[36]),D=l(D,O,_,R,F,11,o[37]),R=l(R,D,O,_,M,16,o[38]),_=l(_,R,D,O,Q,23,o[39]),O=l(O,_,R,D,z,4,o[40]),D=l(D,O,_,R,x,11,o[41]),R=l(R,D,O,_,I,16,o[42]),_=l(_,R,D,O,q,23,o[43]),O=l(O,_,R,D,L,4,o[44]),D=l(D,O,_,R,j,11,o[45]),R=l(R,D,O,_,U,16,o[46]),_=l(_,R,D,O,A,23,o[47]),O=d(O,_,R,D,x,6,o[48]),D=d(D,O,_,R,M,10,o[49]),R=d(R,D,O,_,B,15,o[50]),_=d(_,R,D,O,w,21,o[51]),O=d(O,_,R,D,j,6,o[52]),D=d(D,O,_,R,I,10,o[53]),R=d(R,D,O,_,Q,15,o[54]),_=d(_,R,D,O,b,21,o[55]),O=d(O,_,R,D,E,6,o[56]),D=d(D,O,_,R,U,10,o[57]),R=d(R,D,O,_,q,15,o[58]),_=d(_,R,D,O,z,21,o[59]),O=d(O,_,R,D,F,6,o[60]),D=d(D,O,_,R,T,10,o[61]),R=d(R,D,O,_,A,15,o[62]),_=d(_,R,D,O,L,21,o[63]),g[0]=g[0]+O|0,g[1]=g[1]+_|0,g[2]=g[2]+R|0,g[3]=g[3]+D|0},_doFinalize:function(){var m=this._data,f=m.words,y=this._nDataBytes*8,v=m.sigBytes*8;f[v>>>5]|=128<<24-v%32;var p=e.floor(y/4294967296),g=y;f[(v+64>>>9<<4)+15]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,f[(v+64>>>9<<4)+14]=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360,m.sigBytes=(f.length+1)*4,this._process();for(var x=this._hash,b=x.words,A=0;A<4;A++){var I=b[A];b[A]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360}return x},clone:function(){var m=i.clone.call(this);return m._hash=this._hash.clone(),m}});function c(m,f,y,v,p,g,x){var b=m+(f&y|~f&v)+p+x;return(b<<g|b>>>32-g)+f}function u(m,f,y,v,p,g,x){var b=m+(f&v|y&~v)+p+x;return(b<<g|b>>>32-g)+f}function l(m,f,y,v,p,g,x){var b=m+(f^y^v)+p+x;return(b<<g|b>>>32-g)+f}function d(m,f,y,v,p,g,x){var b=m+(y^(f|~v))+p+x;return(b<<g|b>>>32-g)+f}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)})(Math),h.MD5})});var pi=re((bn,ji)=>{(function(h,e){typeof bn=="object"?ji.exports=bn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(bn,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=t.Hasher,i=e.algo,a=[],o=i.SHA1=n.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(s,c){for(var u=this._hash.words,l=u[0],d=u[1],m=u[2],f=u[3],y=u[4],v=0;v<80;v++){if(v<16)a[v]=s[c+v]|0;else{var p=a[v-3]^a[v-8]^a[v-14]^a[v-16];a[v]=p<<1|p>>>31}var g=(l<<5|l>>>27)+y+a[v];v<20?g+=(d&m|~d&f)+1518500249:v<40?g+=(d^m^f)+1859775393:v<60?g+=(d&m|d&f|m&f)-1894007588:g+=(d^m^f)-899497514,y=f,f=m,m=d<<30|d>>>2,d=l,l=g}u[0]=u[0]+l|0,u[1]=u[1]+d|0,u[2]=u[2]+m|0,u[3]=u[3]+f|0,u[4]=u[4]+y|0},_doFinalize:function(){var s=this._data,c=s.words,u=this._nDataBytes*8,l=s.sigBytes*8;return c[l>>>5]|=128<<24-l%32,c[(l+64>>>9<<4)+14]=Math.floor(u/4294967296),c[(l+64>>>9<<4)+15]=u,s.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var s=n.clone.call(this);return s._hash=this._hash.clone(),s}});e.SHA1=n._createHelper(o),e.HmacSHA1=n._createHmacHelper(o)})(),h.SHA1})});var Ut=re((xn,Ki)=>{(function(h,e){typeof xn=="object"?Ki.exports=xn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(xn,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[],s=[];(function(){function l(y){for(var v=e.sqrt(y),p=2;p<=v;p++)if(!(y%p))return!1;return!0}function d(y){return(y-(y|0))*4294967296|0}for(var m=2,f=0;f<64;)l(m)&&(f<8&&(o[f]=d(e.pow(m,1/2))),s[f]=d(e.pow(m,1/3)),f++),m++})();var c=[],u=a.SHA256=i.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(l,d){for(var m=this._hash.words,f=m[0],y=m[1],v=m[2],p=m[3],g=m[4],x=m[5],b=m[6],A=m[7],I=0;I<64;I++){if(I<16)c[I]=l[d+I]|0;else{var F=c[I-15],w=(F<<25|F>>>7)^(F<<14|F>>>18)^F>>>3,q=c[I-2],M=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;c[I]=w+c[I-7]+M+c[I-16]}var E=g&x^~g&b,L=f&y^f&v^y&v,Q=(f<<30|f>>>2)^(f<<19|f>>>13)^(f<<10|f>>>22),T=(g<<26|g>>>6)^(g<<21|g>>>11)^(g<<7|g>>>25),j=A+T+E+s[I]+c[I],z=Q+L;A=b,b=x,x=g,g=p+j|0,p=v,v=y,y=f,f=j+z|0}m[0]=m[0]+f|0,m[1]=m[1]+y|0,m[2]=m[2]+v|0,m[3]=m[3]+p|0,m[4]=m[4]+g|0,m[5]=m[5]+x|0,m[6]=m[6]+b|0,m[7]=m[7]+A|0},_doFinalize:function(){var l=this._data,d=l.words,m=this._nDataBytes*8,f=l.sigBytes*8;return d[f>>>5]|=128<<24-f%32,d[(f+64>>>9<<4)+14]=e.floor(m/4294967296),d[(f+64>>>9<<4)+15]=m,l.sigBytes=d.length*4,this._process(),this._hash},clone:function(){var l=i.clone.call(this);return l._hash=this._hash.clone(),l}});t.SHA256=i._createHelper(u),t.HmacSHA256=i._createHmacHelper(u)})(Math),h.SHA256})});var Wi=re((An,Gi)=>{(function(h,e,t){typeof An=="object"?Gi.exports=An=e(ae(),Ut()):typeof define=="function"&&define.amd?define(["./core","./sha256"],e):e(h.CryptoJS)})(An,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.algo,i=n.SHA256,a=n.SHA224=i.extend({_doReset:function(){this._hash=new r.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=i._doFinalize.call(this);return o.sigBytes-=4,o}});e.SHA224=i._createHelper(a),e.HmacSHA224=i._createHmacHelper(a)})(),h.SHA224})});var mi=re((Sn,Yi)=>{(function(h,e,t){typeof Sn=="object"?Yi.exports=Sn=e(ae(),Or()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(h.CryptoJS)})(Sn,function(h){return(function(){var e=h,t=e.lib,r=t.Hasher,n=e.x64,i=n.Word,a=n.WordArray,o=e.algo;function s(){return i.create.apply(i,arguments)}var c=[s(1116352408,3609767458),s(1899447441,602891725),s(3049323471,3964484399),s(3921009573,2173295548),s(961987163,4081628472),s(1508970993,3053834265),s(2453635748,2937671579),s(2870763221,3664609560),s(3624381080,2734883394),s(310598401,1164996542),s(607225278,1323610764),s(1426881987,3590304994),s(1925078388,4068182383),s(2162078206,991336113),s(2614888103,633803317),s(3248222580,3479774868),s(3835390401,2666613458),s(4022224774,944711139),s(264347078,2341262773),s(604807628,2007800933),s(770255983,1495990901),s(1249150122,1856431235),s(1555081692,3175218132),s(1996064986,2198950837),s(2554220882,3999719339),s(2821834349,766784016),s(2952996808,2566594879),s(3210313671,3203337956),s(3336571891,1034457026),s(3584528711,2466948901),s(113926993,3758326383),s(338241895,168717936),s(666307205,1188179964),s(773529912,1546045734),s(1294757372,1522805485),s(1396182291,2643833823),s(1695183700,2343527390),s(1986661051,1014477480),s(2177026350,1206759142),s(2456956037,344077627),s(2730485921,1290863460),s(2820302411,3158454273),s(3259730800,3505952657),s(3345764771,106217008),s(3516065817,3606008344),s(3600352804,1432725776),s(4094571909,1467031594),s(275423344,851169720),s(430227734,3100823752),s(506948616,1363258195),s(659060556,3750685593),s(883997877,3785050280),s(958139571,3318307427),s(1322822218,3812723403),s(1537002063,2003034995),s(1747873779,3602036899),s(1955562222,1575990012),s(2024104815,1125592928),s(2227730452,2716904306),s(2361852424,442776044),s(2428436474,593698344),s(2756734187,3733110249),s(3204031479,2999351573),s(3329325298,3815920427),s(3391569614,3928383900),s(3515267271,566280711),s(3940187606,3454069534),s(4118630271,4000239992),s(116418474,1914138554),s(174292421,2731055270),s(289380356,3203993006),s(460393269,320620315),s(685471733,587496836),s(852142971,1086792851),s(1017036298,365543100),s(1126000580,2618297676),s(1288033470,3409855158),s(1501505948,4234509866),s(1607167915,987167468),s(1816402316,1246189591)],u=[];(function(){for(var d=0;d<80;d++)u[d]=s()})();var l=o.SHA512=r.extend({_doReset:function(){this._hash=new a.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(d,m){for(var f=this._hash.words,y=f[0],v=f[1],p=f[2],g=f[3],x=f[4],b=f[5],A=f[6],I=f[7],F=y.high,w=y.low,q=v.high,M=v.low,E=p.high,L=p.low,Q=g.high,T=g.low,j=x.high,z=x.low,B=b.high,U=b.low,O=A.high,_=A.low,R=I.high,D=I.low,Z=F,te=w,X=q,Y=M,ye=E,se=L,Ne=Q,ve=T,Te=j,pe=z,We=B,Ye=U,Xe=O,ut=_,vt=R,ct=D,qe=0;qe<80;qe++){var ke,Ue,bt=u[qe];if(qe<16)Ue=bt.high=d[m+qe*2]|0,ke=bt.low=d[m+qe*2+1]|0;else{var wt=u[qe-15],dt=wt.high,ht=wt.low,ft=(dt>>>1|ht<<31)^(dt>>>8|ht<<24)^dt>>>7,Et=(ht>>>1|dt<<31)^(ht>>>8|dt<<24)^(ht>>>7|dt<<25),Ot=u[qe-2],lt=Ot.high,st=Ot.low,S=(lt>>>19|st<<13)^(lt<<3|st>>>29)^lt>>>6,C=(st>>>19|lt<<13)^(st<<3|lt>>>29)^(st>>>6|lt<<26),k=u[qe-7],N=k.high,W=k.low,me=u[qe-16],be=me.high,ee=me.low;ke=Et+W,Ue=ft+N+(ke>>>0<Et>>>0?1:0),ke=ke+C,Ue=Ue+S+(ke>>>0<C>>>0?1:0),ke=ke+ee,Ue=Ue+be+(ke>>>0<ee>>>0?1:0),bt.high=Ue,bt.low=ke}var $=Te&We^~Te&Xe,V=pe&Ye^~pe&ut,K=Z&X^Z&ye^X&ye,G=te&Y^te&se^Y&se,ne=(Z>>>28|te<<4)^(Z<<30|te>>>2)^(Z<<25|te>>>7),de=(te>>>28|Z<<4)^(te<<30|Z>>>2)^(te<<25|Z>>>7),Ie=(Te>>>14|pe<<18)^(Te>>>18|pe<<14)^(Te<<23|pe>>>9),Ze=(pe>>>14|Te<<18)^(pe>>>18|Te<<14)^(pe<<23|Te>>>9),Ht=c[qe],ni=Ht.high,zr=Ht.low,Je=ct+Ze,St=vt+Ie+(Je>>>0<ct>>>0?1:0),Je=Je+V,St=St+$+(Je>>>0<V>>>0?1:0),Je=Je+zr,St=St+ni+(Je>>>0<zr>>>0?1:0),Je=Je+ke,St=St+Ue+(Je>>>0<ke>>>0?1:0),Pi=de+G,io=ne+K+(Pi>>>0<de>>>0?1:0);vt=Xe,ct=ut,Xe=We,ut=Ye,We=Te,Ye=pe,pe=ve+Je|0,Te=Ne+St+(pe>>>0<ve>>>0?1:0)|0,Ne=ye,ve=se,ye=X,se=Y,X=Z,Y=te,te=Je+Pi|0,Z=St+io+(te>>>0<Je>>>0?1:0)|0}w=y.low=w+te,y.high=F+Z+(w>>>0<te>>>0?1:0),M=v.low=M+Y,v.high=q+X+(M>>>0<Y>>>0?1:0),L=p.low=L+se,p.high=E+ye+(L>>>0<se>>>0?1:0),T=g.low=T+ve,g.high=Q+Ne+(T>>>0<ve>>>0?1:0),z=x.low=z+pe,x.high=j+Te+(z>>>0<pe>>>0?1:0),U=b.low=U+Ye,b.high=B+We+(U>>>0<Ye>>>0?1:0),_=A.low=_+ut,A.high=O+Xe+(_>>>0<ut>>>0?1:0),D=I.low=D+ct,I.high=R+vt+(D>>>0<ct>>>0?1:0)},_doFinalize:function(){var d=this._data,m=d.words,f=this._nDataBytes*8,y=d.sigBytes*8;m[y>>>5]|=128<<24-y%32,m[(y+128>>>10<<5)+30]=Math.floor(f/4294967296),m[(y+128>>>10<<5)+31]=f,d.sigBytes=m.length*4,this._process();var v=this._hash.toX32();return v},clone:function(){var d=r.clone.call(this);return d._hash=this._hash.clone(),d},blockSize:1024/32});e.SHA512=r._createHelper(l),e.HmacSHA512=r._createHmacHelper(l)})(),h.SHA512})});var Zi=re((In,Xi)=>{(function(h,e,t){typeof In=="object"?Xi.exports=In=e(ae(),Or(),mi()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./sha512"],e):e(h.CryptoJS)})(In,function(h){return(function(){var e=h,t=e.x64,r=t.Word,n=t.WordArray,i=e.algo,a=i.SHA512,o=i.SHA384=a.extend({_doReset:function(){this._hash=new n.init([new r.init(3418070365,3238371032),new r.init(1654270250,914150663),new r.init(2438529370,812702999),new r.init(355462360,4144912697),new r.init(1731405415,4290775857),new r.init(2394180231,1750603025),new r.init(3675008525,1694076839),new r.init(1203062813,3204075428)])},_doFinalize:function(){var s=a._doFinalize.call(this);return s.sigBytes-=16,s}});e.SHA384=a._createHelper(o),e.HmacSHA384=a._createHmacHelper(o)})(),h.SHA384})});var ea=re((Dn,Ji)=>{(function(h,e,t){typeof Dn=="object"?Ji.exports=Dn=e(ae(),Or()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(h.CryptoJS)})(Dn,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.x64,o=a.Word,s=t.algo,c=[],u=[],l=[];(function(){for(var f=1,y=0,v=0;v<24;v++){c[f+5*y]=(v+1)*(v+2)/2%64;var p=y%5,g=(2*f+3*y)%5;f=p,y=g}for(var f=0;f<5;f++)for(var y=0;y<5;y++)u[f+5*y]=y+(2*f+3*y)%5*5;for(var x=1,b=0;b<24;b++){for(var A=0,I=0,F=0;F<7;F++){if(x&1){var w=(1<<F)-1;w<32?I^=1<<w:A^=1<<w-32}x&128?x=x<<1^113:x<<=1}l[b]=o.create(A,I)}})();var d=[];(function(){for(var f=0;f<25;f++)d[f]=o.create()})();var m=s.SHA3=i.extend({cfg:i.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],y=0;y<25;y++)f[y]=new o.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,y){for(var v=this._state,p=this.blockSize/2,g=0;g<p;g++){var x=f[y+2*g],b=f[y+2*g+1];x=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,b=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;var A=v[g];A.high^=b,A.low^=x}for(var I=0;I<24;I++){for(var F=0;F<5;F++){for(var w=0,q=0,M=0;M<5;M++){var A=v[F+5*M];w^=A.high,q^=A.low}var E=d[F];E.high=w,E.low=q}for(var F=0;F<5;F++)for(var L=d[(F+4)%5],Q=d[(F+1)%5],T=Q.high,j=Q.low,w=L.high^(T<<1|j>>>31),q=L.low^(j<<1|T>>>31),M=0;M<5;M++){var A=v[F+5*M];A.high^=w,A.low^=q}for(var z=1;z<25;z++){var w,q,A=v[z],B=A.high,U=A.low,O=c[z];O<32?(w=B<<O|U>>>32-O,q=U<<O|B>>>32-O):(w=U<<O-32|B>>>64-O,q=B<<O-32|U>>>64-O);var _=d[u[z]];_.high=w,_.low=q}var R=d[0],D=v[0];R.high=D.high,R.low=D.low;for(var F=0;F<5;F++)for(var M=0;M<5;M++){var z=F+5*M,A=v[z],Z=d[z],te=d[(F+1)%5+5*M],X=d[(F+2)%5+5*M];A.high=Z.high^~te.high&X.high,A.low=Z.low^~te.low&X.low}var A=v[0],Y=l[I];A.high^=Y.high,A.low^=Y.low}},_doFinalize:function(){var f=this._data,y=f.words,v=this._nDataBytes*8,p=f.sigBytes*8,g=this.blockSize*32;y[p>>>5]|=1<<24-p%32,y[(e.ceil((p+1)/g)*g>>>5)-1]|=128,f.sigBytes=y.length*4,this._process();for(var x=this._state,b=this.cfg.outputLength/8,A=b/8,I=[],F=0;F<A;F++){var w=x[F],q=w.high,M=w.low;q=(q<<8|q>>>24)&16711935|(q<<24|q>>>8)&4278255360,M=(M<<8|M>>>24)&16711935|(M<<24|M>>>8)&4278255360,I.push(M),I.push(q)}return new n.init(I,b)},clone:function(){for(var f=i.clone.call(this),y=f._state=this._state.slice(0),v=0;v<25;v++)y[v]=y[v].clone();return f}});t.SHA3=i._createHelper(m),t.HmacSHA3=i._createHmacHelper(m)})(Math),h.SHA3})});var ra=re((Pn,ta)=>{(function(h,e){typeof Pn=="object"?ta.exports=Pn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Pn,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),s=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),c=n.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),u=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),l=n.create([0,1518500249,1859775393,2400959708,2840853838]),d=n.create([1352829926,1548603684,1836072691,2053994217,0]),m=a.RIPEMD160=i.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(b,A){for(var I=0;I<16;I++){var F=A+I,w=b[F];b[F]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var q=this._hash.words,M=l.words,E=d.words,L=o.words,Q=s.words,T=c.words,j=u.words,z,B,U,O,_,R,D,Z,te,X;R=z=q[0],D=B=q[1],Z=U=q[2],te=O=q[3],X=_=q[4];for(var Y,I=0;I<80;I+=1)Y=z+b[A+L[I]]|0,I<16?Y+=f(B,U,O)+M[0]:I<32?Y+=y(B,U,O)+M[1]:I<48?Y+=v(B,U,O)+M[2]:I<64?Y+=p(B,U,O)+M[3]:Y+=g(B,U,O)+M[4],Y=Y|0,Y=x(Y,T[I]),Y=Y+_|0,z=_,_=O,O=x(U,10),U=B,B=Y,Y=R+b[A+Q[I]]|0,I<16?Y+=g(D,Z,te)+E[0]:I<32?Y+=p(D,Z,te)+E[1]:I<48?Y+=v(D,Z,te)+E[2]:I<64?Y+=y(D,Z,te)+E[3]:Y+=f(D,Z,te)+E[4],Y=Y|0,Y=x(Y,j[I]),Y=Y+X|0,R=X,X=te,te=x(Z,10),Z=D,D=Y;Y=q[1]+U+te|0,q[1]=q[2]+O+X|0,q[2]=q[3]+_+R|0,q[3]=q[4]+z+D|0,q[4]=q[0]+B+Z|0,q[0]=Y},_doFinalize:function(){var b=this._data,A=b.words,I=this._nDataBytes*8,F=b.sigBytes*8;A[F>>>5]|=128<<24-F%32,A[(F+64>>>9<<4)+14]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360,b.sigBytes=(A.length+1)*4,this._process();for(var w=this._hash,q=w.words,M=0;M<5;M++){var E=q[M];q[M]=(E<<8|E>>>24)&16711935|(E<<24|E>>>8)&4278255360}return w},clone:function(){var b=i.clone.call(this);return b._hash=this._hash.clone(),b}});function f(b,A,I){return b^A^I}function y(b,A,I){return b&A|~b&I}function v(b,A,I){return(b|~A)^I}function p(b,A,I){return b&I|A&~I}function g(b,A,I){return b^(A|~I)}function x(b,A){return b<<A|b>>>32-A}t.RIPEMD160=i._createHelper(m),t.HmacRIPEMD160=i._createHmacHelper(m)})(Math),h.RIPEMD160})});var Rr=re((Cn,na)=>{(function(h,e){typeof Cn=="object"?na.exports=Cn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Cn,function(h){(function(){var e=h,t=e.lib,r=t.Base,n=e.enc,i=n.Utf8,a=e.algo,o=a.HMAC=r.extend({init:function(s,c){s=this._hasher=new s.init,typeof c=="string"&&(c=i.parse(c));var u=s.blockSize,l=u*4;c.sigBytes>l&&(c=s.finalize(c)),c.clamp();for(var d=this._oKey=c.clone(),m=this._iKey=c.clone(),f=d.words,y=m.words,v=0;v<u;v++)f[v]^=1549556828,y[v]^=909522486;d.sigBytes=m.sigBytes=l,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var c=this._hasher,u=c.finalize(s);c.reset();var l=c.finalize(this._oKey.clone().concat(u));return l}})})()})});var aa=re((wn,ia)=>{(function(h,e,t){typeof wn=="object"?ia.exports=wn=e(ae(),Ut(),Rr()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(h.CryptoJS)})(wn,function(h){return(function(){var e=h,t=e.lib,r=t.Base,n=t.WordArray,i=e.algo,a=i.SHA256,o=i.HMAC,s=i.PBKDF2=r.extend({cfg:r.extend({keySize:128/32,hasher:a,iterations:25e4}),init:function(c){this.cfg=this.cfg.extend(c)},compute:function(c,u){for(var l=this.cfg,d=o.create(l.hasher,c),m=n.create(),f=n.create([1]),y=m.words,v=f.words,p=l.keySize,g=l.iterations;y.length<p;){var x=d.update(u).finalize(f);d.reset();for(var b=x.words,A=b.length,I=x,F=1;F<g;F++){I=d.finalize(I),d.reset();for(var w=I.words,q=0;q<A;q++)b[q]^=w[q]}m.concat(x),v[0]++}return m.sigBytes=p*4,m}});e.PBKDF2=function(c,u,l){return s.create(l).compute(c,u)}})(),h.PBKDF2})});var At=re((En,oa)=>{(function(h,e,t){typeof En=="object"?oa.exports=En=e(ae(),pi(),Rr()):typeof define=="function"&&define.amd?define(["./core","./sha1","./hmac"],e):e(h.CryptoJS)})(En,function(h){return(function(){var e=h,t=e.lib,r=t.Base,n=t.WordArray,i=e.algo,a=i.MD5,o=i.EvpKDF=r.extend({cfg:r.extend({keySize:128/32,hasher:a,iterations:1}),init:function(s){this.cfg=this.cfg.extend(s)},compute:function(s,c){for(var u,l=this.cfg,d=l.hasher.create(),m=n.create(),f=m.words,y=l.keySize,v=l.iterations;f.length<y;){u&&d.update(u),u=d.update(s).finalize(c),d.reset();for(var p=1;p<v;p++)u=d.finalize(u),d.reset();m.concat(u)}return m.sigBytes=y*4,m}});e.EvpKDF=function(s,c,u){return o.create(u).compute(s,c)}})(),h.EvpKDF})});var Be=re((On,sa)=>{(function(h,e,t){typeof On=="object"?sa.exports=On=e(ae(),At()):typeof define=="function"&&define.amd?define(["./core","./evpkdf"],e):e(h.CryptoJS)})(On,function(h){h.lib.Cipher||(function(e){var t=h,r=t.lib,n=r.Base,i=r.WordArray,a=r.BufferedBlockAlgorithm,o=t.enc,s=o.Utf8,c=o.Base64,u=t.algo,l=u.EvpKDF,d=r.Cipher=a.extend({cfg:n.extend(),createEncryptor:function(E,L){return this.create(this._ENC_XFORM_MODE,E,L)},createDecryptor:function(E,L){return this.create(this._DEC_XFORM_MODE,E,L)},init:function(E,L,Q){this.cfg=this.cfg.extend(Q),this._xformMode=E,this._key=L,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(E){return this._append(E),this._process()},finalize:function(E){E&&this._append(E);var L=this._doFinalize();return L},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:(function(){function E(L){return typeof L=="string"?M:F}return function(L){return{encrypt:function(Q,T,j){return E(T).encrypt(L,Q,T,j)},decrypt:function(Q,T,j){return E(T).decrypt(L,Q,T,j)}}}})()}),m=r.StreamCipher=d.extend({_doFinalize:function(){var E=this._process(!0);return E},blockSize:1}),f=t.mode={},y=r.BlockCipherMode=n.extend({createEncryptor:function(E,L){return this.Encryptor.create(E,L)},createDecryptor:function(E,L){return this.Decryptor.create(E,L)},init:function(E,L){this._cipher=E,this._iv=L}}),v=f.CBC=(function(){var E=y.extend();E.Encryptor=E.extend({processBlock:function(Q,T){var j=this._cipher,z=j.blockSize;L.call(this,Q,T,z),j.encryptBlock(Q,T),this._prevBlock=Q.slice(T,T+z)}}),E.Decryptor=E.extend({processBlock:function(Q,T){var j=this._cipher,z=j.blockSize,B=Q.slice(T,T+z);j.decryptBlock(Q,T),L.call(this,Q,T,z),this._prevBlock=B}});function L(Q,T,j){var z,B=this._iv;B?(z=B,this._iv=e):z=this._prevBlock;for(var U=0;U<j;U++)Q[T+U]^=z[U]}return E})(),p=t.pad={},g=p.Pkcs7={pad:function(E,L){for(var Q=L*4,T=Q-E.sigBytes%Q,j=T<<24|T<<16|T<<8|T,z=[],B=0;B<T;B+=4)z.push(j);var U=i.create(z,T);E.concat(U)},unpad:function(E){var L=E.words[E.sigBytes-1>>>2]&255;E.sigBytes-=L}},x=r.BlockCipher=d.extend({cfg:d.cfg.extend({mode:v,padding:g}),reset:function(){var E;d.reset.call(this);var L=this.cfg,Q=L.iv,T=L.mode;this._xformMode==this._ENC_XFORM_MODE?E=T.createEncryptor:(E=T.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==E?this._mode.init(this,Q&&Q.words):(this._mode=E.call(T,this,Q&&Q.words),this._mode.__creator=E)},_doProcessBlock:function(E,L){this._mode.processBlock(E,L)},_doFinalize:function(){var E,L=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(L.pad(this._data,this.blockSize),E=this._process(!0)):(E=this._process(!0),L.unpad(E)),E},blockSize:128/32}),b=r.CipherParams=n.extend({init:function(E){this.mixIn(E)},toString:function(E){return(E||this.formatter).stringify(this)}}),A=t.format={},I=A.OpenSSL={stringify:function(E){var L,Q=E.ciphertext,T=E.salt;return T?L=i.create([1398893684,1701076831]).concat(T).concat(Q):L=Q,L.toString(c)},parse:function(E){var L,Q=c.parse(E),T=Q.words;return T[0]==1398893684&&T[1]==1701076831&&(L=i.create(T.slice(2,4)),T.splice(0,4),Q.sigBytes-=16),b.create({ciphertext:Q,salt:L})}},F=r.SerializableCipher=n.extend({cfg:n.extend({format:I}),encrypt:function(E,L,Q,T){T=this.cfg.extend(T);var j=E.createEncryptor(Q,T),z=j.finalize(L),B=j.cfg;return b.create({ciphertext:z,key:Q,iv:B.iv,algorithm:E,mode:B.mode,padding:B.padding,blockSize:E.blockSize,formatter:T.format})},decrypt:function(E,L,Q,T){T=this.cfg.extend(T),L=this._parse(L,T.format);var j=E.createDecryptor(Q,T).finalize(L.ciphertext);return j},_parse:function(E,L){return typeof E=="string"?L.parse(E,this):E}}),w=t.kdf={},q=w.OpenSSL={execute:function(E,L,Q,T,j){if(T||(T=i.random(64/8)),j)var z=l.create({keySize:L+Q,hasher:j}).compute(E,T);else var z=l.create({keySize:L+Q}).compute(E,T);var B=i.create(z.words.slice(L),Q*4);return z.sigBytes=L*4,b.create({key:z,iv:B,salt:T})}},M=r.PasswordBasedCipher=F.extend({cfg:F.cfg.extend({kdf:q}),encrypt:function(E,L,Q,T){T=this.cfg.extend(T);var j=T.kdf.execute(Q,E.keySize,E.ivSize,T.salt,T.hasher);T.iv=j.iv;var z=F.encrypt.call(this,E,L,j.key,T);return z.mixIn(j),z},decrypt:function(E,L,Q,T){T=this.cfg.extend(T),L=this._parse(L,T.format);var j=T.kdf.execute(Q,E.keySize,E.ivSize,L.salt,T.hasher);T.iv=j.iv;var z=F.decrypt.call(this,E,L,j.key,T);return z}})})()})});var ca=re((Rn,ua)=>{(function(h,e,t){typeof Rn=="object"?ua.exports=Rn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Rn,function(h){return h.mode.CFB=(function(){var e=h.lib.BlockCipherMode.extend();e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize;t.call(this,r,n,a,i),this._prevBlock=r.slice(n,n+a)}}),e.Decryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=r.slice(n,n+a);t.call(this,r,n,a,i),this._prevBlock=o}});function t(r,n,i,a){var o,s=this._iv;s?(o=s.slice(0),this._iv=void 0):o=this._prevBlock,a.encryptBlock(o,0);for(var c=0;c<i;c++)r[n+c]^=o[c]}return e})(),h.mode.CFB})});var la=re((_n,da)=>{(function(h,e,t){typeof _n=="object"?da.exports=_n=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(_n,function(h){return h.mode.CTR=(function(){var e=h.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=this._iv,s=this._counter;o&&(s=this._counter=o.slice(0),this._iv=void 0);var c=s.slice(0);i.encryptBlock(c,0),s[a-1]=s[a-1]+1|0;for(var u=0;u<a;u++)r[n+u]^=c[u]}});return e.Decryptor=t,e})(),h.mode.CTR})});var ma=re((Tn,pa)=>{(function(h,e,t){typeof Tn=="object"?pa.exports=Tn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Tn,function(h){return h.mode.CTRGladman=(function(){var e=h.lib.BlockCipherMode.extend();function t(i){if((i>>24&255)===255){var a=i>>16&255,o=i>>8&255,s=i&255;a===255?(a=0,o===255?(o=0,s===255?s=0:++s):++o):++a,i=0,i+=a<<16,i+=o<<8,i+=s}else i+=1<<24;return i}function r(i){return(i[0]=t(i[0]))===0&&(i[1]=t(i[1])),i}var n=e.Encryptor=e.extend({processBlock:function(i,a){var o=this._cipher,s=o.blockSize,c=this._iv,u=this._counter;c&&(u=this._counter=c.slice(0),this._iv=void 0),r(u);var l=u.slice(0);o.encryptBlock(l,0);for(var d=0;d<s;d++)i[a+d]^=l[d]}});return e.Decryptor=n,e})(),h.mode.CTRGladman})});var fa=re((Bn,ha)=>{(function(h,e,t){typeof Bn=="object"?ha.exports=Bn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Bn,function(h){return h.mode.OFB=(function(){var e=h.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=this._iv,s=this._keystream;o&&(s=this._keystream=o.slice(0),this._iv=void 0),i.encryptBlock(s,0);for(var c=0;c<a;c++)r[n+c]^=s[c]}});return e.Decryptor=t,e})(),h.mode.OFB})});var ya=re((kn,ga)=>{(function(h,e,t){typeof kn=="object"?ga.exports=kn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(kn,function(h){return h.mode.ECB=(function(){var e=h.lib.BlockCipherMode.extend();return e.Encryptor=e.extend({processBlock:function(t,r){this._cipher.encryptBlock(t,r)}}),e.Decryptor=e.extend({processBlock:function(t,r){this._cipher.decryptBlock(t,r)}}),e})(),h.mode.ECB})});var ba=re((Fn,va)=>{(function(h,e,t){typeof Fn=="object"?va.exports=Fn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Fn,function(h){return h.pad.AnsiX923={pad:function(e,t){var r=e.sigBytes,n=t*4,i=n-r%n,a=r+i-1;e.clamp(),e.words[a>>>2]|=i<<24-a%4*8,e.sigBytes+=i},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},h.pad.Ansix923})});var Aa=re((Mn,xa)=>{(function(h,e,t){typeof Mn=="object"?xa.exports=Mn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Mn,function(h){return h.pad.Iso10126={pad:function(e,t){var r=t*4,n=r-e.sigBytes%r;e.concat(h.lib.WordArray.random(n-1)).concat(h.lib.WordArray.create([n<<24],1))},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},h.pad.Iso10126})});var Ia=re((qn,Sa)=>{(function(h,e,t){typeof qn=="object"?Sa.exports=qn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(qn,function(h){return h.pad.Iso97971={pad:function(e,t){e.concat(h.lib.WordArray.create([2147483648],1)),h.pad.ZeroPadding.pad(e,t)},unpad:function(e){h.pad.ZeroPadding.unpad(e),e.sigBytes--}},h.pad.Iso97971})});var Pa=re((Ln,Da)=>{(function(h,e,t){typeof Ln=="object"?Da.exports=Ln=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Ln,function(h){return h.pad.ZeroPadding={pad:function(e,t){var r=t*4;e.clamp(),e.sigBytes+=r-(e.sigBytes%r||r)},unpad:function(e){for(var t=e.words,r=e.sigBytes-1,r=e.sigBytes-1;r>=0;r--)if(t[r>>>2]>>>24-r%4*8&255){e.sigBytes=r+1;break}}},h.pad.ZeroPadding})});var wa=re((Nn,Ca)=>{(function(h,e,t){typeof Nn=="object"?Ca.exports=Nn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Nn,function(h){return h.pad.NoPadding={pad:function(){},unpad:function(){}},h.pad.NoPadding})});var Oa=re((Qn,Ea)=>{(function(h,e,t){typeof Qn=="object"?Ea.exports=Qn=e(ae(),Be()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(Qn,function(h){return(function(e){var t=h,r=t.lib,n=r.CipherParams,i=t.enc,a=i.Hex,o=t.format,s=o.Hex={stringify:function(c){return c.ciphertext.toString(a)},parse:function(c){var u=a.parse(c);return n.create({ciphertext:u})}}})(),h.format.Hex})});var _a=re((Un,Ra)=>{(function(h,e,t){typeof Un=="object"?Ra.exports=Un=e(ae(),Pt(),Ct(),At(),Be()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(Un,function(h){return(function(){var e=h,t=e.lib,r=t.BlockCipher,n=e.algo,i=[],a=[],o=[],s=[],c=[],u=[],l=[],d=[],m=[],f=[];(function(){for(var p=[],g=0;g<256;g++)g<128?p[g]=g<<1:p[g]=g<<1^283;for(var x=0,b=0,g=0;g<256;g++){var A=b^b<<1^b<<2^b<<3^b<<4;A=A>>>8^A&255^99,i[x]=A,a[A]=x;var I=p[x],F=p[I],w=p[F],q=p[A]*257^A*16843008;o[x]=q<<24|q>>>8,s[x]=q<<16|q>>>16,c[x]=q<<8|q>>>24,u[x]=q;var q=w*16843009^F*65537^I*257^x*16843008;l[A]=q<<24|q>>>8,d[A]=q<<16|q>>>16,m[A]=q<<8|q>>>24,f[A]=q,x?(x=I^p[p[p[w^I]]],b^=p[p[b]]):x=b=1}})();var y=[0,1,2,4,8,16,32,64,128,27,54],v=n.AES=r.extend({_doReset:function(){var p;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var g=this._keyPriorReset=this._key,x=g.words,b=g.sigBytes/4,A=this._nRounds=b+6,I=(A+1)*4,F=this._keySchedule=[],w=0;w<I;w++)w<b?F[w]=x[w]:(p=F[w-1],w%b?b>6&&w%b==4&&(p=i[p>>>24]<<24|i[p>>>16&255]<<16|i[p>>>8&255]<<8|i[p&255]):(p=p<<8|p>>>24,p=i[p>>>24]<<24|i[p>>>16&255]<<16|i[p>>>8&255]<<8|i[p&255],p^=y[w/b|0]<<24),F[w]=F[w-b]^p);for(var q=this._invKeySchedule=[],M=0;M<I;M++){var w=I-M;if(M%4)var p=F[w];else var p=F[w-4];M<4||w<=4?q[M]=p:q[M]=l[i[p>>>24]]^d[i[p>>>16&255]]^m[i[p>>>8&255]]^f[i[p&255]]}}},encryptBlock:function(p,g){this._doCryptBlock(p,g,this._keySchedule,o,s,c,u,i)},decryptBlock:function(p,g){var x=p[g+1];p[g+1]=p[g+3],p[g+3]=x,this._doCryptBlock(p,g,this._invKeySchedule,l,d,m,f,a);var x=p[g+1];p[g+1]=p[g+3],p[g+3]=x},_doCryptBlock:function(p,g,x,b,A,I,F,w){for(var q=this._nRounds,M=p[g]^x[0],E=p[g+1]^x[1],L=p[g+2]^x[2],Q=p[g+3]^x[3],T=4,j=1;j<q;j++){var z=b[M>>>24]^A[E>>>16&255]^I[L>>>8&255]^F[Q&255]^x[T++],B=b[E>>>24]^A[L>>>16&255]^I[Q>>>8&255]^F[M&255]^x[T++],U=b[L>>>24]^A[Q>>>16&255]^I[M>>>8&255]^F[E&255]^x[T++],O=b[Q>>>24]^A[M>>>16&255]^I[E>>>8&255]^F[L&255]^x[T++];M=z,E=B,L=U,Q=O}var z=(w[M>>>24]<<24|w[E>>>16&255]<<16|w[L>>>8&255]<<8|w[Q&255])^x[T++],B=(w[E>>>24]<<24|w[L>>>16&255]<<16|w[Q>>>8&255]<<8|w[M&255])^x[T++],U=(w[L>>>24]<<24|w[Q>>>16&255]<<16|w[M>>>8&255]<<8|w[E&255])^x[T++],O=(w[Q>>>24]<<24|w[M>>>16&255]<<16|w[E>>>8&255]<<8|w[L&255])^x[T++];p[g]=z,p[g+1]=B,p[g+2]=U,p[g+3]=O},keySize:256/32});e.AES=r._createHelper(v)})(),h.AES})});var Ba=re((Hn,Ta)=>{(function(h,e,t){typeof Hn=="object"?Ta.exports=Hn=e(ae(),Pt(),Ct(),At(),Be()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(Hn,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=t.BlockCipher,i=e.algo,a=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],s=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],c=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],u=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],l=i.DES=n.extend({_doReset:function(){for(var y=this._key,v=y.words,p=[],g=0;g<56;g++){var x=a[g]-1;p[g]=v[x>>>5]>>>31-x%32&1}for(var b=this._subKeys=[],A=0;A<16;A++){for(var I=b[A]=[],F=s[A],g=0;g<24;g++)I[g/6|0]|=p[(o[g]-1+F)%28]<<31-g%6,I[4+(g/6|0)]|=p[28+(o[g+24]-1+F)%28]<<31-g%6;I[0]=I[0]<<1|I[0]>>>31;for(var g=1;g<7;g++)I[g]=I[g]>>>(g-1)*4+3;I[7]=I[7]<<5|I[7]>>>27}for(var w=this._invSubKeys=[],g=0;g<16;g++)w[g]=b[15-g]},encryptBlock:function(y,v){this._doCryptBlock(y,v,this._subKeys)},decryptBlock:function(y,v){this._doCryptBlock(y,v,this._invSubKeys)},_doCryptBlock:function(y,v,p){this._lBlock=y[v],this._rBlock=y[v+1],d.call(this,4,252645135),d.call(this,16,65535),m.call(this,2,858993459),m.call(this,8,16711935),d.call(this,1,1431655765);for(var g=0;g<16;g++){for(var x=p[g],b=this._lBlock,A=this._rBlock,I=0,F=0;F<8;F++)I|=c[F][((A^x[F])&u[F])>>>0];this._lBlock=A,this._rBlock=b^I}var w=this._lBlock;this._lBlock=this._rBlock,this._rBlock=w,d.call(this,1,1431655765),m.call(this,8,16711935),m.call(this,2,858993459),d.call(this,16,65535),d.call(this,4,252645135),y[v]=this._lBlock,y[v+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function d(y,v){var p=(this._lBlock>>>y^this._rBlock)&v;this._rBlock^=p,this._lBlock^=p<<y}function m(y,v){var p=(this._rBlock>>>y^this._lBlock)&v;this._lBlock^=p,this._rBlock^=p<<y}e.DES=n._createHelper(l);var f=i.TripleDES=n.extend({_doReset:function(){var y=this._key,v=y.words;if(v.length!==2&&v.length!==4&&v.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var p=v.slice(0,2),g=v.length<4?v.slice(0,2):v.slice(2,4),x=v.length<6?v.slice(0,2):v.slice(4,6);this._des1=l.createEncryptor(r.create(p)),this._des2=l.createEncryptor(r.create(g)),this._des3=l.createEncryptor(r.create(x))},encryptBlock:function(y,v){this._des1.encryptBlock(y,v),this._des2.decryptBlock(y,v),this._des3.encryptBlock(y,v)},decryptBlock:function(y,v){this._des3.decryptBlock(y,v),this._des2.encryptBlock(y,v),this._des1.decryptBlock(y,v)},keySize:192/32,ivSize:64/32,blockSize:64/32});e.TripleDES=n._createHelper(f)})(),h.TripleDES})});var Fa=re(($n,ka)=>{(function(h,e,t){typeof $n=="object"?ka.exports=$n=e(ae(),Pt(),Ct(),At(),Be()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})($n,function(h){return(function(){var e=h,t=e.lib,r=t.StreamCipher,n=e.algo,i=n.RC4=r.extend({_doReset:function(){for(var s=this._key,c=s.words,u=s.sigBytes,l=this._S=[],d=0;d<256;d++)l[d]=d;for(var d=0,m=0;d<256;d++){var f=d%u,y=c[f>>>2]>>>24-f%4*8&255;m=(m+l[d]+y)%256;var v=l[d];l[d]=l[m],l[m]=v}this._i=this._j=0},_doProcessBlock:function(s,c){s[c]^=a.call(this)},keySize:256/32,ivSize:0});function a(){for(var s=this._S,c=this._i,u=this._j,l=0,d=0;d<4;d++){c=(c+1)%256,u=(u+s[c])%256;var m=s[c];s[c]=s[u],s[u]=m,l|=s[(s[c]+s[u])%256]<<24-d*8}return this._i=c,this._j=u,l}e.RC4=r._createHelper(i);var o=n.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var s=this.cfg.drop;s>0;s--)a.call(this)}});e.RC4Drop=r._createHelper(o)})(),h.RC4})});var qa=re((Vn,Ma)=>{(function(h,e,t){typeof Vn=="object"?Ma.exports=Vn=e(ae(),Pt(),Ct(),At(),Be()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(Vn,function(h){return(function(){var e=h,t=e.lib,r=t.StreamCipher,n=e.algo,i=[],a=[],o=[],s=n.Rabbit=r.extend({_doReset:function(){for(var u=this._key.words,l=this.cfg.iv,d=0;d<4;d++)u[d]=(u[d]<<8|u[d]>>>24)&16711935|(u[d]<<24|u[d]>>>8)&4278255360;var m=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],f=this._C=[u[2]<<16|u[2]>>>16,u[0]&4294901760|u[1]&65535,u[3]<<16|u[3]>>>16,u[1]&4294901760|u[2]&65535,u[0]<<16|u[0]>>>16,u[2]&4294901760|u[3]&65535,u[1]<<16|u[1]>>>16,u[3]&4294901760|u[0]&65535];this._b=0;for(var d=0;d<4;d++)c.call(this);for(var d=0;d<8;d++)f[d]^=m[d+4&7];if(l){var y=l.words,v=y[0],p=y[1],g=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,x=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,b=g>>>16|x&4294901760,A=x<<16|g&65535;f[0]^=g,f[1]^=b,f[2]^=x,f[3]^=A,f[4]^=g,f[5]^=b,f[6]^=x,f[7]^=A;for(var d=0;d<4;d++)c.call(this)}},_doProcessBlock:function(u,l){var d=this._X;c.call(this),i[0]=d[0]^d[5]>>>16^d[3]<<16,i[1]=d[2]^d[7]>>>16^d[5]<<16,i[2]=d[4]^d[1]>>>16^d[7]<<16,i[3]=d[6]^d[3]>>>16^d[1]<<16;for(var m=0;m<4;m++)i[m]=(i[m]<<8|i[m]>>>24)&16711935|(i[m]<<24|i[m]>>>8)&4278255360,u[l+m]^=i[m]},blockSize:128/32,ivSize:64/32});function c(){for(var u=this._X,l=this._C,d=0;d<8;d++)a[d]=l[d];l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0;for(var d=0;d<8;d++){var m=u[d]+l[d],f=m&65535,y=m>>>16,v=((f*f>>>17)+f*y>>>15)+y*y,p=((m&4294901760)*m|0)+((m&65535)*m|0);o[d]=v^p}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.Rabbit=r._createHelper(s)})(),h.Rabbit})});var Na=re((zn,La)=>{(function(h,e,t){typeof zn=="object"?La.exports=zn=e(ae(),Pt(),Ct(),At(),Be()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(zn,function(h){return(function(){var e=h,t=e.lib,r=t.StreamCipher,n=e.algo,i=[],a=[],o=[],s=n.RabbitLegacy=r.extend({_doReset:function(){var u=this._key.words,l=this.cfg.iv,d=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],m=this._C=[u[2]<<16|u[2]>>>16,u[0]&4294901760|u[1]&65535,u[3]<<16|u[3]>>>16,u[1]&4294901760|u[2]&65535,u[0]<<16|u[0]>>>16,u[2]&4294901760|u[3]&65535,u[1]<<16|u[1]>>>16,u[3]&4294901760|u[0]&65535];this._b=0;for(var f=0;f<4;f++)c.call(this);for(var f=0;f<8;f++)m[f]^=d[f+4&7];if(l){var y=l.words,v=y[0],p=y[1],g=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,x=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,b=g>>>16|x&4294901760,A=x<<16|g&65535;m[0]^=g,m[1]^=b,m[2]^=x,m[3]^=A,m[4]^=g,m[5]^=b,m[6]^=x,m[7]^=A;for(var f=0;f<4;f++)c.call(this)}},_doProcessBlock:function(u,l){var d=this._X;c.call(this),i[0]=d[0]^d[5]>>>16^d[3]<<16,i[1]=d[2]^d[7]>>>16^d[5]<<16,i[2]=d[4]^d[1]>>>16^d[7]<<16,i[3]=d[6]^d[3]>>>16^d[1]<<16;for(var m=0;m<4;m++)i[m]=(i[m]<<8|i[m]>>>24)&16711935|(i[m]<<24|i[m]>>>8)&4278255360,u[l+m]^=i[m]},blockSize:128/32,ivSize:64/32});function c(){for(var u=this._X,l=this._C,d=0;d<8;d++)a[d]=l[d];l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0;for(var d=0;d<8;d++){var m=u[d]+l[d],f=m&65535,y=m>>>16,v=((f*f>>>17)+f*y>>>15)+y*y,p=((m&4294901760)*m|0)+((m&65535)*m|0);o[d]=v^p}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.RabbitLegacy=r._createHelper(s)})(),h.RabbitLegacy})});var Ua=re((jn,Qa)=>{(function(h,e,t){typeof jn=="object"?Qa.exports=jn=e(ae(),Pt(),Ct(),At(),Be()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(jn,function(h){return(function(){var e=h,t=e.lib,r=t.BlockCipher,n=e.algo;let i=16,a=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],o=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var s={pbox:[],sbox:[]};function c(f,y){let v=y>>24&255,p=y>>16&255,g=y>>8&255,x=y&255,b=f.sbox[0][v]+f.sbox[1][p];return b=b^f.sbox[2][g],b=b+f.sbox[3][x],b}function u(f,y,v){let p=y,g=v,x;for(let b=0;b<i;++b)p=p^f.pbox[b],g=c(f,p)^g,x=p,p=g,g=x;return x=p,p=g,g=x,g=g^f.pbox[i],p=p^f.pbox[i+1],{left:p,right:g}}function l(f,y,v){let p=y,g=v,x;for(let b=i+1;b>1;--b)p=p^f.pbox[b],g=c(f,p)^g,x=p,p=g,g=x;return x=p,p=g,g=x,g=g^f.pbox[1],p=p^f.pbox[0],{left:p,right:g}}function d(f,y,v){for(let A=0;A<4;A++){f.sbox[A]=[];for(let I=0;I<256;I++)f.sbox[A][I]=o[A][I]}let p=0;for(let A=0;A<i+2;A++)f.pbox[A]=a[A]^y[p],p++,p>=v&&(p=0);let g=0,x=0,b=0;for(let A=0;A<i+2;A+=2)b=u(f,g,x),g=b.left,x=b.right,f.pbox[A]=g,f.pbox[A+1]=x;for(let A=0;A<4;A++)for(let I=0;I<256;I+=2)b=u(f,g,x),g=b.left,x=b.right,f.sbox[A][I]=g,f.sbox[A][I+1]=x;return!0}var m=n.Blowfish=r.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,y=f.words,v=f.sigBytes/4;d(s,y,v)}},encryptBlock:function(f,y){var v=u(s,f[y],f[y+1]);f[y]=v.left,f[y+1]=v.right},decryptBlock:function(f,y){var v=l(s,f[y],f[y+1]);f[y]=v.left,f[y+1]=v.right},blockSize:64/32,keySize:128/32,ivSize:64/32});e.Blowfish=r._createHelper(m)})(),h.Blowfish})});var hi=re((Kn,Ha)=>{(function(h,e,t){typeof Kn=="object"?Ha.exports=Kn=e(ae(),Or(),Ni(),Ui(),Pt(),Vi(),Ct(),pi(),Ut(),Wi(),mi(),Zi(),ea(),ra(),Rr(),aa(),At(),Be(),ca(),la(),ma(),fa(),ya(),ba(),Aa(),Ia(),Pa(),wa(),Oa(),_a(),Ba(),Fa(),qa(),Na(),Ua()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./enc-base64url","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy","./blowfish"],e):h.CryptoJS=e(h.CryptoJS)})(Kn,function(h){return h})});var Wa=re((ei,Ga)=>{(function(h,e,t){typeof ei=="object"?Ga.exports=ei=e(ae(),Ut(),Rr()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(h.CryptoJS)})(ei,function(h){return h.HmacSHA256})});var Xa=re((ti,Ya)=>{(function(h,e){typeof ti=="object"?Ya.exports=ti=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(ti,function(h){return h.enc.Hex})});var wo={};lo(wo,{ActivityLogger:()=>Cr,AdapterRegistry:()=>Qr,ApiService:()=>kr,AuthorizationService:()=>Er,BackupScheduler:()=>qr,CONFLICT_POLICY_MATRIX:()=>$a,CURRENT_SYNC_PROTOCOL_VERSION:()=>sn,CartService:()=>Sr,CartStore:()=>Ar,CategoryService:()=>$t,ConfigService:()=>Mr,ConsoleLoggerAdapter:()=>Hr.ConsoleLoggerAdapter,CustomerGroupService:()=>zt,CustomerService:()=>Vt,DEFAULT_GRANULAR_AUTH_POLICY:()=>li,DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS:()=>un,DefaultExportAdapter:()=>Ur.DefaultExportAdapter,DefaultHttpAdapter:()=>Br.DefaultHttpAdapter,DefaultPlatformAdapter:()=>eo.DefaultPlatformAdapter,DomainServices:()=>Dr,EncryptionService:()=>_r,ExpenseService:()=>lr,ExponentialBackoffHttpPolicy:()=>mt.ExponentialBackoffHttpPolicy,ExportService:()=>yr,FinancialSettingService:()=>dr,HistoryService:()=>jt,InMemoryDbAdapter:()=>no.InMemoryDbAdapter,InMemorySocketAdapter:()=>Vr.InMemorySocketAdapter,IntegrationServices:()=>Lr,InventoryLogService:()=>ar,InventoryService:()=>fr,MemoryActivitySink:()=>Ft.MemoryActivitySink,MemoryStorage:()=>yt,NoRetryHttpPolicy:()=>mt.NoRetryHttpPolicy,NoopActivitySink:()=>Ft.NoopActivitySink,NoopChecksumAdapter:()=>Xn.NoopChecksumAdapter,NoopEncryptionAdapter:()=>Yn.NoopEncryptionAdapter,NoopNotificationAdapter:()=>$r.NoopNotificationAdapter,NoopSocketService:()=>Bt,NoopSyncService:()=>Tt,NotificationService:()=>Fr,OrderService:()=>Kt,POS_DOMAIN_TABLES:()=>xo,PayableService:()=>mr,PosCore:()=>kt,PriceHistoryService:()=>or,PriceTierService:()=>Gt,PricingService:()=>vr,ProductService:()=>Wt,PromotionService:()=>Yt,PurchaseOrderService:()=>nr,PurchaseService:()=>ir,ReceivableService:()=>pr,ReportScheduleService:()=>cr,ReportingService:()=>xr,ReturnService:()=>Xt,RoleAdapter:()=>wr,SaleService:()=>Zt,SessionStore:()=>Nr,SettlementService:()=>hr,ShiftService:()=>Jt,SocketService:()=>gi,StockAdjustmentService:()=>ur,StockOpnameService:()=>sr,SupplierService:()=>rr,SyncService:()=>fi,SyncStore:()=>Pr,TASK_ID:()=>za,TaxService:()=>Ir,TransactionService:()=>er,UIProductService:()=>Ii,UITransactionService:()=>Di,UomService:()=>tr,UserService:()=>Tr,applyPendingMigrations:()=>vi,bomTable:()=>Fe,categoryTable:()=>et,computeChecksum:()=>gr,createChangeQueuePort:()=>H,customerGroupTable:()=>tt,customerTable:()=>je,eventBus:()=>Le,executeHttpRequestWithRetry:()=>mt.executeHttpRequestWithRetry,expenseTable:()=>ot,financialSettingTable:()=>ze,getSyncProtocolContract:()=>Ao,historyTable:()=>ie,initialSessionState:()=>ja,initialState:()=>Dt,inventoryLogTable:()=>Oe,isContractVersionCompatible:()=>ro.isContractVersionCompatible,isFailureEnvelope:()=>to.isFailureEnvelope,isServerProtocolCompatible:()=>ui,kitchenTicketItemTable:()=>si,kitchenTicketTable:()=>Yr,loyaltyAccountTable:()=>Rt,loyaltyLedgerTable:()=>gt,migrations:()=>yi,orderItemTable:()=>xe,orderTable:()=>oe,payableTable:()=>ge,priceHistoryTable:()=>Ge,priceTierTable:()=>He,productTable:()=>ce,projectScopedPosSaleFinance:()=>Co,promotionTable:()=>rt,purchaseItemTable:()=>De,purchaseOrderItemTable:()=>Ve,purchaseOrderTable:()=>_e,purchaseTable:()=>Se,receivableTable:()=>he,reportScheduleTable:()=>at,returnItemTable:()=>Re,returnTable:()=>Ae,roleTable:()=>Pe,saleItemTable:()=>fe,saleTable:()=>ue,schemas:()=>xt,settlementTable:()=>Qe,shiftTable:()=>le,stockAdjustmentTable:()=>it,stockOpnameItemTable:()=>Me,stockOpnameTable:()=>Ce,supplierTable:()=>Ke,taxRateTable:()=>Ee,transactionTable:()=>J,uomTable:()=>nt,userTable:()=>$e});var Wg=Mt(Ei());var Ka=we("ofcore"),Wn=we("ofcore");var Kr="0123456789abcdef",Gr=class h{constructor(e){this.bytes=e}static ofInner(e){if(e.length!==16)throw new TypeError("not 128-bit length");return new h(e)}static fromFieldsV7(e,t,r,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||t<0||r<0||n<0||e>0xffffffffffff||t>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/2**8,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new h(i)}static parse(e){var t,r,n,i;let a;switch(e.length){case 32:a=(t=/^[0-9a-f]{32}$/i.exec(e))===null||t===void 0?void 0:t[0];break;case 36:a=(r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||r===void 0?void 0:r.slice(1,6).join("");break;case 38:a=(n=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e))===null||n===void 0?void 0:n.slice(1,6).join("");break;case 45:a=(i=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||i===void 0?void 0:i.slice(1,6).join("");break;default:break}if(a){let o=new Uint8Array(16);for(let s=0;s<16;s+=4){let c=parseInt(a.substring(2*s,2*s+8),16);o[s+0]=c>>>24,o[s+1]=c>>>16,o[s+2]=c>>>8,o[s+3]=c}return new h(o)}else throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Kr.charAt(this.bytes[t]>>>4),e+=Kr.charAt(this.bytes[t]&15),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Kr.charAt(this.bytes[t]>>>4),e+=Kr.charAt(this.bytes[t]&15);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new h(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}},ii=class{constructor(e){this.timestamp_biased=0,this.counter=0,this.random=e!=null?e:mo()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return r===void 0&&(this.timestamp_biased=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<0||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit unsigned integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e++,e>this.timestamp_biased)this.timestamp_biased=e,this.resetCounter();else if(e+t>=this.timestamp_biased)this.counter++,this.counter>4398046511103&&(this.timestamp_biased++,this.resetCounter());else return;return Gr.fromFieldsV7(this.timestamp_biased-1,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Gr.ofInner(e)}},mo=()=>{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues!="undefined")return new ai;if(typeof UUIDV7_DENY_WEAK_RNG!="undefined"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");return{nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}},ai=class{constructor(){this.buffer=new Uint32Array(8),this.cursor=65535}nextUint32(){return this.cursor>=this.buffer.length&&(crypto.getRandomValues(this.buffer),this.cursor=0),this.buffer[this.cursor++]}},Oi;var P=()=>ho().toString(),ho=()=>(Oi||(Oi=new ii)).generateV4();var oi=class{constructor(e){this.context=e}enqueue(e){this.context.enqueueDomainChange(e)}};function H(h){return new oi(h)}var Fe="boms";var Wr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addBom(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Fe,i);return this.changeQueue.enqueue({type:"create",model:Fe,record:a}),this.context.logActivity("AddBom",{id:r}),a}async updateBom(e,t,r){let n=await(r||this.dbAdapter).get(Fe,e);if(!n)throw new Error(`Bom with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Fe,e,a);return this.changeQueue.enqueue({type:"update",model:Fe,record:o}),this.context.logActivity("UpdateBom",{id:e}),o}async getBoms(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Fe,{...e,filters:i})}async getBom(e,t){return(t||this.dbAdapter).get(Fe,e)}async deleteBom(e,t){return await(t||this.dbAdapter).delete(Fe,e),this.changeQueue.enqueue({type:"delete",model:Fe,record:{id:e}}),this.context.logActivity("DeleteBom",{id:e}),{id:e,queued:!0}}async duplicateBom(e,t){let r=await this.getBom(e,t);if(!r)throw new Error(`Bom with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Fe,a);return this.changeQueue.enqueue({type:"create",model:Fe,record:a}),this.context.logActivity("DuplicateBom",{originalId:e,newId:n}),o}async getBomsByParentItemId(e,t){let r=t||this.dbAdapter,n={and:[{parentItemId:e},{deleted:!1}]};return r.query(Fe,{filters:n})}async getBomsByComponentItemId(e,t){let r=t||this.dbAdapter,n={and:[{componentItemId:e},{deleted:!1}]};return r.query(Fe,{filters:n})}async getBomsByProductId(e,t){return this.dbAdapter.query(Fe,{filters:{or:[{and:[{field:"parentItemId",value:e},{field:"deleted",value:!1}]},{and:[{field:"componentItemId",value:e},{field:"deleted",value:!1}]}]}})}async expandBom(e){let t=new Map,r=async(n,i)=>{let a=await this.dbAdapter.query(Fe,{filters:{parentItemId:n,deleted:!1}});for(let o of a){let s=o.quantity*i;if((await this.dbAdapter.query(Fe,{filters:{parentItemId:o.componentItemId,deleted:!1}})).length>0)await r(o.componentItemId,s);else{let u=t.get(o.componentItemId);u?u.quantity+=s:t.set(o.componentItemId,{componentItemId:o.componentItemId,quantity:s,uomId:o.uomId})}}};return await r(e,1),Array.from(t.values())}};var et="categories";var $t=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addCategory(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(et,i);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("AddCategory",{id:r}),a}async updateCategory(e,t,r){let n=await(r||this.dbAdapter).get(et,e);if(!n)throw new Error(`Category with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(et,e,a);return this.changeQueue.enqueue({type:"update",model:et,record:o}),this.context.logActivity("UpdateCategory",{id:e}),o}async getCategories(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(et,{...e,filters:i})}async getCategory(e,t){return(t||this.dbAdapter).get(et,e)}async deleteCategory(e,t){return await(t||this.dbAdapter).delete(et,e),this.changeQueue.enqueue({type:"delete",model:et,record:{id:e}}),this.context.logActivity("DeleteCategory",{id:e}),{id:e,queued:!0}}async duplicateCategory(e,t){let r=await this.getCategory(e,t);if(!r)throw new Error(`Category with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(et,a);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("DuplicateCategory",{originalId:e,newId:n}),o}async fetchNestedCategories(){let e=await this.getCategories(),t={};e.forEach(n=>{t[n.id]={...n,children:[]}});let r=[];return e.forEach(n=>{var a;let i=(a=n.parentId)!=null?a:null;i&&t[i]?t[i].children.push(t[n.id]):r.push(t[n.id])}),r}};var je="customers";var Rt="loyalty_accounts";var gt="loyalty_ledgers";var Vt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}async getOrCreateLoyaltyAccount(e,t){let r=await e.query(Rt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]},limit:1});if(r.length>0)return r[0];let n=new Date().toISOString();return e.create(Rt,{id:P(),customerId:t,pointsBalance:0,totalEarned:0,totalRedeemed:0,totalExpired:0,version:Date.now(),lastModified:n,deleted:!1})}async addCustomer(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(je,i);return this.changeQueue.enqueue({type:"create",model:je,record:a}),this.context.logActivity("AddCustomer",{id:r}),a}async updateCustomer(e,t,r){let n=await(r||this.dbAdapter).get(je,e);if(!n)throw new Error(`Customer with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(je,e,a);return this.changeQueue.enqueue({type:"update",model:je,record:o}),this.context.logActivity("UpdateCustomer",{id:e}),o}async getCustomers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(je,{...e,filters:i})}async getCustomer(e,t){return(t||this.dbAdapter).get(je,e)}async deleteCustomer(e,t){return await(t||this.dbAdapter).delete(je,e),this.changeQueue.enqueue({type:"delete",model:je,record:{id:e}}),this.context.logActivity("DeleteCustomer",{id:e}),{id:e,queued:!0}}async duplicateCustomer(e,t){let r=await this.getCustomer(e,t);if(!r)throw new Error(`Customer with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(je,a);return this.changeQueue.enqueue({type:"create",model:je,record:a}),this.context.logActivity("DuplicateCustomer",{originalId:e,newId:n}),o}async searchCustomers(e,t,r){let n=e.trim();if(!n)return[];let i=r||this.dbAdapter,a={and:[{or:[{field:"name",operator:"like",value:`%${n}%`},{field:"phone",operator:"like",value:`%${n}%`},{field:"email",operator:"like",value:`%${n}%`}]},{deleted:!1}]};return i.query(je,{...t,filters:a})}async earnLoyaltyPoints(e){let t=String(e.customerId||"").trim(),r=String(e.referenceType||"").trim(),n=String(e.referenceId||"").trim();if(!t)throw new Error("Loyalty: customerId is required");if(!r||!n)throw new Error("Loyalty: referenceType/referenceId are required");if(!Number.isFinite(e.baseAmount)||e.baseAmount<=0)throw new Error("Loyalty: baseAmount must be > 0");if(!Number.isFinite(e.earnRate)||e.earnRate<=0)throw new Error("Loyalty: earnRate must be > 0");return this.runInTransaction(async i=>{let a=e.date||new Date().toISOString(),o=await i.query(gt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"entryType",operator:"=",value:"earn"},{field:"referenceType",operator:"=",value:r},{field:"referenceId",operator:"=",value:n},{field:"deleted",operator:"=",value:!1}]},limit:1});if(o.length>0){let l=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:Number(o[0].points||0),balance:Number(l.pointsBalance||0)}}let s=Math.floor(e.baseAmount*e.earnRate);if(s<=0){let l=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:0,balance:Number(l.pointsBalance||0)}}await i.create(gt,{id:P(),customerId:t,entryType:"earn",points:s,availablePoints:s,expiresAt:e.expiresAt||null,consumedAt:null,referenceType:r,referenceId:n,note:e.note||null,date:a,version:Date.now(),lastModified:a,deleted:!1});let c=await this.getOrCreateLoyaltyAccount(i,t),u=await i.update(Rt,c.id,{pointsBalance:Number(c.pointsBalance||0)+s,totalEarned:Number(c.totalEarned||0)+s,version:Date.now(),lastModified:a});return this.context.logActivity("LoyaltyEarnPoints",{customerId:t,referenceType:r,referenceId:n,earnedPoints:s}),{earnedPoints:s,balance:Number(u.pointsBalance||0)}})}async redeemLoyaltyPoints(e){let t=String(e.customerId||"").trim(),r=String(e.referenceType||"").trim(),n=String(e.referenceId||"").trim();if(!t)throw new Error("Loyalty: customerId is required");if(!r||!n)throw new Error("Loyalty: referenceType/referenceId are required");if(!Number.isInteger(e.points)||e.points<=0)throw new Error("Loyalty: redeem points must be positive integer");return this.runInTransaction(async i=>{let a=e.date||new Date().toISOString(),o=await this.getOrCreateLoyaltyAccount(i,t),s=Number(o.pointsBalance||0);if(s<e.points)throw new Error(`Loyalty: insufficient points, required=${e.points}, available=${s}`);let c=await i.query(gt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"entryType",operator:"=",value:"earn"},{field:"deleted",operator:"=",value:!1},{field:"availablePoints",operator:">",value:0}]},sort:[{field:"expiresAt",direction:"asc"},{field:"date",direction:"asc"}]}),u=e.points;for(let d of c){if(u<=0)break;let m=Number(d.availablePoints||0);if(m<=0)continue;let f=Math.min(m,u),y=m-f;await i.update(gt,d.id,{availablePoints:y,consumedAt:y===0?a:d.consumedAt,version:Date.now(),lastModified:a}),u-=f}if(u>0)throw new Error(`Loyalty: redeem allocation failed, remaining=${u}`);await i.create(gt,{id:P(),customerId:t,entryType:"redeem",points:e.points,availablePoints:0,expiresAt:null,consumedAt:a,referenceType:r,referenceId:n,note:e.note||null,date:a,version:Date.now(),lastModified:a,deleted:!1});let l=await i.update(Rt,o.id,{pointsBalance:s-e.points,totalRedeemed:Number(o.totalRedeemed||0)+e.points,version:Date.now(),lastModified:a});return this.context.logActivity("LoyaltyRedeemPoints",{customerId:t,referenceType:r,referenceId:n,redeemedPoints:e.points}),{redeemedPoints:e.points,balance:Number(l.pointsBalance||0)}})}async expireLoyaltyPoints(e){return this.runInTransaction(async t=>{let r=(e==null?void 0:e.asOfDate)||new Date().toISOString(),n=[{field:"entryType",operator:"=",value:"earn"},{field:"deleted",operator:"=",value:!1},{field:"availablePoints",operator:">",value:0},{field:"expiresAt",operator:"<=",value:r}];e!=null&&e.customerId&&n.push({field:"customerId",operator:"=",value:e.customerId});let i=await t.query(gt,{filters:{and:n}});if(!i.length)return{expiredPoints:0,affectedCustomers:0};let a=0,o=new Map;for(let s of i){let c=Number(s.availablePoints||0);c<=0||(a+=c,o.set(s.customerId,(o.get(s.customerId)||0)+c),await t.update(gt,s.id,{availablePoints:0,consumedAt:r,version:Date.now(),lastModified:r}),await t.create(gt,{id:P(),customerId:s.customerId,entryType:"expire",points:c,availablePoints:0,expiresAt:s.expiresAt,consumedAt:r,referenceType:"loyalty_expiry",referenceId:s.id,note:"auto expiry",date:r,version:Date.now(),lastModified:r,deleted:!1}))}for(let[s,c]of o.entries()){let u=await this.getOrCreateLoyaltyAccount(t,s);await t.update(Rt,u.id,{pointsBalance:Math.max(0,Number(u.pointsBalance||0)-c),totalExpired:Number(u.totalExpired||0)+c,version:Date.now(),lastModified:r})}return this.context.logActivity("LoyaltyExpirePoints",{asOfDate:r,expiredPoints:a,affectedCustomers:o.size}),{expiredPoints:a,affectedCustomers:o.size}})}async getLoyaltySummary(e){let t=String(e||"").trim();if(!t)throw new Error("Loyalty: customerId is required");let r=await this.getOrCreateLoyaltyAccount(this.dbAdapter,t);return{customerId:t,pointsBalance:Number(r.pointsBalance||0),totalEarned:Number(r.totalEarned||0),totalRedeemed:Number(r.totalRedeemed||0),totalExpired:Number(r.totalExpired||0)}}};var tt="customer_groups";var zt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addCustomerGroup(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(tt,i);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("AddCustomerGroup",{id:r}),a}async updateCustomerGroup(e,t,r){let n=await(r||this.dbAdapter).get(tt,e);if(!n)throw new Error(`CustomerGroup with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(tt,e,a);return this.changeQueue.enqueue({type:"update",model:tt,record:o}),this.context.logActivity("UpdateCustomerGroup",{id:e}),o}async getCustomerGroups(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(tt,{...e,filters:i})}async getCustomerGroup(e,t){return(t||this.dbAdapter).get(tt,e)}async deleteCustomerGroup(e,t){return await(t||this.dbAdapter).delete(tt,e),this.changeQueue.enqueue({type:"delete",model:tt,record:{id:e}}),this.context.logActivity("DeleteCustomerGroup",{id:e}),{id:e,queued:!0}}async duplicateCustomerGroup(e,t){let r=await this.getCustomerGroup(e,t);if(!r)throw new Error(`CustomerGroup with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(tt,a);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("DuplicateCustomerGroup",{originalId:e,newId:n}),o}};var ie="histories";var jt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addHistory(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(ie,i);return this.changeQueue.enqueue({type:"create",model:ie,record:a}),this.context.logActivity("AddHistory",{id:r}),a}async updateHistory(e,t,r){if(!await(r||this.dbAdapter).get(ie,e))throw new Error(`History with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e},o=await(r||this.dbAdapter).update(ie,e,a);return this.changeQueue.enqueue({type:"update",model:ie,record:o}),this.context.logActivity("UpdateHistory",{id:e}),o}async getHistories(e,t){return(t||this.dbAdapter).query(ie,e)}async getHistory(e,t){return(t||this.dbAdapter).get(ie,e)}async deleteHistory(e,t){return await(t||this.dbAdapter).delete(ie,e),this.changeQueue.enqueue({type:"delete",model:ie,record:{id:e}}),this.context.logActivity("DeleteHistory",{id:e}),{id:e,queued:!0}}async duplicateHistory(e,t){let r=await this.getHistory(e,t);if(!r)throw new Error(`History with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ie,a);return this.changeQueue.enqueue({type:"create",model:ie,record:a}),this.context.logActivity("DuplicateHistory",{originalId:e,newId:n}),o}async enforceRetentionPolicy(e=new Date){var u;let t=this.context.config.auditLogRetentionDays,r=this.context.config.auditLogArchiveBeforePurge,n=this.context.config.auditLogPurgeBatchSize,i=e.getTime()-t*24*60*60*1e3,a=await this.dbAdapter.query(ie,{sort:[{field:"timestamp",direction:"asc"}]}),o=a.filter(l=>{let d=Date.parse(String(l.timestamp||""));return Number.isFinite(d)&&d<=i}).slice(0,n);if(o.length===0)return{scanned:a.length,archived:0,purged:0,archiveKey:null};let s=0,c=null;if(r){let l=(u=this.context.registry)==null?void 0:u.storageAdapter;c=`audit-archive:${e.toISOString().slice(0,10)}`;let m=await(l==null?void 0:l.getItem(c)),f=m?JSON.parse(m):[],y=o.map(v=>({id:v.id,tableName:v.tableName,recordId:v.recordId,action:v.action,userId:v.userId,timestamp:v.timestamp,changes:v.changes}));await(l==null?void 0:l.setItem(c,JSON.stringify([...Array.isArray(f)?f:[],...y]))),s=y.length}for(let l of o)await this.dbAdapter.delete(ie,l.id);return this.context.logInfo("History retention enforcement completed",{scanned:a.length,archived:s,purged:o.length,retentionDays:t,archiveBeforePurge:r,archiveKey:c}),{scanned:a.length,archived:s,purged:o.length,archiveKey:c}}};var oe="orders";var xe="order_items";var Ri=we("ofcore"),yt=class extends Ri.MemoryStorageAdapter{};var It=class{constructor(e){this.context=e;this.queue=Promise.resolve();var t;this.storage=((t=this.context.registry)==null?void 0:t.storageAdapter)||new yt(this.context)}getBranchSegment(){return String(this.context.config.branchId||"LOCAL").trim().toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"LOCAL"}getDateSegment(e){let t=new Date(e),r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${r}${n}${i}`}getCounterKey(e,t){let r=this.getBranchSegment(),n=this.getDateSegment(t);return`docseq:${r}:${e}:${n}`}async withLock(e){let t=this.queue,r=()=>{};this.queue=new Promise(n=>{r=n}),await t;try{return await e()}finally{r()}}async next(e,t){return this.withLock(async()=>{let r=this.getCounterKey(e,t),n=await this.storage.getItem(r),i=Number(n||"0"),a=Number.isFinite(i)&&i>=0?i+1:1;await this.storage.setItem(r,String(a));let o=e.toUpperCase().slice(0,3),s=this.getBranchSegment(),c=this.getDateSegment(t);return`${o}-${s}-${c}-${String(a).padStart(6,"0")}`})}withNote(e,t){let r=String(e||"").trim(),n=`[DOC_NO=${t}]`;return r?r.includes("[DOC_NO=")?r:`${r} | ${n}`:n}extractDocNo(e){let r=String(e||"").match(/\[DOC_NO=([^\]]+)\]/);return r&&String(r[1]||"").trim()||null}};var si="kitchen_ticket_items";var Yr="kitchen_tickets";var Kt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e),this.docNumberPolicy=new It(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}validateOmnichannelInput(e){var r;let t=(r=e.channel)!=null?r:null;if(t){if(!["dine_in","takeaway","delivery","preorder"].includes(t))throw new Error(`Order channel ${t} is invalid`);if(t==="dine_in"&&!String(e.tableNumber||"").trim())throw new Error("Dine-in order requires tableNumber");if(t==="preorder"&&!String(e.scheduledAt||"").trim())throw new Error("Preorder requires scheduledAt");if(t==="delivery"&&!String(e.deliveryAddress||"").trim())throw new Error("Delivery order requires deliveryAddress")}}isValidTransition(e,t,r){let n={draft:["confirmed","canceled"],confirmed:["preparing","canceled"],preparing:["ready","canceled"],ready:["completed","canceled"],out_for_delivery:["completed","canceled"],completed:[],canceled:[],merged:[]},i=String(t||"draft"),a=String(r||""),o=n[i]||[];return e==="delivery"&&i==="ready"?["out_for_delivery","canceled"].includes(a):e!=="delivery"&&i==="ready"?["completed","canceled"].includes(a):o.includes(a)}async recalculateOrderTotals(e,t){let r=await e.get(oe,t);if(!r||r.deleted)throw new Error(`Order with ID ${t} not found.`);let i=(await e.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((l,d)=>l+Number(d.unitPrice||0)*Number(d.quantity||0),0),a=Number(r.serviceChargeAmount||0),o=Number(r.gratuityAmount||0),s=Number(r.ppn||0),c=Number(r.pph||0),u=i+a+o+s+c;return e.update(oe,t,{total:i,finalTotal:u,version:Date.now(),lastModified:new Date().toISOString()})}async addOrder(e,t){var s,c,u,l,d,m,f,y;this.validateOmnichannelInput(e);let r=P(),n=new Date().toISOString(),i=((s=this.context.config)==null?void 0:s.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("order",e.date||n):null,a={id:r,userId:e.userId,customerId:e.customerId,parentOrderId:(c=e.parentOrderId)!=null?c:null,discountCode:e.discountCode,channel:(u=e.channel)!=null?u:null,status:e.status,saleId:e.saleId,scheduledAt:(l=e.scheduledAt)!=null?l:null,deliveryAddress:(d=e.deliveryAddress)!=null?d:null,tableNumber:(m=e.tableNumber)!=null?m:null,serviceChargeAmount:(f=e.serviceChargeAmount)!=null?f:null,gratuityAmount:(y=e.gratuityAmount)!=null?y:null,date:e.date,total:e.total,ppn:e.ppn,pph:e.pph,finalTotal:e.finalTotal,note:i?this.docNumberPolicy.withNote(e.note,i):e.note,version:1,lastModified:n,deleted:!1},o=await(t||this.dbAdapter).create(oe,a);return this.changeQueue.enqueue({type:"create",model:oe,record:o}),this.context.logActivity("AddOrder",{id:r,channel:a.channel,status:a.status}),o}async updateOrder(e,t,r){let n=await(r||this.dbAdapter).get(oe,e);if(!n)throw new Error(`Order with ID ${e} not found.`);this.validateOmnichannelInput({...n,...t});let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(oe,e,a);return this.changeQueue.enqueue({type:"update",model:oe,record:o}),this.context.logActivity("UpdateOrder",{id:e}),o}async getOrders(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(oe,{...e,filters:i})}async getOrder(e,t){return(t||this.dbAdapter).get(oe,e)}async deleteOrder(e,t){return await(t||this.dbAdapter).delete(oe,e),this.changeQueue.enqueue({type:"delete",model:oe,record:{id:e}}),this.context.logActivity("DeleteOrder",{id:e}),{id:e,queued:!0}}async duplicateOrder(e,t){let r=await this.getOrder(e,t);if(!r)throw new Error(`Order with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,status:"draft",saleId:null,version:1,lastModified:i,deleted:!1},o=await(t||this.dbAdapter).create(oe,a);return this.changeQueue.enqueue({type:"create",model:oe,record:a}),this.context.logActivity("DuplicateOrder",{originalId:e,newId:n}),o}async finalizeOrder(e){return await this.runInTransaction(async t=>{await this.recalculateOrderTotals(t,e),await t.update(oe,e,{status:"completed",version:Date.now(),lastModified:new Date().toISOString()})}),this.context.eventBus.emit("order:finalized",e),{id:e,queued:!0}}async transitionOrderLifecycle(e){let t=String(e.orderId||"").trim(),r=String(e.actorId||"").trim(),n=String(e.toStatus||"").trim();if(!t)throw new Error("orderId is required");if(!r)throw new Error("actorId is required");if(!n)throw new Error("toStatus is required");return this.runInTransaction(async i=>{let a=await i.get(oe,t);if(!a||a.deleted)throw new Error(`Order with ID ${t} not found.`);let o=a.channel||null;if(!this.isValidTransition(o,a.status,n))throw new Error(`Invalid order lifecycle transition: ${a.status} -> ${n}`);let s=new Date().toISOString(),c=await i.update(oe,t,{status:n,version:Date.now(),lastModified:s});return await i.create(ie,{id:P(),tableName:oe,recordId:t,action:"lifecycle_transition",changes:{fromStatus:a.status,toStatus:n,actorId:r,reason:e.reason||null,channel:o},userId:r,timestamp:s}),c})}async createKitchenTicket(e){if(!String(e.orderId||"").trim())throw new Error("orderId is required");if(!String(e.station||"").trim())throw new Error("station is required");if(!String(e.actorId||"").trim())throw new Error("actorId is required");if(!Array.isArray(e.items)||e.items.length===0)throw new Error("items is required");return this.runInTransaction(async t=>{let r=await t.get(oe,e.orderId);if(!r||r.deleted)throw new Error(`Order with ID ${e.orderId} not found.`);let n=new Date().toISOString(),i=await t.create(Yr,{id:P(),orderId:e.orderId,station:e.station,status:"queued",note:e.note||null,createdBy:e.actorId,createdAt:n,version:Date.now(),lastModified:n,deleted:!1}),a=[];for(let o of e.items){let s=String(o.orderItemId||"").trim();if(!s)throw new Error("orderItemId is required");let c=await t.get(xe,s);if(!c||c.deleted||String(c.orderId)!==e.orderId)throw new Error(`Order item ${s} does not belong to order ${e.orderId}`);let u=await t.create(si,{id:P(),ticketId:i.id,orderItemId:s,course:o.course||null,status:"queued",note:o.note||null,version:Date.now(),lastModified:n,deleted:!1});a.push(u)}return await t.create(ie,{id:P(),tableName:Yr,recordId:i.id,action:"create",changes:{orderId:e.orderId,station:e.station,itemCount:a.length},userId:e.actorId,timestamp:n}),{ticket:i,items:a}})}async splitOrderBill(e){let t=String(e.orderId||"").trim(),r=String(e.actorId||"").trim();if(!t)throw new Error("orderId is required");if(!r)throw new Error("actorId is required");if(!Array.isArray(e.splits)||e.splits.length===0)throw new Error("splits is required");return this.runInTransaction(async n=>{let i=await n.get(oe,t);if(!i||i.deleted)throw new Error(`Order with ID ${t} not found.`);let a=await n.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}}),o=new Set(a.map(l=>String(l.id))),s=new Set,c=new Date().toISOString(),u=[];for(let l of e.splits){let d=(l.orderItemIds||[]).map(f=>String(f));if(d.length===0)continue;for(let f of d){if(!o.has(f))throw new Error(`Order item ${f} does not belong to parent order`);if(s.has(f))throw new Error(`Order item ${f} referenced by multiple splits`);s.add(f)}let m=await n.create(oe,{id:P(),userId:i.userId,customerId:i.customerId,parentOrderId:t,discountCode:i.discountCode,channel:i.channel,status:"draft",saleId:null,scheduledAt:i.scheduledAt,deliveryAddress:i.deliveryAddress,tableNumber:i.tableNumber,serviceChargeAmount:0,gratuityAmount:0,date:i.date,total:0,ppn:0,pph:0,finalTotal:0,note:l.label?`SPLIT:${l.label}`:"SPLIT",version:Date.now(),lastModified:c,deleted:!1});u.push(m.id);for(let f of d)await n.get(xe,f)&&await n.update(xe,f,{orderId:m.id,version:Date.now(),lastModified:c});await this.recalculateOrderTotals(n,m.id)}return await this.recalculateOrderTotals(n,t),await n.create(ie,{id:P(),tableName:oe,recordId:t,action:"bill_split",changes:{actorId:r,childOrderIds:u,movedItems:Array.from(s)},userId:r,timestamp:c}),{parentOrderId:t,childOrderIds:u}})}async mergeOrderBills(e){let t=String(e.targetOrderId||"").trim(),r=String(e.actorId||"").trim();if(!t)throw new Error("targetOrderId is required");if(!r)throw new Error("actorId is required");let n=Array.from(new Set((e.sourceOrderIds||[]).map(i=>String(i).trim()).filter(Boolean)));if(!n.length)throw new Error("sourceOrderIds is required");if(n.includes(t))throw new Error("targetOrderId cannot be included in sourceOrderIds");return this.runInTransaction(async i=>{let a=await i.get(oe,t);if(!a||a.deleted)throw new Error(`Order with ID ${t} not found.`);let o=new Date().toISOString();for(let s of n){let c=await i.get(oe,s);if(!c||c.deleted)throw new Error(`Order with ID ${s} not found.`);let u=await i.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:s},{field:"deleted",operator:"=",value:!1}]}});for(let l of u)await i.update(xe,l.id,{orderId:t,version:Date.now(),lastModified:o});await i.update(oe,s,{status:"merged",version:Date.now(),lastModified:o,note:[c.note,`MERGED_INTO:${t}`].filter(Boolean).join(" | ")})}return await this.recalculateOrderTotals(i,t),await i.create(ie,{id:P(),tableName:oe,recordId:t,action:"bill_merge",changes:{actorId:r,mergedOrderIds:n},userId:r,timestamp:o}),{targetOrderId:t,mergedOrderIds:n}})}async applyServiceChargeAndGratuity(e){let t=String(e.orderId||"").trim();if(!t)throw new Error("orderId is required");if(!String(e.actorId||"").trim())throw new Error("actorId is required");if(!Number.isFinite(e.serviceChargeRate)||e.serviceChargeRate<0)throw new Error("serviceChargeRate must be >= 0");if(!Number.isFinite(e.gratuityRate)||e.gratuityRate<0)throw new Error("gratuityRate must be >= 0");return this.runInTransaction(async r=>{let n=await r.get(oe,t);if(!n||n.deleted)throw new Error(`Order with ID ${t} not found.`);let a=(await r.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((l,d)=>l+Number(d.unitPrice||0)*Number(d.quantity||0),0),o=Math.round(a*e.serviceChargeRate*100)/100,s=Math.round(a*e.gratuityRate*100)/100,c=new Date().toISOString(),u=await r.update(oe,t,{serviceChargeAmount:o,gratuityAmount:s,total:a,finalTotal:a+o+s+Number(n.ppn||0)+Number(n.pph||0),version:Date.now(),lastModified:c});return await r.create(ie,{id:P(),tableName:oe,recordId:t,action:"service_charge_gratuity_applied",changes:{actorId:e.actorId,serviceChargeRate:e.serviceChargeRate,gratuityRate:e.gratuityRate,serviceChargeAmount:o,gratuityAmount:s},userId:e.actorId,timestamp:c}),u})}};var Xr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addOrderItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(xe,i);return this.changeQueue.enqueue({type:"create",model:xe,record:a}),this.context.logActivity("AddOrderItem",{id:r}),a}async updateOrderItem(e,t,r){let n=await(r||this.dbAdapter).get(xe,e);if(!n)throw new Error(`OrderItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(xe,e,a);return this.changeQueue.enqueue({type:"update",model:xe,record:o}),this.context.logActivity("UpdateOrderItem",{id:e}),o}async getOrderItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(xe,{...e,filters:i})}async getOrderItem(e,t){return(t||this.dbAdapter).get(xe,e)}async deleteOrderItem(e,t){return await(t||this.dbAdapter).delete(xe,e),this.changeQueue.enqueue({type:"delete",model:xe,record:{id:e}}),this.context.logActivity("DeleteOrderItem",{id:e}),{id:e,queued:!0}}async duplicateOrderItem(e,t){let r=await this.getOrderItem(e,t);if(!r)throw new Error(`OrderItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(xe,a);return this.changeQueue.enqueue({type:"create",model:xe,record:a}),this.context.logActivity("DuplicateOrderItem",{originalId:e,newId:n}),o}};var He="price_tiers";var Gt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPriceTier(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(He,i);return this.changeQueue.enqueue({type:"create",model:He,record:a}),this.context.logActivity("AddPriceTier",{id:r}),a}async updatePriceTier(e,t,r){let n=await(r||this.dbAdapter).get(He,e);if(!n)throw new Error(`PriceTier with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(He,e,a);return this.changeQueue.enqueue({type:"update",model:He,record:o}),this.context.logActivity("UpdatePriceTier",{id:e}),o}async getPriceTiers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(He,{...e,filters:i})}async getPriceTier(e,t){return(t||this.dbAdapter).get(He,e)}async deletePriceTier(e,t){return await(t||this.dbAdapter).delete(He,e),this.changeQueue.enqueue({type:"delete",model:He,record:{id:e}}),this.context.logActivity("DeletePriceTier",{id:e}),{id:e,queued:!0}}async duplicatePriceTier(e,t){let r=await this.getPriceTier(e,t);if(!r)throw new Error(`PriceTier with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(He,a);return this.changeQueue.enqueue({type:"create",model:He,record:a}),this.context.logActivity("DuplicatePriceTier",{originalId:e,newId:n}),o}};var ce="products";var Wt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addProduct(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ce,i);return this.changeQueue.enqueue({type:"create",model:ce,record:a}),this.context.logActivity("AddProduct",{id:r}),a}async updateProduct(e,t,r){let n=await(r||this.dbAdapter).get(ce,e);if(!n)throw new Error(`Product with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ce,e,a);return this.changeQueue.enqueue({type:"update",model:ce,record:o}),this.context.logActivity("UpdateProduct",{id:e}),o}async getProducts(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ce,{...e,filters:i})}async getProduct(e,t){return(t||this.dbAdapter).get(ce,e)}async deleteProduct(e,t){return await(t||this.dbAdapter).delete(ce,e),this.changeQueue.enqueue({type:"delete",model:ce,record:{id:e}}),this.context.logActivity("DeleteProduct",{id:e}),{id:e,queued:!0}}async duplicateProduct(e,t){let r=await this.getProduct(e,t);if(!r)throw new Error(`Product with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ce,a);return this.changeQueue.enqueue({type:"create",model:ce,record:a}),this.context.logActivity("DuplicateProduct",{originalId:e,newId:n}),o}async getProductsByBarcode(e,t){let r=t||this.dbAdapter,n={and:[{barcode:e},{deleted:!1}]};return r.query(ce,{filters:n})}async getProductsByQrCode(e,t){let r=t||this.dbAdapter,n={and:[{qrCode:e},{deleted:!1}]};return r.query(ce,{filters:n})}async searchProducts(e,t,r){let n=e.trim();if(!n)return[];let i=r||this.dbAdapter,a={and:[{or:[{field:"name",operator:"like",value:`%${n}%`},{field:"description",operator:"like",value:`%${n}%`},{field:"barcode",operator:"like",value:`%${n}%`},{field:"qrCode",operator:"like",value:`%${n}%`}]},{deleted:!1}]};return i.query(ce,{...t,filters:a})}};var rt="promotions";var Yt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPromotion(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(rt,i);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("AddPromotion",{id:r}),a}async updatePromotion(e,t,r){let n=await(r||this.dbAdapter).get(rt,e);if(!n)throw new Error(`Promotion with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(rt,e,a);return this.changeQueue.enqueue({type:"update",model:rt,record:o}),this.context.logActivity("UpdatePromotion",{id:e}),o}async getPromotions(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(rt,{...e,filters:i})}async getPromotion(e,t){return(t||this.dbAdapter).get(rt,e)}async deletePromotion(e,t){return await(t||this.dbAdapter).delete(rt,e),this.changeQueue.enqueue({type:"delete",model:rt,record:{id:e}}),this.context.logActivity("DeletePromotion",{id:e}),{id:e,queued:!0}}async duplicatePromotion(e,t){let r=await this.getPromotion(e,t);if(!r)throw new Error(`Promotion with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(rt,a);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("DuplicatePromotion",{originalId:e,newId:n}),o}};var Ae="returns";var fe="sale_items";var De="purchase_items";var Re="return_items";var J="transactions";var Xt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addReturn(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ae,i);return this.changeQueue.enqueue({type:"create",model:Ae,record:a}),this.context.logActivity("AddReturn",{id:r}),a}async updateReturn(e,t,r){let n=await(r||this.dbAdapter).get(Ae,e);if(!n)throw new Error(`Return with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ae,e,a);return this.changeQueue.enqueue({type:"update",model:Ae,record:o}),this.context.logActivity("UpdateReturn",{id:e}),o}async getReturns(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ae,{...e,filters:i})}async getReturn(e,t){return(t||this.dbAdapter).get(Ae,e)}async deleteReturn(e,t){return await(t||this.dbAdapter).delete(Ae,e),this.changeQueue.enqueue({type:"delete",model:Ae,record:{id:e}}),this.context.logActivity("DeleteReturn",{id:e}),{id:e,queued:!0}}async duplicateReturn(e,t){let r=await this.getReturn(e,t);if(!r)throw new Error(`Return with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ae,a);return this.changeQueue.enqueue({type:"create",model:Ae,record:a}),this.context.logActivity("DuplicateReturn",{originalId:e,newId:n}),o}async getReferenceItem(e,t,r,n){let i=await n.query(e==="sale_return"?fe:De,{filters:{deleted:!1,productId:r,...e==="sale_return"?{saleId:t}:{purchaseId:t}}});return i.length?i[0]:null}getCurrentRole(){var t,r;let e=(r=(t=this.context.session)==null?void 0:t.user)==null?void 0:r.role;return e?String(e).trim().toLowerCase():null}normalizeRoles(e,t){if(!Array.isArray(e))return t;let r=e.map(n=>String(n||"").trim().toLowerCase()).filter(Boolean);return r.length>0?r:t}validateApproval(e,t,r){let n=String((e==null?void 0:e.approvedBy)||"").trim(),i=String((e==null?void 0:e.reason)||"").trim(),a=String((e==null?void 0:e.approverRole)||"").trim().toLowerCase();if(!n||!i||!a)throw new Error(`${r} approval is required with approvedBy, reason, and approverRole`);if(!t.includes(a))throw new Error(`${r} approval approverRole is not allowed`);return{approvedBy:n,reason:i,approverRole:a}}getFraudGuardPolicy(){var i,a,o,s;let e=((i=this.context.config)==null?void 0:i.enableReturnFraudGuard)===!0,t=Number(((a=this.context.config)==null?void 0:a.returnFraudWindowMinutes)||60),r=Number(((o=this.context.config)==null?void 0:o.returnFraudMaxEvents)||3),n=((s=this.context.config)==null?void 0:s.returnFraudAction)==="block"?"block":"require_approval";return{enabled:e,windowMinutes:t>0?t:60,maxEvents:r>0?r:3,action:n}}async shouldTriggerFraudGuardForRefund(e){let t=this.getFraudGuardPolicy();if(!t.enabled||!e)return!1;let r=new Date(Date.now()-t.windowMinutes*60*1e3).toISOString();return(await this.dbAdapter.query(Ae,{filters:{and:[{field:"userId",operator:"=",value:e},{field:"date",operator:">=",value:r},{field:"deleted",operator:"=",value:!1}]}})).filter(a=>Number(a.actualRefund||0)>0).length>=t.maxEvents}async shouldTriggerFraudGuardForCancel(e){let t=this.getFraudGuardPolicy();if(!t.enabled||!e)return!1;let r=new Date(Date.now()-t.windowMinutes*60*1e3).toISOString();return(await this.dbAdapter.query(J,{filters:{and:[{field:"userId",operator:"=",value:e},{field:"date",operator:">=",value:r},{field:"referenceType",operator:"IN",value:["sale_return_cancelled","purchase_return_cancelled"]},{field:"deleted",operator:"=",value:!1}]}})).length>=t.maxEvents}async processReturn(e){var j,z,B,U;let t=(z=(j=this.context)==null?void 0:j.domainServices)==null?void 0:z.inventory,{type:r,saleId:n=null,purchaseId:i=null,reason:a="",items:o,refundAmount:s,actualRefund:c=s,refundMethod:u="cash",creditNoteNumber:l=null,refundNote:d,refundReceivedDate:m,approval:f}=e;if(!n&&!i)throw new Error("saleId or purchaseId is required");if(r==="sale_return"&&!n)throw new Error("saleId required for sale_return");if(r==="purchase_return"&&!i)throw new Error("purchaseId required for purchase_return");let y=this.context.config.requireReasonForReturnOperations,v=String(a||"").trim();if(y&&!v)throw new Error("Return reason is required by policy");let p=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),g=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),x=this.getCurrentRole(),b=!x||!p.includes(x),A=c>0&&this.context.config.requireApprovalForReturnRefund&&b,I=String(((B=this.context.session)==null?void 0:B.userId)||"").trim(),F=c>0&&await this.shouldTriggerFraudGuardForRefund(I),w=this.getFraudGuardPolicy();if(F&&w.action==="block")throw new Error("Fraud guard: repeat return pattern detected (refund blocked)");let q=F&&w.action==="require_approval",M=A||q?this.validateApproval(f,g,q?"Fraud guard return refund":"Return refund"):null,E=(U=this.context.domainServices)==null?void 0:U.uom,L=await E.getUomsMap(),Q=this.context.domainServices.transaction;if(e.saleId){let O=await this.getReturnsByReference("sale_return",e.saleId);if(O.length>0){let _=await this.calculateTotalReturnedQty(O,e.items.map(R=>R.productId));for(let R of e.items){let D=await this.getOriginalQuantity("sale",e.saleId,R.productId),Z=D-(_.get(R.productId)||0);if(R.quantity>Z)throw new Error(`Produk ${R.productId} hanya bisa diretur ${Z} lagi (sudah diretur ${_.get(R.productId)||0}/${D})`)}}}if(e.purchaseId){let O=await this.getReturnsByReference("purchase_return",e.purchaseId);if(O.length>0){let _=await this.calculateTotalReturnedQty(O,e.items.map(R=>R.productId));for(let R of e.items){let D=await this.getOriginalQuantity("purchase",e.purchaseId,R.productId),Z=D-(_.get(R.productId)||0);if(R.quantity>Z)throw new Error(`Produk ${R.productId} hanya bisa diretur ${Z} lagi (sudah diretur ${_.get(R.productId)||0}/${D})`)}}}let T=await this.dbAdapter.transaction(async O=>{var te,X,Y;let _=new Date().toISOString(),R=P(),D=[],Z={id:R,type:r,saleId:n,purchaseId:i,reason:v||null,refundAmount:s,actualRefund:c,refundMethod:c>0?u:null,creditNoteNumber:l,refundNote:c<s?typeof d=="number"?d:s-c:null,refundReceivedDate:c>0?m||_:null,status:c===s?"completed":c>0?"partially_refunded":"no_refund",date:_,userId:((te=this.context.session)==null?void 0:te.userId)||"",version:1,lastModified:_,deleted:!1};await O.create(Ae,Z),D.push({type:"create",model:Ae,record:Z});for(let ye of o){let se=(X=ye.restock)!=null?X:!0,Ne=ye.quantity,ve=await this.getReferenceItem(r,n||i,ye.productId,O);if(!ve)throw new Error(`Item not found in ${r==="sale_return"?"sale":"purchase"} ${n||i}`);let Te=r==="sale_return"?ve.unitPrice:ve.unitCost,pe=ve.uomId,We={id:P(),returnId:R,productId:ye.productId,quantity:Ne,unitPrice:Te,uomId:pe,restock:se,restockNote:se?null:ye.restockNote||"Rusak / tidak bisa dijual",version:1,lastModified:_,deleted:!1};if(await O.create(Re,We),D.push({type:"create",model:Re,record:We}),se){let Ye=E.convertQuantity(Ne,{conversionFactor:pe&&((Y=L.get(pe))==null?void 0:Y.conversionFactor)||1},{conversionFactor:1}),Xe=r==="sale_return"?+Ye:-Ye;await t.updateStock(ye.productId,Xe,r,Ae,R,O)}}if(c>0)if((r==="sale_return"?"out":"in")==="in"){let se=await Q.recordCashIn({amount:c,method:u,data:{referenceType:r,referenceId:R,note:d}},O);D.push({type:"create",model:J,record:se})}else{let se=await Q.recordCashOut({amount:c,method:u,data:{referenceType:r,referenceId:R,note:d}},O);D.push({type:"create",model:J,record:se})}return M&&this.context.logActivity("ReturnRefundApproved",{returnId:R,approvedBy:M.approvedBy,approverRole:M.approverRole,reason:M.reason}),{returnId:R,queued:!0,type:r,actualRefund:c,syncChanges:D}});for(let O of T.syncChanges)this.changeQueue.enqueue(O);return this.context.eventBus.emit("return:processed",{returnId:T.returnId,type:T.type,actualRefund:T.actualRefund}),this.context.logActivity("processReturn",{returnId:T.returnId,type:T.type,actualRefund:T.actualRefund}),{returnId:T.returnId,queued:T.queued}}async cancelReturn(e,t="Cancelled by user"){var A,I,F,w;let r=(I=(A=this.context)==null?void 0:A.domainServices)==null?void 0:I.inventory,n=(F=this.context.domainServices)==null?void 0:F.uom,i=await n.getUomsMap(),a=this.context.domainServices.transaction,o=typeof t=="string"?String(t||"").trim()||"Cancelled by user":t.reason===void 0?"Cancelled by user":String(t.reason||"").trim(),s=typeof t=="string"?void 0:t.approval;if(this.context.config.requireReasonForReturnOperations&&!String(o||"").trim())throw new Error("Return cancellation reason is required by policy");let u=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),l=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),d=this.getCurrentRole(),m=!d||!u.includes(d),f=this.context.config.requireApprovalForReturnCancel&&m,y=String(((w=this.context.session)==null?void 0:w.userId)||"").trim(),v=await this.shouldTriggerFraudGuardForCancel(y),p=this.getFraudGuardPolicy();if(v&&p.action==="block")throw new Error("Fraud guard: repeat return cancellation pattern detected (cancel blocked)");let g=v&&p.action==="require_approval",x=f||g?this.validateApproval(s,l,g?"Fraud guard return cancellation":"Return cancellation"):null,b=await this.dbAdapter.transaction(async q=>{var Q;let M=await q.get(Ae,e);if(!M||M.deleted)throw new Error("Return not found or already deleted");let E=[],L=await q.query(Re,{filters:{returnId:e,deleted:!1}});for(let T of L){if(T.restock){let j=n.convertQuantity(T.quantity,{conversionFactor:T.uomId&&((Q=i.get(T.uomId))==null?void 0:Q.conversionFactor)||1},{conversionFactor:1}),z=M.type==="sale_return"?-j:+j;await r.updateStock(T.productId,z,`${M.type}_cancelled`,Ae,e,q)}await q.update(Re,T.id,{deleted:!0,lastModified:new Date().toISOString()}),E.push({type:"delete",model:Re,record:{id:T.id}})}if(M.actualRefund>0)if((M.type==="sale_return"?"in":"out")==="in"){let j=await a.recordCashIn({amount:M.actualRefund,method:M.refundMethod||"cash",data:{referenceType:`${M.type}_cancelled`,referenceId:e,note:o}},q);E.push({type:"create",model:J,record:j})}else{let j=await a.recordCashOut({amount:M.actualRefund,method:M.refundMethod||"cash",data:{referenceType:`${M.type}_cancelled`,referenceId:e,note:o}},q);E.push({type:"create",model:J,record:j})}return await q.update(Ae,e,{deleted:!0,lastModified:new Date().toISOString()}),E.push({type:"delete",model:Ae,record:{id:e}}),x&&this.context.logActivity("CancelReturnApproved",{returnId:e,approvedBy:x.approvedBy,approverRole:x.approverRole,reason:x.reason}),{returnId:e,queued:!0,syncChanges:E}});for(let q of b.syncChanges)this.changeQueue.enqueue(q);return this.context.eventBus.emit("return:canceled",{returnId:b.returnId}),this.context.logActivity("cancelReturn",{returnId:b.returnId}),{returnId:b.returnId,queued:b.queued}}async getReturnsByReference(e,t){let r=e==="sale_return"?{saleId:t,deleted:!1}:{purchaseId:t,deleted:!1};return this.dbAdapter.query(Ae,{filters:r})}async getReturnableQuantity(e,t,r){let n=await this.getOriginalQuantity(e,t,r);if(n<=0)return 0;let i=e==="sale"?"sale_return":"purchase_return",a=await this.getReturnsByReference(i,t);if(!a.length)return n;let s=(await this.calculateTotalReturnedQty(a,[r])).get(r)||0;return Math.max(0,n-s)}async calculateTotalReturnedQty(e,t){let r=new Map;for(let n of e){let i=await this.dbAdapter.query(Re,{filters:{returnId:n.id,deleted:!1,restock:!0}});for(let a of i)t.includes(a.productId)&&r.set(a.productId,(r.get(a.productId)||0)+a.quantity)}return r}async getOriginalQuantity(e,t,r){let n=e==="sale"?fe:De,i=e==="sale"?"saleId":"purchaseId",a=await this.dbAdapter.query(n,{filters:{[i]:t,productId:r,deleted:!1}});return a.length?a[0].quantity:0}};var Zr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addReturnItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Re,i);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("AddReturnItem",{id:r}),a}async updateReturnItem(e,t,r){let n=await(r||this.dbAdapter).get(Re,e);if(!n)throw new Error(`ReturnItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Re,e,a);return this.changeQueue.enqueue({type:"update",model:Re,record:o}),this.context.logActivity("UpdateReturnItem",{id:e}),o}async getReturnItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Re,{...e,filters:i})}async getReturnItem(e,t){return(t||this.dbAdapter).get(Re,e)}async deleteReturnItem(e,t){return await(t||this.dbAdapter).delete(Re,e),this.changeQueue.enqueue({type:"delete",model:Re,record:{id:e}}),this.context.logActivity("DeleteReturnItem",{id:e}),{id:e,queued:!0}}async duplicateReturnItem(e,t){let r=await this.getReturnItem(e,t);if(!r)throw new Error(`ReturnItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Re,a);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("DuplicateReturnItem",{originalId:e,newId:n}),o}};var Pe="roles";var Jr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addRole(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Pe,i);return this.changeQueue.enqueue({type:"create",model:Pe,record:a}),this.context.logActivity("AddRole",{id:r}),a}async updateRole(e,t,r){let n=await(r||this.dbAdapter).get(Pe,e);if(!n)throw new Error(`Role with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Pe,e,a);return this.changeQueue.enqueue({type:"update",model:Pe,record:o}),this.context.logActivity("UpdateRole",{id:e}),o}async getRoles(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Pe,{...e,filters:i})}async getRole(e,t){return(t||this.dbAdapter).get(Pe,e)}async deleteRole(e,t){return await(t||this.dbAdapter).delete(Pe,e),this.changeQueue.enqueue({type:"delete",model:Pe,record:{id:e}}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async duplicateRole(e,t){let r=await this.getRole(e,t);if(!r)throw new Error(`Role with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Pe,a);return this.changeQueue.enqueue({type:"create",model:Pe,record:a}),this.context.logActivity("DuplicateRole",{originalId:e,newId:n}),o}};var ue="sales";var he="receivables";var pt="inventory_lots";var Zt=class{constructor(e){this.context=e;this.defaultBaseCurrencyCode="IDR";var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e),this.docNumberPolicy=new It(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t,r){var c,u,l;let n=(c=e.transactionCurrencyCode)!=null?c:this.defaultBaseCurrencyCode,i=(u=e.exchangeRate)!=null?u:1,a=Number.isFinite(i)&&i>0?Number(i):1,o=this.roundCurrencyAmount(e.totalInBaseCurrency!=null?Number(e.totalInBaseCurrency):t*a),s=this.roundCurrencyAmount(e.finalTotalInBaseCurrency!=null?Number(e.finalTotalInBaseCurrency):r*a);return{transactionCurrencyCode:n,exchangeRate:a,exchangeRateSource:(l=e.exchangeRateSource)!=null?l:"snapshot.manual",totalInBaseCurrency:o,finalTotalInBaseCurrency:s}}isExpiredLot(e,t){if(!e)return!1;let r=Date.parse(String(e));return Number.isFinite(r)?r<t:!1}diffInDays(e,t){let r=e.getTime(),n=t.getTime();return!Number.isFinite(r)||!Number.isFinite(n)?NaN:Math.floor((n-r)/(1440*60*1e3))}async enforceTempoCustomerCreditPolicy(e,t){if(!this.context.config.enableCustomerCreditPolicy)return;let r=String(t.customerId||"").trim();if(!r)throw new Error("Customer credit policy: customerId is required for tempo sale");let n=await e.query(he,{filters:{and:[{field:"customerId",operator:"=",value:r},{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),i=new Date(t.nowIso),a=this.context.config.customerCreditOverdueGraceDays,o=0,s=0;for(let l of n){let d=Number(l.amount||0),m=Number(l.paidAmount||0),f=Math.max(0,d-m);if(f<=0)continue;o+=f;let y=this.diffInDays(new Date(String(l.dueDate||"")),i);Number.isFinite(y)&&(s=Math.max(s,y))}let c=this.context.config.customerCreditMaxOutstandingAmount;if(c!=null&&o+t.receivableAmount>c)throw new Error(`Customer credit policy: limit exceeded for customer ${r}`);if(this.context.config.customerCreditBlockOnOverdue&&s>a)throw new Error(`Customer credit policy: overdue receivable exceeds grace period for customer ${r}`);let u=this.context.config.customerCreditEscalationThresholdDays;s>=u&&this.context.logActivity("customerCreditEscalationDetected",{customerId:r,maxDaysPastDue:s,referenceId:t.referenceId,dueDate:t.dueDate})}normalizeDocNo(e){return this.docNumberPolicy.extractDocNo(e)}toBaseQuantity(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertQuantity(e,{conversionFactor:i},{conversionFactor:1}):e}async getDuplicateDocumentNumbers(e){let t=[{field:"deleted",operator:"=",value:!1}];e!=null&&e.dateFrom&&t.push({field:"date",operator:">=",value:e.dateFrom}),e!=null&&e.dateTo&&t.push({field:"date",operator:"<=",value:e.dateTo});let r=await this.dbAdapter.query(ue,{filters:{and:t}}),n=new Map;for(let i of r){let a=this.normalizeDocNo(i.note);if(!a)continue;let o=n.get(a)||[];o.push(String(i.id)),n.set(a,o)}return Array.from(n.entries()).filter(([,i])=>i.length>1).map(([i,a])=>({docNo:i,saleIds:a}))}async requestReprint(e,t){let r=String(t.actorId||"").trim(),n=String(t.reason||"").trim();if(!r)throw new Error("Reprint policy: actorId is required");if(!n)throw new Error("Reprint policy: reason is required");let i=await this.dbAdapter.get(ue,e);if(!i||i.deleted)throw new Error(`Sale ${e} not found`);let a=this.normalizeDocNo(i.note),s=(await this.dbAdapter.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:ue},{field:"recordId",operator:"=",value:e},{field:"action",operator:"=",value:"reprint"}]}})).length+1,c=a?(await this.getDuplicateDocumentNumbers()).some(l=>l.docNo===a):!1,u=new Date().toISOString();return await this.dbAdapter.create(ie,{id:P(),tableName:ue,recordId:e,action:"reprint",changes:{actorId:r,reason:n,terminalId:t.terminalId||null,docNo:a,reprintCount:s,duplicateDocNoDetected:c},userId:r,timestamp:u}),c&&await this.dbAdapter.create(ie,{id:P(),tableName:ue,recordId:e,action:"duplicate_doc_detected",changes:{docNo:a,detector:"sale.requestReprint",detectedAt:u},userId:r,timestamp:u}),{saleId:e,docNo:a,reprintCount:s,duplicateDocNoDetected:c}}async consumeInventoryLotsForSale(e,t){var v,p,g;let r=Number(t.quantity||0);if(!Number.isFinite(r)||r<=0)return[];let n=(v=this.context.domainServices)==null?void 0:v.uom,i=await n.getUomsMap(),a=t.uomId&&((p=i.get(t.uomId))==null?void 0:p.conversionFactor)||1,o=n.convertQuantity(r,{conversionFactor:a},{conversionFactor:1});if(!Number.isFinite(o)||o<=0)return[];let s=await e.query(pt,{filters:{and:[{field:"productId",operator:"=",value:t.productId},{field:"deleted",operator:"=",value:!1},{field:"remainingQuantity",operator:">",value:0},{field:"status",operator:"IN",value:["active","expired"]}]},sort:[{field:"lastModified",direction:"asc"}]});if(!s.length)return[];let c=Number.isFinite(Date.parse(t.saleDate))?Date.parse(t.saleDate):Date.now(),u=new Date().toISOString(),l=[],d=[],m=0;for(let x of s){if(this.isExpiredLot(x.expiryDate,c)){if(x.status!=="expired"){let A=await e.update(pt,x.id,{status:"expired",version:Number(x.version||0)+1,lastModified:u});l.push({id:A.id,remainingQuantity:Number(A.remainingQuantity||0),status:String(A.status||"expired"),version:Number(A.version||0),lastModified:String(A.lastModified||u)})}continue}d.push(x),m+=Number(x.remainingQuantity||0)}if(m<o)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: insufficient non-expired lot stock`);let f=((g=this.context.config)==null?void 0:g.lotConsumptionPolicy)==="FIFO"?"FIFO":"FEFO";d.sort((x,b)=>{let A=Date.parse(x.lastModified||""),I=Date.parse(b.lastModified||"");if(f==="FIFO"){if(Number.isFinite(A)&&Number.isFinite(I)&&A!==I)return A-I}else{let F=x.expiryDate?Date.parse(x.expiryDate):Number.POSITIVE_INFINITY,w=b.expiryDate?Date.parse(b.expiryDate):Number.POSITIVE_INFINITY;if(Number.isFinite(F)&&Number.isFinite(w)&&F!==w)return F-w;if(Number.isFinite(F)!==Number.isFinite(w))return Number.isFinite(F)?-1:1}return Number.isFinite(A)&&Number.isFinite(I)&&A!==I?A-I:String(x.id).localeCompare(String(b.id))});let y=o;for(let x of d){if(y<=0)break;let b=Number(x.remainingQuantity||0);if(b<=0)continue;let A=Math.min(y,b),I=b-A,F=I<=0?"depleted":"active",w=await e.update(pt,x.id,{remainingQuantity:I,status:F,version:Number(x.version||0)+1,lastModified:u});l.push({id:w.id,remainingQuantity:Number(w.remainingQuantity||0),status:String(w.status||F),version:Number(w.version||0),lastModified:String(w.lastModified||u)}),y-=A}if(y>0)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: lot consumption incomplete`);return l}async addSale(e,t){let r=P(),n=new Date().toISOString(),i=this.resolveCurrencySnapshot(e,Number(e.total||0),Number(e.finalTotal||0)),a={id:r,...e,...i,version:1,lastModified:n,deleted:!1},o=await(t||this.dbAdapter).create(ue,a);return this.changeQueue.enqueue({type:"create",model:ue,record:o}),this.context.logActivity("AddSale",{id:r}),o}async updateSale(e,t,r){let n=await(r||this.dbAdapter).get(ue,e);if(!n)throw new Error(`Sale with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ue,e,a);return this.changeQueue.enqueue({type:"update",model:ue,record:o}),this.context.logActivity("UpdateSale",{id:e}),o}async getSales(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ue,{...e,filters:i})}async getSale(e,t){return(t||this.dbAdapter).get(ue,e)}async deleteSale(e,t){return await(t||this.dbAdapter).delete(ue,e),this.changeQueue.enqueue({type:"delete",model:ue,record:{id:e}}),this.context.logActivity("DeleteSale",{id:e}),{id:e,queued:!0}}async duplicateSale(e,t){let r=await this.getSale(e,t);if(!r)throw new Error(`Sale with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ue,a);return this.changeQueue.enqueue({type:"create",model:ue,record:a}),this.context.logActivity("DuplicateSale",{originalId:e,newId:n}),o}async createSale(e,t,r){let n=await this.dbAdapter.transaction(async i=>{var f,y,v,p,g;let a=((f=this.context.domainServices)==null?void 0:f.uom)||null,o=a?await a.getUomsMap():new Map,s=new Date().toISOString(),c=(y=e.id)!=null?y:P(),u=((v=this.context.config)==null?void 0:v.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",e.date||s):null,l={id:c,userId:e.userId,customerId:e.customerId,sourceOrderId:e.sourceOrderId,status:"completed",date:e.date||s,total:0,ppn:(p=e.ppn)!=null?p:0,pph:(g=e.pph)!=null?g:0,finalTotal:0,transactionCurrencyCode:null,exchangeRate:null,exchangeRateSource:null,totalInBaseCurrency:0,finalTotalInBaseCurrency:0,note:u?this.docNumberPolicy.withNote(e.note,u):e.note,version:1,lastModified:s,deleted:!1},d=[];if(t){let x=t.reduce((b,A)=>{var I;return b+((I=A.unitPrice)!=null?I:0)*A.quantity},0);l.total=x,l.finalTotal=x+l.ppn+l.pph}if(Object.assign(l,this.resolveCurrencySnapshot(e,l.total,l.finalTotal)),await i.create(ue,l),d.push({type:"create",model:ue,record:l}),!t)return{sale:l,syncChanges:d};let m=t.map(x=>({id:P(),saleId:c,...x,version:1,lastModified:s,deleted:!1}));await i.bulkCreate(fe,m);for(let x of m)d.push({type:"create",model:fe,record:x});if(r)if(r.method!=="tempo"){let x=await this.context.domainServices.transaction.recordCashIn({method:r.method,data:{...r.data,referenceType:"sale",referenceId:c},amount:l.finalTotal},i);d.push({type:"create",model:J,record:x})}else{let x=r.dueDate;await this.enforceTempoCustomerCreditPolicy(i,{customerId:l.customerId,receivableAmount:l.finalTotal,referenceId:l.id,dueDate:x,nowIso:s});let b=await this.context.domainServices.receivable.addReceivable({saleId:l.id,customerId:l.customerId,amount:l.finalTotal,dueDate:x,status:"unpaid",paidAmount:0,date:s},i);d.push({type:"create",model:he,record:b})}for(let x of m){let b=this.toBaseQuantity(x.quantity,x.uomId,a,o),A=await this.consumeInventoryLotsForSale(i,{saleId:l.id,saleDate:l.date,productId:x.productId,quantity:x.quantity,uomId:x.uomId});for(let I of A)d.push({type:"update",model:pt,record:I});await this.context.domainServices.inventory.updateStock(x.productId,-b,"sale",ue,l.id,i)}return{sale:l,items:m,syncChanges:d}});for(let i of n.syncChanges)this.changeQueue.enqueue(i);return this.context.eventBus.emit("sale:finalized",n.sale.id),t?{sale:n.sale,items:n.items}:n.sale}async finalizeSale(e,t){let r=await this.dbAdapter.transaction(async n=>{var u;let i=((u=this.context.domainServices)==null?void 0:u.uom)||null,a=i?await i.getUomsMap():new Map,o=await this.getSale(e,n);if(!o)throw new Error(`Sale not found for id ${e}`);let s=[];if(t)if(t.method!=="tempo"){let l=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:e},amount:o.finalTotal},n);s.push({type:"create",model:J,record:l})}else{let l=new Date().toISOString();await this.enforceTempoCustomerCreditPolicy(n,{customerId:o.customerId,receivableAmount:o.finalTotal,referenceId:o.id,dueDate:t.dueDate,nowIso:l});let d=await this.context.domainServices.receivable.addReceivable({saleId:o.id,customerId:o.customerId,amount:o.finalTotal,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:l},n);s.push({type:"create",model:he,record:d})}let c=await n.query(fe,{filters:{saleId:e}});for(let l of c){let d=this.toBaseQuantity(l.quantity,l.uomId,i,a),m=await this.consumeInventoryLotsForSale(n,{saleId:e,saleDate:o.date,productId:l.productId,quantity:l.quantity,uomId:l.uomId});for(let f of m)s.push({type:"update",model:pt,record:f});await this.context.domainServices.inventory.updateStock(l.productId,-d,"sale",ue,e,n)}return{saleId:e,syncChanges:s}});for(let n of r.syncChanges)this.changeQueue.enqueue(n);this.context.eventBus.emit("sale:finalized",r.saleId)}async createSaleFromOrder(e,t){let r=await this.dbAdapter.transaction(async n=>{var b,A,I,F;let i=((b=this.context.domainServices)==null?void 0:b.uom)||null,a=i?await i.getUomsMap():new Map,o=await n.get(oe,e);if(!o)throw new Error(`Order not found for id ${e}`);let s=await n.query(xe,{filters:{orderId:e,deleted:!1}}),c=new Date().toISOString(),u=P(),l=((A=this.context.config)==null?void 0:A.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",o.date||c):null,d=[],m=s.reduce((w,q)=>w+(q.unitPrice||0)*q.quantity,0),f=(I=o.ppn)!=null?I:0,y=(F=o.pph)!=null?F:0,v=m+f+y,p=this.resolveCurrencySnapshot(o,m,v),g={id:u,userId:o.userId,customerId:o.customerId,sourceOrderId:o.id,discountCode:o.discountCode||null,status:"completed",date:o.date,total:m,discount:0,ppn:f,pph:y,finalTotal:v,...p,note:l?this.docNumberPolicy.withNote(o.note,l):o.note,version:1,lastModified:c,deleted:!1};await n.create(ue,g),d.push({type:"create",model:ue,record:g});let x=s.map(w=>({id:P(),saleId:u,productId:w.productId,quantity:w.quantity,uomId:w.uomId,unitPrice:w.unitPrice,version:1,lastModified:c,deleted:!1}));await n.bulkCreate(fe,x);for(let w of x)d.push({type:"create",model:fe,record:w});if(await n.update(oe,e,{status:"completed",saleId:u,lastModified:c}),d.push({type:"update",model:oe,record:{id:e,status:"completed",saleId:u,lastModified:c}}),t.method!=="tempo"){let w=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:u},amount:g.finalTotal},n);d.push({type:"create",model:J,record:w})}else{let w=t.dueDate;await this.enforceTempoCustomerCreditPolicy(n,{customerId:g.customerId,receivableAmount:g.finalTotal,referenceId:g.id,dueDate:w,nowIso:c});let q=await this.context.domainServices.receivable.addReceivable({saleId:g.id,customerId:g.customerId,amount:g.finalTotal,dueDate:w,status:"unpaid",paidAmount:0,date:c},n);d.push({type:"create",model:he,record:q})}for(let w of x){let q=this.toBaseQuantity(w.quantity,w.uomId,i,a),M=await this.consumeInventoryLotsForSale(n,{saleId:u,saleDate:g.date,productId:w.productId,quantity:w.quantity,uomId:w.uomId});for(let E of M)d.push({type:"update",model:pt,record:E});await this.context.domainServices.inventory.updateStock(w.productId,-q,"sale",ue,u,n)}return{sale:g,items:x,saleId:u,syncChanges:d}});for(let n of r.syncChanges)this.changeQueue.enqueue(n);return this.context.eventBus.emit("sale:finalized",r.saleId),{sale:r.sale,items:r.items}}async createSaleFromCart(e,t){var s;let r=this.context.domainServices.pricing,n=await this.context.domainServices.cart.getCart(e);if(!n)throw new Error(`Cart not found for id ${e}`);let i=(s=this.context.domainServices)==null?void 0:s.uom,a=await i.getUomsMap(),o=await this.dbAdapter.transaction(async c=>{var I,F,w,q;let u=n.customerId?await this.context.domainServices.customer.getCustomer(n.customerId,c):void 0,l=await r.calculateOrderTotal(n.items,n.discountCode,(u==null?void 0:u.groupId)||void 0),d=await r.calculatePPN(l.subTotal),m=await r.calculatePPH(l.subTotal),f=l.total+d+m,y=this.resolveCurrencySnapshot(n,l.subTotal,f),v=new Date().toISOString(),p=P(),g=((I=this.context.config)==null?void 0:I.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",v):null,x={id:p,userId:((w=(F=this.context)==null?void 0:F.session)==null?void 0:w.userId)||"",customerId:n.customerId||null,sourceOrderId:null,discountCode:n.discountCode||null,status:"completed",date:v,total:l.subTotal,discount:l.discount,ppn:d,pph:m,finalTotal:f,...y,note:g?this.docNumberPolicy.withNote(n.note||null,g):n.note||null,version:1,lastModified:v,deleted:!1},b=n.items.map(M=>({id:P(),saleId:p,productId:M.productId,quantity:M.quantity,uomId:M.uomId||null,unitPrice:M.unitPrice,version:1,lastModified:v,deleted:!1})),A=[];await c.create(ue,x),await c.bulkCreate(fe,b),A.push({type:"create",model:ue,record:x});for(let M of b)A.push({type:"create",model:fe,record:M});if(t.method!=="tempo"){let M=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:p},amount:x.finalTotal},c);A.push({type:"create",model:J,record:M})}else{let M=t.dueDate;await this.enforceTempoCustomerCreditPolicy(c,{customerId:x.customerId,receivableAmount:x.finalTotal,referenceId:x.id,dueDate:M,nowIso:v});let E=await this.context.domainServices.receivable.addReceivable({saleId:x.id,customerId:x.customerId,amount:x.finalTotal,dueDate:M,status:"unpaid",paidAmount:0,date:v},c);A.push({type:"create",model:he,record:E})}for(let M of b){let E=typeof M.uomId=="string"&&((q=a.get(M.uomId))==null?void 0:q.conversionFactor)||1,L=i.convertQuantity(M.quantity,{conversionFactor:E},{conversionFactor:1}),Q=await this.consumeInventoryLotsForSale(c,{saleId:p,saleDate:x.date,productId:M.productId,quantity:M.quantity,uomId:M.uomId});for(let T of Q)A.push({type:"update",model:pt,record:T});await this.context.domainServices.inventory.updateStock(M.productId,-L,"sale",ue,x.id,c)}return{sale:x,items:b,syncChanges:A}});for(let c of o.syncChanges)this.changeQueue.enqueue(c);this.context.eventBus.emit("sale:finalized",o.sale.id);try{await this.context.domainServices.cart.deleteCart(e)}catch(c){this.context.logError(c,{message:`Sale created but failed to delete cart ${e}`})}return{sale:o.sale,items:o.items}}};var en=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addSaleItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(fe,i);return this.changeQueue.enqueue({type:"create",model:fe,record:a}),this.context.logActivity("AddSaleItem",{id:r}),a}async updateSaleItem(e,t,r){let n=await(r||this.dbAdapter).get(fe,e);if(!n)throw new Error(`SaleItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(fe,e,a);return this.changeQueue.enqueue({type:"update",model:fe,record:o}),this.context.logActivity("UpdateSaleItem",{id:e}),o}async getSaleItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(fe,{...e,filters:i})}async getSaleItem(e,t){return(t||this.dbAdapter).get(fe,e)}async deleteSaleItem(e,t){return await(t||this.dbAdapter).delete(fe,e),this.changeQueue.enqueue({type:"delete",model:fe,record:{id:e}}),this.context.logActivity("DeleteSaleItem",{id:e}),{id:e,queued:!0}}async duplicateSaleItem(e,t){let r=await this.getSaleItem(e,t);if(!r)throw new Error(`SaleItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(fe,a);return this.changeQueue.enqueue({type:"create",model:fe,record:a}),this.context.logActivity("DuplicateSaleItem",{originalId:e,newId:n}),o}};var le="shifts";var Jt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addShift(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(le,i);return this.changeQueue.enqueue({type:"create",model:le,record:a}),this.context.logActivity("AddShift",{id:r}),a}async updateShift(e,t,r){let n=await(r||this.dbAdapter).get(le,e);if(!n)throw new Error(`Shift with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(le,e,a);return this.changeQueue.enqueue({type:"update",model:le,record:o}),this.context.logActivity("UpdateShift",{id:e}),o}async getShifts(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(le,{...e,filters:i})}async getShift(e,t){return(t||this.dbAdapter).get(le,e)}async deleteShift(e,t){return await(t||this.dbAdapter).delete(le,e),this.changeQueue.enqueue({type:"delete",model:le,record:{id:e}}),this.context.logActivity("DeleteShift",{id:e}),{id:e,queued:!0}}async duplicateShift(e,t){let r=await this.getShift(e,t);if(!r)throw new Error(`Shift with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(le,a);return this.changeQueue.enqueue({type:"create",model:le,record:a}),this.context.logActivity("DuplicateShift",{originalId:e,newId:n}),o}async openShift(e,t,r){return this.dbAdapter.transaction(async n=>{var c;if(await this.getActiveShift(e))throw new Error("Kasir ini masih memiliki shift yang aktif");let a=new Date().toISOString(),o=P(),s={id:o,cashierId:e,cashierName:((c=this.context.session)==null?void 0:c.userId)||"Unknown",openedAt:a,closedAt:null,startingCash:t,endingCash:null,systemCash:null,cashDifference:null,status:"open",note:r||null,version:1,lastModified:a,deleted:!1};return await n.create(le,s),this.changeQueue.enqueue({type:"create",model:le,record:s}),this.context.eventBus.emit("shift:opened",{shiftId:o,cashierId:e,startingCash:t}),s})}async closeShift(e,t,r){let n=typeof r=="string"?r:r==null?void 0:r.note,i=typeof r=="string"||r==null?void 0:r.approval;return this.dbAdapter.transaction(async a=>{var p,g,x,b;let o=await a.get(le,e);if(!o||o.deleted||o.status!=="open")throw new Error("Shift tidak ditemukan atau sudah ditutup");let s=await a.query(J,{aggregates:[{function:"SUM",field:"amount",as:"cashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashOut",filter:{and:[{field:"referenceType",operator:"IN",value:["sale_return","expense"]},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:o.openedAt},{field:"date",operator:"<",value:new Date(new Date().getTime()+1e3).toISOString()},{field:"deleted",operator:"=",value:!1}]}}),c=((p=s==null?void 0:s[0])==null?void 0:p.cashIn)||0,u=((g=s==null?void 0:s[0])==null?void 0:g.cashOut)||0,l=c-u,d=o.startingCash+l,m=t-d,f=Math.abs(m);if((x=this.context.config)!=null&&x.requireShiftCloseApprovalOnDifference){let A=(b=this.context.config)==null?void 0:b.shiftCloseDifferenceApprovalThreshold,I=typeof A=="number"&&A>=0?A:0;if(f>I){let F=String((i==null?void 0:i.approvedBy)||"").trim(),w=String((i==null?void 0:i.reason)||"").trim();if(!F||!w)throw new Error(`Shift close approval is required when cash difference exceeds ${I}`)}}let y=i?`[CLOSE_APPROVED_BY=${i.approvedBy}] [CLOSE_APPROVAL_REASON=${i.reason}]`:"",v={closedAt:new Date().toISOString(),endingCash:t,systemCash:d,cashDifference:m,status:"closed",note:[o.note||"",n||"",y].filter(Boolean).join(" | ")||null,lastModified:new Date().toISOString()};return await a.update(le,e,v),this.changeQueue.enqueue({type:"update",model:le,id:e,record:v}),this.context.eventBus.emit("shift:closed",{shiftId:e,cashierId:o.cashierId,systemEndingCash:d,physicalEndingCash:t,difference:m}),i&&this.context.logActivity("CloseShiftApproval",{shiftId:e,cashierId:o.cashierId,approvedBy:i.approvedBy,reason:i.reason,cashDifference:m},a),{...o,...v}})}async reopenShift(e,t){let r=String(t.approvedBy||"").trim(),n=String(t.reason||"").trim();if(!r)throw new Error("approvedBy is required to reopen shift");if(!n)throw new Error("reason is required to reopen shift");return this.dbAdapter.transaction(async i=>{var m;let a=await i.get(le,e);if(!a||a.deleted)throw new Error("Shift tidak ditemukan");if(a.status!=="closed")throw new Error("Hanya shift berstatus closed yang dapat di-reopen");if(await this.getActiveShift(a.cashierId))throw new Error("Kasir ini masih memiliki shift yang aktif");let s=new Date().toISOString(),c=P(),u=t.startingCash!=null?t.startingCash:(m=a.endingCash)!=null?m:a.startingCash,l=[a.note||"",`[REOPEN_FROM=${e}]`,`[APPROVED_BY=${r}]`,`[REASON=${n}]`].filter(Boolean),d={id:c,cashierId:a.cashierId,cashierName:a.cashierName,openedAt:s,closedAt:null,startingCash:u,endingCash:null,systemCash:null,cashDifference:null,status:"open",note:l.join(" "),version:1,lastModified:s,deleted:!1};return await i.create(le,d),this.changeQueue.enqueue({type:"create",model:le,record:d}),this.context.logActivity("ReopenShiftApproved",{fromShiftId:e,reopenedShiftId:c,cashierId:a.cashierId,approvedBy:r,reason:n},i),this.context.eventBus.emit("shift:reopened",{fromShiftId:e,reopenedShiftId:c,cashierId:a.cashierId,approvedBy:r}),d})}async getActiveShift(e){let t=await this.dbAdapter.query(le,{filters:{cashierId:e,status:"open",deleted:!1},limit:1});return(t==null?void 0:t[0])||null}async getShiftsByDate(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`;return this.dbAdapter.query(le,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]},sort:[{field:"openedAt",direction:"asc"}]})}async closeShiftPreview(e){let t=await this.dbAdapter.get(le,e);if(!t)throw new Error("Shift tidak ditemukan");let r=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"cashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashOut",filter:{and:[{field:"referenceType",operator:"IN",value:["sale_return","expense"]},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:t.openedAt},{field:"deleted",operator:"=",value:!1}]}});return{cashIn:(r==null?void 0:r.cashIn)||0,cashOut:(r==null?void 0:r.cashOut)||0}}async getDailyReport(e){var d,m,f;let t=await this.getShiftsByDate(e),r=0,n=0,i=0;for(let y of t)r+=y.startingCash,y.status==="closed"&&(n+=y.endingCash||0,i+=y.systemCash||0);let a=`${e}T00:00:00.000Z`,o=`${e}T23:59:59.999Z`,s=await this.dbAdapter.query(J,{aggregates:[{function:"SUM",field:"amount",as:"salesCash",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"returnsCash",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"expenses",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:a},{field:"date",operator:"<=",value:o},{field:"deleted",operator:"=",value:!1}]}}),c=((d=s==null?void 0:s[0])==null?void 0:d.salesCash)||0,u=((m=s==null?void 0:s[0])==null?void 0:m.returnsCash)||0,l=((f=s==null?void 0:s[0])==null?void 0:f.expenses)||0;return{date:e,totalSalesCash:c,totalReturnsCash:u,totalExpenses:l,netCashMovement:c-u-l,startingCash:r,systemEndingCash:i,physicalEndingCash:n,cashDifference:n-i,shifts:t}}};var Ee="tax_rates";var tn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addTaxRate(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ee,i);return this.changeQueue.enqueue({type:"create",model:Ee,record:a}),this.context.logActivity("AddTaxRate",{id:r}),a}async updateTaxRate(e,t,r){let n=await(r||this.dbAdapter).get(Ee,e);if(!n)throw new Error(`TaxRate with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ee,e,a);return this.changeQueue.enqueue({type:"update",model:Ee,record:o}),this.context.logActivity("UpdateTaxRate",{id:e}),o}async getTaxRates(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ee,{...e,filters:i})}async getTaxRate(e,t){return(t||this.dbAdapter).get(Ee,e)}async deleteTaxRate(e,t){return await(t||this.dbAdapter).delete(Ee,e),this.changeQueue.enqueue({type:"delete",model:Ee,record:{id:e}}),this.context.logActivity("DeleteTaxRate",{id:e}),{id:e,queued:!0}}async duplicateTaxRate(e,t){let r=await this.getTaxRate(e,t);if(!r)throw new Error(`TaxRate with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ee,a);return this.changeQueue.enqueue({type:"create",model:Ee,record:a}),this.context.logActivity("DuplicateTaxRate",{originalId:e,newId:n}),o}};var er=class{constructor(e){this.context=e;this.allowedReferenceTypes=new Set(["sale","purchase","sale_return","purchase_return","sale_return_cancelled","purchase_return_cancelled","receivable_payment","payable_payment","cash_adjustment","expense"]);var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async getIdempotentTransaction(e,t,r){let n=r||this.dbAdapter,i=await n.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:"idempotency_keys"},{field:"recordId",operator:"=",value:t},{field:"action",operator:"=",value:`transaction_${e}`}]},sort:[{field:"timestamp",direction:"desc"}],limit:1});if(!i.length)return null;let a=i[0].changes||{},o=String(a.transactionId||"").trim();return o?n.get(J,o):null}async saveIdempotencyMarker(e,t,r,n){var i;await n.create(ie,{id:P(),tableName:"idempotency_keys",recordId:t,action:`transaction_${e}`,changes:{transactionId:r,action:e},userId:String(((i=this.context.session)==null?void 0:i.userId)||"").trim()||null,timestamp:new Date().toISOString()})}getActorId(e){var n,i,a;let t=String(((n=this.context.session)==null?void 0:n.userId)||"").trim();return t||String(((i=e==null?void 0:e.data)==null?void 0:i.userId)||((a=e==null?void 0:e.data)==null?void 0:a.cashierId)||"").trim()}isShiftGuardEnabled(){var e;return((e=this.context.config)==null?void 0:e.requireActiveShiftForCash)===!0}shouldRequireActiveShift(e){return["sale","purchase","sale_return","purchase_return","receivable_payment","payable_payment","expense","cash_adjustment"].includes(e)}async assertActiveShiftGuard(e,t){var o;let r=String(((o=e==null?void 0:e.data)==null?void 0:o.referenceType)||"").trim();if(!this.isShiftGuardEnabled()||!this.shouldRequireActiveShift(r))return;let n=this.getActorId(e);if(!n)throw new Error("Active shift guard: actor userId/cashierId is required");let a=await(t||this.dbAdapter).query("shifts",{filters:{and:[{field:"cashierId",operator:"=",value:n},{field:"status",operator:"=",value:"open"},{field:"deleted",operator:"=",value:!1}]},limit:1});if(!a||a.length===0)throw new Error(`Active shift guard: no open shift for cashier ${n}`)}assertCashPolicy(e){var n,i,a;if(!this.isShiftGuardEnabled())return;let t=String(((n=e==null?void 0:e.data)==null?void 0:n.referenceType)||"").trim(),r=String(((i=e==null?void 0:e.data)==null?void 0:i.reasonCode)||"").trim();if((t==="expense"||t==="cash_adjustment")&&!r)throw new Error(`Cash policy: reasonCode is required for ${t}`);if(t==="cash_adjustment"){let o=(a=this.context.config)==null?void 0:a.maxCashAdjustmentAmount;if(typeof o=="number"&&o>0&&e.amount>o)throw new Error(`Cash policy: cash adjustment exceeds max limit (${o})`)}}assertReferenceIntegrity(e){var n,i;let t=String(((n=e==null?void 0:e.data)==null?void 0:n.referenceType)||"").trim(),r=String(((i=e==null?void 0:e.data)==null?void 0:i.referenceId)||"").trim();if(!t)throw new Error("Cash movement requires referenceType");if(!r)throw new Error("Cash movement requires referenceId");if(!this.allowedReferenceTypes.has(t))throw new Error(`Cash movement referenceType is invalid: ${t}`)}assertIdempotentReplayConsistency(e,t,r){var c,u;let n=t==="cash_in"?"in":"out",i=String(((c=r==null?void 0:r.data)==null?void 0:c.referenceType)||"").trim(),a=String(((u=r==null?void 0:r.data)==null?void 0:u.referenceId)||"").trim(),o=String((r==null?void 0:r.method)||"").trim();if(e.direction!==n||e.amount!==r.amount||String(e.referenceType||"")!==i||String(e.referenceId||"")!==a||String(e.method||"")!==o)throw new Error("Idempotency key reused with different cash transaction payload")}async addTransaction(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(J,i);return t||this.changeQueue.enqueue({type:"create",model:J,record:a}),this.context.logActivity("AddTransaction",{id:r}),a}async updateTransaction(e,t,r){let n=await(r||this.dbAdapter).get(J,e);if(!n)throw new Error(`Transaction with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(J,e,a);return r||this.changeQueue.enqueue({type:"update",model:J,record:o}),this.context.logActivity("UpdateTransaction",{id:e}),o}async getTransactions(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(J,{...e,filters:i})}async getTransaction(e,t){return(t||this.dbAdapter).get(J,e)}async deleteTransaction(e,t){return await(t||this.dbAdapter).delete(J,e),t||this.changeQueue.enqueue({type:"delete",model:J,record:{id:e}}),this.context.logActivity("DeleteTransaction",{id:e}),{id:e,queued:!0}}async duplicateTransaction(e,t){let r=await this.getTransaction(e,t);if(!r)throw new Error(`Transaction with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(J,a);return t||this.changeQueue.enqueue({type:"create",model:J,record:a}),this.context.logActivity("DuplicateTransaction",{originalId:e,newId:n}),o}async recordCashIn(e,t){var l,d;let r=(l=this.context.registry)==null?void 0:l.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((d=e==null?void 0:e.data)==null?void 0:d.idempotencyKey)||"").trim();if(n){let m=await this.getIdempotentTransaction("cash_in",n,t);if(m)return this.assertIdempotentReplayConsistency(m,"cash_in",e),m}let i=this.getActorId(e),a=P(),o=t||this.dbAdapter,s=1,c=new Date().toISOString(),u={id:a,referenceType:e.data.referenceType,referenceId:e.data.referenceId,direction:"in",amount:e.amount,method:e.method,metadata:e.data,date:new Date().toISOString(),description:e.method,userId:i,version:s,lastModified:c,deleted:!1};try{let m=await o.create(J,u);return n&&await this.saveIdempotencyMarker("cash_in",n,m.id,o),t||this.changeQueue.enqueue({type:"create",model:J,record:m}),this.context.logActivity("RecordCashIn",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash in recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashIn"}),m}catch(m){throw r.logError("Error recording cash in",{id:a,method:e.method,amount:e.amount,error:m}),m}}async recordCashOut(e,t){var l,d;let r=(l=this.context.registry)==null?void 0:l.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((d=e==null?void 0:e.data)==null?void 0:d.idempotencyKey)||"").trim();if(n){let m=await this.getIdempotentTransaction("cash_out",n,t);if(m)return this.assertIdempotentReplayConsistency(m,"cash_out",e),m}let i=this.getActorId(e),a=P(),o=t||this.dbAdapter,s=1,c=new Date().toISOString(),u={id:a,referenceType:e.data.referenceType,referenceId:e.data.referenceId,direction:"out",amount:e.amount,method:e.method,metadata:e.data,date:new Date().toISOString(),description:e.method,userId:i,version:s,lastModified:c,deleted:!1};try{let m=await o.create(J,u);return n&&await this.saveIdempotencyMarker("cash_out",n,m.id,o),t||this.changeQueue.enqueue({type:"create",model:J,record:m}),this.context.logActivity("RecordCashOut",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash out recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashOut"}),m}catch(m){throw r.logError("Error recording cash out",{id:a,method:e.method,amount:e.amount,error:m}),m}}async adjustCash(e,t,r,n){var o,s;if(e<=0)throw new Error("Amount must be positive");let a={method:"cash",data:{referenceType:"cash_adjustment",referenceId:`adj-${new Date().toISOString().split("T")[0]}-${Date.now()}`,reason:r,reasonCode:"manual_adjustment",adjustedBy:((o=this.context.session)==null?void 0:o.userId)||"",userId:((s=this.context.session)==null?void 0:s.userId)||""},amount:e};return t==="in"?this.recordCashIn(a,n):this.recordCashOut(a,n)}async getTransactionsByReference(e,t,r,n){let i=n||this.dbAdapter,a={deleted:!1,referenceType:e,...t!==void 0?{referenceId:t}:{}},o=r!=null&&r.filters?{and:[r.filters,a]}:a;return await i.query(J,{...r,filters:o})}async getDailySummary(e){let t=e||new Date().toISOString().slice(0,10),r=await this.dbAdapter.query(J,{filters:{field:"date",operator:"LIKE",value:`${t}%`}}),n=r.filter(a=>a.direction==="in").reduce((a,o)=>a+o.amount,0),i=r.filter(a=>a.direction==="out").reduce((a,o)=>a+o.amount,0);return{totalIn:n,totalOut:i,net:n-i,date:t}}};var nt="uoms";function fo(h,e){return h*e}function go(h,e){return e!==0?h/e:NaN}var tr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addUom(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(nt,i);return this.changeQueue.enqueue({type:"create",model:nt,record:a}),this.context.logActivity("AddUom",{id:r}),a}async updateUom(e,t,r){let n=await(r||this.dbAdapter).get(nt,e);if(!n)throw new Error(`Uom with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(nt,e,a);return this.changeQueue.enqueue({type:"update",model:nt,record:o}),this.context.logActivity("UpdateUom",{id:e}),o}async getUoms(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(nt,{...e,filters:i})}async getUom(e,t){return(t||this.dbAdapter).get(nt,e)}async deleteUom(e,t){return await(t||this.dbAdapter).delete(nt,e),this.changeQueue.enqueue({type:"delete",model:nt,record:{id:e}}),this.context.logActivity("DeleteUom",{id:e}),{id:e,queued:!0}}async duplicateUom(e,t){let r=await this.getUom(e,t);if(!r)throw new Error(`Uom with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(nt,a);return this.changeQueue.enqueue({type:"create",model:nt,record:a}),this.context.logActivity("DuplicateUom",{originalId:e,newId:n}),o}convertQuantity(e,t,r){let n=fo(e,t.conversionFactor);return go(n,r.conversionFactor)}convertUnitPrice(e,t,r){if(t.conversionFactor<=0||r.conversionFactor<=0)throw new Error("conversionFactor must be > 0");return e*(r.conversionFactor/t.conversionFactor)}async getUomsMap(){let e=await this.getUoms();return new Map(e.map(t=>[t.id,t]))}};var $e="users";var rn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addUser(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create($e,i);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("AddUser",{id:r}),a}async updateUser(e,t,r){let n=await(r||this.dbAdapter).get($e,e);if(!n)throw new Error(`User with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update($e,e,a);return this.changeQueue.enqueue({type:"update",model:$e,record:o}),this.context.logActivity("UpdateUser",{id:e}),o}async getUsers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query($e,{...e,filters:i})}async getUser(e,t){return(t||this.dbAdapter).get($e,e)}async deleteUser(e,t){return await(t||this.dbAdapter).delete($e,e),this.changeQueue.enqueue({type:"delete",model:$e,record:{id:e}}),this.context.logActivity("DeleteUser",{id:e}),{id:e,queued:!0}}async duplicateUser(e,t){let r=await this.getUser(e,t);if(!r)throw new Error(`User with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create($e,a);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("DuplicateUser",{originalId:e,newId:n}),o}};var Ke="suppliers";var rr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addSupplier(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ke,i);return this.changeQueue.enqueue({type:"create",model:Ke,record:a}),this.context.logActivity("AddSupplier",{id:r}),a}async updateSupplier(e,t,r){let n=await(r||this.dbAdapter).get(Ke,e);if(!n)throw new Error(`Supplier with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ke,e,a);return this.changeQueue.enqueue({type:"update",model:Ke,record:o}),this.context.logActivity("UpdateSupplier",{id:e}),o}async getSuppliers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ke,{...e,filters:i})}async getSupplier(e,t){return(t||this.dbAdapter).get(Ke,e)}async deleteSupplier(e,t){return await(t||this.dbAdapter).delete(Ke,e),this.changeQueue.enqueue({type:"delete",model:Ke,record:{id:e}}),this.context.logActivity("DeleteSupplier",{id:e}),{id:e,queued:!0}}async duplicateSupplier(e,t){let r=await this.getSupplier(e,t);if(!r)throw new Error(`Supplier with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ke,a);return this.changeQueue.enqueue({type:"create",model:Ke,record:a}),this.context.logActivity("DuplicateSupplier",{originalId:e,newId:n}),o}async searchSuppliers(e,t,r){let n=e.trim();if(!n)return[];let i=r||this.dbAdapter,a={and:[{or:[{field:"name",operator:"like",value:`%${n}%`},{field:"contactPerson",operator:"like",value:`%${n}%`},{field:"phone",operator:"like",value:`%${n}%`},{field:"email",operator:"like",value:`%${n}%`}]},{deleted:!1}]};return i.query(Ke,{...t,filters:a})}};var _e="purchase_orders";var nr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPurchaseOrder(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(_e,i);return this.changeQueue.enqueue({type:"create",model:_e,record:a}),this.context.logActivity("AddPurchaseOrder",{id:r}),a}async updatePurchaseOrder(e,t,r){let n=await(r||this.dbAdapter).get(_e,e);if(!n)throw new Error(`PurchaseOrder with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(_e,e,a);return this.changeQueue.enqueue({type:"update",model:_e,record:o}),this.context.logActivity("UpdatePurchaseOrder",{id:e}),o}async getPurchaseOrders(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(_e,{...e,filters:i})}async getPurchaseOrder(e,t){return(t||this.dbAdapter).get(_e,e)}async deletePurchaseOrder(e,t){return await(t||this.dbAdapter).delete(_e,e),this.changeQueue.enqueue({type:"delete",model:_e,record:{id:e}}),this.context.logActivity("DeletePurchaseOrder",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrder(e,t){let r=await this.getPurchaseOrder(e,t);if(!r)throw new Error(`PurchaseOrder with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(_e,a);return this.changeQueue.enqueue({type:"create",model:_e,record:a}),this.context.logActivity("DuplicatePurchaseOrder",{originalId:e,newId:n}),o}};var Ve="purchase_order_items";var nn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPurchaseOrderItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ve,i);return this.changeQueue.enqueue({type:"create",model:Ve,record:a}),this.context.logActivity("AddPurchaseOrderItem",{id:r}),a}async updatePurchaseOrderItem(e,t,r){let n=await(r||this.dbAdapter).get(Ve,e);if(!n)throw new Error(`PurchaseOrderItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ve,e,a);return this.changeQueue.enqueue({type:"update",model:Ve,record:o}),this.context.logActivity("UpdatePurchaseOrderItem",{id:e}),o}async getPurchaseOrderItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ve,{...e,filters:i})}async getPurchaseOrderItem(e,t){return(t||this.dbAdapter).get(Ve,e)}async deletePurchaseOrderItem(e,t){return await(t||this.dbAdapter).delete(Ve,e),this.changeQueue.enqueue({type:"delete",model:Ve,record:{id:e}}),this.context.logActivity("DeletePurchaseOrderItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrderItem(e,t){let r=await this.getPurchaseOrderItem(e,t);if(!r)throw new Error(`PurchaseOrderItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ve,a);return this.changeQueue.enqueue({type:"create",model:Ve,record:a}),this.context.logActivity("DuplicatePurchaseOrderItem",{originalId:e,newId:n}),o}};var Se="purchases";var ge="payables";var ze="financial_settings";var ir=class{constructor(e){this.context=e;this.defaultBaseCurrencyCode="IDR";var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e),this.docNumberPolicy=new It(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t){var o,s,c;let r=(o=e.transactionCurrencyCode)!=null?o:this.defaultBaseCurrencyCode,n=(s=e.exchangeRate)!=null?s:1,i=Number.isFinite(n)&&n>0?Number(n):1,a=this.roundCurrencyAmount(e.totalInBaseCurrency!=null?Number(e.totalInBaseCurrency):t*i);return{transactionCurrencyCode:r,exchangeRate:i,exchangeRateSource:(c=e.exchangeRateSource)!=null?c:"snapshot.manual",totalInBaseCurrency:a}}toBaseQuantity(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertQuantity(e,{conversionFactor:i},{conversionFactor:1}):e}toBaseUnitCost(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertUnitPrice(e,{conversionFactor:i},{conversionFactor:1}):e}async getCostingMethod(e){var n;let t=await e.query(ze,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}],limit:1});return String(((n=t[0])==null?void 0:n.costingMethod)||"FIFO").trim().toUpperCase()==="AVERAGE"?"AVERAGE":"FIFO"}async applyCostingPolicy(e,t){var a;if(!t.length)return;let r=(a=this.context.domainServices)==null?void 0:a.inventory,n=await this.getCostingMethod(e),i=new Map;for(let o of t){let s=Number(o.quantity),c=Number(o.unitCost);if(!Number.isFinite(s)||!Number.isFinite(c)||s<=0)continue;let u=i.get(o.productId)||{quantity:0,totalCost:0};u.quantity+=s,u.totalCost+=s*c,i.set(o.productId,u)}for(let[o,s]of i.entries()){let c=await e.get(ce,o);if(!c||c.deleted)continue;let u=s.totalCost/s.quantity,l=await r.getStock(o),d=c.cost;if(n==="AVERAGE"){let y=Math.max(0,Number(l)||0),v=y+s.quantity;v>0?d=(c.cost*y+s.totalCost)/v:d=u}else(Number(l)||0)<=0&&(d=u);if(!Number.isFinite(d)||d===c.cost)continue;let m=new Date().toISOString(),f=await e.update(ce,o,{cost:d,version:c.version+1,lastModified:m});this.changeQueue.enqueue({type:"update",model:ce,record:f})}}async addPurchase(e,t){var c;let r=P(),n=new Date().toISOString(),i=((c=this.context.config)==null?void 0:c.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",e.date||n):null,a=this.resolveCurrencySnapshot(e,Number(e.total||0)),o={id:r,...e,...a,note:i?this.docNumberPolicy.withNote(e.note,i):e.note,version:1,lastModified:n,deleted:!1},s=await(t||this.dbAdapter).create(Se,o);return this.changeQueue.enqueue({type:"create",model:Se,record:s}),this.context.logActivity("AddPurchase",{id:r}),s}async updatePurchase(e,t,r){let n=await(r||this.dbAdapter).get(Se,e);if(!n)throw new Error(`Purchase with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Se,e,a);return this.changeQueue.enqueue({type:"update",model:Se,record:o}),this.context.logActivity("UpdatePurchase",{id:e}),o}async getPurchases(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Se,{...e,filters:i})}async getPurchase(e,t){return(t||this.dbAdapter).get(Se,e)}async deletePurchase(e,t){return await(t||this.dbAdapter).delete(Se,e),this.changeQueue.enqueue({type:"delete",model:Se,record:{id:e}}),this.context.logActivity("DeletePurchase",{id:e}),{id:e,queued:!0}}async duplicatePurchase(e,t){let r=await this.getPurchase(e,t);if(!r)throw new Error(`Purchase with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Se,a);return this.changeQueue.enqueue({type:"create",model:Se,record:a}),this.context.logActivity("DuplicatePurchase",{originalId:e,newId:n}),o}async finalizePurchase(e,t,r){var f,y,v;if(!r){let p=await this.dbAdapter.transaction(async g=>this.finalizePurchase(e,t,g));return this.context.eventBus.emit("purchase:finalized",e),p}let n=(y=(f=this.context)==null?void 0:f.domainServices)==null?void 0:y.inventory,i=((v=this.context.domainServices)==null?void 0:v.uom)||null,a=i?await i.getUomsMap():new Map,o=await r.get(Se,e);if(!o)throw new Error(`Purchase not found for id ${e}`);let s=await r.query(De,{filters:{and:[{field:"purchaseId",value:e},{field:"deleted",value:!1}]}}),c=s.reduce((p,g)=>p+g.unitCost*g.quantity,0),u=Date.now(),l=new Date().toISOString(),d=this.resolveCurrencySnapshot(o,c);await r.update(Se,e,{total:c,...d,version:u,lastModified:l});let m={...o,total:c,...d,version:u,lastModified:l};await this.applyCostingPolicy(r,s.map(p=>({productId:p.productId,quantity:this.toBaseQuantity(p.quantity,p.uomId,i,a),unitCost:this.toBaseUnitCost(p.unitCost,p.uomId,i,a)})));for(let p of s)await n.updateStock(p.productId,this.toBaseQuantity(p.quantity,p.uomId,i,a),"purchase",Se,e,r);return await this.context.domainServices.priceHistory.recordPriceHistory(s.map(p=>({productId:p.productId,unitCost:this.toBaseUnitCost(p.unitCost,p.uomId,i,a),supplierId:o.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:m.supplierId,purchaseId:m.id,amount:m.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:m.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:m.total,method:t.method,data:{referenceType:"purchase",referenceId:m.id,...t.data||{}}},r),this.changeQueue.enqueue({type:"update",model:Se,record:m}),{purchase:m,queued:!0}}async receivePurchaseFromPO(e,t,r){var E,L,Q,T,j,z;if(!r){let B=await this.dbAdapter.transaction(async U=>this.receivePurchaseFromPO(e,t,U));return this.context.eventBus.emit("purchase:finalized",B.purchase.id),B}let n=(L=(E=this.context)==null?void 0:E.domainServices)==null?void 0:L.inventory,i=((Q=this.context.domainServices)==null?void 0:Q.uom)||null,a=i?await i.getUomsMap():new Map,o=await r.get(_e,e);if(!o)throw new Error(`PurchaseOrder not found for id ${e}`);if(o.status!=="draft"&&o.status!=="sent"&&o.status!=="partially_received")throw new Error(`PurchaseOrder with id ${e} cannot be received as it is not in draft/sent/partially_received status`);let s=await r.query(Ve,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}}),u=(await r.query(Se,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}})).map(B=>B.id),l=new Map;if(u.length>0){let B=await r.query(De,{filters:{and:[{field:"deleted",value:!1},{or:u.map(U=>({field:"purchaseId",value:U}))}]}});for(let U of B)U.purchaseOrderItemId&&l.set(U.purchaseOrderItemId,(l.get(U.purchaseOrderItemId)||0)+Number(U.quantity||0))}let d=new Map(s.map(B=>[B.id,B])),m=new Map;for(let B of s){let U=m.get(B.productId)||[];U.push(B),m.set(B.productId,U)}let f=[],y=Array.isArray(t.receivedItems)?t.receivedItems:null;if(y&&y.length>0){let B=((T=this.context.config)==null?void 0:T.requireLotExpiryForPurchaseReceiving)===!0;for(let U of y){let _=U.purchaseOrderItemId?d.get(U.purchaseOrderItemId):void 0;if(!_&&U.productId){let se=m.get(U.productId)||[];if(se.length===1)_=se[0];else if(se.length>1)throw new Error(`Ambiguous productId ${U.productId}: provide purchaseOrderItemId for partial receiving`)}if(!_)throw new Error("Invalid partial receiving payload: source purchase order item not found");let R=Number(U.receivedQuantity);if(!Number.isFinite(R)||R<=0)throw new Error("Invalid partial receiving payload: receivedQuantity must be > 0");let D=l.get(_.id)||0,Z=f.filter(se=>se.sourceOrderItem.id===_.id).reduce((se,Ne)=>se+Ne.quantity,0),te=Number(_.quantity)-D-Z;if(R>te)throw new Error(`Partial receiving exceeds remaining quantity for PO item ${_.id}`);let X=U.unitCost!=null?Number(U.unitCost):Number(_.unitCost);if(!Number.isFinite(X)||X<0)throw new Error("Invalid partial receiving payload: unitCost must be >= 0");let Y=U.serialNumber!=null?String(U.serialNumber).trim():"";if(Y&&R!==1)throw new Error("Serial-number receiving currently requires receivedQuantity = 1");f.push({sourceOrderItem:_,quantity:R,unitCost:X,uomId:U.uomId!==void 0?U.uomId:_.uomId,lotNumber:U.lotNumber!=null&&String(U.lotNumber).trim()||null,serialNumber:Y||null,expiryDate:U.expiryDate!=null&&String(U.expiryDate).trim()||null,note:U.note!=null?String(U.note):null});let ye=f[f.length-1];if(B){if(!ye.lotNumber)throw new Error("Lot policy violation: lotNumber is required when requireLotExpiryForPurchaseReceiving=true");if(!ye.expiryDate)throw new Error("Lot policy violation: expiryDate is required when requireLotExpiryForPurchaseReceiving=true")}}}else{if(((j=this.context.config)==null?void 0:j.requireLotExpiryForPurchaseReceiving)===!0)throw new Error("Lot policy violation: receivedItems with lotNumber and expiryDate are required when requireLotExpiryForPurchaseReceiving=true");for(let B of s){let U=l.get(B.id)||0,O=Number(B.quantity)-U;O<=0||f.push({sourceOrderItem:B,quantity:O,unitCost:Number(B.unitCost),uomId:B.uomId,lotNumber:null,serialNumber:null,expiryDate:null,note:null})}}if(f.length===0)throw new Error(`PurchaseOrder with id ${e} has no remaining receivable items`);let v=f.reduce((B,U)=>B+U.unitCost*U.quantity,0),p=P(),g=new Date().toISOString(),x=((z=this.context.config)==null?void 0:z.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",o.date||g):null,b={id:p,supplierId:o.supplierId,userId:o.userId,purchaseOrderId:e,date:o.date,total:v,...this.resolveCurrencySnapshot(o,v),note:x?this.docNumberPolicy.withNote(o.note,x):o.note,version:1,lastModified:g,deleted:!1};await r.create(Se,b),this.changeQueue.enqueue({type:"create",model:Se,record:b});for(let B of f){let U=P(),O={id:U,purchaseId:p,purchaseOrderItemId:B.sourceOrderItem.id,productId:B.sourceOrderItem.productId,quantity:B.quantity,uomId:B.uomId,unitCost:B.unitCost,version:1,lastModified:g,deleted:!1};if(await r.create(De,O),this.changeQueue.enqueue({type:"create",model:De,record:O}),B.lotNumber||B.serialNumber||B.expiryDate){let _=this.toBaseQuantity(B.quantity,B.uomId,i,a),R={id:P(),productId:B.sourceOrderItem.productId,purchaseId:p,purchaseItemId:U,purchaseOrderId:e,purchaseOrderItemId:B.sourceOrderItem.id,lotNumber:B.lotNumber,serialNumber:B.serialNumber,expiryDate:B.expiryDate,quantity:_,remainingQuantity:_,status:"active",note:B.note,version:1,lastModified:g,deleted:!1};await r.create(pt,R),this.changeQueue.enqueue({type:"create",model:pt,record:R})}}let A=new Map(l);for(let B of f)A.set(B.sourceOrderItem.id,(A.get(B.sourceOrderItem.id)||0)+B.quantity);let F=s.every(B=>(A.get(B.id)||0)>=Number(B.quantity))?"received":"partially_received",w=Date.now(),q=new Date().toISOString();await r.update(_e,e,{status:F,version:w,lastModified:q}),this.changeQueue.enqueue({type:"update",model:_e,record:{id:e,status:F,version:w,lastModified:q}});let M=f.filter(B=>Number(B.unitCost)!==Number(B.sourceOrderItem.unitCost)).map(B=>({purchaseOrderItemId:B.sourceOrderItem.id,productId:B.sourceOrderItem.productId,orderedUnitCost:B.sourceOrderItem.unitCost,receivedUnitCost:B.unitCost,quantity:B.quantity,varianceAmount:(B.unitCost-B.sourceOrderItem.unitCost)*B.quantity}));M.length>0&&await this.context.logActivity("PO_PRICE_VARIANCE_DETECTED",{purchaseOrderId:e,purchaseId:p,entries:M},r),await this.applyCostingPolicy(r,f.map(B=>({productId:B.sourceOrderItem.productId,quantity:this.toBaseQuantity(B.quantity,B.uomId,i,a),unitCost:this.toBaseUnitCost(B.unitCost,B.uomId,i,a)})));for(let B of f)await n.updateStock(B.sourceOrderItem.productId,this.toBaseQuantity(B.quantity,B.uomId,i,a),"purchase",Se,p,r);return await this.context.domainServices.priceHistory.recordPriceHistory(f.map(B=>({productId:B.sourceOrderItem.productId,unitCost:this.toBaseUnitCost(B.unitCost,B.uomId,i,a),supplierId:o.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:b.supplierId,purchaseId:b.id,amount:b.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:b.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:b.total,method:t.method,data:{referenceType:"purchase",referenceId:b.id,...t.data||{}}},r),{purchase:b,queued:!0}}async createPurchaseFromCart(e){var a,o,s;let t=(o=(a=this.context)==null?void 0:a.domainServices)==null?void 0:o.inventory,r=(s=this.context.domainServices)==null?void 0:s.uom,n=(await r.getUoms()).reduce((c,u)=>({...c,[u.id]:u}),{}),i;try{i=await this.dbAdapter.transaction(async c=>{var g,x;let u=new Date().toISOString(),l=P(),d=((g=this.context.config)==null?void 0:g.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",u):null,m=[],f=e.items.reduce((b,A)=>b+A.unitCost*A.quantity,0),y={id:l,supplierId:e.supplierId,userId:((x=this.context.session)==null?void 0:x.userId)||"",purchaseOrderId:null,date:u,total:f,...this.resolveCurrencySnapshot(e,f),note:d?this.docNumberPolicy.withNote(e.note||null,d):e.note||null,version:1,lastModified:u,deleted:!1};await c.create(Se,y),m.push({type:"create",model:Se,record:y});let v=e.items.map(b=>({id:P(),purchaseId:l,purchaseOrderItemId:null,productId:b.productId,quantity:b.quantity,uomId:b.uomId||null,unitCost:b.unitCost,version:1,lastModified:u,deleted:!1}));await c.bulkCreate(De,v);for(let b of v)m.push({type:"create",model:De,record:b});await this.applyCostingPolicy(c,v.map(b=>{let A=typeof b.uomId=="string"?n[b.uomId].conversionFactor:1;return{productId:b.productId,quantity:r.convertQuantity(b.quantity,{conversionFactor:A},{conversionFactor:1}),unitCost:r.convertUnitPrice(b.unitCost,{conversionFactor:A},{conversionFactor:1})}}));for(let b of v){let A=typeof b.uomId=="string"?n[b.uomId].conversionFactor:1;await t.updateStock(b.productId,r.convertQuantity(b.quantity,{conversionFactor:A},{conversionFactor:1}),"purchase",Se,l,c)}let p=[];for(let b of v){let A=typeof b.uomId=="string"?n[b.uomId].conversionFactor:1;p.push({productId:b.productId,unitCost:r.convertUnitPrice(b.unitCost,{conversionFactor:A},{conversionFactor:1}),supplierId:e.supplierId,effectiveDate:u})}if(await this.context.domainServices.priceHistory.recordPriceHistory(p,c),e.paymentMethod==="tempo"){let b=await this.context.domainServices.payable.addPayable({supplierId:y.supplierId,purchaseId:y.id,amount:y.total,dueDate:e.dueDate,status:"unpaid",paidAmount:0,date:y.date||new Date().toISOString()},c);m.push({type:"create",model:ge,record:b})}else{let b=await this.context.domainServices.transaction.recordCashOut({amount:f,method:e.paymentMethod,data:{referenceType:"purchase",referenceId:l,...e.paymentData||{}}},c);m.push({type:"create",model:J,record:b})}return{purchase:y,items:v,purchaseId:l,syncChanges:m}})}catch(c){throw t.clearStockCache(),c}for(let c of i.syncChanges)this.changeQueue.enqueue(c);return this.context.eventBus.emit("purchase:finalized",i.purchaseId),{purchase:i.purchase,items:i.items}}};var an=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPurchaseItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(De,i);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("AddPurchaseItem",{id:r}),a}async updatePurchaseItem(e,t,r){let n=await(r||this.dbAdapter).get(De,e);if(!n)throw new Error(`PurchaseItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(De,e,a);return this.changeQueue.enqueue({type:"update",model:De,record:o}),this.context.logActivity("UpdatePurchaseItem",{id:e}),o}async getPurchaseItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(De,{...e,filters:i})}async getPurchaseItem(e,t){return(t||this.dbAdapter).get(De,e)}async deletePurchaseItem(e,t){return await(t||this.dbAdapter).delete(De,e),this.changeQueue.enqueue({type:"delete",model:De,record:{id:e}}),this.context.logActivity("DeletePurchaseItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseItem(e,t){let r=await this.getPurchaseItem(e,t);if(!r)throw new Error(`PurchaseItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(De,a);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("DuplicatePurchaseItem",{originalId:e,newId:n}),o}};var Oe="inventory_logs";function _t(h){return{all:h=h||new Map,on:function(e,t){var r=h.get(e);r?r.push(t):h.set(e,[t])},off:function(e,t){var r=h.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):h.set(e,[]))},emit:function(e,t){var r=h.get(e);r&&r.slice().map(function(n){n(t)}),(r=h.get("*"))&&r.slice().map(function(n){n(e,t)})}}}var Le=_t();var ar=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addInventoryLog(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(Oe,i);return this.changeQueue.enqueue({type:"create",model:Oe,record:a}),this.emitStockChanged(a.productId),this.context.logActivity("AddInventoryLog",{id:r}),a}async updateInventoryLog(e,t,r){let n=await(r||this.dbAdapter).get(Oe,e);if(!n)throw new Error(`InventoryLog with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e},o=await(r||this.dbAdapter).update(Oe,e,a);return this.changeQueue.enqueue({type:"update",model:Oe,record:o}),this.emitStockChanged(n.productId),this.emitStockChanged(o.productId),this.context.logActivity("UpdateInventoryLog",{id:e}),o}async getInventoryLogs(e,t){return(t||this.dbAdapter).query(Oe,e)}async getInventoryLog(e,t){return(t||this.dbAdapter).get(Oe,e)}async deleteInventoryLog(e,t){let r=await(t||this.dbAdapter).get(Oe,e);return await(t||this.dbAdapter).delete(Oe,e),this.changeQueue.enqueue({type:"delete",model:Oe,record:{id:e}}),this.emitStockChanged(r==null?void 0:r.productId),this.context.logActivity("DeleteInventoryLog",{id:e}),{id:e,queued:!0}}async duplicateInventoryLog(e,t){let r=await this.getInventoryLog(e,t);if(!r)throw new Error(`InventoryLog with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Oe,a);return this.changeQueue.enqueue({type:"create",model:Oe,record:a}),this.emitStockChanged(o.productId),this.context.logActivity("DuplicateInventoryLog",{originalId:e,newId:n}),o}emitStockChanged(e){var r,n;if(!e)return;let t=(r=this.context.domainServices)==null?void 0:r.inventory;(n=t==null?void 0:t.invalidateProductStock)==null||n.call(t,e),Le.emit("stock:changed",{productId:e,delta:0})}};var Ge="price_histories";var or=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPriceHistory(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ge,i);return this.changeQueue.enqueue({type:"create",model:Ge,record:a}),this.context.logActivity("AddPriceHistory",{id:r}),a}async updatePriceHistory(e,t,r){let n=await(r||this.dbAdapter).get(Ge,e);if(!n)throw new Error(`PriceHistory with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ge,e,a);return this.changeQueue.enqueue({type:"update",model:Ge,record:o}),this.context.logActivity("UpdatePriceHistory",{id:e}),o}async getPriceHistories(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ge,{...e,filters:i})}async getPriceHistory(e,t){return(t||this.dbAdapter).get(Ge,e)}async deletePriceHistory(e,t){return await(t||this.dbAdapter).delete(Ge,e),this.changeQueue.enqueue({type:"delete",model:Ge,record:{id:e}}),this.context.logActivity("DeletePriceHistory",{id:e}),{id:e,queued:!0}}async duplicatePriceHistory(e,t){let r=await this.getPriceHistory(e,t);if(!r)throw new Error(`PriceHistory with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ge,a);return this.changeQueue.enqueue({type:"create",model:Ge,record:a}),this.context.logActivity("DuplicatePriceHistory",{originalId:e,newId:n}),o}async recordPriceHistory(e,t){var n;let r=[];for(let i of e){let a={id:P(),productId:i.productId,unitCost:i.unitCost,supplierId:i.supplierId,effectiveDate:(n=i.effectiveDate)!=null?n:new Date().toISOString(),version:1,lastModified:new Date().toISOString(),deleted:!1},o=await(t||this.dbAdapter).create(Ge,a);this.context.logActivity("RecordPriceHistory",{productId:i.productId,unitCost:i.unitCost}),r.push(o)}return r}};var Ce="stock_opnames";var Me="stock_opname_items";var sr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addStockOpname(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ce,i);return this.changeQueue.enqueue({type:"create",model:Ce,record:a}),this.context.logActivity("AddStockOpname",{id:r}),a}async updateStockOpname(e,t,r){let n=await(r||this.dbAdapter).get(Ce,e);if(!n)throw new Error(`StockOpname with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ce,e,a);return this.changeQueue.enqueue({type:"update",model:Ce,record:o}),this.context.logActivity("UpdateStockOpname",{id:e}),o}async getStockOpnames(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ce,{...e,filters:i})}async getStockOpname(e,t){return(t||this.dbAdapter).get(Ce,e)}async deleteStockOpname(e,t){return await(t||this.dbAdapter).delete(Ce,e),this.changeQueue.enqueue({type:"delete",model:Ce,record:{id:e}}),this.context.logActivity("DeleteStockOpname",{id:e}),{id:e,queued:!0}}async duplicateStockOpname(e,t){let r=await this.getStockOpname(e,t);if(!r)throw new Error(`StockOpname with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ce,a);return this.changeQueue.enqueue({type:"create",model:Ce,record:a}),this.context.logActivity("DuplicateStockOpname",{originalId:e,newId:n}),o}async cancelOpname(e){let t=await this.dbAdapter.get(Ce,e);if(!t||t.deleted||t.status!=="pending")throw new Error("Stock opname tidak valid atau sudah selesai");let r={...t,status:"cancelled",version:t.version+1,lastModified:new Date().toISOString(),deleted:!1};await this.dbAdapter.update(Ce,e,r);try{this.changeQueue.enqueue({type:"update",model:Ce,id:t.id,record:r})}catch{}}async completeOpname(e){await this.dbAdapter.transaction(async t=>{var o,s;let r=(s=(o=this.context)==null?void 0:o.domainServices)==null?void 0:s.inventory,n=await t.get(Ce,e);if(!n||n.deleted||n.status!=="pending")throw new Error("Stock opname tidak valid atau sudah selesai");let i=await t.query(Me,{filters:{stockOpnameId:e,deleted:!1}});for(let c of i)c.difference!==0&&await r.updateStock(c.productId,c.difference,"opname_adjustment",Ce,e,t);let a=await t.update(Ce,e,{status:"completed",lastModified:new Date().toISOString()});this.changeQueue.enqueue({type:"update",model:Ce,id:e,record:a})})}};var on=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addStockOpnameItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Me,i);return this.changeQueue.enqueue({type:"create",model:Me,record:a}),this.context.logActivity("AddStockOpnameItem",{id:r}),a}async updateStockOpnameItem(e,t,r){let n=await(r||this.dbAdapter).get(Me,e);if(!n)throw new Error(`StockOpnameItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Me,e,a);return this.changeQueue.enqueue({type:"update",model:Me,record:o}),this.context.logActivity("UpdateStockOpnameItem",{id:e}),o}async getStockOpnameItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Me,{...e,filters:i})}async getStockOpnameItem(e,t){return(t||this.dbAdapter).get(Me,e)}async deleteStockOpnameItem(e,t){return await(t||this.dbAdapter).delete(Me,e),this.changeQueue.enqueue({type:"delete",model:Me,record:{id:e}}),this.context.logActivity("DeleteStockOpnameItem",{id:e}),{id:e,queued:!0}}async duplicateStockOpnameItem(e,t){let r=await this.getStockOpnameItem(e,t);if(!r)throw new Error(`StockOpnameItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Me,a);return this.changeQueue.enqueue({type:"create",model:Me,record:a}),this.context.logActivity("DuplicateStockOpnameItem",{originalId:e,newId:n}),o}};var it="stock_adjustments";var ur=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addStockAdjustment(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(it,i);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("AddStockAdjustment",{id:r}),a}async updateStockAdjustment(e,t,r){let n=await(r||this.dbAdapter).get(it,e);if(!n)throw new Error(`StockAdjustment with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(it,e,a);return this.changeQueue.enqueue({type:"update",model:it,record:o}),this.context.logActivity("UpdateStockAdjustment",{id:e}),o}async getStockAdjustments(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(it,{...e,filters:i})}async getStockAdjustment(e,t){return(t||this.dbAdapter).get(it,e)}async deleteStockAdjustment(e,t){return await(t||this.dbAdapter).delete(it,e),this.changeQueue.enqueue({type:"delete",model:it,record:{id:e}}),this.context.logActivity("DeleteStockAdjustment",{id:e}),{id:e,queued:!0}}async duplicateStockAdjustment(e,t){let r=await this.getStockAdjustment(e,t);if(!r)throw new Error(`StockAdjustment with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(it,a);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("DuplicateStockAdjustment",{originalId:e,newId:n}),o}};var at="report_schedules";var cr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addReportSchedule(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(at,i);return this.changeQueue.enqueue({type:"create",model:at,record:a}),this.context.logActivity("AddReportSchedule",{id:r}),a}async updateReportSchedule(e,t,r){let n=await(r||this.dbAdapter).get(at,e);if(!n)throw new Error(`ReportSchedule with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(at,e,a);return this.changeQueue.enqueue({type:"update",model:at,record:o}),this.context.logActivity("UpdateReportSchedule",{id:e}),o}async getReportSchedules(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(at,{...e,filters:i})}async getReportSchedule(e,t){return(t||this.dbAdapter).get(at,e)}async deleteReportSchedule(e,t){return await(t||this.dbAdapter).delete(at,e),this.changeQueue.enqueue({type:"delete",model:at,record:{id:e}}),this.context.logActivity("DeleteReportSchedule",{id:e}),{id:e,queued:!0}}async duplicateReportSchedule(e,t){let r=await this.getReportSchedule(e,t);if(!r)throw new Error(`ReportSchedule with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(at,a);return this.changeQueue.enqueue({type:"create",model:at,record:a}),this.context.logActivity("DuplicateReportSchedule",{originalId:e,newId:n}),o}};var dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addFinancialSetting(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ze,i);return this.changeQueue.enqueue({type:"create",model:ze,record:a}),this.context.logActivity("AddFinancialSetting",{id:r}),a}async updateFinancialSetting(e,t,r){let n=await(r||this.dbAdapter).get(ze,e);if(!n)throw new Error(`FinancialSetting with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ze,e,a);return this.changeQueue.enqueue({type:"update",model:ze,record:o}),this.context.logActivity("UpdateFinancialSetting",{id:e}),o}async getFinancialSettings(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ze,{...e,filters:i})}async getFinancialSetting(e,t){return(t||this.dbAdapter).get(ze,e)}async deleteFinancialSetting(e,t){return await(t||this.dbAdapter).delete(ze,e),this.changeQueue.enqueue({type:"delete",model:ze,record:{id:e}}),this.context.logActivity("DeleteFinancialSetting",{id:e}),{id:e,queued:!0}}async duplicateFinancialSetting(e,t){let r=await this.getFinancialSetting(e,t);if(!r)throw new Error(`FinancialSetting with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ze,a);return this.changeQueue.enqueue({type:"create",model:ze,record:a}),this.context.logActivity("DuplicateFinancialSetting",{originalId:e,newId:n}),o}};var ot="expenses";var lr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addExpense(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ot,i);return this.changeQueue.enqueue({type:"create",model:ot,record:a}),this.context.logActivity("AddExpense",{id:r}),a}async updateExpense(e,t,r){let n=await(r||this.dbAdapter).get(ot,e);if(!n)throw new Error(`Expense with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ot,e,a);return this.changeQueue.enqueue({type:"update",model:ot,record:o}),this.context.logActivity("UpdateExpense",{id:e}),o}async getExpenses(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ot,{...e,filters:i})}async getExpense(e,t){return(t||this.dbAdapter).get(ot,e)}async deleteExpense(e,t){return await(t||this.dbAdapter).delete(ot,e),this.changeQueue.enqueue({type:"delete",model:ot,record:{id:e}}),this.context.logActivity("DeleteExpense",{id:e}),{id:e,queued:!0}}async duplicateExpense(e,t){let r=await this.getExpense(e,t);if(!r)throw new Error(`Expense with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ot,a);return this.changeQueue.enqueue({type:"create",model:ot,record:a}),this.context.logActivity("DuplicateExpense",{originalId:e,newId:n}),o}};var pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addReceivable(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(he,i);return t||this.changeQueue.enqueue({type:"create",model:he,record:a}),this.context.logActivity("AddReceivable",{id:r}),a}async updateReceivable(e,t,r){let n=await(r||this.dbAdapter).get(he,e);if(!n)throw new Error(`Receivable with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(he,e,a);return r||this.changeQueue.enqueue({type:"update",model:he,record:o}),this.context.logActivity("UpdateReceivable",{id:e}),o}async getReceivables(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(he,{...e,filters:i})}async getReceivable(e,t){return(t||this.dbAdapter).get(he,e)}async deleteReceivable(e,t){return await(t||this.dbAdapter).delete(he,e),t||this.changeQueue.enqueue({type:"delete",model:he,record:{id:e}}),this.context.logActivity("DeleteReceivable",{id:e}),{id:e,queued:!0}}async duplicateReceivable(e,t){let r=await this.getReceivable(e,t);if(!r)throw new Error(`Receivable with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(he,a);return t||this.changeQueue.enqueue({type:"create",model:he,record:a}),this.context.logActivity("DuplicateReceivable",{originalId:e,newId:n}),o}};var mr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPayable(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ge,i);return t||this.changeQueue.enqueue({type:"create",model:ge,record:a}),this.context.logActivity("AddPayable",{id:r}),a}async updatePayable(e,t,r){let n=await(r||this.dbAdapter).get(ge,e);if(!n)throw new Error(`Payable with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ge,e,a);return r||this.changeQueue.enqueue({type:"update",model:ge,record:o}),this.context.logActivity("UpdatePayable",{id:e}),o}async getPayables(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ge,{...e,filters:i})}async getPayable(e,t){return(t||this.dbAdapter).get(ge,e)}async deletePayable(e,t){return await(t||this.dbAdapter).delete(ge,e),t||this.changeQueue.enqueue({type:"delete",model:ge,record:{id:e}}),this.context.logActivity("DeletePayable",{id:e}),{id:e,queued:!0}}async duplicatePayable(e,t){let r=await this.getPayable(e,t);if(!r)throw new Error(`Payable with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ge,a);return t||this.changeQueue.enqueue({type:"create",model:ge,record:a}),this.context.logActivity("DuplicatePayable",{originalId:e,newId:n}),o}async updatePaidAmount(e,t){var s;let r=(s=this.context.registry)==null?void 0:s.loggerAdapter,n=await this.dbAdapter.get(ge,e);if(!n)throw r.logError("Payable not found",{payableId:e}),new Error(`Payable ${e} not found`);let i=(n.paidAmount||0)+t,a=i>=n.amount?"paid":"partial",o={paidAmount:i,status:a,version:Date.now(),lastModified:new Date().toISOString()};await this.dbAdapter.update(ge,e,o),this.changeQueue.enqueue({type:"update",model:ge,record:{id:e,...o}}),this.context.logActivity("updatePaidAmount",{payableId:e,paidAmount:i,status:a}),r.logInfo("Payable updated",{payableId:e,paidAmount:i,status:a})}};var Qe="settlements";var hr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}async addSettlement(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Qe,i);return this.changeQueue.enqueue({type:"create",model:Qe,record:a}),this.context.logActivity("AddSettlement",{id:r}),a}async updateSettlement(e,t,r){let n=await(r||this.dbAdapter).get(Qe,e);if(!n)throw new Error(`Settlement with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Qe,e,a);return this.changeQueue.enqueue({type:"update",model:Qe,record:o}),this.context.logActivity("UpdateSettlement",{id:e}),o}async getSettlements(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Qe,{...e,filters:i})}async getSettlement(e,t){return(t||this.dbAdapter).get(Qe,e)}async deleteSettlement(e,t){return await(t||this.dbAdapter).delete(Qe,e),this.changeQueue.enqueue({type:"delete",model:Qe,record:{id:e}}),this.context.logActivity("DeleteSettlement",{id:e}),{id:e,queued:!0}}async duplicateSettlement(e,t){let r=await this.getSettlement(e,t);if(!r)throw new Error(`Settlement with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Qe,a);return this.changeQueue.enqueue({type:"create",model:Qe,record:a}),this.context.logActivity("DuplicateSettlement",{originalId:e,newId:n}),o}async createSettlement(e){var s;let t=(s=this.context.registry)==null?void 0:s.loggerAdapter,r=new Date().toISOString(),n=String(e.idempotencyKey||"").trim(),i=!!String(e.receivableId||"").trim(),a=!!String(e.payableId||"").trim();if(e.amount<=0)throw new Error("Settlement amount must be positive");if(i===a)throw new Error("Settlement must reference exactly one of receivableId or payableId");let o=await this.runInTransaction(async c=>{if(n){let d=await c.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:"idempotency_keys"},{field:"recordId",operator:"=",value:n},{field:"action",operator:"=",value:"settlement_create"}]},sort:[{field:"timestamp",direction:"desc"}],limit:1});if(d.length){let m=d[0].changes||{},f=String(m.settlementId||"").trim();if(f){let y=await c.get(Qe,f);if(y)return y}}}if(e.receivableId){let d=await c.get(he,e.receivableId);if(!d||d.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let m=d.amount-d.paidAmount;if(e.amount>m)throw new Error("Settlement amount exceeds remaining receivable amount")}if(e.payableId){let d=await c.get(ge,e.payableId);if(!d||d.deleted)throw new Error(`Payable ${e.payableId} not found`);let m=d.amount-d.paidAmount;if(e.amount>m)throw new Error("Settlement amount exceeds remaining payable amount")}let u={id:P(),receivableId:e.receivableId||null,payableId:e.payableId||null,amount:e.amount,method:e.method,date:e.date,reference:e.reference||null,userId:e.userId,version:Date.now(),lastModified:r,deleted:!1},l=await c.create(Qe,u);if(e.receivableId){let d=await c.get(he,e.receivableId);if(!d||d.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let m=d.paidAmount+e.amount,f={...d,paidAmount:m,status:m>=d.amount?"paid":"partial",version:Date.now(),lastModified:r};await c.update(he,f.id,f)}if(e.payableId){let d=await c.get(ge,e.payableId);if(!d||d.deleted)throw new Error(`Payable ${e.payableId} not found`);let m=d.paidAmount+e.amount,f={...d,paidAmount:m,status:m>=d.amount?"paid":"partial",version:Date.now(),lastModified:r};await c.update(ge,f.id,f)}return n&&await c.create(ie,{id:P(),tableName:"idempotency_keys",recordId:n,action:"settlement_create",changes:{settlementId:l.id},userId:String(e.userId||"").trim()||null,timestamp:r}),l});if(this.changeQueue.enqueue({type:"create",model:Qe,record:o}),e.receivableId){let c=await this.dbAdapter.get(he,e.receivableId);c&&this.changeQueue.enqueue({type:"update",model:he,record:c})}if(e.payableId){let c=await this.dbAdapter.get(ge,e.payableId);c&&this.changeQueue.enqueue({type:"update",model:ge,record:c})}return this.context.logActivity("createSettlement",{id:o.id}),t.logInfo("Settlement created",{id:o.id}),o}};var fr=class{constructor(e){this.context=e;this.stockCache=new Map;this.isRebuilding=!1;this.onStockChanged=e=>{this.invalidateProductStock(e.productId)};this.onStockRebuild=()=>{this.rebuildStockCache()};var t;this.adapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(this.context),Le.on("stock:changed",this.onStockChanged),Le.on("stock:rebuild",this.onStockRebuild)}async getStock(e){if(this.stockCache.has(e))return this.stockCache.get(e);let t=await this.computeStockFromLogs(e);return this.stockCache.set(e,t),t}async updateStock(e,t,r,n,i,a){var l,d;let o=a||this.adapter;if(t<0){let m=(l=this.context.domainServices)==null?void 0:l.bom;if(m&&(await m.getBomsByParentItemId(e)).length>0){let y=await m.expandBom(e),v=Math.abs(t);for(let p of y){let g=p.quantity*v;if(await this.getStock(p.componentItemId)<g)throw new Error(`Insufficient component ${p.componentItemId}`)}for(let p of y)await this.updateStock(p.componentItemId,-p.quantity*v,r,n,i,o);return}}let s;if(this.stockCache.has(e)?s=this.stockCache.get(e):(s=await this.computeStockFromLogs(e),this.stockCache.set(e,s)),t<0&&s+t<0)throw new Error(`Insufficient stock for product ${e}`);let c={id:P(),productId:e,change:t,reason:r,referenceType:n,referenceId:i,userId:((d=this.context.session)==null?void 0:d.userId)||"",timestamp:new Date().toISOString()};await o.create(Oe,c),this.changeQueue.enqueue({type:"create",model:Oe,record:c});let u=Math.max(0,s+t);this.stockCache.set(e,u)}async rebuildStockCache(){if(!this.isRebuilding){this.isRebuilding=!0;try{let e=await this.adapter.query(Oe,{aggregates:[{function:"SUM",field:"change",as:"total"}],groupBy:[{field:"productId"}]});this.stockCache.clear();for(let{productId:t,total:r}of e)this.stockCache.set(t,r!=null?r:0);console.info(`InventoryService stock cache rebuilt: ${this.stockCache.size} products`),Le.emit("stockCache:rebuilt")}finally{this.isRebuilding=!1}}}invalidateProductStock(e){e&&this.stockCache.delete(e)}invalidateProductsStock(e){for(let t of e)this.invalidateProductStock(t)}clearStockCache(){this.stockCache.clear()}async computeStockFromLogs(e){var r;let[t]=await this.adapter.query(Oe,{aggregates:[{function:"SUM",field:"change",as:"total"}],filters:{productId:e}});return(r=t==null?void 0:t.total)!=null?r:0}async getLowStockProducts(e=10,t=50){let r=[];for(let[s,c]of this.stockCache.entries())c<e&&r.push({productId:s,stock:c});r.sort((s,c)=>s.stock-c.stock);let n=r.slice(0,t),i=n.map(s=>s.productId);if(i.length===0)return[];let a=await this.adapter.query(ce,{filters:{and:[{field:"id",operator:"IN",value:i},{deleted:!1}]},include:["baseUom","category"]}),o=new Map(a.map(s=>[s.id,s]));return n.map(s=>({productId:s.productId,stock:s.stock,product:o.get(s.productId)}))}};var _i={categories:{parentId:{table:"categories",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},products:{categoryId:{table:"categories",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},baseUomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},boms:{parentItemId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},componentItemId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},customers:{groupId:{table:"customer_groups",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},loyalty_accounts:{customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"}},loyalty_ledgers:{customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"}},histories:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},orders:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},parentOrderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},order_items:{orderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},kitchen_tickets:{orderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},createdBy:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},kitchen_ticket_items:{ticketId:{table:"kitchen_tickets",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},orderItemId:{table:"order_items",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},price_tiers:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},uom:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},customerGroupId:{table:"customer_groups",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},returns:{saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},return_items:{returnId:{table:"returns",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},sales:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},sourceOrderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},sale_items:{saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},shifts:{cashierId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},transactions:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},users:{role:{table:"roles",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchase_orders:{supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchase_order_items:{purchaseOrderId:{table:"purchase_orders",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchases:{supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseOrderId:{table:"purchase_orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchase_items:{purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},purchaseOrderItemId:{table:"purchase_order_items",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},inventory_lots:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},purchaseItemId:{table:"purchase_items",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},purchaseOrderId:{table:"purchase_orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseOrderItemId:{table:"purchase_order_items",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},inventory_logs:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},price_histories:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},stock_opnames:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},stock_opname_items:{stockOpnameId:{table:"stock_opnames",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},stock_adjustments:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},expenses:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},receivables:{customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},payables:{supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},settlements:{receivableId:{table:"receivables",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},payableId:{table:"payables",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}}},Ti={transactions:[{typeField:"referenceType",idField:"referenceId",types:{sale:{table:"sales",foreignKey:"id"},purchase:{table:"purchases",foreignKey:"id"},sale_return:{table:"returns",foreignKey:"id"},purchase_return:{table:"returns",foreignKey:"id"},receivable_payment:{table:"receivables",foreignKey:"id"},payable_payment:{table:"payables",foreignKey:"id"},cash_adjustment:{table:"stock_adjustments",foreignKey:"id"},expense:{table:"expenses",foreignKey:"id"}}}],inventory_logs:[{typeField:"referenceType",idField:"referenceId",types:{sale:{table:"sales",foreignKey:"id"},purchase:{table:"purchases",foreignKey:"id"},sale_return:{table:"returns",foreignKey:"id"},purchase_return:{table:"returns",foreignKey:"id"},stock_opname:{table:"stock_opnames",foreignKey:"id"},stock_adjustment:{table:"stock_adjustments",foreignKey:"id"}}}]};var yo=[{name:"boms",columns:[{name:"id",type:"string"},{name:"parentItemId",type:"string",isOptional:!0,isPrimarySearchKey:!0},{name:"componentItemId",type:"string",isOptional:!0,isPrimarySearchKey:!0},{name:"quantity",type:"number"},{name:"uomId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"categories",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"parentId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"customers",columns:[{name:"id",type:"string"},{name:"name",type:"string",isFullTextSearchable:!0},{name:"phone",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"email",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"groupId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"customer_groups",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"loyalty_accounts",columns:[{name:"id",type:"string"},{name:"customerId",type:"string",isIndexed:!0},{name:"pointsBalance",type:"number"},{name:"totalEarned",type:"number"},{name:"totalRedeemed",type:"number"},{name:"totalExpired",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"loyalty_ledgers",columns:[{name:"id",type:"string"},{name:"customerId",type:"string",isIndexed:!0},{name:"entryType",type:"string",enum:["earn","redeem","expire","adjustment"]},{name:"points",type:"number"},{name:"availablePoints",type:"number"},{name:"expiresAt",type:"string",isOptional:!0,isIndexed:!0},{name:"consumedAt",type:"string",isOptional:!0,isIndexed:!0},{name:"referenceType",type:"string",isOptional:!0},{name:"referenceId",type:"string",isOptional:!0},{name:"note",type:"string",isOptional:!0},{name:"date",type:"string",isIndexed:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"histories",columns:[{name:"id",type:"string"},{name:"tableName",type:"string"},{name:"recordId",type:"string"},{name:"action",type:"string"},{name:"changes",type:"json"},{name:"userId",type:"string",isOptional:!0},{name:"timestamp",type:"string"}],skipMetadataColumns:!0},{name:"orders",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"customerId",type:"string",isOptional:!0},{name:"parentOrderId",type:"string",isOptional:!0},{name:"discountCode",type:"string",isOptional:!0},{name:"channel",type:"string",enum:["dine_in","takeaway","delivery","preorder"],isOptional:!0},{name:"status",type:"string"},{name:"saleId",type:"string",isOptional:!0},{name:"scheduledAt",type:"string",isOptional:!0},{name:"deliveryAddress",type:"string",isOptional:!0},{name:"tableNumber",type:"string",isOptional:!0,isIndexed:!0},{name:"serviceChargeAmount",type:"number",isOptional:!0},{name:"gratuityAmount",type:"number",isOptional:!0},{name:"date",type:"string"},{name:"total",type:"number"},{name:"ppn",type:"number"},{name:"pph",type:"number"},{name:"finalTotal",type:"number"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"order_items",columns:[{name:"id",type:"string"},{name:"orderId",type:"string"},{name:"productId",type:"string"},{name:"quantity",type:"number"},{name:"uomId",type:"string",isOptional:!0},{name:"unitPrice",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"kitchen_tickets",columns:[{name:"id",type:"string"},{name:"orderId",type:"string"},{name:"station",type:"string"},{name:"status",type:"string",enum:["queued","in_progress","ready","served","canceled"]},{name:"note",type:"string",isOptional:!0},{name:"createdBy",type:"string",isOptional:!0},{name:"createdAt",type:"string",isIndexed:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"kitchen_ticket_items",columns:[{name:"id",type:"string"},{name:"ticketId",type:"string"},{name:"orderItemId",type:"string"},{name:"course",type:"string",isOptional:!0},{name:"status",type:"string",enum:["queued","in_progress","ready","served","canceled"]},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"price_tiers",columns:[{name:"id",type:"string"},{name:"tierLevel",type:"number"},{name:"price",type:"number"},{name:"productId",type:"string"},{name:"uom",type:"string",isOptional:!0},{name:"customerGroupId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"products",columns:[{name:"id",type:"string"},{name:"name",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"description",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"barcode",type:"string",isOptional:!0,isFullTextSearchable:!0,isPrimarySearchKey:!0},{name:"qrCode",type:"string",isOptional:!0,isIndexed:!0,isFullTextSearchable:!0,isPrimarySearchKey:!0},{name:"price",type:"number"},{name:"cost",type:"number"},{name:"categoryId",type:"string"},{name:"baseUomId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"promotions",columns:[{name:"id",type:"string"},{name:"code",type:"string"},{name:"type",type:"string"},{name:"value",type:"number"},{name:"name",type:"string",isOptional:!0},{name:"description",type:"string",isOptional:!0},{name:"targetType",type:"string"},{name:"targetIds",type:"string[]"},{name:"expiresAt",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"returns",notes:`
1
+ "use strict";var OFPosSharedCore=(()=>{var go=Object.create;var Gr=Object.defineProperty;var yo=Object.getOwnPropertyDescriptor;var bo=Object.getOwnPropertyNames;var vo=Object.getPrototypeOf,xo=Object.prototype.hasOwnProperty;var Pe=(u=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(u,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):u)(function(u){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+u+'" is not supported')});var re=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports),Ao=(u,e)=>{for(var t in e)Gr(u,t,{get:e[t],enumerable:!0})},Bi=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of bo(e))!xo.call(u,n)&&n!==t&&Gr(u,n,{get:()=>e[n],enumerable:!(r=yo(e,n))||r.enumerable});return u};var Mt=(u,e,t)=>(t=u!=null?go(vo(u)):{},Bi(e||!u||!u.__esModule?Gr(t,"default",{value:u,enumerable:!0}):t,u)),So=u=>Bi(Gr({},"__esModule",{value:!0}),u);var qi=re(()=>{var Mi;(function(u){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:o(),r=n(u);typeof t.Reflect!="undefined"&&(r=n(t.Reflect,r)),e(r,t),typeof t.Reflect=="undefined"&&(t.Reflect=u);function n(s,d){return function(c,p){Object.defineProperty(s,c,{configurable:!0,writable:!0,value:p}),d&&d(c,p)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function o(){return i()||a()}})(function(e,t){var r=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",i=n&&typeof Symbol.toPrimitive!="undefined"?Symbol.toPrimitive:"@@toPrimitive",a=n&&typeof Symbol.iterator!="undefined"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",s={__proto__:[]}instanceof Array,d=!o&&!s,c={create:o?function(){return st(Object.create(null))}:s?function(){return st({__proto__:null})}:function(){return st({})},has:d?function(S,C){return r.call(S,C)}:function(S,C){return C in S},get:d?function(S,C){return r.call(S,C)?S[C]:void 0}:function(S,C){return S[C]}},p=Object.getPrototypeOf(Function),l=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Et(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ot(),f=typeof WeakMap=="function"?WeakMap:lt(),y=n?Symbol.for("@reflect-metadata:registry"):void 0,b=wt(),h=dt(b);function g(S,C,B,N){if(P(B)){if(!Te(S))throw new TypeError;if(!We(C))throw new TypeError;return L(S,C)}else{if(!Te(S))throw new TypeError;if(!J(C))throw new TypeError;if(!J(N)&&!P(N)&&!X(N))throw new TypeError;return X(N)&&(N=void 0),B=pe(B),Q(S,C,B,N)}}e("decorate",g);function x(S,C){function B(N,W){if(!J(N))throw new TypeError;if(!P(W)&&!Ye(W))throw new TypeError;U(S,C,N,W)}return B}e("metadata",x);function v(S,C,B,N){if(!J(B))throw new TypeError;return P(N)||(N=pe(N)),U(S,C,B,N)}e("defineMetadata",v);function A(S,C,B){if(!J(C))throw new TypeError;return P(B)||(B=pe(B)),T(S,C,B)}e("hasMetadata",A);function I(S,C,B){if(!J(C))throw new TypeError;return P(B)||(B=pe(B)),z(S,C,B)}e("hasOwnMetadata",I);function k(S,C,B){if(!J(C))throw new TypeError;return P(B)||(B=pe(B)),V(S,C,B)}e("getMetadata",k);function w(S,C,B){if(!J(C))throw new TypeError;return P(B)||(B=pe(B)),F(S,C,B)}e("getOwnMetadata",w);function q(S,C){if(!J(S))throw new TypeError;return P(C)||(C=pe(C)),O(S,C)}e("getMetadataKeys",q);function M(S,C){if(!J(S))throw new TypeError;return P(C)||(C=pe(C)),_(S,C)}e("getOwnMetadataKeys",M);function E(S,C,B){if(!J(C))throw new TypeError;if(P(B)||(B=pe(B)),!J(C))throw new TypeError;P(B)||(B=pe(B));var N=ft(C,B,!1);return P(N)?!1:N.OrdinaryDeleteMetadata(S,C,B)}e("deleteMetadata",E);function L(S,C){for(var B=S.length-1;B>=0;--B){var N=S[B],W=N(C);if(!P(W)&&!X(W)){if(!We(W))throw new TypeError;C=W}}return C}function Q(S,C,B,N){for(var W=S.length-1;W>=0;--W){var he=S[W],ve=he(C,B,N);if(!P(ve)&&!X(ve)){if(!J(ve))throw new TypeError;N=ve}}return N}function T(S,C,B){var N=z(S,C,B);if(N)return!0;var W=Ue(C);return X(W)?!1:T(S,W,B)}function z(S,C,B){var N=ft(C,B,!1);return P(N)?!1:se(N.OrdinaryHasOwnMetadata(S,C,B))}function V(S,C,B){var N=z(S,C,B);if(N)return F(S,C,B);var W=Ue(C);if(!X(W))return V(S,W,B)}function F(S,C,B){var N=ft(C,B,!1);if(!P(N))return N.OrdinaryGetOwnMetadata(S,C,B)}function U(S,C,B,N){var W=ft(B,N,!0);W.OrdinaryDefineOwnMetadata(S,C,B,N)}function O(S,C){var B=_(S,C),N=Ue(S);if(N===null)return B;var W=O(N,C);if(W.length<=0)return B;if(B.length<=0)return W;for(var he=new m,ve=[],ee=0,j=B;ee<j.length;ee++){var $=j[ee],K=he.has($);K||(he.add($),ve.push($))}for(var G=0,ne=W;G<ne.length;G++){var $=ne[G],K=he.has($);K||(he.add($),ve.push($))}return ve}function _(S,C){var B=ft(S,C,!1);return B?B.OrdinaryOwnMetadataKeys(S,C):[]}function R(S){if(S===null)return 1;switch(typeof S){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return S===null?1:6;default:return 6}}function P(S){return S===void 0}function X(S){return S===null}function te(S){return typeof S=="symbol"}function J(S){return typeof S=="object"?S!==null:typeof S=="function"}function Y(S,C){switch(R(S)){case 0:return S;case 1:return S;case 2:return S;case 3:return S;case 4:return S;case 5:return S}var B=C===3?"string":C===5?"number":"default",N=ct(S,i);if(N!==void 0){var W=N.call(S,B);if(J(W))throw new TypeError;return W}return be(S,B==="default"?"number":B)}function be(S,C){if(C==="string"){var B=S.toString;if(me(B)){var N=B.call(S);if(!J(N))return N}var W=S.valueOf;if(me(W)){var N=W.call(S);if(!J(N))return N}}else{var W=S.valueOf;if(me(W)){var N=W.call(S);if(!J(N))return N}var he=S.toString;if(me(he)){var N=he.call(S);if(!J(N))return N}}throw new TypeError}function se(S){return!!S}function Ne(S){return""+S}function pe(S){var C=Y(S,3);return te(C)?C:Ne(C)}function Te(S){return Array.isArray?Array.isArray(S):S instanceof Object?S instanceof Array:Object.prototype.toString.call(S)==="[object Array]"}function me(S){return typeof S=="function"}function We(S){return typeof S=="function"}function Ye(S){switch(R(S)){case 3:return!0;case 4:return!0;default:return!1}}function Xe(S,C){return S===C||S!==S&&C!==C}function ct(S,C){var B=S[C];if(B!=null){if(!me(B))throw new TypeError;return B}}function bt(S){var C=ct(S,a);if(!me(C))throw new TypeError;var B=C.call(S);if(!J(B))throw new TypeError;return B}function ut(S){return S.value}function qe(S){var C=S.next();return C.done?!1:C}function ke(S){var C=S.return;C&&C.call(S)}function Ue(S){var C=Object.getPrototypeOf(S);if(typeof S!="function"||S===p||C!==p)return C;var B=S.prototype,N=B&&Object.getPrototypeOf(B);if(N==null||N===Object.prototype)return C;var W=N.constructor;return typeof W!="function"||W===S?C:W}function vt(){var S;!P(y)&&typeof t.Reflect!="undefined"&&!(y in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(S=ht(t.Reflect));var C,B,N,W=new f,he={registerProvider:ve,getProvider:j,setProvider:K};return he;function ve(G){if(!Object.isExtensible(he))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case S===G:break;case P(C):C=G;break;case C===G:break;case P(B):B=G;break;case B===G:break;default:N===void 0&&(N=new m),N.add(G);break}}function ee(G,ne){if(!P(C)){if(C.isProviderFor(G,ne))return C;if(!P(B)){if(B.isProviderFor(G,ne))return C;if(!P(N))for(var de=bt(N);;){var Ie=qe(de);if(!Ie)return;var Je=ut(Ie);if(Je.isProviderFor(G,ne))return ke(de),Je}}}if(!P(S)&&S.isProviderFor(G,ne))return S}function j(G,ne){var de=W.get(G),Ie;return P(de)||(Ie=de.get(ne)),P(Ie)&&(Ie=ee(G,ne),P(Ie)||(P(de)&&(de=new l,W.set(G,de)),de.set(ne,Ie))),Ie}function $(G){if(P(G))throw new TypeError;return C===G||B===G||!P(N)&&N.has(G)}function K(G,ne,de){if(!$(de))throw new Error("Metadata provider not registered.");var Ie=j(G,ne);if(Ie!==de){if(!P(Ie))return!1;var Je=W.get(G);P(Je)&&(Je=new l,W.set(G,Je)),Je.set(ne,de)}return!0}}function wt(){var S;return!P(y)&&J(t.Reflect)&&Object.isExtensible(t.Reflect)&&(S=t.Reflect[y]),P(S)&&(S=vt()),!P(y)&&J(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:S}),S}function dt(S){var C=new f,B={isProviderFor:function($,K){var G=C.get($);return P(G)?!1:G.has(K)},OrdinaryDefineOwnMetadata:ve,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:he,OrdinaryOwnMetadataKeys:ee,OrdinaryDeleteMetadata:j};return b.registerProvider(B),B;function N($,K,G){var ne=C.get($),de=!1;if(P(ne)){if(!G)return;ne=new l,C.set($,ne),de=!0}var Ie=ne.get(K);if(P(Ie)){if(!G)return;if(Ie=new l,ne.set(K,Ie),!S.setProvider($,K,B))throw ne.delete(K),de&&C.delete($),new Error("Wrong provider for target.")}return Ie}function W($,K,G){var ne=N(K,G,!1);return P(ne)?!1:se(ne.has($))}function he($,K,G){var ne=N(K,G,!1);if(!P(ne))return ne.get($)}function ve($,K,G,ne){var de=N(G,ne,!0);de.set($,K)}function ee($,K){var G=[],ne=N($,K,!1);if(P(ne))return G;for(var de=ne.keys(),Ie=bt(de),Je=0;;){var Ht=qe(Ie);if(!Ht)return G.length=Je,G;var oi=ut(Ht);try{G[Je]=oi}catch(Kr){try{ke(Ie)}finally{throw Kr}}Je++}}function j($,K,G){var ne=N(K,G,!1);if(P(ne)||!ne.delete($))return!1;if(ne.size===0){var de=C.get(K);P(de)||(de.delete(G),de.size===0&&C.delete(de))}return!0}}function ht(S){var C=S.defineMetadata,B=S.hasOwnMetadata,N=S.getOwnMetadata,W=S.getOwnMetadataKeys,he=S.deleteMetadata,ve=new f,ee={isProviderFor:function(j,$){var K=ve.get(j);return!P(K)&&K.has($)?!0:W(j,$).length?(P(K)&&(K=new m,ve.set(j,K)),K.add($),!0):!1},OrdinaryDefineOwnMetadata:C,OrdinaryHasOwnMetadata:B,OrdinaryGetOwnMetadata:N,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:he};return ee}function ft(S,C,B){var N=b.getProvider(S,C);if(!P(N))return N;if(B){if(b.setProvider(S,C,h))return h;throw new Error("Illegal state.")}}function Et(){var S={},C=[],B=(function(){function ee(j,$,K){this._index=0,this._keys=j,this._values=$,this._selector=K}return ee.prototype["@@iterator"]=function(){return this},ee.prototype[a]=function(){return this},ee.prototype.next=function(){var j=this._index;if(j>=0&&j<this._keys.length){var $=this._selector(this._keys[j],this._values[j]);return j+1>=this._keys.length?(this._index=-1,this._keys=C,this._values=C):this._index++,{value:$,done:!1}}return{value:void 0,done:!0}},ee.prototype.throw=function(j){throw this._index>=0&&(this._index=-1,this._keys=C,this._values=C),j},ee.prototype.return=function(j){return this._index>=0&&(this._index=-1,this._keys=C,this._values=C),{value:j,done:!0}},ee})(),N=(function(){function ee(){this._keys=[],this._values=[],this._cacheKey=S,this._cacheIndex=-2}return Object.defineProperty(ee.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ee.prototype.has=function(j){return this._find(j,!1)>=0},ee.prototype.get=function(j){var $=this._find(j,!1);return $>=0?this._values[$]:void 0},ee.prototype.set=function(j,$){var K=this._find(j,!0);return this._values[K]=$,this},ee.prototype.delete=function(j){var $=this._find(j,!1);if($>=0){for(var K=this._keys.length,G=$+1;G<K;G++)this._keys[G-1]=this._keys[G],this._values[G-1]=this._values[G];return this._keys.length--,this._values.length--,Xe(j,this._cacheKey)&&(this._cacheKey=S,this._cacheIndex=-2),!0}return!1},ee.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=S,this._cacheIndex=-2},ee.prototype.keys=function(){return new B(this._keys,this._values,W)},ee.prototype.values=function(){return new B(this._keys,this._values,he)},ee.prototype.entries=function(){return new B(this._keys,this._values,ve)},ee.prototype["@@iterator"]=function(){return this.entries()},ee.prototype[a]=function(){return this.entries()},ee.prototype._find=function(j,$){if(!Xe(this._cacheKey,j)){this._cacheIndex=-1;for(var K=0;K<this._keys.length;K++)if(Xe(this._keys[K],j)){this._cacheIndex=K;break}}return this._cacheIndex<0&&$&&(this._cacheIndex=this._keys.length,this._keys.push(j),this._values.push(void 0)),this._cacheIndex},ee})();return N;function W(ee,j){return ee}function he(ee,j){return j}function ve(ee,j){return[ee,j]}}function Ot(){var S=(function(){function C(){this._map=new l}return Object.defineProperty(C.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),C.prototype.has=function(B){return this._map.has(B)},C.prototype.add=function(B){return this._map.set(B,B),this},C.prototype.delete=function(B){return this._map.delete(B)},C.prototype.clear=function(){this._map.clear()},C.prototype.keys=function(){return this._map.keys()},C.prototype.values=function(){return this._map.keys()},C.prototype.entries=function(){return this._map.entries()},C.prototype["@@iterator"]=function(){return this.keys()},C.prototype[a]=function(){return this.keys()},C})();return S}function lt(){var S=16,C=c.create(),B=N();return(function(){function j(){this._key=N()}return j.prototype.has=function($){var K=W($,!1);return K!==void 0?c.has(K,this._key):!1},j.prototype.get=function($){var K=W($,!1);return K!==void 0?c.get(K,this._key):void 0},j.prototype.set=function($,K){var G=W($,!0);return G[this._key]=K,this},j.prototype.delete=function($){var K=W($,!1);return K!==void 0?delete K[this._key]:!1},j.prototype.clear=function(){this._key=N()},j})();function N(){var j;do j="@@WeakMap@@"+ee();while(c.has(C,j));return C[j]=!0,j}function W(j,$){if(!r.call(j,B)){if(!$)return;Object.defineProperty(j,B,{value:c.create()})}return j[B]}function he(j,$){for(var K=0;K<$;++K)j[K]=Math.random()*255|0;return j}function ve(j){if(typeof Uint8Array=="function"){var $=new Uint8Array(j);return typeof crypto!="undefined"?crypto.getRandomValues($):typeof msCrypto!="undefined"?msCrypto.getRandomValues($):he($,j),$}return he(new Array(j),j)}function ee(){var j=ve(S);j[6]=j[6]&79|64,j[8]=j[8]&191|128;for(var $="",K=0;K<S;++K){var G=j[K];(K===4||K===6||K===8)&&($+="-"),G<16&&($+="0"),$+=G.toString(16).toLowerCase()}return $}}function st(S){return S.__=void 0,delete S.__,S}})})(Mi||(Mi={}))});var ae=re((fn,zi)=>{(function(u,e){typeof fn=="object"?zi.exports=fn=e():typeof define=="function"&&define.amd?define([],e):u.CryptoJS=e()})(fn,function(){var u=u||(function(e,t){var r;if(typeof window!="undefined"&&window.crypto&&(r=window.crypto),typeof self!="undefined"&&self.crypto&&(r=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof window!="undefined"&&window.msCrypto&&(r=window.msCrypto),!r&&typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof Pe=="function")try{r=Pe("crypto")}catch{}var n=function(){if(r){if(typeof r.getRandomValues=="function")try{return r.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof r.randomBytes=="function")try{return r.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},i=Object.create||(function(){function h(){}return function(g){var x;return h.prototype=g,x=new h,h.prototype=null,x}})(),a={},o=a.lib={},s=o.Base=(function(){return{extend:function(h){var g=i(this);return h&&g.mixIn(h),(!g.hasOwnProperty("init")||this.init===g.init)&&(g.init=function(){g.$super.init.apply(this,arguments)}),g.init.prototype=g,g.$super=this,g},create:function(){var h=this.extend();return h.init.apply(h,arguments),h},init:function(){},mixIn:function(h){for(var g in h)h.hasOwnProperty(g)&&(this[g]=h[g]);h.hasOwnProperty("toString")&&(this.toString=h.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),d=o.WordArray=s.extend({init:function(h,g){h=this.words=h||[],g!=t?this.sigBytes=g:this.sigBytes=h.length*4},toString:function(h){return(h||p).stringify(this)},concat:function(h){var g=this.words,x=h.words,v=this.sigBytes,A=h.sigBytes;if(this.clamp(),v%4)for(var I=0;I<A;I++){var k=x[I>>>2]>>>24-I%4*8&255;g[v+I>>>2]|=k<<24-(v+I)%4*8}else for(var w=0;w<A;w+=4)g[v+w>>>2]=x[w>>>2];return this.sigBytes+=A,this},clamp:function(){var h=this.words,g=this.sigBytes;h[g>>>2]&=4294967295<<32-g%4*8,h.length=e.ceil(g/4)},clone:function(){var h=s.clone.call(this);return h.words=this.words.slice(0),h},random:function(h){for(var g=[],x=0;x<h;x+=4)g.push(n());return new d.init(g,h)}}),c=a.enc={},p=c.Hex={stringify:function(h){for(var g=h.words,x=h.sigBytes,v=[],A=0;A<x;A++){var I=g[A>>>2]>>>24-A%4*8&255;v.push((I>>>4).toString(16)),v.push((I&15).toString(16))}return v.join("")},parse:function(h){for(var g=h.length,x=[],v=0;v<g;v+=2)x[v>>>3]|=parseInt(h.substr(v,2),16)<<24-v%8*4;return new d.init(x,g/2)}},l=c.Latin1={stringify:function(h){for(var g=h.words,x=h.sigBytes,v=[],A=0;A<x;A++){var I=g[A>>>2]>>>24-A%4*8&255;v.push(String.fromCharCode(I))}return v.join("")},parse:function(h){for(var g=h.length,x=[],v=0;v<g;v++)x[v>>>2]|=(h.charCodeAt(v)&255)<<24-v%4*8;return new d.init(x,g)}},m=c.Utf8={stringify:function(h){try{return decodeURIComponent(escape(l.stringify(h)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(h){return l.parse(unescape(encodeURIComponent(h)))}},f=o.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(h){typeof h=="string"&&(h=m.parse(h)),this._data.concat(h),this._nDataBytes+=h.sigBytes},_process:function(h){var g,x=this._data,v=x.words,A=x.sigBytes,I=this.blockSize,k=I*4,w=A/k;h?w=e.ceil(w):w=e.max((w|0)-this._minBufferSize,0);var q=w*I,M=e.min(q*4,A);if(q){for(var E=0;E<q;E+=I)this._doProcessBlock(v,E);g=v.splice(0,q),x.sigBytes-=M}return new d.init(g,M)},clone:function(){var h=s.clone.call(this);return h._data=this._data.clone(),h},_minBufferSize:0}),y=o.Hasher=f.extend({cfg:s.extend(),init:function(h){this.cfg=this.cfg.extend(h),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(h){return this._append(h),this._process(),this},finalize:function(h){h&&this._append(h);var g=this._doFinalize();return g},blockSize:512/32,_createHelper:function(h){return function(g,x){return new h.init(x).finalize(g)}},_createHmacHelper:function(h){return function(g,x){return new b.HMAC.init(h,x).finalize(g)}}}),b=a.algo={};return a})(Math);return u})});var _r=re((gn,Ki)=>{(function(u,e){typeof gn=="object"?Ki.exports=gn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(gn,function(u){return(function(e){var t=u,r=t.lib,n=r.Base,i=r.WordArray,a=t.x64={},o=a.Word=n.extend({init:function(d,c){this.high=d,this.low=c}}),s=a.WordArray=n.extend({init:function(d,c){d=this.words=d||[],c!=e?this.sigBytes=c:this.sigBytes=d.length*8},toX32:function(){for(var d=this.words,c=d.length,p=[],l=0;l<c;l++){var m=d[l];p.push(m.high),p.push(m.low)}return i.create(p,this.sigBytes)},clone:function(){for(var d=n.clone.call(this),c=d.words=this.words.slice(0),p=c.length,l=0;l<p;l++)c[l]=c[l].clone();return d}})})(),u})});var Wi=re((yn,Gi)=>{(function(u,e){typeof yn=="object"?Gi.exports=yn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(yn,function(u){return(function(){if(typeof ArrayBuffer=="function"){var e=u,t=e.lib,r=t.WordArray,n=r.init,i=r.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var o=a.byteLength,s=[],d=0;d<o;d++)s[d>>>2]|=a[d]<<24-d%4*8;n.call(this,s,o)}else n.apply(this,arguments)};i.prototype=r}})(),u.lib.WordArray})});var Xi=re((bn,Yi)=>{(function(u,e){typeof bn=="object"?Yi.exports=bn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(bn,function(u){return(function(){var e=u,t=e.lib,r=t.WordArray,n=e.enc,i=n.Utf16=n.Utf16BE={stringify:function(o){for(var s=o.words,d=o.sigBytes,c=[],p=0;p<d;p+=2){var l=s[p>>>2]>>>16-p%4*8&65535;c.push(String.fromCharCode(l))}return c.join("")},parse:function(o){for(var s=o.length,d=[],c=0;c<s;c++)d[c>>>1]|=o.charCodeAt(c)<<16-c%2*16;return r.create(d,s*2)}};n.Utf16LE={stringify:function(o){for(var s=o.words,d=o.sigBytes,c=[],p=0;p<d;p+=2){var l=a(s[p>>>2]>>>16-p%4*8&65535);c.push(String.fromCharCode(l))}return c.join("")},parse:function(o){for(var s=o.length,d=[],c=0;c<s;c++)d[c>>>1]|=a(o.charCodeAt(c)<<16-c%2*16);return r.create(d,s*2)}};function a(o){return o<<8&4278255360|o>>>8&16711935}})(),u.enc.Utf16})});var Dt=re((vn,Ji)=>{(function(u,e){typeof vn=="object"?Ji.exports=vn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(vn,function(u){return(function(){var e=u,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64={stringify:function(o){var s=o.words,d=o.sigBytes,c=this._map;o.clamp();for(var p=[],l=0;l<d;l+=3)for(var m=s[l>>>2]>>>24-l%4*8&255,f=s[l+1>>>2]>>>24-(l+1)%4*8&255,y=s[l+2>>>2]>>>24-(l+2)%4*8&255,b=m<<16|f<<8|y,h=0;h<4&&l+h*.75<d;h++)p.push(c.charAt(b>>>6*(3-h)&63));var g=c.charAt(64);if(g)for(;p.length%4;)p.push(g);return p.join("")},parse:function(o){var s=o.length,d=this._map,c=this._reverseMap;if(!c){c=this._reverseMap=[];for(var p=0;p<d.length;p++)c[d.charCodeAt(p)]=p}var l=d.charAt(64);if(l){var m=o.indexOf(l);m!==-1&&(s=m)}return a(o,s,c)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function a(o,s,d){for(var c=[],p=0,l=0;l<s;l++)if(l%4){var m=d[o.charCodeAt(l-1)]<<l%4*2,f=d[o.charCodeAt(l)]>>>6-l%4*2,y=m|f;c[p>>>2]|=y<<24-p%4*8,p++}return r.create(c,p)}})(),u.enc.Base64})});var ea=re((xn,Zi)=>{(function(u,e){typeof xn=="object"?Zi.exports=xn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(xn,function(u){return(function(){var e=u,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64url={stringify:function(o,s){s===void 0&&(s=!0);var d=o.words,c=o.sigBytes,p=s?this._safe_map:this._map;o.clamp();for(var l=[],m=0;m<c;m+=3)for(var f=d[m>>>2]>>>24-m%4*8&255,y=d[m+1>>>2]>>>24-(m+1)%4*8&255,b=d[m+2>>>2]>>>24-(m+2)%4*8&255,h=f<<16|y<<8|b,g=0;g<4&&m+g*.75<c;g++)l.push(p.charAt(h>>>6*(3-g)&63));var x=p.charAt(64);if(x)for(;l.length%4;)l.push(x);return l.join("")},parse:function(o,s){s===void 0&&(s=!0);var d=o.length,c=s?this._safe_map:this._map,p=this._reverseMap;if(!p){p=this._reverseMap=[];for(var l=0;l<c.length;l++)p[c.charCodeAt(l)]=l}var m=c.charAt(64);if(m){var f=o.indexOf(m);f!==-1&&(d=f)}return a(o,d,p)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function a(o,s,d){for(var c=[],p=0,l=0;l<s;l++)if(l%4){var m=d[o.charCodeAt(l-1)]<<l%4*2,f=d[o.charCodeAt(l)]>>>6-l%4*2,y=m|f;c[p>>>2]|=y<<24-p%4*8,p++}return r.create(c,p)}})(),u.enc.Base64url})});var Ct=re((An,ta)=>{(function(u,e){typeof An=="object"?ta.exports=An=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(An,function(u){return(function(e){var t=u,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[];(function(){for(var m=0;m<64;m++)o[m]=e.abs(e.sin(m+1))*4294967296|0})();var s=a.MD5=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(m,f){for(var y=0;y<16;y++){var b=f+y,h=m[b];m[b]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360}var g=this._hash.words,x=m[f+0],v=m[f+1],A=m[f+2],I=m[f+3],k=m[f+4],w=m[f+5],q=m[f+6],M=m[f+7],E=m[f+8],L=m[f+9],Q=m[f+10],T=m[f+11],z=m[f+12],V=m[f+13],F=m[f+14],U=m[f+15],O=g[0],_=g[1],R=g[2],P=g[3];O=d(O,_,R,P,x,7,o[0]),P=d(P,O,_,R,v,12,o[1]),R=d(R,P,O,_,A,17,o[2]),_=d(_,R,P,O,I,22,o[3]),O=d(O,_,R,P,k,7,o[4]),P=d(P,O,_,R,w,12,o[5]),R=d(R,P,O,_,q,17,o[6]),_=d(_,R,P,O,M,22,o[7]),O=d(O,_,R,P,E,7,o[8]),P=d(P,O,_,R,L,12,o[9]),R=d(R,P,O,_,Q,17,o[10]),_=d(_,R,P,O,T,22,o[11]),O=d(O,_,R,P,z,7,o[12]),P=d(P,O,_,R,V,12,o[13]),R=d(R,P,O,_,F,17,o[14]),_=d(_,R,P,O,U,22,o[15]),O=c(O,_,R,P,v,5,o[16]),P=c(P,O,_,R,q,9,o[17]),R=c(R,P,O,_,T,14,o[18]),_=c(_,R,P,O,x,20,o[19]),O=c(O,_,R,P,w,5,o[20]),P=c(P,O,_,R,Q,9,o[21]),R=c(R,P,O,_,U,14,o[22]),_=c(_,R,P,O,k,20,o[23]),O=c(O,_,R,P,L,5,o[24]),P=c(P,O,_,R,F,9,o[25]),R=c(R,P,O,_,I,14,o[26]),_=c(_,R,P,O,E,20,o[27]),O=c(O,_,R,P,V,5,o[28]),P=c(P,O,_,R,A,9,o[29]),R=c(R,P,O,_,M,14,o[30]),_=c(_,R,P,O,z,20,o[31]),O=p(O,_,R,P,w,4,o[32]),P=p(P,O,_,R,E,11,o[33]),R=p(R,P,O,_,T,16,o[34]),_=p(_,R,P,O,F,23,o[35]),O=p(O,_,R,P,v,4,o[36]),P=p(P,O,_,R,k,11,o[37]),R=p(R,P,O,_,M,16,o[38]),_=p(_,R,P,O,Q,23,o[39]),O=p(O,_,R,P,V,4,o[40]),P=p(P,O,_,R,x,11,o[41]),R=p(R,P,O,_,I,16,o[42]),_=p(_,R,P,O,q,23,o[43]),O=p(O,_,R,P,L,4,o[44]),P=p(P,O,_,R,z,11,o[45]),R=p(R,P,O,_,U,16,o[46]),_=p(_,R,P,O,A,23,o[47]),O=l(O,_,R,P,x,6,o[48]),P=l(P,O,_,R,M,10,o[49]),R=l(R,P,O,_,F,15,o[50]),_=l(_,R,P,O,w,21,o[51]),O=l(O,_,R,P,z,6,o[52]),P=l(P,O,_,R,I,10,o[53]),R=l(R,P,O,_,Q,15,o[54]),_=l(_,R,P,O,v,21,o[55]),O=l(O,_,R,P,E,6,o[56]),P=l(P,O,_,R,U,10,o[57]),R=l(R,P,O,_,q,15,o[58]),_=l(_,R,P,O,V,21,o[59]),O=l(O,_,R,P,k,6,o[60]),P=l(P,O,_,R,T,10,o[61]),R=l(R,P,O,_,A,15,o[62]),_=l(_,R,P,O,L,21,o[63]),g[0]=g[0]+O|0,g[1]=g[1]+_|0,g[2]=g[2]+R|0,g[3]=g[3]+P|0},_doFinalize:function(){var m=this._data,f=m.words,y=this._nDataBytes*8,b=m.sigBytes*8;f[b>>>5]|=128<<24-b%32;var h=e.floor(y/4294967296),g=y;f[(b+64>>>9<<4)+15]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360,f[(b+64>>>9<<4)+14]=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360,m.sigBytes=(f.length+1)*4,this._process();for(var x=this._hash,v=x.words,A=0;A<4;A++){var I=v[A];v[A]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360}return x},clone:function(){var m=i.clone.call(this);return m._hash=this._hash.clone(),m}});function d(m,f,y,b,h,g,x){var v=m+(f&y|~f&b)+h+x;return(v<<g|v>>>32-g)+f}function c(m,f,y,b,h,g,x){var v=m+(f&b|y&~b)+h+x;return(v<<g|v>>>32-g)+f}function p(m,f,y,b,h,g,x){var v=m+(f^y^b)+h+x;return(v<<g|v>>>32-g)+f}function l(m,f,y,b,h,g,x){var v=m+(y^(f|~b))+h+x;return(v<<g|v>>>32-g)+f}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)})(Math),u.MD5})});var Ai=re((Sn,ra)=>{(function(u,e){typeof Sn=="object"?ra.exports=Sn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(Sn,function(u){return(function(){var e=u,t=e.lib,r=t.WordArray,n=t.Hasher,i=e.algo,a=[],o=i.SHA1=n.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(s,d){for(var c=this._hash.words,p=c[0],l=c[1],m=c[2],f=c[3],y=c[4],b=0;b<80;b++){if(b<16)a[b]=s[d+b]|0;else{var h=a[b-3]^a[b-8]^a[b-14]^a[b-16];a[b]=h<<1|h>>>31}var g=(p<<5|p>>>27)+y+a[b];b<20?g+=(l&m|~l&f)+1518500249:b<40?g+=(l^m^f)+1859775393:b<60?g+=(l&m|l&f|m&f)-1894007588:g+=(l^m^f)-899497514,y=f,f=m,m=l<<30|l>>>2,l=p,p=g}c[0]=c[0]+p|0,c[1]=c[1]+l|0,c[2]=c[2]+m|0,c[3]=c[3]+f|0,c[4]=c[4]+y|0},_doFinalize:function(){var s=this._data,d=s.words,c=this._nDataBytes*8,p=s.sigBytes*8;return d[p>>>5]|=128<<24-p%32,d[(p+64>>>9<<4)+14]=Math.floor(c/4294967296),d[(p+64>>>9<<4)+15]=c,s.sigBytes=d.length*4,this._process(),this._hash},clone:function(){var s=n.clone.call(this);return s._hash=this._hash.clone(),s}});e.SHA1=n._createHelper(o),e.HmacSHA1=n._createHmacHelper(o)})(),u.SHA1})});var Ut=re((In,na)=>{(function(u,e){typeof In=="object"?na.exports=In=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(In,function(u){return(function(e){var t=u,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[],s=[];(function(){function p(y){for(var b=e.sqrt(y),h=2;h<=b;h++)if(!(y%h))return!1;return!0}function l(y){return(y-(y|0))*4294967296|0}for(var m=2,f=0;f<64;)p(m)&&(f<8&&(o[f]=l(e.pow(m,1/2))),s[f]=l(e.pow(m,1/3)),f++),m++})();var d=[],c=a.SHA256=i.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(p,l){for(var m=this._hash.words,f=m[0],y=m[1],b=m[2],h=m[3],g=m[4],x=m[5],v=m[6],A=m[7],I=0;I<64;I++){if(I<16)d[I]=p[l+I]|0;else{var k=d[I-15],w=(k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3,q=d[I-2],M=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;d[I]=w+d[I-7]+M+d[I-16]}var E=g&x^~g&v,L=f&y^f&b^y&b,Q=(f<<30|f>>>2)^(f<<19|f>>>13)^(f<<10|f>>>22),T=(g<<26|g>>>6)^(g<<21|g>>>11)^(g<<7|g>>>25),z=A+T+E+s[I]+d[I],V=Q+L;A=v,v=x,x=g,g=h+z|0,h=b,b=y,y=f,f=z+V|0}m[0]=m[0]+f|0,m[1]=m[1]+y|0,m[2]=m[2]+b|0,m[3]=m[3]+h|0,m[4]=m[4]+g|0,m[5]=m[5]+x|0,m[6]=m[6]+v|0,m[7]=m[7]+A|0},_doFinalize:function(){var p=this._data,l=p.words,m=this._nDataBytes*8,f=p.sigBytes*8;return l[f>>>5]|=128<<24-f%32,l[(f+64>>>9<<4)+14]=e.floor(m/4294967296),l[(f+64>>>9<<4)+15]=m,p.sigBytes=l.length*4,this._process(),this._hash},clone:function(){var p=i.clone.call(this);return p._hash=this._hash.clone(),p}});t.SHA256=i._createHelper(c),t.HmacSHA256=i._createHmacHelper(c)})(Math),u.SHA256})});var aa=re((Pn,ia)=>{(function(u,e,t){typeof Pn=="object"?ia.exports=Pn=e(ae(),Ut()):typeof define=="function"&&define.amd?define(["./core","./sha256"],e):e(u.CryptoJS)})(Pn,function(u){return(function(){var e=u,t=e.lib,r=t.WordArray,n=e.algo,i=n.SHA256,a=n.SHA224=i.extend({_doReset:function(){this._hash=new r.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=i._doFinalize.call(this);return o.sigBytes-=4,o}});e.SHA224=i._createHelper(a),e.HmacSHA224=i._createHmacHelper(a)})(),u.SHA224})});var Si=re((Dn,oa)=>{(function(u,e,t){typeof Dn=="object"?oa.exports=Dn=e(ae(),_r()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(u.CryptoJS)})(Dn,function(u){return(function(){var e=u,t=e.lib,r=t.Hasher,n=e.x64,i=n.Word,a=n.WordArray,o=e.algo;function s(){return i.create.apply(i,arguments)}var d=[s(1116352408,3609767458),s(1899447441,602891725),s(3049323471,3964484399),s(3921009573,2173295548),s(961987163,4081628472),s(1508970993,3053834265),s(2453635748,2937671579),s(2870763221,3664609560),s(3624381080,2734883394),s(310598401,1164996542),s(607225278,1323610764),s(1426881987,3590304994),s(1925078388,4068182383),s(2162078206,991336113),s(2614888103,633803317),s(3248222580,3479774868),s(3835390401,2666613458),s(4022224774,944711139),s(264347078,2341262773),s(604807628,2007800933),s(770255983,1495990901),s(1249150122,1856431235),s(1555081692,3175218132),s(1996064986,2198950837),s(2554220882,3999719339),s(2821834349,766784016),s(2952996808,2566594879),s(3210313671,3203337956),s(3336571891,1034457026),s(3584528711,2466948901),s(113926993,3758326383),s(338241895,168717936),s(666307205,1188179964),s(773529912,1546045734),s(1294757372,1522805485),s(1396182291,2643833823),s(1695183700,2343527390),s(1986661051,1014477480),s(2177026350,1206759142),s(2456956037,344077627),s(2730485921,1290863460),s(2820302411,3158454273),s(3259730800,3505952657),s(3345764771,106217008),s(3516065817,3606008344),s(3600352804,1432725776),s(4094571909,1467031594),s(275423344,851169720),s(430227734,3100823752),s(506948616,1363258195),s(659060556,3750685593),s(883997877,3785050280),s(958139571,3318307427),s(1322822218,3812723403),s(1537002063,2003034995),s(1747873779,3602036899),s(1955562222,1575990012),s(2024104815,1125592928),s(2227730452,2716904306),s(2361852424,442776044),s(2428436474,593698344),s(2756734187,3733110249),s(3204031479,2999351573),s(3329325298,3815920427),s(3391569614,3928383900),s(3515267271,566280711),s(3940187606,3454069534),s(4118630271,4000239992),s(116418474,1914138554),s(174292421,2731055270),s(289380356,3203993006),s(460393269,320620315),s(685471733,587496836),s(852142971,1086792851),s(1017036298,365543100),s(1126000580,2618297676),s(1288033470,3409855158),s(1501505948,4234509866),s(1607167915,987167468),s(1816402316,1246189591)],c=[];(function(){for(var l=0;l<80;l++)c[l]=s()})();var p=o.SHA512=r.extend({_doReset:function(){this._hash=new a.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(l,m){for(var f=this._hash.words,y=f[0],b=f[1],h=f[2],g=f[3],x=f[4],v=f[5],A=f[6],I=f[7],k=y.high,w=y.low,q=b.high,M=b.low,E=h.high,L=h.low,Q=g.high,T=g.low,z=x.high,V=x.low,F=v.high,U=v.low,O=A.high,_=A.low,R=I.high,P=I.low,X=k,te=w,J=q,Y=M,be=E,se=L,Ne=Q,pe=T,Te=z,me=V,We=F,Ye=U,Xe=O,ct=_,bt=R,ut=P,qe=0;qe<80;qe++){var ke,Ue,vt=c[qe];if(qe<16)Ue=vt.high=l[m+qe*2]|0,ke=vt.low=l[m+qe*2+1]|0;else{var wt=c[qe-15],dt=wt.high,ht=wt.low,ft=(dt>>>1|ht<<31)^(dt>>>8|ht<<24)^dt>>>7,Et=(ht>>>1|dt<<31)^(ht>>>8|dt<<24)^(ht>>>7|dt<<25),Ot=c[qe-2],lt=Ot.high,st=Ot.low,S=(lt>>>19|st<<13)^(lt<<3|st>>>29)^lt>>>6,C=(st>>>19|lt<<13)^(st<<3|lt>>>29)^(st>>>6|lt<<26),B=c[qe-7],N=B.high,W=B.low,he=c[qe-16],ve=he.high,ee=he.low;ke=Et+W,Ue=ft+N+(ke>>>0<Et>>>0?1:0),ke=ke+C,Ue=Ue+S+(ke>>>0<C>>>0?1:0),ke=ke+ee,Ue=Ue+ve+(ke>>>0<ee>>>0?1:0),vt.high=Ue,vt.low=ke}var j=Te&We^~Te&Xe,$=me&Ye^~me&ct,K=X&J^X&be^J&be,G=te&Y^te&se^Y&se,ne=(X>>>28|te<<4)^(X<<30|te>>>2)^(X<<25|te>>>7),de=(te>>>28|X<<4)^(te<<30|X>>>2)^(te<<25|X>>>7),Ie=(Te>>>14|me<<18)^(Te>>>18|me<<14)^(Te<<23|me>>>9),Je=(me>>>14|Te<<18)^(me>>>18|Te<<14)^(me<<23|Te>>>9),Ht=d[qe],oi=Ht.high,Kr=Ht.low,Ze=ut+Je,St=bt+Ie+(Ze>>>0<ut>>>0?1:0),Ze=Ze+$,St=St+j+(Ze>>>0<$>>>0?1:0),Ze=Ze+Kr,St=St+oi+(Ze>>>0<Kr>>>0?1:0),Ze=Ze+ke,St=St+Ue+(Ze>>>0<ke>>>0?1:0),ki=de+G,fo=ne+K+(ki>>>0<de>>>0?1:0);bt=Xe,ut=ct,Xe=We,ct=Ye,We=Te,Ye=me,me=pe+Ze|0,Te=Ne+St+(me>>>0<pe>>>0?1:0)|0,Ne=be,pe=se,be=J,se=Y,J=X,Y=te,te=Ze+ki|0,X=St+fo+(te>>>0<Ze>>>0?1:0)|0}w=y.low=w+te,y.high=k+X+(w>>>0<te>>>0?1:0),M=b.low=M+Y,b.high=q+J+(M>>>0<Y>>>0?1:0),L=h.low=L+se,h.high=E+be+(L>>>0<se>>>0?1:0),T=g.low=T+pe,g.high=Q+Ne+(T>>>0<pe>>>0?1:0),V=x.low=V+me,x.high=z+Te+(V>>>0<me>>>0?1:0),U=v.low=U+Ye,v.high=F+We+(U>>>0<Ye>>>0?1:0),_=A.low=_+ct,A.high=O+Xe+(_>>>0<ct>>>0?1:0),P=I.low=P+ut,I.high=R+bt+(P>>>0<ut>>>0?1:0)},_doFinalize:function(){var l=this._data,m=l.words,f=this._nDataBytes*8,y=l.sigBytes*8;m[y>>>5]|=128<<24-y%32,m[(y+128>>>10<<5)+30]=Math.floor(f/4294967296),m[(y+128>>>10<<5)+31]=f,l.sigBytes=m.length*4,this._process();var b=this._hash.toX32();return b},clone:function(){var l=r.clone.call(this);return l._hash=this._hash.clone(),l},blockSize:1024/32});e.SHA512=r._createHelper(p),e.HmacSHA512=r._createHmacHelper(p)})(),u.SHA512})});var ca=re((Cn,sa)=>{(function(u,e,t){typeof Cn=="object"?sa.exports=Cn=e(ae(),_r(),Si()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./sha512"],e):e(u.CryptoJS)})(Cn,function(u){return(function(){var e=u,t=e.x64,r=t.Word,n=t.WordArray,i=e.algo,a=i.SHA512,o=i.SHA384=a.extend({_doReset:function(){this._hash=new n.init([new r.init(3418070365,3238371032),new r.init(1654270250,914150663),new r.init(2438529370,812702999),new r.init(355462360,4144912697),new r.init(1731405415,4290775857),new r.init(2394180231,1750603025),new r.init(3675008525,1694076839),new r.init(1203062813,3204075428)])},_doFinalize:function(){var s=a._doFinalize.call(this);return s.sigBytes-=16,s}});e.SHA384=a._createHelper(o),e.HmacSHA384=a._createHmacHelper(o)})(),u.SHA384})});var da=re((wn,ua)=>{(function(u,e,t){typeof wn=="object"?ua.exports=wn=e(ae(),_r()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(u.CryptoJS)})(wn,function(u){return(function(e){var t=u,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.x64,o=a.Word,s=t.algo,d=[],c=[],p=[];(function(){for(var f=1,y=0,b=0;b<24;b++){d[f+5*y]=(b+1)*(b+2)/2%64;var h=y%5,g=(2*f+3*y)%5;f=h,y=g}for(var f=0;f<5;f++)for(var y=0;y<5;y++)c[f+5*y]=y+(2*f+3*y)%5*5;for(var x=1,v=0;v<24;v++){for(var A=0,I=0,k=0;k<7;k++){if(x&1){var w=(1<<k)-1;w<32?I^=1<<w:A^=1<<w-32}x&128?x=x<<1^113:x<<=1}p[v]=o.create(A,I)}})();var l=[];(function(){for(var f=0;f<25;f++)l[f]=o.create()})();var m=s.SHA3=i.extend({cfg:i.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],y=0;y<25;y++)f[y]=new o.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,y){for(var b=this._state,h=this.blockSize/2,g=0;g<h;g++){var x=f[y+2*g],v=f[y+2*g+1];x=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,v=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360;var A=b[g];A.high^=v,A.low^=x}for(var I=0;I<24;I++){for(var k=0;k<5;k++){for(var w=0,q=0,M=0;M<5;M++){var A=b[k+5*M];w^=A.high,q^=A.low}var E=l[k];E.high=w,E.low=q}for(var k=0;k<5;k++)for(var L=l[(k+4)%5],Q=l[(k+1)%5],T=Q.high,z=Q.low,w=L.high^(T<<1|z>>>31),q=L.low^(z<<1|T>>>31),M=0;M<5;M++){var A=b[k+5*M];A.high^=w,A.low^=q}for(var V=1;V<25;V++){var w,q,A=b[V],F=A.high,U=A.low,O=d[V];O<32?(w=F<<O|U>>>32-O,q=U<<O|F>>>32-O):(w=U<<O-32|F>>>64-O,q=F<<O-32|U>>>64-O);var _=l[c[V]];_.high=w,_.low=q}var R=l[0],P=b[0];R.high=P.high,R.low=P.low;for(var k=0;k<5;k++)for(var M=0;M<5;M++){var V=k+5*M,A=b[V],X=l[V],te=l[(k+1)%5+5*M],J=l[(k+2)%5+5*M];A.high=X.high^~te.high&J.high,A.low=X.low^~te.low&J.low}var A=b[0],Y=p[I];A.high^=Y.high,A.low^=Y.low}},_doFinalize:function(){var f=this._data,y=f.words,b=this._nDataBytes*8,h=f.sigBytes*8,g=this.blockSize*32;y[h>>>5]|=1<<24-h%32,y[(e.ceil((h+1)/g)*g>>>5)-1]|=128,f.sigBytes=y.length*4,this._process();for(var x=this._state,v=this.cfg.outputLength/8,A=v/8,I=[],k=0;k<A;k++){var w=x[k],q=w.high,M=w.low;q=(q<<8|q>>>24)&16711935|(q<<24|q>>>8)&4278255360,M=(M<<8|M>>>24)&16711935|(M<<24|M>>>8)&4278255360,I.push(M),I.push(q)}return new n.init(I,v)},clone:function(){for(var f=i.clone.call(this),y=f._state=this._state.slice(0),b=0;b<25;b++)y[b]=y[b].clone();return f}});t.SHA3=i._createHelper(m),t.HmacSHA3=i._createHmacHelper(m)})(Math),u.SHA3})});var pa=re((En,la)=>{(function(u,e){typeof En=="object"?la.exports=En=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(En,function(u){return(function(e){var t=u,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),s=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),d=n.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),c=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),p=n.create([0,1518500249,1859775393,2400959708,2840853838]),l=n.create([1352829926,1548603684,1836072691,2053994217,0]),m=a.RIPEMD160=i.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(v,A){for(var I=0;I<16;I++){var k=A+I,w=v[k];v[k]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var q=this._hash.words,M=p.words,E=l.words,L=o.words,Q=s.words,T=d.words,z=c.words,V,F,U,O,_,R,P,X,te,J;R=V=q[0],P=F=q[1],X=U=q[2],te=O=q[3],J=_=q[4];for(var Y,I=0;I<80;I+=1)Y=V+v[A+L[I]]|0,I<16?Y+=f(F,U,O)+M[0]:I<32?Y+=y(F,U,O)+M[1]:I<48?Y+=b(F,U,O)+M[2]:I<64?Y+=h(F,U,O)+M[3]:Y+=g(F,U,O)+M[4],Y=Y|0,Y=x(Y,T[I]),Y=Y+_|0,V=_,_=O,O=x(U,10),U=F,F=Y,Y=R+v[A+Q[I]]|0,I<16?Y+=g(P,X,te)+E[0]:I<32?Y+=h(P,X,te)+E[1]:I<48?Y+=b(P,X,te)+E[2]:I<64?Y+=y(P,X,te)+E[3]:Y+=f(P,X,te)+E[4],Y=Y|0,Y=x(Y,z[I]),Y=Y+J|0,R=J,J=te,te=x(X,10),X=P,P=Y;Y=q[1]+U+te|0,q[1]=q[2]+O+J|0,q[2]=q[3]+_+R|0,q[3]=q[4]+V+P|0,q[4]=q[0]+F+X|0,q[0]=Y},_doFinalize:function(){var v=this._data,A=v.words,I=this._nDataBytes*8,k=v.sigBytes*8;A[k>>>5]|=128<<24-k%32,A[(k+64>>>9<<4)+14]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360,v.sigBytes=(A.length+1)*4,this._process();for(var w=this._hash,q=w.words,M=0;M<5;M++){var E=q[M];q[M]=(E<<8|E>>>24)&16711935|(E<<24|E>>>8)&4278255360}return w},clone:function(){var v=i.clone.call(this);return v._hash=this._hash.clone(),v}});function f(v,A,I){return v^A^I}function y(v,A,I){return v&A|~v&I}function b(v,A,I){return(v|~A)^I}function h(v,A,I){return v&I|A&~I}function g(v,A,I){return v^(A|~I)}function x(v,A){return v<<A|v>>>32-A}t.RIPEMD160=i._createHelper(m),t.HmacRIPEMD160=i._createHmacHelper(m)})(Math),u.RIPEMD160})});var Tr=re((On,ma)=>{(function(u,e){typeof On=="object"?ma.exports=On=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(On,function(u){(function(){var e=u,t=e.lib,r=t.Base,n=e.enc,i=n.Utf8,a=e.algo,o=a.HMAC=r.extend({init:function(s,d){s=this._hasher=new s.init,typeof d=="string"&&(d=i.parse(d));var c=s.blockSize,p=c*4;d.sigBytes>p&&(d=s.finalize(d)),d.clamp();for(var l=this._oKey=d.clone(),m=this._iKey=d.clone(),f=l.words,y=m.words,b=0;b<c;b++)f[b]^=1549556828,y[b]^=909522486;l.sigBytes=m.sigBytes=p,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var d=this._hasher,c=d.finalize(s);d.reset();var p=d.finalize(this._oKey.clone().concat(c));return p}})})()})});var fa=re((Rn,ha)=>{(function(u,e,t){typeof Rn=="object"?ha.exports=Rn=e(ae(),Ut(),Tr()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(u.CryptoJS)})(Rn,function(u){return(function(){var e=u,t=e.lib,r=t.Base,n=t.WordArray,i=e.algo,a=i.SHA256,o=i.HMAC,s=i.PBKDF2=r.extend({cfg:r.extend({keySize:128/32,hasher:a,iterations:25e4}),init:function(d){this.cfg=this.cfg.extend(d)},compute:function(d,c){for(var p=this.cfg,l=o.create(p.hasher,d),m=n.create(),f=n.create([1]),y=m.words,b=f.words,h=p.keySize,g=p.iterations;y.length<h;){var x=l.update(c).finalize(f);l.reset();for(var v=x.words,A=v.length,I=x,k=1;k<g;k++){I=l.finalize(I),l.reset();for(var w=I.words,q=0;q<A;q++)v[q]^=w[q]}m.concat(x),b[0]++}return m.sigBytes=h*4,m}});e.PBKDF2=function(d,c,p){return s.create(p).compute(d,c)}})(),u.PBKDF2})});var At=re((_n,ga)=>{(function(u,e,t){typeof _n=="object"?ga.exports=_n=e(ae(),Ai(),Tr()):typeof define=="function"&&define.amd?define(["./core","./sha1","./hmac"],e):e(u.CryptoJS)})(_n,function(u){return(function(){var e=u,t=e.lib,r=t.Base,n=t.WordArray,i=e.algo,a=i.MD5,o=i.EvpKDF=r.extend({cfg:r.extend({keySize:128/32,hasher:a,iterations:1}),init:function(s){this.cfg=this.cfg.extend(s)},compute:function(s,d){for(var c,p=this.cfg,l=p.hasher.create(),m=n.create(),f=m.words,y=p.keySize,b=p.iterations;f.length<y;){c&&l.update(c),c=l.update(s).finalize(d),l.reset();for(var h=1;h<b;h++)c=l.finalize(c),l.reset();m.concat(c)}return m.sigBytes=y*4,m}});e.EvpKDF=function(s,d,c){return o.create(c).compute(s,d)}})(),u.EvpKDF})});var Fe=re((Tn,ya)=>{(function(u,e,t){typeof Tn=="object"?ya.exports=Tn=e(ae(),At()):typeof define=="function"&&define.amd?define(["./core","./evpkdf"],e):e(u.CryptoJS)})(Tn,function(u){u.lib.Cipher||(function(e){var t=u,r=t.lib,n=r.Base,i=r.WordArray,a=r.BufferedBlockAlgorithm,o=t.enc,s=o.Utf8,d=o.Base64,c=t.algo,p=c.EvpKDF,l=r.Cipher=a.extend({cfg:n.extend(),createEncryptor:function(E,L){return this.create(this._ENC_XFORM_MODE,E,L)},createDecryptor:function(E,L){return this.create(this._DEC_XFORM_MODE,E,L)},init:function(E,L,Q){this.cfg=this.cfg.extend(Q),this._xformMode=E,this._key=L,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(E){return this._append(E),this._process()},finalize:function(E){E&&this._append(E);var L=this._doFinalize();return L},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:(function(){function E(L){return typeof L=="string"?M:k}return function(L){return{encrypt:function(Q,T,z){return E(T).encrypt(L,Q,T,z)},decrypt:function(Q,T,z){return E(T).decrypt(L,Q,T,z)}}}})()}),m=r.StreamCipher=l.extend({_doFinalize:function(){var E=this._process(!0);return E},blockSize:1}),f=t.mode={},y=r.BlockCipherMode=n.extend({createEncryptor:function(E,L){return this.Encryptor.create(E,L)},createDecryptor:function(E,L){return this.Decryptor.create(E,L)},init:function(E,L){this._cipher=E,this._iv=L}}),b=f.CBC=(function(){var E=y.extend();E.Encryptor=E.extend({processBlock:function(Q,T){var z=this._cipher,V=z.blockSize;L.call(this,Q,T,V),z.encryptBlock(Q,T),this._prevBlock=Q.slice(T,T+V)}}),E.Decryptor=E.extend({processBlock:function(Q,T){var z=this._cipher,V=z.blockSize,F=Q.slice(T,T+V);z.decryptBlock(Q,T),L.call(this,Q,T,V),this._prevBlock=F}});function L(Q,T,z){var V,F=this._iv;F?(V=F,this._iv=e):V=this._prevBlock;for(var U=0;U<z;U++)Q[T+U]^=V[U]}return E})(),h=t.pad={},g=h.Pkcs7={pad:function(E,L){for(var Q=L*4,T=Q-E.sigBytes%Q,z=T<<24|T<<16|T<<8|T,V=[],F=0;F<T;F+=4)V.push(z);var U=i.create(V,T);E.concat(U)},unpad:function(E){var L=E.words[E.sigBytes-1>>>2]&255;E.sigBytes-=L}},x=r.BlockCipher=l.extend({cfg:l.cfg.extend({mode:b,padding:g}),reset:function(){var E;l.reset.call(this);var L=this.cfg,Q=L.iv,T=L.mode;this._xformMode==this._ENC_XFORM_MODE?E=T.createEncryptor:(E=T.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==E?this._mode.init(this,Q&&Q.words):(this._mode=E.call(T,this,Q&&Q.words),this._mode.__creator=E)},_doProcessBlock:function(E,L){this._mode.processBlock(E,L)},_doFinalize:function(){var E,L=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(L.pad(this._data,this.blockSize),E=this._process(!0)):(E=this._process(!0),L.unpad(E)),E},blockSize:128/32}),v=r.CipherParams=n.extend({init:function(E){this.mixIn(E)},toString:function(E){return(E||this.formatter).stringify(this)}}),A=t.format={},I=A.OpenSSL={stringify:function(E){var L,Q=E.ciphertext,T=E.salt;return T?L=i.create([1398893684,1701076831]).concat(T).concat(Q):L=Q,L.toString(d)},parse:function(E){var L,Q=d.parse(E),T=Q.words;return T[0]==1398893684&&T[1]==1701076831&&(L=i.create(T.slice(2,4)),T.splice(0,4),Q.sigBytes-=16),v.create({ciphertext:Q,salt:L})}},k=r.SerializableCipher=n.extend({cfg:n.extend({format:I}),encrypt:function(E,L,Q,T){T=this.cfg.extend(T);var z=E.createEncryptor(Q,T),V=z.finalize(L),F=z.cfg;return v.create({ciphertext:V,key:Q,iv:F.iv,algorithm:E,mode:F.mode,padding:F.padding,blockSize:E.blockSize,formatter:T.format})},decrypt:function(E,L,Q,T){T=this.cfg.extend(T),L=this._parse(L,T.format);var z=E.createDecryptor(Q,T).finalize(L.ciphertext);return z},_parse:function(E,L){return typeof E=="string"?L.parse(E,this):E}}),w=t.kdf={},q=w.OpenSSL={execute:function(E,L,Q,T,z){if(T||(T=i.random(64/8)),z)var V=p.create({keySize:L+Q,hasher:z}).compute(E,T);else var V=p.create({keySize:L+Q}).compute(E,T);var F=i.create(V.words.slice(L),Q*4);return V.sigBytes=L*4,v.create({key:V,iv:F,salt:T})}},M=r.PasswordBasedCipher=k.extend({cfg:k.cfg.extend({kdf:q}),encrypt:function(E,L,Q,T){T=this.cfg.extend(T);var z=T.kdf.execute(Q,E.keySize,E.ivSize,T.salt,T.hasher);T.iv=z.iv;var V=k.encrypt.call(this,E,L,z.key,T);return V.mixIn(z),V},decrypt:function(E,L,Q,T){T=this.cfg.extend(T),L=this._parse(L,T.format);var z=T.kdf.execute(Q,E.keySize,E.ivSize,L.salt,T.hasher);T.iv=z.iv;var V=k.decrypt.call(this,E,L,z.key,T);return V}})})()})});var va=re((Fn,ba)=>{(function(u,e,t){typeof Fn=="object"?ba.exports=Fn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Fn,function(u){return u.mode.CFB=(function(){var e=u.lib.BlockCipherMode.extend();e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize;t.call(this,r,n,a,i),this._prevBlock=r.slice(n,n+a)}}),e.Decryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=r.slice(n,n+a);t.call(this,r,n,a,i),this._prevBlock=o}});function t(r,n,i,a){var o,s=this._iv;s?(o=s.slice(0),this._iv=void 0):o=this._prevBlock,a.encryptBlock(o,0);for(var d=0;d<i;d++)r[n+d]^=o[d]}return e})(),u.mode.CFB})});var Aa=re((kn,xa)=>{(function(u,e,t){typeof kn=="object"?xa.exports=kn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(kn,function(u){return u.mode.CTR=(function(){var e=u.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=this._iv,s=this._counter;o&&(s=this._counter=o.slice(0),this._iv=void 0);var d=s.slice(0);i.encryptBlock(d,0),s[a-1]=s[a-1]+1|0;for(var c=0;c<a;c++)r[n+c]^=d[c]}});return e.Decryptor=t,e})(),u.mode.CTR})});var Ia=re((Bn,Sa)=>{(function(u,e,t){typeof Bn=="object"?Sa.exports=Bn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Bn,function(u){return u.mode.CTRGladman=(function(){var e=u.lib.BlockCipherMode.extend();function t(i){if((i>>24&255)===255){var a=i>>16&255,o=i>>8&255,s=i&255;a===255?(a=0,o===255?(o=0,s===255?s=0:++s):++o):++a,i=0,i+=a<<16,i+=o<<8,i+=s}else i+=1<<24;return i}function r(i){return(i[0]=t(i[0]))===0&&(i[1]=t(i[1])),i}var n=e.Encryptor=e.extend({processBlock:function(i,a){var o=this._cipher,s=o.blockSize,d=this._iv,c=this._counter;d&&(c=this._counter=d.slice(0),this._iv=void 0),r(c);var p=c.slice(0);o.encryptBlock(p,0);for(var l=0;l<s;l++)i[a+l]^=p[l]}});return e.Decryptor=n,e})(),u.mode.CTRGladman})});var Da=re((Mn,Pa)=>{(function(u,e,t){typeof Mn=="object"?Pa.exports=Mn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Mn,function(u){return u.mode.OFB=(function(){var e=u.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=this._iv,s=this._keystream;o&&(s=this._keystream=o.slice(0),this._iv=void 0),i.encryptBlock(s,0);for(var d=0;d<a;d++)r[n+d]^=s[d]}});return e.Decryptor=t,e})(),u.mode.OFB})});var wa=re((qn,Ca)=>{(function(u,e,t){typeof qn=="object"?Ca.exports=qn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(qn,function(u){return u.mode.ECB=(function(){var e=u.lib.BlockCipherMode.extend();return e.Encryptor=e.extend({processBlock:function(t,r){this._cipher.encryptBlock(t,r)}}),e.Decryptor=e.extend({processBlock:function(t,r){this._cipher.decryptBlock(t,r)}}),e})(),u.mode.ECB})});var Oa=re((Ln,Ea)=>{(function(u,e,t){typeof Ln=="object"?Ea.exports=Ln=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Ln,function(u){return u.pad.AnsiX923={pad:function(e,t){var r=e.sigBytes,n=t*4,i=n-r%n,a=r+i-1;e.clamp(),e.words[a>>>2]|=i<<24-a%4*8,e.sigBytes+=i},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},u.pad.Ansix923})});var _a=re((Nn,Ra)=>{(function(u,e,t){typeof Nn=="object"?Ra.exports=Nn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Nn,function(u){return u.pad.Iso10126={pad:function(e,t){var r=t*4,n=r-e.sigBytes%r;e.concat(u.lib.WordArray.random(n-1)).concat(u.lib.WordArray.create([n<<24],1))},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},u.pad.Iso10126})});var Fa=re((Qn,Ta)=>{(function(u,e,t){typeof Qn=="object"?Ta.exports=Qn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Qn,function(u){return u.pad.Iso97971={pad:function(e,t){e.concat(u.lib.WordArray.create([2147483648],1)),u.pad.ZeroPadding.pad(e,t)},unpad:function(e){u.pad.ZeroPadding.unpad(e),e.sigBytes--}},u.pad.Iso97971})});var Ba=re((Un,ka)=>{(function(u,e,t){typeof Un=="object"?ka.exports=Un=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Un,function(u){return u.pad.ZeroPadding={pad:function(e,t){var r=t*4;e.clamp(),e.sigBytes+=r-(e.sigBytes%r||r)},unpad:function(e){for(var t=e.words,r=e.sigBytes-1,r=e.sigBytes-1;r>=0;r--)if(t[r>>>2]>>>24-r%4*8&255){e.sigBytes=r+1;break}}},u.pad.ZeroPadding})});var qa=re((Hn,Ma)=>{(function(u,e,t){typeof Hn=="object"?Ma.exports=Hn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Hn,function(u){return u.pad.NoPadding={pad:function(){},unpad:function(){}},u.pad.NoPadding})});var Na=re((jn,La)=>{(function(u,e,t){typeof jn=="object"?La.exports=jn=e(ae(),Fe()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(jn,function(u){return(function(e){var t=u,r=t.lib,n=r.CipherParams,i=t.enc,a=i.Hex,o=t.format,s=o.Hex={stringify:function(d){return d.ciphertext.toString(a)},parse:function(d){var c=a.parse(d);return n.create({ciphertext:c})}}})(),u.format.Hex})});var Ua=re(($n,Qa)=>{(function(u,e,t){typeof $n=="object"?Qa.exports=$n=e(ae(),Dt(),Ct(),At(),Fe()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(u.CryptoJS)})($n,function(u){return(function(){var e=u,t=e.lib,r=t.BlockCipher,n=e.algo,i=[],a=[],o=[],s=[],d=[],c=[],p=[],l=[],m=[],f=[];(function(){for(var h=[],g=0;g<256;g++)g<128?h[g]=g<<1:h[g]=g<<1^283;for(var x=0,v=0,g=0;g<256;g++){var A=v^v<<1^v<<2^v<<3^v<<4;A=A>>>8^A&255^99,i[x]=A,a[A]=x;var I=h[x],k=h[I],w=h[k],q=h[A]*257^A*16843008;o[x]=q<<24|q>>>8,s[x]=q<<16|q>>>16,d[x]=q<<8|q>>>24,c[x]=q;var q=w*16843009^k*65537^I*257^x*16843008;p[A]=q<<24|q>>>8,l[A]=q<<16|q>>>16,m[A]=q<<8|q>>>24,f[A]=q,x?(x=I^h[h[h[w^I]]],v^=h[h[v]]):x=v=1}})();var y=[0,1,2,4,8,16,32,64,128,27,54],b=n.AES=r.extend({_doReset:function(){var h;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var g=this._keyPriorReset=this._key,x=g.words,v=g.sigBytes/4,A=this._nRounds=v+6,I=(A+1)*4,k=this._keySchedule=[],w=0;w<I;w++)w<v?k[w]=x[w]:(h=k[w-1],w%v?v>6&&w%v==4&&(h=i[h>>>24]<<24|i[h>>>16&255]<<16|i[h>>>8&255]<<8|i[h&255]):(h=h<<8|h>>>24,h=i[h>>>24]<<24|i[h>>>16&255]<<16|i[h>>>8&255]<<8|i[h&255],h^=y[w/v|0]<<24),k[w]=k[w-v]^h);for(var q=this._invKeySchedule=[],M=0;M<I;M++){var w=I-M;if(M%4)var h=k[w];else var h=k[w-4];M<4||w<=4?q[M]=h:q[M]=p[i[h>>>24]]^l[i[h>>>16&255]]^m[i[h>>>8&255]]^f[i[h&255]]}}},encryptBlock:function(h,g){this._doCryptBlock(h,g,this._keySchedule,o,s,d,c,i)},decryptBlock:function(h,g){var x=h[g+1];h[g+1]=h[g+3],h[g+3]=x,this._doCryptBlock(h,g,this._invKeySchedule,p,l,m,f,a);var x=h[g+1];h[g+1]=h[g+3],h[g+3]=x},_doCryptBlock:function(h,g,x,v,A,I,k,w){for(var q=this._nRounds,M=h[g]^x[0],E=h[g+1]^x[1],L=h[g+2]^x[2],Q=h[g+3]^x[3],T=4,z=1;z<q;z++){var V=v[M>>>24]^A[E>>>16&255]^I[L>>>8&255]^k[Q&255]^x[T++],F=v[E>>>24]^A[L>>>16&255]^I[Q>>>8&255]^k[M&255]^x[T++],U=v[L>>>24]^A[Q>>>16&255]^I[M>>>8&255]^k[E&255]^x[T++],O=v[Q>>>24]^A[M>>>16&255]^I[E>>>8&255]^k[L&255]^x[T++];M=V,E=F,L=U,Q=O}var V=(w[M>>>24]<<24|w[E>>>16&255]<<16|w[L>>>8&255]<<8|w[Q&255])^x[T++],F=(w[E>>>24]<<24|w[L>>>16&255]<<16|w[Q>>>8&255]<<8|w[M&255])^x[T++],U=(w[L>>>24]<<24|w[Q>>>16&255]<<16|w[M>>>8&255]<<8|w[E&255])^x[T++],O=(w[Q>>>24]<<24|w[M>>>16&255]<<16|w[E>>>8&255]<<8|w[L&255])^x[T++];h[g]=V,h[g+1]=F,h[g+2]=U,h[g+3]=O},keySize:256/32});e.AES=r._createHelper(b)})(),u.AES})});var ja=re((Vn,Ha)=>{(function(u,e,t){typeof Vn=="object"?Ha.exports=Vn=e(ae(),Dt(),Ct(),At(),Fe()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(u.CryptoJS)})(Vn,function(u){return(function(){var e=u,t=e.lib,r=t.WordArray,n=t.BlockCipher,i=e.algo,a=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],s=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],d=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],c=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],p=i.DES=n.extend({_doReset:function(){for(var y=this._key,b=y.words,h=[],g=0;g<56;g++){var x=a[g]-1;h[g]=b[x>>>5]>>>31-x%32&1}for(var v=this._subKeys=[],A=0;A<16;A++){for(var I=v[A]=[],k=s[A],g=0;g<24;g++)I[g/6|0]|=h[(o[g]-1+k)%28]<<31-g%6,I[4+(g/6|0)]|=h[28+(o[g+24]-1+k)%28]<<31-g%6;I[0]=I[0]<<1|I[0]>>>31;for(var g=1;g<7;g++)I[g]=I[g]>>>(g-1)*4+3;I[7]=I[7]<<5|I[7]>>>27}for(var w=this._invSubKeys=[],g=0;g<16;g++)w[g]=v[15-g]},encryptBlock:function(y,b){this._doCryptBlock(y,b,this._subKeys)},decryptBlock:function(y,b){this._doCryptBlock(y,b,this._invSubKeys)},_doCryptBlock:function(y,b,h){this._lBlock=y[b],this._rBlock=y[b+1],l.call(this,4,252645135),l.call(this,16,65535),m.call(this,2,858993459),m.call(this,8,16711935),l.call(this,1,1431655765);for(var g=0;g<16;g++){for(var x=h[g],v=this._lBlock,A=this._rBlock,I=0,k=0;k<8;k++)I|=d[k][((A^x[k])&c[k])>>>0];this._lBlock=A,this._rBlock=v^I}var w=this._lBlock;this._lBlock=this._rBlock,this._rBlock=w,l.call(this,1,1431655765),m.call(this,8,16711935),m.call(this,2,858993459),l.call(this,16,65535),l.call(this,4,252645135),y[b]=this._lBlock,y[b+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function l(y,b){var h=(this._lBlock>>>y^this._rBlock)&b;this._rBlock^=h,this._lBlock^=h<<y}function m(y,b){var h=(this._rBlock>>>y^this._lBlock)&b;this._lBlock^=h,this._rBlock^=h<<y}e.DES=n._createHelper(p);var f=i.TripleDES=n.extend({_doReset:function(){var y=this._key,b=y.words;if(b.length!==2&&b.length!==4&&b.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var h=b.slice(0,2),g=b.length<4?b.slice(0,2):b.slice(2,4),x=b.length<6?b.slice(0,2):b.slice(4,6);this._des1=p.createEncryptor(r.create(h)),this._des2=p.createEncryptor(r.create(g)),this._des3=p.createEncryptor(r.create(x))},encryptBlock:function(y,b){this._des1.encryptBlock(y,b),this._des2.decryptBlock(y,b),this._des3.encryptBlock(y,b)},decryptBlock:function(y,b){this._des3.decryptBlock(y,b),this._des2.encryptBlock(y,b),this._des1.decryptBlock(y,b)},keySize:192/32,ivSize:64/32,blockSize:64/32});e.TripleDES=n._createHelper(f)})(),u.TripleDES})});var Va=re((zn,$a)=>{(function(u,e,t){typeof zn=="object"?$a.exports=zn=e(ae(),Dt(),Ct(),At(),Fe()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(u.CryptoJS)})(zn,function(u){return(function(){var e=u,t=e.lib,r=t.StreamCipher,n=e.algo,i=n.RC4=r.extend({_doReset:function(){for(var s=this._key,d=s.words,c=s.sigBytes,p=this._S=[],l=0;l<256;l++)p[l]=l;for(var l=0,m=0;l<256;l++){var f=l%c,y=d[f>>>2]>>>24-f%4*8&255;m=(m+p[l]+y)%256;var b=p[l];p[l]=p[m],p[m]=b}this._i=this._j=0},_doProcessBlock:function(s,d){s[d]^=a.call(this)},keySize:256/32,ivSize:0});function a(){for(var s=this._S,d=this._i,c=this._j,p=0,l=0;l<4;l++){d=(d+1)%256,c=(c+s[d])%256;var m=s[d];s[d]=s[c],s[c]=m,p|=s[(s[d]+s[c])%256]<<24-l*8}return this._i=d,this._j=c,p}e.RC4=r._createHelper(i);var o=n.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var s=this.cfg.drop;s>0;s--)a.call(this)}});e.RC4Drop=r._createHelper(o)})(),u.RC4})});var Ka=re((Kn,za)=>{(function(u,e,t){typeof Kn=="object"?za.exports=Kn=e(ae(),Dt(),Ct(),At(),Fe()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(u.CryptoJS)})(Kn,function(u){return(function(){var e=u,t=e.lib,r=t.StreamCipher,n=e.algo,i=[],a=[],o=[],s=n.Rabbit=r.extend({_doReset:function(){for(var c=this._key.words,p=this.cfg.iv,l=0;l<4;l++)c[l]=(c[l]<<8|c[l]>>>24)&16711935|(c[l]<<24|c[l]>>>8)&4278255360;var m=this._X=[c[0],c[3]<<16|c[2]>>>16,c[1],c[0]<<16|c[3]>>>16,c[2],c[1]<<16|c[0]>>>16,c[3],c[2]<<16|c[1]>>>16],f=this._C=[c[2]<<16|c[2]>>>16,c[0]&4294901760|c[1]&65535,c[3]<<16|c[3]>>>16,c[1]&4294901760|c[2]&65535,c[0]<<16|c[0]>>>16,c[2]&4294901760|c[3]&65535,c[1]<<16|c[1]>>>16,c[3]&4294901760|c[0]&65535];this._b=0;for(var l=0;l<4;l++)d.call(this);for(var l=0;l<8;l++)f[l]^=m[l+4&7];if(p){var y=p.words,b=y[0],h=y[1],g=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360,x=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360,v=g>>>16|x&4294901760,A=x<<16|g&65535;f[0]^=g,f[1]^=v,f[2]^=x,f[3]^=A,f[4]^=g,f[5]^=v,f[6]^=x,f[7]^=A;for(var l=0;l<4;l++)d.call(this)}},_doProcessBlock:function(c,p){var l=this._X;d.call(this),i[0]=l[0]^l[5]>>>16^l[3]<<16,i[1]=l[2]^l[7]>>>16^l[5]<<16,i[2]=l[4]^l[1]>>>16^l[7]<<16,i[3]=l[6]^l[3]>>>16^l[1]<<16;for(var m=0;m<4;m++)i[m]=(i[m]<<8|i[m]>>>24)&16711935|(i[m]<<24|i[m]>>>8)&4278255360,c[p+m]^=i[m]},blockSize:128/32,ivSize:64/32});function d(){for(var c=this._X,p=this._C,l=0;l<8;l++)a[l]=p[l];p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<a[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<a[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<a[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<a[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<a[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<a[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<a[6]>>>0?1:0)|0,this._b=p[7]>>>0<a[7]>>>0?1:0;for(var l=0;l<8;l++){var m=c[l]+p[l],f=m&65535,y=m>>>16,b=((f*f>>>17)+f*y>>>15)+y*y,h=((m&4294901760)*m|0)+((m&65535)*m|0);o[l]=b^h}c[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,c[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,c[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,c[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,c[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,c[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,c[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,c[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.Rabbit=r._createHelper(s)})(),u.Rabbit})});var Wa=re((Gn,Ga)=>{(function(u,e,t){typeof Gn=="object"?Ga.exports=Gn=e(ae(),Dt(),Ct(),At(),Fe()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(u.CryptoJS)})(Gn,function(u){return(function(){var e=u,t=e.lib,r=t.StreamCipher,n=e.algo,i=[],a=[],o=[],s=n.RabbitLegacy=r.extend({_doReset:function(){var c=this._key.words,p=this.cfg.iv,l=this._X=[c[0],c[3]<<16|c[2]>>>16,c[1],c[0]<<16|c[3]>>>16,c[2],c[1]<<16|c[0]>>>16,c[3],c[2]<<16|c[1]>>>16],m=this._C=[c[2]<<16|c[2]>>>16,c[0]&4294901760|c[1]&65535,c[3]<<16|c[3]>>>16,c[1]&4294901760|c[2]&65535,c[0]<<16|c[0]>>>16,c[2]&4294901760|c[3]&65535,c[1]<<16|c[1]>>>16,c[3]&4294901760|c[0]&65535];this._b=0;for(var f=0;f<4;f++)d.call(this);for(var f=0;f<8;f++)m[f]^=l[f+4&7];if(p){var y=p.words,b=y[0],h=y[1],g=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360,x=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360,v=g>>>16|x&4294901760,A=x<<16|g&65535;m[0]^=g,m[1]^=v,m[2]^=x,m[3]^=A,m[4]^=g,m[5]^=v,m[6]^=x,m[7]^=A;for(var f=0;f<4;f++)d.call(this)}},_doProcessBlock:function(c,p){var l=this._X;d.call(this),i[0]=l[0]^l[5]>>>16^l[3]<<16,i[1]=l[2]^l[7]>>>16^l[5]<<16,i[2]=l[4]^l[1]>>>16^l[7]<<16,i[3]=l[6]^l[3]>>>16^l[1]<<16;for(var m=0;m<4;m++)i[m]=(i[m]<<8|i[m]>>>24)&16711935|(i[m]<<24|i[m]>>>8)&4278255360,c[p+m]^=i[m]},blockSize:128/32,ivSize:64/32});function d(){for(var c=this._X,p=this._C,l=0;l<8;l++)a[l]=p[l];p[0]=p[0]+1295307597+this._b|0,p[1]=p[1]+3545052371+(p[0]>>>0<a[0]>>>0?1:0)|0,p[2]=p[2]+886263092+(p[1]>>>0<a[1]>>>0?1:0)|0,p[3]=p[3]+1295307597+(p[2]>>>0<a[2]>>>0?1:0)|0,p[4]=p[4]+3545052371+(p[3]>>>0<a[3]>>>0?1:0)|0,p[5]=p[5]+886263092+(p[4]>>>0<a[4]>>>0?1:0)|0,p[6]=p[6]+1295307597+(p[5]>>>0<a[5]>>>0?1:0)|0,p[7]=p[7]+3545052371+(p[6]>>>0<a[6]>>>0?1:0)|0,this._b=p[7]>>>0<a[7]>>>0?1:0;for(var l=0;l<8;l++){var m=c[l]+p[l],f=m&65535,y=m>>>16,b=((f*f>>>17)+f*y>>>15)+y*y,h=((m&4294901760)*m|0)+((m&65535)*m|0);o[l]=b^h}c[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,c[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,c[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,c[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,c[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,c[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,c[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,c[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.RabbitLegacy=r._createHelper(s)})(),u.RabbitLegacy})});var Xa=re((Wn,Ya)=>{(function(u,e,t){typeof Wn=="object"?Ya.exports=Wn=e(ae(),Dt(),Ct(),At(),Fe()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(u.CryptoJS)})(Wn,function(u){return(function(){var e=u,t=e.lib,r=t.BlockCipher,n=e.algo;let i=16,a=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],o=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var s={pbox:[],sbox:[]};function d(f,y){let b=y>>24&255,h=y>>16&255,g=y>>8&255,x=y&255,v=f.sbox[0][b]+f.sbox[1][h];return v=v^f.sbox[2][g],v=v+f.sbox[3][x],v}function c(f,y,b){let h=y,g=b,x;for(let v=0;v<i;++v)h=h^f.pbox[v],g=d(f,h)^g,x=h,h=g,g=x;return x=h,h=g,g=x,g=g^f.pbox[i],h=h^f.pbox[i+1],{left:h,right:g}}function p(f,y,b){let h=y,g=b,x;for(let v=i+1;v>1;--v)h=h^f.pbox[v],g=d(f,h)^g,x=h,h=g,g=x;return x=h,h=g,g=x,g=g^f.pbox[1],h=h^f.pbox[0],{left:h,right:g}}function l(f,y,b){for(let A=0;A<4;A++){f.sbox[A]=[];for(let I=0;I<256;I++)f.sbox[A][I]=o[A][I]}let h=0;for(let A=0;A<i+2;A++)f.pbox[A]=a[A]^y[h],h++,h>=b&&(h=0);let g=0,x=0,v=0;for(let A=0;A<i+2;A+=2)v=c(f,g,x),g=v.left,x=v.right,f.pbox[A]=g,f.pbox[A+1]=x;for(let A=0;A<4;A++)for(let I=0;I<256;I+=2)v=c(f,g,x),g=v.left,x=v.right,f.sbox[A][I]=g,f.sbox[A][I+1]=x;return!0}var m=n.Blowfish=r.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,y=f.words,b=f.sigBytes/4;l(s,y,b)}},encryptBlock:function(f,y){var b=c(s,f[y],f[y+1]);f[y]=b.left,f[y+1]=b.right},decryptBlock:function(f,y){var b=p(s,f[y],f[y+1]);f[y]=b.left,f[y+1]=b.right},blockSize:64/32,keySize:128/32,ivSize:64/32});e.Blowfish=r._createHelper(m)})(),u.Blowfish})});var Ii=re((Yn,Ja)=>{(function(u,e,t){typeof Yn=="object"?Ja.exports=Yn=e(ae(),_r(),Wi(),Xi(),Dt(),ea(),Ct(),Ai(),Ut(),aa(),Si(),ca(),da(),pa(),Tr(),fa(),At(),Fe(),va(),Aa(),Ia(),Da(),wa(),Oa(),_a(),Fa(),Ba(),qa(),Na(),Ua(),ja(),Va(),Ka(),Wa(),Xa()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./enc-base64url","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy","./blowfish"],e):u.CryptoJS=e(u.CryptoJS)})(Yn,function(u){return u})});var ao=re((ni,io)=>{(function(u,e,t){typeof ni=="object"?io.exports=ni=e(ae(),Ut(),Tr()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(u.CryptoJS)})(ni,function(u){return u.HmacSHA256})});var so=re((ii,oo)=>{(function(u,e){typeof ii=="object"?oo.exports=ii=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(ii,function(u){return u.enc.Hex})});var Ho={};Ao(Ho,{ActivityLogger:()=>Er,AdapterRegistry:()=>Hr,ApiService:()=>Mr,AuthorizationService:()=>Rr,BackupScheduler:()=>Nr,CONFLICT_POLICY_MATRIX:()=>Za,CURRENT_SYNC_PROTOCOL_VERSION:()=>dn,CartService:()=>Pr,CartStore:()=>Ir,CategoryService:()=>jt,ConfigService:()=>Lr,ConsoleLoggerAdapter:()=>$r.ConsoleLoggerAdapter,CustomerGroupService:()=>Vt,CustomerService:()=>$t,DEFAULT_GRANULAR_AUTH_POLICY:()=>xi,DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS:()=>ln,DefaultExportAdapter:()=>jr.DefaultExportAdapter,DefaultHttpAdapter:()=>Br.DefaultHttpAdapter,DefaultPlatformAdapter:()=>lo.DefaultPlatformAdapter,DomainServices:()=>Cr,EncryptionService:()=>Fr,ExpenseService:()=>mr,ExponentialBackoffHttpPolicy:()=>mt.ExponentialBackoffHttpPolicy,ExportService:()=>vr,FinancialSettingService:()=>pr,HistoryService:()=>zt,InMemoryDbAdapter:()=>ho.InMemoryDbAdapter,InMemorySocketAdapter:()=>zr.InMemorySocketAdapter,IntegrationServices:()=>Qr,InventoryLogService:()=>sr,InventoryService:()=>yr,MemoryActivitySink:()=>Bt.MemoryActivitySink,MemoryStorage:()=>yt,NoRetryHttpPolicy:()=>mt.NoRetryHttpPolicy,NoopActivitySink:()=>Bt.NoopActivitySink,NoopChecksumAdapter:()=>ei.NoopChecksumAdapter,NoopEncryptionAdapter:()=>Zn.NoopEncryptionAdapter,NoopNotificationAdapter:()=>Vr.NoopNotificationAdapter,NoopSocketService:()=>Ft,NoopSyncService:()=>Tt,NotificationService:()=>qr,OrderService:()=>Kt,POS_DOMAIN_TABLES:()=>Mo,PayableService:()=>fr,PosCore:()=>kt,PriceHistoryService:()=>cr,PriceTierService:()=>Gt,PricingService:()=>xr,ProductService:()=>Wt,PromotionService:()=>Yt,PurchaseOrderService:()=>ar,PurchaseService:()=>or,ReceivableService:()=>hr,ReportScheduleService:()=>lr,ReportingService:()=>Sr,ReturnService:()=>Zt,RoleAdapter:()=>Or,SaleService:()=>er,SessionStore:()=>Ur,SettlementService:()=>gr,ShiftService:()=>tr,SocketService:()=>Di,StockAdjustmentService:()=>dr,StockOpnameService:()=>ur,SupplierService:()=>ir,SyncService:()=>Pi,SyncStore:()=>wr,TASK_ID:()=>to,TaxService:()=>Dr,TransactionService:()=>rr,UIProductService:()=>Ti,UITransactionService:()=>Fi,UomService:()=>nr,UserService:()=>kr,applyPendingMigrations:()=>wi,bomTable:()=>Be,buildJournalDraftFromPosFinanceProjection:()=>Qi,categoryTable:()=>et,computeChecksum:()=>br,createChangeQueuePort:()=>H,createPosFinanceRuntimeOptions:()=>Ro,customerGroupTable:()=>tt,customerTable:()=>ze,eventBus:()=>Le,executeHttpRequestWithRetry:()=>mt.executeHttpRequestWithRetry,expenseTable:()=>ot,financialSettingTable:()=>Ve,getSyncProtocolContract:()=>qo,historyTable:()=>ie,initialSessionState:()=>ro,initialState:()=>Pt,inventoryLogTable:()=>Oe,isContractVersionCompatible:()=>mo.isContractVersionCompatible,isFailureEnvelope:()=>po.isFailureEnvelope,isServerProtocolCompatible:()=>yi,kitchenTicketItemTable:()=>di,kitchenTicketTable:()=>Jr,loyaltyAccountTable:()=>Rt,loyaltyLedgerTable:()=>gt,migrations:()=>Ci,orderItemTable:()=>xe,orderTable:()=>oe,payableTable:()=>ye,priceHistoryTable:()=>Ge,priceTierTable:()=>He,productTable:()=>ue,projectPosCashAdjustmentFinance:()=>gi,projectPosExpenseFinance:()=>hi,projectPosPurchaseFinance:()=>pi,projectPosReturnFinance:()=>mi,projectPosSettlementFinance:()=>fi,projectScopedPosSaleFinance:()=>li,promotionTable:()=>rt,purchaseItemTable:()=>De,purchaseOrderItemTable:()=>$e,purchaseOrderTable:()=>_e,purchaseTable:()=>Se,receivableTable:()=>fe,reportScheduleTable:()=>at,returnItemTable:()=>Re,returnTable:()=>Ae,roleTable:()=>Ce,saleItemTable:()=>ge,saleTable:()=>ce,schemas:()=>xt,settlementTable:()=>Qe,shiftTable:()=>le,stockAdjustmentTable:()=>it,stockOpnameItemTable:()=>Me,stockOpnameTable:()=>we,supplierTable:()=>Ke,taxRateTable:()=>Ee,transactionTable:()=>Z,uomTable:()=>nt,userTable:()=>je});var yy=Mt(qi());var no=Pe("ofcore"),Jn=Pe("ofcore");var Wr="0123456789abcdef",Yr=class u{constructor(e){this.bytes=e}static ofInner(e){if(e.length!==16)throw new TypeError("not 128-bit length");return new u(e)}static fromFieldsV7(e,t,r,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||t<0||r<0||n<0||e>0xffffffffffff||t>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/2**8,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new u(i)}static parse(e){var t,r,n,i;let a;switch(e.length){case 32:a=(t=/^[0-9a-f]{32}$/i.exec(e))===null||t===void 0?void 0:t[0];break;case 36:a=(r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||r===void 0?void 0:r.slice(1,6).join("");break;case 38:a=(n=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e))===null||n===void 0?void 0:n.slice(1,6).join("");break;case 45:a=(i=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||i===void 0?void 0:i.slice(1,6).join("");break;default:break}if(a){let o=new Uint8Array(16);for(let s=0;s<16;s+=4){let d=parseInt(a.substring(2*s,2*s+8),16);o[s+0]=d>>>24,o[s+1]=d>>>16,o[s+2]=d>>>8,o[s+3]=d}return new u(o)}else throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Wr.charAt(this.bytes[t]>>>4),e+=Wr.charAt(this.bytes[t]&15),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Wr.charAt(this.bytes[t]>>>4),e+=Wr.charAt(this.bytes[t]&15);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.isNil()?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.isMax()?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}isNil(){return this.bytes.every(e=>e===0)}isMax(){return this.bytes.every(e=>e===255)}clone(){return new u(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}},si=class{constructor(e){this.timestampBiased=0,this.counter=0,this.rollbackAllowance=1e4,this.random=e!=null?e:Io()}setRollbackAllowance(e){if(e<0||e>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");this.rollbackAllowance=e}generate(){return this.generateOrResetWithTs(Date.now())}generateOrAbort(){return this.generateOrAbortWithTs(Date.now())}generateOrResetWithTs(e){let t=this.generateOrAbortWithTs(e);return t===void 0&&(this.timestampBiased=0,t=this.generateOrAbortWithTs(e)),t}generateOrAbortWithTs(e){if(!Number.isInteger(e)||e<0||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit unsigned integer");if(e++,e>this.timestampBiased)this.timestampBiased=e,this.resetCounter();else if(e+this.rollbackAllowance>=this.timestampBiased)this.counter++,this.counter>4398046511103&&(this.timestampBiased++,this.resetCounter());else return;return Yr.fromFieldsV7(this.timestampBiased-1,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}generateOrResetCore(e,t){let r=this.rollbackAllowance;try{return this.setRollbackAllowance(t),this.generateOrResetWithTs(e)}catch(n){throw n}finally{this.rollbackAllowance=r}}generateOrAbortCore(e,t){let r=this.rollbackAllowance;try{return this.setRollbackAllowance(t),this.generateOrAbortWithTs(e)}catch(n){throw n}finally{this.rollbackAllowance=r}}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Yr.ofInner(e)}},Io=()=>{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues!="undefined")return new ci;if(typeof UUIDV7_DENY_WEAK_RNG!="undefined"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");return{nextUint32:()=>Math.trunc(Math.random()*65536)*65536+Math.trunc(Math.random()*65536)}},ci=class{constructor(){this.buffer=new Uint32Array(8),this.cursor=65535}nextUint32(){return this.cursor>=this.buffer.length&&(crypto.getRandomValues(this.buffer),this.cursor=0),this.buffer[this.cursor++]}},Li;var D=()=>Po().toString(),Po=()=>(Li||(Li=new si)).generateV4();var ui=class{constructor(e){this.context=e}enqueue(e){this.context.enqueueDomainChange(e)}};function H(u){return new ui(u)}var Be="boms";var Xr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addBom(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Be,i);return this.changeQueue.enqueue({type:"create",model:Be,record:a}),this.context.logActivity("AddBom",{id:r}),a}async updateBom(e,t,r){let n=await(r||this.dbAdapter).get(Be,e);if(!n)throw new Error(`Bom with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Be,e,a);return this.changeQueue.enqueue({type:"update",model:Be,record:o}),this.context.logActivity("UpdateBom",{id:e}),o}async getBoms(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Be,{...e,filters:i})}async getBom(e,t){return(t||this.dbAdapter).get(Be,e)}async deleteBom(e,t){return await(t||this.dbAdapter).delete(Be,e),this.changeQueue.enqueue({type:"delete",model:Be,record:{id:e}}),this.context.logActivity("DeleteBom",{id:e}),{id:e,queued:!0}}async duplicateBom(e,t){let r=await this.getBom(e,t);if(!r)throw new Error(`Bom with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Be,a);return this.changeQueue.enqueue({type:"create",model:Be,record:a}),this.context.logActivity("DuplicateBom",{originalId:e,newId:n}),o}async getBomsByParentItemId(e,t){let r=t||this.dbAdapter,n={and:[{parentItemId:e},{deleted:!1}]};return r.query(Be,{filters:n})}async getBomsByComponentItemId(e,t){let r=t||this.dbAdapter,n={and:[{componentItemId:e},{deleted:!1}]};return r.query(Be,{filters:n})}async getBomsByProductId(e,t){return this.dbAdapter.query(Be,{filters:{or:[{and:[{field:"parentItemId",value:e},{field:"deleted",value:!1}]},{and:[{field:"componentItemId",value:e},{field:"deleted",value:!1}]}]}})}async expandBom(e){let t=new Map,r=async(n,i)=>{let a=await this.dbAdapter.query(Be,{filters:{parentItemId:n,deleted:!1}});for(let o of a){let s=o.quantity*i;if((await this.dbAdapter.query(Be,{filters:{parentItemId:o.componentItemId,deleted:!1}})).length>0)await r(o.componentItemId,s);else{let c=t.get(o.componentItemId);c?c.quantity+=s:t.set(o.componentItemId,{componentItemId:o.componentItemId,quantity:s,uomId:o.uomId})}}};return await r(e,1),Array.from(t.values())}};var et="categories";var jt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addCategory(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(et,i);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("AddCategory",{id:r}),a}async updateCategory(e,t,r){let n=await(r||this.dbAdapter).get(et,e);if(!n)throw new Error(`Category with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(et,e,a);return this.changeQueue.enqueue({type:"update",model:et,record:o}),this.context.logActivity("UpdateCategory",{id:e}),o}async getCategories(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(et,{...e,filters:i})}async getCategory(e,t){return(t||this.dbAdapter).get(et,e)}async deleteCategory(e,t){return await(t||this.dbAdapter).delete(et,e),this.changeQueue.enqueue({type:"delete",model:et,record:{id:e}}),this.context.logActivity("DeleteCategory",{id:e}),{id:e,queued:!0}}async duplicateCategory(e,t){let r=await this.getCategory(e,t);if(!r)throw new Error(`Category with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(et,a);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("DuplicateCategory",{originalId:e,newId:n}),o}async fetchNestedCategories(){let e=await this.getCategories(),t={};e.forEach(n=>{t[n.id]={...n,children:[]}});let r=[];return e.forEach(n=>{var a;let i=(a=n.parentId)!=null?a:null;i&&t[i]?t[i].children.push(t[n.id]):r.push(t[n.id])}),r}};var ze="customers";var Rt="loyalty_accounts";var gt="loyalty_ledgers";var $t=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}async getOrCreateLoyaltyAccount(e,t){let r=await e.query(Rt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]},limit:1});if(r.length>0)return r[0];let n=new Date().toISOString();return e.create(Rt,{id:D(),customerId:t,pointsBalance:0,totalEarned:0,totalRedeemed:0,totalExpired:0,version:Date.now(),lastModified:n,deleted:!1})}async addCustomer(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ze,i);return this.changeQueue.enqueue({type:"create",model:ze,record:a}),this.context.logActivity("AddCustomer",{id:r}),a}async updateCustomer(e,t,r){let n=await(r||this.dbAdapter).get(ze,e);if(!n)throw new Error(`Customer with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ze,e,a);return this.changeQueue.enqueue({type:"update",model:ze,record:o}),this.context.logActivity("UpdateCustomer",{id:e}),o}async getCustomers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ze,{...e,filters:i})}async getCustomer(e,t){return(t||this.dbAdapter).get(ze,e)}async deleteCustomer(e,t){return await(t||this.dbAdapter).delete(ze,e),this.changeQueue.enqueue({type:"delete",model:ze,record:{id:e}}),this.context.logActivity("DeleteCustomer",{id:e}),{id:e,queued:!0}}async duplicateCustomer(e,t){let r=await this.getCustomer(e,t);if(!r)throw new Error(`Customer with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ze,a);return this.changeQueue.enqueue({type:"create",model:ze,record:a}),this.context.logActivity("DuplicateCustomer",{originalId:e,newId:n}),o}async searchCustomers(e,t,r){let n=e.trim();if(!n)return[];let i=r||this.dbAdapter,a={and:[{or:[{field:"name",operator:"like",value:`%${n}%`},{field:"phone",operator:"like",value:`%${n}%`},{field:"email",operator:"like",value:`%${n}%`}]},{deleted:!1}]};return i.query(ze,{...t,filters:a})}async earnLoyaltyPoints(e){let t=String(e.customerId||"").trim(),r=String(e.referenceType||"").trim(),n=String(e.referenceId||"").trim();if(!t)throw new Error("Loyalty: customerId is required");if(!r||!n)throw new Error("Loyalty: referenceType/referenceId are required");if(!Number.isFinite(e.baseAmount)||e.baseAmount<=0)throw new Error("Loyalty: baseAmount must be > 0");if(!Number.isFinite(e.earnRate)||e.earnRate<=0)throw new Error("Loyalty: earnRate must be > 0");return this.runInTransaction(async i=>{let a=e.date||new Date().toISOString(),o=await i.query(gt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"entryType",operator:"=",value:"earn"},{field:"referenceType",operator:"=",value:r},{field:"referenceId",operator:"=",value:n},{field:"deleted",operator:"=",value:!1}]},limit:1});if(o.length>0){let p=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:Number(o[0].points||0),balance:Number(p.pointsBalance||0)}}let s=Math.floor(e.baseAmount*e.earnRate);if(s<=0){let p=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:0,balance:Number(p.pointsBalance||0)}}await i.create(gt,{id:D(),customerId:t,entryType:"earn",points:s,availablePoints:s,expiresAt:e.expiresAt||null,consumedAt:null,referenceType:r,referenceId:n,note:e.note||null,date:a,version:Date.now(),lastModified:a,deleted:!1});let d=await this.getOrCreateLoyaltyAccount(i,t),c=await i.update(Rt,d.id,{pointsBalance:Number(d.pointsBalance||0)+s,totalEarned:Number(d.totalEarned||0)+s,version:Date.now(),lastModified:a});return this.context.logActivity("LoyaltyEarnPoints",{customerId:t,referenceType:r,referenceId:n,earnedPoints:s}),{earnedPoints:s,balance:Number(c.pointsBalance||0)}})}async redeemLoyaltyPoints(e){let t=String(e.customerId||"").trim(),r=String(e.referenceType||"").trim(),n=String(e.referenceId||"").trim();if(!t)throw new Error("Loyalty: customerId is required");if(!r||!n)throw new Error("Loyalty: referenceType/referenceId are required");if(!Number.isInteger(e.points)||e.points<=0)throw new Error("Loyalty: redeem points must be positive integer");return this.runInTransaction(async i=>{let a=e.date||new Date().toISOString(),o=await this.getOrCreateLoyaltyAccount(i,t),s=Number(o.pointsBalance||0);if(s<e.points)throw new Error(`Loyalty: insufficient points, required=${e.points}, available=${s}`);let d=await i.query(gt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"entryType",operator:"=",value:"earn"},{field:"deleted",operator:"=",value:!1},{field:"availablePoints",operator:">",value:0}]},sort:[{field:"expiresAt",direction:"asc"},{field:"date",direction:"asc"}]}),c=e.points;for(let l of d){if(c<=0)break;let m=Number(l.availablePoints||0);if(m<=0)continue;let f=Math.min(m,c),y=m-f;await i.update(gt,l.id,{availablePoints:y,consumedAt:y===0?a:l.consumedAt,version:Date.now(),lastModified:a}),c-=f}if(c>0)throw new Error(`Loyalty: redeem allocation failed, remaining=${c}`);await i.create(gt,{id:D(),customerId:t,entryType:"redeem",points:e.points,availablePoints:0,expiresAt:null,consumedAt:a,referenceType:r,referenceId:n,note:e.note||null,date:a,version:Date.now(),lastModified:a,deleted:!1});let p=await i.update(Rt,o.id,{pointsBalance:s-e.points,totalRedeemed:Number(o.totalRedeemed||0)+e.points,version:Date.now(),lastModified:a});return this.context.logActivity("LoyaltyRedeemPoints",{customerId:t,referenceType:r,referenceId:n,redeemedPoints:e.points}),{redeemedPoints:e.points,balance:Number(p.pointsBalance||0)}})}async expireLoyaltyPoints(e){return this.runInTransaction(async t=>{let r=(e==null?void 0:e.asOfDate)||new Date().toISOString(),n=[{field:"entryType",operator:"=",value:"earn"},{field:"deleted",operator:"=",value:!1},{field:"availablePoints",operator:">",value:0},{field:"expiresAt",operator:"<=",value:r}];e!=null&&e.customerId&&n.push({field:"customerId",operator:"=",value:e.customerId});let i=await t.query(gt,{filters:{and:n}});if(!i.length)return{expiredPoints:0,affectedCustomers:0};let a=0,o=new Map;for(let s of i){let d=Number(s.availablePoints||0);d<=0||(a+=d,o.set(s.customerId,(o.get(s.customerId)||0)+d),await t.update(gt,s.id,{availablePoints:0,consumedAt:r,version:Date.now(),lastModified:r}),await t.create(gt,{id:D(),customerId:s.customerId,entryType:"expire",points:d,availablePoints:0,expiresAt:s.expiresAt,consumedAt:r,referenceType:"loyalty_expiry",referenceId:s.id,note:"auto expiry",date:r,version:Date.now(),lastModified:r,deleted:!1}))}for(let[s,d]of o.entries()){let c=await this.getOrCreateLoyaltyAccount(t,s);await t.update(Rt,c.id,{pointsBalance:Math.max(0,Number(c.pointsBalance||0)-d),totalExpired:Number(c.totalExpired||0)+d,version:Date.now(),lastModified:r})}return this.context.logActivity("LoyaltyExpirePoints",{asOfDate:r,expiredPoints:a,affectedCustomers:o.size}),{expiredPoints:a,affectedCustomers:o.size}})}async getLoyaltySummary(e){let t=String(e||"").trim();if(!t)throw new Error("Loyalty: customerId is required");let r=await this.getOrCreateLoyaltyAccount(this.dbAdapter,t);return{customerId:t,pointsBalance:Number(r.pointsBalance||0),totalEarned:Number(r.totalEarned||0),totalRedeemed:Number(r.totalRedeemed||0),totalExpired:Number(r.totalExpired||0)}}};var tt="customer_groups";var Vt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addCustomerGroup(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(tt,i);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("AddCustomerGroup",{id:r}),a}async updateCustomerGroup(e,t,r){let n=await(r||this.dbAdapter).get(tt,e);if(!n)throw new Error(`CustomerGroup with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(tt,e,a);return this.changeQueue.enqueue({type:"update",model:tt,record:o}),this.context.logActivity("UpdateCustomerGroup",{id:e}),o}async getCustomerGroups(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(tt,{...e,filters:i})}async getCustomerGroup(e,t){return(t||this.dbAdapter).get(tt,e)}async deleteCustomerGroup(e,t){return await(t||this.dbAdapter).delete(tt,e),this.changeQueue.enqueue({type:"delete",model:tt,record:{id:e}}),this.context.logActivity("DeleteCustomerGroup",{id:e}),{id:e,queued:!0}}async duplicateCustomerGroup(e,t){let r=await this.getCustomerGroup(e,t);if(!r)throw new Error(`CustomerGroup with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(tt,a);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("DuplicateCustomerGroup",{originalId:e,newId:n}),o}};var ie="histories";var zt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addHistory(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(ie,i);return this.changeQueue.enqueue({type:"create",model:ie,record:a}),this.context.logActivity("AddHistory",{id:r}),a}async updateHistory(e,t,r){if(!await(r||this.dbAdapter).get(ie,e))throw new Error(`History with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e},o=await(r||this.dbAdapter).update(ie,e,a);return this.changeQueue.enqueue({type:"update",model:ie,record:o}),this.context.logActivity("UpdateHistory",{id:e}),o}async getHistories(e,t){return(t||this.dbAdapter).query(ie,e)}async getHistory(e,t){return(t||this.dbAdapter).get(ie,e)}async deleteHistory(e,t){return await(t||this.dbAdapter).delete(ie,e),this.changeQueue.enqueue({type:"delete",model:ie,record:{id:e}}),this.context.logActivity("DeleteHistory",{id:e}),{id:e,queued:!0}}async duplicateHistory(e,t){let r=await this.getHistory(e,t);if(!r)throw new Error(`History with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ie,a);return this.changeQueue.enqueue({type:"create",model:ie,record:a}),this.context.logActivity("DuplicateHistory",{originalId:e,newId:n}),o}async enforceRetentionPolicy(e=new Date){var c;let t=this.context.config.auditLogRetentionDays,r=this.context.config.auditLogArchiveBeforePurge,n=this.context.config.auditLogPurgeBatchSize,i=e.getTime()-t*24*60*60*1e3,a=await this.dbAdapter.query(ie,{sort:[{field:"timestamp",direction:"asc"}]}),o=a.filter(p=>{let l=Date.parse(String(p.timestamp||""));return Number.isFinite(l)&&l<=i}).slice(0,n);if(o.length===0)return{scanned:a.length,archived:0,purged:0,archiveKey:null};let s=0,d=null;if(r){let p=(c=this.context.registry)==null?void 0:c.storageAdapter;d=`audit-archive:${e.toISOString().slice(0,10)}`;let m=await(p==null?void 0:p.getItem(d)),f=m?JSON.parse(m):[],y=o.map(b=>({id:b.id,tableName:b.tableName,recordId:b.recordId,action:b.action,userId:b.userId,timestamp:b.timestamp,changes:b.changes}));await(p==null?void 0:p.setItem(d,JSON.stringify([...Array.isArray(f)?f:[],...y]))),s=y.length}for(let p of o)await this.dbAdapter.delete(ie,p.id);return this.context.logInfo("History retention enforcement completed",{scanned:a.length,archived:s,purged:o.length,retentionDays:t,archiveBeforePurge:r,archiveKey:d}),{scanned:a.length,archived:s,purged:o.length,archiveKey:d}}};var oe="orders";var xe="order_items";var Ni=Pe("ofcore"),yt=class extends Ni.MemoryStorageAdapter{};var It=class{constructor(e){this.context=e;this.queue=Promise.resolve();var t;this.storage=((t=this.context.registry)==null?void 0:t.storageAdapter)||new yt(this.context)}getBranchSegment(){return String(this.context.config.branchId||"LOCAL").trim().toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"LOCAL"}getDateSegment(e){let t=new Date(e),r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${r}${n}${i}`}getCounterKey(e,t){let r=this.getBranchSegment(),n=this.getDateSegment(t);return`docseq:${r}:${e}:${n}`}async withLock(e){let t=this.queue,r=()=>{};this.queue=new Promise(n=>{r=n}),await t;try{return await e()}finally{r()}}async next(e,t){return this.withLock(async()=>{let r=this.getCounterKey(e,t),n=await this.storage.getItem(r),i=Number(n||"0"),a=Number.isFinite(i)&&i>=0?i+1:1;await this.storage.setItem(r,String(a));let o=e.toUpperCase().slice(0,3),s=this.getBranchSegment(),d=this.getDateSegment(t);return`${o}-${s}-${d}-${String(a).padStart(6,"0")}`})}withNote(e,t){let r=String(e||"").trim(),n=`[DOC_NO=${t}]`;return r?r.includes("[DOC_NO=")?r:`${r} | ${n}`:n}extractDocNo(e){let r=String(e||"").match(/\[DOC_NO=([^\]]+)\]/);return r&&String(r[1]||"").trim()||null}};var di="kitchen_ticket_items";var Jr="kitchen_tickets";var Kt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e),this.docNumberPolicy=new It(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}validateOmnichannelInput(e){var r;let t=(r=e.channel)!=null?r:null;if(t){if(!["dine_in","takeaway","delivery","preorder"].includes(t))throw new Error(`Order channel ${t} is invalid`);if(t==="dine_in"&&!String(e.tableNumber||"").trim())throw new Error("Dine-in order requires tableNumber");if(t==="preorder"&&!String(e.scheduledAt||"").trim())throw new Error("Preorder requires scheduledAt");if(t==="delivery"&&!String(e.deliveryAddress||"").trim())throw new Error("Delivery order requires deliveryAddress")}}isValidTransition(e,t,r){let n={draft:["confirmed","canceled"],confirmed:["preparing","canceled"],preparing:["ready","canceled"],ready:["completed","canceled"],out_for_delivery:["completed","canceled"],completed:[],canceled:[],merged:[]},i=String(t||"draft"),a=String(r||""),o=n[i]||[];return e==="delivery"&&i==="ready"?["out_for_delivery","canceled"].includes(a):e!=="delivery"&&i==="ready"?["completed","canceled"].includes(a):o.includes(a)}async recalculateOrderTotals(e,t){let r=await e.get(oe,t);if(!r||r.deleted)throw new Error(`Order with ID ${t} not found.`);let i=(await e.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((p,l)=>p+Number(l.unitPrice||0)*Number(l.quantity||0),0),a=Number(r.serviceChargeAmount||0),o=Number(r.gratuityAmount||0),s=Number(r.ppn||0),d=Number(r.pph||0),c=i+a+o+s+d;return e.update(oe,t,{total:i,finalTotal:c,version:Date.now(),lastModified:new Date().toISOString()})}async addOrder(e,t){var s,d,c,p,l,m,f,y;this.validateOmnichannelInput(e);let r=D(),n=new Date().toISOString(),i=((s=this.context.config)==null?void 0:s.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("order",e.date||n):null,a={id:r,userId:e.userId,customerId:e.customerId,parentOrderId:(d=e.parentOrderId)!=null?d:null,discountCode:e.discountCode,channel:(c=e.channel)!=null?c:null,status:e.status,saleId:e.saleId,scheduledAt:(p=e.scheduledAt)!=null?p:null,deliveryAddress:(l=e.deliveryAddress)!=null?l:null,tableNumber:(m=e.tableNumber)!=null?m:null,serviceChargeAmount:(f=e.serviceChargeAmount)!=null?f:null,gratuityAmount:(y=e.gratuityAmount)!=null?y:null,date:e.date,total:e.total,ppn:e.ppn,pph:e.pph,finalTotal:e.finalTotal,note:i?this.docNumberPolicy.withNote(e.note,i):e.note,version:1,lastModified:n,deleted:!1},o=await(t||this.dbAdapter).create(oe,a);return this.changeQueue.enqueue({type:"create",model:oe,record:o}),this.context.logActivity("AddOrder",{id:r,channel:a.channel,status:a.status}),o}async updateOrder(e,t,r){let n=await(r||this.dbAdapter).get(oe,e);if(!n)throw new Error(`Order with ID ${e} not found.`);this.validateOmnichannelInput({...n,...t});let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(oe,e,a);return this.changeQueue.enqueue({type:"update",model:oe,record:o}),this.context.logActivity("UpdateOrder",{id:e}),o}async getOrders(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(oe,{...e,filters:i})}async getOrder(e,t){return(t||this.dbAdapter).get(oe,e)}async deleteOrder(e,t){return await(t||this.dbAdapter).delete(oe,e),this.changeQueue.enqueue({type:"delete",model:oe,record:{id:e}}),this.context.logActivity("DeleteOrder",{id:e}),{id:e,queued:!0}}async duplicateOrder(e,t){let r=await this.getOrder(e,t);if(!r)throw new Error(`Order with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,status:"draft",saleId:null,version:1,lastModified:i,deleted:!1},o=await(t||this.dbAdapter).create(oe,a);return this.changeQueue.enqueue({type:"create",model:oe,record:a}),this.context.logActivity("DuplicateOrder",{originalId:e,newId:n}),o}async finalizeOrder(e){return await this.runInTransaction(async t=>{await this.recalculateOrderTotals(t,e),await t.update(oe,e,{status:"completed",version:Date.now(),lastModified:new Date().toISOString()})}),this.context.eventBus.emit("order:finalized",e),{id:e,queued:!0}}async transitionOrderLifecycle(e){let t=String(e.orderId||"").trim(),r=String(e.actorId||"").trim(),n=String(e.toStatus||"").trim();if(!t)throw new Error("orderId is required");if(!r)throw new Error("actorId is required");if(!n)throw new Error("toStatus is required");return this.runInTransaction(async i=>{let a=await i.get(oe,t);if(!a||a.deleted)throw new Error(`Order with ID ${t} not found.`);let o=a.channel||null;if(!this.isValidTransition(o,a.status,n))throw new Error(`Invalid order lifecycle transition: ${a.status} -> ${n}`);let s=new Date().toISOString(),d=await i.update(oe,t,{status:n,version:Date.now(),lastModified:s});return await i.create(ie,{id:D(),tableName:oe,recordId:t,action:"lifecycle_transition",changes:{fromStatus:a.status,toStatus:n,actorId:r,reason:e.reason||null,channel:o},userId:r,timestamp:s}),d})}async createKitchenTicket(e){if(!String(e.orderId||"").trim())throw new Error("orderId is required");if(!String(e.station||"").trim())throw new Error("station is required");if(!String(e.actorId||"").trim())throw new Error("actorId is required");if(!Array.isArray(e.items)||e.items.length===0)throw new Error("items is required");return this.runInTransaction(async t=>{let r=await t.get(oe,e.orderId);if(!r||r.deleted)throw new Error(`Order with ID ${e.orderId} not found.`);let n=new Date().toISOString(),i=await t.create(Jr,{id:D(),orderId:e.orderId,station:e.station,status:"queued",note:e.note||null,createdBy:e.actorId,createdAt:n,version:Date.now(),lastModified:n,deleted:!1}),a=[];for(let o of e.items){let s=String(o.orderItemId||"").trim();if(!s)throw new Error("orderItemId is required");let d=await t.get(xe,s);if(!d||d.deleted||String(d.orderId)!==e.orderId)throw new Error(`Order item ${s} does not belong to order ${e.orderId}`);let c=await t.create(di,{id:D(),ticketId:i.id,orderItemId:s,course:o.course||null,status:"queued",note:o.note||null,version:Date.now(),lastModified:n,deleted:!1});a.push(c)}return await t.create(ie,{id:D(),tableName:Jr,recordId:i.id,action:"create",changes:{orderId:e.orderId,station:e.station,itemCount:a.length},userId:e.actorId,timestamp:n}),{ticket:i,items:a}})}async splitOrderBill(e){let t=String(e.orderId||"").trim(),r=String(e.actorId||"").trim();if(!t)throw new Error("orderId is required");if(!r)throw new Error("actorId is required");if(!Array.isArray(e.splits)||e.splits.length===0)throw new Error("splits is required");return this.runInTransaction(async n=>{let i=await n.get(oe,t);if(!i||i.deleted)throw new Error(`Order with ID ${t} not found.`);let a=await n.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}}),o=new Set(a.map(p=>String(p.id))),s=new Set,d=new Date().toISOString(),c=[];for(let p of e.splits){let l=(p.orderItemIds||[]).map(f=>String(f));if(l.length===0)continue;for(let f of l){if(!o.has(f))throw new Error(`Order item ${f} does not belong to parent order`);if(s.has(f))throw new Error(`Order item ${f} referenced by multiple splits`);s.add(f)}let m=await n.create(oe,{id:D(),userId:i.userId,customerId:i.customerId,parentOrderId:t,discountCode:i.discountCode,channel:i.channel,status:"draft",saleId:null,scheduledAt:i.scheduledAt,deliveryAddress:i.deliveryAddress,tableNumber:i.tableNumber,serviceChargeAmount:0,gratuityAmount:0,date:i.date,total:0,ppn:0,pph:0,finalTotal:0,note:p.label?`SPLIT:${p.label}`:"SPLIT",version:Date.now(),lastModified:d,deleted:!1});c.push(m.id);for(let f of l)await n.get(xe,f)&&await n.update(xe,f,{orderId:m.id,version:Date.now(),lastModified:d});await this.recalculateOrderTotals(n,m.id)}return await this.recalculateOrderTotals(n,t),await n.create(ie,{id:D(),tableName:oe,recordId:t,action:"bill_split",changes:{actorId:r,childOrderIds:c,movedItems:Array.from(s)},userId:r,timestamp:d}),{parentOrderId:t,childOrderIds:c}})}async mergeOrderBills(e){let t=String(e.targetOrderId||"").trim(),r=String(e.actorId||"").trim();if(!t)throw new Error("targetOrderId is required");if(!r)throw new Error("actorId is required");let n=Array.from(new Set((e.sourceOrderIds||[]).map(i=>String(i).trim()).filter(Boolean)));if(!n.length)throw new Error("sourceOrderIds is required");if(n.includes(t))throw new Error("targetOrderId cannot be included in sourceOrderIds");return this.runInTransaction(async i=>{let a=await i.get(oe,t);if(!a||a.deleted)throw new Error(`Order with ID ${t} not found.`);let o=new Date().toISOString();for(let s of n){let d=await i.get(oe,s);if(!d||d.deleted)throw new Error(`Order with ID ${s} not found.`);let c=await i.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:s},{field:"deleted",operator:"=",value:!1}]}});for(let p of c)await i.update(xe,p.id,{orderId:t,version:Date.now(),lastModified:o});await i.update(oe,s,{status:"merged",version:Date.now(),lastModified:o,note:[d.note,`MERGED_INTO:${t}`].filter(Boolean).join(" | ")})}return await this.recalculateOrderTotals(i,t),await i.create(ie,{id:D(),tableName:oe,recordId:t,action:"bill_merge",changes:{actorId:r,mergedOrderIds:n},userId:r,timestamp:o}),{targetOrderId:t,mergedOrderIds:n}})}async applyServiceChargeAndGratuity(e){let t=String(e.orderId||"").trim();if(!t)throw new Error("orderId is required");if(!String(e.actorId||"").trim())throw new Error("actorId is required");if(!Number.isFinite(e.serviceChargeRate)||e.serviceChargeRate<0)throw new Error("serviceChargeRate must be >= 0");if(!Number.isFinite(e.gratuityRate)||e.gratuityRate<0)throw new Error("gratuityRate must be >= 0");return this.runInTransaction(async r=>{let n=await r.get(oe,t);if(!n||n.deleted)throw new Error(`Order with ID ${t} not found.`);let a=(await r.query(xe,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((p,l)=>p+Number(l.unitPrice||0)*Number(l.quantity||0),0),o=Math.round(a*e.serviceChargeRate*100)/100,s=Math.round(a*e.gratuityRate*100)/100,d=new Date().toISOString(),c=await r.update(oe,t,{serviceChargeAmount:o,gratuityAmount:s,total:a,finalTotal:a+o+s+Number(n.ppn||0)+Number(n.pph||0),version:Date.now(),lastModified:d});return await r.create(ie,{id:D(),tableName:oe,recordId:t,action:"service_charge_gratuity_applied",changes:{actorId:e.actorId,serviceChargeRate:e.serviceChargeRate,gratuityRate:e.gratuityRate,serviceChargeAmount:o,gratuityAmount:s},userId:e.actorId,timestamp:d}),c})}};var Zr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addOrderItem(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(xe,i);return this.changeQueue.enqueue({type:"create",model:xe,record:a}),this.context.logActivity("AddOrderItem",{id:r}),a}async updateOrderItem(e,t,r){let n=await(r||this.dbAdapter).get(xe,e);if(!n)throw new Error(`OrderItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(xe,e,a);return this.changeQueue.enqueue({type:"update",model:xe,record:o}),this.context.logActivity("UpdateOrderItem",{id:e}),o}async getOrderItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(xe,{...e,filters:i})}async getOrderItem(e,t){return(t||this.dbAdapter).get(xe,e)}async deleteOrderItem(e,t){return await(t||this.dbAdapter).delete(xe,e),this.changeQueue.enqueue({type:"delete",model:xe,record:{id:e}}),this.context.logActivity("DeleteOrderItem",{id:e}),{id:e,queued:!0}}async duplicateOrderItem(e,t){let r=await this.getOrderItem(e,t);if(!r)throw new Error(`OrderItem with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(xe,a);return this.changeQueue.enqueue({type:"create",model:xe,record:a}),this.context.logActivity("DuplicateOrderItem",{originalId:e,newId:n}),o}};var He="price_tiers";var Gt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPriceTier(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(He,i);return this.changeQueue.enqueue({type:"create",model:He,record:a}),this.context.logActivity("AddPriceTier",{id:r}),a}async updatePriceTier(e,t,r){let n=await(r||this.dbAdapter).get(He,e);if(!n)throw new Error(`PriceTier with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(He,e,a);return this.changeQueue.enqueue({type:"update",model:He,record:o}),this.context.logActivity("UpdatePriceTier",{id:e}),o}async getPriceTiers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(He,{...e,filters:i})}async getPriceTier(e,t){return(t||this.dbAdapter).get(He,e)}async deletePriceTier(e,t){return await(t||this.dbAdapter).delete(He,e),this.changeQueue.enqueue({type:"delete",model:He,record:{id:e}}),this.context.logActivity("DeletePriceTier",{id:e}),{id:e,queued:!0}}async duplicatePriceTier(e,t){let r=await this.getPriceTier(e,t);if(!r)throw new Error(`PriceTier with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(He,a);return this.changeQueue.enqueue({type:"create",model:He,record:a}),this.context.logActivity("DuplicatePriceTier",{originalId:e,newId:n}),o}};var ue="products";var Wt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addProduct(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ue,i);return this.changeQueue.enqueue({type:"create",model:ue,record:a}),this.context.logActivity("AddProduct",{id:r}),a}async updateProduct(e,t,r){let n=await(r||this.dbAdapter).get(ue,e);if(!n)throw new Error(`Product with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ue,e,a);return this.changeQueue.enqueue({type:"update",model:ue,record:o}),this.context.logActivity("UpdateProduct",{id:e}),o}async getProducts(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ue,{...e,filters:i})}async getProduct(e,t){return(t||this.dbAdapter).get(ue,e)}async deleteProduct(e,t){return await(t||this.dbAdapter).delete(ue,e),this.changeQueue.enqueue({type:"delete",model:ue,record:{id:e}}),this.context.logActivity("DeleteProduct",{id:e}),{id:e,queued:!0}}async duplicateProduct(e,t){let r=await this.getProduct(e,t);if(!r)throw new Error(`Product with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ue,a);return this.changeQueue.enqueue({type:"create",model:ue,record:a}),this.context.logActivity("DuplicateProduct",{originalId:e,newId:n}),o}async getProductsByBarcode(e,t){let r=t||this.dbAdapter,n={and:[{barcode:e},{deleted:!1}]};return r.query(ue,{filters:n})}async getProductsByQrCode(e,t){let r=t||this.dbAdapter,n={and:[{qrCode:e},{deleted:!1}]};return r.query(ue,{filters:n})}async searchProducts(e,t,r){let n=e.trim();if(!n)return[];let i=r||this.dbAdapter,a={and:[{or:[{field:"name",operator:"like",value:`%${n}%`},{field:"description",operator:"like",value:`%${n}%`},{field:"barcode",operator:"like",value:`%${n}%`},{field:"qrCode",operator:"like",value:`%${n}%`}]},{deleted:!1}]};return i.query(ue,{...t,filters:a})}};var rt="promotions";var Yt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPromotion(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(rt,i);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("AddPromotion",{id:r}),a}async updatePromotion(e,t,r){let n=await(r||this.dbAdapter).get(rt,e);if(!n)throw new Error(`Promotion with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(rt,e,a);return this.changeQueue.enqueue({type:"update",model:rt,record:o}),this.context.logActivity("UpdatePromotion",{id:e}),o}async getPromotions(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(rt,{...e,filters:i})}async getPromotion(e,t){return(t||this.dbAdapter).get(rt,e)}async deletePromotion(e,t){return await(t||this.dbAdapter).delete(rt,e),this.changeQueue.enqueue({type:"delete",model:rt,record:{id:e}}),this.context.logActivity("DeletePromotion",{id:e}),{id:e,queued:!0}}async duplicatePromotion(e,t){let r=await this.getPromotion(e,t);if(!r)throw new Error(`Promotion with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(rt,a);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("DuplicatePromotion",{originalId:e,newId:n}),o}};var Ae="returns";var ge="sale_items";var De="purchase_items";var Re="return_items";var Z="transactions";var en=Pe("offinance-shared-core");function li(u){var t,r;let e=u.sale.date||new Date().toISOString();return{context:{journalId:(t=u.journalId)!=null?t:`journal-sale-${u.sale.id}`,tenantId:u.tenantId,branchId:u.branchId,occurredAt:e,reference:`${(r=u.referencePrefix)!=null?r:"sale"}:${u.sale.id}`},input:{grossAmount:u.sale.total,discountAmount:u.sale.discount,taxAmount:u.sale.ppn,scopedAccountMapping:u.scopedAccountMapping}}}function pi(u){var e,t;return{kind:"purchase",context:{journalId:(e=u.journalId)!=null?e:`journal-purchase-${u.purchase.id}`,tenantId:u.tenantId,branchId:u.branchId,occurredAt:u.purchase.date||new Date().toISOString(),reference:`${(t=u.referencePrefix)!=null?t:"purchase"}:${u.purchase.id}`},input:{totalAmount:u.purchase.total,paymentMethod:u.paymentMethod,scopedAccountMapping:u.scopedAccountMapping}}}function mi(u){var t,r;return{kind:u.returnEntry.type==="purchase_return"?"purchase_return":"sale_return",context:{journalId:(t=u.journalId)!=null?t:`journal-return-${u.returnEntry.id}`,tenantId:u.tenantId,branchId:u.branchId,occurredAt:u.returnEntry.date||new Date().toISOString(),reference:`${(r=u.referencePrefix)!=null?r:"return"}:${u.returnEntry.id}`},input:{actualRefund:u.returnEntry.actualRefund,scopedAccountMapping:u.scopedAccountMapping}}}function hi(u){var e,t;return{kind:"expense",context:{journalId:(e=u.journalId)!=null?e:`journal-expense-${u.expense.id}`,tenantId:u.tenantId,branchId:u.branchId,occurredAt:u.expense.date||new Date().toISOString(),reference:`${(t=u.referencePrefix)!=null?t:"expense"}:${u.expense.id}`},input:{amount:u.expense.amount,category:u.expense.category,description:u.expense.description,scopedAccountMapping:u.scopedAccountMapping}}}function fi(u){var t,r,n,i;let e=u.settlement.receivableId?"receivable_payment":"payable_payment";return{kind:e,context:{journalId:(t=u.journalId)!=null?t:`journal-settlement-${u.settlement.id}`,tenantId:u.tenantId,branchId:u.branchId,occurredAt:u.settlement.date||new Date().toISOString(),reference:`${(r=u.referencePrefix)!=null?r:e}:${u.settlement.id}`},input:{amount:u.settlement.amount,method:u.settlement.method,receivableId:(n=u.settlement.receivableId)!=null?n:null,payableId:(i=u.settlement.payableId)!=null?i:null,scopedAccountMapping:u.scopedAccountMapping}}}function gi(u){var e,t;return{kind:"cash_adjustment",context:{journalId:(e=u.journalId)!=null?e:`journal-cash-adjustment-${u.adjustment.id}`,tenantId:u.tenantId,branchId:u.branchId,occurredAt:u.adjustment.date||new Date().toISOString(),reference:`${(t=u.referencePrefix)!=null?t:"cash_adjustment"}:${u.adjustment.id}`},input:{amount:u.adjustment.amount,direction:u.adjustment.direction,reason:u.adjustment.reason,scopedAccountMapping:u.scopedAccountMapping}}}function Xt(u,e){var i,a;let t=e.tenantId?(i=u.byTenant)==null?void 0:i[e.tenantId]:void 0,r=e.tenantId&&e.branchId?`${e.tenantId}:${e.branchId}`:"",n=r?(a=u.byBranch)==null?void 0:a[r]:void 0;return{...u.default,...t!=null?t:{},...n!=null?n:{}}}function Do(u){return"grossAmount"in u.input}function Co(u){return u.kind==="purchase"}function wo(u){return u.kind==="sale_return"||u.kind==="purchase_return"}function Eo(u){return u.kind==="receivable_payment"||u.kind==="payable_payment"}function Oo(u){return u.kind==="cash_adjustment"}function Jt(u){return{id:u.journalId,tenantId:u.tenantId,branchId:u.branchId,occurredAt:u.occurredAt,reference:u.reference,ledgerProfileId:u.ledgerProfileId,financeDomainId:u.financeDomainId,lines:u.lines}}function Qi(u,e){var n,i,a,o,s;let t=(n=e.financeDomainId)!=null?n:"ofpos";if(Do(u))return(0,en.buildJournalFromScopedPosSale)({...u.context,ledgerProfileId:e.ledgerProfileId,financeDomainId:t},u.input);if(Co(u)){let d=Xt(u.input.scopedAccountMapping,u.context),c=u.input.paymentMethod==="tempo"?d.payableAccountId:d.paymentAccountId;if(!c)throw new Error("POS_PURCHASE_SETTLEMENT_ACCOUNT_REQUIRED");return Jt({journalId:u.context.journalId,tenantId:u.context.tenantId,branchId:u.context.branchId,occurredAt:u.context.occurredAt,reference:u.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:[{accountId:d.inventoryAccountId,debit:u.input.totalAmount,credit:0,memo:"POS purchase inventory"},{accountId:c,debit:0,credit:u.input.totalAmount,memo:"POS purchase settlement"}]})}if(wo(u)){let d=Xt(u.input.scopedAccountMapping,u.context);return Jt({journalId:u.context.journalId,tenantId:u.context.tenantId,branchId:u.context.branchId,occurredAt:u.context.occurredAt,reference:u.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:u.kind==="sale_return"?[{accountId:d.salesReturnAccountId,debit:u.input.actualRefund,credit:0,memo:"POS sale return refund"},{accountId:d.settlementAccountId,debit:0,credit:u.input.actualRefund,memo:"POS sale return cash out"}]:[{accountId:d.settlementAccountId,debit:u.input.actualRefund,credit:0,memo:"POS purchase return refund in"},{accountId:d.purchaseReturnAccountId,debit:0,credit:u.input.actualRefund,memo:"POS purchase return recovery"}]})}if(Eo(u)){let d=Xt(u.input.scopedAccountMapping,u.context);return Jt({journalId:u.context.journalId,tenantId:u.context.tenantId,branchId:u.context.branchId,occurredAt:u.context.occurredAt,reference:u.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:u.kind==="receivable_payment"?[{accountId:d.cashAccountId,debit:u.input.amount,credit:0,memo:"POS receivable payment cash in"},{accountId:d.receivableAccountId,debit:0,credit:u.input.amount,memo:"POS receivable settlement"}]:[{accountId:d.payableAccountId,debit:u.input.amount,credit:0,memo:"POS payable settlement"},{accountId:d.cashAccountId,debit:0,credit:u.input.amount,memo:"POS payable payment cash out"}]})}if(Oo(u)){let d=Xt(u.input.scopedAccountMapping,u.context);return Jt({journalId:u.context.journalId,tenantId:u.context.tenantId,branchId:u.context.branchId,occurredAt:u.context.occurredAt,reference:u.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:u.input.direction==="in"?[{accountId:d.cashAccountId,debit:u.input.amount,credit:0,memo:((i=u.input.reason)==null?void 0:i.trim())||"POS cash adjustment in"},{accountId:d.cashOverShortIncomeAccountId,debit:0,credit:u.input.amount,memo:"POS cash over/short gain"}]:[{accountId:d.cashOverShortExpenseAccountId,debit:u.input.amount,credit:0,memo:"POS cash over/short loss"},{accountId:d.cashAccountId,debit:0,credit:u.input.amount,memo:((a=u.input.reason)==null?void 0:a.trim())||"POS cash adjustment out"}]})}let r=Xt(u.input.scopedAccountMapping,u.context);return Jt({journalId:u.context.journalId,tenantId:u.context.tenantId,branchId:u.context.branchId,occurredAt:u.context.occurredAt,reference:u.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:[{accountId:r.expenseAccountId,debit:u.input.amount,credit:0,memo:((o=u.input.category)==null?void 0:o.trim())||"POS expense"},{accountId:r.paymentAccountId,debit:0,credit:u.input.amount,memo:((s=u.input.description)==null?void 0:s.trim())||"POS expense payment"}]})}function Ro(u){var e,t;return{saleAccountMapping:u.saleAccountMapping,purchaseAccountMapping:u.purchaseAccountMapping,returnAccountMapping:u.returnAccountMapping,expenseAccountMapping:u.expenseAccountMapping,settlementAccountMapping:u.settlementAccountMapping,cashAdjustmentAccountMapping:u.cashAdjustmentAccountMapping,financeProjectionSink:(0,en.createFinanceProjectionSink)({dbAdapter:u.dbAdapter,resolveFinanceServices:u.resolveFinanceServices,resolveLedgerProfileId:u.resolveLedgerProfileId,resolveSyncEnqueuer:u.resolveSyncEnqueuer,requiredAccounts:u.requiredAccounts,buildJournalDraft:(r,n)=>{var i;return Qi(r,{ledgerProfileId:n,financeDomainId:(i=u.financeDomainId)!=null?i:"ofpos"})},missingServicesErrorCode:(e=u.missingServicesErrorCode)!=null?e:"POS_FINANCE_SERVICES_UNAVAILABLE",missingLedgerProfileErrorCode:(t=u.missingLedgerProfileErrorCode)!=null?t:"POS_LEDGER_PROFILE_REQUIRED"})}}var Zt=class{constructor(e,t={}){this.context=e;this._runtimeOptions=t;var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=H(e)}async addReturn(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ae,i);return this.changeQueue.enqueue({type:"create",model:Ae,record:a}),this.context.logActivity("AddReturn",{id:r}),a}async updateReturn(e,t,r){let n=await(r||this.dbAdapter).get(Ae,e);if(!n)throw new Error(`Return with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ae,e,a);return this.changeQueue.enqueue({type:"update",model:Ae,record:o}),this.context.logActivity("UpdateReturn",{id:e}),o}async getReturns(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ae,{...e,filters:i})}async getReturn(e,t){return(t||this.dbAdapter).get(Ae,e)}async deleteReturn(e,t){return await(t||this.dbAdapter).delete(Ae,e),this.changeQueue.enqueue({type:"delete",model:Ae,record:{id:e}}),this.context.logActivity("DeleteReturn",{id:e}),{id:e,queued:!0}}async duplicateReturn(e,t){let r=await this.getReturn(e,t);if(!r)throw new Error(`Return with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ae,a);return this.changeQueue.enqueue({type:"create",model:Ae,record:a}),this.context.logActivity("DuplicateReturn",{originalId:e,newId:n}),o}async getReferenceItem(e,t,r,n){let i=await n.query(e==="sale_return"?ge:De,{filters:{deleted:!1,productId:r,...e==="sale_return"?{saleId:t}:{purchaseId:t}}});return i.length?i[0]:null}getCurrentRole(){var t,r;let e=(r=(t=this.context.session)==null?void 0:t.user)==null?void 0:r.role;return e?String(e).trim().toLowerCase():null}normalizeRoles(e,t){if(!Array.isArray(e))return t;let r=e.map(n=>String(n||"").trim().toLowerCase()).filter(Boolean);return r.length>0?r:t}validateApproval(e,t,r){let n=String((e==null?void 0:e.approvedBy)||"").trim(),i=String((e==null?void 0:e.reason)||"").trim(),a=String((e==null?void 0:e.approverRole)||"").trim().toLowerCase();if(!n||!i||!a)throw new Error(`${r} approval is required with approvedBy, reason, and approverRole`);if(!t.includes(a))throw new Error(`${r} approval approverRole is not allowed`);return{approvedBy:n,reason:i,approverRole:a}}getFraudGuardPolicy(){var i,a,o,s;let e=((i=this.context.config)==null?void 0:i.enableReturnFraudGuard)===!0,t=Number(((a=this.context.config)==null?void 0:a.returnFraudWindowMinutes)||60),r=Number(((o=this.context.config)==null?void 0:o.returnFraudMaxEvents)||3),n=((s=this.context.config)==null?void 0:s.returnFraudAction)==="block"?"block":"require_approval";return{enabled:e,windowMinutes:t>0?t:60,maxEvents:r>0?r:3,action:n}}async shouldTriggerFraudGuardForRefund(e){let t=this.getFraudGuardPolicy();if(!t.enabled||!e)return!1;let r=new Date(Date.now()-t.windowMinutes*60*1e3).toISOString();return(await this.dbAdapter.query(Ae,{filters:{and:[{field:"userId",operator:"=",value:e},{field:"date",operator:">=",value:r},{field:"deleted",operator:"=",value:!1}]}})).filter(a=>Number(a.actualRefund||0)>0).length>=t.maxEvents}async shouldTriggerFraudGuardForCancel(e){let t=this.getFraudGuardPolicy();if(!t.enabled||!e)return!1;let r=new Date(Date.now()-t.windowMinutes*60*1e3).toISOString();return(await this.dbAdapter.query(Z,{filters:{and:[{field:"userId",operator:"=",value:e},{field:"date",operator:">=",value:r},{field:"referenceType",operator:"IN",value:["sale_return_cancelled","purchase_return_cancelled"]},{field:"deleted",operator:"=",value:!1}]}})).length>=t.maxEvents}async emitFinanceProjection(e){var r,n,i,a;if(!this._runtimeOptions.financeProjectionSink||!this._runtimeOptions.returnAccountMapping||!(Number(e.actualRefund)>0))return;let t=String(((r=this.context.session)==null?void 0:r.tenantId)||"").trim();if(!t){(i=(n=this._runtimeOptions.logger)==null?void 0:n.logInfo)==null||i.call(n,"[ofpos] return finance projection skipped: tenantId unavailable");return}await this._runtimeOptions.financeProjectionSink(mi({returnEntry:e,tenantId:t,branchId:((a=this.context.config)==null?void 0:a.branchId)||void 0,scopedAccountMapping:this._runtimeOptions.returnAccountMapping}))}async processReturn(e){var z,V,F,U;let t=(V=(z=this.context)==null?void 0:z.domainServices)==null?void 0:V.inventory,{type:r,saleId:n=null,purchaseId:i=null,reason:a="",items:o,refundAmount:s,actualRefund:d=s,refundMethod:c="cash",creditNoteNumber:p=null,refundNote:l,refundReceivedDate:m,approval:f}=e;if(!n&&!i)throw new Error("saleId or purchaseId is required");if(r==="sale_return"&&!n)throw new Error("saleId required for sale_return");if(r==="purchase_return"&&!i)throw new Error("purchaseId required for purchase_return");let y=this.context.config.requireReasonForReturnOperations,b=String(a||"").trim();if(y&&!b)throw new Error("Return reason is required by policy");let h=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),g=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),x=this.getCurrentRole(),v=!x||!h.includes(x),A=d>0&&this.context.config.requireApprovalForReturnRefund&&v,I=String(((F=this.context.session)==null?void 0:F.userId)||"").trim(),k=d>0&&await this.shouldTriggerFraudGuardForRefund(I),w=this.getFraudGuardPolicy();if(k&&w.action==="block")throw new Error("Fraud guard: repeat return pattern detected (refund blocked)");let q=k&&w.action==="require_approval",M=A||q?this.validateApproval(f,g,q?"Fraud guard return refund":"Return refund"):null,E=(U=this.context.domainServices)==null?void 0:U.uom,L=await E.getUomsMap(),Q=this.context.domainServices.transaction;if(e.saleId){let O=await this.getReturnsByReference("sale_return",e.saleId);if(O.length>0){let _=await this.calculateTotalReturnedQty(O,e.items.map(R=>R.productId));for(let R of e.items){let P=await this.getOriginalQuantity("sale",e.saleId,R.productId),X=P-(_.get(R.productId)||0);if(R.quantity>X)throw new Error(`Produk ${R.productId} hanya bisa diretur ${X} lagi (sudah diretur ${_.get(R.productId)||0}/${P})`)}}}if(e.purchaseId){let O=await this.getReturnsByReference("purchase_return",e.purchaseId);if(O.length>0){let _=await this.calculateTotalReturnedQty(O,e.items.map(R=>R.productId));for(let R of e.items){let P=await this.getOriginalQuantity("purchase",e.purchaseId,R.productId),X=P-(_.get(R.productId)||0);if(R.quantity>X)throw new Error(`Produk ${R.productId} hanya bisa diretur ${X} lagi (sudah diretur ${_.get(R.productId)||0}/${P})`)}}}let T=await this.dbAdapter.transaction(async O=>{var te,J,Y;let _=new Date().toISOString(),R=D(),P=[],X={id:R,type:r,saleId:n,purchaseId:i,reason:b||null,refundAmount:s,actualRefund:d,refundMethod:d>0?c:null,creditNoteNumber:p,refundNote:d<s?typeof l=="number"?l:s-d:null,refundReceivedDate:d>0?m||_:null,status:d===s?"completed":d>0?"partially_refunded":"no_refund",date:_,userId:((te=this.context.session)==null?void 0:te.userId)||"",version:1,lastModified:_,deleted:!1};await O.create(Ae,X),P.push({type:"create",model:Ae,record:X});for(let be of o){let se=(J=be.restock)!=null?J:!0,Ne=be.quantity,pe=await this.getReferenceItem(r,n||i,be.productId,O);if(!pe)throw new Error(`Item not found in ${r==="sale_return"?"sale":"purchase"} ${n||i}`);let Te=r==="sale_return"?pe.unitPrice:pe.unitCost,me=pe.uomId,We={id:D(),returnId:R,productId:be.productId,quantity:Ne,unitPrice:Te,uomId:me,restock:se,restockNote:se?null:be.restockNote||"Rusak / tidak bisa dijual",version:1,lastModified:_,deleted:!1};if(await O.create(Re,We),P.push({type:"create",model:Re,record:We}),se){let Ye=E.convertQuantity(Ne,{conversionFactor:me&&((Y=L.get(me))==null?void 0:Y.conversionFactor)||1},{conversionFactor:1}),Xe=r==="sale_return"?+Ye:-Ye;await t.updateStock(be.productId,Xe,r,Ae,R,O)}}if(d>0)if((r==="sale_return"?"out":"in")==="in"){let se=await Q.recordCashIn({amount:d,method:c,data:{referenceType:r,referenceId:R,note:l}},O);P.push({type:"create",model:Z,record:se})}else{let se=await Q.recordCashOut({amount:d,method:c,data:{referenceType:r,referenceId:R,note:l}},O);P.push({type:"create",model:Z,record:se})}return M&&this.context.logActivity("ReturnRefundApproved",{returnId:R,approvedBy:M.approvedBy,approverRole:M.approverRole,reason:M.reason}),await this.emitFinanceProjection(X),{returnId:R,queued:!0,type:r,actualRefund:d,syncChanges:P}});for(let O of T.syncChanges)this.changeQueue.enqueue(O);return this.context.eventBus.emit("return:processed",{returnId:T.returnId,type:T.type,actualRefund:T.actualRefund}),this.context.logActivity("processReturn",{returnId:T.returnId,type:T.type,actualRefund:T.actualRefund}),{returnId:T.returnId,queued:T.queued}}async cancelReturn(e,t="Cancelled by user"){var A,I,k,w;let r=(I=(A=this.context)==null?void 0:A.domainServices)==null?void 0:I.inventory,n=(k=this.context.domainServices)==null?void 0:k.uom,i=await n.getUomsMap(),a=this.context.domainServices.transaction,o=typeof t=="string"?String(t||"").trim()||"Cancelled by user":t.reason===void 0?"Cancelled by user":String(t.reason||"").trim(),s=typeof t=="string"?void 0:t.approval;if(this.context.config.requireReasonForReturnOperations&&!String(o||"").trim())throw new Error("Return cancellation reason is required by policy");let c=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),p=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),l=this.getCurrentRole(),m=!l||!c.includes(l),f=this.context.config.requireApprovalForReturnCancel&&m,y=String(((w=this.context.session)==null?void 0:w.userId)||"").trim(),b=await this.shouldTriggerFraudGuardForCancel(y),h=this.getFraudGuardPolicy();if(b&&h.action==="block")throw new Error("Fraud guard: repeat return cancellation pattern detected (cancel blocked)");let g=b&&h.action==="require_approval",x=f||g?this.validateApproval(s,p,g?"Fraud guard return cancellation":"Return cancellation"):null,v=await this.dbAdapter.transaction(async q=>{var Q;let M=await q.get(Ae,e);if(!M||M.deleted)throw new Error("Return not found or already deleted");let E=[],L=await q.query(Re,{filters:{returnId:e,deleted:!1}});for(let T of L){if(T.restock){let z=n.convertQuantity(T.quantity,{conversionFactor:T.uomId&&((Q=i.get(T.uomId))==null?void 0:Q.conversionFactor)||1},{conversionFactor:1}),V=M.type==="sale_return"?-z:+z;await r.updateStock(T.productId,V,`${M.type}_cancelled`,Ae,e,q)}await q.update(Re,T.id,{deleted:!0,lastModified:new Date().toISOString()}),E.push({type:"delete",model:Re,record:{id:T.id}})}if(M.actualRefund>0)if((M.type==="sale_return"?"in":"out")==="in"){let z=await a.recordCashIn({amount:M.actualRefund,method:M.refundMethod||"cash",data:{referenceType:`${M.type}_cancelled`,referenceId:e,note:o}},q);E.push({type:"create",model:Z,record:z})}else{let z=await a.recordCashOut({amount:M.actualRefund,method:M.refundMethod||"cash",data:{referenceType:`${M.type}_cancelled`,referenceId:e,note:o}},q);E.push({type:"create",model:Z,record:z})}return await q.update(Ae,e,{deleted:!0,lastModified:new Date().toISOString()}),E.push({type:"delete",model:Ae,record:{id:e}}),x&&this.context.logActivity("CancelReturnApproved",{returnId:e,approvedBy:x.approvedBy,approverRole:x.approverRole,reason:x.reason}),{returnId:e,queued:!0,syncChanges:E}});for(let q of v.syncChanges)this.changeQueue.enqueue(q);return this.context.eventBus.emit("return:canceled",{returnId:v.returnId}),this.context.logActivity("cancelReturn",{returnId:v.returnId}),{returnId:v.returnId,queued:v.queued}}async getReturnsByReference(e,t){let r=e==="sale_return"?{saleId:t,deleted:!1}:{purchaseId:t,deleted:!1};return this.dbAdapter.query(Ae,{filters:r})}async getReturnableQuantity(e,t,r){let n=await this.getOriginalQuantity(e,t,r);if(n<=0)return 0;let i=e==="sale"?"sale_return":"purchase_return",a=await this.getReturnsByReference(i,t);if(!a.length)return n;let s=(await this.calculateTotalReturnedQty(a,[r])).get(r)||0;return Math.max(0,n-s)}async calculateTotalReturnedQty(e,t){let r=new Map;for(let n of e){let i=await this.dbAdapter.query(Re,{filters:{returnId:n.id,deleted:!1,restock:!0}});for(let a of i)t.includes(a.productId)&&r.set(a.productId,(r.get(a.productId)||0)+a.quantity)}return r}async getOriginalQuantity(e,t,r){let n=e==="sale"?ge:De,i=e==="sale"?"saleId":"purchaseId",a=await this.dbAdapter.query(n,{filters:{[i]:t,productId:r,deleted:!1}});return a.length?a[0].quantity:0}};var tn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addReturnItem(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Re,i);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("AddReturnItem",{id:r}),a}async updateReturnItem(e,t,r){let n=await(r||this.dbAdapter).get(Re,e);if(!n)throw new Error(`ReturnItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Re,e,a);return this.changeQueue.enqueue({type:"update",model:Re,record:o}),this.context.logActivity("UpdateReturnItem",{id:e}),o}async getReturnItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Re,{...e,filters:i})}async getReturnItem(e,t){return(t||this.dbAdapter).get(Re,e)}async deleteReturnItem(e,t){return await(t||this.dbAdapter).delete(Re,e),this.changeQueue.enqueue({type:"delete",model:Re,record:{id:e}}),this.context.logActivity("DeleteReturnItem",{id:e}),{id:e,queued:!0}}async duplicateReturnItem(e,t){let r=await this.getReturnItem(e,t);if(!r)throw new Error(`ReturnItem with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Re,a);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("DuplicateReturnItem",{originalId:e,newId:n}),o}};var Ce="roles";var rn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addRole(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ce,i);return this.changeQueue.enqueue({type:"create",model:Ce,record:a}),this.context.logActivity("AddRole",{id:r}),a}async updateRole(e,t,r){let n=await(r||this.dbAdapter).get(Ce,e);if(!n)throw new Error(`Role with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ce,e,a);return this.changeQueue.enqueue({type:"update",model:Ce,record:o}),this.context.logActivity("UpdateRole",{id:e}),o}async getRoles(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ce,{...e,filters:i})}async getRole(e,t){return(t||this.dbAdapter).get(Ce,e)}async deleteRole(e,t){return await(t||this.dbAdapter).delete(Ce,e),this.changeQueue.enqueue({type:"delete",model:Ce,record:{id:e}}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async duplicateRole(e,t){let r=await this.getRole(e,t);if(!r)throw new Error(`Role with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ce,a);return this.changeQueue.enqueue({type:"create",model:Ce,record:a}),this.context.logActivity("DuplicateRole",{originalId:e,newId:n}),o}};var ce="sales";var fe="receivables";var pt="inventory_lots";var er=class{constructor(e,t={}){this.context=e;this.runtimeOptions=t;this.defaultBaseCurrencyCode="IDR";var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=H(e),this.docNumberPolicy=new It(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t,r){var d,c,p;let n=(d=e.transactionCurrencyCode)!=null?d:this.defaultBaseCurrencyCode,i=(c=e.exchangeRate)!=null?c:1,a=Number.isFinite(i)&&i>0?Number(i):1,o=this.roundCurrencyAmount(e.totalInBaseCurrency!=null?Number(e.totalInBaseCurrency):t*a),s=this.roundCurrencyAmount(e.finalTotalInBaseCurrency!=null?Number(e.finalTotalInBaseCurrency):r*a);return{transactionCurrencyCode:n,exchangeRate:a,exchangeRateSource:(p=e.exchangeRateSource)!=null?p:"snapshot.manual",totalInBaseCurrency:o,finalTotalInBaseCurrency:s}}isExpiredLot(e,t){if(!e)return!1;let r=Date.parse(String(e));return Number.isFinite(r)?r<t:!1}diffInDays(e,t){let r=e.getTime(),n=t.getTime();return!Number.isFinite(r)||!Number.isFinite(n)?NaN:Math.floor((n-r)/(1440*60*1e3))}async enforceTempoCustomerCreditPolicy(e,t){if(!this.context.config.enableCustomerCreditPolicy)return;let r=String(t.customerId||"").trim();if(!r)throw new Error("Customer credit policy: customerId is required for tempo sale");let n=await e.query(fe,{filters:{and:[{field:"customerId",operator:"=",value:r},{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),i=new Date(t.nowIso),a=this.context.config.customerCreditOverdueGraceDays,o=0,s=0;for(let p of n){let l=Number(p.amount||0),m=Number(p.paidAmount||0),f=Math.max(0,l-m);if(f<=0)continue;o+=f;let y=this.diffInDays(new Date(String(p.dueDate||"")),i);Number.isFinite(y)&&(s=Math.max(s,y))}let d=this.context.config.customerCreditMaxOutstandingAmount;if(d!=null&&o+t.receivableAmount>d)throw new Error(`Customer credit policy: limit exceeded for customer ${r}`);if(this.context.config.customerCreditBlockOnOverdue&&s>a)throw new Error(`Customer credit policy: overdue receivable exceeds grace period for customer ${r}`);let c=this.context.config.customerCreditEscalationThresholdDays;s>=c&&this.context.logActivity("customerCreditEscalationDetected",{customerId:r,maxDaysPastDue:s,referenceId:t.referenceId,dueDate:t.dueDate})}normalizeDocNo(e){return this.docNumberPolicy.extractDocNo(e)}toBaseQuantity(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertQuantity(e,{conversionFactor:i},{conversionFactor:1}):e}async emitFinanceProjection(e){var r,n,i,a;if(!this.runtimeOptions.financeProjectionSink||!this.runtimeOptions.saleAccountMapping)return;let t=String(((r=this.context.session)==null?void 0:r.tenantId)||"").trim();if(!t){(i=(n=this.runtimeOptions.logger)==null?void 0:n.logInfo)==null||i.call(n,"[ofpos] sale finance projection skipped: tenantId unavailable");return}await this.runtimeOptions.financeProjectionSink(li({sale:e,tenantId:t,branchId:((a=this.context.config)==null?void 0:a.branchId)||void 0,scopedAccountMapping:this.runtimeOptions.saleAccountMapping}))}async getDuplicateDocumentNumbers(e){let t=[{field:"deleted",operator:"=",value:!1}];e!=null&&e.dateFrom&&t.push({field:"date",operator:">=",value:e.dateFrom}),e!=null&&e.dateTo&&t.push({field:"date",operator:"<=",value:e.dateTo});let r=await this.dbAdapter.query(ce,{filters:{and:t}}),n=new Map;for(let i of r){let a=this.normalizeDocNo(i.note);if(!a)continue;let o=n.get(a)||[];o.push(String(i.id)),n.set(a,o)}return Array.from(n.entries()).filter(([,i])=>i.length>1).map(([i,a])=>({docNo:i,saleIds:a}))}async requestReprint(e,t){let r=String(t.actorId||"").trim(),n=String(t.reason||"").trim();if(!r)throw new Error("Reprint policy: actorId is required");if(!n)throw new Error("Reprint policy: reason is required");let i=await this.dbAdapter.get(ce,e);if(!i||i.deleted)throw new Error(`Sale ${e} not found`);let a=this.normalizeDocNo(i.note),s=(await this.dbAdapter.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:ce},{field:"recordId",operator:"=",value:e},{field:"action",operator:"=",value:"reprint"}]}})).length+1,d=a?(await this.getDuplicateDocumentNumbers()).some(p=>p.docNo===a):!1,c=new Date().toISOString();return await this.dbAdapter.create(ie,{id:D(),tableName:ce,recordId:e,action:"reprint",changes:{actorId:r,reason:n,terminalId:t.terminalId||null,docNo:a,reprintCount:s,duplicateDocNoDetected:d},userId:r,timestamp:c}),d&&await this.dbAdapter.create(ie,{id:D(),tableName:ce,recordId:e,action:"duplicate_doc_detected",changes:{docNo:a,detector:"sale.requestReprint",detectedAt:c},userId:r,timestamp:c}),{saleId:e,docNo:a,reprintCount:s,duplicateDocNoDetected:d}}async consumeInventoryLotsForSale(e,t){var b,h,g;let r=Number(t.quantity||0);if(!Number.isFinite(r)||r<=0)return[];let n=(b=this.context.domainServices)==null?void 0:b.uom,i=await n.getUomsMap(),a=t.uomId&&((h=i.get(t.uomId))==null?void 0:h.conversionFactor)||1,o=n.convertQuantity(r,{conversionFactor:a},{conversionFactor:1});if(!Number.isFinite(o)||o<=0)return[];let s=await e.query(pt,{filters:{and:[{field:"productId",operator:"=",value:t.productId},{field:"deleted",operator:"=",value:!1},{field:"remainingQuantity",operator:">",value:0},{field:"status",operator:"IN",value:["active","expired"]}]},sort:[{field:"lastModified",direction:"asc"}]});if(!s.length)return[];let d=Number.isFinite(Date.parse(t.saleDate))?Date.parse(t.saleDate):Date.now(),c=new Date().toISOString(),p=[],l=[],m=0;for(let x of s){if(this.isExpiredLot(x.expiryDate,d)){if(x.status!=="expired"){let A=await e.update(pt,x.id,{status:"expired",version:Number(x.version||0)+1,lastModified:c});p.push({id:A.id,remainingQuantity:Number(A.remainingQuantity||0),status:String(A.status||"expired"),version:Number(A.version||0),lastModified:String(A.lastModified||c)})}continue}l.push(x),m+=Number(x.remainingQuantity||0)}if(m<o)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: insufficient non-expired lot stock`);let f=((g=this.context.config)==null?void 0:g.lotConsumptionPolicy)==="FIFO"?"FIFO":"FEFO";l.sort((x,v)=>{let A=Date.parse(x.lastModified||""),I=Date.parse(v.lastModified||"");if(f==="FIFO"){if(Number.isFinite(A)&&Number.isFinite(I)&&A!==I)return A-I}else{let k=x.expiryDate?Date.parse(x.expiryDate):Number.POSITIVE_INFINITY,w=v.expiryDate?Date.parse(v.expiryDate):Number.POSITIVE_INFINITY;if(Number.isFinite(k)&&Number.isFinite(w)&&k!==w)return k-w;if(Number.isFinite(k)!==Number.isFinite(w))return Number.isFinite(k)?-1:1}return Number.isFinite(A)&&Number.isFinite(I)&&A!==I?A-I:String(x.id).localeCompare(String(v.id))});let y=o;for(let x of l){if(y<=0)break;let v=Number(x.remainingQuantity||0);if(v<=0)continue;let A=Math.min(y,v),I=v-A,k=I<=0?"depleted":"active",w=await e.update(pt,x.id,{remainingQuantity:I,status:k,version:Number(x.version||0)+1,lastModified:c});p.push({id:w.id,remainingQuantity:Number(w.remainingQuantity||0),status:String(w.status||k),version:Number(w.version||0),lastModified:String(w.lastModified||c)}),y-=A}if(y>0)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: lot consumption incomplete`);return p}async addSale(e,t){let r=D(),n=new Date().toISOString(),i=this.resolveCurrencySnapshot(e,Number(e.total||0),Number(e.finalTotal||0)),a={id:r,...e,...i,version:1,lastModified:n,deleted:!1},o=await(t||this.dbAdapter).create(ce,a);return this.changeQueue.enqueue({type:"create",model:ce,record:o}),this.context.logActivity("AddSale",{id:r}),o}async updateSale(e,t,r){let n=await(r||this.dbAdapter).get(ce,e);if(!n)throw new Error(`Sale with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ce,e,a);return this.changeQueue.enqueue({type:"update",model:ce,record:o}),this.context.logActivity("UpdateSale",{id:e}),o}async getSales(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ce,{...e,filters:i})}async getSale(e,t){return(t||this.dbAdapter).get(ce,e)}async deleteSale(e,t){return await(t||this.dbAdapter).delete(ce,e),this.changeQueue.enqueue({type:"delete",model:ce,record:{id:e}}),this.context.logActivity("DeleteSale",{id:e}),{id:e,queued:!0}}async duplicateSale(e,t){let r=await this.getSale(e,t);if(!r)throw new Error(`Sale with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ce,a);return this.changeQueue.enqueue({type:"create",model:ce,record:a}),this.context.logActivity("DuplicateSale",{originalId:e,newId:n}),o}async createSale(e,t,r){let n=await this.dbAdapter.transaction(async i=>{var f,y,b,h,g,x;let a=((f=this.context.domainServices)==null?void 0:f.uom)||null,o=a?await a.getUomsMap():new Map,s=new Date().toISOString(),d=(y=e.id)!=null?y:D(),c=((b=this.context.config)==null?void 0:b.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",e.date||s):null,p={id:d,userId:e.userId,customerId:e.customerId,sourceOrderId:e.sourceOrderId,status:"completed",date:e.date||s,total:0,discount:(h=e.discount)!=null?h:0,ppn:(g=e.ppn)!=null?g:0,pph:(x=e.pph)!=null?x:0,finalTotal:0,transactionCurrencyCode:null,exchangeRate:null,exchangeRateSource:null,totalInBaseCurrency:0,finalTotalInBaseCurrency:0,note:c?this.docNumberPolicy.withNote(e.note,c):e.note,version:1,lastModified:s,deleted:!1},l=[];if(t){let v=t.reduce((A,I)=>{var k;return A+((k=I.unitPrice)!=null?k:0)*I.quantity},0);p.total=v,p.finalTotal=v+p.ppn+p.pph}if(Object.assign(p,this.resolveCurrencySnapshot(e,p.total,p.finalTotal)),await i.create(ce,p),l.push({type:"create",model:ce,record:p}),!t)return{sale:p,syncChanges:l};let m=t.map(v=>({id:D(),saleId:d,...v,version:1,lastModified:s,deleted:!1}));await i.bulkCreate(ge,m);for(let v of m)l.push({type:"create",model:ge,record:v});if(r)if(r.method!=="tempo"){let v=await this.context.domainServices.transaction.recordCashIn({method:r.method,data:{...r.data,referenceType:"sale",referenceId:d},amount:p.finalTotal},i);l.push({type:"create",model:Z,record:v})}else{let v=r.dueDate;await this.enforceTempoCustomerCreditPolicy(i,{customerId:p.customerId,receivableAmount:p.finalTotal,referenceId:p.id,dueDate:v,nowIso:s});let A=await this.context.domainServices.receivable.addReceivable({saleId:p.id,customerId:p.customerId,amount:p.finalTotal,dueDate:v,status:"unpaid",paidAmount:0,date:s},i);l.push({type:"create",model:fe,record:A})}for(let v of m){let A=this.toBaseQuantity(v.quantity,v.uomId,a,o),I=await this.consumeInventoryLotsForSale(i,{saleId:p.id,saleDate:p.date,productId:v.productId,quantity:v.quantity,uomId:v.uomId});for(let k of I)l.push({type:"update",model:pt,record:k});await this.context.domainServices.inventory.updateStock(v.productId,-A,"sale",ce,p.id,i)}return{sale:p,items:m,syncChanges:l}});for(let i of n.syncChanges)this.changeQueue.enqueue(i);return await this.emitFinanceProjection(n.sale),this.context.eventBus.emit("sale:finalized",n.sale.id),t?{sale:n.sale,items:n.items}:n.sale}async finalizeSale(e,t){let r=await this.dbAdapter.transaction(async i=>{var p;let a=((p=this.context.domainServices)==null?void 0:p.uom)||null,o=a?await a.getUomsMap():new Map,s=await this.getSale(e,i);if(!s)throw new Error(`Sale not found for id ${e}`);let d=[];if(t)if(t.method!=="tempo"){let l=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:e},amount:s.finalTotal},i);d.push({type:"create",model:Z,record:l})}else{let l=new Date().toISOString();await this.enforceTempoCustomerCreditPolicy(i,{customerId:s.customerId,receivableAmount:s.finalTotal,referenceId:s.id,dueDate:t.dueDate,nowIso:l});let m=await this.context.domainServices.receivable.addReceivable({saleId:s.id,customerId:s.customerId,amount:s.finalTotal,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:l},i);d.push({type:"create",model:fe,record:m})}let c=await i.query(ge,{filters:{saleId:e}});for(let l of c){let m=this.toBaseQuantity(l.quantity,l.uomId,a,o),f=await this.consumeInventoryLotsForSale(i,{saleId:e,saleDate:s.date,productId:l.productId,quantity:l.quantity,uomId:l.uomId});for(let y of f)d.push({type:"update",model:pt,record:y});await this.context.domainServices.inventory.updateStock(l.productId,-m,"sale",ce,e,i)}return{saleId:e,syncChanges:d}});for(let i of r.syncChanges)this.changeQueue.enqueue(i);let n=await this.getSale(r.saleId);n&&await this.emitFinanceProjection(n),this.context.eventBus.emit("sale:finalized",r.saleId)}async createSaleFromOrder(e,t){let r=await this.dbAdapter.transaction(async n=>{var v,A,I,k;let i=((v=this.context.domainServices)==null?void 0:v.uom)||null,a=i?await i.getUomsMap():new Map,o=await n.get(oe,e);if(!o)throw new Error(`Order not found for id ${e}`);let s=await n.query(xe,{filters:{orderId:e,deleted:!1}}),d=new Date().toISOString(),c=D(),p=((A=this.context.config)==null?void 0:A.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",o.date||d):null,l=[],m=s.reduce((w,q)=>w+(q.unitPrice||0)*q.quantity,0),f=(I=o.ppn)!=null?I:0,y=(k=o.pph)!=null?k:0,b=m+f+y,h=this.resolveCurrencySnapshot(o,m,b),g={id:c,userId:o.userId,customerId:o.customerId,sourceOrderId:o.id,discountCode:o.discountCode||null,status:"completed",date:o.date,total:m,discount:0,ppn:f,pph:y,finalTotal:b,...h,note:p?this.docNumberPolicy.withNote(o.note,p):o.note,version:1,lastModified:d,deleted:!1};await n.create(ce,g),l.push({type:"create",model:ce,record:g});let x=s.map(w=>({id:D(),saleId:c,productId:w.productId,quantity:w.quantity,uomId:w.uomId,unitPrice:w.unitPrice,version:1,lastModified:d,deleted:!1}));await n.bulkCreate(ge,x);for(let w of x)l.push({type:"create",model:ge,record:w});if(await n.update(oe,e,{status:"completed",saleId:c,lastModified:d}),l.push({type:"update",model:oe,record:{id:e,status:"completed",saleId:c,lastModified:d}}),t.method!=="tempo"){let w=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:c},amount:g.finalTotal},n);l.push({type:"create",model:Z,record:w})}else{let w=t.dueDate;await this.enforceTempoCustomerCreditPolicy(n,{customerId:g.customerId,receivableAmount:g.finalTotal,referenceId:g.id,dueDate:w,nowIso:d});let q=await this.context.domainServices.receivable.addReceivable({saleId:g.id,customerId:g.customerId,amount:g.finalTotal,dueDate:w,status:"unpaid",paidAmount:0,date:d},n);l.push({type:"create",model:fe,record:q})}for(let w of x){let q=this.toBaseQuantity(w.quantity,w.uomId,i,a),M=await this.consumeInventoryLotsForSale(n,{saleId:c,saleDate:g.date,productId:w.productId,quantity:w.quantity,uomId:w.uomId});for(let E of M)l.push({type:"update",model:pt,record:E});await this.context.domainServices.inventory.updateStock(w.productId,-q,"sale",ce,c,n)}return{sale:g,items:x,saleId:c,syncChanges:l}});for(let n of r.syncChanges)this.changeQueue.enqueue(n);return await this.emitFinanceProjection(r.sale),this.context.eventBus.emit("sale:finalized",r.saleId),{sale:r.sale,items:r.items}}async createSaleFromCart(e,t){var s;let r=this.context.domainServices.pricing,n=await this.context.domainServices.cart.getCart(e);if(!n)throw new Error(`Cart not found for id ${e}`);let i=(s=this.context.domainServices)==null?void 0:s.uom,a=await i.getUomsMap(),o=await this.dbAdapter.transaction(async d=>{var I,k,w,q;let c=n.customerId?await this.context.domainServices.customer.getCustomer(n.customerId,d):void 0,p=await r.calculateOrderTotal(n.items,n.discountCode,(c==null?void 0:c.groupId)||void 0),l=await r.calculatePPN(p.subTotal),m=await r.calculatePPH(p.subTotal),f=p.total+l+m,y=this.resolveCurrencySnapshot(n,p.subTotal,f),b=new Date().toISOString(),h=D(),g=((I=this.context.config)==null?void 0:I.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",b):null,x={id:h,userId:((w=(k=this.context)==null?void 0:k.session)==null?void 0:w.userId)||"",customerId:n.customerId||null,sourceOrderId:null,discountCode:n.discountCode||null,status:"completed",date:b,total:p.subTotal,discount:p.discount,ppn:l,pph:m,finalTotal:f,...y,note:g?this.docNumberPolicy.withNote(n.note||null,g):n.note||null,version:1,lastModified:b,deleted:!1},v=n.items.map(M=>({id:D(),saleId:h,productId:M.productId,quantity:M.quantity,uomId:M.uomId||null,unitPrice:M.unitPrice,version:1,lastModified:b,deleted:!1})),A=[];await d.create(ce,x),await d.bulkCreate(ge,v),A.push({type:"create",model:ce,record:x});for(let M of v)A.push({type:"create",model:ge,record:M});if(t.method!=="tempo"){let M=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:h},amount:x.finalTotal},d);A.push({type:"create",model:Z,record:M})}else{let M=t.dueDate;await this.enforceTempoCustomerCreditPolicy(d,{customerId:x.customerId,receivableAmount:x.finalTotal,referenceId:x.id,dueDate:M,nowIso:b});let E=await this.context.domainServices.receivable.addReceivable({saleId:x.id,customerId:x.customerId,amount:x.finalTotal,dueDate:M,status:"unpaid",paidAmount:0,date:b},d);A.push({type:"create",model:fe,record:E})}for(let M of v){let E=typeof M.uomId=="string"&&((q=a.get(M.uomId))==null?void 0:q.conversionFactor)||1,L=i.convertQuantity(M.quantity,{conversionFactor:E},{conversionFactor:1}),Q=await this.consumeInventoryLotsForSale(d,{saleId:h,saleDate:x.date,productId:M.productId,quantity:M.quantity,uomId:M.uomId});for(let T of Q)A.push({type:"update",model:pt,record:T});await this.context.domainServices.inventory.updateStock(M.productId,-L,"sale",ce,x.id,d)}return{sale:x,items:v,syncChanges:A}});await this.emitFinanceProjection(o.sale);for(let d of o.syncChanges)this.changeQueue.enqueue(d);this.context.eventBus.emit("sale:finalized",o.sale.id);try{await this.context.domainServices.cart.deleteCart(e)}catch(d){this.context.logError(d,{message:`Sale created but failed to delete cart ${e}`})}return{sale:o.sale,items:o.items}}};var nn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addSaleItem(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ge,i);return this.changeQueue.enqueue({type:"create",model:ge,record:a}),this.context.logActivity("AddSaleItem",{id:r}),a}async updateSaleItem(e,t,r){let n=await(r||this.dbAdapter).get(ge,e);if(!n)throw new Error(`SaleItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ge,e,a);return this.changeQueue.enqueue({type:"update",model:ge,record:o}),this.context.logActivity("UpdateSaleItem",{id:e}),o}async getSaleItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ge,{...e,filters:i})}async getSaleItem(e,t){return(t||this.dbAdapter).get(ge,e)}async deleteSaleItem(e,t){return await(t||this.dbAdapter).delete(ge,e),this.changeQueue.enqueue({type:"delete",model:ge,record:{id:e}}),this.context.logActivity("DeleteSaleItem",{id:e}),{id:e,queued:!0}}async duplicateSaleItem(e,t){let r=await this.getSaleItem(e,t);if(!r)throw new Error(`SaleItem with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ge,a);return this.changeQueue.enqueue({type:"create",model:ge,record:a}),this.context.logActivity("DuplicateSaleItem",{originalId:e,newId:n}),o}};var le="shifts";var tr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addShift(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(le,i);return this.changeQueue.enqueue({type:"create",model:le,record:a}),this.context.logActivity("AddShift",{id:r}),a}async updateShift(e,t,r){let n=await(r||this.dbAdapter).get(le,e);if(!n)throw new Error(`Shift with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(le,e,a);return this.changeQueue.enqueue({type:"update",model:le,record:o}),this.context.logActivity("UpdateShift",{id:e}),o}async getShifts(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(le,{...e,filters:i})}async getShift(e,t){return(t||this.dbAdapter).get(le,e)}async deleteShift(e,t){return await(t||this.dbAdapter).delete(le,e),this.changeQueue.enqueue({type:"delete",model:le,record:{id:e}}),this.context.logActivity("DeleteShift",{id:e}),{id:e,queued:!0}}async duplicateShift(e,t){let r=await this.getShift(e,t);if(!r)throw new Error(`Shift with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(le,a);return this.changeQueue.enqueue({type:"create",model:le,record:a}),this.context.logActivity("DuplicateShift",{originalId:e,newId:n}),o}async openShift(e,t,r){return this.dbAdapter.transaction(async n=>{var d;if(await this.getActiveShift(e))throw new Error("Kasir ini masih memiliki shift yang aktif");let a=new Date().toISOString(),o=D(),s={id:o,cashierId:e,cashierName:((d=this.context.session)==null?void 0:d.userId)||"Unknown",openedAt:a,closedAt:null,startingCash:t,endingCash:null,systemCash:null,cashDifference:null,status:"open",note:r||null,version:1,lastModified:a,deleted:!1};return await n.create(le,s),this.changeQueue.enqueue({type:"create",model:le,record:s}),this.context.eventBus.emit("shift:opened",{shiftId:o,cashierId:e,startingCash:t}),s})}async closeShift(e,t,r){let n=typeof r=="string"?r:r==null?void 0:r.note,i=typeof r=="string"||r==null?void 0:r.approval;return this.dbAdapter.transaction(async a=>{var h,g,x,v;let o=await a.get(le,e);if(!o||o.deleted||o.status!=="open")throw new Error("Shift tidak ditemukan atau sudah ditutup");let s=await a.query(Z,{aggregates:[{function:"SUM",field:"amount",as:"cashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashOut",filter:{and:[{field:"referenceType",operator:"IN",value:["sale_return","expense"]},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:o.openedAt},{field:"date",operator:"<",value:new Date(new Date().getTime()+1e3).toISOString()},{field:"deleted",operator:"=",value:!1}]}}),d=((h=s==null?void 0:s[0])==null?void 0:h.cashIn)||0,c=((g=s==null?void 0:s[0])==null?void 0:g.cashOut)||0,p=d-c,l=o.startingCash+p,m=t-l,f=Math.abs(m);if((x=this.context.config)!=null&&x.requireShiftCloseApprovalOnDifference){let A=(v=this.context.config)==null?void 0:v.shiftCloseDifferenceApprovalThreshold,I=typeof A=="number"&&A>=0?A:0;if(f>I){let k=String((i==null?void 0:i.approvedBy)||"").trim(),w=String((i==null?void 0:i.reason)||"").trim();if(!k||!w)throw new Error(`Shift close approval is required when cash difference exceeds ${I}`)}}let y=i?`[CLOSE_APPROVED_BY=${i.approvedBy}] [CLOSE_APPROVAL_REASON=${i.reason}]`:"",b={closedAt:new Date().toISOString(),endingCash:t,systemCash:l,cashDifference:m,status:"closed",note:[o.note||"",n||"",y].filter(Boolean).join(" | ")||null,lastModified:new Date().toISOString()};return await a.update(le,e,b),this.changeQueue.enqueue({type:"update",model:le,id:e,record:b}),this.context.eventBus.emit("shift:closed",{shiftId:e,cashierId:o.cashierId,systemEndingCash:l,physicalEndingCash:t,difference:m}),i&&this.context.logActivity("CloseShiftApproval",{shiftId:e,cashierId:o.cashierId,approvedBy:i.approvedBy,reason:i.reason,cashDifference:m},a),{...o,...b}})}async reopenShift(e,t){let r=String(t.approvedBy||"").trim(),n=String(t.reason||"").trim();if(!r)throw new Error("approvedBy is required to reopen shift");if(!n)throw new Error("reason is required to reopen shift");return this.dbAdapter.transaction(async i=>{var m;let a=await i.get(le,e);if(!a||a.deleted)throw new Error("Shift tidak ditemukan");if(a.status!=="closed")throw new Error("Hanya shift berstatus closed yang dapat di-reopen");if(await this.getActiveShift(a.cashierId))throw new Error("Kasir ini masih memiliki shift yang aktif");let s=new Date().toISOString(),d=D(),c=t.startingCash!=null?t.startingCash:(m=a.endingCash)!=null?m:a.startingCash,p=[a.note||"",`[REOPEN_FROM=${e}]`,`[APPROVED_BY=${r}]`,`[REASON=${n}]`].filter(Boolean),l={id:d,cashierId:a.cashierId,cashierName:a.cashierName,openedAt:s,closedAt:null,startingCash:c,endingCash:null,systemCash:null,cashDifference:null,status:"open",note:p.join(" "),version:1,lastModified:s,deleted:!1};return await i.create(le,l),this.changeQueue.enqueue({type:"create",model:le,record:l}),this.context.logActivity("ReopenShiftApproved",{fromShiftId:e,reopenedShiftId:d,cashierId:a.cashierId,approvedBy:r,reason:n},i),this.context.eventBus.emit("shift:reopened",{fromShiftId:e,reopenedShiftId:d,cashierId:a.cashierId,approvedBy:r}),l})}async getActiveShift(e){let t=await this.dbAdapter.query(le,{filters:{cashierId:e,status:"open",deleted:!1},limit:1});return(t==null?void 0:t[0])||null}async getShiftsByDate(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`;return this.dbAdapter.query(le,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]},sort:[{field:"openedAt",direction:"asc"}]})}async closeShiftPreview(e){let t=await this.dbAdapter.get(le,e);if(!t)throw new Error("Shift tidak ditemukan");let r=await this.dbAdapter.get(Z,{aggregates:[{function:"SUM",field:"amount",as:"cashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashOut",filter:{and:[{field:"referenceType",operator:"IN",value:["sale_return","expense"]},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:t.openedAt},{field:"deleted",operator:"=",value:!1}]}});return{cashIn:(r==null?void 0:r.cashIn)||0,cashOut:(r==null?void 0:r.cashOut)||0}}async getDailyReport(e){var l,m,f;let t=await this.getShiftsByDate(e),r=0,n=0,i=0;for(let y of t)r+=y.startingCash,y.status==="closed"&&(n+=y.endingCash||0,i+=y.systemCash||0);let a=`${e}T00:00:00.000Z`,o=`${e}T23:59:59.999Z`,s=await this.dbAdapter.query(Z,{aggregates:[{function:"SUM",field:"amount",as:"salesCash",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"returnsCash",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"expenses",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:a},{field:"date",operator:"<=",value:o},{field:"deleted",operator:"=",value:!1}]}}),d=((l=s==null?void 0:s[0])==null?void 0:l.salesCash)||0,c=((m=s==null?void 0:s[0])==null?void 0:m.returnsCash)||0,p=((f=s==null?void 0:s[0])==null?void 0:f.expenses)||0;return{date:e,totalSalesCash:d,totalReturnsCash:c,totalExpenses:p,netCashMovement:d-c-p,startingCash:r,systemEndingCash:i,physicalEndingCash:n,cashDifference:n-i,shifts:t}}};var Ee="tax_rates";var an=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addTaxRate(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ee,i);return this.changeQueue.enqueue({type:"create",model:Ee,record:a}),this.context.logActivity("AddTaxRate",{id:r}),a}async updateTaxRate(e,t,r){let n=await(r||this.dbAdapter).get(Ee,e);if(!n)throw new Error(`TaxRate with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ee,e,a);return this.changeQueue.enqueue({type:"update",model:Ee,record:o}),this.context.logActivity("UpdateTaxRate",{id:e}),o}async getTaxRates(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ee,{...e,filters:i})}async getTaxRate(e,t){return(t||this.dbAdapter).get(Ee,e)}async deleteTaxRate(e,t){return await(t||this.dbAdapter).delete(Ee,e),this.changeQueue.enqueue({type:"delete",model:Ee,record:{id:e}}),this.context.logActivity("DeleteTaxRate",{id:e}),{id:e,queued:!0}}async duplicateTaxRate(e,t){let r=await this.getTaxRate(e,t);if(!r)throw new Error(`TaxRate with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ee,a);return this.changeQueue.enqueue({type:"create",model:Ee,record:a}),this.context.logActivity("DuplicateTaxRate",{originalId:e,newId:n}),o}};var rr=class{constructor(e,t={}){this.context=e;this.runtimeOptions=t;this.allowedReferenceTypes=new Set(["sale","purchase","sale_return","purchase_return","sale_return_cancelled","purchase_return_cancelled","receivable_payment","payable_payment","cash_adjustment","expense"]);var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=H(e)}async emitCashAdjustmentFinanceProjection(e){var r,n,i;if(!this.runtimeOptions.financeProjectionSink||!this.runtimeOptions.cashAdjustmentAccountMapping)return;let t=String(((r=this.context.session)==null?void 0:r.tenantId)||"").trim();t&&await this.runtimeOptions.financeProjectionSink(gi({adjustment:{id:e.id,date:e.date,amount:e.amount,direction:e.direction,reason:typeof((n=e.metadata)==null?void 0:n.reason)=="string"?e.metadata.reason:null},tenantId:t,branchId:((i=this.context.config)==null?void 0:i.branchId)||void 0,scopedAccountMapping:this.runtimeOptions.cashAdjustmentAccountMapping}))}async getIdempotentTransaction(e,t,r){let n=r||this.dbAdapter,i=await n.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:"idempotency_keys"},{field:"recordId",operator:"=",value:t},{field:"action",operator:"=",value:`transaction_${e}`}]},sort:[{field:"timestamp",direction:"desc"}],limit:1});if(!i.length)return null;let a=i[0].changes||{},o=String(a.transactionId||"").trim();return o?n.get(Z,o):null}async saveIdempotencyMarker(e,t,r,n){var i;await n.create(ie,{id:D(),tableName:"idempotency_keys",recordId:t,action:`transaction_${e}`,changes:{transactionId:r,action:e},userId:String(((i=this.context.session)==null?void 0:i.userId)||"").trim()||null,timestamp:new Date().toISOString()})}getActorId(e){var n,i,a;let t=String(((n=this.context.session)==null?void 0:n.userId)||"").trim();return t||String(((i=e==null?void 0:e.data)==null?void 0:i.userId)||((a=e==null?void 0:e.data)==null?void 0:a.cashierId)||"").trim()}isShiftGuardEnabled(){var e;return((e=this.context.config)==null?void 0:e.requireActiveShiftForCash)===!0}shouldRequireActiveShift(e){return["sale","purchase","sale_return","purchase_return","receivable_payment","payable_payment","expense","cash_adjustment"].includes(e)}async assertActiveShiftGuard(e,t){var o;let r=String(((o=e==null?void 0:e.data)==null?void 0:o.referenceType)||"").trim();if(!this.isShiftGuardEnabled()||!this.shouldRequireActiveShift(r))return;let n=this.getActorId(e);if(!n)throw new Error("Active shift guard: actor userId/cashierId is required");let a=await(t||this.dbAdapter).query("shifts",{filters:{and:[{field:"cashierId",operator:"=",value:n},{field:"status",operator:"=",value:"open"},{field:"deleted",operator:"=",value:!1}]},limit:1});if(!a||a.length===0)throw new Error(`Active shift guard: no open shift for cashier ${n}`)}assertCashPolicy(e){var n,i,a;if(!this.isShiftGuardEnabled())return;let t=String(((n=e==null?void 0:e.data)==null?void 0:n.referenceType)||"").trim(),r=String(((i=e==null?void 0:e.data)==null?void 0:i.reasonCode)||"").trim();if((t==="expense"||t==="cash_adjustment")&&!r)throw new Error(`Cash policy: reasonCode is required for ${t}`);if(t==="cash_adjustment"){let o=(a=this.context.config)==null?void 0:a.maxCashAdjustmentAmount;if(typeof o=="number"&&o>0&&e.amount>o)throw new Error(`Cash policy: cash adjustment exceeds max limit (${o})`)}}assertReferenceIntegrity(e){var n,i;let t=String(((n=e==null?void 0:e.data)==null?void 0:n.referenceType)||"").trim(),r=String(((i=e==null?void 0:e.data)==null?void 0:i.referenceId)||"").trim();if(!t)throw new Error("Cash movement requires referenceType");if(!r)throw new Error("Cash movement requires referenceId");if(!this.allowedReferenceTypes.has(t))throw new Error(`Cash movement referenceType is invalid: ${t}`)}assertIdempotentReplayConsistency(e,t,r){var d,c;let n=t==="cash_in"?"in":"out",i=String(((d=r==null?void 0:r.data)==null?void 0:d.referenceType)||"").trim(),a=String(((c=r==null?void 0:r.data)==null?void 0:c.referenceId)||"").trim(),o=String((r==null?void 0:r.method)||"").trim();if(e.direction!==n||e.amount!==r.amount||String(e.referenceType||"")!==i||String(e.referenceId||"")!==a||String(e.method||"")!==o)throw new Error("Idempotency key reused with different cash transaction payload")}async addTransaction(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Z,i);return t||this.changeQueue.enqueue({type:"create",model:Z,record:a}),this.context.logActivity("AddTransaction",{id:r}),a}async updateTransaction(e,t,r){let n=await(r||this.dbAdapter).get(Z,e);if(!n)throw new Error(`Transaction with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Z,e,a);return r||this.changeQueue.enqueue({type:"update",model:Z,record:o}),this.context.logActivity("UpdateTransaction",{id:e}),o}async getTransactions(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Z,{...e,filters:i})}async getTransaction(e,t){return(t||this.dbAdapter).get(Z,e)}async deleteTransaction(e,t){return await(t||this.dbAdapter).delete(Z,e),t||this.changeQueue.enqueue({type:"delete",model:Z,record:{id:e}}),this.context.logActivity("DeleteTransaction",{id:e}),{id:e,queued:!0}}async duplicateTransaction(e,t){let r=await this.getTransaction(e,t);if(!r)throw new Error(`Transaction with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Z,a);return t||this.changeQueue.enqueue({type:"create",model:Z,record:a}),this.context.logActivity("DuplicateTransaction",{originalId:e,newId:n}),o}async recordCashIn(e,t){var p,l;let r=(p=this.context.registry)==null?void 0:p.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((l=e==null?void 0:e.data)==null?void 0:l.idempotencyKey)||"").trim();if(n){let m=await this.getIdempotentTransaction("cash_in",n,t);if(m)return this.assertIdempotentReplayConsistency(m,"cash_in",e),m}let i=this.getActorId(e),a=D(),o=t||this.dbAdapter,s=1,d=new Date().toISOString(),c={id:a,referenceType:e.data.referenceType,referenceId:e.data.referenceId,direction:"in",amount:e.amount,method:e.method,metadata:e.data,date:new Date().toISOString(),description:e.method,userId:i,version:s,lastModified:d,deleted:!1};try{let m=await o.create(Z,c);return n&&await this.saveIdempotencyMarker("cash_in",n,m.id,o),t||this.changeQueue.enqueue({type:"create",model:Z,record:m}),this.context.logActivity("RecordCashIn",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash in recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashIn"}),e.data.referenceType==="cash_adjustment"&&await this.emitCashAdjustmentFinanceProjection({id:m.id,date:m.date,amount:m.amount,direction:"in",metadata:m.metadata}),m}catch(m){throw r.logError("Error recording cash in",{id:a,method:e.method,amount:e.amount,error:m}),m}}async recordCashOut(e,t){var p,l;let r=(p=this.context.registry)==null?void 0:p.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((l=e==null?void 0:e.data)==null?void 0:l.idempotencyKey)||"").trim();if(n){let m=await this.getIdempotentTransaction("cash_out",n,t);if(m)return this.assertIdempotentReplayConsistency(m,"cash_out",e),m}let i=this.getActorId(e),a=D(),o=t||this.dbAdapter,s=1,d=new Date().toISOString(),c={id:a,referenceType:e.data.referenceType,referenceId:e.data.referenceId,direction:"out",amount:e.amount,method:e.method,metadata:e.data,date:new Date().toISOString(),description:e.method,userId:i,version:s,lastModified:d,deleted:!1};try{let m=await o.create(Z,c);return n&&await this.saveIdempotencyMarker("cash_out",n,m.id,o),t||this.changeQueue.enqueue({type:"create",model:Z,record:m}),this.context.logActivity("RecordCashOut",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash out recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashOut"}),e.data.referenceType==="cash_adjustment"&&await this.emitCashAdjustmentFinanceProjection({id:m.id,date:m.date,amount:m.amount,direction:"out",metadata:m.metadata}),m}catch(m){throw r.logError("Error recording cash out",{id:a,method:e.method,amount:e.amount,error:m}),m}}async adjustCash(e,t,r,n){var o,s;if(e<=0)throw new Error("Amount must be positive");let a={method:"cash",data:{referenceType:"cash_adjustment",referenceId:`adj-${new Date().toISOString().split("T")[0]}-${Date.now()}`,reason:r,reasonCode:"manual_adjustment",adjustedBy:((o=this.context.session)==null?void 0:o.userId)||"",userId:((s=this.context.session)==null?void 0:s.userId)||""},amount:e};return t==="in"?this.recordCashIn(a,n):this.recordCashOut(a,n)}async getTransactionsByReference(e,t,r,n){let i=n||this.dbAdapter,a={deleted:!1,referenceType:e,...t!==void 0?{referenceId:t}:{}},o=r!=null&&r.filters?{and:[r.filters,a]}:a;return await i.query(Z,{...r,filters:o})}async getDailySummary(e){let t=e||new Date().toISOString().slice(0,10),r=await this.dbAdapter.query(Z,{filters:{field:"date",operator:"LIKE",value:`${t}%`}}),n=r.filter(a=>a.direction==="in").reduce((a,o)=>a+o.amount,0),i=r.filter(a=>a.direction==="out").reduce((a,o)=>a+o.amount,0);return{totalIn:n,totalOut:i,net:n-i,date:t}}};var nt="uoms";function _o(u,e){return u*e}function To(u,e){return e!==0?u/e:NaN}var nr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addUom(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(nt,i);return this.changeQueue.enqueue({type:"create",model:nt,record:a}),this.context.logActivity("AddUom",{id:r}),a}async updateUom(e,t,r){let n=await(r||this.dbAdapter).get(nt,e);if(!n)throw new Error(`Uom with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(nt,e,a);return this.changeQueue.enqueue({type:"update",model:nt,record:o}),this.context.logActivity("UpdateUom",{id:e}),o}async getUoms(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(nt,{...e,filters:i})}async getUom(e,t){return(t||this.dbAdapter).get(nt,e)}async deleteUom(e,t){return await(t||this.dbAdapter).delete(nt,e),this.changeQueue.enqueue({type:"delete",model:nt,record:{id:e}}),this.context.logActivity("DeleteUom",{id:e}),{id:e,queued:!0}}async duplicateUom(e,t){let r=await this.getUom(e,t);if(!r)throw new Error(`Uom with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(nt,a);return this.changeQueue.enqueue({type:"create",model:nt,record:a}),this.context.logActivity("DuplicateUom",{originalId:e,newId:n}),o}convertQuantity(e,t,r){let n=_o(e,t.conversionFactor);return To(n,r.conversionFactor)}convertUnitPrice(e,t,r){if(t.conversionFactor<=0||r.conversionFactor<=0)throw new Error("conversionFactor must be > 0");return e*(r.conversionFactor/t.conversionFactor)}async getUomsMap(){let e=await this.getUoms();return new Map(e.map(t=>[t.id,t]))}};var je="users";var on=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addUser(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(je,i);return this.changeQueue.enqueue({type:"create",model:je,record:a}),this.context.logActivity("AddUser",{id:r}),a}async updateUser(e,t,r){let n=await(r||this.dbAdapter).get(je,e);if(!n)throw new Error(`User with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(je,e,a);return this.changeQueue.enqueue({type:"update",model:je,record:o}),this.context.logActivity("UpdateUser",{id:e}),o}async getUsers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(je,{...e,filters:i})}async getUser(e,t){return(t||this.dbAdapter).get(je,e)}async deleteUser(e,t){return await(t||this.dbAdapter).delete(je,e),this.changeQueue.enqueue({type:"delete",model:je,record:{id:e}}),this.context.logActivity("DeleteUser",{id:e}),{id:e,queued:!0}}async duplicateUser(e,t){let r=await this.getUser(e,t);if(!r)throw new Error(`User with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(je,a);return this.changeQueue.enqueue({type:"create",model:je,record:a}),this.context.logActivity("DuplicateUser",{originalId:e,newId:n}),o}};var Ke="suppliers";var ir=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addSupplier(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ke,i);return this.changeQueue.enqueue({type:"create",model:Ke,record:a}),this.context.logActivity("AddSupplier",{id:r}),a}async updateSupplier(e,t,r){let n=await(r||this.dbAdapter).get(Ke,e);if(!n)throw new Error(`Supplier with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ke,e,a);return this.changeQueue.enqueue({type:"update",model:Ke,record:o}),this.context.logActivity("UpdateSupplier",{id:e}),o}async getSuppliers(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ke,{...e,filters:i})}async getSupplier(e,t){return(t||this.dbAdapter).get(Ke,e)}async deleteSupplier(e,t){return await(t||this.dbAdapter).delete(Ke,e),this.changeQueue.enqueue({type:"delete",model:Ke,record:{id:e}}),this.context.logActivity("DeleteSupplier",{id:e}),{id:e,queued:!0}}async duplicateSupplier(e,t){let r=await this.getSupplier(e,t);if(!r)throw new Error(`Supplier with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ke,a);return this.changeQueue.enqueue({type:"create",model:Ke,record:a}),this.context.logActivity("DuplicateSupplier",{originalId:e,newId:n}),o}async searchSuppliers(e,t,r){let n=e.trim();if(!n)return[];let i=r||this.dbAdapter,a={and:[{or:[{field:"name",operator:"like",value:`%${n}%`},{field:"contactPerson",operator:"like",value:`%${n}%`},{field:"phone",operator:"like",value:`%${n}%`},{field:"email",operator:"like",value:`%${n}%`}]},{deleted:!1}]};return i.query(Ke,{...t,filters:a})}};var _e="purchase_orders";var ar=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPurchaseOrder(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(_e,i);return this.changeQueue.enqueue({type:"create",model:_e,record:a}),this.context.logActivity("AddPurchaseOrder",{id:r}),a}async updatePurchaseOrder(e,t,r){let n=await(r||this.dbAdapter).get(_e,e);if(!n)throw new Error(`PurchaseOrder with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(_e,e,a);return this.changeQueue.enqueue({type:"update",model:_e,record:o}),this.context.logActivity("UpdatePurchaseOrder",{id:e}),o}async getPurchaseOrders(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(_e,{...e,filters:i})}async getPurchaseOrder(e,t){return(t||this.dbAdapter).get(_e,e)}async deletePurchaseOrder(e,t){return await(t||this.dbAdapter).delete(_e,e),this.changeQueue.enqueue({type:"delete",model:_e,record:{id:e}}),this.context.logActivity("DeletePurchaseOrder",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrder(e,t){let r=await this.getPurchaseOrder(e,t);if(!r)throw new Error(`PurchaseOrder with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(_e,a);return this.changeQueue.enqueue({type:"create",model:_e,record:a}),this.context.logActivity("DuplicatePurchaseOrder",{originalId:e,newId:n}),o}};var $e="purchase_order_items";var sn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPurchaseOrderItem(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create($e,i);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("AddPurchaseOrderItem",{id:r}),a}async updatePurchaseOrderItem(e,t,r){let n=await(r||this.dbAdapter).get($e,e);if(!n)throw new Error(`PurchaseOrderItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update($e,e,a);return this.changeQueue.enqueue({type:"update",model:$e,record:o}),this.context.logActivity("UpdatePurchaseOrderItem",{id:e}),o}async getPurchaseOrderItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query($e,{...e,filters:i})}async getPurchaseOrderItem(e,t){return(t||this.dbAdapter).get($e,e)}async deletePurchaseOrderItem(e,t){return await(t||this.dbAdapter).delete($e,e),this.changeQueue.enqueue({type:"delete",model:$e,record:{id:e}}),this.context.logActivity("DeletePurchaseOrderItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrderItem(e,t){let r=await this.getPurchaseOrderItem(e,t);if(!r)throw new Error(`PurchaseOrderItem with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create($e,a);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("DuplicatePurchaseOrderItem",{originalId:e,newId:n}),o}};var Se="purchases";var ye="payables";var Ve="financial_settings";var or=class{constructor(e,t={}){this.context=e;this._runtimeOptions=t;this.defaultBaseCurrencyCode="IDR";var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=H(e),this.docNumberPolicy=new It(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t){var o,s,d;let r=(o=e.transactionCurrencyCode)!=null?o:this.defaultBaseCurrencyCode,n=(s=e.exchangeRate)!=null?s:1,i=Number.isFinite(n)&&n>0?Number(n):1,a=this.roundCurrencyAmount(e.totalInBaseCurrency!=null?Number(e.totalInBaseCurrency):t*i);return{transactionCurrencyCode:r,exchangeRate:i,exchangeRateSource:(d=e.exchangeRateSource)!=null?d:"snapshot.manual",totalInBaseCurrency:a}}toBaseQuantity(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertQuantity(e,{conversionFactor:i},{conversionFactor:1}):e}toBaseUnitCost(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertUnitPrice(e,{conversionFactor:i},{conversionFactor:1}):e}async emitFinanceProjection(e,t){var n,i,a,o;if(!this._runtimeOptions.financeProjectionSink||!this._runtimeOptions.purchaseAccountMapping)return;let r=String(((n=this.context.session)==null?void 0:n.tenantId)||"").trim();if(!r){(a=(i=this._runtimeOptions.logger)==null?void 0:i.logInfo)==null||a.call(i,"[ofpos] purchase finance projection skipped: tenantId unavailable");return}await this._runtimeOptions.financeProjectionSink(pi({purchase:e,tenantId:r,branchId:((o=this.context.config)==null?void 0:o.branchId)||void 0,paymentMethod:t,scopedAccountMapping:this._runtimeOptions.purchaseAccountMapping}))}async getCostingMethod(e){var n;let t=await e.query(Ve,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}],limit:1});return String(((n=t[0])==null?void 0:n.costingMethod)||"FIFO").trim().toUpperCase()==="AVERAGE"?"AVERAGE":"FIFO"}async applyCostingPolicy(e,t){var a;if(!t.length)return;let r=(a=this.context.domainServices)==null?void 0:a.inventory,n=await this.getCostingMethod(e),i=new Map;for(let o of t){let s=Number(o.quantity),d=Number(o.unitCost);if(!Number.isFinite(s)||!Number.isFinite(d)||s<=0)continue;let c=i.get(o.productId)||{quantity:0,totalCost:0};c.quantity+=s,c.totalCost+=s*d,i.set(o.productId,c)}for(let[o,s]of i.entries()){let d=await e.get(ue,o);if(!d||d.deleted)continue;let c=s.totalCost/s.quantity,p=await r.getStock(o),l=d.cost;if(n==="AVERAGE"){let y=Math.max(0,Number(p)||0),b=y+s.quantity;b>0?l=(d.cost*y+s.totalCost)/b:l=c}else(Number(p)||0)<=0&&(l=c);if(!Number.isFinite(l)||l===d.cost)continue;let m=new Date().toISOString(),f=await e.update(ue,o,{cost:l,version:d.version+1,lastModified:m});this.changeQueue.enqueue({type:"update",model:ue,record:f})}}async addPurchase(e,t){var d;let r=D(),n=new Date().toISOString(),i=((d=this.context.config)==null?void 0:d.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",e.date||n):null,a=this.resolveCurrencySnapshot(e,Number(e.total||0)),o={id:r,...e,...a,note:i?this.docNumberPolicy.withNote(e.note,i):e.note,version:1,lastModified:n,deleted:!1},s=await(t||this.dbAdapter).create(Se,o);return this.changeQueue.enqueue({type:"create",model:Se,record:s}),this.context.logActivity("AddPurchase",{id:r}),s}async updatePurchase(e,t,r){let n=await(r||this.dbAdapter).get(Se,e);if(!n)throw new Error(`Purchase with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Se,e,a);return this.changeQueue.enqueue({type:"update",model:Se,record:o}),this.context.logActivity("UpdatePurchase",{id:e}),o}async getPurchases(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Se,{...e,filters:i})}async getPurchase(e,t){return(t||this.dbAdapter).get(Se,e)}async deletePurchase(e,t){return await(t||this.dbAdapter).delete(Se,e),this.changeQueue.enqueue({type:"delete",model:Se,record:{id:e}}),this.context.logActivity("DeletePurchase",{id:e}),{id:e,queued:!0}}async duplicatePurchase(e,t){let r=await this.getPurchase(e,t);if(!r)throw new Error(`Purchase with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Se,a);return this.changeQueue.enqueue({type:"create",model:Se,record:a}),this.context.logActivity("DuplicatePurchase",{originalId:e,newId:n}),o}async finalizePurchase(e,t,r){var f,y,b;if(!r){let h=await this.dbAdapter.transaction(async g=>this.finalizePurchase(e,t,g));return this.context.eventBus.emit("purchase:finalized",e),h}let n=(y=(f=this.context)==null?void 0:f.domainServices)==null?void 0:y.inventory,i=((b=this.context.domainServices)==null?void 0:b.uom)||null,a=i?await i.getUomsMap():new Map,o=await r.get(Se,e);if(!o)throw new Error(`Purchase not found for id ${e}`);let s=await r.query(De,{filters:{and:[{field:"purchaseId",value:e},{field:"deleted",value:!1}]}}),d=s.reduce((h,g)=>h+g.unitCost*g.quantity,0),c=Date.now(),p=new Date().toISOString(),l=this.resolveCurrencySnapshot(o,d);await r.update(Se,e,{total:d,...l,version:c,lastModified:p});let m={...o,total:d,...l,version:c,lastModified:p};await this.applyCostingPolicy(r,s.map(h=>({productId:h.productId,quantity:this.toBaseQuantity(h.quantity,h.uomId,i,a),unitCost:this.toBaseUnitCost(h.unitCost,h.uomId,i,a)})));for(let h of s)await n.updateStock(h.productId,this.toBaseQuantity(h.quantity,h.uomId,i,a),"purchase",Se,e,r);return await this.context.domainServices.priceHistory.recordPriceHistory(s.map(h=>({productId:h.productId,unitCost:this.toBaseUnitCost(h.unitCost,h.uomId,i,a),supplierId:o.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:m.supplierId,purchaseId:m.id,amount:m.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:m.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:m.total,method:t.method,data:{referenceType:"purchase",referenceId:m.id,...t.data||{}}},r),this.changeQueue.enqueue({type:"update",model:Se,record:m}),await this.emitFinanceProjection(m,t.method),{purchase:m,queued:!0}}async receivePurchaseFromPO(e,t,r){var E,L,Q,T,z,V;if(!r){let F=await this.dbAdapter.transaction(async U=>this.receivePurchaseFromPO(e,t,U));return this.context.eventBus.emit("purchase:finalized",F.purchase.id),F}let n=(L=(E=this.context)==null?void 0:E.domainServices)==null?void 0:L.inventory,i=((Q=this.context.domainServices)==null?void 0:Q.uom)||null,a=i?await i.getUomsMap():new Map,o=await r.get(_e,e);if(!o)throw new Error(`PurchaseOrder not found for id ${e}`);if(o.status!=="draft"&&o.status!=="sent"&&o.status!=="partially_received")throw new Error(`PurchaseOrder with id ${e} cannot be received as it is not in draft/sent/partially_received status`);let s=await r.query($e,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}}),c=(await r.query(Se,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}})).map(F=>F.id),p=new Map;if(c.length>0){let F=await r.query(De,{filters:{and:[{field:"deleted",value:!1},{or:c.map(U=>({field:"purchaseId",value:U}))}]}});for(let U of F)U.purchaseOrderItemId&&p.set(U.purchaseOrderItemId,(p.get(U.purchaseOrderItemId)||0)+Number(U.quantity||0))}let l=new Map(s.map(F=>[F.id,F])),m=new Map;for(let F of s){let U=m.get(F.productId)||[];U.push(F),m.set(F.productId,U)}let f=[],y=Array.isArray(t.receivedItems)?t.receivedItems:null;if(y&&y.length>0){let F=((T=this.context.config)==null?void 0:T.requireLotExpiryForPurchaseReceiving)===!0;for(let U of y){let _=U.purchaseOrderItemId?l.get(U.purchaseOrderItemId):void 0;if(!_&&U.productId){let se=m.get(U.productId)||[];if(se.length===1)_=se[0];else if(se.length>1)throw new Error(`Ambiguous productId ${U.productId}: provide purchaseOrderItemId for partial receiving`)}if(!_)throw new Error("Invalid partial receiving payload: source purchase order item not found");let R=Number(U.receivedQuantity);if(!Number.isFinite(R)||R<=0)throw new Error("Invalid partial receiving payload: receivedQuantity must be > 0");let P=p.get(_.id)||0,X=f.filter(se=>se.sourceOrderItem.id===_.id).reduce((se,Ne)=>se+Ne.quantity,0),te=Number(_.quantity)-P-X;if(R>te)throw new Error(`Partial receiving exceeds remaining quantity for PO item ${_.id}`);let J=U.unitCost!=null?Number(U.unitCost):Number(_.unitCost);if(!Number.isFinite(J)||J<0)throw new Error("Invalid partial receiving payload: unitCost must be >= 0");let Y=U.serialNumber!=null?String(U.serialNumber).trim():"";if(Y&&R!==1)throw new Error("Serial-number receiving currently requires receivedQuantity = 1");f.push({sourceOrderItem:_,quantity:R,unitCost:J,uomId:U.uomId!==void 0?U.uomId:_.uomId,lotNumber:U.lotNumber!=null&&String(U.lotNumber).trim()||null,serialNumber:Y||null,expiryDate:U.expiryDate!=null&&String(U.expiryDate).trim()||null,note:U.note!=null?String(U.note):null});let be=f[f.length-1];if(F){if(!be.lotNumber)throw new Error("Lot policy violation: lotNumber is required when requireLotExpiryForPurchaseReceiving=true");if(!be.expiryDate)throw new Error("Lot policy violation: expiryDate is required when requireLotExpiryForPurchaseReceiving=true")}}}else{if(((z=this.context.config)==null?void 0:z.requireLotExpiryForPurchaseReceiving)===!0)throw new Error("Lot policy violation: receivedItems with lotNumber and expiryDate are required when requireLotExpiryForPurchaseReceiving=true");for(let F of s){let U=p.get(F.id)||0,O=Number(F.quantity)-U;O<=0||f.push({sourceOrderItem:F,quantity:O,unitCost:Number(F.unitCost),uomId:F.uomId,lotNumber:null,serialNumber:null,expiryDate:null,note:null})}}if(f.length===0)throw new Error(`PurchaseOrder with id ${e} has no remaining receivable items`);let b=f.reduce((F,U)=>F+U.unitCost*U.quantity,0),h=D(),g=new Date().toISOString(),x=((V=this.context.config)==null?void 0:V.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",o.date||g):null,v={id:h,supplierId:o.supplierId,userId:o.userId,purchaseOrderId:e,date:o.date,total:b,...this.resolveCurrencySnapshot(o,b),note:x?this.docNumberPolicy.withNote(o.note,x):o.note,version:1,lastModified:g,deleted:!1};await r.create(Se,v),this.changeQueue.enqueue({type:"create",model:Se,record:v});for(let F of f){let U=D(),O={id:U,purchaseId:h,purchaseOrderItemId:F.sourceOrderItem.id,productId:F.sourceOrderItem.productId,quantity:F.quantity,uomId:F.uomId,unitCost:F.unitCost,version:1,lastModified:g,deleted:!1};if(await r.create(De,O),this.changeQueue.enqueue({type:"create",model:De,record:O}),F.lotNumber||F.serialNumber||F.expiryDate){let _=this.toBaseQuantity(F.quantity,F.uomId,i,a),R={id:D(),productId:F.sourceOrderItem.productId,purchaseId:h,purchaseItemId:U,purchaseOrderId:e,purchaseOrderItemId:F.sourceOrderItem.id,lotNumber:F.lotNumber,serialNumber:F.serialNumber,expiryDate:F.expiryDate,quantity:_,remainingQuantity:_,status:"active",note:F.note,version:1,lastModified:g,deleted:!1};await r.create(pt,R),this.changeQueue.enqueue({type:"create",model:pt,record:R})}}let A=new Map(p);for(let F of f)A.set(F.sourceOrderItem.id,(A.get(F.sourceOrderItem.id)||0)+F.quantity);let k=s.every(F=>(A.get(F.id)||0)>=Number(F.quantity))?"received":"partially_received",w=Date.now(),q=new Date().toISOString();await r.update(_e,e,{status:k,version:w,lastModified:q}),this.changeQueue.enqueue({type:"update",model:_e,record:{id:e,status:k,version:w,lastModified:q}});let M=f.filter(F=>Number(F.unitCost)!==Number(F.sourceOrderItem.unitCost)).map(F=>({purchaseOrderItemId:F.sourceOrderItem.id,productId:F.sourceOrderItem.productId,orderedUnitCost:F.sourceOrderItem.unitCost,receivedUnitCost:F.unitCost,quantity:F.quantity,varianceAmount:(F.unitCost-F.sourceOrderItem.unitCost)*F.quantity}));M.length>0&&await this.context.logActivity("PO_PRICE_VARIANCE_DETECTED",{purchaseOrderId:e,purchaseId:h,entries:M},r),await this.applyCostingPolicy(r,f.map(F=>({productId:F.sourceOrderItem.productId,quantity:this.toBaseQuantity(F.quantity,F.uomId,i,a),unitCost:this.toBaseUnitCost(F.unitCost,F.uomId,i,a)})));for(let F of f)await n.updateStock(F.sourceOrderItem.productId,this.toBaseQuantity(F.quantity,F.uomId,i,a),"purchase",Se,h,r);return await this.context.domainServices.priceHistory.recordPriceHistory(f.map(F=>({productId:F.sourceOrderItem.productId,unitCost:this.toBaseUnitCost(F.unitCost,F.uomId,i,a),supplierId:o.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:v.supplierId,purchaseId:v.id,amount:v.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:v.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:v.total,method:t.method,data:{referenceType:"purchase",referenceId:v.id,...t.data||{}}},r),await this.emitFinanceProjection(v,t.method),{purchase:v,queued:!0}}async createPurchaseFromCart(e){var a,o,s;let t=(o=(a=this.context)==null?void 0:a.domainServices)==null?void 0:o.inventory,r=(s=this.context.domainServices)==null?void 0:s.uom,n=(await r.getUoms()).reduce((d,c)=>({...d,[c.id]:c}),{}),i;try{i=await this.dbAdapter.transaction(async d=>{var g,x;let c=new Date().toISOString(),p=D(),l=((g=this.context.config)==null?void 0:g.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",c):null,m=[],f=e.items.reduce((v,A)=>v+A.unitCost*A.quantity,0),y={id:p,supplierId:e.supplierId,userId:((x=this.context.session)==null?void 0:x.userId)||"",purchaseOrderId:null,date:c,total:f,...this.resolveCurrencySnapshot(e,f),note:l?this.docNumberPolicy.withNote(e.note||null,l):e.note||null,version:1,lastModified:c,deleted:!1};await d.create(Se,y),m.push({type:"create",model:Se,record:y});let b=e.items.map(v=>({id:D(),purchaseId:p,purchaseOrderItemId:null,productId:v.productId,quantity:v.quantity,uomId:v.uomId||null,unitCost:v.unitCost,version:1,lastModified:c,deleted:!1}));await d.bulkCreate(De,b);for(let v of b)m.push({type:"create",model:De,record:v});await this.applyCostingPolicy(d,b.map(v=>{let A=typeof v.uomId=="string"?n[v.uomId].conversionFactor:1;return{productId:v.productId,quantity:r.convertQuantity(v.quantity,{conversionFactor:A},{conversionFactor:1}),unitCost:r.convertUnitPrice(v.unitCost,{conversionFactor:A},{conversionFactor:1})}}));for(let v of b){let A=typeof v.uomId=="string"?n[v.uomId].conversionFactor:1;await t.updateStock(v.productId,r.convertQuantity(v.quantity,{conversionFactor:A},{conversionFactor:1}),"purchase",Se,p,d)}let h=[];for(let v of b){let A=typeof v.uomId=="string"?n[v.uomId].conversionFactor:1;h.push({productId:v.productId,unitCost:r.convertUnitPrice(v.unitCost,{conversionFactor:A},{conversionFactor:1}),supplierId:e.supplierId,effectiveDate:c})}if(await this.context.domainServices.priceHistory.recordPriceHistory(h,d),e.paymentMethod==="tempo"){let v=await this.context.domainServices.payable.addPayable({supplierId:y.supplierId,purchaseId:y.id,amount:y.total,dueDate:e.dueDate,status:"unpaid",paidAmount:0,date:y.date||new Date().toISOString()},d);m.push({type:"create",model:ye,record:v})}else{let v=await this.context.domainServices.transaction.recordCashOut({amount:f,method:e.paymentMethod,data:{referenceType:"purchase",referenceId:p,...e.paymentData||{}}},d);m.push({type:"create",model:Z,record:v})}return{purchase:y,items:b,purchaseId:p,syncChanges:m}})}catch(d){throw t.clearStockCache(),d}for(let d of i.syncChanges)this.changeQueue.enqueue(d);return await this.emitFinanceProjection(i.purchase,e.paymentMethod),this.context.eventBus.emit("purchase:finalized",i.purchaseId),{purchase:i.purchase,items:i.items}}};var cn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPurchaseItem(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(De,i);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("AddPurchaseItem",{id:r}),a}async updatePurchaseItem(e,t,r){let n=await(r||this.dbAdapter).get(De,e);if(!n)throw new Error(`PurchaseItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(De,e,a);return this.changeQueue.enqueue({type:"update",model:De,record:o}),this.context.logActivity("UpdatePurchaseItem",{id:e}),o}async getPurchaseItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(De,{...e,filters:i})}async getPurchaseItem(e,t){return(t||this.dbAdapter).get(De,e)}async deletePurchaseItem(e,t){return await(t||this.dbAdapter).delete(De,e),this.changeQueue.enqueue({type:"delete",model:De,record:{id:e}}),this.context.logActivity("DeletePurchaseItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseItem(e,t){let r=await this.getPurchaseItem(e,t);if(!r)throw new Error(`PurchaseItem with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(De,a);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("DuplicatePurchaseItem",{originalId:e,newId:n}),o}};var Oe="inventory_logs";function _t(u){return{all:u=u||new Map,on:function(e,t){var r=u.get(e);r?r.push(t):u.set(e,[t])},off:function(e,t){var r=u.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):u.set(e,[]))},emit:function(e,t){var r=u.get(e);r&&r.slice().map(function(n){n(t)}),(r=u.get("*"))&&r.slice().map(function(n){n(e,t)})}}}var Le=_t();var sr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addInventoryLog(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(Oe,i);return this.changeQueue.enqueue({type:"create",model:Oe,record:a}),this.emitStockChanged(a.productId),this.context.logActivity("AddInventoryLog",{id:r}),a}async updateInventoryLog(e,t,r){let n=await(r||this.dbAdapter).get(Oe,e);if(!n)throw new Error(`InventoryLog with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e},o=await(r||this.dbAdapter).update(Oe,e,a);return this.changeQueue.enqueue({type:"update",model:Oe,record:o}),this.emitStockChanged(n.productId),this.emitStockChanged(o.productId),this.context.logActivity("UpdateInventoryLog",{id:e}),o}async getInventoryLogs(e,t){return(t||this.dbAdapter).query(Oe,e)}async getInventoryLog(e,t){return(t||this.dbAdapter).get(Oe,e)}async deleteInventoryLog(e,t){let r=await(t||this.dbAdapter).get(Oe,e);return await(t||this.dbAdapter).delete(Oe,e),this.changeQueue.enqueue({type:"delete",model:Oe,record:{id:e}}),this.emitStockChanged(r==null?void 0:r.productId),this.context.logActivity("DeleteInventoryLog",{id:e}),{id:e,queued:!0}}async duplicateInventoryLog(e,t){let r=await this.getInventoryLog(e,t);if(!r)throw new Error(`InventoryLog with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Oe,a);return this.changeQueue.enqueue({type:"create",model:Oe,record:a}),this.emitStockChanged(o.productId),this.context.logActivity("DuplicateInventoryLog",{originalId:e,newId:n}),o}emitStockChanged(e){var r,n;if(!e)return;let t=(r=this.context.domainServices)==null?void 0:r.inventory;(n=t==null?void 0:t.invalidateProductStock)==null||n.call(t,e),Le.emit("stock:changed",{productId:e,delta:0})}};var Ge="price_histories";var cr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPriceHistory(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ge,i);return this.changeQueue.enqueue({type:"create",model:Ge,record:a}),this.context.logActivity("AddPriceHistory",{id:r}),a}async updatePriceHistory(e,t,r){let n=await(r||this.dbAdapter).get(Ge,e);if(!n)throw new Error(`PriceHistory with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ge,e,a);return this.changeQueue.enqueue({type:"update",model:Ge,record:o}),this.context.logActivity("UpdatePriceHistory",{id:e}),o}async getPriceHistories(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ge,{...e,filters:i})}async getPriceHistory(e,t){return(t||this.dbAdapter).get(Ge,e)}async deletePriceHistory(e,t){return await(t||this.dbAdapter).delete(Ge,e),this.changeQueue.enqueue({type:"delete",model:Ge,record:{id:e}}),this.context.logActivity("DeletePriceHistory",{id:e}),{id:e,queued:!0}}async duplicatePriceHistory(e,t){let r=await this.getPriceHistory(e,t);if(!r)throw new Error(`PriceHistory with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ge,a);return this.changeQueue.enqueue({type:"create",model:Ge,record:a}),this.context.logActivity("DuplicatePriceHistory",{originalId:e,newId:n}),o}async recordPriceHistory(e,t){var n;let r=[];for(let i of e){let a={id:D(),productId:i.productId,unitCost:i.unitCost,supplierId:i.supplierId,effectiveDate:(n=i.effectiveDate)!=null?n:new Date().toISOString(),version:1,lastModified:new Date().toISOString(),deleted:!1},o=await(t||this.dbAdapter).create(Ge,a);this.context.logActivity("RecordPriceHistory",{productId:i.productId,unitCost:i.unitCost}),r.push(o)}return r}};var we="stock_opnames";var Me="stock_opname_items";var ur=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addStockOpname(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(we,i);return this.changeQueue.enqueue({type:"create",model:we,record:a}),this.context.logActivity("AddStockOpname",{id:r}),a}async updateStockOpname(e,t,r){let n=await(r||this.dbAdapter).get(we,e);if(!n)throw new Error(`StockOpname with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(we,e,a);return this.changeQueue.enqueue({type:"update",model:we,record:o}),this.context.logActivity("UpdateStockOpname",{id:e}),o}async getStockOpnames(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(we,{...e,filters:i})}async getStockOpname(e,t){return(t||this.dbAdapter).get(we,e)}async deleteStockOpname(e,t){return await(t||this.dbAdapter).delete(we,e),this.changeQueue.enqueue({type:"delete",model:we,record:{id:e}}),this.context.logActivity("DeleteStockOpname",{id:e}),{id:e,queued:!0}}async duplicateStockOpname(e,t){let r=await this.getStockOpname(e,t);if(!r)throw new Error(`StockOpname with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(we,a);return this.changeQueue.enqueue({type:"create",model:we,record:a}),this.context.logActivity("DuplicateStockOpname",{originalId:e,newId:n}),o}async cancelOpname(e){let t=await this.dbAdapter.get(we,e);if(!t||t.deleted||t.status!=="pending")throw new Error("Stock opname tidak valid atau sudah selesai");let r={...t,status:"cancelled",version:t.version+1,lastModified:new Date().toISOString(),deleted:!1};await this.dbAdapter.update(we,e,r);try{this.changeQueue.enqueue({type:"update",model:we,id:t.id,record:r})}catch{}}async completeOpname(e){await this.dbAdapter.transaction(async t=>{var o,s;let r=(s=(o=this.context)==null?void 0:o.domainServices)==null?void 0:s.inventory,n=await t.get(we,e);if(!n||n.deleted||n.status!=="pending")throw new Error("Stock opname tidak valid atau sudah selesai");let i=await t.query(Me,{filters:{stockOpnameId:e,deleted:!1}});for(let d of i)d.difference!==0&&await r.updateStock(d.productId,d.difference,"opname_adjustment",we,e,t);let a=await t.update(we,e,{status:"completed",lastModified:new Date().toISOString()});this.changeQueue.enqueue({type:"update",model:we,id:e,record:a})})}};var un=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addStockOpnameItem(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Me,i);return this.changeQueue.enqueue({type:"create",model:Me,record:a}),this.context.logActivity("AddStockOpnameItem",{id:r}),a}async updateStockOpnameItem(e,t,r){let n=await(r||this.dbAdapter).get(Me,e);if(!n)throw new Error(`StockOpnameItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Me,e,a);return this.changeQueue.enqueue({type:"update",model:Me,record:o}),this.context.logActivity("UpdateStockOpnameItem",{id:e}),o}async getStockOpnameItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Me,{...e,filters:i})}async getStockOpnameItem(e,t){return(t||this.dbAdapter).get(Me,e)}async deleteStockOpnameItem(e,t){return await(t||this.dbAdapter).delete(Me,e),this.changeQueue.enqueue({type:"delete",model:Me,record:{id:e}}),this.context.logActivity("DeleteStockOpnameItem",{id:e}),{id:e,queued:!0}}async duplicateStockOpnameItem(e,t){let r=await this.getStockOpnameItem(e,t);if(!r)throw new Error(`StockOpnameItem with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Me,a);return this.changeQueue.enqueue({type:"create",model:Me,record:a}),this.context.logActivity("DuplicateStockOpnameItem",{originalId:e,newId:n}),o}};var it="stock_adjustments";var dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addStockAdjustment(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(it,i);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("AddStockAdjustment",{id:r}),a}async updateStockAdjustment(e,t,r){let n=await(r||this.dbAdapter).get(it,e);if(!n)throw new Error(`StockAdjustment with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(it,e,a);return this.changeQueue.enqueue({type:"update",model:it,record:o}),this.context.logActivity("UpdateStockAdjustment",{id:e}),o}async getStockAdjustments(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(it,{...e,filters:i})}async getStockAdjustment(e,t){return(t||this.dbAdapter).get(it,e)}async deleteStockAdjustment(e,t){return await(t||this.dbAdapter).delete(it,e),this.changeQueue.enqueue({type:"delete",model:it,record:{id:e}}),this.context.logActivity("DeleteStockAdjustment",{id:e}),{id:e,queued:!0}}async duplicateStockAdjustment(e,t){let r=await this.getStockAdjustment(e,t);if(!r)throw new Error(`StockAdjustment with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(it,a);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("DuplicateStockAdjustment",{originalId:e,newId:n}),o}};var at="report_schedules";var lr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addReportSchedule(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(at,i);return this.changeQueue.enqueue({type:"create",model:at,record:a}),this.context.logActivity("AddReportSchedule",{id:r}),a}async updateReportSchedule(e,t,r){let n=await(r||this.dbAdapter).get(at,e);if(!n)throw new Error(`ReportSchedule with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(at,e,a);return this.changeQueue.enqueue({type:"update",model:at,record:o}),this.context.logActivity("UpdateReportSchedule",{id:e}),o}async getReportSchedules(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(at,{...e,filters:i})}async getReportSchedule(e,t){return(t||this.dbAdapter).get(at,e)}async deleteReportSchedule(e,t){return await(t||this.dbAdapter).delete(at,e),this.changeQueue.enqueue({type:"delete",model:at,record:{id:e}}),this.context.logActivity("DeleteReportSchedule",{id:e}),{id:e,queued:!0}}async duplicateReportSchedule(e,t){let r=await this.getReportSchedule(e,t);if(!r)throw new Error(`ReportSchedule with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(at,a);return this.changeQueue.enqueue({type:"create",model:at,record:a}),this.context.logActivity("DuplicateReportSchedule",{originalId:e,newId:n}),o}};var pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addFinancialSetting(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ve,i);return this.changeQueue.enqueue({type:"create",model:Ve,record:a}),this.context.logActivity("AddFinancialSetting",{id:r}),a}async updateFinancialSetting(e,t,r){let n=await(r||this.dbAdapter).get(Ve,e);if(!n)throw new Error(`FinancialSetting with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ve,e,a);return this.changeQueue.enqueue({type:"update",model:Ve,record:o}),this.context.logActivity("UpdateFinancialSetting",{id:e}),o}async getFinancialSettings(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ve,{...e,filters:i})}async getFinancialSetting(e,t){return(t||this.dbAdapter).get(Ve,e)}async deleteFinancialSetting(e,t){return await(t||this.dbAdapter).delete(Ve,e),this.changeQueue.enqueue({type:"delete",model:Ve,record:{id:e}}),this.context.logActivity("DeleteFinancialSetting",{id:e}),{id:e,queued:!0}}async duplicateFinancialSetting(e,t){let r=await this.getFinancialSetting(e,t);if(!r)throw new Error(`FinancialSetting with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ve,a);return this.changeQueue.enqueue({type:"create",model:Ve,record:a}),this.context.logActivity("DuplicateFinancialSetting",{originalId:e,newId:n}),o}};var ot="expenses";var mr=class{constructor(e,t={}){this.context=e;this._runtimeOptions=t;var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=H(e)}async emitFinanceProjection(e){var r,n,i,a;if(!this._runtimeOptions.financeProjectionSink||!this._runtimeOptions.expenseAccountMapping)return;let t=String(((r=this.context.session)==null?void 0:r.tenantId)||"").trim();if(!t){(i=(n=this._runtimeOptions.logger)==null?void 0:n.logInfo)==null||i.call(n,"[ofpos] expense finance projection skipped: tenantId unavailable");return}await this._runtimeOptions.financeProjectionSink(hi({expense:e,tenantId:t,branchId:((a=this.context.config)==null?void 0:a.branchId)||void 0,scopedAccountMapping:this._runtimeOptions.expenseAccountMapping}))}async addExpense(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ot,i);return this.changeQueue.enqueue({type:"create",model:ot,record:a}),await this.emitFinanceProjection(a),this.context.logActivity("AddExpense",{id:r}),a}async updateExpense(e,t,r){let n=await(r||this.dbAdapter).get(ot,e);if(!n)throw new Error(`Expense with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ot,e,a);return this.changeQueue.enqueue({type:"update",model:ot,record:o}),this.context.logActivity("UpdateExpense",{id:e}),o}async getExpenses(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ot,{...e,filters:i})}async getExpense(e,t){return(t||this.dbAdapter).get(ot,e)}async deleteExpense(e,t){return await(t||this.dbAdapter).delete(ot,e),this.changeQueue.enqueue({type:"delete",model:ot,record:{id:e}}),this.context.logActivity("DeleteExpense",{id:e}),{id:e,queued:!0}}async duplicateExpense(e,t){let r=await this.getExpense(e,t);if(!r)throw new Error(`Expense with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ot,a);return this.changeQueue.enqueue({type:"create",model:ot,record:a}),this.context.logActivity("DuplicateExpense",{originalId:e,newId:n}),o}};var hr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addReceivable(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(fe,i);return t||this.changeQueue.enqueue({type:"create",model:fe,record:a}),this.context.logActivity("AddReceivable",{id:r}),a}async updateReceivable(e,t,r){let n=await(r||this.dbAdapter).get(fe,e);if(!n)throw new Error(`Receivable with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(fe,e,a);return r||this.changeQueue.enqueue({type:"update",model:fe,record:o}),this.context.logActivity("UpdateReceivable",{id:e}),o}async getReceivables(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(fe,{...e,filters:i})}async getReceivable(e,t){return(t||this.dbAdapter).get(fe,e)}async deleteReceivable(e,t){return await(t||this.dbAdapter).delete(fe,e),t||this.changeQueue.enqueue({type:"delete",model:fe,record:{id:e}}),this.context.logActivity("DeleteReceivable",{id:e}),{id:e,queued:!0}}async duplicateReceivable(e,t){let r=await this.getReceivable(e,t);if(!r)throw new Error(`Receivable with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(fe,a);return t||this.changeQueue.enqueue({type:"create",model:fe,record:a}),this.context.logActivity("DuplicateReceivable",{originalId:e,newId:n}),o}};var fr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(e)}async addPayable(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ye,i);return t||this.changeQueue.enqueue({type:"create",model:ye,record:a}),this.context.logActivity("AddPayable",{id:r}),a}async updatePayable(e,t,r){let n=await(r||this.dbAdapter).get(ye,e);if(!n)throw new Error(`Payable with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ye,e,a);return r||this.changeQueue.enqueue({type:"update",model:ye,record:o}),this.context.logActivity("UpdatePayable",{id:e}),o}async getPayables(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ye,{...e,filters:i})}async getPayable(e,t){return(t||this.dbAdapter).get(ye,e)}async deletePayable(e,t){return await(t||this.dbAdapter).delete(ye,e),t||this.changeQueue.enqueue({type:"delete",model:ye,record:{id:e}}),this.context.logActivity("DeletePayable",{id:e}),{id:e,queued:!0}}async duplicatePayable(e,t){let r=await this.getPayable(e,t);if(!r)throw new Error(`Payable with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ye,a);return t||this.changeQueue.enqueue({type:"create",model:ye,record:a}),this.context.logActivity("DuplicatePayable",{originalId:e,newId:n}),o}async updatePaidAmount(e,t){var s;let r=(s=this.context.registry)==null?void 0:s.loggerAdapter,n=await this.dbAdapter.get(ye,e);if(!n)throw r.logError("Payable not found",{payableId:e}),new Error(`Payable ${e} not found`);let i=(n.paidAmount||0)+t,a=i>=n.amount?"paid":"partial",o={paidAmount:i,status:a,version:Date.now(),lastModified:new Date().toISOString()};await this.dbAdapter.update(ye,e,o),this.changeQueue.enqueue({type:"update",model:ye,record:{id:e,...o}}),this.context.logActivity("updatePaidAmount",{payableId:e,paidAmount:i,status:a}),r.logInfo("Payable updated",{payableId:e,paidAmount:i,status:a})}};var Qe="settlements";var gr=class{constructor(e,t={}){this.context=e;this.runtimeOptions=t;var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=H(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}async emitFinanceProjection(e){var r,n;if(!this.runtimeOptions.financeProjectionSink||!this.runtimeOptions.settlementAccountMapping)return;let t=String(((r=this.context.session)==null?void 0:r.tenantId)||"").trim();t&&await this.runtimeOptions.financeProjectionSink(fi({settlement:e,tenantId:t,branchId:((n=this.context.config)==null?void 0:n.branchId)||void 0,scopedAccountMapping:this.runtimeOptions.settlementAccountMapping}))}async addSettlement(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Qe,i);return this.changeQueue.enqueue({type:"create",model:Qe,record:a}),this.context.logActivity("AddSettlement",{id:r}),a}async updateSettlement(e,t,r){let n=await(r||this.dbAdapter).get(Qe,e);if(!n)throw new Error(`Settlement with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Qe,e,a);return this.changeQueue.enqueue({type:"update",model:Qe,record:o}),this.context.logActivity("UpdateSettlement",{id:e}),o}async getSettlements(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Qe,{...e,filters:i})}async getSettlement(e,t){return(t||this.dbAdapter).get(Qe,e)}async deleteSettlement(e,t){return await(t||this.dbAdapter).delete(Qe,e),this.changeQueue.enqueue({type:"delete",model:Qe,record:{id:e}}),this.context.logActivity("DeleteSettlement",{id:e}),{id:e,queued:!0}}async duplicateSettlement(e,t){let r=await this.getSettlement(e,t);if(!r)throw new Error(`Settlement with ID ${e} not found.`);let n=D(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Qe,a);return this.changeQueue.enqueue({type:"create",model:Qe,record:a}),this.context.logActivity("DuplicateSettlement",{originalId:e,newId:n}),o}async createSettlement(e){var s;let t=(s=this.context.registry)==null?void 0:s.loggerAdapter,r=new Date().toISOString(),n=String(e.idempotencyKey||"").trim(),i=!!String(e.receivableId||"").trim(),a=!!String(e.payableId||"").trim();if(e.amount<=0)throw new Error("Settlement amount must be positive");if(i===a)throw new Error("Settlement must reference exactly one of receivableId or payableId");let o=await this.runInTransaction(async d=>{if(n){let l=await d.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:"idempotency_keys"},{field:"recordId",operator:"=",value:n},{field:"action",operator:"=",value:"settlement_create"}]},sort:[{field:"timestamp",direction:"desc"}],limit:1});if(l.length){let m=l[0].changes||{},f=String(m.settlementId||"").trim();if(f){let y=await d.get(Qe,f);if(y)return y}}}if(e.receivableId){let l=await d.get(fe,e.receivableId);if(!l||l.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let m=l.amount-l.paidAmount;if(e.amount>m)throw new Error("Settlement amount exceeds remaining receivable amount")}if(e.payableId){let l=await d.get(ye,e.payableId);if(!l||l.deleted)throw new Error(`Payable ${e.payableId} not found`);let m=l.amount-l.paidAmount;if(e.amount>m)throw new Error("Settlement amount exceeds remaining payable amount")}let c={id:D(),receivableId:e.receivableId||null,payableId:e.payableId||null,amount:e.amount,method:e.method,date:e.date,reference:e.reference||null,userId:e.userId,version:Date.now(),lastModified:r,deleted:!1},p=await d.create(Qe,c);if(e.receivableId){let l=await d.get(fe,e.receivableId);if(!l||l.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let m=l.paidAmount+e.amount,f={...l,paidAmount:m,status:m>=l.amount?"paid":"partial",version:Date.now(),lastModified:r};await d.update(fe,f.id,f)}if(e.payableId){let l=await d.get(ye,e.payableId);if(!l||l.deleted)throw new Error(`Payable ${e.payableId} not found`);let m=l.paidAmount+e.amount,f={...l,paidAmount:m,status:m>=l.amount?"paid":"partial",version:Date.now(),lastModified:r};await d.update(ye,f.id,f)}return n&&await d.create(ie,{id:D(),tableName:"idempotency_keys",recordId:n,action:"settlement_create",changes:{settlementId:p.id},userId:String(e.userId||"").trim()||null,timestamp:r}),p});if(this.changeQueue.enqueue({type:"create",model:Qe,record:o}),e.receivableId){let d=await this.dbAdapter.get(fe,e.receivableId);d&&this.changeQueue.enqueue({type:"update",model:fe,record:d})}if(e.payableId){let d=await this.dbAdapter.get(ye,e.payableId);d&&this.changeQueue.enqueue({type:"update",model:ye,record:d})}return this.context.logActivity("createSettlement",{id:o.id}),t.logInfo("Settlement created",{id:o.id}),await this.emitFinanceProjection({id:o.id,amount:o.amount,method:o.method,date:o.date,receivableId:o.receivableId,payableId:o.payableId}),o}};var yr=class{constructor(e){this.context=e;this.stockCache=new Map;this.isRebuilding=!1;this.onStockChanged=e=>{this.invalidateProductStock(e.productId)};this.onStockRebuild=()=>{this.rebuildStockCache()};var t;this.adapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.changeQueue=H(this.context),Le.on("stock:changed",this.onStockChanged),Le.on("stock:rebuild",this.onStockRebuild)}async getStock(e){if(this.stockCache.has(e))return this.stockCache.get(e);let t=await this.computeStockFromLogs(e);return this.stockCache.set(e,t),t}async updateStock(e,t,r,n,i,a){var p,l;let o=a||this.adapter;if(t<0){let m=(p=this.context.domainServices)==null?void 0:p.bom;if(m&&(await m.getBomsByParentItemId(e)).length>0){let y=await m.expandBom(e),b=Math.abs(t);for(let h of y){let g=h.quantity*b;if(await this.getStock(h.componentItemId)<g)throw new Error(`Insufficient component ${h.componentItemId}`)}for(let h of y)await this.updateStock(h.componentItemId,-h.quantity*b,r,n,i,o);return}}let s;if(this.stockCache.has(e)?s=this.stockCache.get(e):(s=await this.computeStockFromLogs(e),this.stockCache.set(e,s)),t<0&&s+t<0)throw new Error(`Insufficient stock for product ${e}`);let d={id:D(),productId:e,change:t,reason:r,referenceType:n,referenceId:i,userId:((l=this.context.session)==null?void 0:l.userId)||"",timestamp:new Date().toISOString()};await o.create(Oe,d),this.changeQueue.enqueue({type:"create",model:Oe,record:d});let c=Math.max(0,s+t);this.stockCache.set(e,c)}async rebuildStockCache(){if(!this.isRebuilding){this.isRebuilding=!0;try{let e=await this.adapter.query(Oe,{aggregates:[{function:"SUM",field:"change",as:"total"}],groupBy:[{field:"productId"}]});this.stockCache.clear();for(let{productId:t,total:r}of e)this.stockCache.set(t,r!=null?r:0);console.info(`InventoryService stock cache rebuilt: ${this.stockCache.size} products`),Le.emit("stockCache:rebuilt")}finally{this.isRebuilding=!1}}}invalidateProductStock(e){e&&this.stockCache.delete(e)}invalidateProductsStock(e){for(let t of e)this.invalidateProductStock(t)}clearStockCache(){this.stockCache.clear()}async computeStockFromLogs(e){var r;let[t]=await this.adapter.query(Oe,{aggregates:[{function:"SUM",field:"change",as:"total"}],filters:{productId:e}});return(r=t==null?void 0:t.total)!=null?r:0}async getLowStockProducts(e=10,t=50){let r=[];for(let[s,d]of this.stockCache.entries())d<e&&r.push({productId:s,stock:d});r.sort((s,d)=>s.stock-d.stock);let n=r.slice(0,t),i=n.map(s=>s.productId);if(i.length===0)return[];let a=await this.adapter.query(ue,{filters:{and:[{field:"id",operator:"IN",value:i},{deleted:!1}]},include:["baseUom","category"]}),o=new Map(a.map(s=>[s.id,s]));return n.map(s=>({productId:s.productId,stock:s.stock,product:o.get(s.productId)}))}};var Ui={categories:{parentId:{table:"categories",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},products:{categoryId:{table:"categories",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},baseUomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},boms:{parentItemId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},componentItemId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},customers:{groupId:{table:"customer_groups",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},loyalty_accounts:{customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"}},loyalty_ledgers:{customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"}},histories:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},orders:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},parentOrderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},order_items:{orderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},kitchen_tickets:{orderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},createdBy:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},kitchen_ticket_items:{ticketId:{table:"kitchen_tickets",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},orderItemId:{table:"order_items",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},price_tiers:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},uom:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},customerGroupId:{table:"customer_groups",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},returns:{saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},return_items:{returnId:{table:"returns",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},sales:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},sourceOrderId:{table:"orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},sale_items:{saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},shifts:{cashierId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},transactions:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},users:{role:{table:"roles",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchase_orders:{supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchase_order_items:{purchaseOrderId:{table:"purchase_orders",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchases:{supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseOrderId:{table:"purchase_orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},purchase_items:{purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},purchaseOrderItemId:{table:"purchase_order_items",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},uomId:{table:"uoms",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},inventory_lots:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},purchaseItemId:{table:"purchase_items",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},purchaseOrderId:{table:"purchase_orders",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseOrderItemId:{table:"purchase_order_items",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},inventory_logs:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},price_histories:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},stock_opnames:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},stock_opname_items:{stockOpnameId:{table:"stock_opnames",foreignKey:"id",type:"many-to-one",onDelete:"CASCADE"},productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},stock_adjustments:{productId:{table:"products",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},expenses:{userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},receivables:{customerId:{table:"customers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},saleId:{table:"sales",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},payables:{supplierId:{table:"suppliers",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},purchaseId:{table:"purchases",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}},settlements:{receivableId:{table:"receivables",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},payableId:{table:"payables",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"},userId:{table:"users",foreignKey:"id",type:"many-to-one",onDelete:"SET NULL"}}},Hi={transactions:[{typeField:"referenceType",idField:"referenceId",types:{sale:{table:"sales",foreignKey:"id"},purchase:{table:"purchases",foreignKey:"id"},sale_return:{table:"returns",foreignKey:"id"},purchase_return:{table:"returns",foreignKey:"id"},receivable_payment:{table:"receivables",foreignKey:"id"},payable_payment:{table:"payables",foreignKey:"id"},cash_adjustment:{table:"stock_adjustments",foreignKey:"id"},expense:{table:"expenses",foreignKey:"id"}}}],inventory_logs:[{typeField:"referenceType",idField:"referenceId",types:{sale:{table:"sales",foreignKey:"id"},purchase:{table:"purchases",foreignKey:"id"},sale_return:{table:"returns",foreignKey:"id"},purchase_return:{table:"returns",foreignKey:"id"},stock_opname:{table:"stock_opnames",foreignKey:"id"},stock_adjustment:{table:"stock_adjustments",foreignKey:"id"}}}]};var Fo=[{name:"boms",columns:[{name:"id",type:"string"},{name:"parentItemId",type:"string",isOptional:!0,isPrimarySearchKey:!0},{name:"componentItemId",type:"string",isOptional:!0,isPrimarySearchKey:!0},{name:"quantity",type:"number"},{name:"uomId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"categories",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"parentId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"customers",columns:[{name:"id",type:"string"},{name:"name",type:"string",isFullTextSearchable:!0},{name:"phone",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"email",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"groupId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"customer_groups",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"loyalty_accounts",columns:[{name:"id",type:"string"},{name:"customerId",type:"string",isIndexed:!0},{name:"pointsBalance",type:"number"},{name:"totalEarned",type:"number"},{name:"totalRedeemed",type:"number"},{name:"totalExpired",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"loyalty_ledgers",columns:[{name:"id",type:"string"},{name:"customerId",type:"string",isIndexed:!0},{name:"entryType",type:"string",enum:["earn","redeem","expire","adjustment"]},{name:"points",type:"number"},{name:"availablePoints",type:"number"},{name:"expiresAt",type:"string",isOptional:!0,isIndexed:!0},{name:"consumedAt",type:"string",isOptional:!0,isIndexed:!0},{name:"referenceType",type:"string",isOptional:!0},{name:"referenceId",type:"string",isOptional:!0},{name:"note",type:"string",isOptional:!0},{name:"date",type:"string",isIndexed:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"histories",columns:[{name:"id",type:"string"},{name:"tableName",type:"string"},{name:"recordId",type:"string"},{name:"action",type:"string"},{name:"changes",type:"json"},{name:"userId",type:"string",isOptional:!0},{name:"timestamp",type:"string"}],skipMetadataColumns:!0},{name:"orders",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"customerId",type:"string",isOptional:!0},{name:"parentOrderId",type:"string",isOptional:!0},{name:"discountCode",type:"string",isOptional:!0},{name:"channel",type:"string",enum:["dine_in","takeaway","delivery","preorder"],isOptional:!0},{name:"status",type:"string"},{name:"saleId",type:"string",isOptional:!0},{name:"scheduledAt",type:"string",isOptional:!0},{name:"deliveryAddress",type:"string",isOptional:!0},{name:"tableNumber",type:"string",isOptional:!0,isIndexed:!0},{name:"serviceChargeAmount",type:"number",isOptional:!0},{name:"gratuityAmount",type:"number",isOptional:!0},{name:"date",type:"string"},{name:"total",type:"number"},{name:"ppn",type:"number"},{name:"pph",type:"number"},{name:"finalTotal",type:"number"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"order_items",columns:[{name:"id",type:"string"},{name:"orderId",type:"string"},{name:"productId",type:"string"},{name:"quantity",type:"number"},{name:"uomId",type:"string",isOptional:!0},{name:"unitPrice",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"kitchen_tickets",columns:[{name:"id",type:"string"},{name:"orderId",type:"string"},{name:"station",type:"string"},{name:"status",type:"string",enum:["queued","in_progress","ready","served","canceled"]},{name:"note",type:"string",isOptional:!0},{name:"createdBy",type:"string",isOptional:!0},{name:"createdAt",type:"string",isIndexed:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"kitchen_ticket_items",columns:[{name:"id",type:"string"},{name:"ticketId",type:"string"},{name:"orderItemId",type:"string"},{name:"course",type:"string",isOptional:!0},{name:"status",type:"string",enum:["queued","in_progress","ready","served","canceled"]},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"price_tiers",columns:[{name:"id",type:"string"},{name:"tierLevel",type:"number"},{name:"price",type:"number"},{name:"productId",type:"string"},{name:"uom",type:"string",isOptional:!0},{name:"customerGroupId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"products",columns:[{name:"id",type:"string"},{name:"name",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"description",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"barcode",type:"string",isOptional:!0,isFullTextSearchable:!0,isPrimarySearchKey:!0},{name:"qrCode",type:"string",isOptional:!0,isIndexed:!0,isFullTextSearchable:!0,isPrimarySearchKey:!0},{name:"price",type:"number"},{name:"cost",type:"number"},{name:"categoryId",type:"string"},{name:"baseUomId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"promotions",columns:[{name:"id",type:"string"},{name:"code",type:"string"},{name:"type",type:"string"},{name:"value",type:"number"},{name:"name",type:"string",isOptional:!0},{name:"description",type:"string",isOptional:!0},{name:"targetType",type:"string"},{name:"targetIds",type:"string[]"},{name:"expiresAt",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"returns",notes:`
2
2
  referenceType | Arah Stok | Arah Kas | Catatan
3
3
  -----------------+----------------+----------------------+-----------------------
4
4
  sale | - (out) | + (in) | Penjualan
@@ -13,6 +13,6 @@ referenceType untuk inventory_logs:
13
13
  'reason': 'opname_adjustment'
14
14
  'referenceType': 'stock_opname'
15
15
  'referenceId': stockOpnameId
16
- `,columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"date",type:"string"},{name:"status",type:"string",enum:["pending","completed","cancelled"]},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"stock_opname_items",columns:[{name:"id",type:"string"},{name:"stockOpnameId",type:"string"},{name:"productId",type:"string"},{name:"systemStock",type:"number",notes:"stok sistem (base UOM)"},{name:"physicalStock",type:"number",notes:"hasil hitung fisik (base UOM)"},{name:"difference",type:"number",notes:"physical - system"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"stock_adjustments",columns:[{name:"id",type:"string"},{name:"productId",type:"string"},{name:"change",type:"number"},{name:"reasonType",type:"string"},{name:"note",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"report_schedules",columns:[{name:"id",type:"string"},{name:"reportType",type:"string"},{name:"frequency",type:"string"},{name:"recipients",type:"string[]"},{name:"lastRunAt",type:"string",isOptional:!0},{name:"nextRunAt",type:"string"},{name:"isActive",type:"boolean"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"financial_settings",columns:[{name:"id",type:"string"},{name:"costingMethod",type:"string"},{name:"defaultExpenseAccount",type:"string",isOptional:!0},{name:"fiscalYearStart",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string"}]},{name:"expenses",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"amount",type:"number"},{name:"category",type:"string"},{name:"description",type:"string",isOptional:!0},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"receivables",columns:[{name:"id",type:"string"},{name:"customerId",type:"string"},{name:"saleId",type:"string"},{name:"amount",type:"number"},{name:"dueDate",type:"string"},{name:"status",type:"string"},{name:"paidAmount",type:"number"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"payables",columns:[{name:"id",type:"string"},{name:"supplierId",type:"string"},{name:"purchaseId",type:"string"},{name:"amount",type:"number"},{name:"dueDate",type:"string"},{name:"status",type:"string"},{name:"paidAmount",type:"number"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"settlements",columns:[{name:"id",type:"string"},{name:"receivableId",type:"string",isOptional:!0},{name:"payableId",type:"string",isOptional:!0},{name:"amount",type:"number"},{name:"method",type:"string"},{name:"date",type:"string"},{name:"reference",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]}],vo=[{name:"branchId",type:"string",isOptional:!0,isIndexed:!0},{name:"tenantId",type:"string",isOptional:!0,isIndexed:!0}];function bo(h){let e=[...h.columns];for(let t of vo)e.some(r=>r.name===t.name)||e.push({...t});return{...h,columns:e}}var xt=yo.map(bo),xo=Object.freeze(xt.map(h=>h.name));for(let[h,e]of Object.entries(_i)){let t=xt.find(r=>r.name===h);for(let[r,n]of Object.entries(e)){let i=t==null?void 0:t.columns.find(a=>a.name===r);i&&(i.relation=n)}}for(let[h,e]of Object.entries(Ti)){let t=xt.find(r=>r.name===h);t.polymorphic=e}var sn=1,un=[1,0];function Ao(){return{currentVersion:1,compatibleServerVersions:[...un]}}function ui(h,e){return e.includes(h)}var gr=(h,e)=>{var i;let t=e.config.paymentSigningKey;if(!t)return"";let r=(i=e.registry)==null?void 0:i.checksumAdapter;if(!r)throw new Error("ChecksumAdapter is not initialized in AdapterRegistry");let n=r.compute({algorithm:"hmac-sha256",payload:h,secret:t});if(n&&typeof n.then=="function")throw new Error("Shared-core checksum path requires synchronous ChecksumAdapter.compute");return String(n||"")};var yr=class{constructor(e){this.context=e;var t,r,n;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.exportAdapter=(r=this.context.registry)==null?void 0:r.exportAdapter,this.inventoryService=(n=this.context.domainServices)==null?void 0:n.inventory}toCsv(e,t){let r=i=>`"${i.replace(/"/g,'""')}"`,n=[e.map(r).join(",")];return t.forEach(i=>n.push(i.map(r).join(","))),n.join(`
17
- `)}async exportSalesReportCSV(e){let t=this.dbAdapter,r=e!=null&&e.date?{field:"date",value:e.date}:e!=null&&e.from&&(e!=null&&e.to)?{and:[{field:"date",operator:">=",value:e.from},{field:"date",operator:"<=",value:e.to}]}:void 0,n=await t.query("orders",{filters:r}),i=["Date","Total","PPN","PPH","FinalTotal"],a=n.map(u=>[u.date,u.total.toString(),u.ppn.toString(),u.pph.toString(),u.finalTotal.toString()]),o=this.toCsv(i,a),s=this.exportAdapter,c=s.getDocumentPath("sales_report.csv");await s.writeFile(c,o),await s.share(c)}async exportStockCSV(){let t=await this.dbAdapter.query("products"),r=["ID","Name","Stock"],n=await Promise.all(t.map(c=>this.inventoryService.getStock(c.id))),i=t.map((c,u)=>{var l;return[c.id,(l=c.name)!=null?l:"",n[u].toString()]}),a=this.toCsv(r,i),o=this.exportAdapter,s=o.getDocumentPath("stock_report.csv");await o.writeFile(s,a),await o.share(s)}async exportCustomersCSV(){let t=await this.dbAdapter.query("customers"),r=["ID","Name","Phone","Email"],n=t.map(s=>{var c,u;return[s.id,s.name,(c=s.phone)!=null?c:"",(u=s.email)!=null?u:""]}),i=this.toCsv(r,n),a=this.exportAdapter,o=a.getDocumentPath("customers_report.csv");await a.writeFile(o,i),await a.share(o)}async createLocalBackupSnapshot(){let e={};for(let t of xt.map(r=>r.name))e[t]=await this.dbAdapter.query(t,{});return JSON.stringify({format:"ofpos-local-backup-v1",createdAt:new Date().toISOString(),deploymentMode:this.context.config.deploymentMode,tables:e})}async restoreLocalBackupSnapshot(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Invalid backup snapshot JSON")}if((t==null?void 0:t.format)!=="ofpos-local-backup-v1"||!(t!=null&&t.tables)||typeof t.tables!="object")throw new Error("Invalid backup snapshot format");let r=xt.map(n=>n.name);await this.dbAdapter.transaction(async n=>{for(let i of[...r].reverse()){let a=await n.query(i,{});for(let o of a)o!=null&&o.id&&await n.delete(i,o.id)}for(let i of r){let a=Array.isArray(t.tables[i])?t.tables[i]:[];for(let o of a)await n.create(i,o)}})}async createTaxReadyExportContract(e={}){var m,f,y,v;let t=await this.dbAdapter.query("sales",{filters:{deleted:!1}}),r=await this.dbAdapter.query("returns",{filters:{deleted:!1}}),n=await this.dbAdapter.query("purchases",{filters:{deleted:!1}}),i=await this.dbAdapter.query("settlements",{filters:{deleted:!1}}),a=t.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),o=r.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),s=n.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),c=i.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),u={sales:a.map(p=>({id:p.id,date:p.date,total:p.total,discount:p.discount,ppn:p.ppn,pph:p.pph,finalTotal:p.finalTotal,status:p.status,customerId:p.customerId,userId:p.userId})),returns:o.map(p=>({id:p.id,date:p.date,type:p.type,refundAmount:p.refundAmount,actualRefund:p.actualRefund,status:p.status,saleId:p.saleId,purchaseId:p.purchaseId,userId:p.userId})),purchases:s.map(p=>({id:p.id,date:p.date,total:p.total,supplierId:p.supplierId,userId:p.userId,purchaseOrderId:p.purchaseOrderId})),payments:c.map(p=>({id:p.id,date:p.date,amount:p.amount,method:p.method,direction:p.receivableId?"in":"out",receivableId:p.receivableId,payableId:p.payableId,reference:p.reference,userId:p.userId}))},l={salesFinalTotal:u.sales.reduce((p,g)=>p+g.finalTotal,0),salesPpnTotal:u.sales.reduce((p,g)=>p+g.ppn,0),salesPphTotal:u.sales.reduce((p,g)=>p+g.pph,0),returnsActualRefundTotal:u.returns.reduce((p,g)=>p+g.actualRefund,0),purchasesTotal:u.purchases.reduce((p,g)=>p+g.total,0),paymentInTotal:u.payments.filter(p=>p.direction==="in").reduce((p,g)=>p+g.amount,0),paymentOutTotal:u.payments.filter(p=>p.direction==="out").reduce((p,g)=>p+g.amount,0)},d={contractVersion:"tex-v1",generatedAt:new Date().toISOString(),sourceVersion:`sync-protocol-v${1}`,period:{from:(m=e.from)!=null?m:null,to:(f=e.to)!=null?f:null,label:(y=e.periodLabel)!=null?y:null},currency:{baseCurrencyCode:(v=e.baseCurrencyCode)!=null?v:"IDR"},records:u,summary:l};return e.compatibilityTarget==="N-1"?{contractVersion:"tex-v0",generatedAt:d.generatedAt,sourceVersion:d.sourceVersion,period:d.period,currency:d.currency,records:{sales:d.records.sales.map(g=>({id:g.id,date:g.date,total:g.total,discount:g.discount,taxTotal:g.ppn+g.pph,finalTotal:g.finalTotal,status:g.status,customerId:g.customerId,userId:g.userId})),returns:d.records.returns,purchases:d.records.purchases,payments:d.records.payments.map(g=>({id:g.id,date:g.date,amount:g.amount,method:g.method,flow:g.direction==="in"?"receipt":"disbursement",receivableId:g.receivableId,payableId:g.payableId,reference:g.reference,userId:g.userId}))},summary:{salesFinalTotal:d.summary.salesFinalTotal,salesTaxTotal:d.summary.salesPpnTotal+d.summary.salesPphTotal,returnsActualRefundTotal:d.summary.returnsActualRefundTotal,purchasesTotal:d.summary.purchasesTotal,paymentInTotal:d.summary.paymentInTotal,paymentOutTotal:d.summary.paymentOutTotal}}:d}async createTaxReadyExportCsvBundle(e={}){let t=await this.createTaxReadyExportContract(e),r=this.normalizeTaxReadyExportContract(t),n={};return n["tax_ready_manifest.json"]=JSON.stringify({contractVersion:t.contractVersion,generatedAt:t.generatedAt,sourceVersion:t.sourceVersion,period:t.period,currency:t.currency,summary:r.summary}),n["tax_ready_sales.csv"]=this.toCsv(["id","date","total","discount","ppn","pph","finalTotal","status","customerId","userId"],r.records.sales.map(i=>{var a;return[i.id,i.date,i.total.toString(),i.discount.toString(),i.ppn.toString(),i.pph.toString(),i.finalTotal.toString(),i.status,(a=i.customerId)!=null?a:"",i.userId]})),n["tax_ready_returns.csv"]=this.toCsv(["id","date","type","refundAmount","actualRefund","status","saleId","purchaseId","userId"],r.records.returns.map(i=>{var a,o;return[i.id,i.date,i.type,i.refundAmount.toString(),i.actualRefund.toString(),i.status,(a=i.saleId)!=null?a:"",(o=i.purchaseId)!=null?o:"",i.userId]})),n["tax_ready_purchases.csv"]=this.toCsv(["id","date","total","supplierId","userId","purchaseOrderId"],r.records.purchases.map(i=>{var a;return[i.id,i.date,i.total.toString(),i.supplierId,i.userId,(a=i.purchaseOrderId)!=null?a:""]})),n["tax_ready_payments.csv"]=this.toCsv(["id","date","amount","method","direction","receivableId","payableId","reference","userId"],r.records.payments.map(i=>{var a,o,s;return[i.id,i.date,i.amount.toString(),i.method,i.direction,(a=i.receivableId)!=null?a:"",(o=i.payableId)!=null?o:"",(s=i.reference)!=null?s:"",i.userId]})),n}normalizeTaxReadyExportContract(e){return e.contractVersion==="tex-v1"?e:{contractVersion:"tex-v1",generatedAt:e.generatedAt,sourceVersion:e.sourceVersion,period:e.period,currency:e.currency,records:{sales:e.records.sales.map(t=>({id:t.id,date:t.date,total:t.total,discount:t.discount,ppn:t.taxTotal,pph:0,finalTotal:t.finalTotal,status:t.status,customerId:t.customerId,userId:t.userId})),returns:e.records.returns,purchases:e.records.purchases,payments:e.records.payments.map(t=>({id:t.id,date:t.date,amount:t.amount,method:t.method,direction:t.flow==="receipt"?"in":"out",receivableId:t.receivableId,payableId:t.payableId,reference:t.reference,userId:t.userId}))},summary:{salesFinalTotal:e.summary.salesFinalTotal,salesPpnTotal:e.summary.salesTaxTotal,salesPphTotal:0,returnsActualRefundTotal:e.summary.returnsActualRefundTotal,purchasesTotal:e.summary.purchasesTotal,paymentInTotal:e.summary.paymentInTotal,paymentOutTotal:e.summary.paymentOutTotal}}}async createFiscalArchiveSnapshot(e){let t=String(e.actorId||"").trim(),r=String(e.reason||"").trim();if(!t)throw new Error("Fiscal archive policy: actorId is required");if(!r)throw new Error("Fiscal archive policy: reason is required");let n=await this.createTaxReadyExportContract(e),i=this.normalizeTaxReadyExportContract(n),a=await this.createTaxReadyExportCsvBundle(e),o=P(),s=new Date().toISOString(),c=JSON.stringify({archiveId:o,generatedAt:s,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,period:n.period,currency:n.currency,summary:i.summary,actorId:t,reason:r}),u=gr(c,this.context),l={archiveId:o,generatedAt:s,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,period:n.period,currency:n.currency,summary:i.summary,checksum:u,actorId:t,reason:r};return await this.dbAdapter.create(ie,{id:P(),tableName:"fiscal_archives",recordId:o,action:"snapshot_created",changes:{period:n.period,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,fileNames:Object.keys(a),checksum:u,reason:r},userId:t,timestamp:s}),{archiveId:o,generatedAt:s,period:n.period,files:a,manifest:l}}isWithinPeriod(e,t,r){let n=new Date(e).getTime();if(!Number.isFinite(n))return!1;if(t){let i=new Date(t).getTime();if(Number.isFinite(i)&&n<i)return!1}if(r){let i=new Date(r).getTime();if(Number.isFinite(i)&&n>i)return!1}return!0}};var vr=class{constructor(e){this.context=e;var t,r,n,i;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.taxService=(r=this.context.domainServices)==null?void 0:r.tax,this.uomService=(n=this.context.domainServices)==null?void 0:n.uom,this.promotionService=(i=this.context.domainServices)==null?void 0:i.promotion}getRoundingIncrement(){let e=this.context.config.pricingRoundingIncrement;if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<=0?null:t}roundValue(e){let t=this.getRoundingIncrement();return t==null?e:Math.round(e/t)*t}normalizePrecision(e){let t=Number(e.toFixed(10)),r=Math.round(t);return Math.abs(t-r)<1e-9?r:t}normalizeDiscountCodes(e){return e?Array.isArray(e)?e.map(t=>String(t||"").trim()).filter(Boolean):String(e).split(",").map(t=>t.trim()).filter(Boolean):[]}async getTieredPrice(e,t,r,n){let i=this.dbAdapter,a={and:[{field:"productId",value:e},...r?[{field:"customerGroupId",value:r}]:[],...n?[{field:"uom",value:n}]:[]]},s=await i.query(He,{filters:a});s.sort((m,f)=>{let y=m.customerGroupId===r?0:1,v=f.customerGroupId===r?0:1;return y!==v?y-v:f.tierLevel-m.tierLevel});let c=s.find(m=>t>=m.tierLevel),u=await i.get(ce,e);if(!u)throw new Error(`Product with id ${e} not found`);let l=c?c.price:u.price,d=l;if(!c&&n){let m=u.baseUomId;if(m&&m!==n){let f=await this.uomService.getUom(m),y=await this.uomService.getUom(n);f&&y&&(d=this.uomService.convertUnitPrice(l,f,y))}}return this.context.config.pricingRoundingScope==="line"&&(d=this.roundValue(d)),this.context.logActivity("TieredPrice",{productId:e,quantity:t,uom:n,price:d}),d}async applyTieredPricing(e,t){return await Promise.all(e.map(async n=>({...n,unitPrice:await this.getTieredPrice(n.productId,n.quantity,t,n.uomId)})))}async calculatePromotionDiscount(e,t){var y;let r=((y=this.context.domainServices)==null?void 0:y.promotion)||this.promotionService,n=this.normalizeDiscountCodes(t);if(!n.length)return 0;let i=await(r==null?void 0:r.getPromotions());if(!(i!=null&&i.length))return 0;let a=Date.now(),o=n.map(v=>i.find(p=>{if(p.code!==v)return!1;if(!p.expiresAt)return!0;let g=Date.parse(p.expiresAt);return Number.isNaN(g)?!1:g>=a})).filter(Boolean);if(!o.length)return 0;let s=this.roundValue(e.reduce((v,p)=>v+p.quantity*p.unitPrice,0)),c=this.context.config.allowPromotionStacking,u=this.context.config.promotionSelectionStrategy;if(!c){let v=u==="first_valid"?o[0]:o.map(g=>{let x=g.type==="percent"?s*g.value/100:g.value;return{promo:g,discount:Math.min(Math.max(0,x),s)}}).sort((g,x)=>x.discount-g.discount)[0].promo,p=v.type==="percent"?s*v.value/100:v.value;return this.roundValue(Math.min(Math.max(0,p),s))}let l=this.context.config.promotionStackingOrder,d=[...o];l==="percent_then_fixed"?d.sort((v,p)=>v.type===p.type?0:v.type==="percent"?-1:1):l==="fixed_then_percent"&&d.sort((v,p)=>v.type===p.type?0:v.type==="fixed"?-1:1);let m=s,f=0;for(let v of d){let p=v.type==="percent"?m*v.value/100:v.value,g=Math.min(Math.max(0,this.roundValue(p)),m);m-=g,f+=g}return this.roundValue(f)}async calculateOrderTotal(e,t,r){let n=await this.applyTieredPricing(e,r),i=this.roundValue(n.reduce((s,c)=>s+c.quantity*c.unitPrice,0)),a=this.roundValue(await this.calculatePromotionDiscount(n,t)),o=this.roundValue(Math.max(0,i-a));return{items:n,subTotal:i,discount:a,total:o}}async calculatePPN(e){var r;let t=((r=this.context.domainServices)==null?void 0:r.tax)||this.taxService;return this.roundValue(e*await t.getPpnRate())}async calculatePPH(e){var r;let t=((r=this.context.domainServices)==null?void 0:r.tax)||this.taxService;return this.roundValue(e*await t.getPphRate())}async calculateTaxBreakdown(e,t){var v;let r=(t==null?void 0:t.mode)==="inclusive"?"inclusive":"exclusive",n=((v=this.context.domainServices)==null?void 0:v.tax)||this.taxService,i=await n.getPpnRate(),a=await n.getPphRate(),o=Number(e||0),s=o;if(r==="inclusive"){let p=1+i+a;s=p>0?o/p:o}s=this.normalizePrecision(this.roundValue(s));let c=this.normalizePrecision(this.roundValue(s*i)),u=this.normalizePrecision(this.roundValue(s*a)),l=r==="exclusive"?this.normalizePrecision(this.roundValue(s+c+u)):this.normalizePrecision(this.roundValue(o)),d=this.normalizePrecision(this.roundValue(Number((t==null?void 0:t.correctionAmount)||0))),m=this.normalizePrecision(this.roundValue(l+d)),f=String((t==null?void 0:t.correctionReason)||"").trim(),y=d!==0?`[TAX_CORRECTION=${d>=0?"+":""}${d}${f?`|reason=${f}`:""}]`:null;return{mode:r,inputAmount:o,taxBase:s,ppn:c,pph:u,totalBeforeCorrection:l,correctionAmount:d,totalAfterCorrection:m,correctionNote:y}}async calculateReturnTaxImpact(e,t){let r=(t==null?void 0:t.mode)==="inclusive"?"inclusive":"exclusive",n=await this.calculateTaxBreakdown(e,{mode:r});return{mode:r,returnAmount:Number(e||0),taxBaseImpact:this.normalizePrecision(this.roundValue(-n.taxBase)),ppnImpact:this.normalizePrecision(this.roundValue(-n.ppn)),pphImpact:this.normalizePrecision(this.roundValue(-n.pph)),grossImpact:this.normalizePrecision(this.roundValue(-n.totalBeforeCorrection))}}};var So=Math.pow(10,8)*24*60*60*1e3,qm=-So;var Io=3600;var Bi=Io*24,Lm=Bi*7,Do=Bi*365.2425,Po=Do/12,Nm=Po*3,ci=Symbol.for("constructDateFrom");function cn(h,e){return typeof h=="function"?h(e):h&&typeof h=="object"&&ci in h?h[ci](e):h instanceof Date?new h.constructor(e):new Date(e)}function qt(h,e){return cn(e||h,h)}function ki(h,e,t){let r=qt(h,t==null?void 0:t.in);return isNaN(e)?cn((t==null?void 0:t.in)||h,NaN):(e&&r.setDate(r.getDate()+e),r)}function dn(h,e){let t=qt(h,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function br(h,e){let t=qt(h,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Fi(h,e,t){return ki(h,-e,t)}var xr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter}validateDateRange(e,t){if(!(e instanceof Date)||isNaN(e.getTime()))throw new TypeError("startDate bukan Date yang valid");if(!(t instanceof Date)||isNaN(t.getTime()))throw new TypeError("endDate bukan Date yang valid");if(e>t)throw new RangeError("startDate harus \u2264 endDate")}async getSalesAggregate(e,t){var s;this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=0,o=i.length;for(let c of i)a+=(s=c.amount)!=null?s:0;return{totalTransactions:o,totalRevenue:a}}async getTransactionsByHour(e,t){this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=new Map;return i.forEach(o=>{let c=new Date(o.date).getUTCHours().toString().padStart(2,"0");a.set(c,(a.get(c)||0)+1)}),Array.from(a.entries()).sort(([o],[s])=>o.localeCompare(s)).map(([o,s])=>({hour:o,count:s}))}async getRevenueByCustomer(e,t){this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=new Map;return i.forEach(o=>{var s;if(o.referenceType){let c=o.referenceId,u=(s=o.amount)!=null?s:0;a.set(c,(a.get(c)||0)+u)}}),Array.from(a.entries()).map(([o,s])=>({customerId:o,revenue:s}))}async getTodaySales(){let e=dn(new Date).toISOString(),t=br(new Date).toISOString(),r=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:e},{field:"date",operator:"<=",value:t},{field:"deleted",operator:"=",value:!1}]}}]});return{total:Number((r==null?void 0:r.total)||0)}}async getSalesThisMonth(){let e=new Date,t=e.getFullYear(),r=(e.getMonth()+1).toString().padStart(2,"0"),n=`${t}-${r}-01T00:00:00.000Z`,i=br(e).toISOString(),a=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:n},{field:"date",operator:"<=",value:i},{field:"deleted",operator:"=",value:!1}]}}]});return{total:Number((a==null?void 0:a.total)||0)}}async getLowStockProducts(e=this.context.config.reportingLowStockLimit,t=this.context.config.lowStockThreshold){return this.context.domainServices.inventory.getLowStockProducts(t,e)}async getActiveShift(){return(await this.dbAdapter.query(le,{filters:{field:"status",operator:"=",value:"open"},limit:1}))[0]||null}async getTopSellingProducts(e=this.context.config.reportingTopSellingLimit){let t=dn(new Date).toISOString(),r=br(new Date).toISOString(),i=(await this.dbAdapter.query(ue,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["id"]}})).map(l=>String(l.t0_id||l.id||"")).filter(l=>l.length>0);if(!i.length)return[];let a=await this.dbAdapter.query(fe,{filters:{and:[{field:"saleId",operator:"IN",value:i},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["productId","quantity","unitPrice"]}}),o=new Map;for(let l of a){let d=String(l.t0_productId||l.productId||""),m=Number(l.t0_quantity||l.quantity||0),f=Number(l.t0_unitPrice||l.unitPrice||0);if(!d)continue;let y=o.get(d)||{productId:d,quantity:0,totalSales:0};y.quantity+=m,y.totalSales+=m*f,o.set(d,y)}if(!o.size)return[];let s=Array.from(o.keys()),c=await this.dbAdapter.query(ce,{filters:{and:[{field:"id",operator:"IN",value:s},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["id","name"]}}),u=new Map;for(let l of c){let d=String(l.t0_id||l.id||""),m=String(l.t0_name||l.name||"");d&&u.set(d,m||d)}return Array.from(o.values()).map(l=>({productId:l.productId,productName:u.get(l.productId)||l.productId,quantity:l.quantity,totalSales:l.totalSales})).sort((l,d)=>d.quantity-l.quantity).slice(0,e)}async getDailySalesLast7Days(){let e=[];for(let t=6;t>=0;t--){let r=Fi(new Date,t),n=dn(r).toISOString(),i=br(r).toISOString(),a=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:n},{field:"date",operator:"<=",value:i},{field:"deleted",operator:"=",value:!1}]}}]});e.push({date:r.toISOString(),total:Number((a==null?void 0:a.total)||0)})}return e}async getDailyReport(e){var d,m,f;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(le,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r}]}}),this.dbAdapter.query(J,{aggregates:[{function:"SUM",field:"amount",as:"salesCash",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"returnsCash",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"expenses",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}})]),a=0,o=0,s=0;for(let y of n)a+=y.startingCash||0,y.status==="closed"&&(o+=y.endingCash||0,s+=y.systemCash||0);let c=Number(((d=i==null?void 0:i[0])==null?void 0:d.salesCash)||0),u=Number(((m=i==null?void 0:i[0])==null?void 0:m.returnsCash)||0),l=Number(((f=i==null?void 0:i[0])==null?void 0:f.expenses)||0);return{date:e,totalSalesCash:c,totalReturnsCash:u,totalExpenses:l,netCashMovement:c-u-l,startingCash:a,systemEndingCash:s,physicalEndingCash:o,cashDifference:o-s,shifts:n}}async getDailyReconciliationPack(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(J,{aggregates:[{function:"SUM",field:"amount",as:"salesCashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"salesReturnCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"purchaseCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"purchase"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"purchaseReturnCashIn",filter:{and:[{field:"referenceType",operator:"=",value:"purchase_return"},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"expenseCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"cashAdjustmentIn",filter:{and:[{field:"referenceType",operator:"=",value:"cash_adjustment"},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashAdjustmentOut",filter:{and:[{field:"referenceType",operator:"=",value:"cash_adjustment"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"totalCashIn",filter:{field:"direction",operator:"=",value:"in"}},{function:"SUM",field:"amount",as:"totalCashOut",filter:{field:"direction",operator:"=",value:"out"}}],filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Oe,{aggregates:[{function:"COUNT",field:"id",as:"inventoryAdjustmentEntries",filter:{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]}},{function:"SUM",field:"change",as:"inventoryAdjustmentInQty",filter:{and:[{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]},{field:"change",operator:">",value:0}]}},{function:"SUM",field:"change",as:"inventoryAdjustmentOutQtyNegative",filter:{and:[{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]},{field:"change",operator:"<",value:0}]}},{function:"SUM",field:"change",as:"inventoryAdjustmentNetQty",filter:{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]}}],filters:{and:[{field:"timestamp",operator:">=",value:t},{field:"timestamp",operator:"<=",value:r}]}})]),a=(n==null?void 0:n[0])||{},o=(i==null?void 0:i[0])||{},s=Number(a.totalCashIn||0),c=Number(a.totalCashOut||0),u=Math.abs(Number(o.inventoryAdjustmentOutQtyNegative||0));return{date:e,salesCashIn:Number(a.salesCashIn||0),salesReturnCashOut:Number(a.salesReturnCashOut||0),purchaseCashOut:Number(a.purchaseCashOut||0),purchaseReturnCashIn:Number(a.purchaseReturnCashIn||0),expenseCashOut:Number(a.expenseCashOut||0),cashAdjustmentIn:Number(a.cashAdjustmentIn||0),cashAdjustmentOut:Number(a.cashAdjustmentOut||0),totalCashIn:s,totalCashOut:c,netCashMovement:s-c,inventoryAdjustmentEntries:Number(o.inventoryAdjustmentEntries||0),inventoryAdjustmentInQty:Number(o.inventoryAdjustmentInQty||0),inventoryAdjustmentOutQty:u,inventoryAdjustmentNetQty:Number(o.inventoryAdjustmentNetQty||0)}}async getBranchPerformancePack(e){var y;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,n=String(((y=this.context.config)==null?void 0:y.branchId)||"LOCAL"),i=await this.getDailyReconciliationPack(e),[a,o]=await Promise.all([this.dbAdapter.query(le,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r},{field:"status",operator:"=",value:"closed"},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Ce,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"status",operator:"=",value:"completed"},{field:"deleted",operator:"=",value:!1}]}})]),s=o.map(v=>v.id).filter(Boolean),c=s.length>0?await this.dbAdapter.query(Me,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:s},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],u=a.reduce((v,p)=>v+Math.abs(Number(p.cashDifference||0)),0),l=c.length,d=c.reduce((v,p)=>v+Math.abs(Number(p.difference||0)),0),m=[];return(i.salesCashIn>0?i.salesReturnCashOut/i.salesCashIn:0)>.1&&m.push("HIGH_REFUND_RATIO"),u>0&&m.push("SHIFT_CASH_DIFFERENCE"),l>0&&m.push("STOCK_DISCREPANCY"),{date:e,branchId:n,totalSalesCash:i.salesCashIn,totalReturnsCash:i.salesReturnCashOut,totalExpenses:i.expenseCashOut,totalCashIn:i.totalCashIn,totalCashOut:i.totalCashOut,netCashMovement:i.netCashMovement,shiftsClosed:a.length,totalCashDifferenceAbs:u,stockDiscrepancyItems:l,stockDiscrepancyAbsQty:d,anomalyIndicators:m}}async getDailyExceptionReport(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i,a]=await Promise.all([this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"referenceType",operator:"IN",value:["sale_return_cancelled","purchase_return_cancelled"]},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Ae,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Ce,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"status",operator:"=",value:"completed"},{field:"deleted",operator:"=",value:!1}]}})]),o=(a||[]).map(u=>u.id).filter(Boolean),s=o.length>0?await this.dbAdapter.query(Me,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:o},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],c=new Map((a||[]).map(u=>[String(u.id),String(u.date)]));return{date:e,voidEvents:(n||[]).map(u=>({transactionId:String(u.id),referenceType:String(u.referenceType),referenceId:String(u.referenceId),amount:Number(u.amount||0),date:String(u.date)})),refundExceptions:(i||[]).filter(u=>["partially_refunded","no_refund"].includes(String(u.status||""))||Number(u.actualRefund||0)<Number(u.refundAmount||0)).map(u=>({returnId:String(u.id),type:String(u.type),refundAmount:Number(u.refundAmount||0),actualRefund:Number(u.actualRefund||0),status:String(u.status),date:String(u.date)})),stockDiscrepancies:s.map(u=>{var l;return{stockOpnameId:String(u.stockOpnameId),productId:String(u.productId),difference:Number((l=u.difference)!=null?l:0),date:String(c.get(String(u.stockOpnameId))||"")}})}}async getSupplierPayableAging(e=new Date().toISOString()){var a;let t=new Date(e),r=await this.dbAdapter.query(ge,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),n=new Map;for(let o of r){let s=String(o.supplierId||"");if(!s)continue;let c=Number(o.amount||0),u=Number(o.paidAmount||0),l=Math.max(0,c-u);if(l<=0)continue;let d=new Date(String(o.dueDate||"")),m=this.diffInDays(d,t),f=Number.isFinite(m)&&m>0,y=(a=n.get(s))!=null?a:{supplierId:s,openPayableCount:0,totalOutstanding:0,overduePayableCount:0,overdueOutstanding:0,maxDaysPastDue:0,avgDaysPastDue:0};y.openPayableCount+=1,y.totalOutstanding+=l,f&&(y.overduePayableCount+=1,y.overdueOutstanding+=l,y.maxDaysPastDue=Math.max(y.maxDaysPastDue,m)),n.set(s,y)}return Array.from(n.values()).map(o=>{let s=o.overduePayableCount>0?Math.round(o.maxDaysPastDue+o.overdueOutstanding/Math.max(1,o.totalOutstanding)*o.maxDaysPastDue)/2:0;return{...o,avgDaysPastDue:s}}).sort((o,s)=>s.overdueOutstanding-o.overdueOutstanding)}async getCustomerReceivableAging(e=new Date().toISOString()){var o;let t=new Date(e),r=await this.dbAdapter.query(he,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),n=new Map;for(let s of r){let c=String(s.customerId||"");if(!c)continue;let u=Number(s.amount||0),l=Number(s.paidAmount||0),d=Math.max(0,u-l);if(d<=0)continue;let m=new Date(String(s.dueDate||"")),f=this.diffInDays(m,t),y=Number.isFinite(f)&&f>0,v=(o=n.get(c))!=null?o:{customerId:c,openReceivableCount:0,totalOutstanding:0,overdueReceivableCount:0,overdueOutstanding:0,maxDaysPastDue:0};v.openReceivableCount+=1,v.totalOutstanding+=d,y&&(v.overdueReceivableCount+=1,v.overdueOutstanding+=d,v.maxDaysPastDue=Math.max(v.maxDaysPastDue,f)),n.set(c,v)}let i=this.context.config.customerCreditEscalationThresholdDays;return Array.from(n.values()).map(s=>{let c="none";return s.maxDaysPastDue>=i*2?c="critical":s.maxDaysPastDue>=i&&(c="warning"),{...s,escalationLevel:c}}).sort((s,c)=>c.overdueOutstanding-s.overdueOutstanding)}async getOverduePurchaseOrderAlerts(e=new Date().toISOString()){let t=new Date(e),r=await this.dbAdapter.query(_e,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"NOT IN",value:["received","cancelled"]}]}}),n=[];for(let i of r){if(!i.expectedDeliveryDate)continue;let a=new Date(String(i.expectedDeliveryDate)),o=this.diffInDays(a,t);!Number.isFinite(o)||o<=0||n.push({purchaseOrderId:String(i.id),supplierId:String(i.supplierId),status:String(i.status),expectedDeliveryDate:String(i.expectedDeliveryDate),daysOverdue:o,total:Number(i.total||0)})}return n.sort((i,a)=>a.daysOverdue-i.daysOverdue)}async getSupplierPerformanceBaseline(e=new Date().toISOString()){let[t,r,n]=await Promise.all([this.getSupplierPayableAging(e),this.getOverduePurchaseOrderAlerts(e),this.dbAdapter.query(_e,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"NOT IN",value:["received","cancelled"]}]}})]),i=new Map;for(let c of n){let u=String(c.supplierId||"");u&&i.set(u,(i.get(u)||0)+1)}let a=new Map;for(let c of r)a.set(c.supplierId,(a.get(c.supplierId)||0)+1);let o=new Set([...t.map(c=>c.supplierId),...Array.from(i.keys())]),s=[];for(let c of o){let u=t.find(x=>x.supplierId===c),l=(u==null?void 0:u.openPayableCount)||0,d=u&&u.totalOutstanding>0?u.overdueOutstanding/u.totalOutstanding:0,m=i.get(c)||0,f=a.get(c)||0,y=m>0?f/m:0,v=Math.round(100-(d*60+y*40)*100),p=Math.max(0,Math.min(100,v)),g=p>=85?"A":p>=70?"B":p>=50?"C":"D";s.push({supplierId:c,rating:p,grade:g,openPayableCount:l,overduePayableRatio:Number(d.toFixed(4)),openPurchaseOrderCount:m,overdueOrderCount:f,overdueOrderRatio:Number(y.toFixed(4))})}return s.sort((c,u)=>u.rating-c.rating)}diffInDays(e,t){let r=e.getTime(),n=t.getTime();return!Number.isFinite(r)||!Number.isFinite(n)?NaN:Math.floor((n-r)/(1440*60*1e3))}};var Lt=class Lt{constructor(e){this.context=e;var t;this.storage=(t=this.context.registry)==null?void 0:t.storageAdapter}async getAllCarts(){let e=await this.storage.getItem(Lt.KEY);return e?JSON.parse(e):{}}async saveAllCarts(e){await this.storage.setItem(Lt.KEY,JSON.stringify(e))}async createCart(e){let t=await this.getAllCarts();t[e.id]=e,await this.saveAllCarts(t)}async updateCart(e){let t=await this.getAllCarts();t[e.id]&&(t[e.id]={...t[e.id],...e,lastModified:new Date().toISOString()},await this.saveAllCarts(t))}async deleteCart(e){let t=await this.getAllCarts();delete t[e],await this.saveAllCarts(t)}async clearAllCarts(){await this.storage.removeItem(Lt.KEY)}};Lt.KEY="carts";var Ar=Lt;var Sr=class{constructor(e){this.context=e;this.cartStore=new Ar(this.context)}async createCart(e){var n;let t=new Date().toISOString(),r={id:P(),createdAt:t,lastModified:t,items:[],subtotal:0,totalDiscount:0,ppn:0,pph:0,finalTotal:0,userId:((n=this.context.session)==null?void 0:n.userId)||void 0,...e};return await this.cartStore.createCart(r),r}async updateCart(e){await this.cartStore.updateCart(e)}async deleteCart(e){await this.cartStore.deleteCart(e)}async getCart(e){return(await this.cartStore.getAllCarts())[e]}async getAllCarts(){return await this.cartStore.getAllCarts()}async clearAllCarts(){await this.cartStore.clearAllCarts()}async getActiveCarts(){let e=await this.cartStore.getAllCarts();return Object.values(e).filter(t=>!t.isLocked)}async getCartByCustomerId(e){let t=await this.cartStore.getAllCarts();return Object.values(t).filter(r=>r.customerId===e)}async getCartByTableNumber(e){let t=await this.cartStore.getAllCarts();return Object.values(t).filter(r=>r.tableNumber===e)}async addItemToCart(e,t){let r=await this.cartStore.getAllCarts();if(!r[e])throw new Error("Cart not found");let n=r[e];return n.items.push({...t}),n.subtotal+=t.quantity*t.unitPrice,n.finalTotal=n.subtotal+n.ppn+n.pph-n.totalDiscount,await this.cartStore.updateCart(n),n}async removeItemFromCart(e,t){let r=await this.cartStore.getAllCarts();if(!r[e])throw new Error("Cart not found");let n=r[e],i=n.items.findIndex(o=>o.id===t);if(i===-1)throw new Error("Item not found in cart");let a=n.items[i];return n.subtotal-=a.quantity*a.unitPrice,n.finalTotal=n.subtotal+n.ppn+n.pph-n.totalDiscount,n.items.splice(i,1),await this.cartStore.updateCart(n),n}async updateCartItem(e,t,r){let n=await this.cartStore.getAllCarts();if(!n[e])throw new Error("Cart not found");let i=n[e],a=i.items.findIndex(l=>l.id===t);if(a===-1)throw new Error("Item not found in cart");let o=i.items[a],s=o.quantity*o.unitPrice,c={...i.items[a],...r,id:t},u=c.quantity*c.unitPrice;return i.subtotal=i.subtotal-s+u,i.finalTotal=i.subtotal+i.ppn+i.pph-i.totalDiscount,i.items=[...i.items.slice(0,a),c,...i.items.slice(a+1)],await this.cartStore.updateCart(i),i}};var Nt=null,Qt=null,Ir=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,Le.on("taxRateChanged",this.clearTaxRateCache)}async getPpnRate(){if(Nt!==null)return Nt;let e=await this.dbAdapter.query(Ee,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});return Nt=e.length>0?e[0].rate:0,Nt}async getPphRate(){if(Qt!==null)return Qt;let e=await this.dbAdapter.query(Ee,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});return Qt=e.length>0?e[0].rate:0,Qt}async setPpnRate(e){if(e<0)throw new Error("PPN rate must be non-negative");await this.dbAdapter.transaction(async t=>{let r=await t.query(Ee,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(Ee,n.id))),await t.create(Ee,{key:"ppn",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),Le.emit("taxRateChanged"),Nt=e}async setPphRate(e){if(e<0)throw new Error("PPH rate must be non-negative");await this.dbAdapter.transaction(async t=>{let r=await t.query(Ee,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(Ee,n.id))),await t.create(Ee,{key:"pph",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),Le.emit("taxRateChanged"),Qt=e}clearTaxRateCache(){Nt=null,Qt=null}};var ln=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter}getActorId(){var e;return String(((e=this.context.session)==null?void 0:e.userId)||"").trim()}normalizeBranch(e){let t=String(e||"").trim();if(!t)throw new Error("branchId is required");return t}ensureItems(e){if(!Array.isArray(e)||e.length===0)throw new Error("Transfer items are required");return e.map(t=>{let r=String(t.productId||"").trim(),n=Number(t.quantity||0);if(!r||n<=0)throw new Error("Each transfer item requires productId and quantity > 0");return{productId:r,quantity:n}})}async appendEvent(e,t,r,n){let i=new Date().toISOString();await n.create(ie,{id:P(),tableName:"stock_transfers",recordId:e,action:t,changes:r,userId:this.getActorId()||null,timestamp:i})}mergeState(e,t){let r=t.changes||{},n=e||{id:String(t.recordId),sourceBranchId:String(r.sourceBranchId||""),targetBranchId:String(r.targetBranchId||""),status:"requested",items:Array.isArray(r.items)?r.items:[],notes:null};return{...n,...r,id:String(t.recordId),status:String(r.status||n.status),items:Array.isArray(r.items)?r.items:n.items}}async getTransfer(e){let t=await this.dbAdapter.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:"stock_transfers"},{field:"recordId",operator:"=",value:e}]},sort:[{field:"timestamp",direction:"asc"}]});if(!t.length)return null;let r=null;for(let n of t)r=this.mergeState(r,n);return r}async requestTransfer(e){let t=this.normalizeBranch(e.sourceBranchId),r=this.normalizeBranch(e.targetBranchId);if(t===r)throw new Error("sourceBranchId and targetBranchId must be different");let n=this.ensureItems(e.items),i=new Date().toISOString(),a=P(),o=this.getActorId()||null;await this.dbAdapter.transaction(async c=>{await this.appendEvent(a,"stock_transfer_requested",{sourceBranchId:t,targetBranchId:r,status:"requested",items:n,notes:e.notes||null,requestedBy:o,requestedAt:i},c)});let s=await this.getTransfer(a);if(!s)throw new Error("Failed to persist stock transfer request");return s}async approveTransfer(e,t){let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="requested")throw new Error("Stock transfer can only be approved from requested status");let n=new Date().toISOString(),i=this.getActorId()||null;await this.dbAdapter.transaction(async o=>{await this.appendEvent(e,"stock_transfer_approved",{status:"approved",approvedBy:i,approvedAt:n,notes:(t==null?void 0:t.notes)||r.notes||null},o)});let a=await this.getTransfer(e);if(!a)throw new Error("Stock transfer not found after approval");return a}async shipTransfer(e,t){var s;let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="approved")throw new Error("Stock transfer can only be shipped from approved status");let n=String(((s=this.context.config)==null?void 0:s.branchId)||"").trim();if(!n||n!==r.sourceBranchId)throw new Error("Ship operation is only allowed on source branch context");let i=this.getActorId()||null,a=new Date().toISOString();await this.dbAdapter.transaction(async c=>{for(let u of r.items)await this.context.domainServices.inventory.updateStock(u.productId,-Number(u.quantity),"stock_transfer_out","stock_transfer",e,c);await this.appendEvent(e,"stock_transfer_shipped",{status:"shipped",shippedBy:i,shippedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},c)});let o=await this.getTransfer(e);if(!o)throw new Error("Stock transfer not found after shipping");return o}async receiveTransfer(e,t){var s;let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="shipped")throw new Error("Stock transfer can only be received from shipped status");let n=String(((s=this.context.config)==null?void 0:s.branchId)||"").trim();if(!n||n!==r.targetBranchId)throw new Error("Receive operation is only allowed on target branch context");let i=this.getActorId()||null,a=new Date().toISOString();await this.dbAdapter.transaction(async c=>{for(let u of r.items)await this.context.domainServices.inventory.updateStock(u.productId,Number(u.quantity),"stock_transfer_in","stock_transfer",e,c);await this.appendEvent(e,"stock_transfer_received",{status:"received",receivedBy:i,receivedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},c)});let o=await this.getTransfer(e);if(!o)throw new Error("Stock transfer not found after receiving");return o}};var Dr=class{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,c,u,l,d,m,f,y,v,p,g,x,b,A,I,F,w,q,M,E,L,Q,T,j,z,B,U,O,_,R,D,Z,te,X,Y,ye,se,Ne;this.context.domainServices=this,this.bom=(r=t.bomService)!=null?r:new Wr(this.context),this.category=(n=t.categoryService)!=null?n:new $t(this.context),this.customer=(i=t.customerService)!=null?i:new Vt(this.context),this.customerGroup=(a=t.customerGroupService)!=null?a:new zt(this.context),this.history=(o=t.historyService)!=null?o:new jt(this.context),this.order=(s=t.orderService)!=null?s:new Kt(this.context),this.orderItem=(c=t.orderItemService)!=null?c:new Xr(this.context),this.priceTier=(u=t.priceTierService)!=null?u:new Gt(this.context),this.product=(l=t.productService)!=null?l:new Wt(this.context),this.promotion=(d=t.promotionService)!=null?d:new Yt(this.context),this.returnService=(m=t.returnService)!=null?m:new Xt(this.context),this.returnItem=(f=t.returnItemService)!=null?f:new Zr(this.context),this.role=(y=t.roleService)!=null?y:new Jr(this.context),this.sale=(v=t.saleService)!=null?v:new Zt(this.context),this.saleItem=(p=t.saleItemService)!=null?p:new en(this.context),this.shift=(g=t.shiftService)!=null?g:new Jt(this.context),this.taxRate=(x=t.taxRateService)!=null?x:new tn(this.context),this.transaction=(b=t.transactionService)!=null?b:new er(this.context),this.uom=(A=t.uomService)!=null?A:new tr(this.context),this.user=(I=t.userService)!=null?I:new rn(this.context),this.supplier=(F=t.supplierService)!=null?F:new rr(this.context),this.purchaseOrder=(w=t.purchaseOrderService)!=null?w:new nr(this.context),this.purchaseOrderItem=(q=t.purchaseOrderItemService)!=null?q:new nn(this.context),this.purchase=(M=t.purchaseService)!=null?M:new ir(this.context),this.purchaseItem=(E=t.purchaseItemService)!=null?E:new an(this.context),this.inventoryLog=(L=t.inventoryLogService)!=null?L:new ar(this.context),this.priceHistory=(Q=t.priceHistoryService)!=null?Q:new or(this.context),this.stockOpname=(T=t.stockOpnameService)!=null?T:new sr(this.context),this.stockOpnameItem=(j=t.stockOpnameItemService)!=null?j:new on(this.context),this.stockAdjustment=(z=t.stockAdjustmentService)!=null?z:new ur(this.context),this.reportSchedule=(B=t.reportScheduleService)!=null?B:new cr(this.context),this.financialSetting=(U=t.financialSettingService)!=null?U:new dr(this.context),this.expense=(O=t.expenseService)!=null?O:new lr(this.context),this.receivable=(_=t.receivableService)!=null?_:new pr(this.context),this.payable=(R=t.payableService)!=null?R:new mr(this.context),this.settlement=(D=t.settlementService)!=null?D:new hr(this.context),this.inventory=(Z=t.inventoryService)!=null?Z:new fr(this.context),this.exportService=(te=t.exportService)!=null?te:new yr(this.context),this.pricing=(X=t.pricingService)!=null?X:new vr(this.context),this.reporting=(Y=t.reportingService)!=null?Y:new xr(this.context),this.cart=(ye=t.cartService)!=null?ye:new Sr(this.context),this.tax=(se=t.taxService)!=null?se:new Ir(this.context),this.stockTransfer=(Ne=t.stockTransferService)!=null?Ne:new ln(this.context)}};var Dt={status:"idle",queue:[],queueLength:0,conflicts:[],deadLetters:[],metrics:{totalPushAttempted:0,totalPushSucceeded:0,totalPushFailed:0,totalPullApplied:0,totalConflictsRecorded:0,lastQueueLatencyMs:0,lastRunDurationMs:0,lastRunAt:null},lastError:null,lastSyncAt:null},di="sync-store",Pr=class{constructor(e){this.context=e;var t;this.emitter=_t(),this.storage=(t=this.context.registry)==null?void 0:t.storageAdapter,this.state={...Dt},this.load().then(r=>{r&&(this.state=r,this.emitter.emit("update",this.getState()))})}subscribe(e){return e(this.state),this.emitter.on("update",e),()=>this.emitter.off("update",e)}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.save(),this.emitter.emit("update",this.getState())}normalizeChange(e){var y,v,p,g,x;let t=(y=e==null?void 0:e.table)!=null?y:e==null?void 0:e.model,r=(v=e==null?void 0:e.record)!=null?v:{},n=typeof(r==null?void 0:r.id)=="string"?r.id:void 0,i=(p=e==null?void 0:e.id)!=null?p:n;if(typeof t!="string"||!t||typeof i!="string"||!i)return this.context.logError(new Error("Invalid sync change payload"),{raw:e}),null;let a=String((g=e==null?void 0:e.type)!=null?g:"").toUpperCase(),o=a==="CREATE"||a==="UPDATE"||a==="DELETE"?a:"UPDATE",s=Number(e==null?void 0:e.updated_at),c=Date.parse(String((x=r==null?void 0:r.lastModified)!=null?x:"")),u=Number.isFinite(s)&&s>0?s:Number.isFinite(c)&&c>0?c:Date.now(),l=Number(e==null?void 0:e.firstQueuedAt),d=Number(e==null?void 0:e.retryCount),m=Number(e==null?void 0:e.lastAttemptAt),f=e==null?void 0:e.lastErrorMessage;return{id:i,table:t,type:o,record:r,updated_at:u,firstQueuedAt:Number.isFinite(l)&&l>0?l:Date.now(),retryCount:Number.isFinite(d)&&d>=0?Math.floor(d):0,lastAttemptAt:Number.isFinite(m)&&m>0?m:null,lastErrorMessage:typeof f=="string"&&f.trim()?f.trim():null}}startSync(e){this.setState({status:"syncing",lastError:null}),this.context.logInfo("Sync started",e)}setError(e,t){this.setState({status:"error",lastError:e}),this.context.logError(e,{message:"Sync error",...t||{}})}clearError(){this.state.lastError&&(this.setState({lastError:null}),this.context.logInfo("Error cleared"))}enqueueChange(e){let t=this.normalizeChange(e);if(!t)return;let r=[...this.state.queue,t];this.setState({queue:r,queueLength:r.length}),this.context.logInfo("Enqueued change, queueLength: "+r.length)}dequeueChange(){if(this.state.queue.length===0)return;let[,...e]=this.state.queue;this.setState({queue:e,queueLength:e.length}),this.context.logInfo("Dequeued change, queueLength: "+e.length)}removeQueuedChange(e){if(!e)return;let t=this.state.queue.filter(r=>r.id!==e);t.length!==this.state.queue.length&&(this.setState({queue:t,queueLength:t.length}),this.context.logInfo(`Removed queued change ${e}, queueLength: ${t.length}`))}addConflict(e){let t=[...this.state.conflicts,e];this.setState({conflicts:t,metrics:{...this.state.metrics,totalConflictsRecorded:this.state.metrics.totalConflictsRecorded+1}}),this.context.logInfo("Conflict added, total conflicts: "+t.length)}markRetryAttempt(e,t){let r=Date.now(),n=this.state.queue.map(i=>i.id!==e?i:{...i,retryCount:i.retryCount+1,lastAttemptAt:r,lastErrorMessage:t instanceof Error?t.message:String(t||"")});this.setState({queue:n,queueLength:n.length})}moveToDeadLetter(e,t,r){let n=this.state.queue.find(o=>o.id===e);if(!n)return;let i=this.state.queue.filter(o=>o.id!==e),a=[...this.state.deadLetters,{movedAt:Date.now(),reason:t,attempts:n.retryCount,errorMessage:r instanceof Error?r.message:String(r||""),change:n}];this.setState({queue:i,queueLength:i.length,deadLetters:a}),this.context.logInfo(`Change ${e} moved to dead-letter queue (${t})`)}requeueDeadLetter(e){let t=this.state.deadLetters.findIndex(a=>a.change.id===e);if(t<0)return!1;let r=this.state.deadLetters[t],n=this.state.deadLetters.filter((a,o)=>o!==t),i=[...this.state.queue,{...r.change,retryCount:0,lastAttemptAt:null,lastErrorMessage:null,firstQueuedAt:Date.now()}];return this.setState({deadLetters:n,queue:i,queueLength:i.length}),this.context.logInfo(`Dead-letter ${e} requeued`),!0}recordSyncMetrics(e){this.setState({metrics:{...this.state.metrics,...e}})}clearConflicts(){this.state.conflicts.length>0&&(this.setState({conflicts:[]}),this.context.logInfo("Conflicts cleared"))}setLastSyncAt(e){this.setState({lastSyncAt:e}),this.context.logInfo("Last sync at set to "+e)}finishSync(e){this.setState({status:"idle"}),this.context.logInfo("Sync finished",e)}logoutLocal(){this.state={...Dt};try{this.storage.removeItem(di)}catch(e){this.context.logError(e,{message:"Gagal clear sync-store saat logout"})}this.emitter.emit("update",this.getState()),this.context.logInfo("Local logout performed; sync-store cleared")}save(){try{this.storage.setItem(di,JSON.stringify(this.state))}catch(e){this.context.logError(e,{message:"Gagal persist sync-store"})}}async load(){try{let e=await this.storage.getItem(di);if(!e)return null;let t=JSON.parse(e),r=Array.isArray(t.queue)?t.queue.map(s=>this.normalizeChange(s)).filter(s=>s!==null):[],n=Array.isArray(t.conflicts)?t.conflicts.filter(s=>typeof s=="object"&&s!==null):[],i=Array.isArray(t.deadLetters)?t.deadLetters.filter(s=>{if(!s||typeof s!="object")return!1;let c=s;return!!c.change&&typeof c.change.id=="string"}):[],a=t.metrics||{},o={...Dt.metrics,...a};return{...Dt,...t,queue:r,queueLength:r.length,conflicts:n,deadLetters:i,metrics:o,lastError:null}}catch(e){return this.context.logError(e,{message:"Gagal load sync-store"}),null}}async shutdown(){this.emitter=_t()}};var Cr=class{constructor(e){this.context=e;this.explicitActionTableMap={createSettlement:"settlements",RecordCashIn:"transactions",RecordCashOut:"transactions",processReturn:"returns",cancelReturn:"returns",ReturnRefundApproved:"returns",CancelReturnApproved:"returns",CloseShiftApproval:"shifts",ReopenShiftApproved:"shifts",PO_PRICE_VARIANCE_DETECTED:"purchases",customerCreditEscalationDetected:"sales",TieredPrice:"products",LoyaltyEarnPoints:"loyalty_ledgers",LoyaltyRedeemPoints:"loyalty_ledgers",LoyaltyExpirePoints:"loyalty_ledgers"};this.entityTableMap={Bom:"boms",Category:"categories",Customer:"customers",CustomerGroup:"customer_groups",Expense:"expenses",FinancialSetting:"financial_settings",History:"histories",InventoryLog:"inventory_logs",InventoryLot:"inventory_lots",KitchenTicket:"kitchen_tickets",KitchenTicketItem:"kitchen_ticket_items",LoyaltyAccount:"loyalty_accounts",LoyaltyLedger:"loyalty_ledgers",Order:"orders",OrderItem:"order_items",Payable:"payables",PriceHistory:"price_histories",PriceTier:"price_tiers",Product:"products",Promotion:"promotions",Purchase:"purchases",PurchaseItem:"purchase_items",PurchaseOrder:"purchase_orders",PurchaseOrderItem:"purchase_order_items",Receivable:"receivables",ReportSchedule:"report_schedules",Return:"returns",ReturnItem:"return_items",Role:"roles",Sale:"sales",SaleItem:"sale_items",Settlement:"settlements",Shift:"shifts",StockAdjustment:"stock_adjustments",StockOpname:"stock_opnames",StockOpnameItem:"stock_opname_items",Supplier:"suppliers",TaxRate:"tax_rates",Transaction:"transactions",Uom:"uoms",User:"users"};var t;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter}inferEntityFromAction(e){let t=String(e||"").trim();if(!t)return null;let r=t.match(/^(Add|Update|Delete|Duplicate)([A-Z].*)$/);if(r)return r[2];let n=t.match(/^(create|record|process|cancel|close|reopen)([A-Z].*)$/);return n?n[2]:null}inferTableName(e,t){let r=String((t==null?void 0:t.tableName)||"").trim();if(r)return r;let n=(t==null?void 0:t.itemType)==="productId"?"products":(t==null?void 0:t.itemType)==="promotionId"?"promotions":(t==null?void 0:t.itemType)==="bomId"?"boms":"";if(n)return n;let i=this.explicitActionTableMap[e];if(i)return i;let a=this.inferEntityFromAction(e);return a&&this.entityTableMap[a]?this.entityTableMap[a]:"system_events"}resolveRecordId(e){var r,n,i,a,o,s,c;let t=(c=(s=(o=(a=(i=(n=(r=e==null?void 0:e.recordId)!=null?r:e==null?void 0:e.id)!=null?n:e==null?void 0:e.itemId)!=null?i:e==null?void 0:e.productId)!=null?a:e==null?void 0:e.promotionId)!=null?o:e==null?void 0:e.bomId)!=null?s:e==null?void 0:e.newId)!=null?c:e==null?void 0:e.originalId;return t==null||String(t).trim()===""?`activity-${Date.now()}`:String(t)}async logActivity(e,t,r,n){var o,s,c;let i=new Date().toISOString(),a=`${t} | ${e} | ${i}`;try{let u=this.context.config.deploymentMode,l=((o=this.context.session)==null?void 0:o.tenantId)||null,d=this.context.config.branchId||null,m=(r==null?void 0:r.tenantId)||null,f=(r==null?void 0:r.branchId)||null,y=m||l,v=f||d;if(u==="saas"&&(!y||!String(y).trim()))throw new Error("Tenant context is required for audit log entries in SaaS mode (missing tenantId)");if(u==="saas"&&l&&m&&String(m)!==String(l))throw new Error("Tenant isolation violation in audit log context (tenant override mismatch)");if(d&&f&&String(f)!==String(d))throw new Error("Branch isolation violation in audit log context (branch override mismatch)");let p={...r||{},tenantId:y||null,branchId:v||null,deploymentMode:u};await((c=(s=this.context.registry)==null?void 0:s.activitySink)==null?void 0:c.publish({activityId:P(),activityType:e,occurredAt:i,scopeRef:{tenantId:y||void 0,branchId:v||void 0,domain:"ofpos"},actor:{userId:t,source:"shared-core"},payload:p})),this.context.logInfo(a,p);let g=this.inferTableName(e,r),x=this.resolveRecordId(r),b={...p};await(n||this.dbAdapter).create(ie,{id:P(),userId:t,action:e,tableName:g,recordId:x,changes:b,timestamp:i})}catch(u){this.context.logError(u,{action:e,userId:t,extraContext:r})}}};var wr=class{constructor(e){this.context=e;this.recordCache=new Map;this.allCache=null;var t;this.db=(t=this.context.registry)==null?void 0:t.dbAdapter}async create(e){this.validateData(e,["name","permissions"]);let t=new Date().toISOString(),r={id:P().toString(),name:e.name,permissions:JSON.stringify(e.permissions),version:1,lastModified:t,deleted:!1},n=await this.db.create(Pe,r),i=this.denormalize(n);return this.recordCache.set(i.id,i),this.allCache=null,i}async update(e,t){if(!e)throw new Error("Missing role id for update");let r=await this.db.get(Pe,e);if(!r)throw new Error(`Role not found: ${e}`);let n=new Date().toISOString(),a={version:r.version+1,lastModified:n};t.name!==void 0&&(a.name=t.name),t.permissions!==void 0&&(a.permissions=JSON.stringify(t.permissions));let o=await this.db.update(Pe,e,a);if(!o)throw new Error(`Role not found: ${e}`);let s=this.denormalize(o);return this.recordCache.set(e,s),this.allCache=null,s}async delete(e){if(!e)throw new Error("Missing role id for delete");let t=await this.db.get(Pe,e);if(!t)return;if(!await this.db.update(Pe,e,{deleted:!0,version:t.version+1,lastModified:new Date().toISOString()}))throw new Error(`Role not found: ${e}`);this.recordCache.delete(e),this.allCache=null}async queryAll(){if(this.allCache)return this.allCache;let t=(await this.db.query(Pe,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}]})).map(this.denormalize);this.recordCache.clear();for(let r of t)this.recordCache.set(r.id,r);return this.allCache=t,t}async getById(e){if(!e)return null;let t=this.recordCache.get(e);if(t&&!t.deleted)return t;let r=await this.db.get(Pe,e);if(!r||r.deleted)return null;let n=this.denormalize(r);return this.recordCache.set(e,n),n}denormalize(e){return{...e,permissions:JSON.parse(e.permissions)}}validateData(e,t){for(let r of t)if(e[r]===void 0)throw new Error(`Field '${r}' is required`)}};var li={version:"gau-v1",rules:[{action:"void",requiredPermission:"sale:void",thresholdAmount:0,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin","manager"]},{action:"refund",requiredPermission:"refund:process",thresholdAmount:1e5,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin","manager"]},{action:"settlement_adjustment",requiredPermission:"settlement:adjust",thresholdAmount:25e4,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin","manager"]},{action:"credit_limit_approval",requiredPermission:"credit:approve",thresholdAmount:5e5,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin"]}]},Er=class{constructor(e){this.context=e;this.roleAdapter=new wr(e),this.changeQueue=H(this.context)}enqueue(e,t,r){this.changeQueue.enqueue({type:e,model:t,record:r})}async addRole(e,t){let r=await this.roleAdapter.create(e);return this.enqueue("create","roles",r),this.context.logActivity("AddRole",{id:r.id}),r}async updateRole(e,t,r){let n=await this.roleAdapter.update(e,t);return this.enqueue("update","roles",n),this.context.logActivity("UpdateRole",{id:e}),n}async deleteRole(e,t){return await this.roleAdapter.delete(e),this.enqueue("delete","roles",{id:e}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async getRoles(e){var a;let t=(a=this.context.registry)==null?void 0:a.dbAdapter,r={deleted:!1},n=e!=null&&e.filters?{and:[e.filters,r]}:r;return await t.query(Pe,{...e,filters:n})}async getRoleById(e){return this.roleAdapter.getById(e)}hasPermission(e,t){return Array.isArray(e.permissions)&&(e.permissions.includes("all")||e.permissions.includes(t))}async can(e,t){let r=await this.getRoleById(e.role);return this.hasPermission(r,t)}getGranularPolicy(){return li}normalizeRole(e){return String(e||"").trim().toLowerCase()}isApprovalValid(e,t){let r=String((e==null?void 0:e.approvedBy)||"").trim(),n=String((e==null?void 0:e.reason)||"").trim(),i=this.normalizeRole(e==null?void 0:e.approverRole);return!r||!n||!i?!1:t.includes(i)}async evaluateGranularAuthorization(e){var u,l,d,m,f;let t=P(),n=(e.policy||li).rules.find(y=>y.action===e.action);if(!n)throw new Error(`Granular authorization rule is not defined for action "${e.action}"`);let i=Number.isFinite(e.amount)?Number(e.amount):0,a=await this.getRoleById(e.actor.role);if(!(!!a&&this.hasPermission(a,n.requiredPermission))){let y={decisionId:t,action:e.action,status:"deny",reasonCode:"ROLE_OR_PERMISSION_DENIED",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((u=this.context.session)==null?void 0:u.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!(n.approvalRequiredAboveThreshold&&i>n.thresholdAmount)){let y={decisionId:t,action:e.action,status:"allow",reasonCode:"ALLOW_BELOW_THRESHOLD",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((l=this.context.session)==null?void 0:l.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!e.approval){let y={decisionId:t,action:e.action,status:"require_approval",reasonCode:"THRESHOLD_APPROVAL_REQUIRED",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((d=this.context.session)==null?void 0:d.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!this.isApprovalValid(e.approval,n.approverRoles.map(y=>this.normalizeRole(y)))){let y={decisionId:t,action:e.action,status:"deny",reasonCode:"APPROVAL_INVALID",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((m=this.context.session)==null?void 0:m.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount,approvedBy:e.approval.approvedBy,approvalReason:e.approval.reason,approverRole:this.normalizeRole(e.approval.approverRole)}),y}let c={decisionId:t,action:e.action,status:"allow",reasonCode:"ALLOW_WITH_APPROVAL",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:c.status,reasonCode:c.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((f=this.context.session)==null?void 0:f.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount,approvedBy:e.approval.approvedBy,approvalReason:e.approval.reason,approverRole:this.normalizeRole(e.approval.approverRole)}),c}};var Gn=Mt(hi()),_r=class{constructor(e,t){this.context=e;this.keySettingName="encryption_key";var r,n;this.secretKey=t||this.context.config.encryptionKey,this.adapter=(r=this.context.registry)==null?void 0:r.dbAdapter,this.encryptionAdapter=(n=this.context.registry)==null?void 0:n.encryptionAdapter}get masterKey(){return this.context.config.encryptionPassphrase}encryptData(e){let t=typeof e=="string"?e:JSON.stringify(e),r=this.encryptionAdapter.encrypt(t,{keyId:this.keySettingName,metadata:{secretKey:this.secretKey}});if(r&&typeof r.then=="function")throw new Error("Shared-core encryption path requires synchronous EncryptionAdapter.encrypt");return String(r||"")}decryptData(e){try{let t=this.encryptionAdapter.decrypt(e,{keyId:this.keySettingName,metadata:{secretKey:this.secretKey}});if(t&&typeof t.then=="function")throw new Error("Shared-core encryption path requires synchronous EncryptionAdapter.decrypt");if(!t)return null;try{return JSON.parse(String(t))}catch{return String(t)}}catch{return null}}async setItem(e,t){let r=this.encryptData(t);await this.adapter.get("settings",e)?await this.adapter.update("settings",e,{value:r}):await this.adapter.create("settings",{id:e,value:r})}async getItem(e){let t=await this.adapter.get("settings",e);return t!=null&&t.value?this.decryptData(t.value):null}async storeKey(e=this.keySettingName){let t=Gn.default.AES.encrypt(this.secretKey,this.masterKey).toString();await this.adapter.get("settings",e)?await this.adapter.update("settings",e,{value:t}):await this.adapter.create("settings",{id:e,value:t})}async retrieveKey(e=this.keySettingName){let t=await this.adapter.get("settings",e);if(!(t!=null&&t.value))return!1;let n=Gn.default.AES.decrypt(t.value,this.masterKey).toString(Gn.default.enc.Utf8);return n?(this.secretKey=n,!0):!1}async rotateKey(e,t=this.keySettingName,r=["auth_token"]){let n=Array.from(new Set(r.map(a=>String(a||"").trim()).filter(a=>a.length>0))),i=[];for(let a of n){let o=await this.getItem(a);o!==null&&i.push({key:a,value:o})}this.secretKey=e,await this.storeKey(t);for(let a of i)await this.setItem(a.key,a.value)}};var Tr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter}authorityProvisioningError(e){let t=new Error(`User ${e} is not allowed in ofpos-shared-core. Identity authority must be managed by ofauth-* and synced as projection to POS.`);return t.code="AUTH_AUTHORITY_REQUIRED",t}async addUser(e){throw this.authorityProvisioningError("add")}async updateUser(e,t){throw this.authorityProvisioningError("update")}async deleteUser(e){throw this.authorityProvisioningError("delete")}async fetchUsers(e){let t=this.dbAdapter,r={deleted:!1},n=e!=null&&e.filters?{and:[e.filters,r]}:r;return await t.query($e,{...e,filters:n})}setActiveSession(e){var t,r,n;this.activeSession=e,this.context.logInfo("auth.session.activated",{userId:e.id,username:e.username}),(n=(r=(t=this.context).getSessionStore)==null?void 0:r.call(t))==null||n.login(e)}logoutLocal(){var e,t,r;this.activeSession=void 0,(r=(t=(e=this.context).getSessionStore)==null?void 0:t.call(e))==null||r.logout(),this.context.logInfo("auth.session.deactivated")}getActiveSession(){return this.activeSession}};var Br=we("ofcore"),mt=we("ofcore");var kr=class{constructor(e){this.context=e;var t,r,n;if(this.encryptionService=(t=this.context.integrationServices)==null?void 0:t.encryption,this.httpAdapter=(r=this.context.registry)==null?void 0:r.httpAdapter,this.httpRetryPolicy=(n=this.context.registry)==null?void 0:n.httpRetryPolicy,!this.httpAdapter)throw new Error("ApiService requires HttpAdapter from registry")}validateSyncProtocolHandshake(e,t){var s;if(!(e.includes("/sync/push")||e.includes("/sync/pull"))||!this.context.config.enforceSyncProtocolHandshake)return;let n=t||{},i=(s=n["x-sync-protocol-version"])!=null?s:n["x-server-protocol-version"];if(i==null||i==="")throw new Error("Sync protocol handshake failed: missing server protocol version header");let a=Number(i);if(!Number.isInteger(a)||a<0)throw new Error(`Sync protocol handshake failed: invalid server protocol version "${i}"`);let o=this.context.config.syncCompatibleServerVersions;if(!ui(a,o))throw new Error(`Sync protocol mismatch: server=${a}, client=${this.context.config.syncProtocolVersion}, compatible=[${o.join(",")}]`)}async buildHeaders(e,t,r,n={}){var c;let i={...n},a=await this.encryptionService.getItem("auth_token");a&&(i.Authorization=`Bearer ${a}`);let o=t.includes("/sync/push")||t.includes("/sync/pull"),s=t.startsWith("/sync/")||t.startsWith("/erp")||t.startsWith("/shifts/")||t.startsWith("/backup/");try{let u=this.context.config.branchId;u&&(i["X-Branch-ID"]=u)}catch{}if(s&&this.context.config.deploymentMode==="saas"){let u=(c=this.context.session)==null?void 0:c.tenantId;if(!u||!String(u).trim())throw new Error("Tenant context is required for tenant-scoped requests in SaaS mode (missing tenantId)");i["X-Tenant-ID"]=u}if(e==="POST"&&t.includes("/sync/push")&&r){let u=typeof r=="string"?r:JSON.stringify(r),l=this.context.checksum(u);if(!l)throw new Error("paymentSigningKey is required for sync push checksum");i["X-Data-Checksum"]=l}return o&&(i["X-Sync-Protocol-Version"]=String(this.context.config.syncProtocolVersion),i["X-Sync-Compatible-Versions"]=this.context.config.syncCompatibleServerVersions.join(",")),i}async requestData(e,t,r={}){let n=await this.buildHeaders(e,t,r.data,r.headers),i=this.context.config.apiUrl||"",a=t.startsWith("http")?t:`${i}${t}`,o=await(0,mt.executeHttpRequestWithRetry)(this.httpAdapter,{method:e,url:a,headers:n,query:r.params,body:r.data,timeoutMs:this.context.config.apiTimeoutMs},{policy:this.httpRetryPolicy});if(o.status===401&&await this.encryptionService.setItem("auth_token",""),this.validateSyncProtocolHandshake(t,o.headers),o.status>=400)throw new Error(`HTTP request failed: ${e} ${t} status=${o.status}`);return o.data}async login(e){let t=await this.requestData("POST","/auth/login",{data:e});if(!(t!=null&&t.token))throw new Error("Authentication failed: no token returned");return await this.encryptionService.setItem("auth_token",t.token),t}async logout(){await this.encryptionService.setItem("auth_token","")}async getProfile(){return this.requestData("GET","/auth/profile")}async getErpData(e,t,r){let n=e?`/erp${e}`:"/sync/erp";return this.requestData("GET",n,{params:t,headers:{...r!=null&&r.correlationId?{"X-Correlation-ID":r.correlationId}:{},...r!=null&&r.syncBatchId?{"X-Sync-Batch-ID":r.syncBatchId}:{}}})}async postErpData(e,t){return this.requestData("POST",`/erp${e}`,{data:t})}async putErpData(e,t){return this.requestData("PUT",`/erp${e}`,{data:t})}async deleteErpData(e,t){return this.requestData("DELETE",`/erp${e}`,{params:t})}async pushChange(e,t){return this.requestData("POST","/sync/push",{data:e,headers:{...t!=null&&t.correlationId?{"X-Correlation-ID":t.correlationId}:{},...t!=null&&t.syncBatchId?{"X-Sync-Batch-ID":t.syncBatchId}:{}}})}async pullChanges(e,t){let r=await this.requestData("GET","/sync/pull",{params:e,headers:{...t!=null&&t.correlationId?{"X-Correlation-ID":t.correlationId}:{},...t!=null&&t.syncBatchId?{"X-Sync-Batch-ID":t.syncBatchId}:{}}});return Array.isArray(r)?r:Array.isArray(r==null?void 0:r.changes)?r.changes:[]}async openShift(){return this.requestData("POST","/shifts/open")}async closeShift(){return this.requestData("POST","/shifts/close")}async getShiftHistory(){return this.requestData("GET","/shifts/history")}async createBackup(e){return this.requestData("POST","/backup/create",{data:e})}async restoreBackup(e){return this.requestData("POST","/backup/restore",{data:e})}async listBackups(e={}){return e.limit===void 0&&(e.limit=this.context.config.apiBackupListLimit),this.requestData("GET","/backup/list",{params:e})}};var $a={products:"server_wins",categories:"server_wins",uoms:"server_wins",customers:"server_wins",suppliers:"server_wins",tax_rates:"server_wins",promotions:"server_wins",price_tiers:"server_wins",users:"server_wins",roles:"server_wins"},Tt=class{async backoff(e){return e()}async applyChanges(){}async syncWithErp(){}async syncLoop(){}},fi=class{constructor(e){this.context=e;this.lastAlertAtByCode=new Map;this.started=!1;var t,r;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.apiService=(r=e.integrationServices)==null?void 0:r.api,this.syncStore=e.getSyncStore(),this.onDataChanged=()=>{this.syncLoop().catch(n=>this.context.logError(n,{message:"Socket-triggered sync gagal"}))}}start(){this.started||(this.unsubscribeStore=this.syncStore.subscribe(e=>{e.queueLength>0&&(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.syncLoop().catch(t=>this.context.logError(t,{message:"Debounced sync gagal"}))},this.context.config.syncDebounceMs))}),Le.on("data_changed",this.onDataChanged),this.periodicTimer=setInterval(()=>{this.context.isOnline()&&this.syncLoop().catch(e=>this.context.logError(e,{message:"Periodic sync gagal"}))},this.context.config.syncIntervalMs),this.started=!0)}normalizeOutgoingChange(e){var u,l,d,m,f;let t=(u=e==null?void 0:e.table)!=null?u:e==null?void 0:e.model,r=(l=e==null?void 0:e.record)!=null?l:{},n=(d=e==null?void 0:e.id)!=null?d:r==null?void 0:r.id;if(!t||!n)return null;let i=String((m=e==null?void 0:e.type)!=null?m:"").toUpperCase(),a=i==="CREATE"||i==="UPDATE"||i==="DELETE"?i:"UPDATE",o=Number(e==null?void 0:e.updated_at),s=Date.parse(String((f=r==null?void 0:r.lastModified)!=null?f:"")),c=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s:Date.now();return{id:n,table:t,type:a,record:r,updated_at:c}}getRemoteTimestamp(e){var n,i,a;let t=Number(e==null?void 0:e.updated_at);if(Number.isFinite(t)&&t>0)return t;let r=Date.parse(String((a=(i=(n=e==null?void 0:e.record)==null?void 0:n.lastModified)!=null?i:e==null?void 0:e.lastModified)!=null?a:""));return Number.isFinite(r)&&r>0?r:Date.now()}getConflictResolutionStrategy(e){return $a[e]||"local_wins_manual"}requireBranchContext(){var t;if(!String((t=this.context.config.branchId)!=null?t:"").trim())throw new Error("Branch context is required for sync operations (missing branchId)")}async backoff(e,t=this.context.config.syncMaxRetries,r=this.context.config.syncBackoffDelayMs){let n=0;for(;;)try{return await e()}catch(i){if(n++,n>t)throw i;let a=r*Math.pow(2,n)+Math.random()*100;await new Promise(o=>setTimeout(o,a))}}async applyChanges(e,t){var i,a,o;let r=this.dbAdapter,n=this.syncStore;for(let s of e){let c=s==null?void 0:s.table,u=s==null?void 0:s.id;if(!c||!u){this.context.logError(new Error("Invalid remote change payload"),{change:s,...t||{}});continue}let l=this.getRemoteTimestamp(s),d=new Date(l).toISOString(),m=(i=s==null?void 0:s.record)!=null?i:{},f={...m,id:u,lastModified:(a=m==null?void 0:m.lastModified)!=null?a:d};try{let y=await r.get(c,u);if(!y)await r.create(c,f);else{let v=Date.parse(String((o=y==null?void 0:y.lastModified)!=null?o:""));if(!Number.isFinite(v)||l>v)await r.update(c,u,f);else if(l!==v)if(this.getConflictResolutionStrategy(c)==="server_wins")await r.update(c,u,f),this.context.logInfo(`Auto-resolve konflik master data ${c}:${u}`,t);else{let p={table:c,id:u,localLastModified:y==null?void 0:y.lastModified,remoteUpdatedAt:l,local:y,remote:s,reason:"local_newer"};n.addConflict(p),this.context.logInfo(`Konflik terdeteksi ${c}:${u}, dicatat untuk resolusi manual`,t)}}}catch(y){this.context.logError(y,{message:`Error applyChange ${s.table}:${s.id}`,...t||{}})}}}async syncWithErp(e){var t,r,n,i,a,o;try{this.context.logInfo("Mulai sinkronisasi ERP",e);let s=await this.apiService.getErpData(void 0,void 0,e),c=this.dbAdapter;for(let u of(t=s==null?void 0:s.customers)!=null?t:[]){let l=u==null?void 0:u.id;if(!l)continue;let d=await c.get("customers",l),m={...u,lastModified:(r=u==null?void 0:u.lastModified)!=null?r:new Date().toISOString()};d?await c.update("customers",l,m):await c.create("customers",m)}for(let u of(n=s==null?void 0:s.boms)!=null?n:[]){let l=u==null?void 0:u.id;if(!l)continue;let d=await c.get("boms",l),m={...u,lastModified:(i=u==null?void 0:u.lastModified)!=null?i:new Date().toISOString()};d?await c.update("boms",l,m):await c.create("boms",m)}for(let u of(a=s==null?void 0:s.uoms)!=null?a:[]){let l=u==null?void 0:u.id;if(!l)continue;let d=await c.get("uoms",l),m={...u,lastModified:(o=u==null?void 0:u.lastModified)!=null?o:new Date().toISOString()};d?await c.update("uoms",l,m):await c.create("uoms",m)}this.context.logInfo("Sinkronisasi ERP selesai",e)}catch(s){this.context.logError(s,{message:"Sinkronisasi ERP gagal",...e||{}})}}async cleanupDeleted(){this.context.logInfo("cleanupDeleted: belum diimplementasi")}shouldTriggerAlert(e){let t=this.context.config.opsAlertEscalationCooldownMinutes*60*1e3,r=Date.now(),n=this.lastAlertAtByCode.get(e)||0;return r-n<t?!1:(this.lastAlertAtByCode.set(e,r),!0)}emitOperationalAlert(e){if(!this.shouldTriggerAlert(e.code))return;let t={...e.correlationId?{correlationId:e.correlationId}:{},...e.syncBatchId?{syncBatchId:e.syncBatchId}:{},...e.metrics?{metrics:e.metrics}:{},code:e.code,category:e.category,severity:e.severity,at:e.at};e.severity==="critical"?this.context.logError(new Error(e.message),t):this.context.logInfo(e.message,t),Le.emit("ops:alert",e)}evaluateOperationalAlerts(e){let{traceContext:t,pushAttempted:r,pushFailed:n,queueLatencyMs:i,deadLetterCount:a}=e;if(r>0){let o=Math.round(n/r*100);o>=this.context.config.opsAlertSyncFailureRateThresholdPercent&&this.emitOperationalAlert({severity:o>=75?"critical":"warning",category:"sync",code:"SYNC_FAILURE_RATE",message:`Sync failure rate breached threshold (${o}%)`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{failureRatePercent:o,pushAttempted:r,pushFailed:n},at:new Date().toISOString()})}i>=this.context.config.opsAlertQueueLatencyThresholdMs&&this.emitOperationalAlert({severity:i>=this.context.config.opsAlertQueueLatencyThresholdMs*2?"critical":"warning",category:"sync",code:"SYNC_QUEUE_LATENCY",message:`Sync queue latency breached threshold (${i} ms)`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{queueLatencyMs:i},at:new Date().toISOString()}),a>=this.context.config.opsAlertDeadLetterCountThreshold&&this.emitOperationalAlert({severity:a>=this.context.config.opsAlertDeadLetterCountThreshold*2?"critical":"warning",category:"sync",code:"SYNC_DEAD_LETTER",message:`Dead-letter count breached threshold (${a})`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{deadLetterCount:a},at:new Date().toISOString()})}async syncLoop(){if(this.context.config.demoMode){this.context.logInfo("Demo mode enabled: skipping sync");return}let e=this.syncStore,t={correlationId:this.context.createCorrelationId("sync"),syncBatchId:this.context.createCorrelationId("sync-batch")};try{if(!this.context.isOnline()){this.context.logInfo("Offline. Lewati sinkronisasi.",t);return}this.requireBranchContext(),e.startSync(t),e.clearError();let r=e.getState().queue||[],n=Date.now(),i=r.length?Math.round(r.reduce((m,f)=>{let y=Number(f==null?void 0:f.firstQueuedAt);return!Number.isFinite(y)||y<=0?m:m+Math.max(0,n-y)},0)/r.length):0,a=0,o=0,s=0,c=0;for(let m of r)try{a+=1;let f=this.normalizeOutgoingChange(m);if(!f){this.context.logError(new Error("Invalid queued change"),{change:m,...t}),e.removeQueuedChange(String((m==null?void 0:m.id)||"")),s+=1;continue}await this.backoff(()=>this.apiService.pushChange({changes:[f]},t)),e.removeQueuedChange(f.id),o+=1}catch(f){this.context.logError(f,{message:"Gagal push change",...t}),s+=1,e.markRetryAttempt(m.id,f);let y=e.getState().queue.find(v=>v.id===m.id);y&&y.retryCount>=this.context.config.syncMaxRetries&&e.moveToDeadLetter(m.id,"max_retry_exceeded",f)}let u=[];try{let m=e.getState().lastSyncAt;u=await this.backoff(()=>this.apiService.pullChanges({since:m},t)),await this.applyChanges(u,t),c=u.length}catch(m){this.context.logError(m,{message:"Gagal pull/apply changes",...t})}await this.syncWithErp(t),e.setLastSyncAt(Date.now()),await this.cleanupDeleted();let l=Date.now(),d=e.getState().metrics;e.recordSyncMetrics({totalPushAttempted:d.totalPushAttempted+a,totalPushSucceeded:d.totalPushSucceeded+o,totalPushFailed:d.totalPushFailed+s,totalPullApplied:d.totalPullApplied+c,lastQueueLatencyMs:i,lastRunDurationMs:Math.max(0,l-n),lastRunAt:l}),this.evaluateOperationalAlerts({traceContext:t,pushAttempted:a,pushFailed:s,queueLatencyMs:i,deadLetterCount:e.getState().deadLetters.length})}catch(r){this.context.logError(r,{message:"Sync loop error",...t}),e.setError(r,t)}finally{e.finishSync(t),this.context.logInfo("Sync loop selesai",t)}}shutdown(){this.started&&(this.debounceTimer&&clearTimeout(this.debounceTimer),this.periodicTimer&&clearInterval(this.periodicTimer),this.unsubscribeStore&&(this.unsubscribeStore(),this.unsubscribeStore=void 0),Le.off("data_changed",this.onDataChanged),this.started=!1)}};var Bt=class{getSocket(){}shutdown(){}},gi=class h{constructor(e,t="http://localhost:3000"){this.context=e;this.url=t;this.started=!1;var r,n,i,a;if(this.syncStore=(n=(r=this.context).getSyncStore)==null?void 0:n.call(r),this.syncService=(i=this.context.integrationServices)==null?void 0:i.sync,this.debouncedSync=h.debounce(()=>{var o;(o=this.syncService)==null||o.syncLoop()}),this.socketAdapter=(a=this.context.registry)==null?void 0:a.socketAdapter,!this.socketAdapter)throw new Error("SocketService requires SocketAdapter from registry")}static debounce(e,t=1e3){let r;return((...n)=>{r&&clearTimeout(r),r=setTimeout(()=>e(...n),t)})}async start(){this.started||(await this.initSocket(),this.started=!0)}async initSocket(){var r;let e=(r=this.context.integrationServices)==null?void 0:r.encryption,t=await(e==null?void 0:e.getItem("auth_token"));await this.socketAdapter.connect({url:this.url,headers:{...t?{Authorization:`Bearer ${t}`}:{},"X-Branch-ID":this.context.config.branchId||""}}),this.unsubscribeConnect=this.socketAdapter.subscribe("connect",()=>{this.debouncedSync()}),this.unsubscribeDisconnect=this.socketAdapter.subscribe("disconnect",n=>{var a;let i=typeof n=="string"?n:"unknown";(a=this.syncStore)==null||a.setError(new Error(`Socket disconnected: ${i}`))}),this.unsubscribeDataChanged=this.socketAdapter.subscribe("data_changed",()=>{this.debouncedSync()})}getSocket(){return this.socketAdapter}shutdown(){var e,t,r,n,i;this.started&&((e=this.unsubscribeDataChanged)==null||e.call(this),(t=this.unsubscribeConnect)==null||t.call(this),(r=this.unsubscribeDisconnect)==null||r.call(this),this.unsubscribeDataChanged=void 0,this.unsubscribeConnect=void 0,this.unsubscribeDisconnect=void 0,(i=(n=this.socketAdapter)==null?void 0:n.disconnect)==null||i.call(n).catch(()=>{}),this.started=!1)}};var Fr=class{constructor(e){this.context=e;this.flushing=!1;this.notificationQueue=[];this.MAX_QUEUE=1e3;var t;if(this.notifier=(t=this.context.registry)==null?void 0:t.notificationAdapter,this.notifier)try{typeof this.notifier.configure=="function"&&this.notifier.configure({}),typeof this.notifier.createChannel=="function"&&this.notifier.createChannel({channelId:"default",channelName:"Default",importance:3})}catch(r){console.error("[PosCore] Error configuring notifications",r)}}async initNotifications(){var t;if(this.flushing||!this.notifier)return;this.flushing=!0;let e=this.notificationQueue;this.notificationQueue=[];for(let r of e)try{await this.notifier.localNotification({channelId:"default",title:r.title,message:r.message})}catch(n){r.retries=((t=r.retries)!=null?t:0)+1,r.retries<5&&this.notificationQueue.push(r),console.error("[PosCore] Error flushing notification, re-queueing",n)}this.flushing=!1}notify(e,t){if(this.notificationQueue.length>=this.MAX_QUEUE&&this.notificationQueue.shift(),!this.notifier){this.notificationQueue.push({title:e,message:t});return}try{this.notifier.localNotification({channelId:"default",title:e,message:t})}catch(r){console.error("[PosCore] Error showing notification",r),this.notificationQueue.push({title:e,message:t})}}};var Va=we("ofcore");var Mr=class{constructor(e){this.context=e;this._lowStockThreshold=null;this._paymentSigningKey=null;this._apiUrl=null;this._branchId=null;this._demoMode=null;this._deploymentMode=null;this._requireActiveShiftForCash=null;this._maxCashAdjustmentAmount=null;this._requireShiftCloseApprovalOnDifference=null;this._shiftCloseDifferenceApprovalThreshold=null;this._requireReasonForReturnOperations=null;this._requireApprovalForReturnRefund=null;this._requireApprovalForReturnCancel=null;this._requireLotExpiryForPurchaseReceiving=null;this._lotConsumptionPolicy=null;this._enableCustomerCreditPolicy=null;this._customerCreditMaxOutstandingAmount=null;this._customerCreditBlockOnOverdue=null;this._customerCreditOverdueGraceDays=null;this._customerCreditEscalationThresholdDays=null;this._enableReturnFraudGuard=null;this._returnFraudWindowMinutes=null;this._returnFraudMaxEvents=null;this._returnFraudAction=null;this._returnApprovalBypassRoles=null;this._returnApprovalApproverRoles=null;this._allowPromotionStacking=null;this._promotionSelectionStrategy=null;this._promotionStackingOrder=null;this._pricingRoundingIncrement=null;this._pricingRoundingScope=null;this._enableSequentialDocumentNumbers=null;this._syncProtocolVersion=null;this._syncCompatibleServerVersions=null;this._enforceSyncProtocolHandshake=null;this._onlineAuthMaxFailedAttempts=null;this._onlineAuthLockoutSeconds=null;this._drRpoTargetMinutes=null;this._drRtoTargetMinutes=null;this._backupIntervalMinutes=null;this._backupRestoreDrillIntervalHours=null;this._opsAlertSyncFailureRateThresholdPercent=null;this._opsAlertQueueLatencyThresholdMs=null;this._opsAlertDeadLetterCountThreshold=null;this._opsAlertEscalationCooldownMinutes=null;this._auditLogRetentionDays=null;this._auditLogArchiveBeforePurge=null;this._auditLogPurgeBatchSize=null;this._sessionIdleTimeoutMinutes=null;this._sessionReauthTimeoutMinutes=null;this._apiTimeoutMs=null;this._syncIntervalMs=null;this._syncMaxRetries=null;this._syncBackoffDelayMs=null;this._syncDebounceMs=null;this._reportingTopSellingLimit=null;this._reportingLowStockLimit=null;this._apiBackupListLimit=null;this._encryptionKey=null;this._encryptionPassphrase=null;var r,n;let t=this.context.registry;this.platformAdapter=(r=t==null?void 0:t.platformAdapter)!=null?r:new Va.DefaultPlatformAdapter(this.context),this.storage=(n=t==null?void 0:t.storageAdapter)!=null?n:new yt(this.context)}async init(){let e=await this.storage.getItem("config");if(e)try{let t=JSON.parse(e);this._lowStockThreshold=t.lowStockThreshold?Number(t.lowStockThreshold):this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=t.paymentSigningKey?t.paymentSigningKey:this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=t.apiUrl?t.apiUrl:this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=t.branchId?t.branchId:this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=t.demoMode!=null?!!t.demoMode:this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let r=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE"),n=t.deploymentMode==="saas"||t.deploymentMode==="standalone"?t.deploymentMode:r==="saas"||r==="standalone"?r:null;this._deploymentMode=n,this._requireActiveShiftForCash=t.requireActiveShiftForCash!=null?!!t.requireActiveShiftForCash:null,this._maxCashAdjustmentAmount=t.maxCashAdjustmentAmount!=null?Number(t.maxCashAdjustmentAmount):null,this._requireShiftCloseApprovalOnDifference=t.requireShiftCloseApprovalOnDifference!=null?!!t.requireShiftCloseApprovalOnDifference:null,this._shiftCloseDifferenceApprovalThreshold=t.shiftCloseDifferenceApprovalThreshold!=null?Number(t.shiftCloseDifferenceApprovalThreshold):null,this._requireReasonForReturnOperations=t.requireReasonForReturnOperations!=null?!!t.requireReasonForReturnOperations:null,this._requireApprovalForReturnRefund=t.requireApprovalForReturnRefund!=null?!!t.requireApprovalForReturnRefund:null,this._requireApprovalForReturnCancel=t.requireApprovalForReturnCancel!=null?!!t.requireApprovalForReturnCancel:null,this._requireLotExpiryForPurchaseReceiving=t.requireLotExpiryForPurchaseReceiving!=null?!!t.requireLotExpiryForPurchaseReceiving:null,this._lotConsumptionPolicy=t.lotConsumptionPolicy==="FEFO"||t.lotConsumptionPolicy==="FIFO"?t.lotConsumptionPolicy:null,this._enableCustomerCreditPolicy=t.enableCustomerCreditPolicy!=null?!!t.enableCustomerCreditPolicy:null,this._customerCreditMaxOutstandingAmount=t.customerCreditMaxOutstandingAmount!=null?Number(t.customerCreditMaxOutstandingAmount):null,this._customerCreditBlockOnOverdue=t.customerCreditBlockOnOverdue!=null?!!t.customerCreditBlockOnOverdue:null,this._customerCreditOverdueGraceDays=t.customerCreditOverdueGraceDays!=null?Number(t.customerCreditOverdueGraceDays):null,this._customerCreditEscalationThresholdDays=t.customerCreditEscalationThresholdDays!=null?Number(t.customerCreditEscalationThresholdDays):null,this._enableReturnFraudGuard=t.enableReturnFraudGuard!=null?!!t.enableReturnFraudGuard:null,this._returnFraudWindowMinutes=t.returnFraudWindowMinutes!=null?Number(t.returnFraudWindowMinutes):null,this._returnFraudMaxEvents=t.returnFraudMaxEvents!=null?Number(t.returnFraudMaxEvents):null,this._returnFraudAction=t.returnFraudAction==="require_approval"||t.returnFraudAction==="block"?t.returnFraudAction:null,this._returnApprovalBypassRoles=Array.isArray(t.returnApprovalBypassRoles)?t.returnApprovalBypassRoles.map(i=>String(i)):null,this._returnApprovalApproverRoles=Array.isArray(t.returnApprovalApproverRoles)?t.returnApprovalApproverRoles.map(i=>String(i)):null,this._allowPromotionStacking=t.allowPromotionStacking!=null?!!t.allowPromotionStacking:null,this._promotionSelectionStrategy=t.promotionSelectionStrategy==="best_discount"||t.promotionSelectionStrategy==="first_valid"?t.promotionSelectionStrategy:null,this._promotionStackingOrder=t.promotionStackingOrder==="input_order"||t.promotionStackingOrder==="percent_then_fixed"||t.promotionStackingOrder==="fixed_then_percent"?t.promotionStackingOrder:null,this._pricingRoundingIncrement=t.pricingRoundingIncrement!=null?Number(t.pricingRoundingIncrement):null,this._pricingRoundingScope=t.pricingRoundingScope==="line"||t.pricingRoundingScope==="total"?t.pricingRoundingScope:null,this._enableSequentialDocumentNumbers=t.enableSequentialDocumentNumbers!=null?!!t.enableSequentialDocumentNumbers:null,this._syncProtocolVersion=Number.isInteger(t.syncProtocolVersion)&&Number(t.syncProtocolVersion)>=0?Number(t.syncProtocolVersion):null,this._syncCompatibleServerVersions=Array.isArray(t.syncCompatibleServerVersions)?t.syncCompatibleServerVersions.map(i=>Number(i)).filter(i=>Number.isInteger(i)&&i>=0):null,this._enforceSyncProtocolHandshake=t.enforceSyncProtocolHandshake!=null?!!t.enforceSyncProtocolHandshake:null,this._onlineAuthMaxFailedAttempts=t.onlineAuthMaxFailedAttempts!=null?Number(t.onlineAuthMaxFailedAttempts):null,this._onlineAuthLockoutSeconds=t.onlineAuthLockoutSeconds!=null?Number(t.onlineAuthLockoutSeconds):null,this._drRpoTargetMinutes=t.drRpoTargetMinutes!=null?Number(t.drRpoTargetMinutes):null,this._drRtoTargetMinutes=t.drRtoTargetMinutes!=null?Number(t.drRtoTargetMinutes):null,this._backupIntervalMinutes=t.backupIntervalMinutes!=null?Number(t.backupIntervalMinutes):null,this._backupRestoreDrillIntervalHours=t.backupRestoreDrillIntervalHours!=null?Number(t.backupRestoreDrillIntervalHours):null,this._opsAlertSyncFailureRateThresholdPercent=t.opsAlertSyncFailureRateThresholdPercent!=null?Number(t.opsAlertSyncFailureRateThresholdPercent):null,this._opsAlertQueueLatencyThresholdMs=t.opsAlertQueueLatencyThresholdMs!=null?Number(t.opsAlertQueueLatencyThresholdMs):null,this._opsAlertDeadLetterCountThreshold=t.opsAlertDeadLetterCountThreshold!=null?Number(t.opsAlertDeadLetterCountThreshold):null,this._opsAlertEscalationCooldownMinutes=t.opsAlertEscalationCooldownMinutes!=null?Number(t.opsAlertEscalationCooldownMinutes):null,this._auditLogRetentionDays=t.auditLogRetentionDays!=null?Number(t.auditLogRetentionDays):null,this._auditLogArchiveBeforePurge=t.auditLogArchiveBeforePurge!=null?!!t.auditLogArchiveBeforePurge:null,this._auditLogPurgeBatchSize=t.auditLogPurgeBatchSize!=null?Number(t.auditLogPurgeBatchSize):null,this._sessionIdleTimeoutMinutes=t.sessionIdleTimeoutMinutes!=null?Number(t.sessionIdleTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=t.sessionReauthTimeoutMinutes!=null?Number(t.sessionReauthTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=t.apiTimeoutMs!=null?Number(t.apiTimeoutMs):this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=t.syncIntervalMs!=null?Number(t.syncIntervalMs):this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=t.syncMaxRetries!=null?Number(t.syncMaxRetries):this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=t.syncBackoffDelayMs!=null?Number(t.syncBackoffDelayMs):this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=t.syncDebounceMs!=null?Number(t.syncDebounceMs):this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=t.reportingTopSellingLimit!=null?Number(t.reportingTopSellingLimit):this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=t.reportingLowStockLimit!=null?Number(t.reportingLowStockLimit):this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=t.apiBackupListLimit!=null?Number(t.apiBackupListLimit):this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=t.encryptionKey?t.encryptionKey:this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=t.encryptionPassphrase?t.encryptionPassphrase:this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}catch(t){this.context.logError(t,{message:"Gagal mengurai konfigurasi dari storage"})}else{this._lowStockThreshold=this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let t=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE");this._deploymentMode=t==="saas"||t==="standalone"?t:null,this._requireActiveShiftForCash=null,this._maxCashAdjustmentAmount=null,this._requireShiftCloseApprovalOnDifference=null,this._shiftCloseDifferenceApprovalThreshold=null,this._requireReasonForReturnOperations=null,this._requireApprovalForReturnRefund=null,this._requireApprovalForReturnCancel=null,this._requireLotExpiryForPurchaseReceiving=null,this._lotConsumptionPolicy=null,this._enableCustomerCreditPolicy=null,this._customerCreditMaxOutstandingAmount=null,this._customerCreditBlockOnOverdue=null,this._customerCreditOverdueGraceDays=null,this._customerCreditEscalationThresholdDays=null,this._enableReturnFraudGuard=null,this._returnFraudWindowMinutes=null,this._returnFraudMaxEvents=null,this._returnFraudAction=null,this._returnApprovalBypassRoles=null,this._returnApprovalApproverRoles=null,this._allowPromotionStacking=null,this._promotionSelectionStrategy=null,this._promotionStackingOrder=null,this._pricingRoundingIncrement=null,this._pricingRoundingScope=null,this._enableSequentialDocumentNumbers=null,this._syncProtocolVersion=null,this._syncCompatibleServerVersions=null,this._enforceSyncProtocolHandshake=null,this._onlineAuthMaxFailedAttempts=null,this._onlineAuthLockoutSeconds=null,this._drRpoTargetMinutes=null,this._drRtoTargetMinutes=null,this._backupIntervalMinutes=null,this._backupRestoreDrillIntervalHours=null,this._opsAlertSyncFailureRateThresholdPercent=null,this._opsAlertQueueLatencyThresholdMs=null,this._opsAlertDeadLetterCountThreshold=null,this._opsAlertEscalationCooldownMinutes=null,this._auditLogRetentionDays=null,this._auditLogArchiveBeforePurge=null,this._auditLogPurgeBatchSize=null,this._sessionIdleTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}}get apiUrl(){return this._apiUrl||"https://localhost:3000/api"}get lowStockThreshold(){return this._lowStockThreshold!=null?this._lowStockThreshold:10}get paymentSigningKey(){return this._paymentSigningKey||""}get demoMode(){return this._demoMode===!0}get branchId(){return this._branchId}get deploymentMode(){var e;return(e=this._deploymentMode)!=null?e:"standalone"}get requireActiveShiftForCash(){return this._requireActiveShiftForCash===!0}get maxCashAdjustmentAmount(){return this._maxCashAdjustmentAmount}get requireShiftCloseApprovalOnDifference(){return this._requireShiftCloseApprovalOnDifference===!0}get shiftCloseDifferenceApprovalThreshold(){return this._shiftCloseDifferenceApprovalThreshold}get requireReasonForReturnOperations(){return this._requireReasonForReturnOperations===!0}get requireApprovalForReturnRefund(){return this._requireApprovalForReturnRefund===!0}get requireApprovalForReturnCancel(){return this._requireApprovalForReturnCancel===!0}get requireLotExpiryForPurchaseReceiving(){return this._requireLotExpiryForPurchaseReceiving===!0}get lotConsumptionPolicy(){var e;return(e=this._lotConsumptionPolicy)!=null?e:"FEFO"}get enableCustomerCreditPolicy(){return this._enableCustomerCreditPolicy===!0}get customerCreditMaxOutstandingAmount(){return this._customerCreditMaxOutstandingAmount!=null&&this._customerCreditMaxOutstandingAmount>=0?this._customerCreditMaxOutstandingAmount:null}get customerCreditBlockOnOverdue(){return this._customerCreditBlockOnOverdue===!0}get customerCreditOverdueGraceDays(){return this._customerCreditOverdueGraceDays!=null&&this._customerCreditOverdueGraceDays>=0?this._customerCreditOverdueGraceDays:0}get customerCreditEscalationThresholdDays(){return this._customerCreditEscalationThresholdDays!=null&&this._customerCreditEscalationThresholdDays>0?this._customerCreditEscalationThresholdDays:14}get enableReturnFraudGuard(){return this._enableReturnFraudGuard===!0}get returnFraudWindowMinutes(){return this._returnFraudWindowMinutes!=null&&this._returnFraudWindowMinutes>0?this._returnFraudWindowMinutes:60}get returnFraudMaxEvents(){return this._returnFraudMaxEvents!=null&&this._returnFraudMaxEvents>0?this._returnFraudMaxEvents:3}get returnFraudAction(){var e;return(e=this._returnFraudAction)!=null?e:"require_approval"}get returnApprovalBypassRoles(){return this._returnApprovalBypassRoles}get returnApprovalApproverRoles(){return this._returnApprovalApproverRoles}get allowPromotionStacking(){return this._allowPromotionStacking===!0}get promotionSelectionStrategy(){var e;return(e=this._promotionSelectionStrategy)!=null?e:"best_discount"}get promotionStackingOrder(){var e;return(e=this._promotionStackingOrder)!=null?e:"input_order"}get pricingRoundingIncrement(){return this._pricingRoundingIncrement}get pricingRoundingScope(){var e;return(e=this._pricingRoundingScope)!=null?e:"total"}get enableSequentialDocumentNumbers(){return this._enableSequentialDocumentNumbers===!0}get syncProtocolVersion(){return this._syncProtocolVersion!=null&&Number.isInteger(this._syncProtocolVersion)&&this._syncProtocolVersion>=0?this._syncProtocolVersion:1}get syncCompatibleServerVersions(){let e=this._syncCompatibleServerVersions,t=[...un],r=Array.isArray(e)?e.filter(i=>Number.isInteger(i)&&i>=0):t,n=r.includes(this.syncProtocolVersion)?r:[this.syncProtocolVersion,...r];return Array.from(new Set(n))}get enforceSyncProtocolHandshake(){return this._enforceSyncProtocolHandshake===!0}get onlineAuthMaxFailedAttempts(){return this._onlineAuthMaxFailedAttempts!=null&&this._onlineAuthMaxFailedAttempts>0?this._onlineAuthMaxFailedAttempts:5}get onlineAuthLockoutSeconds(){return this._onlineAuthLockoutSeconds!=null&&this._onlineAuthLockoutSeconds>0?this._onlineAuthLockoutSeconds:60}get drRpoTargetMinutes(){return this._drRpoTargetMinutes!=null&&this._drRpoTargetMinutes>0?this._drRpoTargetMinutes:1440}get drRtoTargetMinutes(){return this._drRtoTargetMinutes!=null&&this._drRtoTargetMinutes>0?this._drRtoTargetMinutes:240}get backupIntervalMinutes(){return this._backupIntervalMinutes!=null&&this._backupIntervalMinutes>0?this._backupIntervalMinutes:360}get backupRestoreDrillIntervalHours(){return this._backupRestoreDrillIntervalHours!=null&&this._backupRestoreDrillIntervalHours>0?this._backupRestoreDrillIntervalHours:168}get opsAlertSyncFailureRateThresholdPercent(){return this._opsAlertSyncFailureRateThresholdPercent!=null&&this._opsAlertSyncFailureRateThresholdPercent>0?this._opsAlertSyncFailureRateThresholdPercent:30}get opsAlertQueueLatencyThresholdMs(){return this._opsAlertQueueLatencyThresholdMs!=null&&this._opsAlertQueueLatencyThresholdMs>0?this._opsAlertQueueLatencyThresholdMs:300*1e3}get opsAlertDeadLetterCountThreshold(){return this._opsAlertDeadLetterCountThreshold!=null&&this._opsAlertDeadLetterCountThreshold>0?this._opsAlertDeadLetterCountThreshold:10}get opsAlertEscalationCooldownMinutes(){return this._opsAlertEscalationCooldownMinutes!=null&&this._opsAlertEscalationCooldownMinutes>0?this._opsAlertEscalationCooldownMinutes:15}get auditLogRetentionDays(){return this._auditLogRetentionDays!=null&&this._auditLogRetentionDays>0?this._auditLogRetentionDays:365}get auditLogArchiveBeforePurge(){return this._auditLogArchiveBeforePurge!==!1}get auditLogPurgeBatchSize(){return this._auditLogPurgeBatchSize!=null&&this._auditLogPurgeBatchSize>0?this._auditLogPurgeBatchSize:500}get sessionIdleTimeoutMinutes(){return this._sessionIdleTimeoutMinutes!=null&&this._sessionIdleTimeoutMinutes>0?this._sessionIdleTimeoutMinutes:5}get sessionReauthTimeoutMinutes(){return this._sessionReauthTimeoutMinutes!=null&&this._sessionReauthTimeoutMinutes>0?this._sessionReauthTimeoutMinutes:1}get apiTimeoutMs(){return this._apiTimeoutMs!=null&&this._apiTimeoutMs>0?this._apiTimeoutMs:5e3}get syncIntervalMs(){return this._syncIntervalMs!=null&&this._syncIntervalMs>0?this._syncIntervalMs:300*1e3}get syncMaxRetries(){return this._syncMaxRetries!=null&&this._syncMaxRetries>0?this._syncMaxRetries:5}get syncBackoffDelayMs(){return this._syncBackoffDelayMs!=null&&this._syncBackoffDelayMs>0?this._syncBackoffDelayMs:1e3}get syncDebounceMs(){return this._syncDebounceMs!=null&&this._syncDebounceMs>0?this._syncDebounceMs:2e3}get reportingTopSellingLimit(){return this._reportingTopSellingLimit!=null&&this._reportingTopSellingLimit>0?this._reportingTopSellingLimit:5}get reportingLowStockLimit(){return this._reportingLowStockLimit!=null&&this._reportingLowStockLimit>0?this._reportingLowStockLimit:10}get apiBackupListLimit(){return this._apiBackupListLimit!=null&&this._apiBackupListLimit>0?this._apiBackupListLimit:10}get encryptionKey(){return this._encryptionKey||"default_secret_key"}get encryptionPassphrase(){return this._encryptionPassphrase||"default_passphrase"}validateConfig(e){var Z,te,X,Y,ye,se,Ne,ve,Te,pe,We,Ye,Xe,ut,vt,ct,qe,ke,Ue,bt,wt,dt,ht,ft,Et,Ot,lt,st,S,C,k,N,W,me,be,ee,$;let t=(Z=e.requireShiftCloseApprovalOnDifference)!=null?Z:this.requireShiftCloseApprovalOnDifference,r=(te=e.shiftCloseDifferenceApprovalThreshold)!=null?te:this.shiftCloseDifferenceApprovalThreshold,n=(X=e.requireApprovalForReturnRefund)!=null?X:this.requireApprovalForReturnRefund,i=(Y=e.requireApprovalForReturnCancel)!=null?Y:this.requireApprovalForReturnCancel,a=(ye=e.returnApprovalApproverRoles)!=null?ye:this.returnApprovalApproverRoles,o=(se=e.enableReturnFraudGuard)!=null?se:this.enableReturnFraudGuard,s=(Ne=e.returnFraudWindowMinutes)!=null?Ne:this.returnFraudWindowMinutes,c=(ve=e.returnFraudMaxEvents)!=null?ve:this.returnFraudMaxEvents,u=(Te=e.syncProtocolVersion)!=null?Te:this.syncProtocolVersion,l=(pe=e.syncCompatibleServerVersions)!=null?pe:this.syncCompatibleServerVersions,d=(We=e.enforceSyncProtocolHandshake)!=null?We:this.enforceSyncProtocolHandshake;if(e.maxCashAdjustmentAmount!=null&&e.maxCashAdjustmentAmount<=0)throw new Error("Invalid config: maxCashAdjustmentAmount must be greater than 0");if(t===!0&&(r==null||r<0))throw new Error("Invalid config: shiftCloseDifferenceApprovalThreshold is required and must be >= 0 when requireShiftCloseApprovalOnDifference=true");if(e.pricingRoundingIncrement!=null&&e.pricingRoundingIncrement<=0)throw new Error("Invalid config: pricingRoundingIncrement must be greater than 0");let m=(Ye=e.enableCustomerCreditPolicy)!=null?Ye:this.enableCustomerCreditPolicy,f=(Xe=e.customerCreditMaxOutstandingAmount)!=null?Xe:this.customerCreditMaxOutstandingAmount,y=(ut=e.customerCreditOverdueGraceDays)!=null?ut:this.customerCreditOverdueGraceDays,v=(vt=e.customerCreditEscalationThresholdDays)!=null?vt:this.customerCreditEscalationThresholdDays;if(m){if(f!=null&&f<0)throw new Error("Invalid config: customerCreditMaxOutstandingAmount must be >= 0");if(!Number.isInteger(y)||y<0)throw new Error("Invalid config: customerCreditOverdueGraceDays must be integer >= 0");if(!Number.isInteger(v)||v<=0)throw new Error("Invalid config: customerCreditEscalationThresholdDays must be integer > 0")}if((n===!0||i===!0)&&(!a||a.length===0))throw new Error("Invalid config: returnApprovalApproverRoles is required when return approval is enabled");if(o===!0){if(s==null||s<=0)throw new Error("Invalid config: returnFraudWindowMinutes must be greater than 0 when enableReturnFraudGuard=true");if(c==null||c<=0)throw new Error("Invalid config: returnFraudMaxEvents must be greater than 0 when enableReturnFraudGuard=true")}if(!Number.isInteger(u)||u<0)throw new Error("Invalid config: syncProtocolVersion must be a non-negative integer");if(!Array.isArray(l)||l.length===0)throw new Error("Invalid config: syncCompatibleServerVersions must contain at least one version");if(!l.every(V=>Number.isInteger(V)&&V>=0))throw new Error("Invalid config: syncCompatibleServerVersions must contain only non-negative integers");if(!l.includes(u))throw new Error("Invalid config: syncCompatibleServerVersions must include syncProtocolVersion");if(d===!0&&l.length===0)throw new Error("Invalid config: enforceSyncProtocolHandshake requires non-empty syncCompatibleServerVersions");let p=(ct=e.onlineAuthMaxFailedAttempts)!=null?ct:this.onlineAuthMaxFailedAttempts,g=(qe=e.onlineAuthLockoutSeconds)!=null?qe:this.onlineAuthLockoutSeconds,x=(ke=e.drRpoTargetMinutes)!=null?ke:this.drRpoTargetMinutes,b=(Ue=e.drRtoTargetMinutes)!=null?Ue:this.drRtoTargetMinutes,A=(bt=e.backupIntervalMinutes)!=null?bt:this.backupIntervalMinutes,I=(wt=e.backupRestoreDrillIntervalHours)!=null?wt:this.backupRestoreDrillIntervalHours,F=(dt=e.opsAlertSyncFailureRateThresholdPercent)!=null?dt:this.opsAlertSyncFailureRateThresholdPercent,w=(ht=e.opsAlertQueueLatencyThresholdMs)!=null?ht:this.opsAlertQueueLatencyThresholdMs,q=(ft=e.opsAlertDeadLetterCountThreshold)!=null?ft:this.opsAlertDeadLetterCountThreshold,M=(Et=e.opsAlertEscalationCooldownMinutes)!=null?Et:this.opsAlertEscalationCooldownMinutes,E=(Ot=e.auditLogRetentionDays)!=null?Ot:this.auditLogRetentionDays,L=(lt=e.auditLogPurgeBatchSize)!=null?lt:this.auditLogPurgeBatchSize;if(!Number.isInteger(p)||p<=0)throw new Error("Invalid config: onlineAuthMaxFailedAttempts must be a positive integer");if(!Number.isInteger(g)||g<=0)throw new Error("Invalid config: onlineAuthLockoutSeconds must be a positive integer");if(!Number.isInteger(x)||x<=0)throw new Error("Invalid config: drRpoTargetMinutes must be a positive integer");if(!Number.isInteger(b)||b<=0)throw new Error("Invalid config: drRtoTargetMinutes must be a positive integer");if(!Number.isInteger(A)||A<=0)throw new Error("Invalid config: backupIntervalMinutes must be a positive integer");if(!Number.isInteger(I)||I<=0)throw new Error("Invalid config: backupRestoreDrillIntervalHours must be a positive integer");if(A>x)throw new Error("Invalid config: backupIntervalMinutes must be <= drRpoTargetMinutes");if(!Number.isInteger(F)||F<=0||F>100)throw new Error("Invalid config: opsAlertSyncFailureRateThresholdPercent must be an integer in range 1..100");if(!Number.isInteger(w)||w<=0)throw new Error("Invalid config: opsAlertQueueLatencyThresholdMs must be a positive integer");if(!Number.isInteger(q)||q<=0)throw new Error("Invalid config: opsAlertDeadLetterCountThreshold must be a positive integer");if(!Number.isInteger(M)||M<=0)throw new Error("Invalid config: opsAlertEscalationCooldownMinutes must be a positive integer");if(!Number.isInteger(E)||E<=0)throw new Error("Invalid config: auditLogRetentionDays must be a positive integer");if(!Number.isInteger(L)||L<=0)throw new Error("Invalid config: auditLogPurgeBatchSize must be a positive integer");let Q=(st=e.sessionIdleTimeoutMinutes)!=null?st:this.sessionIdleTimeoutMinutes,T=(S=e.sessionReauthTimeoutMinutes)!=null?S:this.sessionReauthTimeoutMinutes;if(!Number.isInteger(Q)||Q<=0)throw new Error("Invalid config: sessionIdleTimeoutMinutes must be positive");if(!Number.isInteger(T)||T<=0)throw new Error("Invalid config: sessionReauthTimeoutMinutes must be positive");let j=(C=e.apiTimeoutMs)!=null?C:this.apiTimeoutMs,z=(k=e.syncIntervalMs)!=null?k:this.syncIntervalMs,B=(N=e.syncMaxRetries)!=null?N:this.syncMaxRetries,U=(W=e.syncBackoffDelayMs)!=null?W:this.syncBackoffDelayMs,O=(me=e.syncDebounceMs)!=null?me:this.syncDebounceMs,_=(be=e.reportingTopSellingLimit)!=null?be:this.reportingTopSellingLimit,R=(ee=e.reportingLowStockLimit)!=null?ee:this.reportingLowStockLimit,D=($=e.apiBackupListLimit)!=null?$:this.apiBackupListLimit;if(!Number.isInteger(j)||j<=0)throw new Error("Invalid config: apiTimeoutMs must be positive");if(!Number.isInteger(z)||z<=0)throw new Error("Invalid config: syncIntervalMs must be positive");if(!Number.isInteger(B)||B<=0)throw new Error("Invalid config: syncMaxRetries must be positive");if(!Number.isInteger(U)||U<=0)throw new Error("Invalid config: syncBackoffDelayMs must be positive");if(!Number.isInteger(O)||O<=0)throw new Error("Invalid config: syncDebounceMs must be positive");if(!Number.isInteger(_)||_<=0)throw new Error("Invalid config: reportingTopSellingLimit must be positive");if(!Number.isInteger(R)||R<=0)throw new Error("Invalid config: reportingLowStockLimit must be positive");if(!Number.isInteger(D)||D<=0)throw new Error("Invalid config: apiBackupListLimit must be positive")}async setConfig(e){this.validateConfig(e),e.lowStockThreshold!==void 0&&(this._lowStockThreshold=e.lowStockThreshold),e.paymentSigningKey!==void 0&&(this._paymentSigningKey=e.paymentSigningKey),e.apiUrl!==void 0&&(this._apiUrl=e.apiUrl),e.branchId!==void 0&&(this._branchId=e.branchId),e.demoMode!==void 0&&(this._demoMode=e.demoMode),e.deploymentMode!==void 0&&(this._deploymentMode=e.deploymentMode),e.requireActiveShiftForCash!==void 0&&(this._requireActiveShiftForCash=e.requireActiveShiftForCash),e.maxCashAdjustmentAmount!==void 0&&(this._maxCashAdjustmentAmount=e.maxCashAdjustmentAmount),e.requireShiftCloseApprovalOnDifference!==void 0&&(this._requireShiftCloseApprovalOnDifference=e.requireShiftCloseApprovalOnDifference),e.shiftCloseDifferenceApprovalThreshold!==void 0&&(this._shiftCloseDifferenceApprovalThreshold=e.shiftCloseDifferenceApprovalThreshold),e.requireReasonForReturnOperations!==void 0&&(this._requireReasonForReturnOperations=e.requireReasonForReturnOperations),e.requireApprovalForReturnRefund!==void 0&&(this._requireApprovalForReturnRefund=e.requireApprovalForReturnRefund),e.requireApprovalForReturnCancel!==void 0&&(this._requireApprovalForReturnCancel=e.requireApprovalForReturnCancel),e.requireLotExpiryForPurchaseReceiving!==void 0&&(this._requireLotExpiryForPurchaseReceiving=e.requireLotExpiryForPurchaseReceiving),e.lotConsumptionPolicy!==void 0&&(this._lotConsumptionPolicy=e.lotConsumptionPolicy),e.enableCustomerCreditPolicy!==void 0&&(this._enableCustomerCreditPolicy=e.enableCustomerCreditPolicy),e.customerCreditMaxOutstandingAmount!==void 0&&(this._customerCreditMaxOutstandingAmount=e.customerCreditMaxOutstandingAmount),e.customerCreditBlockOnOverdue!==void 0&&(this._customerCreditBlockOnOverdue=e.customerCreditBlockOnOverdue),e.customerCreditOverdueGraceDays!==void 0&&(this._customerCreditOverdueGraceDays=e.customerCreditOverdueGraceDays),e.customerCreditEscalationThresholdDays!==void 0&&(this._customerCreditEscalationThresholdDays=e.customerCreditEscalationThresholdDays),e.enableReturnFraudGuard!==void 0&&(this._enableReturnFraudGuard=e.enableReturnFraudGuard),e.returnFraudWindowMinutes!==void 0&&(this._returnFraudWindowMinutes=e.returnFraudWindowMinutes),e.returnFraudMaxEvents!==void 0&&(this._returnFraudMaxEvents=e.returnFraudMaxEvents),e.returnFraudAction!==void 0&&(this._returnFraudAction=e.returnFraudAction),e.returnApprovalBypassRoles!==void 0&&(this._returnApprovalBypassRoles=e.returnApprovalBypassRoles),e.returnApprovalApproverRoles!==void 0&&(this._returnApprovalApproverRoles=e.returnApprovalApproverRoles),e.allowPromotionStacking!==void 0&&(this._allowPromotionStacking=e.allowPromotionStacking),e.promotionSelectionStrategy!==void 0&&(this._promotionSelectionStrategy=e.promotionSelectionStrategy),e.promotionStackingOrder!==void 0&&(this._promotionStackingOrder=e.promotionStackingOrder),e.pricingRoundingIncrement!==void 0&&(this._pricingRoundingIncrement=e.pricingRoundingIncrement),e.pricingRoundingScope!==void 0&&(this._pricingRoundingScope=e.pricingRoundingScope),e.enableSequentialDocumentNumbers!==void 0&&(this._enableSequentialDocumentNumbers=e.enableSequentialDocumentNumbers),e.syncProtocolVersion!==void 0&&(this._syncProtocolVersion=e.syncProtocolVersion),e.syncCompatibleServerVersions!==void 0&&(this._syncCompatibleServerVersions=e.syncCompatibleServerVersions),e.enforceSyncProtocolHandshake!==void 0&&(this._enforceSyncProtocolHandshake=e.enforceSyncProtocolHandshake),e.onlineAuthMaxFailedAttempts!==void 0&&(this._onlineAuthMaxFailedAttempts=e.onlineAuthMaxFailedAttempts),e.onlineAuthLockoutSeconds!==void 0&&(this._onlineAuthLockoutSeconds=e.onlineAuthLockoutSeconds),e.drRpoTargetMinutes!==void 0&&(this._drRpoTargetMinutes=e.drRpoTargetMinutes),e.drRtoTargetMinutes!==void 0&&(this._drRtoTargetMinutes=e.drRtoTargetMinutes),e.backupIntervalMinutes!==void 0&&(this._backupIntervalMinutes=e.backupIntervalMinutes),e.backupRestoreDrillIntervalHours!==void 0&&(this._backupRestoreDrillIntervalHours=e.backupRestoreDrillIntervalHours),e.opsAlertSyncFailureRateThresholdPercent!==void 0&&(this._opsAlertSyncFailureRateThresholdPercent=e.opsAlertSyncFailureRateThresholdPercent),e.opsAlertQueueLatencyThresholdMs!==void 0&&(this._opsAlertQueueLatencyThresholdMs=e.opsAlertQueueLatencyThresholdMs),e.opsAlertDeadLetterCountThreshold!==void 0&&(this._opsAlertDeadLetterCountThreshold=e.opsAlertDeadLetterCountThreshold),e.opsAlertEscalationCooldownMinutes!==void 0&&(this._opsAlertEscalationCooldownMinutes=e.opsAlertEscalationCooldownMinutes),e.auditLogRetentionDays!==void 0&&(this._auditLogRetentionDays=e.auditLogRetentionDays),e.auditLogArchiveBeforePurge!==void 0&&(this._auditLogArchiveBeforePurge=e.auditLogArchiveBeforePurge),e.auditLogPurgeBatchSize!==void 0&&(this._auditLogPurgeBatchSize=e.auditLogPurgeBatchSize),e.sessionIdleTimeoutMinutes!==void 0&&(this._sessionIdleTimeoutMinutes=e.sessionIdleTimeoutMinutes),e.sessionReauthTimeoutMinutes!==void 0&&(this._sessionReauthTimeoutMinutes=e.sessionReauthTimeoutMinutes),e.apiTimeoutMs!==void 0&&(this._apiTimeoutMs=e.apiTimeoutMs),e.syncIntervalMs!==void 0&&(this._syncIntervalMs=e.syncIntervalMs),e.syncMaxRetries!==void 0&&(this._syncMaxRetries=e.syncMaxRetries),e.syncBackoffDelayMs!==void 0&&(this._syncBackoffDelayMs=e.syncBackoffDelayMs),e.syncDebounceMs!==void 0&&(this._syncDebounceMs=e.syncDebounceMs),e.reportingTopSellingLimit!==void 0&&(this._reportingTopSellingLimit=e.reportingTopSellingLimit),e.reportingLowStockLimit!==void 0&&(this._reportingLowStockLimit=e.reportingLowStockLimit),e.apiBackupListLimit!==void 0&&(this._apiBackupListLimit=e.apiBackupListLimit),e.encryptionKey!==void 0&&(this._encryptionKey=e.encryptionKey),e.encryptionPassphrase!==void 0&&(this._encryptionPassphrase=e.encryptionPassphrase);let t={lowStockThreshold:this._lowStockThreshold,paymentSigningKey:this._paymentSigningKey,apiUrl:this._apiUrl,branchId:this._branchId,demoMode:this._demoMode,deploymentMode:this._deploymentMode,requireActiveShiftForCash:this._requireActiveShiftForCash,maxCashAdjustmentAmount:this._maxCashAdjustmentAmount,requireShiftCloseApprovalOnDifference:this._requireShiftCloseApprovalOnDifference,shiftCloseDifferenceApprovalThreshold:this._shiftCloseDifferenceApprovalThreshold,requireReasonForReturnOperations:this._requireReasonForReturnOperations,requireApprovalForReturnRefund:this._requireApprovalForReturnRefund,requireApprovalForReturnCancel:this._requireApprovalForReturnCancel,requireLotExpiryForPurchaseReceiving:this._requireLotExpiryForPurchaseReceiving,lotConsumptionPolicy:this._lotConsumptionPolicy,enableCustomerCreditPolicy:this._enableCustomerCreditPolicy,customerCreditMaxOutstandingAmount:this._customerCreditMaxOutstandingAmount,customerCreditBlockOnOverdue:this._customerCreditBlockOnOverdue,customerCreditOverdueGraceDays:this._customerCreditOverdueGraceDays,customerCreditEscalationThresholdDays:this._customerCreditEscalationThresholdDays,enableReturnFraudGuard:this._enableReturnFraudGuard,returnFraudWindowMinutes:this._returnFraudWindowMinutes,returnFraudMaxEvents:this._returnFraudMaxEvents,returnFraudAction:this._returnFraudAction,returnApprovalBypassRoles:this._returnApprovalBypassRoles,returnApprovalApproverRoles:this._returnApprovalApproverRoles,allowPromotionStacking:this._allowPromotionStacking,promotionSelectionStrategy:this._promotionSelectionStrategy,promotionStackingOrder:this._promotionStackingOrder,pricingRoundingIncrement:this._pricingRoundingIncrement,pricingRoundingScope:this._pricingRoundingScope,enableSequentialDocumentNumbers:this._enableSequentialDocumentNumbers,syncProtocolVersion:this._syncProtocolVersion,syncCompatibleServerVersions:this._syncCompatibleServerVersions,enforceSyncProtocolHandshake:this._enforceSyncProtocolHandshake,onlineAuthMaxFailedAttempts:this._onlineAuthMaxFailedAttempts,onlineAuthLockoutSeconds:this._onlineAuthLockoutSeconds,drRpoTargetMinutes:this._drRpoTargetMinutes,drRtoTargetMinutes:this._drRtoTargetMinutes,backupIntervalMinutes:this._backupIntervalMinutes,backupRestoreDrillIntervalHours:this._backupRestoreDrillIntervalHours,opsAlertSyncFailureRateThresholdPercent:this._opsAlertSyncFailureRateThresholdPercent,opsAlertQueueLatencyThresholdMs:this._opsAlertQueueLatencyThresholdMs,opsAlertDeadLetterCountThreshold:this._opsAlertDeadLetterCountThreshold,opsAlertEscalationCooldownMinutes:this._opsAlertEscalationCooldownMinutes,auditLogRetentionDays:this._auditLogRetentionDays,auditLogArchiveBeforePurge:this._auditLogArchiveBeforePurge,auditLogPurgeBatchSize:this._auditLogPurgeBatchSize,sessionIdleTimeoutMinutes:this._sessionIdleTimeoutMinutes,sessionReauthTimeoutMinutes:this._sessionReauthTimeoutMinutes,apiTimeoutMs:this._apiTimeoutMs,syncIntervalMs:this._syncIntervalMs,syncMaxRetries:this._syncMaxRetries,syncBackoffDelayMs:this._syncBackoffDelayMs,syncDebounceMs:this._syncDebounceMs,reportingTopSellingLimit:this._reportingTopSellingLimit,reportingLowStockLimit:this._reportingLowStockLimit,apiBackupListLimit:this._apiBackupListLimit,encryptionKey:this._encryptionKey,encryptionPassphrase:this._encryptionPassphrase};return await this.storage.setItem("config",JSON.stringify(t)),t}};var za="com.offlinepos.backup",qr=class{constructor(e,t){this.context=e;this.timer=t;this.backupTimerInstance=null;this.restoreDrillTimerInstance=null;this.pendingBackupPayload=null;this.lastBackupAt=null;this.lastRestoreDrillAt=null}start(e,t){if(this.backupTimerInstance){console.warn("[BackupScheduler] Already started");return}this.backupTimerInstance=this.timer.setInterval(()=>this.runBackupTask().catch(()=>{}),e),t&&t>0&&(this.restoreDrillTimerInstance=this.timer.setInterval(()=>this.runRestoreDrill().catch(()=>{}),t)),typeof window!="undefined"&&window.addEventListener&&(this.onlineHandler=()=>{this.pendingBackupPayload&&this.runBackupTask().catch(()=>{})},window.addEventListener("online",this.onlineHandler))}stop(){this.backupTimerInstance&&(this.backupTimerInstance.clear(),this.backupTimerInstance=null),this.restoreDrillTimerInstance&&(this.restoreDrillTimerInstance.clear(),this.restoreDrillTimerInstance=null),typeof window!="undefined"&&window.removeEventListener&&this.onlineHandler&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=void 0),this.context.logInfo("[BackupScheduler] Stopped")}getState(){return{pendingBackup:!!this.pendingBackupPayload,lastBackupAt:this.lastBackupAt,lastRestoreDrillAt:this.lastRestoreDrillAt,started:!!this.backupTimerInstance}}async runBackupTask(){var t;this.apiService||(this.apiService=(t=this.context.integrationServices)==null?void 0:t.api);let e=za;this.context.logInfo(`[BackupScheduler] Starting backup task: ${e}`);try{this.pendingBackupPayload&&(await this.apiService.createBackup(this.pendingBackupPayload),this.context.logInfo("[BackupScheduler] Flushed pending backup payload"),this.pendingBackupPayload=null);let r={label:`scheduled-${new Date().toISOString()}`,reason:"scheduled-backup"};await this.apiService.createBackup(r),this.lastBackupAt=Date.now(),this.context.logInfo(`[BackupScheduler] Backup task completed: ${e}`)}catch(r){this.context.logError(r,{message:`[BackupScheduler] Error in backup task: ${e}`}),this.pendingBackupPayload={label:`retry-${new Date().toISOString()}`,reason:"retry-pending-backup"}}}async runRestoreDrill(){var e;this.apiService||(this.apiService=(e=this.context.integrationServices)==null?void 0:e.api);try{let t=await this.apiService.listBackups({limit:10});if(!Array.isArray(t)||t.length===0){this.context.logInfo("[BackupScheduler] Restore drill skipped: no backups available");return}let r=t.find(i=>((i==null?void 0:i.status)||"ready")==="ready")||t[0],n=String((r==null?void 0:r.id)||(r==null?void 0:r.backupId)||"").trim();if(!n){this.context.logInfo("[BackupScheduler] Restore drill skipped: backupId missing");return}await this.apiService.restoreBackup({backupId:n,dryRun:!0,reason:"scheduled-restore-drill"}),this.lastRestoreDrillAt=Date.now(),this.context.logInfo(`[BackupScheduler] Restore drill completed for backupId=${n}`)}catch(t){this.context.logError(t,{message:"[BackupScheduler] Restore drill failed"})}}};var Lr=class h{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,c,u,l,d;this.context.integrationServices=this,this.activityLogger=(r=t.activityLogger)!=null?r:new Cr(this.context),this.config=(n=t.configService)!=null?n:new Mr(this.context),this.authorization=(i=t.authorizationService)!=null?i:new Er(this.context),this.encryption=(a=t.encryptionService)!=null?a:new _r(this.context),this.api=(o=t.apiService)!=null?o:new kr(this.context),this.sync=(s=t.syncService)!=null?s:new Tt,this.socket=(c=t.socketService)!=null?c:new Bt,this.notification=(u=t.notificationService)!=null?u:new Fr(this.context),this.user=(l=t.userService)!=null?l:new Tr(this.context),this.backupScheduler=(d=t.backupScheduler)!=null?d:new qr(this.context,{setInterval(m,f){let y=setInterval(m,f);return{clear:()=>clearInterval(y)}}})}static async create(e,t={}){let r=new h(e,t);return r.config.init&&await r.config.init(),r}async shutdown(){var n;let e=this.sync;e&&typeof e.shutdown=="function"&&await e.shutdown();let t=this.socket;if(t&&typeof t.shutdown=="function")t.shutdown();else if(t&&typeof t.getSocket=="function"){let i=t.getSocket();(n=i==null?void 0:i.disconnect)==null||n.call(i)}let r=this.backupScheduler;r&&typeof r.stop=="function"&&r.stop()}};var yi=[{toVersion:1,up:async h=>{for(let e of xt)await h.addTable(e)}}];async function vi(h,e){if(typeof h.getSchemaVersion!="function"||typeof h.setSchemaVersion!="function"){let t="Adapter does not support schema versioning (getSchemaVersion/setSchemaVersion required)";throw e.logError(new Error(t),{message:t}),new Error(t)}e.logInfo("Starting database migration process");try{let t=await h.getSchemaVersion();(t==null||t<0)&&(t=0);let r=[...yi].sort((i,a)=>i.toVersion-a.toVersion),n=r.length>0?r[r.length-1].toVersion:0;if(t>=n){e.logInfo(`Database is already up-to-date at v${t}`);return}e.logInfo(`Migrating database from v${t} to v${n}`);for(let i of r)i.toVersion>t&&(e.logInfo(`Applying migration: v${i.toVersion}`),await i.up(h),await h.setSchemaVersion(i.toVersion),t=i.toVersion);e.logInfo("Database migration completed successfully")}catch(t){throw e.logError(t,{message:"Database migration failed"}),t}}var ja={isLoggedIn:!1,userId:null,user:null,lastLoginAt:null,tenantId:null},Nr=class{constructor(e){this.context=e;this.lastBlurAt=null;this.activityEvents=["mousemove","mousedown","keydown","scroll","touchstart","focus"];this.onActivity=()=>this.resetIdleTimer();this.onBlur=()=>{this.lastBlurAt=Date.now()};this.onFocus=()=>{this.lastBlurAt&&Date.now()-this.lastBlurAt>this.reauthTimeoutMs&&this.emitter.emit("reauthenticate"),this.lastBlurAt=null};this.emitter=_t(),this.state={...ja},this.emitter.emit("update",this.getState()),this.state.isLoggedIn&&this.resetIdleTimer(),this.setupActivityListeners()}get idleTimeoutMs(){var e;return(((e=this.context.config)==null?void 0:e.sessionIdleTimeoutMinutes)||5)*60*1e3}get reauthTimeoutMs(){var e;return(((e=this.context.config)==null?void 0:e.sessionReauthTimeoutMinutes)||1)*60*1e3}subscribe(e){return e(this.state),this.emitter.on("update",e),()=>this.emitter.off("update",e)}onReauthenticate(e){return this.emitter.on("reauthenticate",e),()=>this.emitter.off("reauthenticate",e)}getState(){return{...this.state}}setupActivityListeners(){typeof window!="undefined"&&window.addEventListener&&(this.activityEvents.forEach(e=>window.addEventListener(e,this.onActivity)),window.addEventListener("blur",this.onBlur),window.addEventListener("focus",this.onFocus))}shutdown(){this.clearIdleTimer(),typeof window!="undefined"&&window.removeEventListener&&(this.activityEvents.forEach(e=>window.removeEventListener(e,this.onActivity)),window.removeEventListener("blur",this.onBlur),window.removeEventListener("focus",this.onFocus))}startIdleTimer(){this.clearIdleTimer(),typeof window!="undefined"&&(this.idleTimerId=window.setTimeout(()=>this.handleIdleLogout(),this.idleTimeoutMs))}resetIdleTimer(){this.state.isLoggedIn&&this.startIdleTimer()}clearIdleTimer(){this.idleTimerId!=null&&(clearTimeout(this.idleTimerId),this.idleTimerId=void 0)}handleIdleLogout(){this.context.logInfo("Auto-logout karena tidak aktif"),this.logout()}login(e){this.setState({isLoggedIn:!0,userId:e.id,user:e,lastLoginAt:Date.now(),tenantId:e.tenantId||null}),this.context.logInfo(`User ${e.id} (${e.username}) logged in`),this.startIdleTimer()}logout(){var e;this.clearIdleTimer(),this.setState({isLoggedIn:!1,userId:null,user:null,tenantId:null}),this.context.logInfo("User logged out");try{let t=(e=this.context.integrationServices)==null?void 0:e.encryption;t&&typeof t.setItem=="function"&&t.setItem("auth_token","")}catch{}}setState(e){this.state={...this.state,...e},this.emitter.emit("update",this.getState())}};var kt=class{constructor(){this.eventBus=Le;this.domainServiceOverrides={};this.integrationServiceOverrides={};this.pluginSpecs=[];this.authBridgePolicyMode="bridge-required";this.runtimeStateStore=(0,Wn.createStore)({phase:"idle",started:!1,startCount:0,stopCount:0,lastError:null,lastTransitionAt:new Date().toISOString()}),this.runtimeStore=(0,Wn.asReadonlyStore)(this.runtimeStateStore),this.runtime=this.createRuntime()}getSyncStore(){return this.syncStore}getDomainChangeQueueState(){var e,t;return(t=(e=this.syncStore)==null?void 0:e.getState())!=null?t:{...Dt}}subscribeDomainChangeQueue(e){return this.syncStore?this.syncStore.subscribe(e):(e({...Dt}),()=>{})}getQueuedDomainChanges(){return[...this.getDomainChangeQueueState().queue]}enqueueDomainChange(e){var t;if(this.domainChangeSink){this.domainChangeSink(e);return}(t=this.syncStore)==null||t.enqueueChange(e)}removeDomainQueuedChange(e){var t;(t=this.syncStore)==null||t.removeQueuedChange(e)}setDomainChangeSink(e){this.domainChangeSink=e}getSessionStore(){return this.sessionStore}get session(){var e;return(e=this.sessionStore)==null?void 0:e.getState()}static builder(){return new bi}use(e,t,r=[]){if(this.pluginSpecs.some(i=>i.name===e))return this;let n={name:e,init:t,deps:r};return this.pluginSpecs.push(n),this.runtime.use(e,async()=>{await t(this)},r),this}async stop(){this.runtimeStateStore.setState({phase:"stopping",started:this.runtime.isStarted(),lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.stop(),this.runtimeStateStore.setState(e=>({...e,phase:"stopped",started:!1,stopCount:e.stopCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(e){throw this.runtimeStateStore.setState({phase:"error",started:this.runtime.isStarted(),lastError:e instanceof Error?e.message:String(e),lastTransitionAt:new Date().toISOString()}),e}}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.syncStore=void 0,this.sessionStore=void 0,this.pluginSpecs=[],this.domainServiceOverrides={},this.integrationServiceOverrides={},this.runtime=this.createRuntime()}async restart(){let e=[...this.pluginSpecs],t={...this.domainServiceOverrides},r={...this.integrationServiceOverrides};await this.reset(),this.domainServiceOverrides=t,this.integrationServiceOverrides=r,this.runtime=this.createRuntime();for(let n of e)this.use(n.name,n.init,n.deps);return this.start()}async init(e={runMigrations:!0}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.init({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}async start(e={}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.start({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}checksum(e){return gr(e,this)}logInfo(e,t){var r,n,i;(n=(r=this.registry)==null?void 0:r.loggerAdapter)!=null&&n.logInfo&&((i=this.registry)==null||i.loggerAdapter.logInfo(e,t))}logError(e,t){var r,n,i;(n=(r=this.registry)==null?void 0:r.loggerAdapter)!=null&&n.logError&&((i=this.registry)==null||i.loggerAdapter.logError(e,t))}initNotifications(){var e;(e=this.integrationServices)==null||e.notification.initNotifications()}notify(e,t){var r;(r=this.integrationServices)==null||r.notification.notify(e,t)}get config(){var e;return(e=this.integrationServices)==null?void 0:e.config}isOnline(){var e;return(e=this.registry)==null?void 0:e.platformAdapter.isOnline()}createCorrelationId(e="cid"){return this.runtime.createCorrelationId(e)}async logActivity(e,t={},r){var n,i;try{await((i=this.integrationServices)==null?void 0:i.activityLogger.logActivity(e,((n=this.session)==null?void 0:n.userId)||"system",t,r))}catch(a){this.logError(a,{fn:"logActivity",action:e})}}createRuntime(){let e=Ka.CoreRuntime.builder().build();e.setHooks({runMigrations:async()=>{var n,i;let t=(n=this.registry)==null?void 0:n.dbAdapter,r=(i=this.registry)==null?void 0:i.loggerAdapter;await vi(t,r)},onInit:async()=>{!this.domainChangeSink&&!this.syncStore&&(this.syncStore=new Pr(this)),this.sessionStore||(this.sessionStore=new Nr(this))},createDomainServices:()=>(this.domainServices||(this.domainServices=new Dr(this,this.domainServiceOverrides)),this.domainServices),createIntegrationServices:async()=>(this.integrationServices||(this.integrationServices=await Lr.create(this,this.integrationServiceOverrides)),this.integrationServices),onStop:async()=>{this.sessionStore&&typeof this.sessionStore.shutdown=="function"&&await this.sessionStore.shutdown(),this.syncStore&&typeof this.syncStore.shutdown=="function"&&await this.syncStore.shutdown(),this.integrationServices&&typeof this.integrationServices.shutdown=="function"&&await this.integrationServices.shutdown(),this.domainServices&&typeof this.domainServices.shutdown=="function"&&await this.domainServices.shutdown(),this.registry&&typeof this.registry.clear=="function"&&this.registry.clear()}});for(let t of this.pluginSpecs)e.use(t.name,async()=>{await t.init(this)},t.deps);return e}resolveUseSeedData(e){var t;return e.useSeedData!==void 0?e.useSeedData:!!((t=this.config)!=null&&t.demoMode)}},bi=class{constructor(){this.core=new kt;this.adapterOpts={};this.syncOrchestrationMode="host-managed"}withPlatformAdapter(e){return this.adapterOpts.platformAdapter=e,this}withDbAdapter(e){return this.adapterOpts.dbAdapter=e,this}withLoggerAdapter(e){return this.adapterOpts.loggerAdapter=e,this}withHttpAdapter(e){return this.adapterOpts.httpAdapter=e,this}withHttpRetryPolicy(e){return this.adapterOpts.httpRetryPolicy=e,this}withSocketAdapter(e){return this.adapterOpts.socketAdapter=e,this}withEncryptionAdapter(e){return this.adapterOpts.encryptionAdapter=e,this}withChecksumAdapter(e){return this.adapterOpts.checksumAdapter=e,this}withActivitySink(e){return this.adapterOpts.activitySink=e,this}withNotificationAdapter(e){return this.adapterOpts.notificationAdapter=e,this}withExportAdapter(e){return this.adapterOpts.exportAdapter=e,this}withStorageAdapter(e){return this.adapterOpts.storageAdapter=e,this}overrideDomainServices(e){return this.core.domainServiceOverrides={...this.core.domainServiceOverrides,...e},this}overrideIntegrationServices(e){return this.core.integrationServiceOverrides={...this.core.integrationServiceOverrides,...e},this}withSyncOrchestrationMode(e){return this.syncOrchestrationMode=e,this}withDomainChangeSink(e){return this.core.setDomainChangeSink(e),this}disableInternalSyncOrchestration(){return this.syncOrchestrationMode="host-managed",this}applySyncOrchestrationMode(){var e,t;if(this.syncOrchestrationMode!=="host-managed")throw new Error("Only host-managed sync orchestration is supported");this.core.integrationServiceOverrides={...this.core.integrationServiceOverrides,syncService:(e=this.core.integrationServiceOverrides.syncService)!=null?e:new Tt,socketService:(t=this.core.integrationServiceOverrides.socketService)!=null?t:new Bt}}build(e={runMigrations:!0}){return this.applySyncOrchestrationMode(),this.core.registry=new Qr(this.core,this.adapterOpts),this.core}};var Ai=we("ofcore");var Ur=we("ofcore");var Hr=we("ofcore");var Ft=we("ofcore");var Yn=we("ofcore");var Xn=we("ofcore");var $r=we("ofcore");var Zn=Mt(hi()),Jn=class{constructor(e){this.context=e}encrypt(e,t){let r=this.resolveSecretKey(t);return Zn.default.AES.encrypt(String(e!=null?e:""),r).toString()}decrypt(e,t){let r=this.resolveSecretKey(t);return Zn.default.AES.decrypt(String(e!=null?e:""),r).toString(Zn.default.enc.Utf8)||null}resolveSecretKey(e){var r;let t=(r=e==null?void 0:e.metadata)==null?void 0:r.secretKey;return typeof t=="string"&&t.trim().length>0?t:this.context.config.encryptionKey}};var Za=Mt(Wa()),Ja=Mt(Ut()),xi=Mt(Xa()),ri=class{constructor(e){}compute(e){var r,n;let t=String((r=e==null?void 0:e.payload)!=null?r:"");if(e.algorithm==="hmac-sha256"){let i=String((n=e.secret)!=null?n:"");return i?(0,Za.default)(t,i).toString(xi.default):""}return e.algorithm==="sha256"?(0,Ja.default)(t).toString(xi.default):""}verify(e,t){let r=String(this.compute(e)||"").trim().toLowerCase(),n=String(t||"").trim().toLowerCase();return r===n}};var Si=we("ofcore");var Vr=we("ofcore");var Qr=class{constructor(e,t={}){this.context=e;this.opts=t;this.context.registry=this,this.platformAdapter=this.resolveAdapter(t.platformAdapter,Si.DefaultPlatformAdapter),this.dbAdapter=this.resolveAdapter(t.dbAdapter,Ai.InMemoryDbAdapter),this.loggerAdapter=this.resolveAdapter(t.loggerAdapter,Hr.ConsoleLoggerAdapter),this.httpAdapter=this.resolveAdapter(t.httpAdapter,Br.DefaultHttpAdapter),this.httpRetryPolicy=this.resolveAdapter(t.httpRetryPolicy,mt.NoRetryHttpPolicy),this.socketAdapter=this.resolveAdapter(t.socketAdapter,Vr.InMemorySocketAdapter),this.activitySink=this.resolveAdapter(t.activitySink,Ft.NoopActivitySink),this.encryptionAdapter=this.resolveAdapter(t.encryptionAdapter,Jn),this.checksumAdapter=this.resolveAdapter(t.checksumAdapter,ri),this.notificationAdapter=this.resolveAdapter(t.notificationAdapter,$r.NoopNotificationAdapter),this.exportAdapter=this.resolveAdapter(t.exportAdapter,Ur.DefaultExportAdapter),this.storageAdapter=this.resolveAdapter(t.storageAdapter,yt)}resolveAdapter(e,t){if(!e)return new t(this.context);if(typeof e=="object")return e;if(typeof e=="function"&&e.prototype===void 0)try{return e(this.context)}catch{}let r=e,i=(Reflect.getMetadata("design:paramtypes",r)||[]).map(a=>{if(a===kt)return this.context;if(a===Si.DefaultPlatformAdapter)return this.platformAdapter;if(a===Ai.InMemoryDbAdapter)return this.dbAdapter;if(a===Hr.ConsoleLoggerAdapter)return this.loggerAdapter;if(a===Br.DefaultHttpAdapter)return this.httpAdapter;if(a===mt.NoRetryHttpPolicy)return this.httpRetryPolicy;if(a===Vr.InMemorySocketAdapter)return this.socketAdapter;if(a===Ft.NoopActivitySink)return this.activitySink;if(a===Yn.NoopEncryptionAdapter)return this.encryptionAdapter;if(a===Xn.NoopChecksumAdapter)return this.checksumAdapter;if(a===$r.NoopNotificationAdapter)return this.notificationAdapter;if(a===Ur.DefaultExportAdapter)return this.exportAdapter;if(a===yt)return this.storageAdapter});return new r(...i)}};var no=we("ofcore");var eo=we("ofcore");var to=we("ofcore");var ro=we("ofcore");var Ii=class{constructor(e){this.context=e;var t,r,n;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.productService=(r=this.context.domainServices)==null?void 0:r.product,this.bomService=(n=this.context.domainServices)==null?void 0:n.bom}async listProducts(){let e={field:"deleted",value:!1};return(await this.dbAdapter.query(ce,{filters:e})).map(r=>({id:r.id,name:r.name,price:r.price,stock:r.stock,categoryId:r.categoryId}))}async listProductsByCategory(e){if(!e)return this.listProducts();let t={and:[{field:"deleted",value:!1},{field:"categoryId",value:e}]};return(await this.dbAdapter.query(ce,{filters:t})).map(n=>({id:n.id,name:n.name,price:n.price,stock:n.stock,categoryId:n.categoryId}))}async editProduct(e,t){return this.productService.updateProduct(e,t)}async fetchProductDetails(e){let t=await this.productService.getProduct(e),r=await this.bomService.getBomsByProductId(e);return{product:t,boms:r}}async removeProduct(e){return this.productService.deleteProduct(e)}async scanProduct(e){return this.productService.getProductsByBarcode(e)}};var Di=class{constructor(e){this.context=e;var t;this.pricingService=(t=this.context.domainServices)==null?void 0:t.pricing}async calculateTransactionTotals(e,t,r){let{calculateOrderTotal:n,calculatePPN:i,calculatePPH:a}=this.pricingService,{items:o,subTotal:s,discount:c,total:u}=await n(e,t,r),[l,d]=await Promise.all([i(u),a(u)]);return{pricedItems:o,subTotal:s,discount:c,total:u,ppn:l,pph:d,totalWithTax:u+l+d,payableToSeller:u+l-d}}};function Co(h){var t,r;let e=h.sale.date||new Date().toISOString();return{context:{journalId:(t=h.journalId)!=null?t:`journal-sale-${h.sale.id}`,tenantId:h.tenantId,branchId:h.branchId,occurredAt:e,reference:`${(r=h.referencePrefix)!=null?r:"sale"}:${h.sale.id}`},input:{grossAmount:h.sale.total,discountAmount:h.sale.discount,taxAmount:h.sale.ppn,scopedAccountMapping:h.scopedAccountMapping}}}return po(wo);})();
16
+ `,columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"date",type:"string"},{name:"status",type:"string",enum:["pending","completed","cancelled"]},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"stock_opname_items",columns:[{name:"id",type:"string"},{name:"stockOpnameId",type:"string"},{name:"productId",type:"string"},{name:"systemStock",type:"number",notes:"stok sistem (base UOM)"},{name:"physicalStock",type:"number",notes:"hasil hitung fisik (base UOM)"},{name:"difference",type:"number",notes:"physical - system"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"stock_adjustments",columns:[{name:"id",type:"string"},{name:"productId",type:"string"},{name:"change",type:"number"},{name:"reasonType",type:"string"},{name:"note",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"report_schedules",columns:[{name:"id",type:"string"},{name:"reportType",type:"string"},{name:"frequency",type:"string"},{name:"recipients",type:"string[]"},{name:"lastRunAt",type:"string",isOptional:!0},{name:"nextRunAt",type:"string"},{name:"isActive",type:"boolean"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"financial_settings",columns:[{name:"id",type:"string"},{name:"costingMethod",type:"string"},{name:"defaultExpenseAccount",type:"string",isOptional:!0},{name:"fiscalYearStart",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string"}]},{name:"expenses",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"amount",type:"number"},{name:"category",type:"string"},{name:"description",type:"string",isOptional:!0},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"receivables",columns:[{name:"id",type:"string"},{name:"customerId",type:"string"},{name:"saleId",type:"string"},{name:"amount",type:"number"},{name:"dueDate",type:"string"},{name:"status",type:"string"},{name:"paidAmount",type:"number"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"payables",columns:[{name:"id",type:"string"},{name:"supplierId",type:"string"},{name:"purchaseId",type:"string"},{name:"amount",type:"number"},{name:"dueDate",type:"string"},{name:"status",type:"string"},{name:"paidAmount",type:"number"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"settlements",columns:[{name:"id",type:"string"},{name:"receivableId",type:"string",isOptional:!0},{name:"payableId",type:"string",isOptional:!0},{name:"amount",type:"number"},{name:"method",type:"string"},{name:"date",type:"string"},{name:"reference",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]}],ko=[{name:"branchId",type:"string",isOptional:!0,isIndexed:!0},{name:"tenantId",type:"string",isOptional:!0,isIndexed:!0}];function Bo(u){let e=[...u.columns];for(let t of ko)e.some(r=>r.name===t.name)||e.push({...t});return{...u,columns:e}}var xt=Fo.map(Bo),Mo=Object.freeze(xt.map(u=>u.name));for(let[u,e]of Object.entries(Ui)){let t=xt.find(r=>r.name===u);for(let[r,n]of Object.entries(e)){let i=t==null?void 0:t.columns.find(a=>a.name===r);i&&(i.relation=n)}}for(let[u,e]of Object.entries(Hi)){let t=xt.find(r=>r.name===u);t.polymorphic=e}var dn=1,ln=[1,0];function qo(){return{currentVersion:1,compatibleServerVersions:[...ln]}}function yi(u,e){return e.includes(u)}var br=(u,e)=>{var i;let t=e.config.paymentSigningKey;if(!t)return"";let r=(i=e.registry)==null?void 0:i.checksumAdapter;if(!r)throw new Error("ChecksumAdapter is not initialized in AdapterRegistry");let n=r.compute({algorithm:"hmac-sha256",payload:u,secret:t});if(n&&typeof n.then=="function")throw new Error("Shared-core checksum path requires synchronous ChecksumAdapter.compute");return String(n||"")};var vr=class{constructor(e){this.context=e;var t,r,n;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.exportAdapter=(r=this.context.registry)==null?void 0:r.exportAdapter,this.inventoryService=(n=this.context.domainServices)==null?void 0:n.inventory}toCsv(e,t){let r=i=>`"${i.replace(/"/g,'""')}"`,n=[e.map(r).join(",")];return t.forEach(i=>n.push(i.map(r).join(","))),n.join(`
17
+ `)}async exportSalesReportCSV(e){let t=this.dbAdapter,r=e!=null&&e.date?{field:"date",value:e.date}:e!=null&&e.from&&(e!=null&&e.to)?{and:[{field:"date",operator:">=",value:e.from},{field:"date",operator:"<=",value:e.to}]}:void 0,n=await t.query("orders",{filters:r}),i=["Date","Total","PPN","PPH","FinalTotal"],a=n.map(c=>[c.date,c.total.toString(),c.ppn.toString(),c.pph.toString(),c.finalTotal.toString()]),o=this.toCsv(i,a),s=this.exportAdapter,d=s.getDocumentPath("sales_report.csv");await s.writeFile(d,o),await s.share(d)}async exportStockCSV(){let t=await this.dbAdapter.query("products"),r=["ID","Name","Stock"],n=await Promise.all(t.map(d=>this.inventoryService.getStock(d.id))),i=t.map((d,c)=>{var p;return[d.id,(p=d.name)!=null?p:"",n[c].toString()]}),a=this.toCsv(r,i),o=this.exportAdapter,s=o.getDocumentPath("stock_report.csv");await o.writeFile(s,a),await o.share(s)}async exportCustomersCSV(){let t=await this.dbAdapter.query("customers"),r=["ID","Name","Phone","Email"],n=t.map(s=>{var d,c;return[s.id,s.name,(d=s.phone)!=null?d:"",(c=s.email)!=null?c:""]}),i=this.toCsv(r,n),a=this.exportAdapter,o=a.getDocumentPath("customers_report.csv");await a.writeFile(o,i),await a.share(o)}async createLocalBackupSnapshot(){let e={};for(let t of xt.map(r=>r.name))e[t]=await this.dbAdapter.query(t,{});return JSON.stringify({format:"ofpos-local-backup-v1",createdAt:new Date().toISOString(),deploymentMode:this.context.config.deploymentMode,tables:e})}async restoreLocalBackupSnapshot(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Invalid backup snapshot JSON")}if((t==null?void 0:t.format)!=="ofpos-local-backup-v1"||!(t!=null&&t.tables)||typeof t.tables!="object")throw new Error("Invalid backup snapshot format");let r=xt.map(n=>n.name);await this.dbAdapter.transaction(async n=>{for(let i of[...r].reverse()){let a=await n.query(i,{});for(let o of a)o!=null&&o.id&&await n.delete(i,o.id)}for(let i of r){let a=Array.isArray(t.tables[i])?t.tables[i]:[];for(let o of a)await n.create(i,o)}})}async createTaxReadyExportContract(e={}){var m,f,y,b;let t=await this.dbAdapter.query("sales",{filters:{deleted:!1}}),r=await this.dbAdapter.query("returns",{filters:{deleted:!1}}),n=await this.dbAdapter.query("purchases",{filters:{deleted:!1}}),i=await this.dbAdapter.query("settlements",{filters:{deleted:!1}}),a=t.filter(h=>this.isWithinPeriod(h.date,e.from,e.to)),o=r.filter(h=>this.isWithinPeriod(h.date,e.from,e.to)),s=n.filter(h=>this.isWithinPeriod(h.date,e.from,e.to)),d=i.filter(h=>this.isWithinPeriod(h.date,e.from,e.to)),c={sales:a.map(h=>({id:h.id,date:h.date,total:h.total,discount:h.discount,ppn:h.ppn,pph:h.pph,finalTotal:h.finalTotal,status:h.status,customerId:h.customerId,userId:h.userId})),returns:o.map(h=>({id:h.id,date:h.date,type:h.type,refundAmount:h.refundAmount,actualRefund:h.actualRefund,status:h.status,saleId:h.saleId,purchaseId:h.purchaseId,userId:h.userId})),purchases:s.map(h=>({id:h.id,date:h.date,total:h.total,supplierId:h.supplierId,userId:h.userId,purchaseOrderId:h.purchaseOrderId})),payments:d.map(h=>({id:h.id,date:h.date,amount:h.amount,method:h.method,direction:h.receivableId?"in":"out",receivableId:h.receivableId,payableId:h.payableId,reference:h.reference,userId:h.userId}))},p={salesFinalTotal:c.sales.reduce((h,g)=>h+g.finalTotal,0),salesPpnTotal:c.sales.reduce((h,g)=>h+g.ppn,0),salesPphTotal:c.sales.reduce((h,g)=>h+g.pph,0),returnsActualRefundTotal:c.returns.reduce((h,g)=>h+g.actualRefund,0),purchasesTotal:c.purchases.reduce((h,g)=>h+g.total,0),paymentInTotal:c.payments.filter(h=>h.direction==="in").reduce((h,g)=>h+g.amount,0),paymentOutTotal:c.payments.filter(h=>h.direction==="out").reduce((h,g)=>h+g.amount,0)},l={contractVersion:"tex-v1",generatedAt:new Date().toISOString(),sourceVersion:`sync-protocol-v${1}`,period:{from:(m=e.from)!=null?m:null,to:(f=e.to)!=null?f:null,label:(y=e.periodLabel)!=null?y:null},currency:{baseCurrencyCode:(b=e.baseCurrencyCode)!=null?b:"IDR"},records:c,summary:p};return e.compatibilityTarget==="N-1"?{contractVersion:"tex-v0",generatedAt:l.generatedAt,sourceVersion:l.sourceVersion,period:l.period,currency:l.currency,records:{sales:l.records.sales.map(g=>({id:g.id,date:g.date,total:g.total,discount:g.discount,taxTotal:g.ppn+g.pph,finalTotal:g.finalTotal,status:g.status,customerId:g.customerId,userId:g.userId})),returns:l.records.returns,purchases:l.records.purchases,payments:l.records.payments.map(g=>({id:g.id,date:g.date,amount:g.amount,method:g.method,flow:g.direction==="in"?"receipt":"disbursement",receivableId:g.receivableId,payableId:g.payableId,reference:g.reference,userId:g.userId}))},summary:{salesFinalTotal:l.summary.salesFinalTotal,salesTaxTotal:l.summary.salesPpnTotal+l.summary.salesPphTotal,returnsActualRefundTotal:l.summary.returnsActualRefundTotal,purchasesTotal:l.summary.purchasesTotal,paymentInTotal:l.summary.paymentInTotal,paymentOutTotal:l.summary.paymentOutTotal}}:l}async createTaxReadyExportCsvBundle(e={}){let t=await this.createTaxReadyExportContract(e),r=this.normalizeTaxReadyExportContract(t),n={};return n["tax_ready_manifest.json"]=JSON.stringify({contractVersion:t.contractVersion,generatedAt:t.generatedAt,sourceVersion:t.sourceVersion,period:t.period,currency:t.currency,summary:r.summary}),n["tax_ready_sales.csv"]=this.toCsv(["id","date","total","discount","ppn","pph","finalTotal","status","customerId","userId"],r.records.sales.map(i=>{var a;return[i.id,i.date,i.total.toString(),i.discount.toString(),i.ppn.toString(),i.pph.toString(),i.finalTotal.toString(),i.status,(a=i.customerId)!=null?a:"",i.userId]})),n["tax_ready_returns.csv"]=this.toCsv(["id","date","type","refundAmount","actualRefund","status","saleId","purchaseId","userId"],r.records.returns.map(i=>{var a,o;return[i.id,i.date,i.type,i.refundAmount.toString(),i.actualRefund.toString(),i.status,(a=i.saleId)!=null?a:"",(o=i.purchaseId)!=null?o:"",i.userId]})),n["tax_ready_purchases.csv"]=this.toCsv(["id","date","total","supplierId","userId","purchaseOrderId"],r.records.purchases.map(i=>{var a;return[i.id,i.date,i.total.toString(),i.supplierId,i.userId,(a=i.purchaseOrderId)!=null?a:""]})),n["tax_ready_payments.csv"]=this.toCsv(["id","date","amount","method","direction","receivableId","payableId","reference","userId"],r.records.payments.map(i=>{var a,o,s;return[i.id,i.date,i.amount.toString(),i.method,i.direction,(a=i.receivableId)!=null?a:"",(o=i.payableId)!=null?o:"",(s=i.reference)!=null?s:"",i.userId]})),n}normalizeTaxReadyExportContract(e){return e.contractVersion==="tex-v1"?e:{contractVersion:"tex-v1",generatedAt:e.generatedAt,sourceVersion:e.sourceVersion,period:e.period,currency:e.currency,records:{sales:e.records.sales.map(t=>({id:t.id,date:t.date,total:t.total,discount:t.discount,ppn:t.taxTotal,pph:0,finalTotal:t.finalTotal,status:t.status,customerId:t.customerId,userId:t.userId})),returns:e.records.returns,purchases:e.records.purchases,payments:e.records.payments.map(t=>({id:t.id,date:t.date,amount:t.amount,method:t.method,direction:t.flow==="receipt"?"in":"out",receivableId:t.receivableId,payableId:t.payableId,reference:t.reference,userId:t.userId}))},summary:{salesFinalTotal:e.summary.salesFinalTotal,salesPpnTotal:e.summary.salesTaxTotal,salesPphTotal:0,returnsActualRefundTotal:e.summary.returnsActualRefundTotal,purchasesTotal:e.summary.purchasesTotal,paymentInTotal:e.summary.paymentInTotal,paymentOutTotal:e.summary.paymentOutTotal}}}async createFiscalArchiveSnapshot(e){let t=String(e.actorId||"").trim(),r=String(e.reason||"").trim();if(!t)throw new Error("Fiscal archive policy: actorId is required");if(!r)throw new Error("Fiscal archive policy: reason is required");let n=await this.createTaxReadyExportContract(e),i=this.normalizeTaxReadyExportContract(n),a=await this.createTaxReadyExportCsvBundle(e),o=D(),s=new Date().toISOString(),d=JSON.stringify({archiveId:o,generatedAt:s,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,period:n.period,currency:n.currency,summary:i.summary,actorId:t,reason:r}),c=br(d,this.context),p={archiveId:o,generatedAt:s,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,period:n.period,currency:n.currency,summary:i.summary,checksum:c,actorId:t,reason:r};return await this.dbAdapter.create(ie,{id:D(),tableName:"fiscal_archives",recordId:o,action:"snapshot_created",changes:{period:n.period,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,fileNames:Object.keys(a),checksum:c,reason:r},userId:t,timestamp:s}),{archiveId:o,generatedAt:s,period:n.period,files:a,manifest:p}}isWithinPeriod(e,t,r){let n=new Date(e).getTime();if(!Number.isFinite(n))return!1;if(t){let i=new Date(t).getTime();if(Number.isFinite(i)&&n<i)return!1}if(r){let i=new Date(r).getTime();if(Number.isFinite(i)&&n>i)return!1}return!0}};var xr=class{constructor(e){this.context=e;var t,r,n,i;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.taxService=(r=this.context.domainServices)==null?void 0:r.tax,this.uomService=(n=this.context.domainServices)==null?void 0:n.uom,this.promotionService=(i=this.context.domainServices)==null?void 0:i.promotion}getRoundingIncrement(){let e=this.context.config.pricingRoundingIncrement;if(e==null)return null;let t=Number(e);return!Number.isFinite(t)||t<=0?null:t}roundValue(e){let t=this.getRoundingIncrement();return t==null?e:Math.round(e/t)*t}normalizePrecision(e){let t=Number(e.toFixed(10)),r=Math.round(t);return Math.abs(t-r)<1e-9?r:t}normalizeDiscountCodes(e){return e?Array.isArray(e)?e.map(t=>String(t||"").trim()).filter(Boolean):String(e).split(",").map(t=>t.trim()).filter(Boolean):[]}async getTieredPrice(e,t,r,n){let i=this.dbAdapter,a={and:[{field:"productId",value:e},...r?[{field:"customerGroupId",value:r}]:[],...n?[{field:"uom",value:n}]:[]]},s=await i.query(He,{filters:a});s.sort((m,f)=>{let y=m.customerGroupId===r?0:1,b=f.customerGroupId===r?0:1;return y!==b?y-b:f.tierLevel-m.tierLevel});let d=s.find(m=>t>=m.tierLevel),c=await i.get(ue,e);if(!c)throw new Error(`Product with id ${e} not found`);let p=d?d.price:c.price,l=p;if(!d&&n){let m=c.baseUomId;if(m&&m!==n){let f=await this.uomService.getUom(m),y=await this.uomService.getUom(n);f&&y&&(l=this.uomService.convertUnitPrice(p,f,y))}}return this.context.config.pricingRoundingScope==="line"&&(l=this.roundValue(l)),this.context.logActivity("TieredPrice",{productId:e,quantity:t,uom:n,price:l}),l}async applyTieredPricing(e,t){return await Promise.all(e.map(async n=>({...n,unitPrice:await this.getTieredPrice(n.productId,n.quantity,t,n.uomId)})))}async calculatePromotionDiscount(e,t){var y;let r=((y=this.context.domainServices)==null?void 0:y.promotion)||this.promotionService,n=this.normalizeDiscountCodes(t);if(!n.length)return 0;let i=await(r==null?void 0:r.getPromotions());if(!(i!=null&&i.length))return 0;let a=Date.now(),o=n.map(b=>i.find(h=>{if(h.code!==b)return!1;if(!h.expiresAt)return!0;let g=Date.parse(h.expiresAt);return Number.isNaN(g)?!1:g>=a})).filter(Boolean);if(!o.length)return 0;let s=this.roundValue(e.reduce((b,h)=>b+h.quantity*h.unitPrice,0)),d=this.context.config.allowPromotionStacking,c=this.context.config.promotionSelectionStrategy;if(!d){let b=c==="first_valid"?o[0]:o.map(g=>{let x=g.type==="percent"?s*g.value/100:g.value;return{promo:g,discount:Math.min(Math.max(0,x),s)}}).sort((g,x)=>x.discount-g.discount)[0].promo,h=b.type==="percent"?s*b.value/100:b.value;return this.roundValue(Math.min(Math.max(0,h),s))}let p=this.context.config.promotionStackingOrder,l=[...o];p==="percent_then_fixed"?l.sort((b,h)=>b.type===h.type?0:b.type==="percent"?-1:1):p==="fixed_then_percent"&&l.sort((b,h)=>b.type===h.type?0:b.type==="fixed"?-1:1);let m=s,f=0;for(let b of l){let h=b.type==="percent"?m*b.value/100:b.value,g=Math.min(Math.max(0,this.roundValue(h)),m);m-=g,f+=g}return this.roundValue(f)}async calculateOrderTotal(e,t,r){let n=await this.applyTieredPricing(e,r),i=this.roundValue(n.reduce((s,d)=>s+d.quantity*d.unitPrice,0)),a=this.roundValue(await this.calculatePromotionDiscount(n,t)),o=this.roundValue(Math.max(0,i-a));return{items:n,subTotal:i,discount:a,total:o}}async calculatePPN(e){var r;let t=((r=this.context.domainServices)==null?void 0:r.tax)||this.taxService;return this.roundValue(e*await t.getPpnRate())}async calculatePPH(e){var r;let t=((r=this.context.domainServices)==null?void 0:r.tax)||this.taxService;return this.roundValue(e*await t.getPphRate())}async calculateTaxBreakdown(e,t){var b;let r=(t==null?void 0:t.mode)==="inclusive"?"inclusive":"exclusive",n=((b=this.context.domainServices)==null?void 0:b.tax)||this.taxService,i=await n.getPpnRate(),a=await n.getPphRate(),o=Number(e||0),s=o;if(r==="inclusive"){let h=1+i+a;s=h>0?o/h:o}s=this.normalizePrecision(this.roundValue(s));let d=this.normalizePrecision(this.roundValue(s*i)),c=this.normalizePrecision(this.roundValue(s*a)),p=r==="exclusive"?this.normalizePrecision(this.roundValue(s+d+c)):this.normalizePrecision(this.roundValue(o)),l=this.normalizePrecision(this.roundValue(Number((t==null?void 0:t.correctionAmount)||0))),m=this.normalizePrecision(this.roundValue(p+l)),f=String((t==null?void 0:t.correctionReason)||"").trim(),y=l!==0?`[TAX_CORRECTION=${l>=0?"+":""}${l}${f?`|reason=${f}`:""}]`:null;return{mode:r,inputAmount:o,taxBase:s,ppn:d,pph:c,totalBeforeCorrection:p,correctionAmount:l,totalAfterCorrection:m,correctionNote:y}}async calculateReturnTaxImpact(e,t){let r=(t==null?void 0:t.mode)==="inclusive"?"inclusive":"exclusive",n=await this.calculateTaxBreakdown(e,{mode:r});return{mode:r,returnAmount:Number(e||0),taxBaseImpact:this.normalizePrecision(this.roundValue(-n.taxBase)),ppnImpact:this.normalizePrecision(this.roundValue(-n.ppn)),pphImpact:this.normalizePrecision(this.roundValue(-n.pph)),grossImpact:this.normalizePrecision(this.roundValue(-n.totalBeforeCorrection))}}};var Lo=Math.pow(10,8)*24*60*60*1e3,a0=-Lo;var No=3600;var ji=No*24,o0=ji*7,Qo=ji*365.2425,Uo=Qo/12,s0=Uo*3,bi=Symbol.for("constructDateFrom");function pn(u,e){return typeof u=="function"?u(e):u&&typeof u=="object"&&bi in u?u[bi](e):u instanceof Date?new u.constructor(e):new Date(e)}function qt(u,e){return pn(e||u,u)}function $i(u,e,t){let r=qt(u,t==null?void 0:t.in);return isNaN(e)?pn((t==null?void 0:t.in)||u,NaN):(e&&r.setDate(r.getDate()+e),r)}function mn(u,e){let t=qt(u,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Ar(u,e){let t=qt(u,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Vi(u,e,t){return $i(u,-e,t)}var Sr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter}validateDateRange(e,t){if(!(e instanceof Date)||isNaN(e.getTime()))throw new TypeError("startDate bukan Date yang valid");if(!(t instanceof Date)||isNaN(t.getTime()))throw new TypeError("endDate bukan Date yang valid");if(e>t)throw new RangeError("startDate harus \u2264 endDate")}async getSalesAggregate(e,t){var s;this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(Z,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=0,o=i.length;for(let d of i)a+=(s=d.amount)!=null?s:0;return{totalTransactions:o,totalRevenue:a}}async getTransactionsByHour(e,t){this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(Z,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=new Map;return i.forEach(o=>{let d=new Date(o.date).getUTCHours().toString().padStart(2,"0");a.set(d,(a.get(d)||0)+1)}),Array.from(a.entries()).sort(([o],[s])=>o.localeCompare(s)).map(([o,s])=>({hour:o,count:s}))}async getRevenueByCustomer(e,t){this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(Z,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=new Map;return i.forEach(o=>{var s;if(o.referenceType){let d=o.referenceId,c=(s=o.amount)!=null?s:0;a.set(d,(a.get(d)||0)+c)}}),Array.from(a.entries()).map(([o,s])=>({customerId:o,revenue:s}))}async getTodaySales(){let e=mn(new Date).toISOString(),t=Ar(new Date).toISOString(),r=await this.dbAdapter.get(Z,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:e},{field:"date",operator:"<=",value:t},{field:"deleted",operator:"=",value:!1}]}}]});return{total:Number((r==null?void 0:r.total)||0)}}async getSalesThisMonth(){let e=new Date,t=e.getFullYear(),r=(e.getMonth()+1).toString().padStart(2,"0"),n=`${t}-${r}-01T00:00:00.000Z`,i=Ar(e).toISOString(),a=await this.dbAdapter.get(Z,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:n},{field:"date",operator:"<=",value:i},{field:"deleted",operator:"=",value:!1}]}}]});return{total:Number((a==null?void 0:a.total)||0)}}async getLowStockProducts(e=this.context.config.reportingLowStockLimit,t=this.context.config.lowStockThreshold){return this.context.domainServices.inventory.getLowStockProducts(t,e)}async getActiveShift(){return(await this.dbAdapter.query(le,{filters:{field:"status",operator:"=",value:"open"},limit:1}))[0]||null}async getTopSellingProducts(e=this.context.config.reportingTopSellingLimit){let t=mn(new Date).toISOString(),r=Ar(new Date).toISOString(),i=(await this.dbAdapter.query(ce,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["id"]}})).map(p=>String(p.t0_id||p.id||"")).filter(p=>p.length>0);if(!i.length)return[];let a=await this.dbAdapter.query(ge,{filters:{and:[{field:"saleId",operator:"IN",value:i},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["productId","quantity","unitPrice"]}}),o=new Map;for(let p of a){let l=String(p.t0_productId||p.productId||""),m=Number(p.t0_quantity||p.quantity||0),f=Number(p.t0_unitPrice||p.unitPrice||0);if(!l)continue;let y=o.get(l)||{productId:l,quantity:0,totalSales:0};y.quantity+=m,y.totalSales+=m*f,o.set(l,y)}if(!o.size)return[];let s=Array.from(o.keys()),d=await this.dbAdapter.query(ue,{filters:{and:[{field:"id",operator:"IN",value:s},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["id","name"]}}),c=new Map;for(let p of d){let l=String(p.t0_id||p.id||""),m=String(p.t0_name||p.name||"");l&&c.set(l,m||l)}return Array.from(o.values()).map(p=>({productId:p.productId,productName:c.get(p.productId)||p.productId,quantity:p.quantity,totalSales:p.totalSales})).sort((p,l)=>l.quantity-p.quantity).slice(0,e)}async getDailySalesLast7Days(){let e=[];for(let t=6;t>=0;t--){let r=Vi(new Date,t),n=mn(r).toISOString(),i=Ar(r).toISOString(),a=await this.dbAdapter.get(Z,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:n},{field:"date",operator:"<=",value:i},{field:"deleted",operator:"=",value:!1}]}}]});e.push({date:r.toISOString(),total:Number((a==null?void 0:a.total)||0)})}return e}async getDailyReport(e){var l,m,f;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(le,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r}]}}),this.dbAdapter.query(Z,{aggregates:[{function:"SUM",field:"amount",as:"salesCash",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"returnsCash",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"expenses",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}})]),a=0,o=0,s=0;for(let y of n)a+=y.startingCash||0,y.status==="closed"&&(o+=y.endingCash||0,s+=y.systemCash||0);let d=Number(((l=i==null?void 0:i[0])==null?void 0:l.salesCash)||0),c=Number(((m=i==null?void 0:i[0])==null?void 0:m.returnsCash)||0),p=Number(((f=i==null?void 0:i[0])==null?void 0:f.expenses)||0);return{date:e,totalSalesCash:d,totalReturnsCash:c,totalExpenses:p,netCashMovement:d-c-p,startingCash:a,systemEndingCash:s,physicalEndingCash:o,cashDifference:o-s,shifts:n}}async getDailyReconciliationPack(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(Z,{aggregates:[{function:"SUM",field:"amount",as:"salesCashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"salesReturnCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"purchaseCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"purchase"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"purchaseReturnCashIn",filter:{and:[{field:"referenceType",operator:"=",value:"purchase_return"},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"expenseCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"cashAdjustmentIn",filter:{and:[{field:"referenceType",operator:"=",value:"cash_adjustment"},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashAdjustmentOut",filter:{and:[{field:"referenceType",operator:"=",value:"cash_adjustment"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"totalCashIn",filter:{field:"direction",operator:"=",value:"in"}},{function:"SUM",field:"amount",as:"totalCashOut",filter:{field:"direction",operator:"=",value:"out"}}],filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Oe,{aggregates:[{function:"COUNT",field:"id",as:"inventoryAdjustmentEntries",filter:{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]}},{function:"SUM",field:"change",as:"inventoryAdjustmentInQty",filter:{and:[{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]},{field:"change",operator:">",value:0}]}},{function:"SUM",field:"change",as:"inventoryAdjustmentOutQtyNegative",filter:{and:[{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]},{field:"change",operator:"<",value:0}]}},{function:"SUM",field:"change",as:"inventoryAdjustmentNetQty",filter:{field:"referenceType",operator:"IN",value:["stock_adjustment","stock_opname"]}}],filters:{and:[{field:"timestamp",operator:">=",value:t},{field:"timestamp",operator:"<=",value:r}]}})]),a=(n==null?void 0:n[0])||{},o=(i==null?void 0:i[0])||{},s=Number(a.totalCashIn||0),d=Number(a.totalCashOut||0),c=Math.abs(Number(o.inventoryAdjustmentOutQtyNegative||0));return{date:e,salesCashIn:Number(a.salesCashIn||0),salesReturnCashOut:Number(a.salesReturnCashOut||0),purchaseCashOut:Number(a.purchaseCashOut||0),purchaseReturnCashIn:Number(a.purchaseReturnCashIn||0),expenseCashOut:Number(a.expenseCashOut||0),cashAdjustmentIn:Number(a.cashAdjustmentIn||0),cashAdjustmentOut:Number(a.cashAdjustmentOut||0),totalCashIn:s,totalCashOut:d,netCashMovement:s-d,inventoryAdjustmentEntries:Number(o.inventoryAdjustmentEntries||0),inventoryAdjustmentInQty:Number(o.inventoryAdjustmentInQty||0),inventoryAdjustmentOutQty:c,inventoryAdjustmentNetQty:Number(o.inventoryAdjustmentNetQty||0)}}async getBranchPerformancePack(e){var y;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,n=String(((y=this.context.config)==null?void 0:y.branchId)||"LOCAL"),i=await this.getDailyReconciliationPack(e),[a,o]=await Promise.all([this.dbAdapter.query(le,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r},{field:"status",operator:"=",value:"closed"},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(we,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"status",operator:"=",value:"completed"},{field:"deleted",operator:"=",value:!1}]}})]),s=o.map(b=>b.id).filter(Boolean),d=s.length>0?await this.dbAdapter.query(Me,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:s},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],c=a.reduce((b,h)=>b+Math.abs(Number(h.cashDifference||0)),0),p=d.length,l=d.reduce((b,h)=>b+Math.abs(Number(h.difference||0)),0),m=[];return(i.salesCashIn>0?i.salesReturnCashOut/i.salesCashIn:0)>.1&&m.push("HIGH_REFUND_RATIO"),c>0&&m.push("SHIFT_CASH_DIFFERENCE"),p>0&&m.push("STOCK_DISCREPANCY"),{date:e,branchId:n,totalSalesCash:i.salesCashIn,totalReturnsCash:i.salesReturnCashOut,totalExpenses:i.expenseCashOut,totalCashIn:i.totalCashIn,totalCashOut:i.totalCashOut,netCashMovement:i.netCashMovement,shiftsClosed:a.length,totalCashDifferenceAbs:c,stockDiscrepancyItems:p,stockDiscrepancyAbsQty:l,anomalyIndicators:m}}async getDailyExceptionReport(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i,a]=await Promise.all([this.dbAdapter.query(Z,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"referenceType",operator:"IN",value:["sale_return_cancelled","purchase_return_cancelled"]},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Ae,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(we,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"status",operator:"=",value:"completed"},{field:"deleted",operator:"=",value:!1}]}})]),o=(a||[]).map(c=>c.id).filter(Boolean),s=o.length>0?await this.dbAdapter.query(Me,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:o},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],d=new Map((a||[]).map(c=>[String(c.id),String(c.date)]));return{date:e,voidEvents:(n||[]).map(c=>({transactionId:String(c.id),referenceType:String(c.referenceType),referenceId:String(c.referenceId),amount:Number(c.amount||0),date:String(c.date)})),refundExceptions:(i||[]).filter(c=>["partially_refunded","no_refund"].includes(String(c.status||""))||Number(c.actualRefund||0)<Number(c.refundAmount||0)).map(c=>({returnId:String(c.id),type:String(c.type),refundAmount:Number(c.refundAmount||0),actualRefund:Number(c.actualRefund||0),status:String(c.status),date:String(c.date)})),stockDiscrepancies:s.map(c=>{var p;return{stockOpnameId:String(c.stockOpnameId),productId:String(c.productId),difference:Number((p=c.difference)!=null?p:0),date:String(d.get(String(c.stockOpnameId))||"")}})}}async getSupplierPayableAging(e=new Date().toISOString()){var a;let t=new Date(e),r=await this.dbAdapter.query(ye,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),n=new Map;for(let o of r){let s=String(o.supplierId||"");if(!s)continue;let d=Number(o.amount||0),c=Number(o.paidAmount||0),p=Math.max(0,d-c);if(p<=0)continue;let l=new Date(String(o.dueDate||"")),m=this.diffInDays(l,t),f=Number.isFinite(m)&&m>0,y=(a=n.get(s))!=null?a:{supplierId:s,openPayableCount:0,totalOutstanding:0,overduePayableCount:0,overdueOutstanding:0,maxDaysPastDue:0,avgDaysPastDue:0};y.openPayableCount+=1,y.totalOutstanding+=p,f&&(y.overduePayableCount+=1,y.overdueOutstanding+=p,y.maxDaysPastDue=Math.max(y.maxDaysPastDue,m)),n.set(s,y)}return Array.from(n.values()).map(o=>{let s=o.overduePayableCount>0?Math.round(o.maxDaysPastDue+o.overdueOutstanding/Math.max(1,o.totalOutstanding)*o.maxDaysPastDue)/2:0;return{...o,avgDaysPastDue:s}}).sort((o,s)=>s.overdueOutstanding-o.overdueOutstanding)}async getCustomerReceivableAging(e=new Date().toISOString()){var o;let t=new Date(e),r=await this.dbAdapter.query(fe,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),n=new Map;for(let s of r){let d=String(s.customerId||"");if(!d)continue;let c=Number(s.amount||0),p=Number(s.paidAmount||0),l=Math.max(0,c-p);if(l<=0)continue;let m=new Date(String(s.dueDate||"")),f=this.diffInDays(m,t),y=Number.isFinite(f)&&f>0,b=(o=n.get(d))!=null?o:{customerId:d,openReceivableCount:0,totalOutstanding:0,overdueReceivableCount:0,overdueOutstanding:0,maxDaysPastDue:0};b.openReceivableCount+=1,b.totalOutstanding+=l,y&&(b.overdueReceivableCount+=1,b.overdueOutstanding+=l,b.maxDaysPastDue=Math.max(b.maxDaysPastDue,f)),n.set(d,b)}let i=this.context.config.customerCreditEscalationThresholdDays;return Array.from(n.values()).map(s=>{let d="none";return s.maxDaysPastDue>=i*2?d="critical":s.maxDaysPastDue>=i&&(d="warning"),{...s,escalationLevel:d}}).sort((s,d)=>d.overdueOutstanding-s.overdueOutstanding)}async getOverduePurchaseOrderAlerts(e=new Date().toISOString()){let t=new Date(e),r=await this.dbAdapter.query(_e,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"NOT IN",value:["received","cancelled"]}]}}),n=[];for(let i of r){if(!i.expectedDeliveryDate)continue;let a=new Date(String(i.expectedDeliveryDate)),o=this.diffInDays(a,t);!Number.isFinite(o)||o<=0||n.push({purchaseOrderId:String(i.id),supplierId:String(i.supplierId),status:String(i.status),expectedDeliveryDate:String(i.expectedDeliveryDate),daysOverdue:o,total:Number(i.total||0)})}return n.sort((i,a)=>a.daysOverdue-i.daysOverdue)}async getSupplierPerformanceBaseline(e=new Date().toISOString()){let[t,r,n]=await Promise.all([this.getSupplierPayableAging(e),this.getOverduePurchaseOrderAlerts(e),this.dbAdapter.query(_e,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"NOT IN",value:["received","cancelled"]}]}})]),i=new Map;for(let d of n){let c=String(d.supplierId||"");c&&i.set(c,(i.get(c)||0)+1)}let a=new Map;for(let d of r)a.set(d.supplierId,(a.get(d.supplierId)||0)+1);let o=new Set([...t.map(d=>d.supplierId),...Array.from(i.keys())]),s=[];for(let d of o){let c=t.find(x=>x.supplierId===d),p=(c==null?void 0:c.openPayableCount)||0,l=c&&c.totalOutstanding>0?c.overdueOutstanding/c.totalOutstanding:0,m=i.get(d)||0,f=a.get(d)||0,y=m>0?f/m:0,b=Math.round(100-(l*60+y*40)*100),h=Math.max(0,Math.min(100,b)),g=h>=85?"A":h>=70?"B":h>=50?"C":"D";s.push({supplierId:d,rating:h,grade:g,openPayableCount:p,overduePayableRatio:Number(l.toFixed(4)),openPurchaseOrderCount:m,overdueOrderCount:f,overdueOrderRatio:Number(y.toFixed(4))})}return s.sort((d,c)=>c.rating-d.rating)}diffInDays(e,t){let r=e.getTime(),n=t.getTime();return!Number.isFinite(r)||!Number.isFinite(n)?NaN:Math.floor((n-r)/(1440*60*1e3))}};var Lt=class Lt{constructor(e){this.context=e;var t;this.storage=(t=this.context.registry)==null?void 0:t.storageAdapter}async getAllCarts(){let e=await this.storage.getItem(Lt.KEY);return e?JSON.parse(e):{}}async saveAllCarts(e){await this.storage.setItem(Lt.KEY,JSON.stringify(e))}async createCart(e){let t=await this.getAllCarts();t[e.id]=e,await this.saveAllCarts(t)}async updateCart(e){let t=await this.getAllCarts();t[e.id]&&(t[e.id]={...t[e.id],...e,lastModified:new Date().toISOString()},await this.saveAllCarts(t))}async deleteCart(e){let t=await this.getAllCarts();delete t[e],await this.saveAllCarts(t)}async clearAllCarts(){await this.storage.removeItem(Lt.KEY)}};Lt.KEY="carts";var Ir=Lt;var Pr=class{constructor(e){this.context=e;this.cartStore=new Ir(this.context)}async createCart(e){var n;let t=new Date().toISOString(),r={id:D(),createdAt:t,lastModified:t,items:[],subtotal:0,totalDiscount:0,ppn:0,pph:0,finalTotal:0,userId:((n=this.context.session)==null?void 0:n.userId)||void 0,...e};return await this.cartStore.createCart(r),r}async updateCart(e){await this.cartStore.updateCart(e)}async deleteCart(e){await this.cartStore.deleteCart(e)}async getCart(e){return(await this.cartStore.getAllCarts())[e]}async getAllCarts(){return await this.cartStore.getAllCarts()}async clearAllCarts(){await this.cartStore.clearAllCarts()}async getActiveCarts(){let e=await this.cartStore.getAllCarts();return Object.values(e).filter(t=>!t.isLocked)}async getCartByCustomerId(e){let t=await this.cartStore.getAllCarts();return Object.values(t).filter(r=>r.customerId===e)}async getCartByTableNumber(e){let t=await this.cartStore.getAllCarts();return Object.values(t).filter(r=>r.tableNumber===e)}async addItemToCart(e,t){let r=await this.cartStore.getAllCarts();if(!r[e])throw new Error("Cart not found");let n=r[e];return n.items.push({...t}),n.subtotal+=t.quantity*t.unitPrice,n.finalTotal=n.subtotal+n.ppn+n.pph-n.totalDiscount,await this.cartStore.updateCart(n),n}async removeItemFromCart(e,t){let r=await this.cartStore.getAllCarts();if(!r[e])throw new Error("Cart not found");let n=r[e],i=n.items.findIndex(o=>o.id===t);if(i===-1)throw new Error("Item not found in cart");let a=n.items[i];return n.subtotal-=a.quantity*a.unitPrice,n.finalTotal=n.subtotal+n.ppn+n.pph-n.totalDiscount,n.items.splice(i,1),await this.cartStore.updateCart(n),n}async updateCartItem(e,t,r){let n=await this.cartStore.getAllCarts();if(!n[e])throw new Error("Cart not found");let i=n[e],a=i.items.findIndex(p=>p.id===t);if(a===-1)throw new Error("Item not found in cart");let o=i.items[a],s=o.quantity*o.unitPrice,d={...i.items[a],...r,id:t},c=d.quantity*d.unitPrice;return i.subtotal=i.subtotal-s+c,i.finalTotal=i.subtotal+i.ppn+i.pph-i.totalDiscount,i.items=[...i.items.slice(0,a),d,...i.items.slice(a+1)],await this.cartStore.updateCart(i),i}};var Nt=null,Qt=null,Dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,Le.on("taxRateChanged",this.clearTaxRateCache)}async getPpnRate(){if(Nt!==null)return Nt;let e=await this.dbAdapter.query(Ee,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});return Nt=e.length>0?e[0].rate:0,Nt}async getPphRate(){if(Qt!==null)return Qt;let e=await this.dbAdapter.query(Ee,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});return Qt=e.length>0?e[0].rate:0,Qt}async setPpnRate(e){if(e<0)throw new Error("PPN rate must be non-negative");await this.dbAdapter.transaction(async t=>{let r=await t.query(Ee,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(Ee,n.id))),await t.create(Ee,{key:"ppn",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),Le.emit("taxRateChanged"),Nt=e}async setPphRate(e){if(e<0)throw new Error("PPH rate must be non-negative");await this.dbAdapter.transaction(async t=>{let r=await t.query(Ee,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(Ee,n.id))),await t.create(Ee,{key:"pph",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),Le.emit("taxRateChanged"),Qt=e}clearTaxRateCache(){Nt=null,Qt=null}};var hn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter}getActorId(){var e;return String(((e=this.context.session)==null?void 0:e.userId)||"").trim()}normalizeBranch(e){let t=String(e||"").trim();if(!t)throw new Error("branchId is required");return t}ensureItems(e){if(!Array.isArray(e)||e.length===0)throw new Error("Transfer items are required");return e.map(t=>{let r=String(t.productId||"").trim(),n=Number(t.quantity||0);if(!r||n<=0)throw new Error("Each transfer item requires productId and quantity > 0");return{productId:r,quantity:n}})}async appendEvent(e,t,r,n){let i=new Date().toISOString();await n.create(ie,{id:D(),tableName:"stock_transfers",recordId:e,action:t,changes:r,userId:this.getActorId()||null,timestamp:i})}mergeState(e,t){let r=t.changes||{},n=e||{id:String(t.recordId),sourceBranchId:String(r.sourceBranchId||""),targetBranchId:String(r.targetBranchId||""),status:"requested",items:Array.isArray(r.items)?r.items:[],notes:null};return{...n,...r,id:String(t.recordId),status:String(r.status||n.status),items:Array.isArray(r.items)?r.items:n.items}}async getTransfer(e){let t=await this.dbAdapter.query(ie,{filters:{and:[{field:"tableName",operator:"=",value:"stock_transfers"},{field:"recordId",operator:"=",value:e}]},sort:[{field:"timestamp",direction:"asc"}]});if(!t.length)return null;let r=null;for(let n of t)r=this.mergeState(r,n);return r}async requestTransfer(e){let t=this.normalizeBranch(e.sourceBranchId),r=this.normalizeBranch(e.targetBranchId);if(t===r)throw new Error("sourceBranchId and targetBranchId must be different");let n=this.ensureItems(e.items),i=new Date().toISOString(),a=D(),o=this.getActorId()||null;await this.dbAdapter.transaction(async d=>{await this.appendEvent(a,"stock_transfer_requested",{sourceBranchId:t,targetBranchId:r,status:"requested",items:n,notes:e.notes||null,requestedBy:o,requestedAt:i},d)});let s=await this.getTransfer(a);if(!s)throw new Error("Failed to persist stock transfer request");return s}async approveTransfer(e,t){let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="requested")throw new Error("Stock transfer can only be approved from requested status");let n=new Date().toISOString(),i=this.getActorId()||null;await this.dbAdapter.transaction(async o=>{await this.appendEvent(e,"stock_transfer_approved",{status:"approved",approvedBy:i,approvedAt:n,notes:(t==null?void 0:t.notes)||r.notes||null},o)});let a=await this.getTransfer(e);if(!a)throw new Error("Stock transfer not found after approval");return a}async shipTransfer(e,t){var s;let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="approved")throw new Error("Stock transfer can only be shipped from approved status");let n=String(((s=this.context.config)==null?void 0:s.branchId)||"").trim();if(!n||n!==r.sourceBranchId)throw new Error("Ship operation is only allowed on source branch context");let i=this.getActorId()||null,a=new Date().toISOString();await this.dbAdapter.transaction(async d=>{for(let c of r.items)await this.context.domainServices.inventory.updateStock(c.productId,-Number(c.quantity),"stock_transfer_out","stock_transfer",e,d);await this.appendEvent(e,"stock_transfer_shipped",{status:"shipped",shippedBy:i,shippedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},d)});let o=await this.getTransfer(e);if(!o)throw new Error("Stock transfer not found after shipping");return o}async receiveTransfer(e,t){var s;let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="shipped")throw new Error("Stock transfer can only be received from shipped status");let n=String(((s=this.context.config)==null?void 0:s.branchId)||"").trim();if(!n||n!==r.targetBranchId)throw new Error("Receive operation is only allowed on target branch context");let i=this.getActorId()||null,a=new Date().toISOString();await this.dbAdapter.transaction(async d=>{for(let c of r.items)await this.context.domainServices.inventory.updateStock(c.productId,Number(c.quantity),"stock_transfer_in","stock_transfer",e,d);await this.appendEvent(e,"stock_transfer_received",{status:"received",receivedBy:i,receivedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},d)});let o=await this.getTransfer(e);if(!o)throw new Error("Stock transfer not found after receiving");return o}};var Cr=class{constructor(e,t={},r={}){this.context=e;var n,i,a,o,s,d,c,p,l,m,f,y,b,h,g,x,v,A,I,k,w,q,M,E,L,Q,T,z,V,F,U,O,_,R,P,X,te,J,Y,be,se,Ne,pe;this.context.domainServices=this,this.bom=(n=t.bomService)!=null?n:new Xr(this.context),this.category=(i=t.categoryService)!=null?i:new jt(this.context),this.customer=(a=t.customerService)!=null?a:new $t(this.context),this.customerGroup=(o=t.customerGroupService)!=null?o:new Vt(this.context),this.history=(s=t.historyService)!=null?s:new zt(this.context),this.order=(d=t.orderService)!=null?d:new Kt(this.context),this.orderItem=(c=t.orderItemService)!=null?c:new Zr(this.context),this.priceTier=(p=t.priceTierService)!=null?p:new Gt(this.context),this.product=(l=t.productService)!=null?l:new Wt(this.context),this.promotion=(m=t.promotionService)!=null?m:new Yt(this.context),this.returnService=(f=t.returnService)!=null?f:new Zt(this.context,r),this.returnItem=(y=t.returnItemService)!=null?y:new tn(this.context),this.role=(b=t.roleService)!=null?b:new rn(this.context),this.sale=(h=t.saleService)!=null?h:new er(this.context,r),this.saleItem=(g=t.saleItemService)!=null?g:new nn(this.context),this.shift=(x=t.shiftService)!=null?x:new tr(this.context),this.taxRate=(v=t.taxRateService)!=null?v:new an(this.context),this.transaction=(A=t.transactionService)!=null?A:new rr(this.context,r),this.uom=(I=t.uomService)!=null?I:new nr(this.context),this.user=(k=t.userService)!=null?k:new on(this.context),this.supplier=(w=t.supplierService)!=null?w:new ir(this.context),this.purchaseOrder=(q=t.purchaseOrderService)!=null?q:new ar(this.context),this.purchaseOrderItem=(M=t.purchaseOrderItemService)!=null?M:new sn(this.context),this.purchase=(E=t.purchaseService)!=null?E:new or(this.context,r),this.purchaseItem=(L=t.purchaseItemService)!=null?L:new cn(this.context),this.inventoryLog=(Q=t.inventoryLogService)!=null?Q:new sr(this.context),this.priceHistory=(T=t.priceHistoryService)!=null?T:new cr(this.context),this.stockOpname=(z=t.stockOpnameService)!=null?z:new ur(this.context),this.stockOpnameItem=(V=t.stockOpnameItemService)!=null?V:new un(this.context),this.stockAdjustment=(F=t.stockAdjustmentService)!=null?F:new dr(this.context),this.reportSchedule=(U=t.reportScheduleService)!=null?U:new lr(this.context),this.financialSetting=(O=t.financialSettingService)!=null?O:new pr(this.context),this.expense=(_=t.expenseService)!=null?_:new mr(this.context,r),this.receivable=(R=t.receivableService)!=null?R:new hr(this.context),this.payable=(P=t.payableService)!=null?P:new fr(this.context),this.settlement=(X=t.settlementService)!=null?X:new gr(this.context,r),this.inventory=(te=t.inventoryService)!=null?te:new yr(this.context),this.exportService=(J=t.exportService)!=null?J:new vr(this.context),this.pricing=(Y=t.pricingService)!=null?Y:new xr(this.context),this.reporting=(be=t.reportingService)!=null?be:new Sr(this.context),this.cart=(se=t.cartService)!=null?se:new Pr(this.context),this.tax=(Ne=t.taxService)!=null?Ne:new Dr(this.context),this.stockTransfer=(pe=t.stockTransferService)!=null?pe:new hn(this.context)}};var Pt={status:"idle",queue:[],queueLength:0,conflicts:[],deadLetters:[],metrics:{totalPushAttempted:0,totalPushSucceeded:0,totalPushFailed:0,totalPullApplied:0,totalConflictsRecorded:0,lastQueueLatencyMs:0,lastRunDurationMs:0,lastRunAt:null},lastError:null,lastSyncAt:null},vi="sync-store",wr=class{constructor(e){this.context=e;var t;this.emitter=_t(),this.storage=(t=this.context.registry)==null?void 0:t.storageAdapter,this.state={...Pt},this.load().then(r=>{r&&(this.state=r,this.emitter.emit("update",this.getState()))})}subscribe(e){return e(this.state),this.emitter.on("update",e),()=>this.emitter.off("update",e)}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.save(),this.emitter.emit("update",this.getState())}normalizeChange(e){var y,b,h,g,x;let t=(y=e==null?void 0:e.table)!=null?y:e==null?void 0:e.model,r=(b=e==null?void 0:e.record)!=null?b:{},n=typeof(r==null?void 0:r.id)=="string"?r.id:void 0,i=(h=e==null?void 0:e.id)!=null?h:n;if(typeof t!="string"||!t||typeof i!="string"||!i)return this.context.logError(new Error("Invalid sync change payload"),{raw:e}),null;let a=String((g=e==null?void 0:e.type)!=null?g:"").toUpperCase(),o=a==="CREATE"||a==="UPDATE"||a==="DELETE"?a:"UPDATE",s=Number(e==null?void 0:e.updated_at),d=Date.parse(String((x=r==null?void 0:r.lastModified)!=null?x:"")),c=Number.isFinite(s)&&s>0?s:Number.isFinite(d)&&d>0?d:Date.now(),p=Number(e==null?void 0:e.firstQueuedAt),l=Number(e==null?void 0:e.retryCount),m=Number(e==null?void 0:e.lastAttemptAt),f=e==null?void 0:e.lastErrorMessage;return{id:i,table:t,type:o,record:r,updated_at:c,firstQueuedAt:Number.isFinite(p)&&p>0?p:Date.now(),retryCount:Number.isFinite(l)&&l>=0?Math.floor(l):0,lastAttemptAt:Number.isFinite(m)&&m>0?m:null,lastErrorMessage:typeof f=="string"&&f.trim()?f.trim():null}}startSync(e){this.setState({status:"syncing",lastError:null}),this.context.logInfo("Sync started",e)}setError(e,t){this.setState({status:"error",lastError:e}),this.context.logError(e,{message:"Sync error",...t||{}})}clearError(){this.state.lastError&&(this.setState({lastError:null}),this.context.logInfo("Error cleared"))}enqueueChange(e){let t=this.normalizeChange(e);if(!t)return;let r=[...this.state.queue,t];this.setState({queue:r,queueLength:r.length}),this.context.logInfo("Enqueued change, queueLength: "+r.length)}dequeueChange(){if(this.state.queue.length===0)return;let[,...e]=this.state.queue;this.setState({queue:e,queueLength:e.length}),this.context.logInfo("Dequeued change, queueLength: "+e.length)}removeQueuedChange(e){if(!e)return;let t=this.state.queue.filter(r=>r.id!==e);t.length!==this.state.queue.length&&(this.setState({queue:t,queueLength:t.length}),this.context.logInfo(`Removed queued change ${e}, queueLength: ${t.length}`))}addConflict(e){let t=[...this.state.conflicts,e];this.setState({conflicts:t,metrics:{...this.state.metrics,totalConflictsRecorded:this.state.metrics.totalConflictsRecorded+1}}),this.context.logInfo("Conflict added, total conflicts: "+t.length)}markRetryAttempt(e,t){let r=Date.now(),n=this.state.queue.map(i=>i.id!==e?i:{...i,retryCount:i.retryCount+1,lastAttemptAt:r,lastErrorMessage:t instanceof Error?t.message:String(t||"")});this.setState({queue:n,queueLength:n.length})}moveToDeadLetter(e,t,r){let n=this.state.queue.find(o=>o.id===e);if(!n)return;let i=this.state.queue.filter(o=>o.id!==e),a=[...this.state.deadLetters,{movedAt:Date.now(),reason:t,attempts:n.retryCount,errorMessage:r instanceof Error?r.message:String(r||""),change:n}];this.setState({queue:i,queueLength:i.length,deadLetters:a}),this.context.logInfo(`Change ${e} moved to dead-letter queue (${t})`)}requeueDeadLetter(e){let t=this.state.deadLetters.findIndex(a=>a.change.id===e);if(t<0)return!1;let r=this.state.deadLetters[t],n=this.state.deadLetters.filter((a,o)=>o!==t),i=[...this.state.queue,{...r.change,retryCount:0,lastAttemptAt:null,lastErrorMessage:null,firstQueuedAt:Date.now()}];return this.setState({deadLetters:n,queue:i,queueLength:i.length}),this.context.logInfo(`Dead-letter ${e} requeued`),!0}recordSyncMetrics(e){this.setState({metrics:{...this.state.metrics,...e}})}clearConflicts(){this.state.conflicts.length>0&&(this.setState({conflicts:[]}),this.context.logInfo("Conflicts cleared"))}setLastSyncAt(e){this.setState({lastSyncAt:e}),this.context.logInfo("Last sync at set to "+e)}finishSync(e){this.setState({status:"idle"}),this.context.logInfo("Sync finished",e)}logoutLocal(){this.state={...Pt};try{this.storage.removeItem(vi)}catch(e){this.context.logError(e,{message:"Gagal clear sync-store saat logout"})}this.emitter.emit("update",this.getState()),this.context.logInfo("Local logout performed; sync-store cleared")}save(){try{this.storage.setItem(vi,JSON.stringify(this.state))}catch(e){this.context.logError(e,{message:"Gagal persist sync-store"})}}async load(){try{let e=await this.storage.getItem(vi);if(!e)return null;let t=JSON.parse(e),r=Array.isArray(t.queue)?t.queue.map(s=>this.normalizeChange(s)).filter(s=>s!==null):[],n=Array.isArray(t.conflicts)?t.conflicts.filter(s=>typeof s=="object"&&s!==null):[],i=Array.isArray(t.deadLetters)?t.deadLetters.filter(s=>{if(!s||typeof s!="object")return!1;let d=s;return!!d.change&&typeof d.change.id=="string"}):[],a=t.metrics||{},o={...Pt.metrics,...a};return{...Pt,...t,queue:r,queueLength:r.length,conflicts:n,deadLetters:i,metrics:o,lastError:null}}catch(e){return this.context.logError(e,{message:"Gagal load sync-store"}),null}}async shutdown(){this.emitter=_t()}};var Er=class{constructor(e){this.context=e;this.explicitActionTableMap={createSettlement:"settlements",RecordCashIn:"transactions",RecordCashOut:"transactions",processReturn:"returns",cancelReturn:"returns",ReturnRefundApproved:"returns",CancelReturnApproved:"returns",CloseShiftApproval:"shifts",ReopenShiftApproved:"shifts",PO_PRICE_VARIANCE_DETECTED:"purchases",customerCreditEscalationDetected:"sales",TieredPrice:"products",LoyaltyEarnPoints:"loyalty_ledgers",LoyaltyRedeemPoints:"loyalty_ledgers",LoyaltyExpirePoints:"loyalty_ledgers"};this.entityTableMap={Bom:"boms",Category:"categories",Customer:"customers",CustomerGroup:"customer_groups",Expense:"expenses",FinancialSetting:"financial_settings",History:"histories",InventoryLog:"inventory_logs",InventoryLot:"inventory_lots",KitchenTicket:"kitchen_tickets",KitchenTicketItem:"kitchen_ticket_items",LoyaltyAccount:"loyalty_accounts",LoyaltyLedger:"loyalty_ledgers",Order:"orders",OrderItem:"order_items",Payable:"payables",PriceHistory:"price_histories",PriceTier:"price_tiers",Product:"products",Promotion:"promotions",Purchase:"purchases",PurchaseItem:"purchase_items",PurchaseOrder:"purchase_orders",PurchaseOrderItem:"purchase_order_items",Receivable:"receivables",ReportSchedule:"report_schedules",Return:"returns",ReturnItem:"return_items",Role:"roles",Sale:"sales",SaleItem:"sale_items",Settlement:"settlements",Shift:"shifts",StockAdjustment:"stock_adjustments",StockOpname:"stock_opnames",StockOpnameItem:"stock_opname_items",Supplier:"suppliers",TaxRate:"tax_rates",Transaction:"transactions",Uom:"uoms",User:"users"};var t;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter}inferEntityFromAction(e){let t=String(e||"").trim();if(!t)return null;let r=t.match(/^(Add|Update|Delete|Duplicate)([A-Z].*)$/);if(r)return r[2];let n=t.match(/^(create|record|process|cancel|close|reopen)([A-Z].*)$/);return n?n[2]:null}inferTableName(e,t){let r=String((t==null?void 0:t.tableName)||"").trim();if(r)return r;let n=(t==null?void 0:t.itemType)==="productId"?"products":(t==null?void 0:t.itemType)==="promotionId"?"promotions":(t==null?void 0:t.itemType)==="bomId"?"boms":"";if(n)return n;let i=this.explicitActionTableMap[e];if(i)return i;let a=this.inferEntityFromAction(e);return a&&this.entityTableMap[a]?this.entityTableMap[a]:"system_events"}resolveRecordId(e){var r,n,i,a,o,s,d;let t=(d=(s=(o=(a=(i=(n=(r=e==null?void 0:e.recordId)!=null?r:e==null?void 0:e.id)!=null?n:e==null?void 0:e.itemId)!=null?i:e==null?void 0:e.productId)!=null?a:e==null?void 0:e.promotionId)!=null?o:e==null?void 0:e.bomId)!=null?s:e==null?void 0:e.newId)!=null?d:e==null?void 0:e.originalId;return t==null||String(t).trim()===""?`activity-${Date.now()}`:String(t)}async logActivity(e,t,r,n){var o,s,d;let i=new Date().toISOString(),a=`${t} | ${e} | ${i}`;try{let c=this.context.config.deploymentMode,p=((o=this.context.session)==null?void 0:o.tenantId)||null,l=this.context.config.branchId||null,m=(r==null?void 0:r.tenantId)||null,f=(r==null?void 0:r.branchId)||null,y=m||p,b=f||l;if(c==="saas"&&(!y||!String(y).trim()))throw new Error("Tenant context is required for audit log entries in SaaS mode (missing tenantId)");if(c==="saas"&&p&&m&&String(m)!==String(p))throw new Error("Tenant isolation violation in audit log context (tenant override mismatch)");if(l&&f&&String(f)!==String(l))throw new Error("Branch isolation violation in audit log context (branch override mismatch)");let h={...r||{},tenantId:y||null,branchId:b||null,deploymentMode:c};await((d=(s=this.context.registry)==null?void 0:s.activitySink)==null?void 0:d.publish({activityId:D(),activityType:e,occurredAt:i,scopeRef:{tenantId:y||void 0,branchId:b||void 0,domain:"ofpos"},actor:{userId:t,source:"shared-core"},payload:h})),this.context.logInfo(a,h);let g=this.inferTableName(e,r),x=this.resolveRecordId(r),v={...h};await(n||this.dbAdapter).create(ie,{id:D(),userId:t,action:e,tableName:g,recordId:x,changes:v,timestamp:i})}catch(c){this.context.logError(c,{action:e,userId:t,extraContext:r})}}};var Or=class{constructor(e){this.context=e;this.recordCache=new Map;this.allCache=null;var t;this.db=(t=this.context.registry)==null?void 0:t.dbAdapter}async create(e){this.validateData(e,["name","permissions"]);let t=new Date().toISOString(),r={id:D().toString(),name:e.name,permissions:JSON.stringify(e.permissions),version:1,lastModified:t,deleted:!1},n=await this.db.create(Ce,r),i=this.denormalize(n);return this.recordCache.set(i.id,i),this.allCache=null,i}async update(e,t){if(!e)throw new Error("Missing role id for update");let r=await this.db.get(Ce,e);if(!r)throw new Error(`Role not found: ${e}`);let n=new Date().toISOString(),a={version:r.version+1,lastModified:n};t.name!==void 0&&(a.name=t.name),t.permissions!==void 0&&(a.permissions=JSON.stringify(t.permissions));let o=await this.db.update(Ce,e,a);if(!o)throw new Error(`Role not found: ${e}`);let s=this.denormalize(o);return this.recordCache.set(e,s),this.allCache=null,s}async delete(e){if(!e)throw new Error("Missing role id for delete");let t=await this.db.get(Ce,e);if(!t)return;if(!await this.db.update(Ce,e,{deleted:!0,version:t.version+1,lastModified:new Date().toISOString()}))throw new Error(`Role not found: ${e}`);this.recordCache.delete(e),this.allCache=null}async queryAll(){if(this.allCache)return this.allCache;let t=(await this.db.query(Ce,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}]})).map(this.denormalize);this.recordCache.clear();for(let r of t)this.recordCache.set(r.id,r);return this.allCache=t,t}async getById(e){if(!e)return null;let t=this.recordCache.get(e);if(t&&!t.deleted)return t;let r=await this.db.get(Ce,e);if(!r||r.deleted)return null;let n=this.denormalize(r);return this.recordCache.set(e,n),n}denormalize(e){return{...e,permissions:JSON.parse(e.permissions)}}validateData(e,t){for(let r of t)if(e[r]===void 0)throw new Error(`Field '${r}' is required`)}};var xi={version:"gau-v1",rules:[{action:"void",requiredPermission:"sale:void",thresholdAmount:0,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin","manager"]},{action:"refund",requiredPermission:"refund:process",thresholdAmount:1e5,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin","manager"]},{action:"settlement_adjustment",requiredPermission:"settlement:adjust",thresholdAmount:25e4,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin","manager"]},{action:"credit_limit_approval",requiredPermission:"credit:approve",thresholdAmount:5e5,approvalRequiredAboveThreshold:!0,approverRoles:["owner","admin"]}]},Rr=class{constructor(e){this.context=e;this.roleAdapter=new Or(e),this.changeQueue=H(this.context)}enqueue(e,t,r){this.changeQueue.enqueue({type:e,model:t,record:r})}async addRole(e,t){let r=await this.roleAdapter.create(e);return this.enqueue("create","roles",r),this.context.logActivity("AddRole",{id:r.id}),r}async updateRole(e,t,r){let n=await this.roleAdapter.update(e,t);return this.enqueue("update","roles",n),this.context.logActivity("UpdateRole",{id:e}),n}async deleteRole(e,t){return await this.roleAdapter.delete(e),this.enqueue("delete","roles",{id:e}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async getRoles(e){var a;let t=(a=this.context.registry)==null?void 0:a.dbAdapter,r={deleted:!1},n=e!=null&&e.filters?{and:[e.filters,r]}:r;return await t.query(Ce,{...e,filters:n})}async getRoleById(e){return this.roleAdapter.getById(e)}hasPermission(e,t){return Array.isArray(e.permissions)&&(e.permissions.includes("all")||e.permissions.includes(t))}async can(e,t){let r=await this.getRoleById(e.role);return this.hasPermission(r,t)}getGranularPolicy(){return xi}normalizeRole(e){return String(e||"").trim().toLowerCase()}isApprovalValid(e,t){let r=String((e==null?void 0:e.approvedBy)||"").trim(),n=String((e==null?void 0:e.reason)||"").trim(),i=this.normalizeRole(e==null?void 0:e.approverRole);return!r||!n||!i?!1:t.includes(i)}async evaluateGranularAuthorization(e){var c,p,l,m,f;let t=D(),n=(e.policy||xi).rules.find(y=>y.action===e.action);if(!n)throw new Error(`Granular authorization rule is not defined for action "${e.action}"`);let i=Number.isFinite(e.amount)?Number(e.amount):0,a=await this.getRoleById(e.actor.role);if(!(!!a&&this.hasPermission(a,n.requiredPermission))){let y={decisionId:t,action:e.action,status:"deny",reasonCode:"ROLE_OR_PERMISSION_DENIED",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((c=this.context.session)==null?void 0:c.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!(n.approvalRequiredAboveThreshold&&i>n.thresholdAmount)){let y={decisionId:t,action:e.action,status:"allow",reasonCode:"ALLOW_BELOW_THRESHOLD",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((p=this.context.session)==null?void 0:p.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!e.approval){let y={decisionId:t,action:e.action,status:"require_approval",reasonCode:"THRESHOLD_APPROVAL_REQUIRED",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((l=this.context.session)==null?void 0:l.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!this.isApprovalValid(e.approval,n.approverRoles.map(y=>this.normalizeRole(y)))){let y={decisionId:t,action:e.action,status:"deny",reasonCode:"APPROVAL_INVALID",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((m=this.context.session)==null?void 0:m.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount,approvedBy:e.approval.approvedBy,approvalReason:e.approval.reason,approverRole:this.normalizeRole(e.approval.approverRole)}),y}let d={decisionId:t,action:e.action,status:"allow",reasonCode:"ALLOW_WITH_APPROVAL",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:d.status,reasonCode:d.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((f=this.context.session)==null?void 0:f.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount,approvedBy:e.approval.approvedBy,approvalReason:e.approval.reason,approverRole:this.normalizeRole(e.approval.approverRole)}),d}};var Xn=Mt(Ii()),Fr=class{constructor(e,t){this.context=e;this.keySettingName="encryption_key";var r,n;this.secretKey=t||this.context.config.encryptionKey,this.adapter=(r=this.context.registry)==null?void 0:r.dbAdapter,this.encryptionAdapter=(n=this.context.registry)==null?void 0:n.encryptionAdapter}get masterKey(){return this.context.config.encryptionPassphrase}encryptData(e){let t=typeof e=="string"?e:JSON.stringify(e),r=this.encryptionAdapter.encrypt(t,{keyId:this.keySettingName,metadata:{secretKey:this.secretKey}});if(r&&typeof r.then=="function")throw new Error("Shared-core encryption path requires synchronous EncryptionAdapter.encrypt");return String(r||"")}decryptData(e){try{let t=this.encryptionAdapter.decrypt(e,{keyId:this.keySettingName,metadata:{secretKey:this.secretKey}});if(t&&typeof t.then=="function")throw new Error("Shared-core encryption path requires synchronous EncryptionAdapter.decrypt");if(!t)return null;try{return JSON.parse(String(t))}catch{return String(t)}}catch{return null}}async setItem(e,t){let r=this.encryptData(t);await this.adapter.get("settings",e)?await this.adapter.update("settings",e,{value:r}):await this.adapter.create("settings",{id:e,value:r})}async getItem(e){let t=await this.adapter.get("settings",e);return t!=null&&t.value?this.decryptData(t.value):null}async storeKey(e=this.keySettingName){let t=Xn.default.AES.encrypt(this.secretKey,this.masterKey).toString();await this.adapter.get("settings",e)?await this.adapter.update("settings",e,{value:t}):await this.adapter.create("settings",{id:e,value:t})}async retrieveKey(e=this.keySettingName){let t=await this.adapter.get("settings",e);if(!(t!=null&&t.value))return!1;let n=Xn.default.AES.decrypt(t.value,this.masterKey).toString(Xn.default.enc.Utf8);return n?(this.secretKey=n,!0):!1}async rotateKey(e,t=this.keySettingName,r=["auth_token"]){let n=Array.from(new Set(r.map(a=>String(a||"").trim()).filter(a=>a.length>0))),i=[];for(let a of n){let o=await this.getItem(a);o!==null&&i.push({key:a,value:o})}this.secretKey=e,await this.storeKey(t);for(let a of i)await this.setItem(a.key,a.value)}};var kr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter}authorityProvisioningError(e){let t=new Error(`User ${e} is not allowed in ofpos-shared-core. Identity authority must be managed by ofauth-* and synced as projection to POS.`);return t.code="AUTH_AUTHORITY_REQUIRED",t}async addUser(e){throw this.authorityProvisioningError("add")}async updateUser(e,t){throw this.authorityProvisioningError("update")}async deleteUser(e){throw this.authorityProvisioningError("delete")}async fetchUsers(e){let t=this.dbAdapter,r={deleted:!1},n=e!=null&&e.filters?{and:[e.filters,r]}:r;return await t.query(je,{...e,filters:n})}setActiveSession(e){var t,r,n;this.activeSession=e,this.context.logInfo("auth.session.activated",{userId:e.id,username:e.username}),(n=(r=(t=this.context).getSessionStore)==null?void 0:r.call(t))==null||n.login(e)}logoutLocal(){var e,t,r;this.activeSession=void 0,(r=(t=(e=this.context).getSessionStore)==null?void 0:t.call(e))==null||r.logout(),this.context.logInfo("auth.session.deactivated")}getActiveSession(){return this.activeSession}};var Br=Pe("ofcore"),mt=Pe("ofcore");var Mr=class{constructor(e){this.context=e;var t,r,n;if(this.encryptionService=(t=this.context.integrationServices)==null?void 0:t.encryption,this.httpAdapter=(r=this.context.registry)==null?void 0:r.httpAdapter,this.httpRetryPolicy=(n=this.context.registry)==null?void 0:n.httpRetryPolicy,!this.httpAdapter)throw new Error("ApiService requires HttpAdapter from registry")}validateSyncProtocolHandshake(e,t){var s;if(!(e.includes("/sync/push")||e.includes("/sync/pull"))||!this.context.config.enforceSyncProtocolHandshake)return;let n=t||{},i=(s=n["x-sync-protocol-version"])!=null?s:n["x-server-protocol-version"];if(i==null||i==="")throw new Error("Sync protocol handshake failed: missing server protocol version header");let a=Number(i);if(!Number.isInteger(a)||a<0)throw new Error(`Sync protocol handshake failed: invalid server protocol version "${i}"`);let o=this.context.config.syncCompatibleServerVersions;if(!yi(a,o))throw new Error(`Sync protocol mismatch: server=${a}, client=${this.context.config.syncProtocolVersion}, compatible=[${o.join(",")}]`)}async buildHeaders(e,t,r,n={}){var d;let i={...n},a=await this.encryptionService.getItem("auth_token");a&&(i.Authorization=`Bearer ${a}`);let o=t.includes("/sync/push")||t.includes("/sync/pull"),s=t.startsWith("/sync/")||t.startsWith("/erp")||t.startsWith("/shifts/")||t.startsWith("/backup/");try{let c=this.context.config.branchId;c&&(i["X-Branch-ID"]=c)}catch{}if(s&&this.context.config.deploymentMode==="saas"){let c=(d=this.context.session)==null?void 0:d.tenantId;if(!c||!String(c).trim())throw new Error("Tenant context is required for tenant-scoped requests in SaaS mode (missing tenantId)");i["X-Tenant-ID"]=c}if(e==="POST"&&t.includes("/sync/push")&&r){let c=typeof r=="string"?r:JSON.stringify(r),p=this.context.checksum(c);if(!p)throw new Error("paymentSigningKey is required for sync push checksum");i["X-Data-Checksum"]=p}return o&&(i["X-Sync-Protocol-Version"]=String(this.context.config.syncProtocolVersion),i["X-Sync-Compatible-Versions"]=this.context.config.syncCompatibleServerVersions.join(",")),i}async requestData(e,t,r={}){let n=await this.buildHeaders(e,t,r.data,r.headers),i=this.context.config.apiUrl||"",a=t.startsWith("http")?t:`${i}${t}`,o=await(0,mt.executeHttpRequestWithRetry)(this.httpAdapter,{method:e,url:a,headers:n,query:r.params,body:r.data,timeoutMs:this.context.config.apiTimeoutMs},{policy:this.httpRetryPolicy});if(o.status===401&&await this.encryptionService.setItem("auth_token",""),this.validateSyncProtocolHandshake(t,o.headers),o.status>=400)throw new Error(`HTTP request failed: ${e} ${t} status=${o.status}`);return o.data}async login(e){let t=await this.requestData("POST","/auth/login",{data:e});if(!(t!=null&&t.token))throw new Error("Authentication failed: no token returned");return await this.encryptionService.setItem("auth_token",t.token),t}async logout(){await this.encryptionService.setItem("auth_token","")}async getProfile(){return this.requestData("GET","/auth/profile")}async getErpData(e,t,r){let n=e?`/erp${e}`:"/sync/erp";return this.requestData("GET",n,{params:t,headers:{...r!=null&&r.correlationId?{"X-Correlation-ID":r.correlationId}:{},...r!=null&&r.syncBatchId?{"X-Sync-Batch-ID":r.syncBatchId}:{}}})}async postErpData(e,t){return this.requestData("POST",`/erp${e}`,{data:t})}async putErpData(e,t){return this.requestData("PUT",`/erp${e}`,{data:t})}async deleteErpData(e,t){return this.requestData("DELETE",`/erp${e}`,{params:t})}async pushChange(e,t){return this.requestData("POST","/sync/push",{data:e,headers:{...t!=null&&t.correlationId?{"X-Correlation-ID":t.correlationId}:{},...t!=null&&t.syncBatchId?{"X-Sync-Batch-ID":t.syncBatchId}:{}}})}async pullChanges(e,t){let r=await this.requestData("GET","/sync/pull",{params:e,headers:{...t!=null&&t.correlationId?{"X-Correlation-ID":t.correlationId}:{},...t!=null&&t.syncBatchId?{"X-Sync-Batch-ID":t.syncBatchId}:{}}});return Array.isArray(r)?r:Array.isArray(r==null?void 0:r.changes)?r.changes:[]}async openShift(){return this.requestData("POST","/shifts/open")}async closeShift(){return this.requestData("POST","/shifts/close")}async getShiftHistory(){return this.requestData("GET","/shifts/history")}async createBackup(e){return this.requestData("POST","/backup/create",{data:e})}async restoreBackup(e){return this.requestData("POST","/backup/restore",{data:e})}async listBackups(e={}){return e.limit===void 0&&(e.limit=this.context.config.apiBackupListLimit),this.requestData("GET","/backup/list",{params:e})}};var Za={products:"server_wins",categories:"server_wins",uoms:"server_wins",customers:"server_wins",suppliers:"server_wins",tax_rates:"server_wins",promotions:"server_wins",price_tiers:"server_wins",users:"server_wins",roles:"server_wins"},Tt=class{async backoff(e){return e()}async applyChanges(){}async syncWithErp(){}async syncLoop(){}},Pi=class{constructor(e){this.context=e;this.lastAlertAtByCode=new Map;this.started=!1;var t,r;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.apiService=(r=e.integrationServices)==null?void 0:r.api,this.syncStore=e.getSyncStore(),this.onDataChanged=()=>{this.syncLoop().catch(n=>this.context.logError(n,{message:"Socket-triggered sync gagal"}))}}start(){this.started||(this.unsubscribeStore=this.syncStore.subscribe(e=>{e.queueLength>0&&(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.syncLoop().catch(t=>this.context.logError(t,{message:"Debounced sync gagal"}))},this.context.config.syncDebounceMs))}),Le.on("data_changed",this.onDataChanged),this.periodicTimer=setInterval(()=>{this.context.isOnline()&&this.syncLoop().catch(e=>this.context.logError(e,{message:"Periodic sync gagal"}))},this.context.config.syncIntervalMs),this.started=!0)}normalizeOutgoingChange(e){var c,p,l,m,f;let t=(c=e==null?void 0:e.table)!=null?c:e==null?void 0:e.model,r=(p=e==null?void 0:e.record)!=null?p:{},n=(l=e==null?void 0:e.id)!=null?l:r==null?void 0:r.id;if(!t||!n)return null;let i=String((m=e==null?void 0:e.type)!=null?m:"").toUpperCase(),a=i==="CREATE"||i==="UPDATE"||i==="DELETE"?i:"UPDATE",o=Number(e==null?void 0:e.updated_at),s=Date.parse(String((f=r==null?void 0:r.lastModified)!=null?f:"")),d=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s:Date.now();return{id:n,table:t,type:a,record:r,updated_at:d}}getRemoteTimestamp(e){var n,i,a;let t=Number(e==null?void 0:e.updated_at);if(Number.isFinite(t)&&t>0)return t;let r=Date.parse(String((a=(i=(n=e==null?void 0:e.record)==null?void 0:n.lastModified)!=null?i:e==null?void 0:e.lastModified)!=null?a:""));return Number.isFinite(r)&&r>0?r:Date.now()}getConflictResolutionStrategy(e){return Za[e]||"local_wins_manual"}requireBranchContext(){var t;if(!String((t=this.context.config.branchId)!=null?t:"").trim())throw new Error("Branch context is required for sync operations (missing branchId)")}async backoff(e,t=this.context.config.syncMaxRetries,r=this.context.config.syncBackoffDelayMs){let n=0;for(;;)try{return await e()}catch(i){if(n++,n>t)throw i;let a=r*Math.pow(2,n)+Math.random()*100;await new Promise(o=>setTimeout(o,a))}}async applyChanges(e,t){var i,a,o;let r=this.dbAdapter,n=this.syncStore;for(let s of e){let d=s==null?void 0:s.table,c=s==null?void 0:s.id;if(!d||!c){this.context.logError(new Error("Invalid remote change payload"),{change:s,...t||{}});continue}let p=this.getRemoteTimestamp(s),l=new Date(p).toISOString(),m=(i=s==null?void 0:s.record)!=null?i:{},f={...m,id:c,lastModified:(a=m==null?void 0:m.lastModified)!=null?a:l};try{let y=await r.get(d,c);if(!y)await r.create(d,f);else{let b=Date.parse(String((o=y==null?void 0:y.lastModified)!=null?o:""));if(!Number.isFinite(b)||p>b)await r.update(d,c,f);else if(p!==b)if(this.getConflictResolutionStrategy(d)==="server_wins")await r.update(d,c,f),this.context.logInfo(`Auto-resolve konflik master data ${d}:${c}`,t);else{let h={table:d,id:c,localLastModified:y==null?void 0:y.lastModified,remoteUpdatedAt:p,local:y,remote:s,reason:"local_newer"};n.addConflict(h),this.context.logInfo(`Konflik terdeteksi ${d}:${c}, dicatat untuk resolusi manual`,t)}}}catch(y){this.context.logError(y,{message:`Error applyChange ${s.table}:${s.id}`,...t||{}})}}}async syncWithErp(e){var t,r,n,i,a,o;try{this.context.logInfo("Mulai sinkronisasi ERP",e);let s=await this.apiService.getErpData(void 0,void 0,e),d=this.dbAdapter;for(let c of(t=s==null?void 0:s.customers)!=null?t:[]){let p=c==null?void 0:c.id;if(!p)continue;let l=await d.get("customers",p),m={...c,lastModified:(r=c==null?void 0:c.lastModified)!=null?r:new Date().toISOString()};l?await d.update("customers",p,m):await d.create("customers",m)}for(let c of(n=s==null?void 0:s.boms)!=null?n:[]){let p=c==null?void 0:c.id;if(!p)continue;let l=await d.get("boms",p),m={...c,lastModified:(i=c==null?void 0:c.lastModified)!=null?i:new Date().toISOString()};l?await d.update("boms",p,m):await d.create("boms",m)}for(let c of(a=s==null?void 0:s.uoms)!=null?a:[]){let p=c==null?void 0:c.id;if(!p)continue;let l=await d.get("uoms",p),m={...c,lastModified:(o=c==null?void 0:c.lastModified)!=null?o:new Date().toISOString()};l?await d.update("uoms",p,m):await d.create("uoms",m)}this.context.logInfo("Sinkronisasi ERP selesai",e)}catch(s){this.context.logError(s,{message:"Sinkronisasi ERP gagal",...e||{}})}}async cleanupDeleted(){this.context.logInfo("cleanupDeleted: belum diimplementasi")}shouldTriggerAlert(e){let t=this.context.config.opsAlertEscalationCooldownMinutes*60*1e3,r=Date.now(),n=this.lastAlertAtByCode.get(e)||0;return r-n<t?!1:(this.lastAlertAtByCode.set(e,r),!0)}emitOperationalAlert(e){if(!this.shouldTriggerAlert(e.code))return;let t={...e.correlationId?{correlationId:e.correlationId}:{},...e.syncBatchId?{syncBatchId:e.syncBatchId}:{},...e.metrics?{metrics:e.metrics}:{},code:e.code,category:e.category,severity:e.severity,at:e.at};e.severity==="critical"?this.context.logError(new Error(e.message),t):this.context.logInfo(e.message,t),Le.emit("ops:alert",e)}evaluateOperationalAlerts(e){let{traceContext:t,pushAttempted:r,pushFailed:n,queueLatencyMs:i,deadLetterCount:a}=e;if(r>0){let o=Math.round(n/r*100);o>=this.context.config.opsAlertSyncFailureRateThresholdPercent&&this.emitOperationalAlert({severity:o>=75?"critical":"warning",category:"sync",code:"SYNC_FAILURE_RATE",message:`Sync failure rate breached threshold (${o}%)`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{failureRatePercent:o,pushAttempted:r,pushFailed:n},at:new Date().toISOString()})}i>=this.context.config.opsAlertQueueLatencyThresholdMs&&this.emitOperationalAlert({severity:i>=this.context.config.opsAlertQueueLatencyThresholdMs*2?"critical":"warning",category:"sync",code:"SYNC_QUEUE_LATENCY",message:`Sync queue latency breached threshold (${i} ms)`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{queueLatencyMs:i},at:new Date().toISOString()}),a>=this.context.config.opsAlertDeadLetterCountThreshold&&this.emitOperationalAlert({severity:a>=this.context.config.opsAlertDeadLetterCountThreshold*2?"critical":"warning",category:"sync",code:"SYNC_DEAD_LETTER",message:`Dead-letter count breached threshold (${a})`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{deadLetterCount:a},at:new Date().toISOString()})}async syncLoop(){if(this.context.config.demoMode){this.context.logInfo("Demo mode enabled: skipping sync");return}let e=this.syncStore,t={correlationId:this.context.createCorrelationId("sync"),syncBatchId:this.context.createCorrelationId("sync-batch")};try{if(!this.context.isOnline()){this.context.logInfo("Offline. Lewati sinkronisasi.",t);return}this.requireBranchContext(),e.startSync(t),e.clearError();let r=e.getState().queue||[],n=Date.now(),i=r.length?Math.round(r.reduce((m,f)=>{let y=Number(f==null?void 0:f.firstQueuedAt);return!Number.isFinite(y)||y<=0?m:m+Math.max(0,n-y)},0)/r.length):0,a=0,o=0,s=0,d=0;for(let m of r)try{a+=1;let f=this.normalizeOutgoingChange(m);if(!f){this.context.logError(new Error("Invalid queued change"),{change:m,...t}),e.removeQueuedChange(String((m==null?void 0:m.id)||"")),s+=1;continue}await this.backoff(()=>this.apiService.pushChange({changes:[f]},t)),e.removeQueuedChange(f.id),o+=1}catch(f){this.context.logError(f,{message:"Gagal push change",...t}),s+=1,e.markRetryAttempt(m.id,f);let y=e.getState().queue.find(b=>b.id===m.id);y&&y.retryCount>=this.context.config.syncMaxRetries&&e.moveToDeadLetter(m.id,"max_retry_exceeded",f)}let c=[];try{let m=e.getState().lastSyncAt;c=await this.backoff(()=>this.apiService.pullChanges({since:m},t)),await this.applyChanges(c,t),d=c.length}catch(m){this.context.logError(m,{message:"Gagal pull/apply changes",...t})}await this.syncWithErp(t),e.setLastSyncAt(Date.now()),await this.cleanupDeleted();let p=Date.now(),l=e.getState().metrics;e.recordSyncMetrics({totalPushAttempted:l.totalPushAttempted+a,totalPushSucceeded:l.totalPushSucceeded+o,totalPushFailed:l.totalPushFailed+s,totalPullApplied:l.totalPullApplied+d,lastQueueLatencyMs:i,lastRunDurationMs:Math.max(0,p-n),lastRunAt:p}),this.evaluateOperationalAlerts({traceContext:t,pushAttempted:a,pushFailed:s,queueLatencyMs:i,deadLetterCount:e.getState().deadLetters.length})}catch(r){this.context.logError(r,{message:"Sync loop error",...t}),e.setError(r,t)}finally{e.finishSync(t),this.context.logInfo("Sync loop selesai",t)}}shutdown(){this.started&&(this.debounceTimer&&clearTimeout(this.debounceTimer),this.periodicTimer&&clearInterval(this.periodicTimer),this.unsubscribeStore&&(this.unsubscribeStore(),this.unsubscribeStore=void 0),Le.off("data_changed",this.onDataChanged),this.started=!1)}};var Ft=class{getSocket(){}shutdown(){}},Di=class u{constructor(e,t="http://localhost:3000"){this.context=e;this.url=t;this.started=!1;var r,n,i,a;if(this.syncStore=(n=(r=this.context).getSyncStore)==null?void 0:n.call(r),this.syncService=(i=this.context.integrationServices)==null?void 0:i.sync,this.debouncedSync=u.debounce(()=>{var o;(o=this.syncService)==null||o.syncLoop()}),this.socketAdapter=(a=this.context.registry)==null?void 0:a.socketAdapter,!this.socketAdapter)throw new Error("SocketService requires SocketAdapter from registry")}static debounce(e,t=1e3){let r;return((...n)=>{r&&clearTimeout(r),r=setTimeout(()=>e(...n),t)})}async start(){this.started||(await this.initSocket(),this.started=!0)}async initSocket(){var r;let e=(r=this.context.integrationServices)==null?void 0:r.encryption,t=await(e==null?void 0:e.getItem("auth_token"));await this.socketAdapter.connect({url:this.url,headers:{...t?{Authorization:`Bearer ${t}`}:{},"X-Branch-ID":this.context.config.branchId||""}}),this.unsubscribeConnect=this.socketAdapter.subscribe("connect",()=>{this.debouncedSync()}),this.unsubscribeDisconnect=this.socketAdapter.subscribe("disconnect",n=>{var a;let i=typeof n=="string"?n:"unknown";(a=this.syncStore)==null||a.setError(new Error(`Socket disconnected: ${i}`))}),this.unsubscribeDataChanged=this.socketAdapter.subscribe("data_changed",()=>{this.debouncedSync()})}getSocket(){return this.socketAdapter}shutdown(){var e,t,r,n,i;this.started&&((e=this.unsubscribeDataChanged)==null||e.call(this),(t=this.unsubscribeConnect)==null||t.call(this),(r=this.unsubscribeDisconnect)==null||r.call(this),this.unsubscribeDataChanged=void 0,this.unsubscribeConnect=void 0,this.unsubscribeDisconnect=void 0,(i=(n=this.socketAdapter)==null?void 0:n.disconnect)==null||i.call(n).catch(()=>{}),this.started=!1)}};var qr=class{constructor(e){this.context=e;this.flushing=!1;this.notificationQueue=[];this.MAX_QUEUE=1e3;var t;if(this.notifier=(t=this.context.registry)==null?void 0:t.notificationAdapter,this.notifier)try{typeof this.notifier.configure=="function"&&this.notifier.configure({}),typeof this.notifier.createChannel=="function"&&this.notifier.createChannel({channelId:"default",channelName:"Default",importance:3})}catch(r){console.error("[PosCore] Error configuring notifications",r)}}async initNotifications(){var t;if(this.flushing||!this.notifier)return;this.flushing=!0;let e=this.notificationQueue;this.notificationQueue=[];for(let r of e)try{await this.notifier.localNotification({channelId:"default",title:r.title,message:r.message})}catch(n){r.retries=((t=r.retries)!=null?t:0)+1,r.retries<5&&this.notificationQueue.push(r),console.error("[PosCore] Error flushing notification, re-queueing",n)}this.flushing=!1}notify(e,t){if(this.notificationQueue.length>=this.MAX_QUEUE&&this.notificationQueue.shift(),!this.notifier){this.notificationQueue.push({title:e,message:t});return}try{this.notifier.localNotification({channelId:"default",title:e,message:t})}catch(r){console.error("[PosCore] Error showing notification",r),this.notificationQueue.push({title:e,message:t})}}};var eo=Pe("ofcore");var Lr=class{constructor(e){this.context=e;this._lowStockThreshold=null;this._paymentSigningKey=null;this._apiUrl=null;this._branchId=null;this._demoMode=null;this._deploymentMode=null;this._requireActiveShiftForCash=null;this._maxCashAdjustmentAmount=null;this._requireShiftCloseApprovalOnDifference=null;this._shiftCloseDifferenceApprovalThreshold=null;this._requireReasonForReturnOperations=null;this._requireApprovalForReturnRefund=null;this._requireApprovalForReturnCancel=null;this._requireLotExpiryForPurchaseReceiving=null;this._lotConsumptionPolicy=null;this._enableCustomerCreditPolicy=null;this._customerCreditMaxOutstandingAmount=null;this._customerCreditBlockOnOverdue=null;this._customerCreditOverdueGraceDays=null;this._customerCreditEscalationThresholdDays=null;this._enableReturnFraudGuard=null;this._returnFraudWindowMinutes=null;this._returnFraudMaxEvents=null;this._returnFraudAction=null;this._returnApprovalBypassRoles=null;this._returnApprovalApproverRoles=null;this._allowPromotionStacking=null;this._promotionSelectionStrategy=null;this._promotionStackingOrder=null;this._pricingRoundingIncrement=null;this._pricingRoundingScope=null;this._enableSequentialDocumentNumbers=null;this._syncProtocolVersion=null;this._syncCompatibleServerVersions=null;this._enforceSyncProtocolHandshake=null;this._onlineAuthMaxFailedAttempts=null;this._onlineAuthLockoutSeconds=null;this._drRpoTargetMinutes=null;this._drRtoTargetMinutes=null;this._backupIntervalMinutes=null;this._backupRestoreDrillIntervalHours=null;this._opsAlertSyncFailureRateThresholdPercent=null;this._opsAlertQueueLatencyThresholdMs=null;this._opsAlertDeadLetterCountThreshold=null;this._opsAlertEscalationCooldownMinutes=null;this._auditLogRetentionDays=null;this._auditLogArchiveBeforePurge=null;this._auditLogPurgeBatchSize=null;this._sessionIdleTimeoutMinutes=null;this._sessionReauthTimeoutMinutes=null;this._apiTimeoutMs=null;this._syncIntervalMs=null;this._syncMaxRetries=null;this._syncBackoffDelayMs=null;this._syncDebounceMs=null;this._reportingTopSellingLimit=null;this._reportingLowStockLimit=null;this._apiBackupListLimit=null;this._encryptionKey=null;this._encryptionPassphrase=null;var r,n;let t=this.context.registry;this.platformAdapter=(r=t==null?void 0:t.platformAdapter)!=null?r:new eo.DefaultPlatformAdapter(this.context),this.storage=(n=t==null?void 0:t.storageAdapter)!=null?n:new yt(this.context)}async init(){let e=await this.storage.getItem("config");if(e)try{let t=JSON.parse(e);this._lowStockThreshold=t.lowStockThreshold?Number(t.lowStockThreshold):this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=t.paymentSigningKey?t.paymentSigningKey:this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=t.apiUrl?t.apiUrl:this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=t.branchId?t.branchId:this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=t.demoMode!=null?!!t.demoMode:this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let r=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE"),n=t.deploymentMode==="saas"||t.deploymentMode==="standalone"?t.deploymentMode:r==="saas"||r==="standalone"?r:null;this._deploymentMode=n,this._requireActiveShiftForCash=t.requireActiveShiftForCash!=null?!!t.requireActiveShiftForCash:null,this._maxCashAdjustmentAmount=t.maxCashAdjustmentAmount!=null?Number(t.maxCashAdjustmentAmount):null,this._requireShiftCloseApprovalOnDifference=t.requireShiftCloseApprovalOnDifference!=null?!!t.requireShiftCloseApprovalOnDifference:null,this._shiftCloseDifferenceApprovalThreshold=t.shiftCloseDifferenceApprovalThreshold!=null?Number(t.shiftCloseDifferenceApprovalThreshold):null,this._requireReasonForReturnOperations=t.requireReasonForReturnOperations!=null?!!t.requireReasonForReturnOperations:null,this._requireApprovalForReturnRefund=t.requireApprovalForReturnRefund!=null?!!t.requireApprovalForReturnRefund:null,this._requireApprovalForReturnCancel=t.requireApprovalForReturnCancel!=null?!!t.requireApprovalForReturnCancel:null,this._requireLotExpiryForPurchaseReceiving=t.requireLotExpiryForPurchaseReceiving!=null?!!t.requireLotExpiryForPurchaseReceiving:null,this._lotConsumptionPolicy=t.lotConsumptionPolicy==="FEFO"||t.lotConsumptionPolicy==="FIFO"?t.lotConsumptionPolicy:null,this._enableCustomerCreditPolicy=t.enableCustomerCreditPolicy!=null?!!t.enableCustomerCreditPolicy:null,this._customerCreditMaxOutstandingAmount=t.customerCreditMaxOutstandingAmount!=null?Number(t.customerCreditMaxOutstandingAmount):null,this._customerCreditBlockOnOverdue=t.customerCreditBlockOnOverdue!=null?!!t.customerCreditBlockOnOverdue:null,this._customerCreditOverdueGraceDays=t.customerCreditOverdueGraceDays!=null?Number(t.customerCreditOverdueGraceDays):null,this._customerCreditEscalationThresholdDays=t.customerCreditEscalationThresholdDays!=null?Number(t.customerCreditEscalationThresholdDays):null,this._enableReturnFraudGuard=t.enableReturnFraudGuard!=null?!!t.enableReturnFraudGuard:null,this._returnFraudWindowMinutes=t.returnFraudWindowMinutes!=null?Number(t.returnFraudWindowMinutes):null,this._returnFraudMaxEvents=t.returnFraudMaxEvents!=null?Number(t.returnFraudMaxEvents):null,this._returnFraudAction=t.returnFraudAction==="require_approval"||t.returnFraudAction==="block"?t.returnFraudAction:null,this._returnApprovalBypassRoles=Array.isArray(t.returnApprovalBypassRoles)?t.returnApprovalBypassRoles.map(i=>String(i)):null,this._returnApprovalApproverRoles=Array.isArray(t.returnApprovalApproverRoles)?t.returnApprovalApproverRoles.map(i=>String(i)):null,this._allowPromotionStacking=t.allowPromotionStacking!=null?!!t.allowPromotionStacking:null,this._promotionSelectionStrategy=t.promotionSelectionStrategy==="best_discount"||t.promotionSelectionStrategy==="first_valid"?t.promotionSelectionStrategy:null,this._promotionStackingOrder=t.promotionStackingOrder==="input_order"||t.promotionStackingOrder==="percent_then_fixed"||t.promotionStackingOrder==="fixed_then_percent"?t.promotionStackingOrder:null,this._pricingRoundingIncrement=t.pricingRoundingIncrement!=null?Number(t.pricingRoundingIncrement):null,this._pricingRoundingScope=t.pricingRoundingScope==="line"||t.pricingRoundingScope==="total"?t.pricingRoundingScope:null,this._enableSequentialDocumentNumbers=t.enableSequentialDocumentNumbers!=null?!!t.enableSequentialDocumentNumbers:null,this._syncProtocolVersion=Number.isInteger(t.syncProtocolVersion)&&Number(t.syncProtocolVersion)>=0?Number(t.syncProtocolVersion):null,this._syncCompatibleServerVersions=Array.isArray(t.syncCompatibleServerVersions)?t.syncCompatibleServerVersions.map(i=>Number(i)).filter(i=>Number.isInteger(i)&&i>=0):null,this._enforceSyncProtocolHandshake=t.enforceSyncProtocolHandshake!=null?!!t.enforceSyncProtocolHandshake:null,this._onlineAuthMaxFailedAttempts=t.onlineAuthMaxFailedAttempts!=null?Number(t.onlineAuthMaxFailedAttempts):null,this._onlineAuthLockoutSeconds=t.onlineAuthLockoutSeconds!=null?Number(t.onlineAuthLockoutSeconds):null,this._drRpoTargetMinutes=t.drRpoTargetMinutes!=null?Number(t.drRpoTargetMinutes):null,this._drRtoTargetMinutes=t.drRtoTargetMinutes!=null?Number(t.drRtoTargetMinutes):null,this._backupIntervalMinutes=t.backupIntervalMinutes!=null?Number(t.backupIntervalMinutes):null,this._backupRestoreDrillIntervalHours=t.backupRestoreDrillIntervalHours!=null?Number(t.backupRestoreDrillIntervalHours):null,this._opsAlertSyncFailureRateThresholdPercent=t.opsAlertSyncFailureRateThresholdPercent!=null?Number(t.opsAlertSyncFailureRateThresholdPercent):null,this._opsAlertQueueLatencyThresholdMs=t.opsAlertQueueLatencyThresholdMs!=null?Number(t.opsAlertQueueLatencyThresholdMs):null,this._opsAlertDeadLetterCountThreshold=t.opsAlertDeadLetterCountThreshold!=null?Number(t.opsAlertDeadLetterCountThreshold):null,this._opsAlertEscalationCooldownMinutes=t.opsAlertEscalationCooldownMinutes!=null?Number(t.opsAlertEscalationCooldownMinutes):null,this._auditLogRetentionDays=t.auditLogRetentionDays!=null?Number(t.auditLogRetentionDays):null,this._auditLogArchiveBeforePurge=t.auditLogArchiveBeforePurge!=null?!!t.auditLogArchiveBeforePurge:null,this._auditLogPurgeBatchSize=t.auditLogPurgeBatchSize!=null?Number(t.auditLogPurgeBatchSize):null,this._sessionIdleTimeoutMinutes=t.sessionIdleTimeoutMinutes!=null?Number(t.sessionIdleTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=t.sessionReauthTimeoutMinutes!=null?Number(t.sessionReauthTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=t.apiTimeoutMs!=null?Number(t.apiTimeoutMs):this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=t.syncIntervalMs!=null?Number(t.syncIntervalMs):this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=t.syncMaxRetries!=null?Number(t.syncMaxRetries):this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=t.syncBackoffDelayMs!=null?Number(t.syncBackoffDelayMs):this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=t.syncDebounceMs!=null?Number(t.syncDebounceMs):this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=t.reportingTopSellingLimit!=null?Number(t.reportingTopSellingLimit):this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=t.reportingLowStockLimit!=null?Number(t.reportingLowStockLimit):this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=t.apiBackupListLimit!=null?Number(t.apiBackupListLimit):this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=t.encryptionKey?t.encryptionKey:this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=t.encryptionPassphrase?t.encryptionPassphrase:this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}catch(t){this.context.logError(t,{message:"Gagal mengurai konfigurasi dari storage"})}else{this._lowStockThreshold=this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let t=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE");this._deploymentMode=t==="saas"||t==="standalone"?t:null,this._requireActiveShiftForCash=null,this._maxCashAdjustmentAmount=null,this._requireShiftCloseApprovalOnDifference=null,this._shiftCloseDifferenceApprovalThreshold=null,this._requireReasonForReturnOperations=null,this._requireApprovalForReturnRefund=null,this._requireApprovalForReturnCancel=null,this._requireLotExpiryForPurchaseReceiving=null,this._lotConsumptionPolicy=null,this._enableCustomerCreditPolicy=null,this._customerCreditMaxOutstandingAmount=null,this._customerCreditBlockOnOverdue=null,this._customerCreditOverdueGraceDays=null,this._customerCreditEscalationThresholdDays=null,this._enableReturnFraudGuard=null,this._returnFraudWindowMinutes=null,this._returnFraudMaxEvents=null,this._returnFraudAction=null,this._returnApprovalBypassRoles=null,this._returnApprovalApproverRoles=null,this._allowPromotionStacking=null,this._promotionSelectionStrategy=null,this._promotionStackingOrder=null,this._pricingRoundingIncrement=null,this._pricingRoundingScope=null,this._enableSequentialDocumentNumbers=null,this._syncProtocolVersion=null,this._syncCompatibleServerVersions=null,this._enforceSyncProtocolHandshake=null,this._onlineAuthMaxFailedAttempts=null,this._onlineAuthLockoutSeconds=null,this._drRpoTargetMinutes=null,this._drRtoTargetMinutes=null,this._backupIntervalMinutes=null,this._backupRestoreDrillIntervalHours=null,this._opsAlertSyncFailureRateThresholdPercent=null,this._opsAlertQueueLatencyThresholdMs=null,this._opsAlertDeadLetterCountThreshold=null,this._opsAlertEscalationCooldownMinutes=null,this._auditLogRetentionDays=null,this._auditLogArchiveBeforePurge=null,this._auditLogPurgeBatchSize=null,this._sessionIdleTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}}get apiUrl(){return this._apiUrl||"https://localhost:3000/api"}get lowStockThreshold(){return this._lowStockThreshold!=null?this._lowStockThreshold:10}get paymentSigningKey(){return this._paymentSigningKey||""}get demoMode(){return this._demoMode===!0}get branchId(){return this._branchId}get deploymentMode(){var e;return(e=this._deploymentMode)!=null?e:"standalone"}get requireActiveShiftForCash(){return this._requireActiveShiftForCash===!0}get maxCashAdjustmentAmount(){return this._maxCashAdjustmentAmount}get requireShiftCloseApprovalOnDifference(){return this._requireShiftCloseApprovalOnDifference===!0}get shiftCloseDifferenceApprovalThreshold(){return this._shiftCloseDifferenceApprovalThreshold}get requireReasonForReturnOperations(){return this._requireReasonForReturnOperations===!0}get requireApprovalForReturnRefund(){return this._requireApprovalForReturnRefund===!0}get requireApprovalForReturnCancel(){return this._requireApprovalForReturnCancel===!0}get requireLotExpiryForPurchaseReceiving(){return this._requireLotExpiryForPurchaseReceiving===!0}get lotConsumptionPolicy(){var e;return(e=this._lotConsumptionPolicy)!=null?e:"FEFO"}get enableCustomerCreditPolicy(){return this._enableCustomerCreditPolicy===!0}get customerCreditMaxOutstandingAmount(){return this._customerCreditMaxOutstandingAmount!=null&&this._customerCreditMaxOutstandingAmount>=0?this._customerCreditMaxOutstandingAmount:null}get customerCreditBlockOnOverdue(){return this._customerCreditBlockOnOverdue===!0}get customerCreditOverdueGraceDays(){return this._customerCreditOverdueGraceDays!=null&&this._customerCreditOverdueGraceDays>=0?this._customerCreditOverdueGraceDays:0}get customerCreditEscalationThresholdDays(){return this._customerCreditEscalationThresholdDays!=null&&this._customerCreditEscalationThresholdDays>0?this._customerCreditEscalationThresholdDays:14}get enableReturnFraudGuard(){return this._enableReturnFraudGuard===!0}get returnFraudWindowMinutes(){return this._returnFraudWindowMinutes!=null&&this._returnFraudWindowMinutes>0?this._returnFraudWindowMinutes:60}get returnFraudMaxEvents(){return this._returnFraudMaxEvents!=null&&this._returnFraudMaxEvents>0?this._returnFraudMaxEvents:3}get returnFraudAction(){var e;return(e=this._returnFraudAction)!=null?e:"require_approval"}get returnApprovalBypassRoles(){return this._returnApprovalBypassRoles}get returnApprovalApproverRoles(){return this._returnApprovalApproverRoles}get allowPromotionStacking(){return this._allowPromotionStacking===!0}get promotionSelectionStrategy(){var e;return(e=this._promotionSelectionStrategy)!=null?e:"best_discount"}get promotionStackingOrder(){var e;return(e=this._promotionStackingOrder)!=null?e:"input_order"}get pricingRoundingIncrement(){return this._pricingRoundingIncrement}get pricingRoundingScope(){var e;return(e=this._pricingRoundingScope)!=null?e:"total"}get enableSequentialDocumentNumbers(){return this._enableSequentialDocumentNumbers===!0}get syncProtocolVersion(){return this._syncProtocolVersion!=null&&Number.isInteger(this._syncProtocolVersion)&&this._syncProtocolVersion>=0?this._syncProtocolVersion:1}get syncCompatibleServerVersions(){let e=this._syncCompatibleServerVersions,t=[...ln],r=Array.isArray(e)?e.filter(i=>Number.isInteger(i)&&i>=0):t,n=r.includes(this.syncProtocolVersion)?r:[this.syncProtocolVersion,...r];return Array.from(new Set(n))}get enforceSyncProtocolHandshake(){return this._enforceSyncProtocolHandshake===!0}get onlineAuthMaxFailedAttempts(){return this._onlineAuthMaxFailedAttempts!=null&&this._onlineAuthMaxFailedAttempts>0?this._onlineAuthMaxFailedAttempts:5}get onlineAuthLockoutSeconds(){return this._onlineAuthLockoutSeconds!=null&&this._onlineAuthLockoutSeconds>0?this._onlineAuthLockoutSeconds:60}get drRpoTargetMinutes(){return this._drRpoTargetMinutes!=null&&this._drRpoTargetMinutes>0?this._drRpoTargetMinutes:1440}get drRtoTargetMinutes(){return this._drRtoTargetMinutes!=null&&this._drRtoTargetMinutes>0?this._drRtoTargetMinutes:240}get backupIntervalMinutes(){return this._backupIntervalMinutes!=null&&this._backupIntervalMinutes>0?this._backupIntervalMinutes:360}get backupRestoreDrillIntervalHours(){return this._backupRestoreDrillIntervalHours!=null&&this._backupRestoreDrillIntervalHours>0?this._backupRestoreDrillIntervalHours:168}get opsAlertSyncFailureRateThresholdPercent(){return this._opsAlertSyncFailureRateThresholdPercent!=null&&this._opsAlertSyncFailureRateThresholdPercent>0?this._opsAlertSyncFailureRateThresholdPercent:30}get opsAlertQueueLatencyThresholdMs(){return this._opsAlertQueueLatencyThresholdMs!=null&&this._opsAlertQueueLatencyThresholdMs>0?this._opsAlertQueueLatencyThresholdMs:300*1e3}get opsAlertDeadLetterCountThreshold(){return this._opsAlertDeadLetterCountThreshold!=null&&this._opsAlertDeadLetterCountThreshold>0?this._opsAlertDeadLetterCountThreshold:10}get opsAlertEscalationCooldownMinutes(){return this._opsAlertEscalationCooldownMinutes!=null&&this._opsAlertEscalationCooldownMinutes>0?this._opsAlertEscalationCooldownMinutes:15}get auditLogRetentionDays(){return this._auditLogRetentionDays!=null&&this._auditLogRetentionDays>0?this._auditLogRetentionDays:365}get auditLogArchiveBeforePurge(){return this._auditLogArchiveBeforePurge!==!1}get auditLogPurgeBatchSize(){return this._auditLogPurgeBatchSize!=null&&this._auditLogPurgeBatchSize>0?this._auditLogPurgeBatchSize:500}get sessionIdleTimeoutMinutes(){return this._sessionIdleTimeoutMinutes!=null&&this._sessionIdleTimeoutMinutes>0?this._sessionIdleTimeoutMinutes:5}get sessionReauthTimeoutMinutes(){return this._sessionReauthTimeoutMinutes!=null&&this._sessionReauthTimeoutMinutes>0?this._sessionReauthTimeoutMinutes:1}get apiTimeoutMs(){return this._apiTimeoutMs!=null&&this._apiTimeoutMs>0?this._apiTimeoutMs:5e3}get syncIntervalMs(){return this._syncIntervalMs!=null&&this._syncIntervalMs>0?this._syncIntervalMs:300*1e3}get syncMaxRetries(){return this._syncMaxRetries!=null&&this._syncMaxRetries>0?this._syncMaxRetries:5}get syncBackoffDelayMs(){return this._syncBackoffDelayMs!=null&&this._syncBackoffDelayMs>0?this._syncBackoffDelayMs:1e3}get syncDebounceMs(){return this._syncDebounceMs!=null&&this._syncDebounceMs>0?this._syncDebounceMs:2e3}get reportingTopSellingLimit(){return this._reportingTopSellingLimit!=null&&this._reportingTopSellingLimit>0?this._reportingTopSellingLimit:5}get reportingLowStockLimit(){return this._reportingLowStockLimit!=null&&this._reportingLowStockLimit>0?this._reportingLowStockLimit:10}get apiBackupListLimit(){return this._apiBackupListLimit!=null&&this._apiBackupListLimit>0?this._apiBackupListLimit:10}get encryptionKey(){return this._encryptionKey||"default_secret_key"}get encryptionPassphrase(){return this._encryptionPassphrase||"default_passphrase"}validateConfig(e){var X,te,J,Y,be,se,Ne,pe,Te,me,We,Ye,Xe,ct,bt,ut,qe,ke,Ue,vt,wt,dt,ht,ft,Et,Ot,lt,st,S,C,B,N,W,he,ve,ee,j;let t=(X=e.requireShiftCloseApprovalOnDifference)!=null?X:this.requireShiftCloseApprovalOnDifference,r=(te=e.shiftCloseDifferenceApprovalThreshold)!=null?te:this.shiftCloseDifferenceApprovalThreshold,n=(J=e.requireApprovalForReturnRefund)!=null?J:this.requireApprovalForReturnRefund,i=(Y=e.requireApprovalForReturnCancel)!=null?Y:this.requireApprovalForReturnCancel,a=(be=e.returnApprovalApproverRoles)!=null?be:this.returnApprovalApproverRoles,o=(se=e.enableReturnFraudGuard)!=null?se:this.enableReturnFraudGuard,s=(Ne=e.returnFraudWindowMinutes)!=null?Ne:this.returnFraudWindowMinutes,d=(pe=e.returnFraudMaxEvents)!=null?pe:this.returnFraudMaxEvents,c=(Te=e.syncProtocolVersion)!=null?Te:this.syncProtocolVersion,p=(me=e.syncCompatibleServerVersions)!=null?me:this.syncCompatibleServerVersions,l=(We=e.enforceSyncProtocolHandshake)!=null?We:this.enforceSyncProtocolHandshake;if(e.maxCashAdjustmentAmount!=null&&e.maxCashAdjustmentAmount<=0)throw new Error("Invalid config: maxCashAdjustmentAmount must be greater than 0");if(t===!0&&(r==null||r<0))throw new Error("Invalid config: shiftCloseDifferenceApprovalThreshold is required and must be >= 0 when requireShiftCloseApprovalOnDifference=true");if(e.pricingRoundingIncrement!=null&&e.pricingRoundingIncrement<=0)throw new Error("Invalid config: pricingRoundingIncrement must be greater than 0");let m=(Ye=e.enableCustomerCreditPolicy)!=null?Ye:this.enableCustomerCreditPolicy,f=(Xe=e.customerCreditMaxOutstandingAmount)!=null?Xe:this.customerCreditMaxOutstandingAmount,y=(ct=e.customerCreditOverdueGraceDays)!=null?ct:this.customerCreditOverdueGraceDays,b=(bt=e.customerCreditEscalationThresholdDays)!=null?bt:this.customerCreditEscalationThresholdDays;if(m){if(f!=null&&f<0)throw new Error("Invalid config: customerCreditMaxOutstandingAmount must be >= 0");if(!Number.isInteger(y)||y<0)throw new Error("Invalid config: customerCreditOverdueGraceDays must be integer >= 0");if(!Number.isInteger(b)||b<=0)throw new Error("Invalid config: customerCreditEscalationThresholdDays must be integer > 0")}if((n===!0||i===!0)&&(!a||a.length===0))throw new Error("Invalid config: returnApprovalApproverRoles is required when return approval is enabled");if(o===!0){if(s==null||s<=0)throw new Error("Invalid config: returnFraudWindowMinutes must be greater than 0 when enableReturnFraudGuard=true");if(d==null||d<=0)throw new Error("Invalid config: returnFraudMaxEvents must be greater than 0 when enableReturnFraudGuard=true")}if(!Number.isInteger(c)||c<0)throw new Error("Invalid config: syncProtocolVersion must be a non-negative integer");if(!Array.isArray(p)||p.length===0)throw new Error("Invalid config: syncCompatibleServerVersions must contain at least one version");if(!p.every($=>Number.isInteger($)&&$>=0))throw new Error("Invalid config: syncCompatibleServerVersions must contain only non-negative integers");if(!p.includes(c))throw new Error("Invalid config: syncCompatibleServerVersions must include syncProtocolVersion");if(l===!0&&p.length===0)throw new Error("Invalid config: enforceSyncProtocolHandshake requires non-empty syncCompatibleServerVersions");let h=(ut=e.onlineAuthMaxFailedAttempts)!=null?ut:this.onlineAuthMaxFailedAttempts,g=(qe=e.onlineAuthLockoutSeconds)!=null?qe:this.onlineAuthLockoutSeconds,x=(ke=e.drRpoTargetMinutes)!=null?ke:this.drRpoTargetMinutes,v=(Ue=e.drRtoTargetMinutes)!=null?Ue:this.drRtoTargetMinutes,A=(vt=e.backupIntervalMinutes)!=null?vt:this.backupIntervalMinutes,I=(wt=e.backupRestoreDrillIntervalHours)!=null?wt:this.backupRestoreDrillIntervalHours,k=(dt=e.opsAlertSyncFailureRateThresholdPercent)!=null?dt:this.opsAlertSyncFailureRateThresholdPercent,w=(ht=e.opsAlertQueueLatencyThresholdMs)!=null?ht:this.opsAlertQueueLatencyThresholdMs,q=(ft=e.opsAlertDeadLetterCountThreshold)!=null?ft:this.opsAlertDeadLetterCountThreshold,M=(Et=e.opsAlertEscalationCooldownMinutes)!=null?Et:this.opsAlertEscalationCooldownMinutes,E=(Ot=e.auditLogRetentionDays)!=null?Ot:this.auditLogRetentionDays,L=(lt=e.auditLogPurgeBatchSize)!=null?lt:this.auditLogPurgeBatchSize;if(!Number.isInteger(h)||h<=0)throw new Error("Invalid config: onlineAuthMaxFailedAttempts must be a positive integer");if(!Number.isInteger(g)||g<=0)throw new Error("Invalid config: onlineAuthLockoutSeconds must be a positive integer");if(!Number.isInteger(x)||x<=0)throw new Error("Invalid config: drRpoTargetMinutes must be a positive integer");if(!Number.isInteger(v)||v<=0)throw new Error("Invalid config: drRtoTargetMinutes must be a positive integer");if(!Number.isInteger(A)||A<=0)throw new Error("Invalid config: backupIntervalMinutes must be a positive integer");if(!Number.isInteger(I)||I<=0)throw new Error("Invalid config: backupRestoreDrillIntervalHours must be a positive integer");if(A>x)throw new Error("Invalid config: backupIntervalMinutes must be <= drRpoTargetMinutes");if(!Number.isInteger(k)||k<=0||k>100)throw new Error("Invalid config: opsAlertSyncFailureRateThresholdPercent must be an integer in range 1..100");if(!Number.isInteger(w)||w<=0)throw new Error("Invalid config: opsAlertQueueLatencyThresholdMs must be a positive integer");if(!Number.isInteger(q)||q<=0)throw new Error("Invalid config: opsAlertDeadLetterCountThreshold must be a positive integer");if(!Number.isInteger(M)||M<=0)throw new Error("Invalid config: opsAlertEscalationCooldownMinutes must be a positive integer");if(!Number.isInteger(E)||E<=0)throw new Error("Invalid config: auditLogRetentionDays must be a positive integer");if(!Number.isInteger(L)||L<=0)throw new Error("Invalid config: auditLogPurgeBatchSize must be a positive integer");let Q=(st=e.sessionIdleTimeoutMinutes)!=null?st:this.sessionIdleTimeoutMinutes,T=(S=e.sessionReauthTimeoutMinutes)!=null?S:this.sessionReauthTimeoutMinutes;if(!Number.isInteger(Q)||Q<=0)throw new Error("Invalid config: sessionIdleTimeoutMinutes must be positive");if(!Number.isInteger(T)||T<=0)throw new Error("Invalid config: sessionReauthTimeoutMinutes must be positive");let z=(C=e.apiTimeoutMs)!=null?C:this.apiTimeoutMs,V=(B=e.syncIntervalMs)!=null?B:this.syncIntervalMs,F=(N=e.syncMaxRetries)!=null?N:this.syncMaxRetries,U=(W=e.syncBackoffDelayMs)!=null?W:this.syncBackoffDelayMs,O=(he=e.syncDebounceMs)!=null?he:this.syncDebounceMs,_=(ve=e.reportingTopSellingLimit)!=null?ve:this.reportingTopSellingLimit,R=(ee=e.reportingLowStockLimit)!=null?ee:this.reportingLowStockLimit,P=(j=e.apiBackupListLimit)!=null?j:this.apiBackupListLimit;if(!Number.isInteger(z)||z<=0)throw new Error("Invalid config: apiTimeoutMs must be positive");if(!Number.isInteger(V)||V<=0)throw new Error("Invalid config: syncIntervalMs must be positive");if(!Number.isInteger(F)||F<=0)throw new Error("Invalid config: syncMaxRetries must be positive");if(!Number.isInteger(U)||U<=0)throw new Error("Invalid config: syncBackoffDelayMs must be positive");if(!Number.isInteger(O)||O<=0)throw new Error("Invalid config: syncDebounceMs must be positive");if(!Number.isInteger(_)||_<=0)throw new Error("Invalid config: reportingTopSellingLimit must be positive");if(!Number.isInteger(R)||R<=0)throw new Error("Invalid config: reportingLowStockLimit must be positive");if(!Number.isInteger(P)||P<=0)throw new Error("Invalid config: apiBackupListLimit must be positive")}async setConfig(e){this.validateConfig(e),e.lowStockThreshold!==void 0&&(this._lowStockThreshold=e.lowStockThreshold),e.paymentSigningKey!==void 0&&(this._paymentSigningKey=e.paymentSigningKey),e.apiUrl!==void 0&&(this._apiUrl=e.apiUrl),e.branchId!==void 0&&(this._branchId=e.branchId),e.demoMode!==void 0&&(this._demoMode=e.demoMode),e.deploymentMode!==void 0&&(this._deploymentMode=e.deploymentMode),e.requireActiveShiftForCash!==void 0&&(this._requireActiveShiftForCash=e.requireActiveShiftForCash),e.maxCashAdjustmentAmount!==void 0&&(this._maxCashAdjustmentAmount=e.maxCashAdjustmentAmount),e.requireShiftCloseApprovalOnDifference!==void 0&&(this._requireShiftCloseApprovalOnDifference=e.requireShiftCloseApprovalOnDifference),e.shiftCloseDifferenceApprovalThreshold!==void 0&&(this._shiftCloseDifferenceApprovalThreshold=e.shiftCloseDifferenceApprovalThreshold),e.requireReasonForReturnOperations!==void 0&&(this._requireReasonForReturnOperations=e.requireReasonForReturnOperations),e.requireApprovalForReturnRefund!==void 0&&(this._requireApprovalForReturnRefund=e.requireApprovalForReturnRefund),e.requireApprovalForReturnCancel!==void 0&&(this._requireApprovalForReturnCancel=e.requireApprovalForReturnCancel),e.requireLotExpiryForPurchaseReceiving!==void 0&&(this._requireLotExpiryForPurchaseReceiving=e.requireLotExpiryForPurchaseReceiving),e.lotConsumptionPolicy!==void 0&&(this._lotConsumptionPolicy=e.lotConsumptionPolicy),e.enableCustomerCreditPolicy!==void 0&&(this._enableCustomerCreditPolicy=e.enableCustomerCreditPolicy),e.customerCreditMaxOutstandingAmount!==void 0&&(this._customerCreditMaxOutstandingAmount=e.customerCreditMaxOutstandingAmount),e.customerCreditBlockOnOverdue!==void 0&&(this._customerCreditBlockOnOverdue=e.customerCreditBlockOnOverdue),e.customerCreditOverdueGraceDays!==void 0&&(this._customerCreditOverdueGraceDays=e.customerCreditOverdueGraceDays),e.customerCreditEscalationThresholdDays!==void 0&&(this._customerCreditEscalationThresholdDays=e.customerCreditEscalationThresholdDays),e.enableReturnFraudGuard!==void 0&&(this._enableReturnFraudGuard=e.enableReturnFraudGuard),e.returnFraudWindowMinutes!==void 0&&(this._returnFraudWindowMinutes=e.returnFraudWindowMinutes),e.returnFraudMaxEvents!==void 0&&(this._returnFraudMaxEvents=e.returnFraudMaxEvents),e.returnFraudAction!==void 0&&(this._returnFraudAction=e.returnFraudAction),e.returnApprovalBypassRoles!==void 0&&(this._returnApprovalBypassRoles=e.returnApprovalBypassRoles),e.returnApprovalApproverRoles!==void 0&&(this._returnApprovalApproverRoles=e.returnApprovalApproverRoles),e.allowPromotionStacking!==void 0&&(this._allowPromotionStacking=e.allowPromotionStacking),e.promotionSelectionStrategy!==void 0&&(this._promotionSelectionStrategy=e.promotionSelectionStrategy),e.promotionStackingOrder!==void 0&&(this._promotionStackingOrder=e.promotionStackingOrder),e.pricingRoundingIncrement!==void 0&&(this._pricingRoundingIncrement=e.pricingRoundingIncrement),e.pricingRoundingScope!==void 0&&(this._pricingRoundingScope=e.pricingRoundingScope),e.enableSequentialDocumentNumbers!==void 0&&(this._enableSequentialDocumentNumbers=e.enableSequentialDocumentNumbers),e.syncProtocolVersion!==void 0&&(this._syncProtocolVersion=e.syncProtocolVersion),e.syncCompatibleServerVersions!==void 0&&(this._syncCompatibleServerVersions=e.syncCompatibleServerVersions),e.enforceSyncProtocolHandshake!==void 0&&(this._enforceSyncProtocolHandshake=e.enforceSyncProtocolHandshake),e.onlineAuthMaxFailedAttempts!==void 0&&(this._onlineAuthMaxFailedAttempts=e.onlineAuthMaxFailedAttempts),e.onlineAuthLockoutSeconds!==void 0&&(this._onlineAuthLockoutSeconds=e.onlineAuthLockoutSeconds),e.drRpoTargetMinutes!==void 0&&(this._drRpoTargetMinutes=e.drRpoTargetMinutes),e.drRtoTargetMinutes!==void 0&&(this._drRtoTargetMinutes=e.drRtoTargetMinutes),e.backupIntervalMinutes!==void 0&&(this._backupIntervalMinutes=e.backupIntervalMinutes),e.backupRestoreDrillIntervalHours!==void 0&&(this._backupRestoreDrillIntervalHours=e.backupRestoreDrillIntervalHours),e.opsAlertSyncFailureRateThresholdPercent!==void 0&&(this._opsAlertSyncFailureRateThresholdPercent=e.opsAlertSyncFailureRateThresholdPercent),e.opsAlertQueueLatencyThresholdMs!==void 0&&(this._opsAlertQueueLatencyThresholdMs=e.opsAlertQueueLatencyThresholdMs),e.opsAlertDeadLetterCountThreshold!==void 0&&(this._opsAlertDeadLetterCountThreshold=e.opsAlertDeadLetterCountThreshold),e.opsAlertEscalationCooldownMinutes!==void 0&&(this._opsAlertEscalationCooldownMinutes=e.opsAlertEscalationCooldownMinutes),e.auditLogRetentionDays!==void 0&&(this._auditLogRetentionDays=e.auditLogRetentionDays),e.auditLogArchiveBeforePurge!==void 0&&(this._auditLogArchiveBeforePurge=e.auditLogArchiveBeforePurge),e.auditLogPurgeBatchSize!==void 0&&(this._auditLogPurgeBatchSize=e.auditLogPurgeBatchSize),e.sessionIdleTimeoutMinutes!==void 0&&(this._sessionIdleTimeoutMinutes=e.sessionIdleTimeoutMinutes),e.sessionReauthTimeoutMinutes!==void 0&&(this._sessionReauthTimeoutMinutes=e.sessionReauthTimeoutMinutes),e.apiTimeoutMs!==void 0&&(this._apiTimeoutMs=e.apiTimeoutMs),e.syncIntervalMs!==void 0&&(this._syncIntervalMs=e.syncIntervalMs),e.syncMaxRetries!==void 0&&(this._syncMaxRetries=e.syncMaxRetries),e.syncBackoffDelayMs!==void 0&&(this._syncBackoffDelayMs=e.syncBackoffDelayMs),e.syncDebounceMs!==void 0&&(this._syncDebounceMs=e.syncDebounceMs),e.reportingTopSellingLimit!==void 0&&(this._reportingTopSellingLimit=e.reportingTopSellingLimit),e.reportingLowStockLimit!==void 0&&(this._reportingLowStockLimit=e.reportingLowStockLimit),e.apiBackupListLimit!==void 0&&(this._apiBackupListLimit=e.apiBackupListLimit),e.encryptionKey!==void 0&&(this._encryptionKey=e.encryptionKey),e.encryptionPassphrase!==void 0&&(this._encryptionPassphrase=e.encryptionPassphrase);let t={lowStockThreshold:this._lowStockThreshold,paymentSigningKey:this._paymentSigningKey,apiUrl:this._apiUrl,branchId:this._branchId,demoMode:this._demoMode,deploymentMode:this._deploymentMode,requireActiveShiftForCash:this._requireActiveShiftForCash,maxCashAdjustmentAmount:this._maxCashAdjustmentAmount,requireShiftCloseApprovalOnDifference:this._requireShiftCloseApprovalOnDifference,shiftCloseDifferenceApprovalThreshold:this._shiftCloseDifferenceApprovalThreshold,requireReasonForReturnOperations:this._requireReasonForReturnOperations,requireApprovalForReturnRefund:this._requireApprovalForReturnRefund,requireApprovalForReturnCancel:this._requireApprovalForReturnCancel,requireLotExpiryForPurchaseReceiving:this._requireLotExpiryForPurchaseReceiving,lotConsumptionPolicy:this._lotConsumptionPolicy,enableCustomerCreditPolicy:this._enableCustomerCreditPolicy,customerCreditMaxOutstandingAmount:this._customerCreditMaxOutstandingAmount,customerCreditBlockOnOverdue:this._customerCreditBlockOnOverdue,customerCreditOverdueGraceDays:this._customerCreditOverdueGraceDays,customerCreditEscalationThresholdDays:this._customerCreditEscalationThresholdDays,enableReturnFraudGuard:this._enableReturnFraudGuard,returnFraudWindowMinutes:this._returnFraudWindowMinutes,returnFraudMaxEvents:this._returnFraudMaxEvents,returnFraudAction:this._returnFraudAction,returnApprovalBypassRoles:this._returnApprovalBypassRoles,returnApprovalApproverRoles:this._returnApprovalApproverRoles,allowPromotionStacking:this._allowPromotionStacking,promotionSelectionStrategy:this._promotionSelectionStrategy,promotionStackingOrder:this._promotionStackingOrder,pricingRoundingIncrement:this._pricingRoundingIncrement,pricingRoundingScope:this._pricingRoundingScope,enableSequentialDocumentNumbers:this._enableSequentialDocumentNumbers,syncProtocolVersion:this._syncProtocolVersion,syncCompatibleServerVersions:this._syncCompatibleServerVersions,enforceSyncProtocolHandshake:this._enforceSyncProtocolHandshake,onlineAuthMaxFailedAttempts:this._onlineAuthMaxFailedAttempts,onlineAuthLockoutSeconds:this._onlineAuthLockoutSeconds,drRpoTargetMinutes:this._drRpoTargetMinutes,drRtoTargetMinutes:this._drRtoTargetMinutes,backupIntervalMinutes:this._backupIntervalMinutes,backupRestoreDrillIntervalHours:this._backupRestoreDrillIntervalHours,opsAlertSyncFailureRateThresholdPercent:this._opsAlertSyncFailureRateThresholdPercent,opsAlertQueueLatencyThresholdMs:this._opsAlertQueueLatencyThresholdMs,opsAlertDeadLetterCountThreshold:this._opsAlertDeadLetterCountThreshold,opsAlertEscalationCooldownMinutes:this._opsAlertEscalationCooldownMinutes,auditLogRetentionDays:this._auditLogRetentionDays,auditLogArchiveBeforePurge:this._auditLogArchiveBeforePurge,auditLogPurgeBatchSize:this._auditLogPurgeBatchSize,sessionIdleTimeoutMinutes:this._sessionIdleTimeoutMinutes,sessionReauthTimeoutMinutes:this._sessionReauthTimeoutMinutes,apiTimeoutMs:this._apiTimeoutMs,syncIntervalMs:this._syncIntervalMs,syncMaxRetries:this._syncMaxRetries,syncBackoffDelayMs:this._syncBackoffDelayMs,syncDebounceMs:this._syncDebounceMs,reportingTopSellingLimit:this._reportingTopSellingLimit,reportingLowStockLimit:this._reportingLowStockLimit,apiBackupListLimit:this._apiBackupListLimit,encryptionKey:this._encryptionKey,encryptionPassphrase:this._encryptionPassphrase};return await this.storage.setItem("config",JSON.stringify(t)),t}};var to="com.offlinepos.backup",Nr=class{constructor(e,t){this.context=e;this.timer=t;this.backupTimerInstance=null;this.restoreDrillTimerInstance=null;this.pendingBackupPayload=null;this.lastBackupAt=null;this.lastRestoreDrillAt=null}start(e,t){if(this.backupTimerInstance){console.warn("[BackupScheduler] Already started");return}this.backupTimerInstance=this.timer.setInterval(()=>this.runBackupTask().catch(()=>{}),e),t&&t>0&&(this.restoreDrillTimerInstance=this.timer.setInterval(()=>this.runRestoreDrill().catch(()=>{}),t)),typeof window!="undefined"&&window.addEventListener&&(this.onlineHandler=()=>{this.pendingBackupPayload&&this.runBackupTask().catch(()=>{})},window.addEventListener("online",this.onlineHandler))}stop(){this.backupTimerInstance&&(this.backupTimerInstance.clear(),this.backupTimerInstance=null),this.restoreDrillTimerInstance&&(this.restoreDrillTimerInstance.clear(),this.restoreDrillTimerInstance=null),typeof window!="undefined"&&window.removeEventListener&&this.onlineHandler&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=void 0),this.context.logInfo("[BackupScheduler] Stopped")}getState(){return{pendingBackup:!!this.pendingBackupPayload,lastBackupAt:this.lastBackupAt,lastRestoreDrillAt:this.lastRestoreDrillAt,started:!!this.backupTimerInstance}}async runBackupTask(){var t;this.apiService||(this.apiService=(t=this.context.integrationServices)==null?void 0:t.api);let e=to;this.context.logInfo(`[BackupScheduler] Starting backup task: ${e}`);try{this.pendingBackupPayload&&(await this.apiService.createBackup(this.pendingBackupPayload),this.context.logInfo("[BackupScheduler] Flushed pending backup payload"),this.pendingBackupPayload=null);let r={label:`scheduled-${new Date().toISOString()}`,reason:"scheduled-backup"};await this.apiService.createBackup(r),this.lastBackupAt=Date.now(),this.context.logInfo(`[BackupScheduler] Backup task completed: ${e}`)}catch(r){this.context.logError(r,{message:`[BackupScheduler] Error in backup task: ${e}`}),this.pendingBackupPayload={label:`retry-${new Date().toISOString()}`,reason:"retry-pending-backup"}}}async runRestoreDrill(){var e;this.apiService||(this.apiService=(e=this.context.integrationServices)==null?void 0:e.api);try{let t=await this.apiService.listBackups({limit:10});if(!Array.isArray(t)||t.length===0){this.context.logInfo("[BackupScheduler] Restore drill skipped: no backups available");return}let r=t.find(i=>((i==null?void 0:i.status)||"ready")==="ready")||t[0],n=String((r==null?void 0:r.id)||(r==null?void 0:r.backupId)||"").trim();if(!n){this.context.logInfo("[BackupScheduler] Restore drill skipped: backupId missing");return}await this.apiService.restoreBackup({backupId:n,dryRun:!0,reason:"scheduled-restore-drill"}),this.lastRestoreDrillAt=Date.now(),this.context.logInfo(`[BackupScheduler] Restore drill completed for backupId=${n}`)}catch(t){this.context.logError(t,{message:"[BackupScheduler] Restore drill failed"})}}};var Qr=class u{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,d,c,p,l;this.context.integrationServices=this,this.activityLogger=(r=t.activityLogger)!=null?r:new Er(this.context),this.config=(n=t.configService)!=null?n:new Lr(this.context),this.authorization=(i=t.authorizationService)!=null?i:new Rr(this.context),this.encryption=(a=t.encryptionService)!=null?a:new Fr(this.context),this.api=(o=t.apiService)!=null?o:new Mr(this.context),this.sync=(s=t.syncService)!=null?s:new Tt,this.socket=(d=t.socketService)!=null?d:new Ft,this.notification=(c=t.notificationService)!=null?c:new qr(this.context),this.user=(p=t.userService)!=null?p:new kr(this.context),this.backupScheduler=(l=t.backupScheduler)!=null?l:new Nr(this.context,{setInterval(m,f){let y=setInterval(m,f);return{clear:()=>clearInterval(y)}}})}static async create(e,t={}){let r=new u(e,t);return r.config.init&&await r.config.init(),r}async shutdown(){var n;let e=this.sync;e&&typeof e.shutdown=="function"&&await e.shutdown();let t=this.socket;if(t&&typeof t.shutdown=="function")t.shutdown();else if(t&&typeof t.getSocket=="function"){let i=t.getSocket();(n=i==null?void 0:i.disconnect)==null||n.call(i)}let r=this.backupScheduler;r&&typeof r.stop=="function"&&r.stop()}};var Ci=[{toVersion:1,up:async u=>{for(let e of xt)await u.addTable(e)}}];async function wi(u,e){if(typeof u.getSchemaVersion!="function"||typeof u.setSchemaVersion!="function"){let t="Adapter does not support schema versioning (getSchemaVersion/setSchemaVersion required)";throw e.logError(new Error(t),{message:t}),new Error(t)}e.logInfo("Starting database migration process");try{let t=await u.getSchemaVersion();(t==null||t<0)&&(t=0);let r=[...Ci].sort((i,a)=>i.toVersion-a.toVersion),n=r.length>0?r[r.length-1].toVersion:0;if(t>=n){e.logInfo(`Database is already up-to-date at v${t}`);return}e.logInfo(`Migrating database from v${t} to v${n}`);for(let i of r)i.toVersion>t&&(e.logInfo(`Applying migration: v${i.toVersion}`),await i.up(u),await u.setSchemaVersion(i.toVersion),t=i.toVersion);e.logInfo("Database migration completed successfully")}catch(t){throw e.logError(t,{message:"Database migration failed"}),t}}var ro={isLoggedIn:!1,userId:null,user:null,lastLoginAt:null,tenantId:null},Ur=class{constructor(e){this.context=e;this.lastBlurAt=null;this.activityEvents=["mousemove","mousedown","keydown","scroll","touchstart","focus"];this.onActivity=()=>this.resetIdleTimer();this.onBlur=()=>{this.lastBlurAt=Date.now()};this.onFocus=()=>{this.lastBlurAt&&Date.now()-this.lastBlurAt>this.reauthTimeoutMs&&this.emitter.emit("reauthenticate"),this.lastBlurAt=null};this.emitter=_t(),this.state={...ro},this.emitter.emit("update",this.getState()),this.state.isLoggedIn&&this.resetIdleTimer(),this.setupActivityListeners()}get idleTimeoutMs(){var e;return(((e=this.context.config)==null?void 0:e.sessionIdleTimeoutMinutes)||5)*60*1e3}get reauthTimeoutMs(){var e;return(((e=this.context.config)==null?void 0:e.sessionReauthTimeoutMinutes)||1)*60*1e3}subscribe(e){return e(this.state),this.emitter.on("update",e),()=>this.emitter.off("update",e)}onReauthenticate(e){return this.emitter.on("reauthenticate",e),()=>this.emitter.off("reauthenticate",e)}getState(){return{...this.state}}setupActivityListeners(){typeof window!="undefined"&&window.addEventListener&&(this.activityEvents.forEach(e=>window.addEventListener(e,this.onActivity)),window.addEventListener("blur",this.onBlur),window.addEventListener("focus",this.onFocus))}shutdown(){this.clearIdleTimer(),typeof window!="undefined"&&window.removeEventListener&&(this.activityEvents.forEach(e=>window.removeEventListener(e,this.onActivity)),window.removeEventListener("blur",this.onBlur),window.removeEventListener("focus",this.onFocus))}startIdleTimer(){this.clearIdleTimer(),typeof window!="undefined"&&(this.idleTimerId=window.setTimeout(()=>this.handleIdleLogout(),this.idleTimeoutMs))}resetIdleTimer(){this.state.isLoggedIn&&this.startIdleTimer()}clearIdleTimer(){this.idleTimerId!=null&&(clearTimeout(this.idleTimerId),this.idleTimerId=void 0)}handleIdleLogout(){this.context.logInfo("Auto-logout karena tidak aktif"),this.logout()}login(e){this.setState({isLoggedIn:!0,userId:e.id,user:e,lastLoginAt:Date.now(),tenantId:e.tenantId||null}),this.context.logInfo(`User ${e.id} (${e.username}) logged in`),this.startIdleTimer()}logout(){var e;this.clearIdleTimer(),this.setState({isLoggedIn:!1,userId:null,user:null,tenantId:null}),this.context.logInfo("User logged out");try{let t=(e=this.context.integrationServices)==null?void 0:e.encryption;t&&typeof t.setItem=="function"&&t.setItem("auth_token","")}catch{}}setState(e){this.state={...this.state,...e},this.emitter.emit("update",this.getState())}};var kt=class{constructor(){this.eventBus=Le;this.domainServiceOverrides={};this.integrationServiceOverrides={};this.serviceRuntimeOptions={};this.pluginSpecs=[];this.authBridgePolicyMode="bridge-required";this.runtimeStateStore=(0,Jn.createStore)({phase:"idle",started:!1,startCount:0,stopCount:0,lastError:null,lastTransitionAt:new Date().toISOString()}),this.runtimeStore=(0,Jn.asReadonlyStore)(this.runtimeStateStore),this.runtime=this.createRuntime()}getSyncStore(){return this.syncStore}getDomainChangeQueueState(){var e,t;return(t=(e=this.syncStore)==null?void 0:e.getState())!=null?t:{...Pt}}subscribeDomainChangeQueue(e){return this.syncStore?this.syncStore.subscribe(e):(e({...Pt}),()=>{})}getQueuedDomainChanges(){return[...this.getDomainChangeQueueState().queue]}enqueueDomainChange(e){var t;if(this.domainChangeSink){this.domainChangeSink(e);return}(t=this.syncStore)==null||t.enqueueChange(e)}removeDomainQueuedChange(e){var t;(t=this.syncStore)==null||t.removeQueuedChange(e)}setDomainChangeSink(e){this.domainChangeSink=e}withServiceRuntimeOptions(e){return this.serviceRuntimeOptions={...this.serviceRuntimeOptions,...e},this}getSessionStore(){return this.sessionStore}get session(){var e;return(e=this.sessionStore)==null?void 0:e.getState()}static builder(){return new Ei}use(e,t,r=[]){if(this.pluginSpecs.some(i=>i.name===e))return this;let n={name:e,init:t,deps:r};return this.pluginSpecs.push(n),this.runtime.use(e,async()=>{await t(this)},r),this}async stop(){this.runtimeStateStore.setState({phase:"stopping",started:this.runtime.isStarted(),lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.stop(),this.runtimeStateStore.setState(e=>({...e,phase:"stopped",started:!1,stopCount:e.stopCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(e){throw this.runtimeStateStore.setState({phase:"error",started:this.runtime.isStarted(),lastError:e instanceof Error?e.message:String(e),lastTransitionAt:new Date().toISOString()}),e}}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.syncStore=void 0,this.sessionStore=void 0,this.pluginSpecs=[],this.domainServiceOverrides={},this.integrationServiceOverrides={},this.serviceRuntimeOptions={},this.runtime=this.createRuntime()}async restart(){let e=[...this.pluginSpecs],t={...this.domainServiceOverrides},r={...this.integrationServiceOverrides},n={...this.serviceRuntimeOptions};await this.reset(),this.domainServiceOverrides=t,this.integrationServiceOverrides=r,this.serviceRuntimeOptions=n,this.runtime=this.createRuntime();for(let i of e)this.use(i.name,i.init,i.deps);return this.start()}async init(e={runMigrations:!0}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.init({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}async start(e={}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.start({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}checksum(e){return br(e,this)}logInfo(e,t){var r,n,i;(n=(r=this.registry)==null?void 0:r.loggerAdapter)!=null&&n.logInfo&&((i=this.registry)==null||i.loggerAdapter.logInfo(e,t))}logError(e,t){var r,n,i;(n=(r=this.registry)==null?void 0:r.loggerAdapter)!=null&&n.logError&&((i=this.registry)==null||i.loggerAdapter.logError(e,t))}initNotifications(){var e;(e=this.integrationServices)==null||e.notification.initNotifications()}notify(e,t){var r;(r=this.integrationServices)==null||r.notification.notify(e,t)}get config(){var e;return(e=this.integrationServices)==null?void 0:e.config}isOnline(){var e;return(e=this.registry)==null?void 0:e.platformAdapter.isOnline()}createCorrelationId(e="cid"){return this.runtime.createCorrelationId(e)}async logActivity(e,t={},r){var n,i;try{await((i=this.integrationServices)==null?void 0:i.activityLogger.logActivity(e,((n=this.session)==null?void 0:n.userId)||"system",t,r))}catch(a){this.logError(a,{fn:"logActivity",action:e})}}createRuntime(){let e=no.CoreRuntime.builder().build();e.setHooks({runMigrations:async()=>{var n,i;let t=(n=this.registry)==null?void 0:n.dbAdapter,r=(i=this.registry)==null?void 0:i.loggerAdapter;await wi(t,r)},onInit:async()=>{!this.domainChangeSink&&!this.syncStore&&(this.syncStore=new wr(this)),this.sessionStore||(this.sessionStore=new Ur(this))},createDomainServices:()=>(this.domainServices||(this.domainServices=new Cr(this,this.domainServiceOverrides,this.serviceRuntimeOptions)),this.domainServices),createIntegrationServices:async()=>(this.integrationServices||(this.integrationServices=await Qr.create(this,this.integrationServiceOverrides)),this.integrationServices),onStop:async()=>{this.sessionStore&&typeof this.sessionStore.shutdown=="function"&&await this.sessionStore.shutdown(),this.syncStore&&typeof this.syncStore.shutdown=="function"&&await this.syncStore.shutdown(),this.integrationServices&&typeof this.integrationServices.shutdown=="function"&&await this.integrationServices.shutdown(),this.domainServices&&typeof this.domainServices.shutdown=="function"&&await this.domainServices.shutdown(),this.registry&&typeof this.registry.clear=="function"&&this.registry.clear()}});for(let t of this.pluginSpecs)e.use(t.name,async()=>{await t.init(this)},t.deps);return e}resolveUseSeedData(e){var t;return e.useSeedData!==void 0?e.useSeedData:!!((t=this.config)!=null&&t.demoMode)}},Ei=class{constructor(){this.core=new kt;this.adapterOpts={};this.syncOrchestrationMode="host-managed"}withPlatformAdapter(e){return this.adapterOpts.platformAdapter=e,this}withDbAdapter(e){return this.adapterOpts.dbAdapter=e,this}withLoggerAdapter(e){return this.adapterOpts.loggerAdapter=e,this}withHttpAdapter(e){return this.adapterOpts.httpAdapter=e,this}withHttpRetryPolicy(e){return this.adapterOpts.httpRetryPolicy=e,this}withSocketAdapter(e){return this.adapterOpts.socketAdapter=e,this}withEncryptionAdapter(e){return this.adapterOpts.encryptionAdapter=e,this}withChecksumAdapter(e){return this.adapterOpts.checksumAdapter=e,this}withActivitySink(e){return this.adapterOpts.activitySink=e,this}withNotificationAdapter(e){return this.adapterOpts.notificationAdapter=e,this}withExportAdapter(e){return this.adapterOpts.exportAdapter=e,this}withStorageAdapter(e){return this.adapterOpts.storageAdapter=e,this}overrideDomainServices(e){return this.core.domainServiceOverrides={...this.core.domainServiceOverrides,...e},this}overrideIntegrationServices(e){return this.core.integrationServiceOverrides={...this.core.integrationServiceOverrides,...e},this}withServiceRuntimeOptions(e){return e?(this.core.withServiceRuntimeOptions(e),this):this}withSyncOrchestrationMode(e){return this.syncOrchestrationMode=e,this}withDomainChangeSink(e){return this.core.setDomainChangeSink(e),this}disableInternalSyncOrchestration(){return this.syncOrchestrationMode="host-managed",this}applySyncOrchestrationMode(){var e,t;if(this.syncOrchestrationMode!=="host-managed")throw new Error("Only host-managed sync orchestration is supported");this.core.integrationServiceOverrides={...this.core.integrationServiceOverrides,syncService:(e=this.core.integrationServiceOverrides.syncService)!=null?e:new Tt,socketService:(t=this.core.integrationServiceOverrides.socketService)!=null?t:new Ft}}build(e={runMigrations:!0}){return this.applySyncOrchestrationMode(),this.core.registry=new Hr(this.core,this.adapterOpts),this.core}};var Ri=Pe("ofcore");var jr=Pe("ofcore");var $r=Pe("ofcore");var Bt=Pe("ofcore");var Zn=Pe("ofcore");var ei=Pe("ofcore");var Vr=Pe("ofcore");var ti=Mt(Ii()),ri=class{constructor(e){this.context=e}encrypt(e,t){let r=this.resolveSecretKey(t);return ti.default.AES.encrypt(String(e!=null?e:""),r).toString()}decrypt(e,t){let r=this.resolveSecretKey(t);return ti.default.AES.decrypt(String(e!=null?e:""),r).toString(ti.default.enc.Utf8)||null}resolveSecretKey(e){var r;let t=(r=e==null?void 0:e.metadata)==null?void 0:r.secretKey;return typeof t=="string"&&t.trim().length>0?t:this.context.config.encryptionKey}};var co=Mt(ao()),uo=Mt(Ut()),Oi=Mt(so()),ai=class{constructor(e){}compute(e){var r,n;let t=String((r=e==null?void 0:e.payload)!=null?r:"");if(e.algorithm==="hmac-sha256"){let i=String((n=e.secret)!=null?n:"");return i?(0,co.default)(t,i).toString(Oi.default):""}return e.algorithm==="sha256"?(0,uo.default)(t).toString(Oi.default):""}verify(e,t){let r=String(this.compute(e)||"").trim().toLowerCase(),n=String(t||"").trim().toLowerCase();return r===n}};var _i=Pe("ofcore");var zr=Pe("ofcore");var Hr=class{constructor(e,t={}){this.context=e;this.opts=t;this.context.registry=this,this.platformAdapter=this.resolveAdapter(t.platformAdapter,_i.DefaultPlatformAdapter),this.dbAdapter=this.resolveAdapter(t.dbAdapter,Ri.InMemoryDbAdapter),this.loggerAdapter=this.resolveAdapter(t.loggerAdapter,$r.ConsoleLoggerAdapter),this.httpAdapter=this.resolveAdapter(t.httpAdapter,Br.DefaultHttpAdapter),this.httpRetryPolicy=this.resolveAdapter(t.httpRetryPolicy,mt.NoRetryHttpPolicy),this.socketAdapter=this.resolveAdapter(t.socketAdapter,zr.InMemorySocketAdapter),this.activitySink=this.resolveAdapter(t.activitySink,Bt.NoopActivitySink),this.encryptionAdapter=this.resolveAdapter(t.encryptionAdapter,ri),this.checksumAdapter=this.resolveAdapter(t.checksumAdapter,ai),this.notificationAdapter=this.resolveAdapter(t.notificationAdapter,Vr.NoopNotificationAdapter),this.exportAdapter=this.resolveAdapter(t.exportAdapter,jr.DefaultExportAdapter),this.storageAdapter=this.resolveAdapter(t.storageAdapter,yt)}resolveAdapter(e,t){if(!e)return new t(this.context);if(typeof e=="object")return e;if(typeof e=="function"&&e.prototype===void 0)try{return e(this.context)}catch{}let r=e,i=(Reflect.getMetadata("design:paramtypes",r)||[]).map(a=>{if(a===kt)return this.context;if(a===_i.DefaultPlatformAdapter)return this.platformAdapter;if(a===Ri.InMemoryDbAdapter)return this.dbAdapter;if(a===$r.ConsoleLoggerAdapter)return this.loggerAdapter;if(a===Br.DefaultHttpAdapter)return this.httpAdapter;if(a===mt.NoRetryHttpPolicy)return this.httpRetryPolicy;if(a===zr.InMemorySocketAdapter)return this.socketAdapter;if(a===Bt.NoopActivitySink)return this.activitySink;if(a===Zn.NoopEncryptionAdapter)return this.encryptionAdapter;if(a===ei.NoopChecksumAdapter)return this.checksumAdapter;if(a===Vr.NoopNotificationAdapter)return this.notificationAdapter;if(a===jr.DefaultExportAdapter)return this.exportAdapter;if(a===yt)return this.storageAdapter});return new r(...i)}};var ho=Pe("ofcore");var lo=Pe("ofcore");var po=Pe("ofcore");var mo=Pe("ofcore");var Ti=class{constructor(e){this.context=e;var t,r,n;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.productService=(r=this.context.domainServices)==null?void 0:r.product,this.bomService=(n=this.context.domainServices)==null?void 0:n.bom}async listProducts(){let e={field:"deleted",value:!1};return(await this.dbAdapter.query(ue,{filters:e})).map(r=>({id:r.id,name:r.name,price:r.price,stock:r.stock,categoryId:r.categoryId}))}async listProductsByCategory(e){if(!e)return this.listProducts();let t={and:[{field:"deleted",value:!1},{field:"categoryId",value:e}]};return(await this.dbAdapter.query(ue,{filters:t})).map(n=>({id:n.id,name:n.name,price:n.price,stock:n.stock,categoryId:n.categoryId}))}async editProduct(e,t){return this.productService.updateProduct(e,t)}async fetchProductDetails(e){let t=await this.productService.getProduct(e),r=await this.bomService.getBomsByProductId(e);return{product:t,boms:r}}async removeProduct(e){return this.productService.deleteProduct(e)}async scanProduct(e){return this.productService.getProductsByBarcode(e)}};var Fi=class{constructor(e){this.context=e;var t;this.pricingService=(t=this.context.domainServices)==null?void 0:t.pricing}async calculateTransactionTotals(e,t,r){let{calculateOrderTotal:n,calculatePPN:i,calculatePPH:a}=this.pricingService,{items:o,subTotal:s,discount:d,total:c}=await n(e,t,r),[p,l]=await Promise.all([i(c),a(c)]);return{pricedItems:o,subTotal:s,discount:d,total:c,ppn:p,pph:l,totalWithTax:c+p+l,payableToSeller:c+p-l}}};return So(Ho);})();
18
18
  /*! For license information please see index.umd.js.LEGAL.txt */