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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,8 @@
1
- "use strict";var fo=Object.create;var Kr=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var yo=Object.getOwnPropertyNames;var bo=Object.getPrototypeOf,vo=Object.prototype.hasOwnProperty;var re=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports),xo=(u,e)=>{for(var t in e)Kr(u,t,{get:e[t],enumerable:!0})},ki=(u,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of yo(e))!vo.call(u,n)&&n!==t&&Kr(u,n,{get:()=>e[n],enumerable:!(r=go(e,n))||r.enumerable});return u};var Bt=(u,e,t)=>(t=u!=null?fo(bo(u)):{},ki(e||!u||!u.__esModule?Kr(t,"default",{value:u,enumerable:!0}):t,u)),Ao=u=>ki(Kr({},"__esModule",{value:!0}),u);var Mi=re(()=>{var Bi;(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 ot(Object.create(null))}:s?function(){return ot({__proto__:null})}:function(){return ot({})},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:wt(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Et(),f=typeof WeakMap=="function"?WeakMap:dt(),y=n?Symbol.for("@reflect-metadata:registry"):void 0,b=Ct(),h=ut(b);function g(S,C,B,N){if(P(B)){if(!_e(S))throw new TypeError;if(!Ge(C))throw new TypeError;return L(S,C)}else{if(!_e(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)&&!We(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=ht(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(!Ge(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=Qe(C);return X(W)?!1:T(S,W,B)}function z(S,C,B){var N=ht(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=Qe(C);if(!X(W))return V(S,W,B)}function F(S,C,B){var N=ht(C,B,!1);if(!P(N))return N.OrdinaryGetOwnMetadata(S,C,B)}function U(S,C,B,N){var W=ht(B,N,!0);W.OrdinaryDefineOwnMetadata(S,C,B,N)}function O(S,C){var B=_(S,C),N=Qe(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=ht(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=st(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 Le(S){return""+S}function pe(S){var C=Y(S,3);return te(C)?C:Le(C)}function _e(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 Ge(S){return typeof S=="function"}function We(S){switch(R(S)){case 3:return!0;case 4:return!0;default:return!1}}function Ye(S,C){return S===C||S!==S&&C!==C}function st(S,C){var B=S[C];if(B!=null){if(!me(B))throw new TypeError;return B}}function yt(S){var C=st(S,a);if(!me(C))throw new TypeError;var B=C.call(S);if(!J(B))throw new TypeError;return B}function ct(S){return S.value}function Me(S){var C=S.next();return C.done?!1:C}function Fe(S){var C=S.return;C&&C.call(S)}function Qe(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 bt(){var S;!P(y)&&typeof t.Reflect!="undefined"&&!(y in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(S=mt(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=yt(N);;){var Ie=Me(de);if(!Ie)return;var Xe=ct(Ie);if(Xe.isProviderFor(G,ne))return Fe(de),Xe}}}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 Xe=W.get(G);P(Xe)&&(Xe=new l,W.set(G,Xe)),Xe.set(ne,de)}return!0}}function Ct(){var S;return!P(y)&&J(t.Reflect)&&Object.isExtensible(t.Reflect)&&(S=t.Reflect[y]),P(S)&&(S=bt()),!P(y)&&J(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:S}),S}function ut(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=yt(de),Xe=0;;){var Ut=Me(Ie);if(!Ut)return G.length=Xe,G;var ai=ct(Ut);try{G[Xe]=ai}catch(zr){try{Fe(Ie)}finally{throw zr}}Xe++}}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 mt(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 ht(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 wt(){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--,Ye(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(!Ye(this._cacheKey,j)){this._cacheIndex=-1;for(var K=0;K<this._keys.length;K++)if(Ye(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 Et(){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 dt(){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 ot(S){return S.__=void 0,delete S.__,S}})})(Bi||(Bi={}))});var ae=re((hn,Vi)=>{(function(u,e){typeof hn=="object"?Vi.exports=hn=e():typeof define=="function"&&define.amd?define([],e):u.CryptoJS=e()})(hn,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 require=="function")try{r=require("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 Rr=re((fn,zi)=>{(function(u,e){typeof fn=="object"?zi.exports=fn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(fn,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 Gi=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(){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 Yi=re((yn,Wi)=>{(function(u,e){typeof yn=="object"?Wi.exports=yn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(yn,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 Pt=re((bn,Xi)=>{(function(u,e){typeof bn=="object"?Xi.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.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 Zi=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.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 Dt=re((xn,ea)=>{(function(u,e){typeof xn=="object"?ea.exports=xn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(xn,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 xi=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(){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 Qt=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(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 ia=re((In,na)=>{(function(u,e,t){typeof In=="object"?na.exports=In=e(ae(),Qt()):typeof define=="function"&&define.amd?define(["./core","./sha256"],e):e(u.CryptoJS)})(In,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 Ai=re((Pn,aa)=>{(function(u,e,t){typeof Pn=="object"?aa.exports=Pn=e(ae(),Rr()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(u.CryptoJS)})(Pn,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,Le=Q,pe=T,_e=z,me=V,Ge=F,We=U,Ye=O,st=_,yt=R,ct=P,Me=0;Me<80;Me++){var Fe,Qe,bt=c[Me];if(Me<16)Qe=bt.high=l[m+Me*2]|0,Fe=bt.low=l[m+Me*2+1]|0;else{var Ct=c[Me-15],ut=Ct.high,mt=Ct.low,ht=(ut>>>1|mt<<31)^(ut>>>8|mt<<24)^ut>>>7,wt=(mt>>>1|ut<<31)^(mt>>>8|ut<<24)^(mt>>>7|ut<<25),Et=c[Me-2],dt=Et.high,ot=Et.low,S=(dt>>>19|ot<<13)^(dt<<3|ot>>>29)^dt>>>6,C=(ot>>>19|dt<<13)^(ot<<3|dt>>>29)^(ot>>>6|dt<<26),B=c[Me-7],N=B.high,W=B.low,he=c[Me-16],ve=he.high,ee=he.low;Fe=wt+W,Qe=ht+N+(Fe>>>0<wt>>>0?1:0),Fe=Fe+C,Qe=Qe+S+(Fe>>>0<C>>>0?1:0),Fe=Fe+ee,Qe=Qe+ve+(Fe>>>0<ee>>>0?1:0),bt.high=Qe,bt.low=Fe}var j=_e&Ge^~_e&Ye,$=me&We^~me&st,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=(_e>>>14|me<<18)^(_e>>>18|me<<14)^(_e<<23|me>>>9),Xe=(me>>>14|_e<<18)^(me>>>18|_e<<14)^(me<<23|_e>>>9),Ut=d[Me],ai=Ut.high,zr=Ut.low,Je=ct+Xe,At=yt+Ie+(Je>>>0<ct>>>0?1:0),Je=Je+$,At=At+j+(Je>>>0<$>>>0?1:0),Je=Je+zr,At=At+ai+(Je>>>0<zr>>>0?1:0),Je=Je+Fe,At=At+Qe+(Je>>>0<Fe>>>0?1:0),Fi=de+G,ho=ne+K+(Fi>>>0<de>>>0?1:0);yt=Ye,ct=st,Ye=Ge,st=We,Ge=_e,We=me,me=pe+Je|0,_e=Le+At+(me>>>0<pe>>>0?1:0)|0,Le=be,pe=se,be=J,se=Y,J=X,Y=te,te=Je+Fi|0,X=At+ho+(te>>>0<Je>>>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+Le+(T>>>0<pe>>>0?1:0),V=x.low=V+me,x.high=z+_e+(V>>>0<me>>>0?1:0),U=v.low=U+We,v.high=F+Ge+(U>>>0<We>>>0?1:0),_=A.low=_+st,A.high=O+Ye+(_>>>0<st>>>0?1:0),P=I.low=P+ct,I.high=R+yt+(P>>>0<ct>>>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 sa=re((Dn,oa)=>{(function(u,e,t){typeof Dn=="object"?oa.exports=Dn=e(ae(),Rr(),Ai()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./sha512"],e):e(u.CryptoJS)})(Dn,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 ua=re((Cn,ca)=>{(function(u,e,t){typeof Cn=="object"?ca.exports=Cn=e(ae(),Rr()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(u.CryptoJS)})(Cn,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 la=re((wn,da)=>{(function(u,e){typeof wn=="object"?da.exports=wn=e(ae()):typeof define=="function"&&define.amd?define(["./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.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 _r=re((En,pa)=>{(function(u,e){typeof En=="object"?pa.exports=En=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(En,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 ha=re((On,ma)=>{(function(u,e,t){typeof On=="object"?ma.exports=On=e(ae(),Qt(),_r()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(u.CryptoJS)})(On,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 xt=re((Rn,fa)=>{(function(u,e,t){typeof Rn=="object"?fa.exports=Rn=e(ae(),xi(),_r()):typeof define=="function"&&define.amd?define(["./core","./sha1","./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.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 Te=re((_n,ga)=>{(function(u,e,t){typeof _n=="object"?ga.exports=_n=e(ae(),xt()):typeof define=="function"&&define.amd?define(["./core","./evpkdf"],e):e(u.CryptoJS)})(_n,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 ba=re((Tn,ya)=>{(function(u,e,t){typeof Tn=="object"?ya.exports=Tn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Tn,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 xa=re((Fn,va)=>{(function(u,e,t){typeof Fn=="object"?va.exports=Fn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Fn,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 Sa=re((kn,Aa)=>{(function(u,e,t){typeof kn=="object"?Aa.exports=kn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(kn,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 Pa=re((Bn,Ia)=>{(function(u,e,t){typeof Bn=="object"?Ia.exports=Bn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Bn,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 Ca=re((Mn,Da)=>{(function(u,e,t){typeof Mn=="object"?Da.exports=Mn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Mn,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 Ea=re((qn,wa)=>{(function(u,e,t){typeof qn=="object"?wa.exports=qn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(qn,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 Ra=re((Ln,Oa)=>{(function(u,e,t){typeof Ln=="object"?Oa.exports=Ln=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Ln,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 Ta=re((Nn,_a)=>{(function(u,e,t){typeof Nn=="object"?_a.exports=Nn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Nn,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 ka=re((Qn,Fa)=>{(function(u,e,t){typeof Qn=="object"?Fa.exports=Qn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Qn,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 Ma=re((Un,Ba)=>{(function(u,e,t){typeof Un=="object"?Ba.exports=Un=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Un,function(u){return u.pad.NoPadding={pad:function(){},unpad:function(){}},u.pad.NoPadding})});var La=re((Hn,qa)=>{(function(u,e,t){typeof Hn=="object"?qa.exports=Hn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(u.CryptoJS)})(Hn,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 Qa=re((jn,Na)=>{(function(u,e,t){typeof jn=="object"?Na.exports=jn=e(ae(),Pt(),Dt(),xt(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(u.CryptoJS)})(jn,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 Ha=re(($n,Ua)=>{(function(u,e,t){typeof $n=="object"?Ua.exports=$n=e(ae(),Pt(),Dt(),xt(),Te()):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.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 $a=re((Vn,ja)=>{(function(u,e,t){typeof Vn=="object"?ja.exports=Vn=e(ae(),Pt(),Dt(),xt(),Te()):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.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 za=re((zn,Va)=>{(function(u,e,t){typeof zn=="object"?Va.exports=zn=e(ae(),Pt(),Dt(),xt(),Te()):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=[],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 Ga=re((Kn,Ka)=>{(function(u,e,t){typeof Kn=="object"?Ka.exports=Kn=e(ae(),Pt(),Dt(),xt(),Te()):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.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 Ya=re((Gn,Wa)=>{(function(u,e,t){typeof Gn=="object"?Wa.exports=Gn=e(ae(),Pt(),Dt(),xt(),Te()):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.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 Si=re((Wn,Xa)=>{(function(u,e,t){typeof Wn=="object"?Xa.exports=Wn=e(ae(),Rr(),Gi(),Yi(),Pt(),Zi(),Dt(),xi(),Qt(),ia(),Ai(),sa(),ua(),la(),_r(),ha(),xt(),Te(),ba(),xa(),Sa(),Pa(),Ca(),Ea(),Ra(),Ta(),ka(),Ma(),La(),Qa(),Ha(),$a(),za(),Ga(),Ya()):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)})(Wn,function(u){return u})});var io=re((ri,no)=>{(function(u,e,t){typeof ri=="object"?no.exports=ri=e(ae(),Qt(),_r()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(u.CryptoJS)})(ri,function(u){return u.HmacSHA256})});var oo=re((ni,ao)=>{(function(u,e){typeof ni=="object"?ao.exports=ni=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(u.CryptoJS)})(ni,function(u){return u.enc.Hex})});var Uo={};xo(Uo,{ActivityLogger:()=>wr,AdapterRegistry:()=>Ur,ApiService:()=>Br,AuthorizationService:()=>Or,BackupScheduler:()=>Lr,CONFLICT_POLICY_MATRIX:()=>Ja,CURRENT_SYNC_PROTOCOL_VERSION:()=>un,CartService:()=>Ir,CartStore:()=>Sr,CategoryService:()=>Ht,ConfigService:()=>qr,ConsoleLoggerAdapter:()=>jr.ConsoleLoggerAdapter,CustomerGroupService:()=>$t,CustomerService:()=>jt,DEFAULT_GRANULAR_AUTH_POLICY:()=>vi,DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS:()=>dn,DefaultExportAdapter:()=>Hr.DefaultExportAdapter,DefaultHttpAdapter:()=>kr.DefaultHttpAdapter,DefaultPlatformAdapter:()=>uo.DefaultPlatformAdapter,DomainServices:()=>Dr,EncryptionService:()=>Tr,ExpenseService:()=>pr,ExponentialBackoffHttpPolicy:()=>pt.ExponentialBackoffHttpPolicy,ExportService:()=>br,FinancialSettingService:()=>lr,HistoryService:()=>Vt,InMemoryDbAdapter:()=>mo.InMemoryDbAdapter,InMemorySocketAdapter:()=>Vr.InMemorySocketAdapter,IntegrationServices:()=>Nr,InventoryLogService:()=>or,InventoryService:()=>gr,MemoryActivitySink:()=>kt.MemoryActivitySink,MemoryStorage:()=>gt,NoRetryHttpPolicy:()=>pt.NoRetryHttpPolicy,NoopActivitySink:()=>kt.NoopActivitySink,NoopChecksumAdapter:()=>Zn.NoopChecksumAdapter,NoopEncryptionAdapter:()=>Jn.NoopEncryptionAdapter,NoopNotificationAdapter:()=>$r.NoopNotificationAdapter,NoopSocketService:()=>Tt,NoopSyncService:()=>_t,NotificationService:()=>Mr,OrderService:()=>zt,POS_DOMAIN_TABLES:()=>Bo,PayableService:()=>hr,PosCore:()=>Ft,PriceHistoryService:()=>sr,PriceTierService:()=>Kt,PricingService:()=>vr,ProductService:()=>Gt,PromotionService:()=>Wt,PurchaseOrderService:()=>ir,PurchaseService:()=>ar,ReceivableService:()=>mr,ReportScheduleService:()=>dr,ReportingService:()=>Ar,ReturnService:()=>Jt,RoleAdapter:()=>Er,SaleService:()=>Zt,SessionStore:()=>Qr,SettlementService:()=>fr,ShiftService:()=>er,SocketService:()=>Pi,StockAdjustmentService:()=>ur,StockOpnameService:()=>cr,SupplierService:()=>nr,SyncService:()=>Ii,SyncStore:()=>Cr,TASK_ID:()=>eo,TaxService:()=>Pr,TransactionService:()=>tr,UIProductService:()=>_i,UITransactionService:()=>Ti,UomService:()=>rr,UserService:()=>Fr,applyPendingMigrations:()=>Ci,bomTable:()=>ke,buildJournalDraftFromPosFinanceProjection:()=>Ni,categoryTable:()=>Ze,computeChecksum:()=>yr,createChangeQueuePort:()=>H,createPosFinanceRuntimeOptions:()=>Oo,customerGroupTable:()=>et,customerTable:()=>Ve,eventBus:()=>qe,executeHttpRequestWithRetry:()=>pt.executeHttpRequestWithRetry,expenseTable:()=>at,financialSettingTable:()=>$e,getSyncProtocolContract:()=>Mo,historyTable:()=>ie,initialSessionState:()=>to,initialState:()=>It,inventoryLogTable:()=>Ee,isContractVersionCompatible:()=>po.isContractVersionCompatible,isFailureEnvelope:()=>lo.isFailureEnvelope,isServerProtocolCompatible:()=>gi,kitchenTicketItemTable:()=>ui,kitchenTicketTable:()=>Xr,loyaltyAccountTable:()=>Ot,loyaltyLedgerTable:()=>ft,migrations:()=>Di,orderItemTable:()=>xe,orderTable:()=>oe,payableTable:()=>ye,priceHistoryTable:()=>Ke,priceTierTable:()=>Ue,productTable:()=>ue,projectPosCashAdjustmentFinance:()=>fi,projectPosExpenseFinance:()=>mi,projectPosPurchaseFinance:()=>li,projectPosReturnFinance:()=>pi,projectPosSettlementFinance:()=>hi,projectScopedPosSaleFinance:()=>di,promotionTable:()=>tt,purchaseItemTable:()=>Pe,purchaseOrderItemTable:()=>je,purchaseOrderTable:()=>Re,purchaseTable:()=>Se,receivableTable:()=>fe,reportScheduleTable:()=>it,returnItemTable:()=>Oe,returnTable:()=>Ae,roleTable:()=>De,saleItemTable:()=>ge,saleTable:()=>ce,schemas:()=>vt,settlementTable:()=>Ne,shiftTable:()=>le,stockAdjustmentTable:()=>nt,stockOpnameItemTable:()=>Be,stockOpnameTable:()=>Ce,supplierTable:()=>ze,taxRateTable:()=>we,transactionTable:()=>Z,uomTable:()=>rt,userTable:()=>He});module.exports=Ao(Uo);var fy=Bt(Mi());var ro=require("ofcore"),Xn=require("ofcore");var Gr="0123456789abcdef",Wr=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+=Gr.charAt(this.bytes[t]>>>4),e+=Gr.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+=Gr.charAt(this.bytes[t]>>>4),e+=Gr.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}},oi=class{constructor(e){this.timestampBiased=0,this.counter=0,this.rollbackAllowance=1e4,this.random=e!=null?e:So()}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 Wr.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,Wr.ofInner(e)}},So=()=>{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues!="undefined")return new si;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)}},si=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++]}},qi;var D=()=>Io().toString(),Io=()=>(qi||(qi=new oi)).generateV4();var ci=class{constructor(e){this.context=e}enqueue(e){this.context.enqueueDomainChange(e)}};function H(u){return new ci(u)}var ke="boms";var Yr=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(ke,i);return this.changeQueue.enqueue({type:"create",model:ke,record:a}),this.context.logActivity("AddBom",{id:r}),a}async updateBom(e,t,r){let n=await(r||this.dbAdapter).get(ke,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(ke,e,a);return this.changeQueue.enqueue({type:"update",model:ke,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(ke,{...e,filters:i})}async getBom(e,t){return(t||this.dbAdapter).get(ke,e)}async deleteBom(e,t){return await(t||this.dbAdapter).delete(ke,e),this.changeQueue.enqueue({type:"delete",model:ke,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(ke,a);return this.changeQueue.enqueue({type:"create",model:ke,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(ke,{filters:n})}async getBomsByComponentItemId(e,t){let r=t||this.dbAdapter,n={and:[{componentItemId:e},{deleted:!1}]};return r.query(ke,{filters:n})}async getBomsByProductId(e,t){return this.dbAdapter.query(ke,{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(ke,{filters:{parentItemId:n,deleted:!1}});for(let o of a){let s=o.quantity*i;if((await this.dbAdapter.query(ke,{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 Ze="categories";var Ht=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(Ze,i);return this.changeQueue.enqueue({type:"create",model:Ze,record:a}),this.context.logActivity("AddCategory",{id:r}),a}async updateCategory(e,t,r){let n=await(r||this.dbAdapter).get(Ze,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(Ze,e,a);return this.changeQueue.enqueue({type:"update",model:Ze,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(Ze,{...e,filters:i})}async getCategory(e,t){return(t||this.dbAdapter).get(Ze,e)}async deleteCategory(e,t){return await(t||this.dbAdapter).delete(Ze,e),this.changeQueue.enqueue({type:"delete",model:Ze,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(Ze,a);return this.changeQueue.enqueue({type:"create",model:Ze,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 Ve="customers";var Ot="loyalty_accounts";var ft="loyalty_ledgers";var jt=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(Ot,{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(Ot,{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(Ve,i);return this.changeQueue.enqueue({type:"create",model:Ve,record:a}),this.context.logActivity("AddCustomer",{id:r}),a}async updateCustomer(e,t,r){let n=await(r||this.dbAdapter).get(Ve,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(Ve,e,a);return this.changeQueue.enqueue({type:"update",model:Ve,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(Ve,{...e,filters:i})}async getCustomer(e,t){return(t||this.dbAdapter).get(Ve,e)}async deleteCustomer(e,t){return await(t||this.dbAdapter).delete(Ve,e),this.changeQueue.enqueue({type:"delete",model:Ve,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(Ve,a);return this.changeQueue.enqueue({type:"create",model:Ve,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(Ve,{...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(ft,{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(ft,{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(Ot,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(ft,{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(ft,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(ft,{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(Ot,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(ft,{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(ft,s.id,{availablePoints:0,consumedAt:r,version:Date.now(),lastModified:r}),await t.create(ft,{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(Ot,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 et="customer_groups";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 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(et,i);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("AddCustomerGroup",{id:r}),a}async updateCustomerGroup(e,t,r){let n=await(r||this.dbAdapter).get(et,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(et,e,a);return this.changeQueue.enqueue({type:"update",model:et,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(et,{...e,filters:i})}async getCustomerGroup(e,t){return(t||this.dbAdapter).get(et,e)}async deleteCustomerGroup(e,t){return await(t||this.dbAdapter).delete(et,e),this.changeQueue.enqueue({type:"delete",model:et,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(et,a);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("DuplicateCustomerGroup",{originalId:e,newId:n}),o}};var ie="histories";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 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 Li=require("ofcore"),gt=class extends Li.MemoryStorageAdapter{};var St=class{constructor(e){this.context=e;this.queue=Promise.resolve();var t;this.storage=((t=this.context.registry)==null?void 0:t.storageAdapter)||new gt(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 ui="kitchen_ticket_items";var Xr="kitchen_tickets";var zt=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 St(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(Xr,{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(ui,{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:Xr,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 Jr=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 Ue="price_tiers";var Kt=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(Ue,i);return this.changeQueue.enqueue({type:"create",model:Ue,record:a}),this.context.logActivity("AddPriceTier",{id:r}),a}async updatePriceTier(e,t,r){let n=await(r||this.dbAdapter).get(Ue,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(Ue,e,a);return this.changeQueue.enqueue({type:"update",model:Ue,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(Ue,{...e,filters:i})}async getPriceTier(e,t){return(t||this.dbAdapter).get(Ue,e)}async deletePriceTier(e,t){return await(t||this.dbAdapter).delete(Ue,e),this.changeQueue.enqueue({type:"delete",model:Ue,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(Ue,a);return this.changeQueue.enqueue({type:"create",model:Ue,record:a}),this.context.logActivity("DuplicatePriceTier",{originalId:e,newId:n}),o}};var ue="products";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 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 tt="promotions";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 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(tt,i);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("AddPromotion",{id:r}),a}async updatePromotion(e,t,r){let n=await(r||this.dbAdapter).get(tt,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(tt,e,a);return this.changeQueue.enqueue({type:"update",model:tt,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(tt,{...e,filters:i})}async getPromotion(e,t){return(t||this.dbAdapter).get(tt,e)}async deletePromotion(e,t){return await(t||this.dbAdapter).delete(tt,e),this.changeQueue.enqueue({type:"delete",model:tt,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(tt,a);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("DuplicatePromotion",{originalId:e,newId:n}),o}};var Ae="returns";var ge="sale_items";var Pe="purchase_items";var Oe="return_items";var Z="transactions";var Zr=require("offinance-shared-core");function di(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 li(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 pi(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 mi(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 hi(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 fi(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 Yt(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 Po(u){return"grossAmount"in u.input}function Do(u){return u.kind==="purchase"}function Co(u){return u.kind==="sale_return"||u.kind==="purchase_return"}function wo(u){return u.kind==="receivable_payment"||u.kind==="payable_payment"}function Eo(u){return u.kind==="cash_adjustment"}function Xt(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 Ni(u,e){var n,i,a,o,s;let t=(n=e.financeDomainId)!=null?n:"ofpos";if(Po(u))return(0,Zr.buildJournalFromScopedPosSale)({...u.context,ledgerProfileId:e.ledgerProfileId,financeDomainId:t},u.input);if(Do(u)){let d=Yt(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 Xt({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(Co(u)){let d=Yt(u.input.scopedAccountMapping,u.context);return Xt({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(wo(u)){let d=Yt(u.input.scopedAccountMapping,u.context);return Xt({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(Eo(u)){let d=Yt(u.input.scopedAccountMapping,u.context);return Xt({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=Yt(u.input.scopedAccountMapping,u.context);return Xt({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 Oo(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,Zr.createFinanceProjectionSink)({dbAdapter:u.dbAdapter,resolveFinanceServices:u.resolveFinanceServices,resolveLedgerProfileId:u.resolveLedgerProfileId,resolveSyncEnqueuer:u.resolveSyncEnqueuer,requiredAccounts:u.requiredAccounts,buildJournalDraft:(r,n)=>{var i;return Ni(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 Jt=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:Pe,{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(pi({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,Le=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 _e=r==="sale_return"?pe.unitPrice:pe.unitCost,me=pe.uomId,Ge={id:D(),returnId:R,productId:be.productId,quantity:Le,unitPrice:_e,uomId:me,restock:se,restockNote:se?null:be.restockNote||"Rusak / tidak bisa dijual",version:1,lastModified:_,deleted:!1};if(await O.create(Oe,Ge),P.push({type:"create",model:Oe,record:Ge}),se){let We=E.convertQuantity(Le,{conversionFactor:me&&((Y=L.get(me))==null?void 0:Y.conversionFactor)||1},{conversionFactor:1}),Ye=r==="sale_return"?+We:-We;await t.updateStock(be.productId,Ye,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(Oe,{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(Oe,T.id,{deleted:!0,lastModified:new Date().toISOString()}),E.push({type:"delete",model:Oe,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(Oe,{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:Pe,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 en=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(Oe,i);return this.changeQueue.enqueue({type:"create",model:Oe,record:a}),this.context.logActivity("AddReturnItem",{id:r}),a}async updateReturnItem(e,t,r){let n=await(r||this.dbAdapter).get(Oe,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(Oe,e,a);return this.changeQueue.enqueue({type:"update",model:Oe,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(Oe,{...e,filters:i})}async getReturnItem(e,t){return(t||this.dbAdapter).get(Oe,e)}async deleteReturnItem(e,t){return await(t||this.dbAdapter).delete(Oe,e),this.changeQueue.enqueue({type:"delete",model:Oe,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(Oe,a);return this.changeQueue.enqueue({type:"create",model:Oe,record:a}),this.context.logActivity("DuplicateReturnItem",{originalId:e,newId:n}),o}};var De="roles";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 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(De,i);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("AddRole",{id:r}),a}async updateRole(e,t,r){let n=await(r||this.dbAdapter).get(De,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(De,e,a);return this.changeQueue.enqueue({type:"update",model:De,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(De,{...e,filters:i})}async getRole(e,t){return(t||this.dbAdapter).get(De,e)}async deleteRole(e,t){return await(t||this.dbAdapter).delete(De,e),this.changeQueue.enqueue({type:"delete",model:De,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(De,a);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("DuplicateRole",{originalId:e,newId:n}),o}};var ce="sales";var fe="receivables";var lt="inventory_lots";var Zt=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 St(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(di({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(lt,{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(lt,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(lt,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:lt,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:lt,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:lt,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:lt,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 rn=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 er=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 we="tax_rates";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 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(we,i);return this.changeQueue.enqueue({type:"create",model:we,record:a}),this.context.logActivity("AddTaxRate",{id:r}),a}async updateTaxRate(e,t,r){let n=await(r||this.dbAdapter).get(we,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(we,e,a);return this.changeQueue.enqueue({type:"update",model:we,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(we,{...e,filters:i})}async getTaxRate(e,t){return(t||this.dbAdapter).get(we,e)}async deleteTaxRate(e,t){return await(t||this.dbAdapter).delete(we,e),this.changeQueue.enqueue({type:"delete",model:we,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(we,a);return this.changeQueue.enqueue({type:"create",model:we,record:a}),this.context.logActivity("DuplicateTaxRate",{originalId:e,newId:n}),o}};var tr=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(fi({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 rt="uoms";function Ro(u,e){return u*e}function _o(u,e){return e!==0?u/e:NaN}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 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(rt,i);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("AddUom",{id:r}),a}async updateUom(e,t,r){let n=await(r||this.dbAdapter).get(rt,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(rt,e,a);return this.changeQueue.enqueue({type:"update",model:rt,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(rt,{...e,filters:i})}async getUom(e,t){return(t||this.dbAdapter).get(rt,e)}async deleteUom(e,t){return await(t||this.dbAdapter).delete(rt,e),this.changeQueue.enqueue({type:"delete",model:rt,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(rt,a);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("DuplicateUom",{originalId:e,newId:n}),o}convertQuantity(e,t,r){let n=Ro(e,t.conversionFactor);return _o(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 He="users";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 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(He,i);return this.changeQueue.enqueue({type:"create",model:He,record:a}),this.context.logActivity("AddUser",{id:r}),a}async updateUser(e,t,r){let n=await(r||this.dbAdapter).get(He,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(He,e,a);return this.changeQueue.enqueue({type:"update",model:He,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(He,{...e,filters:i})}async getUser(e,t){return(t||this.dbAdapter).get(He,e)}async deleteUser(e,t){return await(t||this.dbAdapter).delete(He,e),this.changeQueue.enqueue({type:"delete",model:He,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(He,a);return this.changeQueue.enqueue({type:"create",model:He,record:a}),this.context.logActivity("DuplicateUser",{originalId:e,newId:n}),o}};var ze="suppliers";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 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(ze,i);return this.changeQueue.enqueue({type:"create",model:ze,record:a}),this.context.logActivity("AddSupplier",{id:r}),a}async updateSupplier(e,t,r){let n=await(r||this.dbAdapter).get(ze,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(ze,e,a);return this.changeQueue.enqueue({type:"update",model:ze,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(ze,{...e,filters:i})}async getSupplier(e,t){return(t||this.dbAdapter).get(ze,e)}async deleteSupplier(e,t){return await(t||this.dbAdapter).delete(ze,e),this.changeQueue.enqueue({type:"delete",model:ze,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(ze,a);return this.changeQueue.enqueue({type:"create",model:ze,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(ze,{...t,filters:a})}};var Re="purchase_orders";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 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(Re,i);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("AddPurchaseOrder",{id:r}),a}async updatePurchaseOrder(e,t,r){let n=await(r||this.dbAdapter).get(Re,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(Re,e,a);return this.changeQueue.enqueue({type:"update",model:Re,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(Re,{...e,filters:i})}async getPurchaseOrder(e,t){return(t||this.dbAdapter).get(Re,e)}async deletePurchaseOrder(e,t){return await(t||this.dbAdapter).delete(Re,e),this.changeQueue.enqueue({type:"delete",model:Re,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(Re,a);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("DuplicatePurchaseOrder",{originalId:e,newId:n}),o}};var je="purchase_order_items";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 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(je,i);return this.changeQueue.enqueue({type:"create",model:je,record:a}),this.context.logActivity("AddPurchaseOrderItem",{id:r}),a}async updatePurchaseOrderItem(e,t,r){let n=await(r||this.dbAdapter).get(je,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(je,e,a);return this.changeQueue.enqueue({type:"update",model:je,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(je,{...e,filters:i})}async getPurchaseOrderItem(e,t){return(t||this.dbAdapter).get(je,e)}async deletePurchaseOrderItem(e,t){return await(t||this.dbAdapter).delete(je,e),this.changeQueue.enqueue({type:"delete",model:je,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(je,a);return this.changeQueue.enqueue({type:"create",model:je,record:a}),this.context.logActivity("DuplicatePurchaseOrderItem",{originalId:e,newId:n}),o}};var Se="purchases";var ye="payables";var $e="financial_settings";var ar=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 St(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(li({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($e,{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(Pe,{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(Re,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(je,{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(Pe,{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,Le)=>se+Le.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(Pe,O),this.changeQueue.enqueue({type:"create",model:Pe,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(lt,R),this.changeQueue.enqueue({type:"create",model:lt,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(Re,e,{status:k,version:w,lastModified:q}),this.changeQueue.enqueue({type:"update",model:Re,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(Pe,b);for(let v of b)m.push({type:"create",model:Pe,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 sn=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(Pe,i);return this.changeQueue.enqueue({type:"create",model:Pe,record:a}),this.context.logActivity("AddPurchaseItem",{id:r}),a}async updatePurchaseItem(e,t,r){let n=await(r||this.dbAdapter).get(Pe,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(Pe,e,a);return this.changeQueue.enqueue({type:"update",model:Pe,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(Pe,{...e,filters:i})}async getPurchaseItem(e,t){return(t||this.dbAdapter).get(Pe,e)}async deletePurchaseItem(e,t){return await(t||this.dbAdapter).delete(Pe,e),this.changeQueue.enqueue({type:"delete",model:Pe,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(Pe,a);return this.changeQueue.enqueue({type:"create",model:Pe,record:a}),this.context.logActivity("DuplicatePurchaseItem",{originalId:e,newId:n}),o}};var Ee="inventory_logs";function Rt(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 qe=Rt();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 addInventoryLog(e,t){let r=D(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(Ee,i);return this.changeQueue.enqueue({type:"create",model:Ee,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(Ee,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(Ee,e,a);return this.changeQueue.enqueue({type:"update",model:Ee,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(Ee,e)}async getInventoryLog(e,t){return(t||this.dbAdapter).get(Ee,e)}async deleteInventoryLog(e,t){let r=await(t||this.dbAdapter).get(Ee,e);return await(t||this.dbAdapter).delete(Ee,e),this.changeQueue.enqueue({type:"delete",model:Ee,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(Ee,a);return this.changeQueue.enqueue({type:"create",model:Ee,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),qe.emit("stock:changed",{productId:e,delta:0})}};var Ke="price_histories";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 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(Ke,i);return this.changeQueue.enqueue({type:"create",model:Ke,record:a}),this.context.logActivity("AddPriceHistory",{id:r}),a}async updatePriceHistory(e,t,r){let n=await(r||this.dbAdapter).get(Ke,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(Ke,e,a);return this.changeQueue.enqueue({type:"update",model:Ke,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(Ke,{...e,filters:i})}async getPriceHistory(e,t){return(t||this.dbAdapter).get(Ke,e)}async deletePriceHistory(e,t){return await(t||this.dbAdapter).delete(Ke,e),this.changeQueue.enqueue({type:"delete",model:Ke,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(Ke,a);return this.changeQueue.enqueue({type:"create",model:Ke,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(Ke,a);this.context.logActivity("RecordPriceHistory",{productId:i.productId,unitCost:i.unitCost}),r.push(o)}return r}};var Ce="stock_opnames";var Be="stock_opname_items";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 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(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=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("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(Be,{filters:{stockOpnameId:e,deleted:!1}});for(let d of i)d.difference!==0&&await r.updateStock(d.productId,d.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 cn=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(Be,i);return this.changeQueue.enqueue({type:"create",model:Be,record:a}),this.context.logActivity("AddStockOpnameItem",{id:r}),a}async updateStockOpnameItem(e,t,r){let n=await(r||this.dbAdapter).get(Be,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(Be,e,a);return this.changeQueue.enqueue({type:"update",model:Be,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(Be,{...e,filters:i})}async getStockOpnameItem(e,t){return(t||this.dbAdapter).get(Be,e)}async deleteStockOpnameItem(e,t){return await(t||this.dbAdapter).delete(Be,e),this.changeQueue.enqueue({type:"delete",model:Be,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(Be,a);return this.changeQueue.enqueue({type:"create",model:Be,record:a}),this.context.logActivity("DuplicateStockOpnameItem",{originalId:e,newId:n}),o}};var nt="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=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("AddStockAdjustment",{id:r}),a}async updateStockAdjustment(e,t,r){let n=await(r||this.dbAdapter).get(nt,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(nt,e,a);return this.changeQueue.enqueue({type:"update",model:nt,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(nt,{...e,filters:i})}async getStockAdjustment(e,t){return(t||this.dbAdapter).get(nt,e)}async deleteStockAdjustment(e,t){return await(t||this.dbAdapter).delete(nt,e),this.changeQueue.enqueue({type:"delete",model:nt,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(nt,a);return this.changeQueue.enqueue({type:"create",model:nt,record:a}),this.context.logActivity("DuplicateStockAdjustment",{originalId:e,newId:n}),o}};var it="report_schedules";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 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(it,i);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("AddReportSchedule",{id:r}),a}async updateReportSchedule(e,t,r){let n=await(r||this.dbAdapter).get(it,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(it,e,a);return this.changeQueue.enqueue({type:"update",model:it,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(it,{...e,filters:i})}async getReportSchedule(e,t){return(t||this.dbAdapter).get(it,e)}async deleteReportSchedule(e,t){return await(t||this.dbAdapter).delete(it,e),this.changeQueue.enqueue({type:"delete",model:it,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(it,a);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("DuplicateReportSchedule",{originalId:e,newId:n}),o}};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 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($e,i);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("AddFinancialSetting",{id:r}),a}async updateFinancialSetting(e,t,r){let n=await(r||this.dbAdapter).get($e,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($e,e,a);return this.changeQueue.enqueue({type:"update",model:$e,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($e,{...e,filters:i})}async getFinancialSetting(e,t){return(t||this.dbAdapter).get($e,e)}async deleteFinancialSetting(e,t){return await(t||this.dbAdapter).delete($e,e),this.changeQueue.enqueue({type:"delete",model:$e,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($e,a);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("DuplicateFinancialSetting",{originalId:e,newId:n}),o}};var at="expenses";var pr=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(mi({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(at,i);return this.changeQueue.enqueue({type:"create",model:at,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(at,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(at,e,a);return this.changeQueue.enqueue({type:"update",model:at,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(at,{...e,filters:i})}async getExpense(e,t){return(t||this.dbAdapter).get(at,e)}async deleteExpense(e,t){return await(t||this.dbAdapter).delete(at,e),this.changeQueue.enqueue({type:"delete",model:at,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(at,a);return this.changeQueue.enqueue({type:"create",model:at,record:a}),this.context.logActivity("DuplicateExpense",{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 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 hr=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 Ne="settlements";var fr=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(hi({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(Ne,i);return this.changeQueue.enqueue({type:"create",model:Ne,record:a}),this.context.logActivity("AddSettlement",{id:r}),a}async updateSettlement(e,t,r){let n=await(r||this.dbAdapter).get(Ne,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(Ne,e,a);return this.changeQueue.enqueue({type:"update",model:Ne,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(Ne,{...e,filters:i})}async getSettlement(e,t){return(t||this.dbAdapter).get(Ne,e)}async deleteSettlement(e,t){return await(t||this.dbAdapter).delete(Ne,e),this.changeQueue.enqueue({type:"delete",model:Ne,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(Ne,a);return this.changeQueue.enqueue({type:"create",model:Ne,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(Ne,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(Ne,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:Ne,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 gr=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),qe.on("stock:changed",this.onStockChanged),qe.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(Ee,d),this.changeQueue.enqueue({type:"create",model:Ee,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(Ee,{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`),qe.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(Ee,{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 Qi={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"}}},Ui={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 To=[{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 So=Object.create;var Wr=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var Do=Object.getPrototypeOf,Co=Object.prototype.hasOwnProperty;var re=(d,e)=>()=>(e||d((e={exports:{}}).exports,e),e.exports),wo=(d,e)=>{for(var t in e)Wr(d,t,{get:e[t],enumerable:!0})},qi=(d,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Po(e))!Co.call(d,n)&&n!==t&&Wr(d,n,{get:()=>e[n],enumerable:!(r=Io(e,n))||r.enumerable});return d};var Mt=(d,e,t)=>(t=d!=null?So(Do(d)):{},qi(e||!d||!d.__esModule?Wr(t,"default",{value:d,enumerable:!0}):t,d)),Eo=d=>qi(Wr({},"__esModule",{value:!0}),d);var Li=re(()=>{var Ni;(function(d){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:o(),r=n(d);typeof t.Reflect!="undefined"&&(r=n(t.Reflect,r)),e(r,t),typeof t.Reflect=="undefined"&&(t.Reflect=d);function n(s,u){return function(c,p){Object.defineProperty(s,c,{configurable:!0,writable:!0,value:p}),u&&u(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,u=!o&&!s,c={create:o?function(){return ot(Object.create(null))}:s?function(){return ot({__proto__:null})}:function(){return ot({})},has:u?function(P,w){return r.call(P,w)}:function(P,w){return w in P},get:u?function(P,w){return r.call(P,w)?P[w]:void 0}:function(P,w){return P[w]}},p=Object.getPrototypeOf(Function),l=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Et(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ot(),f=typeof WeakMap=="function"?WeakMap:dt(),y=n?Symbol.for("@reflect-metadata:registry"):void 0,b=wt(),m=ut(b);function g(P,w,q,U){if(D(q)){if(!we(P))throw new TypeError;if(!We(w))throw new TypeError;return N(P,w)}else{if(!we(P))throw new TypeError;if(!J(w))throw new TypeError;if(!J(U)&&!D(U)&&!X(U))throw new TypeError;return X(U)&&(U=void 0),q=pe(q),Q(P,w,q,U)}}e("decorate",g);function x(P,w){function q(U,W){if(!J(U))throw new TypeError;if(!D(W)&&!Ye(W))throw new TypeError;L(P,w,U,W)}return q}e("metadata",x);function v(P,w,q,U){if(!J(q))throw new TypeError;return D(U)||(U=pe(U)),L(P,w,q,U)}e("defineMetadata",v);function A(P,w,q){if(!J(w))throw new TypeError;return D(q)||(q=pe(q)),_(P,w,q)}e("hasMetadata",A);function S(P,w,q){if(!J(w))throw new TypeError;return D(q)||(q=pe(q)),$(P,w,q)}e("hasOwnMetadata",S);function M(P,w,q){if(!J(w))throw new TypeError;return D(q)||(q=pe(q)),H(P,w,q)}e("getMetadata",M);function I(P,w,q){if(!J(w))throw new TypeError;return D(q)||(q=pe(q)),k(P,w,q)}e("getOwnMetadata",I);function F(P,w){if(!J(P))throw new TypeError;return D(w)||(w=pe(w)),R(P,w)}e("getMetadataKeys",F);function E(P,w){if(!J(P))throw new TypeError;return D(w)||(w=pe(w)),B(P,w)}e("getOwnMetadataKeys",E);function O(P,w,q){if(!J(w))throw new TypeError;if(D(q)||(q=pe(q)),!J(w))throw new TypeError;D(q)||(q=pe(q));var U=ht(w,q,!1);return D(U)?!1:U.OrdinaryDeleteMetadata(P,w,q)}e("deleteMetadata",O);function N(P,w){for(var q=P.length-1;q>=0;--q){var U=P[q],W=U(w);if(!D(W)&&!X(W)){if(!We(W))throw new TypeError;w=W}}return w}function Q(P,w,q,U){for(var W=P.length-1;W>=0;--W){var he=P[W],ve=he(w,q,U);if(!D(ve)&&!X(ve)){if(!J(ve))throw new TypeError;U=ve}}return U}function _(P,w,q){var U=$(P,w,q);if(U)return!0;var W=Qe(w);return X(W)?!1:_(P,W,q)}function $(P,w,q){var U=ht(w,q,!1);return D(U)?!1:se(U.OrdinaryHasOwnMetadata(P,w,q))}function H(P,w,q){var U=$(P,w,q);if(U)return k(P,w,q);var W=Qe(w);if(!X(W))return H(P,W,q)}function k(P,w,q){var U=ht(w,q,!1);if(!D(U))return U.OrdinaryGetOwnMetadata(P,w,q)}function L(P,w,q,U){var W=ht(q,U,!0);W.OrdinaryDefineOwnMetadata(P,w,q,U)}function R(P,w){var q=B(P,w),U=Qe(P);if(U===null)return q;var W=R(U,w);if(W.length<=0)return q;if(q.length<=0)return W;for(var he=new h,ve=[],ee=0,z=q;ee<z.length;ee++){var V=z[ee],K=he.has(V);K||(he.add(V),ve.push(V))}for(var G=0,ne=W;G<ne.length;G++){var V=ne[G],K=he.has(V);K||(he.add(V),ve.push(V))}return ve}function B(P,w){var q=ht(P,w,!1);return q?q.OrdinaryOwnMetadataKeys(P,w):[]}function T(P){if(P===null)return 1;switch(typeof P){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return P===null?1:6;default:return 6}}function D(P){return P===void 0}function X(P){return P===null}function te(P){return typeof P=="symbol"}function J(P){return typeof P=="object"?P!==null:typeof P=="function"}function Y(P,w){switch(T(P)){case 0:return P;case 1:return P;case 2:return P;case 3:return P;case 4:return P;case 5:return P}var q=w===3?"string":w===5?"number":"default",U=st(P,i);if(U!==void 0){var W=U.call(P,q);if(J(W))throw new TypeError;return W}return be(P,q==="default"?"number":q)}function be(P,w){if(w==="string"){var q=P.toString;if(me(q)){var U=q.call(P);if(!J(U))return U}var W=P.valueOf;if(me(W)){var U=W.call(P);if(!J(U))return U}}else{var W=P.valueOf;if(me(W)){var U=W.call(P);if(!J(U))return U}var he=P.toString;if(me(he)){var U=he.call(P);if(!J(U))return U}}throw new TypeError}function se(P){return!!P}function Ne(P){return""+P}function pe(P){var w=Y(P,3);return te(w)?w:Ne(w)}function we(P){return Array.isArray?Array.isArray(P):P instanceof Object?P instanceof Array:Object.prototype.toString.call(P)==="[object Array]"}function me(P){return typeof P=="function"}function We(P){return typeof P=="function"}function Ye(P){switch(T(P)){case 3:return!0;case 4:return!0;default:return!1}}function Xe(P,w){return P===w||P!==P&&w!==w}function st(P,w){var q=P[w];if(q!=null){if(!me(q))throw new TypeError;return q}}function bt(P){var w=st(P,a);if(!me(w))throw new TypeError;var q=w.call(P);if(!J(q))throw new TypeError;return q}function ct(P){return P.value}function Me(P){var w=P.next();return w.done?!1:w}function ke(P){var w=P.return;w&&w.call(P)}function Qe(P){var w=Object.getPrototypeOf(P);if(typeof P!="function"||P===p||w!==p)return w;var q=P.prototype,U=q&&Object.getPrototypeOf(q);if(U==null||U===Object.prototype)return w;var W=U.constructor;return typeof W!="function"||W===P?w:W}function vt(){var P;!D(y)&&typeof t.Reflect!="undefined"&&!(y in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(P=mt(t.Reflect));var w,q,U,W=new f,he={registerProvider:ve,getProvider:z,setProvider:K};return he;function ve(G){if(!Object.isExtensible(he))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case P===G:break;case D(w):w=G;break;case w===G:break;case D(q):q=G;break;case q===G:break;default:U===void 0&&(U=new h),U.add(G);break}}function ee(G,ne){if(!D(w)){if(w.isProviderFor(G,ne))return w;if(!D(q)){if(q.isProviderFor(G,ne))return w;if(!D(U))for(var de=bt(U);;){var Ie=Me(de);if(!Ie)return;var Je=ct(Ie);if(Je.isProviderFor(G,ne))return ke(de),Je}}}if(!D(P)&&P.isProviderFor(G,ne))return P}function z(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 l,W.set(G,de)),de.set(ne,Ie))),Ie}function V(G){if(D(G))throw new TypeError;return w===G||q===G||!D(U)&&U.has(G)}function K(G,ne,de){if(!V(de))throw new Error("Metadata provider not registered.");var Ie=z(G,ne);if(Ie!==de){if(!D(Ie))return!1;var Je=W.get(G);D(Je)&&(Je=new l,W.set(G,Je)),Je.set(ne,de)}return!0}}function wt(){var P;return!D(y)&&J(t.Reflect)&&Object.isExtensible(t.Reflect)&&(P=t.Reflect[y]),D(P)&&(P=vt()),!D(y)&&J(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:P}),P}function ut(P){var w=new f,q={isProviderFor:function(V,K){var G=w.get(V);return D(G)?!1:G.has(K)},OrdinaryDefineOwnMetadata:ve,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:he,OrdinaryOwnMetadataKeys:ee,OrdinaryDeleteMetadata:z};return b.registerProvider(q),q;function U(V,K,G){var ne=w.get(V),de=!1;if(D(ne)){if(!G)return;ne=new l,w.set(V,ne),de=!0}var Ie=ne.get(K);if(D(Ie)){if(!G)return;if(Ie=new l,ne.set(K,Ie),!P.setProvider(V,K,q))throw ne.delete(K),de&&w.delete(V),new Error("Wrong provider for target.")}return Ie}function W(V,K,G){var ne=U(K,G,!1);return D(ne)?!1:se(ne.has(V))}function he(V,K,G){var ne=U(K,G,!1);if(!D(ne))return ne.get(V)}function ve(V,K,G,ne){var de=U(G,ne,!0);de.set(V,K)}function ee(V,K){var G=[],ne=U(V,K,!1);if(D(ne))return G;for(var de=ne.keys(),Ie=bt(de),Je=0;;){var Ht=Me(Ie);if(!Ht)return G.length=Je,G;var si=ct(Ht);try{G[Je]=si}catch(Gr){try{ke(Ie)}finally{throw Gr}}Je++}}function z(V,K,G){var ne=U(K,G,!1);if(D(ne)||!ne.delete(V))return!1;if(ne.size===0){var de=w.get(K);D(de)||(de.delete(G),de.size===0&&w.delete(de))}return!0}}function mt(P){var w=P.defineMetadata,q=P.hasOwnMetadata,U=P.getOwnMetadata,W=P.getOwnMetadataKeys,he=P.deleteMetadata,ve=new f,ee={isProviderFor:function(z,V){var K=ve.get(z);return!D(K)&&K.has(V)?!0:W(z,V).length?(D(K)&&(K=new h,ve.set(z,K)),K.add(V),!0):!1},OrdinaryDefineOwnMetadata:w,OrdinaryHasOwnMetadata:q,OrdinaryGetOwnMetadata:U,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:he};return ee}function ht(P,w,q){var U=b.getProvider(P,w);if(!D(U))return U;if(q){if(b.setProvider(P,w,m))return m;throw new Error("Illegal state.")}}function Et(){var P={},w=[],q=(function(){function ee(z,V,K){this._index=0,this._keys=z,this._values=V,this._selector=K}return ee.prototype["@@iterator"]=function(){return this},ee.prototype[a]=function(){return this},ee.prototype.next=function(){var z=this._index;if(z>=0&&z<this._keys.length){var V=this._selector(this._keys[z],this._values[z]);return z+1>=this._keys.length?(this._index=-1,this._keys=w,this._values=w):this._index++,{value:V,done:!1}}return{value:void 0,done:!0}},ee.prototype.throw=function(z){throw this._index>=0&&(this._index=-1,this._keys=w,this._values=w),z},ee.prototype.return=function(z){return this._index>=0&&(this._index=-1,this._keys=w,this._values=w),{value:z,done:!0}},ee})(),U=(function(){function ee(){this._keys=[],this._values=[],this._cacheKey=P,this._cacheIndex=-2}return Object.defineProperty(ee.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ee.prototype.has=function(z){return this._find(z,!1)>=0},ee.prototype.get=function(z){var V=this._find(z,!1);return V>=0?this._values[V]:void 0},ee.prototype.set=function(z,V){var K=this._find(z,!0);return this._values[K]=V,this},ee.prototype.delete=function(z){var V=this._find(z,!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(z,this._cacheKey)&&(this._cacheKey=P,this._cacheIndex=-2),!0}return!1},ee.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=P,this._cacheIndex=-2},ee.prototype.keys=function(){return new q(this._keys,this._values,W)},ee.prototype.values=function(){return new q(this._keys,this._values,he)},ee.prototype.entries=function(){return new q(this._keys,this._values,ve)},ee.prototype["@@iterator"]=function(){return this.entries()},ee.prototype[a]=function(){return this.entries()},ee.prototype._find=function(z,V){if(!Xe(this._cacheKey,z)){this._cacheIndex=-1;for(var K=0;K<this._keys.length;K++)if(Xe(this._keys[K],z)){this._cacheIndex=K;break}}return this._cacheIndex<0&&V&&(this._cacheIndex=this._keys.length,this._keys.push(z),this._values.push(void 0)),this._cacheIndex},ee})();return U;function W(ee,z){return ee}function he(ee,z){return z}function ve(ee,z){return[ee,z]}}function Ot(){var P=(function(){function w(){this._map=new l}return Object.defineProperty(w.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),w.prototype.has=function(q){return this._map.has(q)},w.prototype.add=function(q){return this._map.set(q,q),this},w.prototype.delete=function(q){return this._map.delete(q)},w.prototype.clear=function(){this._map.clear()},w.prototype.keys=function(){return this._map.keys()},w.prototype.values=function(){return this._map.keys()},w.prototype.entries=function(){return this._map.entries()},w.prototype["@@iterator"]=function(){return this.keys()},w.prototype[a]=function(){return this.keys()},w})();return P}function dt(){var P=16,w=c.create(),q=U();return(function(){function z(){this._key=U()}return z.prototype.has=function(V){var K=W(V,!1);return K!==void 0?c.has(K,this._key):!1},z.prototype.get=function(V){var K=W(V,!1);return K!==void 0?c.get(K,this._key):void 0},z.prototype.set=function(V,K){var G=W(V,!0);return G[this._key]=K,this},z.prototype.delete=function(V){var K=W(V,!1);return K!==void 0?delete K[this._key]:!1},z.prototype.clear=function(){this._key=U()},z})();function U(){var z;do z="@@WeakMap@@"+ee();while(c.has(w,z));return w[z]=!0,z}function W(z,V){if(!r.call(z,q)){if(!V)return;Object.defineProperty(z,q,{value:c.create()})}return z[q]}function he(z,V){for(var K=0;K<V;++K)z[K]=Math.random()*255|0;return z}function ve(z){if(typeof Uint8Array=="function"){var V=new Uint8Array(z);return typeof crypto!="undefined"?crypto.getRandomValues(V):typeof msCrypto!="undefined"?msCrypto.getRandomValues(V):he(V,z),V}return he(new Array(z),z)}function ee(){var z=ve(P);z[6]=z[6]&79|64,z[8]=z[8]&191|128;for(var V="",K=0;K<P;++K){var G=z[K];(K===4||K===6||K===8)&&(V+="-"),G<16&&(V+="0"),V+=G.toString(16).toLowerCase()}return V}}function ot(P){return P.__=void 0,delete P.__,P}})})(Ni||(Ni={}))});var ae=re((gn,Xi)=>{(function(d,e){typeof gn=="object"?Xi.exports=gn=e():typeof define=="function"&&define.amd?define([],e):d.CryptoJS=e()})(gn,function(){var d=d||(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 require=="function")try{r=require("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 m(){}return function(g){var x;return m.prototype=g,x=new m,m.prototype=null,x}})(),a={},o=a.lib={},s=o.Base=(function(){return{extend:function(m){var g=i(this);return m&&g.mixIn(m),(!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 m=this.extend();return m.init.apply(m,arguments),m},init:function(){},mixIn:function(m){for(var g in m)m.hasOwnProperty(g)&&(this[g]=m[g]);m.hasOwnProperty("toString")&&(this.toString=m.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),u=o.WordArray=s.extend({init:function(m,g){m=this.words=m||[],g!=t?this.sigBytes=g:this.sigBytes=m.length*4},toString:function(m){return(m||p).stringify(this)},concat:function(m){var g=this.words,x=m.words,v=this.sigBytes,A=m.sigBytes;if(this.clamp(),v%4)for(var S=0;S<A;S++){var M=x[S>>>2]>>>24-S%4*8&255;g[v+S>>>2]|=M<<24-(v+S)%4*8}else for(var I=0;I<A;I+=4)g[v+I>>>2]=x[I>>>2];return this.sigBytes+=A,this},clamp:function(){var m=this.words,g=this.sigBytes;m[g>>>2]&=4294967295<<32-g%4*8,m.length=e.ceil(g/4)},clone:function(){var m=s.clone.call(this);return m.words=this.words.slice(0),m},random:function(m){for(var g=[],x=0;x<m;x+=4)g.push(n());return new u.init(g,m)}}),c=a.enc={},p=c.Hex={stringify:function(m){for(var g=m.words,x=m.sigBytes,v=[],A=0;A<x;A++){var S=g[A>>>2]>>>24-A%4*8&255;v.push((S>>>4).toString(16)),v.push((S&15).toString(16))}return v.join("")},parse:function(m){for(var g=m.length,x=[],v=0;v<g;v+=2)x[v>>>3]|=parseInt(m.substr(v,2),16)<<24-v%8*4;return new u.init(x,g/2)}},l=c.Latin1={stringify:function(m){for(var g=m.words,x=m.sigBytes,v=[],A=0;A<x;A++){var S=g[A>>>2]>>>24-A%4*8&255;v.push(String.fromCharCode(S))}return v.join("")},parse:function(m){for(var g=m.length,x=[],v=0;v<g;v++)x[v>>>2]|=(m.charCodeAt(v)&255)<<24-v%4*8;return new u.init(x,g)}},h=c.Utf8={stringify:function(m){try{return decodeURIComponent(escape(l.stringify(m)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(m){return l.parse(unescape(encodeURIComponent(m)))}},f=o.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new u.init,this._nDataBytes=0},_append:function(m){typeof m=="string"&&(m=h.parse(m)),this._data.concat(m),this._nDataBytes+=m.sigBytes},_process:function(m){var g,x=this._data,v=x.words,A=x.sigBytes,S=this.blockSize,M=S*4,I=A/M;m?I=e.ceil(I):I=e.max((I|0)-this._minBufferSize,0);var F=I*S,E=e.min(F*4,A);if(F){for(var O=0;O<F;O+=S)this._doProcessBlock(v,O);g=v.splice(0,F),x.sigBytes-=E}return new u.init(g,E)},clone:function(){var m=s.clone.call(this);return m._data=this._data.clone(),m},_minBufferSize:0}),y=o.Hasher=f.extend({cfg:s.extend(),init:function(m){this.cfg=this.cfg.extend(m),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(m){return this._append(m),this._process(),this},finalize:function(m){m&&this._append(m);var g=this._doFinalize();return g},blockSize:512/32,_createHelper:function(m){return function(g,x){return new m.init(x).finalize(g)}},_createHmacHelper:function(m){return function(g,x){return new b.HMAC.init(m,x).finalize(g)}}}),b=a.algo={};return a})(Math);return d})});var Tr=re((yn,Ji)=>{(function(d,e){typeof yn=="object"?Ji.exports=yn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(yn,function(d){return(function(e){var t=d,r=t.lib,n=r.Base,i=r.WordArray,a=t.x64={},o=a.Word=n.extend({init:function(u,c){this.high=u,this.low=c}}),s=a.WordArray=n.extend({init:function(u,c){u=this.words=u||[],c!=e?this.sigBytes=c:this.sigBytes=u.length*8},toX32:function(){for(var u=this.words,c=u.length,p=[],l=0;l<c;l++){var h=u[l];p.push(h.high),p.push(h.low)}return i.create(p,this.sigBytes)},clone:function(){for(var u=n.clone.call(this),c=u.words=this.words.slice(0),p=c.length,l=0;l<p;l++)c[l]=c[l].clone();return u}})})(),d})});var ea=re((bn,Zi)=>{(function(d,e){typeof bn=="object"?Zi.exports=bn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(bn,function(d){return(function(){if(typeof ArrayBuffer=="function"){var e=d,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=[],u=0;u<o;u++)s[u>>>2]|=a[u]<<24-u%4*8;n.call(this,s,o)}else n.apply(this,arguments)};i.prototype=r}})(),d.lib.WordArray})});var ra=re((vn,ta)=>{(function(d,e){typeof vn=="object"?ta.exports=vn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(vn,function(d){return(function(){var e=d,t=e.lib,r=t.WordArray,n=e.enc,i=n.Utf16=n.Utf16BE={stringify:function(o){for(var s=o.words,u=o.sigBytes,c=[],p=0;p<u;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,u=[],c=0;c<s;c++)u[c>>>1]|=o.charCodeAt(c)<<16-c%2*16;return r.create(u,s*2)}};n.Utf16LE={stringify:function(o){for(var s=o.words,u=o.sigBytes,c=[],p=0;p<u;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,u=[],c=0;c<s;c++)u[c>>>1]|=a(o.charCodeAt(c)<<16-c%2*16);return r.create(u,s*2)}};function a(o){return o<<8&4278255360|o>>>8&16711935}})(),d.enc.Utf16})});var Dt=re((xn,na)=>{(function(d,e){typeof xn=="object"?na.exports=xn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(xn,function(d){return(function(){var e=d,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64={stringify:function(o){var s=o.words,u=o.sigBytes,c=this._map;o.clamp();for(var p=[],l=0;l<u;l+=3)for(var h=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=h<<16|f<<8|y,m=0;m<4&&l+m*.75<u;m++)p.push(c.charAt(b>>>6*(3-m)&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,u=this._map,c=this._reverseMap;if(!c){c=this._reverseMap=[];for(var p=0;p<u.length;p++)c[u.charCodeAt(p)]=p}var l=u.charAt(64);if(l){var h=o.indexOf(l);h!==-1&&(s=h)}return a(o,s,c)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function a(o,s,u){for(var c=[],p=0,l=0;l<s;l++)if(l%4){var h=u[o.charCodeAt(l-1)]<<l%4*2,f=u[o.charCodeAt(l)]>>>6-l%4*2,y=h|f;c[p>>>2]|=y<<24-p%4*8,p++}return r.create(c,p)}})(),d.enc.Base64})});var aa=re((An,ia)=>{(function(d,e){typeof An=="object"?ia.exports=An=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(An,function(d){return(function(){var e=d,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64url={stringify:function(o,s){s===void 0&&(s=!0);var u=o.words,c=o.sigBytes,p=s?this._safe_map:this._map;o.clamp();for(var l=[],h=0;h<c;h+=3)for(var f=u[h>>>2]>>>24-h%4*8&255,y=u[h+1>>>2]>>>24-(h+1)%4*8&255,b=u[h+2>>>2]>>>24-(h+2)%4*8&255,m=f<<16|y<<8|b,g=0;g<4&&h+g*.75<c;g++)l.push(p.charAt(m>>>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 u=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 h=c.charAt(64);if(h){var f=o.indexOf(h);f!==-1&&(u=f)}return a(o,u,p)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function a(o,s,u){for(var c=[],p=0,l=0;l<s;l++)if(l%4){var h=u[o.charCodeAt(l-1)]<<l%4*2,f=u[o.charCodeAt(l)]>>>6-l%4*2,y=h|f;c[p>>>2]|=y<<24-p%4*8,p++}return r.create(c,p)}})(),d.enc.Base64url})});var Ct=re((Sn,oa)=>{(function(d,e){typeof Sn=="object"?oa.exports=Sn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(Sn,function(d){return(function(e){var t=d,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[];(function(){for(var h=0;h<64;h++)o[h]=e.abs(e.sin(h+1))*4294967296|0})();var s=a.MD5=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(h,f){for(var y=0;y<16;y++){var b=f+y,m=h[b];h[b]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360}var g=this._hash.words,x=h[f+0],v=h[f+1],A=h[f+2],S=h[f+3],M=h[f+4],I=h[f+5],F=h[f+6],E=h[f+7],O=h[f+8],N=h[f+9],Q=h[f+10],_=h[f+11],$=h[f+12],H=h[f+13],k=h[f+14],L=h[f+15],R=g[0],B=g[1],T=g[2],D=g[3];R=u(R,B,T,D,x,7,o[0]),D=u(D,R,B,T,v,12,o[1]),T=u(T,D,R,B,A,17,o[2]),B=u(B,T,D,R,S,22,o[3]),R=u(R,B,T,D,M,7,o[4]),D=u(D,R,B,T,I,12,o[5]),T=u(T,D,R,B,F,17,o[6]),B=u(B,T,D,R,E,22,o[7]),R=u(R,B,T,D,O,7,o[8]),D=u(D,R,B,T,N,12,o[9]),T=u(T,D,R,B,Q,17,o[10]),B=u(B,T,D,R,_,22,o[11]),R=u(R,B,T,D,$,7,o[12]),D=u(D,R,B,T,H,12,o[13]),T=u(T,D,R,B,k,17,o[14]),B=u(B,T,D,R,L,22,o[15]),R=c(R,B,T,D,v,5,o[16]),D=c(D,R,B,T,F,9,o[17]),T=c(T,D,R,B,_,14,o[18]),B=c(B,T,D,R,x,20,o[19]),R=c(R,B,T,D,I,5,o[20]),D=c(D,R,B,T,Q,9,o[21]),T=c(T,D,R,B,L,14,o[22]),B=c(B,T,D,R,M,20,o[23]),R=c(R,B,T,D,N,5,o[24]),D=c(D,R,B,T,k,9,o[25]),T=c(T,D,R,B,S,14,o[26]),B=c(B,T,D,R,O,20,o[27]),R=c(R,B,T,D,H,5,o[28]),D=c(D,R,B,T,A,9,o[29]),T=c(T,D,R,B,E,14,o[30]),B=c(B,T,D,R,$,20,o[31]),R=p(R,B,T,D,I,4,o[32]),D=p(D,R,B,T,O,11,o[33]),T=p(T,D,R,B,_,16,o[34]),B=p(B,T,D,R,k,23,o[35]),R=p(R,B,T,D,v,4,o[36]),D=p(D,R,B,T,M,11,o[37]),T=p(T,D,R,B,E,16,o[38]),B=p(B,T,D,R,Q,23,o[39]),R=p(R,B,T,D,H,4,o[40]),D=p(D,R,B,T,x,11,o[41]),T=p(T,D,R,B,S,16,o[42]),B=p(B,T,D,R,F,23,o[43]),R=p(R,B,T,D,N,4,o[44]),D=p(D,R,B,T,$,11,o[45]),T=p(T,D,R,B,L,16,o[46]),B=p(B,T,D,R,A,23,o[47]),R=l(R,B,T,D,x,6,o[48]),D=l(D,R,B,T,E,10,o[49]),T=l(T,D,R,B,k,15,o[50]),B=l(B,T,D,R,I,21,o[51]),R=l(R,B,T,D,$,6,o[52]),D=l(D,R,B,T,S,10,o[53]),T=l(T,D,R,B,Q,15,o[54]),B=l(B,T,D,R,v,21,o[55]),R=l(R,B,T,D,O,6,o[56]),D=l(D,R,B,T,L,10,o[57]),T=l(T,D,R,B,F,15,o[58]),B=l(B,T,D,R,H,21,o[59]),R=l(R,B,T,D,M,6,o[60]),D=l(D,R,B,T,_,10,o[61]),T=l(T,D,R,B,A,15,o[62]),B=l(B,T,D,R,N,21,o[63]),g[0]=g[0]+R|0,g[1]=g[1]+B|0,g[2]=g[2]+T|0,g[3]=g[3]+D|0},_doFinalize:function(){var h=this._data,f=h.words,y=this._nDataBytes*8,b=h.sigBytes*8;f[b>>>5]|=128<<24-b%32;var m=e.floor(y/4294967296),g=y;f[(b+64>>>9<<4)+15]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360,f[(b+64>>>9<<4)+14]=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360,h.sigBytes=(f.length+1)*4,this._process();for(var x=this._hash,v=x.words,A=0;A<4;A++){var S=v[A];v[A]=(S<<8|S>>>24)&16711935|(S<<24|S>>>8)&4278255360}return x},clone:function(){var h=i.clone.call(this);return h._hash=this._hash.clone(),h}});function u(h,f,y,b,m,g,x){var v=h+(f&y|~f&b)+m+x;return(v<<g|v>>>32-g)+f}function c(h,f,y,b,m,g,x){var v=h+(f&b|y&~b)+m+x;return(v<<g|v>>>32-g)+f}function p(h,f,y,b,m,g,x){var v=h+(f^y^b)+m+x;return(v<<g|v>>>32-g)+f}function l(h,f,y,b,m,g,x){var v=h+(y^(f|~b))+m+x;return(v<<g|v>>>32-g)+f}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)})(Math),d.MD5})});var Ii=re((In,sa)=>{(function(d,e){typeof In=="object"?sa.exports=In=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(In,function(d){return(function(){var e=d,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,u){for(var c=this._hash.words,p=c[0],l=c[1],h=c[2],f=c[3],y=c[4],b=0;b<80;b++){if(b<16)a[b]=s[u+b]|0;else{var m=a[b-3]^a[b-8]^a[b-14]^a[b-16];a[b]=m<<1|m>>>31}var g=(p<<5|p>>>27)+y+a[b];b<20?g+=(l&h|~l&f)+1518500249:b<40?g+=(l^h^f)+1859775393:b<60?g+=(l&h|l&f|h&f)-1894007588:g+=(l^h^f)-899497514,y=f,f=h,h=l<<30|l>>>2,l=p,p=g}c[0]=c[0]+p|0,c[1]=c[1]+l|0,c[2]=c[2]+h|0,c[3]=c[3]+f|0,c[4]=c[4]+y|0},_doFinalize:function(){var s=this._data,u=s.words,c=this._nDataBytes*8,p=s.sigBytes*8;return u[p>>>5]|=128<<24-p%32,u[(p+64>>>9<<4)+14]=Math.floor(c/4294967296),u[(p+64>>>9<<4)+15]=c,s.sigBytes=u.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)})(),d.SHA1})});var Ut=re((Pn,ca)=>{(function(d,e){typeof Pn=="object"?ca.exports=Pn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(Pn,function(d){return(function(e){var t=d,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[],s=[];(function(){function p(y){for(var b=e.sqrt(y),m=2;m<=b;m++)if(!(y%m))return!1;return!0}function l(y){return(y-(y|0))*4294967296|0}for(var h=2,f=0;f<64;)p(h)&&(f<8&&(o[f]=l(e.pow(h,1/2))),s[f]=l(e.pow(h,1/3)),f++),h++})();var u=[],c=a.SHA256=i.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(p,l){for(var h=this._hash.words,f=h[0],y=h[1],b=h[2],m=h[3],g=h[4],x=h[5],v=h[6],A=h[7],S=0;S<64;S++){if(S<16)u[S]=p[l+S]|0;else{var M=u[S-15],I=(M<<25|M>>>7)^(M<<14|M>>>18)^M>>>3,F=u[S-2],E=(F<<15|F>>>17)^(F<<13|F>>>19)^F>>>10;u[S]=I+u[S-7]+E+u[S-16]}var O=g&x^~g&v,N=f&y^f&b^y&b,Q=(f<<30|f>>>2)^(f<<19|f>>>13)^(f<<10|f>>>22),_=(g<<26|g>>>6)^(g<<21|g>>>11)^(g<<7|g>>>25),$=A+_+O+s[S]+u[S],H=Q+N;A=v,v=x,x=g,g=m+$|0,m=b,b=y,y=f,f=$+H|0}h[0]=h[0]+f|0,h[1]=h[1]+y|0,h[2]=h[2]+b|0,h[3]=h[3]+m|0,h[4]=h[4]+g|0,h[5]=h[5]+x|0,h[6]=h[6]+v|0,h[7]=h[7]+A|0},_doFinalize:function(){var p=this._data,l=p.words,h=this._nDataBytes*8,f=p.sigBytes*8;return l[f>>>5]|=128<<24-f%32,l[(f+64>>>9<<4)+14]=e.floor(h/4294967296),l[(f+64>>>9<<4)+15]=h,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),d.SHA256})});var da=re((Dn,ua)=>{(function(d,e,t){typeof Dn=="object"?ua.exports=Dn=e(ae(),Ut()):typeof define=="function"&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)})(Dn,function(d){return(function(){var e=d,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)})(),d.SHA224})});var Pi=re((Cn,la)=>{(function(d,e,t){typeof Cn=="object"?la.exports=Cn=e(ae(),Tr()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)})(Cn,function(d){return(function(){var e=d,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 u=[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,h){for(var f=this._hash.words,y=f[0],b=f[1],m=f[2],g=f[3],x=f[4],v=f[5],A=f[6],S=f[7],M=y.high,I=y.low,F=b.high,E=b.low,O=m.high,N=m.low,Q=g.high,_=g.low,$=x.high,H=x.low,k=v.high,L=v.low,R=A.high,B=A.low,T=S.high,D=S.low,X=M,te=I,J=F,Y=E,be=O,se=N,Ne=Q,pe=_,we=$,me=H,We=k,Ye=L,Xe=R,st=B,bt=T,ct=D,Me=0;Me<80;Me++){var ke,Qe,vt=c[Me];if(Me<16)Qe=vt.high=l[h+Me*2]|0,ke=vt.low=l[h+Me*2+1]|0;else{var wt=c[Me-15],ut=wt.high,mt=wt.low,ht=(ut>>>1|mt<<31)^(ut>>>8|mt<<24)^ut>>>7,Et=(mt>>>1|ut<<31)^(mt>>>8|ut<<24)^(mt>>>7|ut<<25),Ot=c[Me-2],dt=Ot.high,ot=Ot.low,P=(dt>>>19|ot<<13)^(dt<<3|ot>>>29)^dt>>>6,w=(ot>>>19|dt<<13)^(ot<<3|dt>>>29)^(ot>>>6|dt<<26),q=c[Me-7],U=q.high,W=q.low,he=c[Me-16],ve=he.high,ee=he.low;ke=Et+W,Qe=ht+U+(ke>>>0<Et>>>0?1:0),ke=ke+w,Qe=Qe+P+(ke>>>0<w>>>0?1:0),ke=ke+ee,Qe=Qe+ve+(ke>>>0<ee>>>0?1:0),vt.high=Qe,vt.low=ke}var z=we&We^~we&Xe,V=me&Ye^~me&st,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=(we>>>14|me<<18)^(we>>>18|me<<14)^(we<<23|me>>>9),Je=(me>>>14|we<<18)^(me>>>18|we<<14)^(me<<23|we>>>9),Ht=u[Me],si=Ht.high,Gr=Ht.low,Ze=ct+Je,St=bt+Ie+(Ze>>>0<ct>>>0?1:0),Ze=Ze+V,St=St+z+(Ze>>>0<V>>>0?1:0),Ze=Ze+Gr,St=St+si+(Ze>>>0<Gr>>>0?1:0),Ze=Ze+ke,St=St+Qe+(Ze>>>0<ke>>>0?1:0),Mi=de+G,Ao=ne+K+(Mi>>>0<de>>>0?1:0);bt=Xe,ct=st,Xe=We,st=Ye,We=we,Ye=me,me=pe+Ze|0,we=Ne+St+(me>>>0<pe>>>0?1:0)|0,Ne=be,pe=se,be=J,se=Y,J=X,Y=te,te=Ze+Mi|0,X=St+Ao+(te>>>0<Ze>>>0?1:0)|0}I=y.low=I+te,y.high=M+X+(I>>>0<te>>>0?1:0),E=b.low=E+Y,b.high=F+J+(E>>>0<Y>>>0?1:0),N=m.low=N+se,m.high=O+be+(N>>>0<se>>>0?1:0),_=g.low=_+pe,g.high=Q+Ne+(_>>>0<pe>>>0?1:0),H=x.low=H+me,x.high=$+we+(H>>>0<me>>>0?1:0),L=v.low=L+Ye,v.high=k+We+(L>>>0<Ye>>>0?1:0),B=A.low=B+st,A.high=R+Xe+(B>>>0<st>>>0?1:0),D=S.low=D+ct,S.high=T+bt+(D>>>0<ct>>>0?1:0)},_doFinalize:function(){var l=this._data,h=l.words,f=this._nDataBytes*8,y=l.sigBytes*8;h[y>>>5]|=128<<24-y%32,h[(y+128>>>10<<5)+30]=Math.floor(f/4294967296),h[(y+128>>>10<<5)+31]=f,l.sigBytes=h.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)})(),d.SHA512})});var ma=re((wn,pa)=>{(function(d,e,t){typeof wn=="object"?pa.exports=wn=e(ae(),Tr(),Pi()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)})(wn,function(d){return(function(){var e=d,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)})(),d.SHA384})});var fa=re((En,ha)=>{(function(d,e,t){typeof En=="object"?ha.exports=En=e(ae(),Tr()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)})(En,function(d){return(function(e){var t=d,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.x64,o=a.Word,s=t.algo,u=[],c=[],p=[];(function(){for(var f=1,y=0,b=0;b<24;b++){u[f+5*y]=(b+1)*(b+2)/2%64;var m=y%5,g=(2*f+3*y)%5;f=m,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,S=0,M=0;M<7;M++){if(x&1){var I=(1<<M)-1;I<32?S^=1<<I:A^=1<<I-32}x&128?x=x<<1^113:x<<=1}p[v]=o.create(A,S)}})();var l=[];(function(){for(var f=0;f<25;f++)l[f]=o.create()})();var h=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,m=this.blockSize/2,g=0;g<m;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 S=0;S<24;S++){for(var M=0;M<5;M++){for(var I=0,F=0,E=0;E<5;E++){var A=b[M+5*E];I^=A.high,F^=A.low}var O=l[M];O.high=I,O.low=F}for(var M=0;M<5;M++)for(var N=l[(M+4)%5],Q=l[(M+1)%5],_=Q.high,$=Q.low,I=N.high^(_<<1|$>>>31),F=N.low^($<<1|_>>>31),E=0;E<5;E++){var A=b[M+5*E];A.high^=I,A.low^=F}for(var H=1;H<25;H++){var I,F,A=b[H],k=A.high,L=A.low,R=u[H];R<32?(I=k<<R|L>>>32-R,F=L<<R|k>>>32-R):(I=L<<R-32|k>>>64-R,F=k<<R-32|L>>>64-R);var B=l[c[H]];B.high=I,B.low=F}var T=l[0],D=b[0];T.high=D.high,T.low=D.low;for(var M=0;M<5;M++)for(var E=0;E<5;E++){var H=M+5*E,A=b[H],X=l[H],te=l[(M+1)%5+5*E],J=l[(M+2)%5+5*E];A.high=X.high^~te.high&J.high,A.low=X.low^~te.low&J.low}var A=b[0],Y=p[S];A.high^=Y.high,A.low^=Y.low}},_doFinalize:function(){var f=this._data,y=f.words,b=this._nDataBytes*8,m=f.sigBytes*8,g=this.blockSize*32;y[m>>>5]|=1<<24-m%32,y[(e.ceil((m+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,S=[],M=0;M<A;M++){var I=x[M],F=I.high,E=I.low;F=(F<<8|F>>>24)&16711935|(F<<24|F>>>8)&4278255360,E=(E<<8|E>>>24)&16711935|(E<<24|E>>>8)&4278255360,S.push(E),S.push(F)}return new n.init(S,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(h),t.HmacSHA3=i._createHmacHelper(h)})(Math),d.SHA3})});var ya=re((On,ga)=>{(function(d,e){typeof On=="object"?ga.exports=On=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(On,function(d){return(function(e){var t=d,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]),u=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]),h=a.RIPEMD160=i.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(v,A){for(var S=0;S<16;S++){var M=A+S,I=v[M];v[M]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360}var F=this._hash.words,E=p.words,O=l.words,N=o.words,Q=s.words,_=u.words,$=c.words,H,k,L,R,B,T,D,X,te,J;T=H=F[0],D=k=F[1],X=L=F[2],te=R=F[3],J=B=F[4];for(var Y,S=0;S<80;S+=1)Y=H+v[A+N[S]]|0,S<16?Y+=f(k,L,R)+E[0]:S<32?Y+=y(k,L,R)+E[1]:S<48?Y+=b(k,L,R)+E[2]:S<64?Y+=m(k,L,R)+E[3]:Y+=g(k,L,R)+E[4],Y=Y|0,Y=x(Y,_[S]),Y=Y+B|0,H=B,B=R,R=x(L,10),L=k,k=Y,Y=T+v[A+Q[S]]|0,S<16?Y+=g(D,X,te)+O[0]:S<32?Y+=m(D,X,te)+O[1]:S<48?Y+=b(D,X,te)+O[2]:S<64?Y+=y(D,X,te)+O[3]:Y+=f(D,X,te)+O[4],Y=Y|0,Y=x(Y,$[S]),Y=Y+J|0,T=J,J=te,te=x(X,10),X=D,D=Y;Y=F[1]+L+te|0,F[1]=F[2]+R+J|0,F[2]=F[3]+B+T|0,F[3]=F[4]+H+D|0,F[4]=F[0]+k+X|0,F[0]=Y},_doFinalize:function(){var v=this._data,A=v.words,S=this._nDataBytes*8,M=v.sigBytes*8;A[M>>>5]|=128<<24-M%32,A[(M+64>>>9<<4)+14]=(S<<8|S>>>24)&16711935|(S<<24|S>>>8)&4278255360,v.sigBytes=(A.length+1)*4,this._process();for(var I=this._hash,F=I.words,E=0;E<5;E++){var O=F[E];F[E]=(O<<8|O>>>24)&16711935|(O<<24|O>>>8)&4278255360}return I},clone:function(){var v=i.clone.call(this);return v._hash=this._hash.clone(),v}});function f(v,A,S){return v^A^S}function y(v,A,S){return v&A|~v&S}function b(v,A,S){return(v|~A)^S}function m(v,A,S){return v&S|A&~S}function g(v,A,S){return v^(A|~S)}function x(v,A){return v<<A|v>>>32-A}t.RIPEMD160=i._createHelper(h),t.HmacRIPEMD160=i._createHmacHelper(h)})(Math),d.RIPEMD160})});var kr=re((Rn,ba)=>{(function(d,e){typeof Rn=="object"?ba.exports=Rn=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(Rn,function(d){(function(){var e=d,t=e.lib,r=t.Base,n=e.enc,i=n.Utf8,a=e.algo,o=a.HMAC=r.extend({init:function(s,u){s=this._hasher=new s.init,typeof u=="string"&&(u=i.parse(u));var c=s.blockSize,p=c*4;u.sigBytes>p&&(u=s.finalize(u)),u.clamp();for(var l=this._oKey=u.clone(),h=this._iKey=u.clone(),f=l.words,y=h.words,b=0;b<c;b++)f[b]^=1549556828,y[b]^=909522486;l.sigBytes=h.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 u=this._hasher,c=u.finalize(s);u.reset();var p=u.finalize(this._oKey.clone().concat(c));return p}})})()})});var xa=re((_n,va)=>{(function(d,e,t){typeof _n=="object"?va.exports=_n=e(ae(),Ut(),kr()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(d.CryptoJS)})(_n,function(d){return(function(){var e=d,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(u){this.cfg=this.cfg.extend(u)},compute:function(u,c){for(var p=this.cfg,l=o.create(p.hasher,u),h=n.create(),f=n.create([1]),y=h.words,b=f.words,m=p.keySize,g=p.iterations;y.length<m;){var x=l.update(c).finalize(f);l.reset();for(var v=x.words,A=v.length,S=x,M=1;M<g;M++){S=l.finalize(S),l.reset();for(var I=S.words,F=0;F<A;F++)v[F]^=I[F]}h.concat(x),b[0]++}return h.sigBytes=m*4,h}});e.PBKDF2=function(u,c,p){return s.create(p).compute(u,c)}})(),d.PBKDF2})});var At=re((Tn,Aa)=>{(function(d,e,t){typeof Tn=="object"?Aa.exports=Tn=e(ae(),Ii(),kr()):typeof define=="function"&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)})(Tn,function(d){return(function(){var e=d,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,u){for(var c,p=this.cfg,l=p.hasher.create(),h=n.create(),f=h.words,y=p.keySize,b=p.iterations;f.length<y;){c&&l.update(c),c=l.update(s).finalize(u),l.reset();for(var m=1;m<b;m++)c=l.finalize(c),l.reset();h.concat(c)}return h.sigBytes=y*4,h}});e.EvpKDF=function(s,u,c){return o.create(c).compute(s,u)}})(),d.EvpKDF})});var Te=re((kn,Sa)=>{(function(d,e,t){typeof kn=="object"?Sa.exports=kn=e(ae(),At()):typeof define=="function"&&define.amd?define(["./core","./evpkdf"],e):e(d.CryptoJS)})(kn,function(d){d.lib.Cipher||(function(e){var t=d,r=t.lib,n=r.Base,i=r.WordArray,a=r.BufferedBlockAlgorithm,o=t.enc,s=o.Utf8,u=o.Base64,c=t.algo,p=c.EvpKDF,l=r.Cipher=a.extend({cfg:n.extend(),createEncryptor:function(O,N){return this.create(this._ENC_XFORM_MODE,O,N)},createDecryptor:function(O,N){return this.create(this._DEC_XFORM_MODE,O,N)},init:function(O,N,Q){this.cfg=this.cfg.extend(Q),this._xformMode=O,this._key=N,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(O){return this._append(O),this._process()},finalize:function(O){O&&this._append(O);var N=this._doFinalize();return N},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:(function(){function O(N){return typeof N=="string"?E:M}return function(N){return{encrypt:function(Q,_,$){return O(_).encrypt(N,Q,_,$)},decrypt:function(Q,_,$){return O(_).decrypt(N,Q,_,$)}}}})()}),h=r.StreamCipher=l.extend({_doFinalize:function(){var O=this._process(!0);return O},blockSize:1}),f=t.mode={},y=r.BlockCipherMode=n.extend({createEncryptor:function(O,N){return this.Encryptor.create(O,N)},createDecryptor:function(O,N){return this.Decryptor.create(O,N)},init:function(O,N){this._cipher=O,this._iv=N}}),b=f.CBC=(function(){var O=y.extend();O.Encryptor=O.extend({processBlock:function(Q,_){var $=this._cipher,H=$.blockSize;N.call(this,Q,_,H),$.encryptBlock(Q,_),this._prevBlock=Q.slice(_,_+H)}}),O.Decryptor=O.extend({processBlock:function(Q,_){var $=this._cipher,H=$.blockSize,k=Q.slice(_,_+H);$.decryptBlock(Q,_),N.call(this,Q,_,H),this._prevBlock=k}});function N(Q,_,$){var H,k=this._iv;k?(H=k,this._iv=e):H=this._prevBlock;for(var L=0;L<$;L++)Q[_+L]^=H[L]}return O})(),m=t.pad={},g=m.Pkcs7={pad:function(O,N){for(var Q=N*4,_=Q-O.sigBytes%Q,$=_<<24|_<<16|_<<8|_,H=[],k=0;k<_;k+=4)H.push($);var L=i.create(H,_);O.concat(L)},unpad:function(O){var N=O.words[O.sigBytes-1>>>2]&255;O.sigBytes-=N}},x=r.BlockCipher=l.extend({cfg:l.cfg.extend({mode:b,padding:g}),reset:function(){var O;l.reset.call(this);var N=this.cfg,Q=N.iv,_=N.mode;this._xformMode==this._ENC_XFORM_MODE?O=_.createEncryptor:(O=_.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==O?this._mode.init(this,Q&&Q.words):(this._mode=O.call(_,this,Q&&Q.words),this._mode.__creator=O)},_doProcessBlock:function(O,N){this._mode.processBlock(O,N)},_doFinalize:function(){var O,N=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(N.pad(this._data,this.blockSize),O=this._process(!0)):(O=this._process(!0),N.unpad(O)),O},blockSize:128/32}),v=r.CipherParams=n.extend({init:function(O){this.mixIn(O)},toString:function(O){return(O||this.formatter).stringify(this)}}),A=t.format={},S=A.OpenSSL={stringify:function(O){var N,Q=O.ciphertext,_=O.salt;return _?N=i.create([1398893684,1701076831]).concat(_).concat(Q):N=Q,N.toString(u)},parse:function(O){var N,Q=u.parse(O),_=Q.words;return _[0]==1398893684&&_[1]==1701076831&&(N=i.create(_.slice(2,4)),_.splice(0,4),Q.sigBytes-=16),v.create({ciphertext:Q,salt:N})}},M=r.SerializableCipher=n.extend({cfg:n.extend({format:S}),encrypt:function(O,N,Q,_){_=this.cfg.extend(_);var $=O.createEncryptor(Q,_),H=$.finalize(N),k=$.cfg;return v.create({ciphertext:H,key:Q,iv:k.iv,algorithm:O,mode:k.mode,padding:k.padding,blockSize:O.blockSize,formatter:_.format})},decrypt:function(O,N,Q,_){_=this.cfg.extend(_),N=this._parse(N,_.format);var $=O.createDecryptor(Q,_).finalize(N.ciphertext);return $},_parse:function(O,N){return typeof O=="string"?N.parse(O,this):O}}),I=t.kdf={},F=I.OpenSSL={execute:function(O,N,Q,_,$){if(_||(_=i.random(64/8)),$)var H=p.create({keySize:N+Q,hasher:$}).compute(O,_);else var H=p.create({keySize:N+Q}).compute(O,_);var k=i.create(H.words.slice(N),Q*4);return H.sigBytes=N*4,v.create({key:H,iv:k,salt:_})}},E=r.PasswordBasedCipher=M.extend({cfg:M.cfg.extend({kdf:F}),encrypt:function(O,N,Q,_){_=this.cfg.extend(_);var $=_.kdf.execute(Q,O.keySize,O.ivSize,_.salt,_.hasher);_.iv=$.iv;var H=M.encrypt.call(this,O,N,$.key,_);return H.mixIn($),H},decrypt:function(O,N,Q,_){_=this.cfg.extend(_),N=this._parse(N,_.format);var $=_.kdf.execute(Q,O.keySize,O.ivSize,N.salt,_.hasher);_.iv=$.iv;var H=M.decrypt.call(this,O,N,$.key,_);return H}})})()})});var Pa=re((Fn,Ia)=>{(function(d,e,t){typeof Fn=="object"?Ia.exports=Fn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Fn,function(d){return d.mode.CFB=(function(){var e=d.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 u=0;u<i;u++)r[n+u]^=o[u]}return e})(),d.mode.CFB})});var Ca=re((Bn,Da)=>{(function(d,e,t){typeof Bn=="object"?Da.exports=Bn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Bn,function(d){return d.mode.CTR=(function(){var e=d.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 u=s.slice(0);i.encryptBlock(u,0),s[a-1]=s[a-1]+1|0;for(var c=0;c<a;c++)r[n+c]^=u[c]}});return e.Decryptor=t,e})(),d.mode.CTR})});var Ea=re((Mn,wa)=>{(function(d,e,t){typeof Mn=="object"?wa.exports=Mn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Mn,function(d){return d.mode.CTRGladman=(function(){var e=d.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,u=this._iv,c=this._counter;u&&(c=this._counter=u.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})(),d.mode.CTRGladman})});var Ra=re((qn,Oa)=>{(function(d,e,t){typeof qn=="object"?Oa.exports=qn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(qn,function(d){return d.mode.OFB=(function(){var e=d.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 u=0;u<a;u++)r[n+u]^=s[u]}});return e.Decryptor=t,e})(),d.mode.OFB})});var Ta=re((Nn,_a)=>{(function(d,e,t){typeof Nn=="object"?_a.exports=Nn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Nn,function(d){return d.mode.ECB=(function(){var e=d.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})(),d.mode.ECB})});var Fa=re((Ln,ka)=>{(function(d,e,t){typeof Ln=="object"?ka.exports=Ln=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Ln,function(d){return d.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}},d.pad.Ansix923})});var Ma=re((Qn,Ba)=>{(function(d,e,t){typeof Qn=="object"?Ba.exports=Qn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Qn,function(d){return d.pad.Iso10126={pad:function(e,t){var r=t*4,n=r-e.sigBytes%r;e.concat(d.lib.WordArray.random(n-1)).concat(d.lib.WordArray.create([n<<24],1))},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},d.pad.Iso10126})});var Na=re((Un,qa)=>{(function(d,e,t){typeof Un=="object"?qa.exports=Un=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Un,function(d){return d.pad.Iso97971={pad:function(e,t){e.concat(d.lib.WordArray.create([2147483648],1)),d.pad.ZeroPadding.pad(e,t)},unpad:function(e){d.pad.ZeroPadding.unpad(e),e.sigBytes--}},d.pad.Iso97971})});var Qa=re((Hn,La)=>{(function(d,e,t){typeof Hn=="object"?La.exports=Hn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(Hn,function(d){return d.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}}},d.pad.ZeroPadding})});var Ha=re((jn,Ua)=>{(function(d,e,t){typeof jn=="object"?Ua.exports=jn=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})(jn,function(d){return d.pad.NoPadding={pad:function(){},unpad:function(){}},d.pad.NoPadding})});var $a=re(($n,ja)=>{(function(d,e,t){typeof $n=="object"?ja.exports=$n=e(ae(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)})($n,function(d){return(function(e){var t=d,r=t.lib,n=r.CipherParams,i=t.enc,a=i.Hex,o=t.format,s=o.Hex={stringify:function(u){return u.ciphertext.toString(a)},parse:function(u){var c=a.parse(u);return n.create({ciphertext:c})}}})(),d.format.Hex})});var Va=re((zn,za)=>{(function(d,e,t){typeof zn=="object"?za.exports=zn=e(ae(),Dt(),Ct(),At(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)})(zn,function(d){return(function(){var e=d,t=e.lib,r=t.BlockCipher,n=e.algo,i=[],a=[],o=[],s=[],u=[],c=[],p=[],l=[],h=[],f=[];(function(){for(var m=[],g=0;g<256;g++)g<128?m[g]=g<<1:m[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 S=m[x],M=m[S],I=m[M],F=m[A]*257^A*16843008;o[x]=F<<24|F>>>8,s[x]=F<<16|F>>>16,u[x]=F<<8|F>>>24,c[x]=F;var F=I*16843009^M*65537^S*257^x*16843008;p[A]=F<<24|F>>>8,l[A]=F<<16|F>>>16,h[A]=F<<8|F>>>24,f[A]=F,x?(x=S^m[m[m[I^S]]],v^=m[m[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 m;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,S=(A+1)*4,M=this._keySchedule=[],I=0;I<S;I++)I<v?M[I]=x[I]:(m=M[I-1],I%v?v>6&&I%v==4&&(m=i[m>>>24]<<24|i[m>>>16&255]<<16|i[m>>>8&255]<<8|i[m&255]):(m=m<<8|m>>>24,m=i[m>>>24]<<24|i[m>>>16&255]<<16|i[m>>>8&255]<<8|i[m&255],m^=y[I/v|0]<<24),M[I]=M[I-v]^m);for(var F=this._invKeySchedule=[],E=0;E<S;E++){var I=S-E;if(E%4)var m=M[I];else var m=M[I-4];E<4||I<=4?F[E]=m:F[E]=p[i[m>>>24]]^l[i[m>>>16&255]]^h[i[m>>>8&255]]^f[i[m&255]]}}},encryptBlock:function(m,g){this._doCryptBlock(m,g,this._keySchedule,o,s,u,c,i)},decryptBlock:function(m,g){var x=m[g+1];m[g+1]=m[g+3],m[g+3]=x,this._doCryptBlock(m,g,this._invKeySchedule,p,l,h,f,a);var x=m[g+1];m[g+1]=m[g+3],m[g+3]=x},_doCryptBlock:function(m,g,x,v,A,S,M,I){for(var F=this._nRounds,E=m[g]^x[0],O=m[g+1]^x[1],N=m[g+2]^x[2],Q=m[g+3]^x[3],_=4,$=1;$<F;$++){var H=v[E>>>24]^A[O>>>16&255]^S[N>>>8&255]^M[Q&255]^x[_++],k=v[O>>>24]^A[N>>>16&255]^S[Q>>>8&255]^M[E&255]^x[_++],L=v[N>>>24]^A[Q>>>16&255]^S[E>>>8&255]^M[O&255]^x[_++],R=v[Q>>>24]^A[E>>>16&255]^S[O>>>8&255]^M[N&255]^x[_++];E=H,O=k,N=L,Q=R}var H=(I[E>>>24]<<24|I[O>>>16&255]<<16|I[N>>>8&255]<<8|I[Q&255])^x[_++],k=(I[O>>>24]<<24|I[N>>>16&255]<<16|I[Q>>>8&255]<<8|I[E&255])^x[_++],L=(I[N>>>24]<<24|I[Q>>>16&255]<<16|I[E>>>8&255]<<8|I[O&255])^x[_++],R=(I[Q>>>24]<<24|I[E>>>16&255]<<16|I[O>>>8&255]<<8|I[N&255])^x[_++];m[g]=H,m[g+1]=k,m[g+2]=L,m[g+3]=R},keySize:256/32});e.AES=r._createHelper(b)})(),d.AES})});var Ga=re((Vn,Ka)=>{(function(d,e,t){typeof Vn=="object"?Ka.exports=Vn=e(ae(),Dt(),Ct(),At(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)})(Vn,function(d){return(function(){var e=d,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],u=[{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,m=[],g=0;g<56;g++){var x=a[g]-1;m[g]=b[x>>>5]>>>31-x%32&1}for(var v=this._subKeys=[],A=0;A<16;A++){for(var S=v[A]=[],M=s[A],g=0;g<24;g++)S[g/6|0]|=m[(o[g]-1+M)%28]<<31-g%6,S[4+(g/6|0)]|=m[28+(o[g+24]-1+M)%28]<<31-g%6;S[0]=S[0]<<1|S[0]>>>31;for(var g=1;g<7;g++)S[g]=S[g]>>>(g-1)*4+3;S[7]=S[7]<<5|S[7]>>>27}for(var I=this._invSubKeys=[],g=0;g<16;g++)I[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,m){this._lBlock=y[b],this._rBlock=y[b+1],l.call(this,4,252645135),l.call(this,16,65535),h.call(this,2,858993459),h.call(this,8,16711935),l.call(this,1,1431655765);for(var g=0;g<16;g++){for(var x=m[g],v=this._lBlock,A=this._rBlock,S=0,M=0;M<8;M++)S|=u[M][((A^x[M])&c[M])>>>0];this._lBlock=A,this._rBlock=v^S}var I=this._lBlock;this._lBlock=this._rBlock,this._rBlock=I,l.call(this,1,1431655765),h.call(this,8,16711935),h.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 m=(this._lBlock>>>y^this._rBlock)&b;this._rBlock^=m,this._lBlock^=m<<y}function h(y,b){var m=(this._rBlock>>>y^this._lBlock)&b;this._lBlock^=m,this._rBlock^=m<<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 m=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(m)),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)})(),d.TripleDES})});var Ya=re((Kn,Wa)=>{(function(d,e,t){typeof Kn=="object"?Wa.exports=Kn=e(ae(),Dt(),Ct(),At(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)})(Kn,function(d){return(function(){var e=d,t=e.lib,r=t.StreamCipher,n=e.algo,i=n.RC4=r.extend({_doReset:function(){for(var s=this._key,u=s.words,c=s.sigBytes,p=this._S=[],l=0;l<256;l++)p[l]=l;for(var l=0,h=0;l<256;l++){var f=l%c,y=u[f>>>2]>>>24-f%4*8&255;h=(h+p[l]+y)%256;var b=p[l];p[l]=p[h],p[h]=b}this._i=this._j=0},_doProcessBlock:function(s,u){s[u]^=a.call(this)},keySize:256/32,ivSize:0});function a(){for(var s=this._S,u=this._i,c=this._j,p=0,l=0;l<4;l++){u=(u+1)%256,c=(c+s[u])%256;var h=s[u];s[u]=s[c],s[c]=h,p|=s[(s[u]+s[c])%256]<<24-l*8}return this._i=u,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)})(),d.RC4})});var Ja=re((Gn,Xa)=>{(function(d,e,t){typeof Gn=="object"?Xa.exports=Gn=e(ae(),Dt(),Ct(),At(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)})(Gn,function(d){return(function(){var e=d,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 h=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++)u.call(this);for(var l=0;l<8;l++)f[l]^=h[l+4&7];if(p){var y=p.words,b=y[0],m=y[1],g=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360,x=(m<<8|m>>>24)&16711935|(m<<24|m>>>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++)u.call(this)}},_doProcessBlock:function(c,p){var l=this._X;u.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 h=0;h<4;h++)i[h]=(i[h]<<8|i[h]>>>24)&16711935|(i[h]<<24|i[h]>>>8)&4278255360,c[p+h]^=i[h]},blockSize:128/32,ivSize:64/32});function u(){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 h=c[l]+p[l],f=h&65535,y=h>>>16,b=((f*f>>>17)+f*y>>>15)+y*y,m=((h&4294901760)*h|0)+((h&65535)*h|0);o[l]=b^m}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)})(),d.Rabbit})});var eo=re((Wn,Za)=>{(function(d,e,t){typeof Wn=="object"?Za.exports=Wn=e(ae(),Dt(),Ct(),At(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)})(Wn,function(d){return(function(){var e=d,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],h=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++)u.call(this);for(var f=0;f<8;f++)h[f]^=l[f+4&7];if(p){var y=p.words,b=y[0],m=y[1],g=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360,x=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360,v=g>>>16|x&4294901760,A=x<<16|g&65535;h[0]^=g,h[1]^=v,h[2]^=x,h[3]^=A,h[4]^=g,h[5]^=v,h[6]^=x,h[7]^=A;for(var f=0;f<4;f++)u.call(this)}},_doProcessBlock:function(c,p){var l=this._X;u.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 h=0;h<4;h++)i[h]=(i[h]<<8|i[h]>>>24)&16711935|(i[h]<<24|i[h]>>>8)&4278255360,c[p+h]^=i[h]},blockSize:128/32,ivSize:64/32});function u(){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 h=c[l]+p[l],f=h&65535,y=h>>>16,b=((f*f>>>17)+f*y>>>15)+y*y,m=((h&4294901760)*h|0)+((h&65535)*h|0);o[l]=b^m}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)})(),d.RabbitLegacy})});var ro=re((Yn,to)=>{(function(d,e,t){typeof Yn=="object"?to.exports=Yn=e(ae(),Dt(),Ct(),At(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)})(Yn,function(d){return(function(){var e=d,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 u(f,y){let b=y>>24&255,m=y>>16&255,g=y>>8&255,x=y&255,v=f.sbox[0][b]+f.sbox[1][m];return v=v^f.sbox[2][g],v=v+f.sbox[3][x],v}function c(f,y,b){let m=y,g=b,x;for(let v=0;v<i;++v)m=m^f.pbox[v],g=u(f,m)^g,x=m,m=g,g=x;return x=m,m=g,g=x,g=g^f.pbox[i],m=m^f.pbox[i+1],{left:m,right:g}}function p(f,y,b){let m=y,g=b,x;for(let v=i+1;v>1;--v)m=m^f.pbox[v],g=u(f,m)^g,x=m,m=g,g=x;return x=m,m=g,g=x,g=g^f.pbox[1],m=m^f.pbox[0],{left:m,right:g}}function l(f,y,b){for(let A=0;A<4;A++){f.sbox[A]=[];for(let S=0;S<256;S++)f.sbox[A][S]=o[A][S]}let m=0;for(let A=0;A<i+2;A++)f.pbox[A]=a[A]^y[m],m++,m>=b&&(m=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 S=0;S<256;S+=2)v=c(f,g,x),g=v.left,x=v.right,f.sbox[A][S]=g,f.sbox[A][S+1]=x;return!0}var h=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(h)})(),d.Blowfish})});var Di=re((Xn,no)=>{(function(d,e,t){typeof Xn=="object"?no.exports=Xn=e(ae(),Tr(),ea(),ra(),Dt(),aa(),Ct(),Ii(),Ut(),da(),Pi(),ma(),fa(),ya(),kr(),xa(),At(),Te(),Pa(),Ca(),Ea(),Ra(),Ta(),Fa(),Ma(),Na(),Qa(),Ha(),$a(),Va(),Ga(),Ya(),Ja(),eo(),ro()):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):d.CryptoJS=e(d.CryptoJS)})(Xn,function(d){return d})});var po=re((ii,lo)=>{(function(d,e,t){typeof ii=="object"?lo.exports=ii=e(ae(),Ut(),kr()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(d.CryptoJS)})(ii,function(d){return d.HmacSHA256})});var ho=re((ai,mo)=>{(function(d,e){typeof ai=="object"?mo.exports=ai=e(ae()):typeof define=="function"&&define.amd?define(["./core"],e):e(d.CryptoJS)})(ai,function(d){return d.enc.Hex})});var Yo={};wo(Yo,{ActivityLogger:()=>Or,AdapterRegistry:()=>jr,ApiService:()=>qr,AuthorizationService:()=>_r,BackupScheduler:()=>Qr,CONFLICT_POLICY_MATRIX:()=>io,CURRENT_SYNC_PROTOCOL_VERSION:()=>ln,CartService:()=>Dr,CartStore:()=>Pr,CategoryService:()=>jt,CheckoutComputationService:()=>$t,ConfigService:()=>Lr,ConsoleLoggerAdapter:()=>zr.ConsoleLoggerAdapter,CustomerGroupService:()=>Vt,CustomerService:()=>zt,DEFAULT_GRANULAR_AUTH_POLICY:()=>Si,DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS:()=>pn,DefaultExportAdapter:()=>$r.DefaultExportAdapter,DefaultHttpAdapter:()=>Mr.DefaultHttpAdapter,DefaultPlatformAdapter:()=>yo.DefaultPlatformAdapter,DomainServices:()=>wr,EncryptionService:()=>Fr,ExpenseService:()=>hr,ExponentialBackoffHttpPolicy:()=>pt.ExponentialBackoffHttpPolicy,ExportService:()=>xr,FinancialSettingService:()=>mr,HistoryService:()=>Kt,InMemoryDbAdapter:()=>xo.InMemoryDbAdapter,InMemorySocketAdapter:()=>Kr.InMemorySocketAdapter,IntegrationServices:()=>Ur,InventoryLogService:()=>cr,InventoryService:()=>br,MemoryActivitySink:()=>Bt.MemoryActivitySink,MemoryStorage:()=>gt,NoRetryHttpPolicy:()=>pt.NoRetryHttpPolicy,NoopActivitySink:()=>Bt.NoopActivitySink,NoopChecksumAdapter:()=>ti.NoopChecksumAdapter,NoopEncryptionAdapter:()=>ei.NoopEncryptionAdapter,NoopNotificationAdapter:()=>Vr.NoopNotificationAdapter,NoopSocketService:()=>kt,NoopSyncService:()=>Tt,NotificationService:()=>Nr,OrderService:()=>Gt,POS_DOMAIN_TABLES:()=>$o,POS_SCHEMA_VERSION:()=>so,PayableService:()=>gr,PosCore:()=>Ft,PriceHistoryService:()=>ur,PriceTierService:()=>Wt,PricingService:()=>Ar,ProductService:()=>Yt,PromotionService:()=>Xt,PurchaseOrderService:()=>or,PurchaseService:()=>sr,ReceivableService:()=>fr,ReportScheduleService:()=>pr,ReportingService:()=>Ir,ReturnService:()=>er,RoleAdapter:()=>Rr,SaleService:()=>tr,SessionStore:()=>Hr,SettlementService:()=>yr,ShiftService:()=>rr,SocketService:()=>wi,StockAdjustmentService:()=>lr,StockOpnameService:()=>dr,SupplierService:()=>ar,SyncService:()=>Ci,SyncStore:()=>Er,TASK_ID:()=>oo,TaxService:()=>Cr,TransactionService:()=>nr,UIProductService:()=>Fi,UITransactionService:()=>Bi,UomService:()=>ir,UserService:()=>Br,applyPendingMigrations:()=>Oi,bomTable:()=>Fe,buildJournalDraftFromPosFinanceProjection:()=>$i,categoryTable:()=>et,computeChecksum:()=>vr,createChangeQueuePort:()=>j,createPosFinanceRuntimeOptions:()=>No,customerGroupTable:()=>tt,customerTable:()=>ze,eventBus:()=>qe,executeHttpRequestWithRetry:()=>pt.executeHttpRequestWithRetry,expenseTable:()=>at,financialSettingTable:()=>$e,getSyncProtocolContract:()=>zo,historyTable:()=>ie,initialSessionState:()=>co,initialState:()=>Pt,inventoryLogTable:()=>Oe,isContractVersionCompatible:()=>vo.isContractVersionCompatible,isFailureEnvelope:()=>bo.isFailureEnvelope,isServerProtocolCompatible:()=>vi,kitchenTicketItemTable:()=>li,kitchenTicketTable:()=>Zr,loyaltyAccountTable:()=>Rt,loyaltyLedgerTable:()=>ft,migrations:()=>Ei,orderItemTable:()=>xe,orderTable:()=>oe,payableTable:()=>ye,priceHistoryTable:()=>Ke,priceTierTable:()=>Ue,productTable:()=>ce,projectPosCashAdjustmentFinance:()=>bi,projectPosExpenseFinance:()=>gi,projectPosPurchaseFinance:()=>hi,projectPosReturnFinance:()=>fi,projectPosSettlementFinance:()=>yi,projectScopedPosSaleFinance:()=>mi,promotionTable:()=>rt,purchaseItemTable:()=>Pe,purchaseOrderItemTable:()=>je,purchaseOrderTable:()=>_e,purchaseTable:()=>Se,receivableTable:()=>fe,reportScheduleTable:()=>it,returnItemTable:()=>Re,returnTable:()=>Ae,roleTable:()=>De,saleItemTable:()=>ge,saleTable:()=>ue,schemas:()=>yt,settlementTable:()=>Le,shiftTable:()=>le,stockAdjustmentTable:()=>Ge,stockOpnameItemTable:()=>Be,stockOpnameTable:()=>Ce,supplierTable:()=>Ve,taxRateTable:()=>Ee,transactionTable:()=>Z,uomTable:()=>nt,userTable:()=>He});module.exports=Eo(Yo);var Ey=Mt(Li());var uo=require("ofcore"),Zn=require("ofcore");var Yr="0123456789abcdef",Xr=class d{constructor(e){this.bytes=e}static ofInner(e){if(e.length!==16)throw new TypeError("not 128-bit length");return new d(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 d(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 u=parseInt(a.substring(2*s,2*s+8),16);o[s+0]=u>>>24,o[s+1]=u>>>16,o[s+2]=u>>>8,o[s+3]=u}return new d(o)}else throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Yr.charAt(this.bytes[t]>>>4),e+=Yr.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+=Yr.charAt(this.bytes[t]>>>4),e+=Yr.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 d(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}},ci=class{constructor(e){this.timestampBiased=0,this.counter=0,this.rollbackAllowance=1e4,this.random=e!=null?e:Oo()}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 Xr.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,Xr.ofInner(e)}},Oo=()=>{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues!="undefined")return new ui;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)}},ui=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++]}},Qi;var C=()=>Ro().toString(),Ro=()=>(Qi||(Qi=new ci)).generateV4();var di=class{constructor(e){this.context=e}enqueue(e){this.context.enqueueDomainChange(e)}};function j(d){return new di(d)}var Fe="boms";var Jr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addBom(e,t){let r=C(),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=C(),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 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=j(e)}async addCategory(e,t){let r=C(),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=C(),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 $t=class{constructor(e){this.context=e}get pricingService(){var t;let e=(t=this.context.domainServices)==null?void 0:t.pricing;if(!e)throw new Error("Checkout computation membutuhkan pricing service canonical.");return e}get customerService(){var e;return((e=this.context.domainServices)==null?void 0:e.customer)||null}toNumber(e,t=0){let r=Number(e);return Number.isFinite(r)?r:t}roundMoney(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}normalizeDiscountCodes(e){let t=(e||[]).map(r=>String(r||"").trim()).filter(Boolean);return t.length>0?t:void 0}async resolveCustomerGroupId(e){let t=String(e.customerGroupId||"").trim();if(t)return t;let r=String(e.customerId||"").trim();if(!r||!this.customerService)return;let n=await this.customerService.getCustomer(r);return String((n==null?void 0:n.groupId)||"").trim()||void 0}async computeCheckout(e){let t=Array.isArray(e.lines)?e.lines:[];if(t.length===0)throw new Error("Checkout computation membutuhkan minimal 1 line.");let r=e.paymentMethod;if(!r)throw new Error("Payment method wajib diisi.");let n=String(e.customerId||"").trim(),i=String(e.dueDate||"").trim(),a=r==="tempo",o=r==="tempo";if(a&&!n)throw new Error("Customer wajib dipilih untuk checkout tempo.");if(o&&!i)throw new Error("Jatuh tempo wajib diisi untuk checkout tempo.");let s=t.map(m=>{let g=String(m.productId||"").trim(),x=Number(m.quantity||0);if(!g)throw new Error("Checkout computation menemukan productId kosong.");if(!Number.isFinite(x)||x<=0)throw new Error(`Checkout computation menemukan qty tidak valid untuk produk ${g}.`);return{productId:g,quantity:x,uomId:String(m.uomId||"").trim()||null}}),u=await this.resolveCustomerGroupId(e),c=await this.pricingService.calculateOrderTotal(s.map(m=>({productId:m.productId,quantity:m.quantity,uomId:m.uomId||void 0})),this.normalizeDiscountCodes(e.discountCodes),u),p=await this.pricingService.calculateTaxBreakdown(c.total,{mode:e.taxMode==="inclusive"?"inclusive":"exclusive"}),l=this.toNumber(p.totalAfterCorrection,this.toNumber(c.total)),h=l,f=null,y=null;if(r==="cash"){let m=Number(e.cashReceived);if(!Number.isFinite(m))throw new Error("Cash received wajib berupa angka valid untuk checkout tunai.");f=this.roundMoney(m),y=this.roundMoney(Math.max(0,f-h))}return{pricedItems:s.map((m,g)=>{let x=(c.items||[])[g],v=this.toNumber(x==null?void 0:x.unitPrice);return{productId:m.productId,quantity:m.quantity,uomId:m.uomId,unitPrice:v,lineSubTotal:this.roundMoney(v*m.quantity)}}),subTotal:this.toNumber(c.subTotal),discount:this.toNumber(c.discount),totalBeforeTax:this.toNumber(c.total),tax:{mode:p.mode,taxBase:this.toNumber(p.taxBase),ppn:this.toNumber(p.ppn),pph:this.toNumber(p.pph)},finalTotal:this.toNumber(l),payment:{method:r,amountDue:this.toNumber(h),cashReceived:f,changeDue:y},flags:{requiresCustomer:a,requiresDueDate:o,isTaxActive:this.toNumber(p.ppn)>0||this.toNumber(p.pph)>0}}}};var ze="customers";var Rt="loyalty_accounts";var ft="loyalty_ledgers";var zt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(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:C(),customerId:t,pointsBalance:0,totalEarned:0,totalRedeemed:0,totalExpired:0,version:Date.now(),lastModified:n,deleted:!1})}async addCustomer(e,t){let r=C(),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=C(),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(ft,{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(ft,{id:C(),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 u=await this.getOrCreateLoyaltyAccount(i,t),c=await i.update(Rt,u.id,{pointsBalance:Number(u.pointsBalance||0)+s,totalEarned:Number(u.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 u=await i.query(ft,{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 u){if(c<=0)break;let h=Number(l.availablePoints||0);if(h<=0)continue;let f=Math.min(h,c),y=h-f;await i.update(ft,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(ft,{id:C(),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(ft,{filters:{and:n}});if(!i.length)return{expiredPoints:0,affectedCustomers:0};let a=0,o=new Map;for(let s of i){let u=Number(s.availablePoints||0);u<=0||(a+=u,o.set(s.customerId,(o.get(s.customerId)||0)+u),await t.update(ft,s.id,{availablePoints:0,consumedAt:r,version:Date.now(),lastModified:r}),await t.create(ft,{id:C(),customerId:s.customerId,entryType:"expire",points:u,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,u]of o.entries()){let c=await this.getOrCreateLoyaltyAccount(t,s);await t.update(Rt,c.id,{pointsBalance:Math.max(0,Number(c.pointsBalance||0)-u),totalExpired:Number(c.totalExpired||0)+u,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=j(e)}async addCustomerGroup(e,t){let r=C(),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=C(),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 Kt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addHistory(e,t){let r=C(),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=C(),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,u=null;if(r){let p=(c=this.context.registry)==null?void 0:c.storageAdapter;u=`audit-archive:${e.toISOString().slice(0,10)}`;let h=await(p==null?void 0:p.getItem(u)),f=h?JSON.parse(h):[],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(u,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:u}),{scanned:a.length,archived:s,purged:o.length,archiveKey:u}}};var oe="orders";var xe="order_items";var Ui=require("ofcore"),gt=class extends Ui.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 gt(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(),u=this.getDateSegment(t);return`${o}-${s}-${u}-${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 li="kitchen_ticket_items";var Zr="kitchen_tickets";var Gt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(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),u=Number(r.pph||0),c=i+a+o+s+u;return e.update(oe,t,{total:i,finalTotal:c,version:Date.now(),lastModified:new Date().toISOString()})}async addOrder(e,t){var s,u,c,p,l,h,f,y;this.validateOmnichannelInput(e);let r=C(),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:(u=e.parentOrderId)!=null?u: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:(h=e.tableNumber)!=null?h: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=C(),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(),u=await i.update(oe,t,{status:n,version:Date.now(),lastModified:s});return await i.create(ie,{id:C(),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}),u})}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(Zr,{id:C(),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 u=await t.get(xe,s);if(!u||u.deleted||String(u.orderId)!==e.orderId)throw new Error(`Order item ${s} does not belong to order ${e.orderId}`);let c=await t.create(li,{id:C(),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:C(),tableName:Zr,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,u=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 h=await n.create(oe,{id:C(),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:u,deleted:!1});c.push(h.id);for(let f of l)await n.get(xe,f)&&await n.update(xe,f,{orderId:h.id,version:Date.now(),lastModified:u});await this.recalculateOrderTotals(n,h.id)}return await this.recalculateOrderTotals(n,t),await n.create(ie,{id:C(),tableName:oe,recordId:t,action:"bill_split",changes:{actorId:r,childOrderIds:c,movedItems:Array.from(s)},userId:r,timestamp:u}),{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 u=await i.get(oe,s);if(!u||u.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:[u.note,`MERGED_INTO:${t}`].filter(Boolean).join(" | ")})}return await this.recalculateOrderTotals(i,t),await i.create(ie,{id:C(),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,u=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:u});return await r.create(ie,{id:C(),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:u}),c})}};var en=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addOrderItem(e,t){let r=C(),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=C(),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 Ue="price_tiers";var Wt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addPriceTier(e,t){let r=C(),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("AddPriceTier",{id:r}),a}async updatePriceTier(e,t,r){let n=await(r||this.dbAdapter).get(Ue,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(Ue,e,a);return this.changeQueue.enqueue({type:"update",model:Ue,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(Ue,{...e,filters:i})}async getPriceTier(e,t){return(t||this.dbAdapter).get(Ue,e)}async deletePriceTier(e,t){return await(t||this.dbAdapter).delete(Ue,e),this.changeQueue.enqueue({type:"delete",model:Ue,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=C(),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("DuplicatePriceTier",{originalId:e,newId:n}),o}};var ce="products";var _o={name:["name","nama","productname","product_name"],barcode:["barcode","code","sku","productcode","product_code"],qrCode:["qrcode","qr_code","qr"],description:["description","deskripsi","desc"],category:["category","kategori","categoryname","category_name"],baseUom:["baseuom","base_uom","uom","uomcode","uom_code"],price:["price","harga","sellingprice","selling_price","baseprice","base_price"],cost:["cost","harga_pokok","modal","hpp"],initialStock:["initialstock","initial_stock","openingstock","opening_stock","stokawal","stok_awal"]};function xt(d){return d.trim().toLowerCase().replace(/[^a-z0-9]+/g,"")}function Hi(d){let e=[],t="",r=!1;for(let n=0;n<d.length;n+=1){let i=d[n];if(i==='"'){let a=d[n+1];if(r&&a==='"'){t+='"',n+=1;continue}r=!r;continue}if(i===","&&!r){e.push(t),t="";continue}t+=i}return e.push(t),e.map(n=>n.trim())}function To(d){let e=d.replace(/\r\n/g,`
2
+ `).replace(/\r/g,`
3
+ `).trim();if(!e)throw new Error("CSV katalog kosong.");let t=e.split(`
4
+ `).map(u=>u.trim()).filter(u=>u.length>0);if(t.length<2)throw new Error("CSV katalog harus berisi header dan minimal satu baris data.");let r=Hi(t[0]),n=new Map;r.forEach((u,c)=>{n.set(xt(u),c)});let i=u=>{let c=_o[u];for(let p of c){let l=n.get(p);if(l!=null)return l}return-1};if(i("name")<0)throw new Error("Header CSV wajib memiliki kolom name/nama.");if(i("price")<0)throw new Error("Header CSV wajib memiliki kolom price/harga.");let s=t.slice(1).map(u=>{let c=Hi(u),p=l=>{var f;let h=i(l);return h>=0?String((f=c[h])!=null?f:"").trim():""};return{name:p("name"),barcode:p("barcode"),qrCode:p("qrCode"),description:p("description"),category:p("category"),baseUom:p("baseUom"),price:p("price"),cost:p("cost"),initialStock:p("initialStock")}});return{headers:r,rows:s}}function pi(d,e=0){if(!d.trim())return e;let t=d.replace(/\./g,"").replace(",",".").trim(),r=Number(t);if(!Number.isFinite(r))throw new Error(`Nilai angka tidak valid: ${d}`);return r}function ji(d,e,t,r){return{tableName:d,recordId:e,action:t,changes:r,userId:null,timestamp:new Date().toISOString()}}var Yt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addProduct(e,t){let r=C(),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=C(),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})}getCatalogImportTemplateCsv(){return["name,barcode,qrCode,description,category,baseUom,price,cost,initialStock","Kopi Susu Gula Aren,899100000001,,Minuman kopi susu botol,Minuman,PCS,18000,9000,24","Keripik Singkong Balado,899100000002,,Snack kemasan pedas,Snack,PCS,12000,7000,40"].join(`
5
+ `)}async importProductsFromCsv(e,t={}){var x,v,A,S,M;let r=To(e),n={processedRows:0,createdCount:0,updatedCount:0,skippedCount:0,errorCount:0,rows:[],errors:[]},i=t.createMissingCategories!==!1,a=t.applyStockToExisting===!0,o=(x=this.context.domainServices)==null?void 0:x.category,s=(v=this.context.domainServices)==null?void 0:v.uom,u=(A=this.context.domainServices)==null?void 0:A.inventory,c=(S=this.context.domainServices)==null?void 0:S.history,p=((M=t.source)==null?void 0:M.trim())||"catalog_csv_import",l=o?await o.getCategories():[],h=s?await s.getUoms():[],f=new Map(l.map(I=>[xt(I.name),I])),y=new Map;for(let I of h)y.set(xt(I.code),I),y.set(xt(I.name),I);let b=async I=>{var $;let F=xt(I);if(!F)throw new Error("Kategori wajib diisi untuk import katalog.");let E=f.get(F);if(E)return E.id;if(!o||!i)throw new Error(`Kategori tidak ditemukan: ${I}`);let O=I.split(">").map(H=>H.trim()).filter(Boolean),N=null,Q="",_="";for(let H of O){Q=Q?`${Q}>${H}`:H;let k=xt(Q),L=($=f.get(k))!=null?$:f.get(xt(H));if(L&&L.parentId===N){_=L.id,N=L.id,f.set(k,L);continue}let R=await o.addCategory({name:H,parentId:N});f.set(k,R),f.set(xt(H),R),_=R.id,N=R.id}if(!_)throw new Error(`Gagal membuat kategori: ${I}`);return _},m=I=>{if(!I.trim())return null;let F=y.get(xt(I));if(!F)throw new Error(`UOM tidak ditemukan: ${I}`);return F.id},g=async I=>{var E;if(I.barcode){let O=await this.getProductsByBarcode(I.barcode);if(O[0])return O[0]}if(I.qrCode){let O=await this.getProductsByQrCode(I.qrCode);if(O[0])return O[0]}return(E=(await this.dbAdapter.query(ce,{filters:{and:[{field:"name",operator:"=",value:I.name},{deleted:!1}]},limit:1}))[0])!=null?E:null};for(let I=0;I<r.rows.length;I+=1){let F=I+2,E=r.rows[I];if(Object.values(E).every(N=>!String(N).trim())){n.skippedCount+=1,n.rows.push({rowNumber:F,action:"skipped",productId:null,productName:"",stockApplied:0,notes:["Baris kosong dilewati."]});continue}try{if(!E.name.trim())throw new Error("Nama produk wajib diisi.");let N=pi(E.price),Q=pi(E.cost,0),_=pi(E.initialStock,0);if(N<0||Q<0||_<0)throw new Error("Harga, modal, dan stok awal tidak boleh negatif.");let $=await b(E.category),H=m(E.baseUom),k=await g(E),L=[];if(!k){let T=await this.addProduct({name:E.name,barcode:E.barcode||null,qrCode:E.qrCode||null,description:E.description||null,categoryId:$,baseUomId:H,price:N,cost:Q});c&&await c.addHistory(ji("products",T.id,"catalog_import_create",{source:p,rowNumber:F,name:E.name,barcode:E.barcode||null}));let D=0;_>0&&u&&(await u.updateStock(T.id,_,"catalog_import_initial_stock","catalog_import",`${p}:${F}`),D=_,L.push("Stok awal dibuat lewat inventory log.")),n.createdCount+=1,n.rows.push({rowNumber:F,action:"created",productId:T.id,productName:T.name||E.name,stockApplied:D,notes:L}),n.processedRows+=1;continue}let R=await this.updateProduct(k.id,{name:E.name||k.name,barcode:E.barcode||k.barcode,qrCode:E.qrCode||k.qrCode,description:E.description||k.description,categoryId:$,baseUomId:H,price:N,cost:Q});c&&await c.addHistory(ji("products",R.id,"catalog_import_update",{source:p,rowNumber:F,name:E.name,barcode:E.barcode||null}));let B=0;_>0&&(a&&u?(await u.updateStock(R.id,_,"catalog_import_stock_increment","catalog_import",`${p}:${F}`),B=_,L.push("Stok ditambahkan ke produk existing lewat inventory log.")):L.push("Stok awal untuk produk existing dilewati demi mencegah double count.")),n.updatedCount+=1,n.rows.push({rowNumber:F,action:"updated",productId:R.id,productName:R.name||E.name,stockApplied:B,notes:L}),n.processedRows+=1}catch(N){n.errorCount+=1,n.errors.push({rowNumber:F,code:"CATALOG_IMPORT_ROW_INVALID",message:N instanceof Error?N.message:String(N),row:E})}}return n}};var rt="promotions";var Xt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addPromotion(e,t){let r=C(),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=C(),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 Pe="purchase_items";var Re="return_items";var Z="transactions";var tn=require("offinance-shared-core");function mi(d){var t,r;let e=d.sale.date||new Date().toISOString();return{context:{journalId:(t=d.journalId)!=null?t:`journal-sale-${d.sale.id}`,tenantId:d.tenantId,branchId:d.branchId,occurredAt:e,reference:`${(r=d.referencePrefix)!=null?r:"sale"}:${d.sale.id}`},input:{grossAmount:d.sale.total,discountAmount:d.sale.discount,taxAmount:d.sale.ppn,scopedAccountMapping:d.scopedAccountMapping}}}function hi(d){var e,t;return{kind:"purchase",context:{journalId:(e=d.journalId)!=null?e:`journal-purchase-${d.purchase.id}`,tenantId:d.tenantId,branchId:d.branchId,occurredAt:d.purchase.date||new Date().toISOString(),reference:`${(t=d.referencePrefix)!=null?t:"purchase"}:${d.purchase.id}`},input:{totalAmount:d.purchase.total,paymentMethod:d.paymentMethod,scopedAccountMapping:d.scopedAccountMapping}}}function fi(d){var t,r;return{kind:d.returnEntry.type==="purchase_return"?"purchase_return":"sale_return",context:{journalId:(t=d.journalId)!=null?t:`journal-return-${d.returnEntry.id}`,tenantId:d.tenantId,branchId:d.branchId,occurredAt:d.returnEntry.date||new Date().toISOString(),reference:`${(r=d.referencePrefix)!=null?r:"return"}:${d.returnEntry.id}`},input:{actualRefund:d.returnEntry.actualRefund,scopedAccountMapping:d.scopedAccountMapping}}}function gi(d){var e,t;return{kind:"expense",context:{journalId:(e=d.journalId)!=null?e:`journal-expense-${d.expense.id}`,tenantId:d.tenantId,branchId:d.branchId,occurredAt:d.expense.date||new Date().toISOString(),reference:`${(t=d.referencePrefix)!=null?t:"expense"}:${d.expense.id}`},input:{amount:d.expense.amount,category:d.expense.category,description:d.expense.description,scopedAccountMapping:d.scopedAccountMapping}}}function yi(d){var t,r,n,i;let e=d.settlement.receivableId?"receivable_payment":"payable_payment";return{kind:e,context:{journalId:(t=d.journalId)!=null?t:`journal-settlement-${d.settlement.id}`,tenantId:d.tenantId,branchId:d.branchId,occurredAt:d.settlement.date||new Date().toISOString(),reference:`${(r=d.referencePrefix)!=null?r:e}:${d.settlement.id}`},input:{amount:d.settlement.amount,method:d.settlement.method,receivableId:(n=d.settlement.receivableId)!=null?n:null,payableId:(i=d.settlement.payableId)!=null?i:null,scopedAccountMapping:d.scopedAccountMapping}}}function bi(d){var e,t;return{kind:"cash_adjustment",context:{journalId:(e=d.journalId)!=null?e:`journal-cash-adjustment-${d.adjustment.id}`,tenantId:d.tenantId,branchId:d.branchId,occurredAt:d.adjustment.date||new Date().toISOString(),reference:`${(t=d.referencePrefix)!=null?t:"cash_adjustment"}:${d.adjustment.id}`},input:{amount:d.adjustment.amount,direction:d.adjustment.direction,reason:d.adjustment.reason,scopedAccountMapping:d.scopedAccountMapping}}}function Jt(d,e){var i,a;let t=e.tenantId?(i=d.byTenant)==null?void 0:i[e.tenantId]:void 0,r=e.tenantId&&e.branchId?`${e.tenantId}:${e.branchId}`:"",n=r?(a=d.byBranch)==null?void 0:a[r]:void 0;return{...d.default,...t!=null?t:{},...n!=null?n:{}}}function ko(d){return"grossAmount"in d.input}function Fo(d){return d.kind==="purchase"}function Bo(d){return d.kind==="sale_return"||d.kind==="purchase_return"}function Mo(d){return d.kind==="receivable_payment"||d.kind==="payable_payment"}function qo(d){return d.kind==="cash_adjustment"}function Zt(d){return{id:d.journalId,tenantId:d.tenantId,branchId:d.branchId,occurredAt:d.occurredAt,reference:d.reference,ledgerProfileId:d.ledgerProfileId,financeDomainId:d.financeDomainId,lines:d.lines}}function $i(d,e){var n,i,a,o,s;let t=(n=e.financeDomainId)!=null?n:"ofpos";if(ko(d))return(0,tn.buildJournalFromScopedPosSale)({...d.context,ledgerProfileId:e.ledgerProfileId,financeDomainId:t},d.input);if(Fo(d)){let u=Jt(d.input.scopedAccountMapping,d.context),c=d.input.paymentMethod==="tempo"?u.payableAccountId:u.paymentAccountId;if(!c)throw new Error("POS_PURCHASE_SETTLEMENT_ACCOUNT_REQUIRED");return Zt({journalId:d.context.journalId,tenantId:d.context.tenantId,branchId:d.context.branchId,occurredAt:d.context.occurredAt,reference:d.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:[{accountId:u.inventoryAccountId,debit:d.input.totalAmount,credit:0,memo:"POS purchase inventory"},{accountId:c,debit:0,credit:d.input.totalAmount,memo:"POS purchase settlement"}]})}if(Bo(d)){let u=Jt(d.input.scopedAccountMapping,d.context);return Zt({journalId:d.context.journalId,tenantId:d.context.tenantId,branchId:d.context.branchId,occurredAt:d.context.occurredAt,reference:d.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:d.kind==="sale_return"?[{accountId:u.salesReturnAccountId,debit:d.input.actualRefund,credit:0,memo:"POS sale return refund"},{accountId:u.settlementAccountId,debit:0,credit:d.input.actualRefund,memo:"POS sale return cash out"}]:[{accountId:u.settlementAccountId,debit:d.input.actualRefund,credit:0,memo:"POS purchase return refund in"},{accountId:u.purchaseReturnAccountId,debit:0,credit:d.input.actualRefund,memo:"POS purchase return recovery"}]})}if(Mo(d)){let u=Jt(d.input.scopedAccountMapping,d.context);return Zt({journalId:d.context.journalId,tenantId:d.context.tenantId,branchId:d.context.branchId,occurredAt:d.context.occurredAt,reference:d.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:d.kind==="receivable_payment"?[{accountId:u.cashAccountId,debit:d.input.amount,credit:0,memo:"POS receivable payment cash in"},{accountId:u.receivableAccountId,debit:0,credit:d.input.amount,memo:"POS receivable settlement"}]:[{accountId:u.payableAccountId,debit:d.input.amount,credit:0,memo:"POS payable settlement"},{accountId:u.cashAccountId,debit:0,credit:d.input.amount,memo:"POS payable payment cash out"}]})}if(qo(d)){let u=Jt(d.input.scopedAccountMapping,d.context);return Zt({journalId:d.context.journalId,tenantId:d.context.tenantId,branchId:d.context.branchId,occurredAt:d.context.occurredAt,reference:d.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:d.input.direction==="in"?[{accountId:u.cashAccountId,debit:d.input.amount,credit:0,memo:((i=d.input.reason)==null?void 0:i.trim())||"POS cash adjustment in"},{accountId:u.cashOverShortIncomeAccountId,debit:0,credit:d.input.amount,memo:"POS cash over/short gain"}]:[{accountId:u.cashOverShortExpenseAccountId,debit:d.input.amount,credit:0,memo:"POS cash over/short loss"},{accountId:u.cashAccountId,debit:0,credit:d.input.amount,memo:((a=d.input.reason)==null?void 0:a.trim())||"POS cash adjustment out"}]})}let r=Jt(d.input.scopedAccountMapping,d.context);return Zt({journalId:d.context.journalId,tenantId:d.context.tenantId,branchId:d.context.branchId,occurredAt:d.context.occurredAt,reference:d.context.reference,ledgerProfileId:e.ledgerProfileId,financeDomainId:t,lines:[{accountId:r.expenseAccountId,debit:d.input.amount,credit:0,memo:((o=d.input.category)==null?void 0:o.trim())||"POS expense"},{accountId:r.paymentAccountId,debit:0,credit:d.input.amount,memo:((s=d.input.description)==null?void 0:s.trim())||"POS expense payment"}]})}function No(d){var e,t;return{saleAccountMapping:d.saleAccountMapping,purchaseAccountMapping:d.purchaseAccountMapping,returnAccountMapping:d.returnAccountMapping,expenseAccountMapping:d.expenseAccountMapping,settlementAccountMapping:d.settlementAccountMapping,cashAdjustmentAccountMapping:d.cashAdjustmentAccountMapping,financeProjectionSink:(0,tn.createFinanceProjectionSink)({dbAdapter:d.dbAdapter,resolveFinanceServices:d.resolveFinanceServices,resolveLedgerProfileId:d.resolveLedgerProfileId,resolveSyncEnqueuer:d.resolveSyncEnqueuer,requiredAccounts:d.requiredAccounts,buildJournalDraft:(r,n)=>{var i;return $i(r,{ledgerProfileId:n,financeDomainId:(i=d.financeDomainId)!=null?i:"ofpos"})},missingServicesErrorCode:(e=d.missingServicesErrorCode)!=null?e:"POS_FINANCE_SERVICES_UNAVAILABLE",missingLedgerProfileErrorCode:(t=d.missingLedgerProfileErrorCode)!=null?t:"POS_LEDGER_PROFILE_REQUIRED"})}}var er=class{constructor(e,t={}){this.context=e;this._runtimeOptions=t;var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=j(e)}async addReturn(e,t){let r=C(),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=C(),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:Pe,{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(fi({returnEntry:e,tenantId:t,branchId:((a=this.context.config)==null?void 0:a.branchId)||void 0,scopedAccountMapping:this._runtimeOptions.returnAccountMapping}))}async processReturn(e){var $,H,k,L;let t=(H=($=this.context)==null?void 0:$.domainServices)==null?void 0:H.inventory,{type:r,saleId:n=null,purchaseId:i=null,reason:a="",items:o,refundAmount:s,actualRefund:u=s,refundMethod:c="cash",creditNoteNumber:p=null,refundNote:l,refundReceivedDate:h,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 m=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),g=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),x=this.getCurrentRole(),v=!x||!m.includes(x),A=u>0&&this.context.config.requireApprovalForReturnRefund&&v,S=String(((k=this.context.session)==null?void 0:k.userId)||"").trim(),M=u>0&&await this.shouldTriggerFraudGuardForRefund(S),I=this.getFraudGuardPolicy();if(M&&I.action==="block")throw new Error("Fraud guard: repeat return pattern detected (refund blocked)");let F=M&&I.action==="require_approval",E=A||F?this.validateApproval(f,g,F?"Fraud guard return refund":"Return refund"):null,O=(L=this.context.domainServices)==null?void 0:L.uom,N=await O.getUomsMap(),Q=this.context.domainServices.transaction;if(e.saleId){let R=await this.getReturnsByReference("sale_return",e.saleId);if(R.length>0){let B=await this.calculateTotalReturnedQty(R,e.items.map(T=>T.productId));for(let T of e.items){let D=await this.getOriginalQuantity("sale",e.saleId,T.productId),X=D-(B.get(T.productId)||0);if(T.quantity>X)throw new Error(`Produk ${T.productId} hanya bisa diretur ${X} lagi (sudah diretur ${B.get(T.productId)||0}/${D})`)}}}if(e.purchaseId){let R=await this.getReturnsByReference("purchase_return",e.purchaseId);if(R.length>0){let B=await this.calculateTotalReturnedQty(R,e.items.map(T=>T.productId));for(let T of e.items){let D=await this.getOriginalQuantity("purchase",e.purchaseId,T.productId),X=D-(B.get(T.productId)||0);if(T.quantity>X)throw new Error(`Produk ${T.productId} hanya bisa diretur ${X} lagi (sudah diretur ${B.get(T.productId)||0}/${D})`)}}}let _=await this.dbAdapter.transaction(async R=>{var te,J,Y;let B=new Date().toISOString(),T=C(),D=[],X={id:T,type:r,saleId:n,purchaseId:i,reason:b||null,refundAmount:s,actualRefund:u,refundMethod:u>0?c:null,creditNoteNumber:p,refundNote:u<s?typeof l=="number"?l:s-u:null,refundReceivedDate:u>0?h||B:null,status:u===s?"completed":u>0?"partially_refunded":"no_refund",date:B,userId:((te=this.context.session)==null?void 0:te.userId)||"",version:1,lastModified:B,deleted:!1};await R.create(Ae,X),D.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,R);if(!pe)throw new Error(`Item not found in ${r==="sale_return"?"sale":"purchase"} ${n||i}`);let we=r==="sale_return"?pe.unitPrice:pe.unitCost,me=pe.uomId,We={id:C(),returnId:T,productId:be.productId,quantity:Ne,unitPrice:we,uomId:me,restock:se,restockNote:se?null:be.restockNote||"Rusak / tidak bisa dijual",version:1,lastModified:B,deleted:!1};if(await R.create(Re,We),D.push({type:"create",model:Re,record:We}),se){let Ye=O.convertQuantity(Ne,{conversionFactor:me&&((Y=N.get(me))==null?void 0:Y.conversionFactor)||1},{conversionFactor:1}),Xe=r==="sale_return"?+Ye:-Ye;await t.updateStock(be.productId,Xe,r,Ae,T,R)}}if(u>0)if((r==="sale_return"?"out":"in")==="in"){let se=await Q.recordCashIn({amount:u,method:c,data:{referenceType:r,referenceId:T,note:l}},R);D.push({type:"create",model:Z,record:se})}else{let se=await Q.recordCashOut({amount:u,method:c,data:{referenceType:r,referenceId:T,note:l}},R);D.push({type:"create",model:Z,record:se})}return E&&this.context.logActivity("ReturnRefundApproved",{returnId:T,approvedBy:E.approvedBy,approverRole:E.approverRole,reason:E.reason}),await this.emitFinanceProjection(X),{returnId:T,queued:!0,type:r,actualRefund:u,syncChanges:D}});for(let R of _.syncChanges)this.changeQueue.enqueue(R);return this.context.eventBus.emit("return:processed",{returnId:_.returnId,type:_.type,actualRefund:_.actualRefund}),this.context.logActivity("processReturn",{returnId:_.returnId,type:_.type,actualRefund:_.actualRefund}),{returnId:_.returnId,queued:_.queued}}async cancelReturn(e,t="Cancelled by user"){var A,S,M,I;let r=(S=(A=this.context)==null?void 0:A.domainServices)==null?void 0:S.inventory,n=(M=this.context.domainServices)==null?void 0:M.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(),h=!l||!c.includes(l),f=this.context.config.requireApprovalForReturnCancel&&h,y=String(((I=this.context.session)==null?void 0:I.userId)||"").trim(),b=await this.shouldTriggerFraudGuardForCancel(y),m=this.getFraudGuardPolicy();if(b&&m.action==="block")throw new Error("Fraud guard: repeat return cancellation pattern detected (cancel blocked)");let g=b&&m.action==="require_approval",x=f||g?this.validateApproval(s,p,g?"Fraud guard return cancellation":"Return cancellation"):null,v=await this.dbAdapter.transaction(async F=>{var Q;let E=await F.get(Ae,e);if(!E||E.deleted)throw new Error("Return not found or already deleted");let O=[],N=await F.query(Re,{filters:{returnId:e,deleted:!1}});for(let _ of N){if(_.restock){let $=n.convertQuantity(_.quantity,{conversionFactor:_.uomId&&((Q=i.get(_.uomId))==null?void 0:Q.conversionFactor)||1},{conversionFactor:1}),H=E.type==="sale_return"?-$:+$;await r.updateStock(_.productId,H,`${E.type}_cancelled`,Ae,e,F)}await F.update(Re,_.id,{deleted:!0,lastModified:new Date().toISOString()}),O.push({type:"delete",model:Re,record:{id:_.id}})}if(E.actualRefund>0)if((E.type==="sale_return"?"in":"out")==="in"){let $=await a.recordCashIn({amount:E.actualRefund,method:E.refundMethod||"cash",data:{referenceType:`${E.type}_cancelled`,referenceId:e,note:o}},F);O.push({type:"create",model:Z,record:$})}else{let $=await a.recordCashOut({amount:E.actualRefund,method:E.refundMethod||"cash",data:{referenceType:`${E.type}_cancelled`,referenceId:e,note:o}},F);O.push({type:"create",model:Z,record:$})}return await F.update(Ae,e,{deleted:!0,lastModified:new Date().toISOString()}),O.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:O}});for(let F of v.syncChanges)this.changeQueue.enqueue(F);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:Pe,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 rn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addReturnItem(e,t){let r=C(),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=C(),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 De="roles";var nn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addRole(e,t){let r=C(),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("AddRole",{id:r}),a}async updateRole(e,t,r){let n=await(r||this.dbAdapter).get(De,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(De,e,a);return this.changeQueue.enqueue({type:"update",model:De,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(De,{...e,filters:i})}async getRole(e,t){return(t||this.dbAdapter).get(De,e)}async deleteRole(e,t){return await(t||this.dbAdapter).delete(De,e),this.changeQueue.enqueue({type:"delete",model:De,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=C(),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("DuplicateRole",{originalId:e,newId:n}),o}};var ue="sales";var fe="receivables";var lt="inventory_lots";var tr=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=j(e),this.docNumberPolicy=new It(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t,r){var u,c,p;let n=(u=e.transactionCurrencyCode)!=null?u: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),h=Number(p.paidAmount||0),f=Math.max(0,l-h);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 u=this.context.config.customerCreditMaxOutstandingAmount;if(u!=null&&o+t.receivableAmount>u)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(mi({sale:e,tenantId:t,branchId:((a=this.context.config)==null?void 0:a.branchId)||void 0,scopedAccountMapping:this.runtimeOptions.saleAccountMapping}))}async emitSaleFinalizedSummary(e){var r,n,i,a,o,s,u,c,p,l;if(!this.runtimeOptions.saleFinalizedSink)return;let t={saleId:e.id,saleDate:e.date,customerId:e.customerId,userId:e.userId,total:e.total,finalTotal:e.finalTotal,transactionCurrencyCode:(r=e.transactionCurrencyCode)!=null?r:null,totalInBaseCurrency:(n=e.totalInBaseCurrency)!=null?n:null,finalTotalInBaseCurrency:(i=e.finalTotalInBaseCurrency)!=null?i:null,note:(a=e.note)!=null?a:null,tenantId:(s=(o=this.context.session)==null?void 0:o.tenantId)!=null?s:null,branchId:(c=(u=this.context.config)==null?void 0:u.branchId)!=null?c:null};try{await this.runtimeOptions.saleFinalizedSink(t)}catch(h){(l=(p=this.runtimeOptions.logger)==null?void 0:p.logError)==null||l.call(p,h,{message:"[ofpos] sale finalized sink failed",saleId:e.id})}}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,u=a?(await this.getDuplicateDocumentNumbers()).some(p=>p.docNo===a):!1,c=new Date().toISOString();return await this.dbAdapter.create(ie,{id:C(),tableName:ue,recordId:e,action:"reprint",changes:{actorId:r,reason:n,terminalId:t.terminalId||null,docNo:a,reprintCount:s,duplicateDocNoDetected:u},userId:r,timestamp:c}),u&&await this.dbAdapter.create(ie,{id:C(),tableName:ue,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:u}}async consumeInventoryLotsForSale(e,t){var b,m,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&&((m=i.get(t.uomId))==null?void 0:m.conversionFactor)||1,o=n.convertQuantity(r,{conversionFactor:a},{conversionFactor:1});if(!Number.isFinite(o)||o<=0)return[];let s=await e.query(lt,{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 u=Number.isFinite(Date.parse(t.saleDate))?Date.parse(t.saleDate):Date.now(),c=new Date().toISOString(),p=[],l=[],h=0;for(let x of s){if(this.isExpiredLot(x.expiryDate,u)){if(x.status!=="expired"){let A=await e.update(lt,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),h+=Number(x.remainingQuantity||0)}if(h<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||""),S=Date.parse(v.lastModified||"");if(f==="FIFO"){if(Number.isFinite(A)&&Number.isFinite(S)&&A!==S)return A-S}else{let M=x.expiryDate?Date.parse(x.expiryDate):Number.POSITIVE_INFINITY,I=v.expiryDate?Date.parse(v.expiryDate):Number.POSITIVE_INFINITY;if(Number.isFinite(M)&&Number.isFinite(I)&&M!==I)return M-I;if(Number.isFinite(M)!==Number.isFinite(I))return Number.isFinite(M)?-1:1}return Number.isFinite(A)&&Number.isFinite(S)&&A!==S?A-S: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),S=v-A,M=S<=0?"depleted":"active",I=await e.update(lt,x.id,{remainingQuantity:S,status:M,version:Number(x.version||0)+1,lastModified:c});p.push({id:I.id,remainingQuantity:Number(I.remainingQuantity||0),status:String(I.status||M),version:Number(I.version||0),lastModified:String(I.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=C(),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=C(),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,b,m,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(),u=(y=e.id)!=null?y:C(),c=((b=this.context.config)==null?void 0:b.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",e.date||s):null,p={id:u,userId:e.userId,customerId:e.customerId,sourceOrderId:e.sourceOrderId,status:"completed",date:e.date||s,total:0,discount:(m=e.discount)!=null?m: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((I,F)=>{var E;return I+((E=F.unitPrice)!=null?E:0)*F.quantity},0),A=Number(e.total),S=Number(e.discount),M=Number(e.finalTotal);p.total=Number.isFinite(A)&&A>=0?A:v,p.discount=Number.isFinite(S)&&S>=0?S:Math.max(0,v-p.total),p.finalTotal=Number.isFinite(M)&&M>=0?M:p.total+p.ppn+p.pph}if(Object.assign(p,this.resolveCurrencySnapshot(e,p.total,p.finalTotal)),await i.create(ue,p),l.push({type:"create",model:ue,record:p}),!t)return{sale:p,syncChanges:l};let h=t.map(v=>({id:C(),saleId:u,...v,version:1,lastModified:s,deleted:!1}));await i.bulkCreate(ge,h);for(let v of h)l.push({type:"create",model:ge,record:v});for(let v of h){let A=this.toBaseQuantity(v.quantity,v.uomId,a,o),S=await this.consumeInventoryLotsForSale(i,{saleId:p.id,saleDate:p.date,productId:v.productId,quantity:v.quantity,uomId:v.uomId});for(let M of S)l.push({type:"update",model:lt,record:M});await this.context.domainServices.inventory.updateStock(v.productId,-A,"sale",ue,p.id,i)}if(r)if(r.method!=="tempo"){let v=await this.context.domainServices.transaction.recordCashIn({method:r.method,data:{...r.data,referenceType:"sale",referenceId:u},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})}return{sale:p,items:h,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),await this.emitSaleFinalizedSummary(n.sale),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 u=[],c=await i.query(ge,{filters:{saleId:e}});for(let l of c){let h=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)u.push({type:"update",model:lt,record:y});await this.context.domainServices.inventory.updateStock(l.productId,-h,"sale",ue,e,i)}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);u.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 h=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);u.push({type:"create",model:fe,record:h})}return{saleId:e,syncChanges:u}});for(let i of r.syncChanges)this.changeQueue.enqueue(i);let n=await this.getSale(r.saleId);n&&(await this.emitFinanceProjection(n),await this.emitSaleFinalizedSummary(n)),this.context.eventBus.emit("sale:finalized",r.saleId)}async createSaleFromOrder(e,t){let r=await this.dbAdapter.transaction(async n=>{var v,A,S,M;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}}),u=new Date().toISOString(),c=C(),p=((A=this.context.config)==null?void 0:A.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",o.date||u):null,l=[],h=s.reduce((I,F)=>I+(F.unitPrice||0)*F.quantity,0),f=(S=o.ppn)!=null?S:0,y=(M=o.pph)!=null?M:0,b=h+f+y,m=this.resolveCurrencySnapshot(o,h,b),g={id:c,userId:o.userId,customerId:o.customerId,sourceOrderId:o.id,discountCode:o.discountCode||null,status:"completed",date:o.date,total:h,discount:0,ppn:f,pph:y,finalTotal:b,...m,note:p?this.docNumberPolicy.withNote(o.note,p):o.note,version:1,lastModified:u,deleted:!1};await n.create(ue,g),l.push({type:"create",model:ue,record:g});let x=s.map(I=>({id:C(),saleId:c,productId:I.productId,quantity:I.quantity,uomId:I.uomId,unitPrice:I.unitPrice,version:1,lastModified:u,deleted:!1}));await n.bulkCreate(ge,x);for(let I of x)l.push({type:"create",model:ge,record:I});if(await n.update(oe,e,{status:"completed",saleId:c,lastModified:u}),l.push({type:"update",model:oe,record:{id:e,status:"completed",saleId:c,lastModified:u}}),t.method!=="tempo"){let I=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:I})}else{let I=t.dueDate;await this.enforceTempoCustomerCreditPolicy(n,{customerId:g.customerId,receivableAmount:g.finalTotal,referenceId:g.id,dueDate:I,nowIso:u});let F=await this.context.domainServices.receivable.addReceivable({saleId:g.id,customerId:g.customerId,amount:g.finalTotal,dueDate:I,status:"unpaid",paidAmount:0,date:u},n);l.push({type:"create",model:fe,record:F})}for(let I of x){let F=this.toBaseQuantity(I.quantity,I.uomId,i,a),E=await this.consumeInventoryLotsForSale(n,{saleId:c,saleDate:g.date,productId:I.productId,quantity:I.quantity,uomId:I.uomId});for(let O of E)l.push({type:"update",model:lt,record:O});await this.context.domainServices.inventory.updateStock(I.productId,-F,"sale",ue,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),await this.emitSaleFinalizedSummary(r.sale),{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 u=>{var S,M,I,F;let c=n.customerId?await this.context.domainServices.customer.getCustomer(n.customerId,u):void 0,p=await r.calculateOrderTotal(n.items,n.discountCode,(c==null?void 0:c.groupId)||void 0),l=await r.calculatePPN(p.subTotal),h=await r.calculatePPH(p.subTotal),f=p.total+l+h,y=this.resolveCurrencySnapshot(n,p.subTotal,f),b=new Date().toISOString(),m=C(),g=((S=this.context.config)==null?void 0:S.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",b):null,x={id:m,userId:((I=(M=this.context)==null?void 0:M.session)==null?void 0:I.userId)||"",customerId:n.customerId||null,sourceOrderId:null,discountCode:n.discountCode||null,status:"completed",date:b,total:p.subTotal,discount:p.discount,ppn:l,pph:h,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(E=>({id:C(),saleId:m,productId:E.productId,quantity:E.quantity,uomId:E.uomId||null,unitPrice:E.unitPrice,version:1,lastModified:b,deleted:!1})),A=[];await u.create(ue,x),await u.bulkCreate(ge,v),A.push({type:"create",model:ue,record:x});for(let E of v)A.push({type:"create",model:ge,record:E});if(t.method!=="tempo"){let E=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:m},amount:x.finalTotal},u);A.push({type:"create",model:Z,record:E})}else{let E=t.dueDate;await this.enforceTempoCustomerCreditPolicy(u,{customerId:x.customerId,receivableAmount:x.finalTotal,referenceId:x.id,dueDate:E,nowIso:b});let O=await this.context.domainServices.receivable.addReceivable({saleId:x.id,customerId:x.customerId,amount:x.finalTotal,dueDate:E,status:"unpaid",paidAmount:0,date:b},u);A.push({type:"create",model:fe,record:O})}for(let E of v){let O=typeof E.uomId=="string"&&((F=a.get(E.uomId))==null?void 0:F.conversionFactor)||1,N=i.convertQuantity(E.quantity,{conversionFactor:O},{conversionFactor:1}),Q=await this.consumeInventoryLotsForSale(u,{saleId:m,saleDate:x.date,productId:E.productId,quantity:E.quantity,uomId:E.uomId});for(let _ of Q)A.push({type:"update",model:lt,record:_});await this.context.domainServices.inventory.updateStock(E.productId,-N,"sale",ue,x.id,u)}return{sale:x,items:v,syncChanges:A}});await this.emitFinanceProjection(o.sale);for(let u of o.syncChanges)this.changeQueue.enqueue(u);this.context.eventBus.emit("sale:finalized",o.sale.id),await this.emitSaleFinalizedSummary(o.sale);try{await this.context.domainServices.cart.deleteCart(e)}catch(u){this.context.logError(u,{message:`Sale created but failed to delete cart ${e}`})}return{sale:o.sale,items:o.items}}};var an=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addSaleItem(e,t){let r=C(),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=C(),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 rr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async computeCashMovementsForShiftWindow(e,t){var i;let r=(i=t.closedAt)!=null?i:new Date(new Date().getTime()+1e3).toISOString();return(await e.query(Z,{filters:{and:[{field:"date",operator:">=",value:t.openedAt},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]},limit:5e3})).reduce((a,o)=>(o.direction==="in"&&["sale","receivable_payment"].includes(o.referenceType)&&(a.cashIn+=Number(o.amount||0)),o.direction==="out"&&["sale_return","expense"].includes(o.referenceType)&&(a.cashOut+=Number(o.amount||0)),a),{cashIn:0,cashOut:0})}async addShift(e,t){let r=C(),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=C(),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 u;if(await this.getActiveShift(e))throw new Error("Kasir ini masih memiliki shift yang aktif");let a=new Date().toISOString(),o=C(),s={id:o,cashierId:e,cashierName:((u=this.context.session)==null?void 0:u.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 b,m;let o=await a.get(le,e);if(!o||o.deleted||o.status!=="open")throw new Error("Shift tidak ditemukan atau sudah ditutup");let{cashIn:s,cashOut:u}=await this.computeCashMovementsForShiftWindow(a,{openedAt:o.openedAt}),c=s-u,p=o.startingCash+c,l=t-p,h=Math.abs(l);if((b=this.context.config)!=null&&b.requireShiftCloseApprovalOnDifference){let g=(m=this.context.config)==null?void 0:m.shiftCloseDifferenceApprovalThreshold,x=typeof g=="number"&&g>=0?g:0;if(h>x){let v=String((i==null?void 0:i.approvedBy)||"").trim(),A=String((i==null?void 0:i.reason)||"").trim();if(!v||!A)throw new Error(`Shift close approval is required when cash difference exceeds ${x}`)}}let f=i?`[CLOSE_APPROVED_BY=${i.approvedBy}] [CLOSE_APPROVAL_REASON=${i.reason}]`:"",y={closedAt:new Date().toISOString(),endingCash:t,systemCash:p,cashDifference:l,status:"closed",note:[o.note||"",n||"",f].filter(Boolean).join(" | ")||null,lastModified:new Date().toISOString()};return await a.update(le,e,y),this.changeQueue.enqueue({type:"update",model:le,id:e,record:y}),this.context.eventBus.emit("shift:closed",{shiftId:e,cashierId:o.cashierId,systemEndingCash:p,physicalEndingCash:t,difference:l}),i&&this.context.logActivity("CloseShiftApproval",{shiftId:e,cashierId:o.cashierId,approvedBy:i.approvedBy,reason:i.reason,cashDifference:l},a),{...o,...y}})}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 h;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(),u=C(),c=t.startingCash!=null?t.startingCash:(h=a.endingCash)!=null?h:a.startingCash,p=[a.note||"",`[REOPEN_FROM=${e}]`,`[APPROVED_BY=${r}]`,`[REASON=${n}]`].filter(Boolean),l={id:u,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:u,cashierId:a.cashierId,approvedBy:r,reason:n},i),this.context.eventBus.emit("shift:reopened",{fromShiftId:e,reopenedShiftId:u,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");return this.computeCashMovementsForShiftWindow(this.dbAdapter,{openedAt:t.openedAt,closedAt:t.closedAt})}async getDailyReport(e){var l,h,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}]}}),u=((l=s==null?void 0:s[0])==null?void 0:l.salesCash)||0,c=((h=s==null?void 0:s[0])==null?void 0:h.returnsCash)||0,p=((f=s==null?void 0:s[0])==null?void 0:f.expenses)||0;return{date:e,totalSalesCash:u,totalReturnsCash:c,totalExpenses:p,netCashMovement:u-c-p,startingCash:r,systemEndingCash:i,physicalEndingCash:n,cashDifference:n-i,shifts:t}}};var Ee="tax_rates";var on=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addTaxRate(e,t){let r=C(),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=C(),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 nr=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=j(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(bi({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:C(),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 u,c;let n=t==="cash_in"?"in":"out",i=String(((u=r==null?void 0:r.data)==null?void 0:u.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=C(),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=C(),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 h=await this.getIdempotentTransaction("cash_in",n,t);if(h)return this.assertIdempotentReplayConsistency(h,"cash_in",e),h}let i=this.getActorId(e),a=C(),o=t||this.dbAdapter,s=1,u=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:u,deleted:!1};try{let h=await o.create(Z,c);return n&&await this.saveIdempotencyMarker("cash_in",n,h.id,o),t||this.changeQueue.enqueue({type:"create",model:Z,record:h}),this.context.logActivity("RecordCashIn",{method:e.method,amount:e.amount,id:h.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:h.id,date:h.date,amount:h.amount,direction:"in",metadata:h.metadata}),h}catch(h){throw r.logError("Error recording cash in",{id:a,method:e.method,amount:e.amount,error:h}),h}}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 h=await this.getIdempotentTransaction("cash_out",n,t);if(h)return this.assertIdempotentReplayConsistency(h,"cash_out",e),h}let i=this.getActorId(e),a=C(),o=t||this.dbAdapter,s=1,u=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:u,deleted:!1};try{let h=await o.create(Z,c);return n&&await this.saveIdempotencyMarker("cash_out",n,h.id,o),t||this.changeQueue.enqueue({type:"create",model:Z,record:h}),this.context.logActivity("RecordCashOut",{method:e.method,amount:e.amount,id:h.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:h.id,date:h.date,amount:h.amount,direction:"out",metadata:h.metadata}),h}catch(h){throw r.logError("Error recording cash out",{id:a,method:e.method,amount:e.amount,error:h}),h}}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 Lo(d,e){return d*e}function Qo(d,e){return e!==0?d/e:NaN}var ir=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addUom(e,t){let r=C(),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=C(),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=Lo(e,t.conversionFactor);return Qo(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 He="users";var sn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addUser(e,t){let r=C(),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("AddUser",{id:r}),a}async updateUser(e,t,r){let n=await(r||this.dbAdapter).get(He,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(He,e,a);return this.changeQueue.enqueue({type:"update",model:He,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(He,{...e,filters:i})}async getUser(e,t){return(t||this.dbAdapter).get(He,e)}async deleteUser(e,t){return await(t||this.dbAdapter).delete(He,e),this.changeQueue.enqueue({type:"delete",model:He,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=C(),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("DuplicateUser",{originalId:e,newId:n}),o}};var Ve="suppliers";var ar=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addSupplier(e,t){let r=C(),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("AddSupplier",{id:r}),a}async updateSupplier(e,t,r){let n=await(r||this.dbAdapter).get(Ve,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(Ve,e,a);return this.changeQueue.enqueue({type:"update",model:Ve,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(Ve,{...e,filters:i})}async getSupplier(e,t){return(t||this.dbAdapter).get(Ve,e)}async deleteSupplier(e,t){return await(t||this.dbAdapter).delete(Ve,e),this.changeQueue.enqueue({type:"delete",model:Ve,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=C(),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("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(Ve,{...t,filters:a})}};var _e="purchase_orders";var or=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addPurchaseOrder(e,t){let r=C(),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=C(),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 je="purchase_order_items";var cn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addPurchaseOrderItem(e,t){let r=C(),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("AddPurchaseOrderItem",{id:r}),a}async updatePurchaseOrderItem(e,t,r){let n=await(r||this.dbAdapter).get(je,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(je,e,a);return this.changeQueue.enqueue({type:"update",model:je,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(je,{...e,filters:i})}async getPurchaseOrderItem(e,t){return(t||this.dbAdapter).get(je,e)}async deletePurchaseOrderItem(e,t){return await(t||this.dbAdapter).delete(je,e),this.changeQueue.enqueue({type:"delete",model:je,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=C(),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("DuplicatePurchaseOrderItem",{originalId:e,newId:n}),o}};var Se="purchases";var ye="payables";var $e="financial_settings";var sr=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=j(e),this.docNumberPolicy=new It(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t){var o,s,u;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:(u=e.exchangeRateSource)!=null?u:"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(hi({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($e,{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),u=Number(o.unitCost);if(!Number.isFinite(s)||!Number.isFinite(u)||s<=0)continue;let c=i.get(o.productId)||{quantity:0,totalCost:0};c.quantity+=s,c.totalCost+=s*u,i.set(o.productId,c)}for(let[o,s]of i.entries()){let u=await e.get(ce,o);if(!u||u.deleted)continue;let c=s.totalCost/s.quantity,p=await r.getStock(o),l=u.cost;if(n==="AVERAGE"){let y=Math.max(0,Number(p)||0),b=y+s.quantity;b>0?l=(u.cost*y+s.totalCost)/b:l=c}else(Number(p)||0)<=0&&(l=c);if(!Number.isFinite(l)||l===u.cost)continue;let h=new Date().toISOString(),f=await e.update(ce,o,{cost:l,version:u.version+1,lastModified:h});this.changeQueue.enqueue({type:"update",model:ce,record:f})}}async addPurchase(e,t){var u;let r=C(),n=new Date().toISOString(),i=((u=this.context.config)==null?void 0:u.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=C(),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 m=await this.dbAdapter.transaction(async g=>this.finalizePurchase(e,t,g));return this.context.eventBus.emit("purchase:finalized",e),m}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(Pe,{filters:{and:[{field:"purchaseId",value:e},{field:"deleted",value:!1}]}}),u=s.reduce((m,g)=>m+g.unitCost*g.quantity,0),c=Date.now(),p=new Date().toISOString(),l=this.resolveCurrencySnapshot(o,u);await r.update(Se,e,{total:u,...l,version:c,lastModified:p});let h={...o,total:u,...l,version:c,lastModified:p};await this.applyCostingPolicy(r,s.map(m=>({productId:m.productId,quantity:this.toBaseQuantity(m.quantity,m.uomId,i,a),unitCost:this.toBaseUnitCost(m.unitCost,m.uomId,i,a)})));for(let m of s)await n.updateStock(m.productId,this.toBaseQuantity(m.quantity,m.uomId,i,a),"purchase",Se,e,r);return await this.context.domainServices.priceHistory.recordPriceHistory(s.map(m=>({productId:m.productId,unitCost:this.toBaseUnitCost(m.unitCost,m.uomId,i,a),supplierId:o.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:h.supplierId,purchaseId:h.id,amount:h.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:h.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:h.total,method:t.method,data:{referenceType:"purchase",referenceId:h.id,...t.data||{}}},r),this.changeQueue.enqueue({type:"update",model:Se,record:h}),await this.emitFinanceProjection(h,t.method),{purchase:h,queued:!0}}async receivePurchaseFromPO(e,t,r){var O,N,Q,_,$,H;if(!r){let k=await this.dbAdapter.transaction(async L=>this.receivePurchaseFromPO(e,t,L));return this.context.eventBus.emit("purchase:finalized",k.purchase.id),k}let n=(N=(O=this.context)==null?void 0:O.domainServices)==null?void 0:N.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(je,{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(k=>k.id),p=new Map;if(c.length>0){let k=await r.query(Pe,{filters:{and:[{field:"deleted",value:!1},{or:c.map(L=>({field:"purchaseId",value:L}))}]}});for(let L of k)L.purchaseOrderItemId&&p.set(L.purchaseOrderItemId,(p.get(L.purchaseOrderItemId)||0)+Number(L.quantity||0))}let l=new Map(s.map(k=>[k.id,k])),h=new Map;for(let k of s){let L=h.get(k.productId)||[];L.push(k),h.set(k.productId,L)}let f=[],y=Array.isArray(t.receivedItems)?t.receivedItems:null;if(y&&y.length>0){let k=((_=this.context.config)==null?void 0:_.requireLotExpiryForPurchaseReceiving)===!0;for(let L of y){let B=L.purchaseOrderItemId?l.get(L.purchaseOrderItemId):void 0;if(!B&&L.productId){let se=h.get(L.productId)||[];if(se.length===1)B=se[0];else if(se.length>1)throw new Error(`Ambiguous productId ${L.productId}: provide purchaseOrderItemId for partial receiving`)}if(!B)throw new Error("Invalid partial receiving payload: source purchase order item not found");let T=Number(L.receivedQuantity);if(!Number.isFinite(T)||T<=0)throw new Error("Invalid partial receiving payload: receivedQuantity must be > 0");let D=p.get(B.id)||0,X=f.filter(se=>se.sourceOrderItem.id===B.id).reduce((se,Ne)=>se+Ne.quantity,0),te=Number(B.quantity)-D-X;if(T>te)throw new Error(`Partial receiving exceeds remaining quantity for PO item ${B.id}`);let J=L.unitCost!=null?Number(L.unitCost):Number(B.unitCost);if(!Number.isFinite(J)||J<0)throw new Error("Invalid partial receiving payload: unitCost must be >= 0");let Y=L.serialNumber!=null?String(L.serialNumber).trim():"";if(Y&&T!==1)throw new Error("Serial-number receiving currently requires receivedQuantity = 1");f.push({sourceOrderItem:B,quantity:T,unitCost:J,uomId:L.uomId!==void 0?L.uomId:B.uomId,lotNumber:L.lotNumber!=null&&String(L.lotNumber).trim()||null,serialNumber:Y||null,expiryDate:L.expiryDate!=null&&String(L.expiryDate).trim()||null,note:L.note!=null?String(L.note):null});let be=f[f.length-1];if(k){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((($=this.context.config)==null?void 0:$.requireLotExpiryForPurchaseReceiving)===!0)throw new Error("Lot policy violation: receivedItems with lotNumber and expiryDate are required when requireLotExpiryForPurchaseReceiving=true");for(let k of s){let L=p.get(k.id)||0,R=Number(k.quantity)-L;R<=0||f.push({sourceOrderItem:k,quantity:R,unitCost:Number(k.unitCost),uomId:k.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((k,L)=>k+L.unitCost*L.quantity,0),m=C(),g=new Date().toISOString(),x=((H=this.context.config)==null?void 0:H.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",o.date||g):null,v={id:m,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 k of f){let L=C(),R={id:L,purchaseId:m,purchaseOrderItemId:k.sourceOrderItem.id,productId:k.sourceOrderItem.productId,quantity:k.quantity,uomId:k.uomId,unitCost:k.unitCost,version:1,lastModified:g,deleted:!1};if(await r.create(Pe,R),this.changeQueue.enqueue({type:"create",model:Pe,record:R}),k.lotNumber||k.serialNumber||k.expiryDate){let B=this.toBaseQuantity(k.quantity,k.uomId,i,a),T={id:C(),productId:k.sourceOrderItem.productId,purchaseId:m,purchaseItemId:L,purchaseOrderId:e,purchaseOrderItemId:k.sourceOrderItem.id,lotNumber:k.lotNumber,serialNumber:k.serialNumber,expiryDate:k.expiryDate,quantity:B,remainingQuantity:B,status:"active",note:k.note,version:1,lastModified:g,deleted:!1};await r.create(lt,T),this.changeQueue.enqueue({type:"create",model:lt,record:T})}}let A=new Map(p);for(let k of f)A.set(k.sourceOrderItem.id,(A.get(k.sourceOrderItem.id)||0)+k.quantity);let M=s.every(k=>(A.get(k.id)||0)>=Number(k.quantity))?"received":"partially_received",I=Date.now(),F=new Date().toISOString();await r.update(_e,e,{status:M,version:I,lastModified:F}),this.changeQueue.enqueue({type:"update",model:_e,record:{id:e,status:M,version:I,lastModified:F}});let E=f.filter(k=>Number(k.unitCost)!==Number(k.sourceOrderItem.unitCost)).map(k=>({purchaseOrderItemId:k.sourceOrderItem.id,productId:k.sourceOrderItem.productId,orderedUnitCost:k.sourceOrderItem.unitCost,receivedUnitCost:k.unitCost,quantity:k.quantity,varianceAmount:(k.unitCost-k.sourceOrderItem.unitCost)*k.quantity}));E.length>0&&await this.context.logActivity("PO_PRICE_VARIANCE_DETECTED",{purchaseOrderId:e,purchaseId:m,entries:E},r),await this.applyCostingPolicy(r,f.map(k=>({productId:k.sourceOrderItem.productId,quantity:this.toBaseQuantity(k.quantity,k.uomId,i,a),unitCost:this.toBaseUnitCost(k.unitCost,k.uomId,i,a)})));for(let k of f)await n.updateStock(k.sourceOrderItem.productId,this.toBaseQuantity(k.quantity,k.uomId,i,a),"purchase",Se,m,r);return await this.context.domainServices.priceHistory.recordPriceHistory(f.map(k=>({productId:k.sourceOrderItem.productId,unitCost:this.toBaseUnitCost(k.unitCost,k.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((u,c)=>({...u,[c.id]:c}),{}),i;try{i=await this.dbAdapter.transaction(async u=>{var g,x;let c=new Date().toISOString(),p=C(),l=((g=this.context.config)==null?void 0:g.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",c):null,h=[],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 u.create(Se,y),h.push({type:"create",model:Se,record:y});let b=e.items.map(v=>({id:C(),purchaseId:p,purchaseOrderItemId:null,productId:v.productId,quantity:v.quantity,uomId:v.uomId||null,unitCost:v.unitCost,version:1,lastModified:c,deleted:!1}));await u.bulkCreate(Pe,b);for(let v of b)h.push({type:"create",model:Pe,record:v});await this.applyCostingPolicy(u,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,u)}let m=[];for(let v of b){let A=typeof v.uomId=="string"?n[v.uomId].conversionFactor:1;m.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(m,u),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()},u);h.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||{}}},u);h.push({type:"create",model:Z,record:v})}return{purchase:y,items:b,purchaseId:p,syncChanges:h}})}catch(u){throw t.clearStockCache(),u}for(let u of i.syncChanges)this.changeQueue.enqueue(u);return await this.emitFinanceProjection(i.purchase,e.paymentMethod),this.context.eventBus.emit("purchase:finalized",i.purchaseId),{purchase:i.purchase,items:i.items}}};var un=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addPurchaseItem(e,t){let r=C(),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("AddPurchaseItem",{id:r}),a}async updatePurchaseItem(e,t,r){let n=await(r||this.dbAdapter).get(Pe,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(Pe,e,a);return this.changeQueue.enqueue({type:"update",model:Pe,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(Pe,{...e,filters:i})}async getPurchaseItem(e,t){return(t||this.dbAdapter).get(Pe,e)}async deletePurchaseItem(e,t){return await(t||this.dbAdapter).delete(Pe,e),this.changeQueue.enqueue({type:"delete",model:Pe,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=C(),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("DuplicatePurchaseItem",{originalId:e,newId:n}),o}};var Oe="inventory_logs";function _t(d){return{all:d=d||new Map,on:function(e,t){var r=d.get(e);r?r.push(t):d.set(e,[t])},off:function(e,t){var r=d.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):d.set(e,[]))},emit:function(e,t){var r=d.get(e);r&&r.slice().map(function(n){n(t)}),(r=d.get("*"))&&r.slice().map(function(n){n(e,t)})}}}var qe=_t();var cr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addInventoryLog(e,t){let r=C(),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=C(),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),qe.emit("stock:changed",{productId:e,delta:0})}};var Ke="price_histories";var ur=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addPriceHistory(e,t){let r=C(),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("AddPriceHistory",{id:r}),a}async updatePriceHistory(e,t,r){let n=await(r||this.dbAdapter).get(Ke,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(Ke,e,a);return this.changeQueue.enqueue({type:"update",model:Ke,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(Ke,{...e,filters:i})}async getPriceHistory(e,t){return(t||this.dbAdapter).get(Ke,e)}async deletePriceHistory(e,t){return await(t||this.dbAdapter).delete(Ke,e),this.changeQueue.enqueue({type:"delete",model:Ke,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=C(),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("DuplicatePriceHistory",{originalId:e,newId:n}),o}async recordPriceHistory(e,t){var n;let r=[];for(let i of e){let a={id:C(),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(Ke,a);this.context.logActivity("RecordPriceHistory",{productId:i.productId,unitCost:i.unitCost}),r.push(o)}return r}};var Ce="stock_opnames";var Be="stock_opname_items";var dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addStockOpname(e,t){let r=C(),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=C(),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(Be,{filters:{stockOpnameId:e,deleted:!1}});for(let u of i)u.difference!==0&&await r.updateStock(u.productId,u.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 dn=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addStockOpnameItem(e,t){let r=C(),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("AddStockOpnameItem",{id:r}),a}async updateStockOpnameItem(e,t,r){let n=await(r||this.dbAdapter).get(Be,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(Be,e,a);return this.changeQueue.enqueue({type:"update",model:Be,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(Be,{...e,filters:i})}async getStockOpnameItem(e,t){return(t||this.dbAdapter).get(Be,e)}async deleteStockOpnameItem(e,t){return await(t||this.dbAdapter).delete(Be,e),this.changeQueue.enqueue({type:"delete",model:Be,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=C(),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("DuplicateStockOpnameItem",{originalId:e,newId:n}),o}};var Ge="stock_adjustments";var lr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addStockAdjustment(e,t){let r=async n=>{var c;let i=C(),a=new Date().toISOString(),o={id:i,...e,version:1,lastModified:a,deleted:!1},s=await n.create(Ge,o),u=(c=this.context.domainServices)==null?void 0:c.inventory;return u&&Number(e.change)!==0&&await u.updateStock(e.productId,Number(e.change),e.reasonType||"stock_adjustment",Ge,i,n),this.changeQueue.enqueue({type:"create",model:Ge,record:s}),this.context.logActivity("AddStockAdjustment",{id:i}),s};return t?r(t):this.dbAdapter.transaction(r)}async updateStockAdjustment(e,t,r){let n=await(r||this.dbAdapter).get(Ge,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(Ge,e,a);return this.changeQueue.enqueue({type:"update",model:Ge,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(Ge,{...e,filters:i})}async getStockAdjustment(e,t){return(t||this.dbAdapter).get(Ge,e)}async deleteStockAdjustment(e,t){return await(t||this.dbAdapter).delete(Ge,e),this.changeQueue.enqueue({type:"delete",model:Ge,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=C(),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("DuplicateStockAdjustment",{originalId:e,newId:n}),o}};var it="report_schedules";var pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addReportSchedule(e,t){let r=C(),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("AddReportSchedule",{id:r}),a}async updateReportSchedule(e,t,r){let n=await(r||this.dbAdapter).get(it,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(it,e,a);return this.changeQueue.enqueue({type:"update",model:it,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(it,{...e,filters:i})}async getReportSchedule(e,t){return(t||this.dbAdapter).get(it,e)}async deleteReportSchedule(e,t){return await(t||this.dbAdapter).delete(it,e),this.changeQueue.enqueue({type:"delete",model:it,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=C(),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("DuplicateReportSchedule",{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=j(e)}async addFinancialSetting(e,t){let r=C(),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("AddFinancialSetting",{id:r}),a}async updateFinancialSetting(e,t,r){let n=await(r||this.dbAdapter).get($e,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($e,e,a);return this.changeQueue.enqueue({type:"update",model:$e,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($e,{...e,filters:i})}async getFinancialSetting(e,t){return(t||this.dbAdapter).get($e,e)}async deleteFinancialSetting(e,t){return await(t||this.dbAdapter).delete($e,e),this.changeQueue.enqueue({type:"delete",model:$e,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=C(),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("DuplicateFinancialSetting",{originalId:e,newId:n}),o}};var at="expenses";var hr=class{constructor(e,t={}){this.context=e;this._runtimeOptions=t;var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=j(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(gi({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=C(),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}),await this.emitFinanceProjection(a),this.context.logActivity("AddExpense",{id:r}),a}async updateExpense(e,t,r){let n=await(r||this.dbAdapter).get(at,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(at,e,a);return this.changeQueue.enqueue({type:"update",model:at,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(at,{...e,filters:i})}async getExpense(e,t){return(t||this.dbAdapter).get(at,e)}async deleteExpense(e,t){return await(t||this.dbAdapter).delete(at,e),this.changeQueue.enqueue({type:"delete",model:at,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=C(),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("DuplicateExpense",{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=j(e)}async addReceivable(e,t){let r=C(),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=C(),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 gr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=j(e)}async addPayable(e,t){let r=C(),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=C(),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 Le="settlements";var yr=class{constructor(e,t={}){this.context=e;this.runtimeOptions=t;var r;this.dbAdapter=(r=e.registry)==null?void 0:r.dbAdapter,this.changeQueue=j(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(yi({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=C(),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("AddSettlement",{id:r}),a}async updateSettlement(e,t,r){let n=await(r||this.dbAdapter).get(Le,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(Le,e,a);return this.changeQueue.enqueue({type:"update",model:Le,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(Le,{...e,filters:i})}async getSettlement(e,t){return(t||this.dbAdapter).get(Le,e)}async deleteSettlement(e,t){return await(t||this.dbAdapter).delete(Le,e),this.changeQueue.enqueue({type:"delete",model:Le,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=C(),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("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 u=>{if(n){let l=await u.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 h=l[0].changes||{},f=String(h.settlementId||"").trim();if(f){let y=await u.get(Le,f);if(y)return y}}}if(e.receivableId){let l=await u.get(fe,e.receivableId);if(!l||l.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let h=l.amount-l.paidAmount;if(e.amount>h)throw new Error("Settlement amount exceeds remaining receivable amount")}if(e.payableId){let l=await u.get(ye,e.payableId);if(!l||l.deleted)throw new Error(`Payable ${e.payableId} not found`);let h=l.amount-l.paidAmount;if(e.amount>h)throw new Error("Settlement amount exceeds remaining payable amount")}let c={id:C(),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 u.create(Le,c);if(e.receivableId){let l=await u.get(fe,e.receivableId);if(!l||l.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let h=l.paidAmount+e.amount,f={...l,paidAmount:h,status:h>=l.amount?"paid":"partial",version:Date.now(),lastModified:r};await u.update(fe,f.id,f)}if(e.payableId){let l=await u.get(ye,e.payableId);if(!l||l.deleted)throw new Error(`Payable ${e.payableId} not found`);let h=l.paidAmount+e.amount,f={...l,paidAmount:h,status:h>=l.amount?"paid":"partial",version:Date.now(),lastModified:r};await u.update(ye,f.id,f)}return n&&await u.create(ie,{id:C(),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:Le,record:o}),e.receivableId){let u=await this.dbAdapter.get(fe,e.receivableId);u&&this.changeQueue.enqueue({type:"update",model:fe,record:u})}if(e.payableId){let u=await this.dbAdapter.get(ye,e.payableId);u&&this.changeQueue.enqueue({type:"update",model:ye,record:u})}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 br=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=j(this.context),qe.on("stock:changed",this.onStockChanged),qe.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 h=(p=this.context.domainServices)==null?void 0:p.bom;if(h&&(await h.getBomsByParentItemId(e)).length>0){let y=await h.expandBom(e),b=Math.abs(t);for(let m of y){let g=m.quantity*b;if(await this.getStock(m.componentItemId)<g)throw new Error(`Insufficient component ${m.componentItemId}`)}for(let m of y)await this.updateStock(m.componentItemId,-m.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 u={id:C(),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,u),this.changeQueue.enqueue({type:"create",model:Oe,record:u});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`),qe.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){this.stockCache.size===0&&await this.rebuildStockCache();let r=[];for(let[s,u]of this.stockCache.entries())u<e&&r.push({productId:s,stock:u});r.sort((s,u)=>s.stock-u.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 zi={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"}}},Vi={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 Uo=[{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
6
  referenceType | Arah Stok | Arah Kas | Catatan
3
7
  -----------------+----------------+----------------------+-----------------------
4
8
  sale | - (out) | + (in) | Penjualan
@@ -13,6 +17,6 @@ referenceType untuk inventory_logs:
13
17
  'reason': 'opname_adjustment'
14
18
  'referenceType': 'stock_opname'
15
19
  '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"}]}],Fo=[{name:"branchId",type:"string",isOptional:!0,isIndexed:!0},{name:"tenantId",type:"string",isOptional:!0,isIndexed:!0}];function ko(u){let e=[...u.columns];for(let t of Fo)e.some(r=>r.name===t.name)||e.push({...t});return{...u,columns:e}}var vt=To.map(ko),Bo=Object.freeze(vt.map(u=>u.name));for(let[u,e]of Object.entries(Qi)){let t=vt.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(Ui)){let t=vt.find(r=>r.name===u);t.polymorphic=e}var un=1,dn=[1,0];function Mo(){return{currentVersion:1,compatibleServerVersions:[...dn]}}function gi(u,e){return e.includes(u)}var yr=(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 br=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 vt.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=vt.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=yr(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 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(Ue,{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 qo=Math.pow(10,8)*24*60*60*1e3,i0=-qo;var Lo=3600;var Hi=Lo*24,a0=Hi*7,No=Hi*365.2425,Qo=No/12,o0=Qo*3,yi=Symbol.for("constructDateFrom");function ln(u,e){return typeof u=="function"?u(e):u&&typeof u=="object"&&yi in u?u[yi](e):u instanceof Date?new u.constructor(e):new Date(e)}function Mt(u,e){return ln(e||u,u)}function ji(u,e,t){let r=Mt(u,t==null?void 0:t.in);return isNaN(e)?ln((t==null?void 0:t.in)||u,NaN):(e&&r.setDate(r.getDate()+e),r)}function pn(u,e){let t=Mt(u,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function xr(u,e){let t=Mt(u,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function $i(u,e,t){return ji(u,-e,t)}var Ar=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=pn(new Date).toISOString(),t=xr(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=xr(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=pn(new Date).toISOString(),r=xr(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=$i(new Date,t),n=pn(r).toISOString(),i=xr(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(Ee,{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(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(b=>b.id).filter(Boolean),d=s.length>0?await this.dbAdapter.query(Be,{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(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(c=>c.id).filter(Boolean),s=o.length>0?await this.dbAdapter.query(Be,{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(Re,{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(Re,{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 qt=class qt{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(qt.KEY);return e?JSON.parse(e):{}}async saveAllCarts(e){await this.storage.setItem(qt.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(qt.KEY)}};qt.KEY="carts";var Sr=qt;var Ir=class{constructor(e){this.context=e;this.cartStore=new Sr(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 Lt=null,Nt=null,Pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,qe.on("taxRateChanged",this.clearTaxRateCache)}async getPpnRate(){if(Lt!==null)return Lt;let e=await this.dbAdapter.query(we,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});return Lt=e.length>0?e[0].rate:0,Lt}async getPphRate(){if(Nt!==null)return Nt;let e=await this.dbAdapter.query(we,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});return Nt=e.length>0?e[0].rate:0,Nt}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(we,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(we,n.id))),await t.create(we,{key:"ppn",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),qe.emit("taxRateChanged"),Lt=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(we,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(we,n.id))),await t.create(we,{key:"pph",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),qe.emit("taxRateChanged"),Nt=e}clearTaxRateCache(){Lt=null,Nt=null}};var mn=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 Dr=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,Le,pe;this.context.domainServices=this,this.bom=(n=t.bomService)!=null?n:new Yr(this.context),this.category=(i=t.categoryService)!=null?i:new Ht(this.context),this.customer=(a=t.customerService)!=null?a:new jt(this.context),this.customerGroup=(o=t.customerGroupService)!=null?o:new $t(this.context),this.history=(s=t.historyService)!=null?s:new Vt(this.context),this.order=(d=t.orderService)!=null?d:new zt(this.context),this.orderItem=(c=t.orderItemService)!=null?c:new Jr(this.context),this.priceTier=(p=t.priceTierService)!=null?p:new Kt(this.context),this.product=(l=t.productService)!=null?l:new Gt(this.context),this.promotion=(m=t.promotionService)!=null?m:new Wt(this.context),this.returnService=(f=t.returnService)!=null?f:new Jt(this.context,r),this.returnItem=(y=t.returnItemService)!=null?y:new en(this.context),this.role=(b=t.roleService)!=null?b:new tn(this.context),this.sale=(h=t.saleService)!=null?h:new Zt(this.context,r),this.saleItem=(g=t.saleItemService)!=null?g:new rn(this.context),this.shift=(x=t.shiftService)!=null?x:new er(this.context),this.taxRate=(v=t.taxRateService)!=null?v:new nn(this.context),this.transaction=(A=t.transactionService)!=null?A:new tr(this.context,r),this.uom=(I=t.uomService)!=null?I:new rr(this.context),this.user=(k=t.userService)!=null?k:new an(this.context),this.supplier=(w=t.supplierService)!=null?w:new nr(this.context),this.purchaseOrder=(q=t.purchaseOrderService)!=null?q:new ir(this.context),this.purchaseOrderItem=(M=t.purchaseOrderItemService)!=null?M:new on(this.context),this.purchase=(E=t.purchaseService)!=null?E:new ar(this.context,r),this.purchaseItem=(L=t.purchaseItemService)!=null?L:new sn(this.context),this.inventoryLog=(Q=t.inventoryLogService)!=null?Q:new or(this.context),this.priceHistory=(T=t.priceHistoryService)!=null?T:new sr(this.context),this.stockOpname=(z=t.stockOpnameService)!=null?z:new cr(this.context),this.stockOpnameItem=(V=t.stockOpnameItemService)!=null?V:new cn(this.context),this.stockAdjustment=(F=t.stockAdjustmentService)!=null?F:new ur(this.context),this.reportSchedule=(U=t.reportScheduleService)!=null?U:new dr(this.context),this.financialSetting=(O=t.financialSettingService)!=null?O:new lr(this.context),this.expense=(_=t.expenseService)!=null?_:new pr(this.context,r),this.receivable=(R=t.receivableService)!=null?R:new mr(this.context),this.payable=(P=t.payableService)!=null?P:new hr(this.context),this.settlement=(X=t.settlementService)!=null?X:new fr(this.context,r),this.inventory=(te=t.inventoryService)!=null?te:new gr(this.context),this.exportService=(J=t.exportService)!=null?J:new br(this.context),this.pricing=(Y=t.pricingService)!=null?Y:new vr(this.context),this.reporting=(be=t.reportingService)!=null?be:new Ar(this.context),this.cart=(se=t.cartService)!=null?se:new Ir(this.context),this.tax=(Le=t.taxService)!=null?Le:new Pr(this.context),this.stockTransfer=(pe=t.stockTransferService)!=null?pe:new mn(this.context)}};var It={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},bi="sync-store",Cr=class{constructor(e){this.context=e;var t;this.emitter=Rt(),this.storage=(t=this.context.registry)==null?void 0:t.storageAdapter,this.state={...It},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={...It};try{this.storage.removeItem(bi)}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(bi,JSON.stringify(this.state))}catch(e){this.context.logError(e,{message:"Gagal persist sync-store"})}}async load(){try{let e=await this.storage.getItem(bi);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={...It.metrics,...a};return{...It,...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=Rt()}};var wr=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 Er=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(De,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(De,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(De,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(De,e);if(!t)return;if(!await this.db.update(De,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(De,{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(De,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 vi={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"]}]},Or=class{constructor(e){this.context=e;this.roleAdapter=new Er(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(De,{...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 vi}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||vi).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 Yn=Bt(Si()),Tr=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=Yn.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=Yn.default.AES.decrypt(t.value,this.masterKey).toString(Yn.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 Fr=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(He,{...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 kr=require("ofcore"),pt=require("ofcore");var Br=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(!gi(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,pt.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 Ja={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"},_t=class{async backoff(e){return e()}async applyChanges(){}async syncWithErp(){}async syncLoop(){}},Ii=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))}),qe.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 Ja[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),qe.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),qe.off("data_changed",this.onDataChanged),this.started=!1)}};var Tt=class{getSocket(){}shutdown(){}},Pi=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 Mr=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 Za=require("ofcore");var qr=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 Za.DefaultPlatformAdapter(this.context),this.storage=(n=t==null?void 0:t.storageAdapter)!=null?n:new gt(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=[...dn],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,Le,pe,_e,me,Ge,We,Ye,st,yt,ct,Me,Fe,Qe,bt,Ct,ut,mt,ht,wt,Et,dt,ot,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=(Le=e.returnFraudWindowMinutes)!=null?Le:this.returnFraudWindowMinutes,d=(pe=e.returnFraudMaxEvents)!=null?pe:this.returnFraudMaxEvents,c=(_e=e.syncProtocolVersion)!=null?_e:this.syncProtocolVersion,p=(me=e.syncCompatibleServerVersions)!=null?me:this.syncCompatibleServerVersions,l=(Ge=e.enforceSyncProtocolHandshake)!=null?Ge: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=(We=e.enableCustomerCreditPolicy)!=null?We:this.enableCustomerCreditPolicy,f=(Ye=e.customerCreditMaxOutstandingAmount)!=null?Ye:this.customerCreditMaxOutstandingAmount,y=(st=e.customerCreditOverdueGraceDays)!=null?st:this.customerCreditOverdueGraceDays,b=(yt=e.customerCreditEscalationThresholdDays)!=null?yt: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=(ct=e.onlineAuthMaxFailedAttempts)!=null?ct:this.onlineAuthMaxFailedAttempts,g=(Me=e.onlineAuthLockoutSeconds)!=null?Me:this.onlineAuthLockoutSeconds,x=(Fe=e.drRpoTargetMinutes)!=null?Fe:this.drRpoTargetMinutes,v=(Qe=e.drRtoTargetMinutes)!=null?Qe:this.drRtoTargetMinutes,A=(bt=e.backupIntervalMinutes)!=null?bt:this.backupIntervalMinutes,I=(Ct=e.backupRestoreDrillIntervalHours)!=null?Ct:this.backupRestoreDrillIntervalHours,k=(ut=e.opsAlertSyncFailureRateThresholdPercent)!=null?ut:this.opsAlertSyncFailureRateThresholdPercent,w=(mt=e.opsAlertQueueLatencyThresholdMs)!=null?mt:this.opsAlertQueueLatencyThresholdMs,q=(ht=e.opsAlertDeadLetterCountThreshold)!=null?ht:this.opsAlertDeadLetterCountThreshold,M=(wt=e.opsAlertEscalationCooldownMinutes)!=null?wt:this.opsAlertEscalationCooldownMinutes,E=(Et=e.auditLogRetentionDays)!=null?Et:this.auditLogRetentionDays,L=(dt=e.auditLogPurgeBatchSize)!=null?dt: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=(ot=e.sessionIdleTimeoutMinutes)!=null?ot: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 eo="com.offlinepos.backup",Lr=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=eo;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 Nr=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 wr(this.context),this.config=(n=t.configService)!=null?n:new qr(this.context),this.authorization=(i=t.authorizationService)!=null?i:new Or(this.context),this.encryption=(a=t.encryptionService)!=null?a:new Tr(this.context),this.api=(o=t.apiService)!=null?o:new Br(this.context),this.sync=(s=t.syncService)!=null?s:new _t,this.socket=(d=t.socketService)!=null?d:new Tt,this.notification=(c=t.notificationService)!=null?c:new Mr(this.context),this.user=(p=t.userService)!=null?p:new Fr(this.context),this.backupScheduler=(l=t.backupScheduler)!=null?l:new Lr(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 Di=[{toVersion:1,up:async u=>{for(let e of vt)await u.addTable(e)}}];async function Ci(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=[...Di].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 to={isLoggedIn:!1,userId:null,user:null,lastLoginAt:null,tenantId:null},Qr=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=Rt(),this.state={...to},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 Ft=class{constructor(){this.eventBus=qe;this.domainServiceOverrides={};this.integrationServiceOverrides={};this.serviceRuntimeOptions={};this.pluginSpecs=[];this.authBridgePolicyMode="bridge-required";this.runtimeStateStore=(0,Xn.createStore)({phase:"idle",started:!1,startCount:0,stopCount:0,lastError:null,lastTransitionAt:new Date().toISOString()}),this.runtimeStore=(0,Xn.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:{...It}}subscribeDomainChangeQueue(e){return this.syncStore?this.syncStore.subscribe(e):(e({...It}),()=>{})}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 wi}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 yr(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=ro.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 Ci(t,r)},onInit:async()=>{!this.domainChangeSink&&!this.syncStore&&(this.syncStore=new Cr(this)),this.sessionStore||(this.sessionStore=new Qr(this))},createDomainServices:()=>(this.domainServices||(this.domainServices=new Dr(this,this.domainServiceOverrides,this.serviceRuntimeOptions)),this.domainServices),createIntegrationServices:async()=>(this.integrationServices||(this.integrationServices=await Nr.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)}},wi=class{constructor(){this.core=new Ft;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 _t,socketService:(t=this.core.integrationServiceOverrides.socketService)!=null?t:new Tt}}build(e={runMigrations:!0}){return this.applySyncOrchestrationMode(),this.core.registry=new Ur(this.core,this.adapterOpts),this.core}};var Oi=require("ofcore");var Hr=require("ofcore");var jr=require("ofcore");var kt=require("ofcore");var Jn=require("ofcore");var Zn=require("ofcore");var $r=require("ofcore");var ei=Bt(Si()),ti=class{constructor(e){this.context=e}encrypt(e,t){let r=this.resolveSecretKey(t);return ei.default.AES.encrypt(String(e!=null?e:""),r).toString()}decrypt(e,t){let r=this.resolveSecretKey(t);return ei.default.AES.decrypt(String(e!=null?e:""),r).toString(ei.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 so=Bt(io()),co=Bt(Qt()),Ei=Bt(oo()),ii=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,so.default)(t,i).toString(Ei.default):""}return e.algorithm==="sha256"?(0,co.default)(t).toString(Ei.default):""}verify(e,t){let r=String(this.compute(e)||"").trim().toLowerCase(),n=String(t||"").trim().toLowerCase();return r===n}};var Ri=require("ofcore");var Vr=require("ofcore");var Ur=class{constructor(e,t={}){this.context=e;this.opts=t;this.context.registry=this,this.platformAdapter=this.resolveAdapter(t.platformAdapter,Ri.DefaultPlatformAdapter),this.dbAdapter=this.resolveAdapter(t.dbAdapter,Oi.InMemoryDbAdapter),this.loggerAdapter=this.resolveAdapter(t.loggerAdapter,jr.ConsoleLoggerAdapter),this.httpAdapter=this.resolveAdapter(t.httpAdapter,kr.DefaultHttpAdapter),this.httpRetryPolicy=this.resolveAdapter(t.httpRetryPolicy,pt.NoRetryHttpPolicy),this.socketAdapter=this.resolveAdapter(t.socketAdapter,Vr.InMemorySocketAdapter),this.activitySink=this.resolveAdapter(t.activitySink,kt.NoopActivitySink),this.encryptionAdapter=this.resolveAdapter(t.encryptionAdapter,ti),this.checksumAdapter=this.resolveAdapter(t.checksumAdapter,ii),this.notificationAdapter=this.resolveAdapter(t.notificationAdapter,$r.NoopNotificationAdapter),this.exportAdapter=this.resolveAdapter(t.exportAdapter,Hr.DefaultExportAdapter),this.storageAdapter=this.resolveAdapter(t.storageAdapter,gt)}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===Ft)return this.context;if(a===Ri.DefaultPlatformAdapter)return this.platformAdapter;if(a===Oi.InMemoryDbAdapter)return this.dbAdapter;if(a===jr.ConsoleLoggerAdapter)return this.loggerAdapter;if(a===kr.DefaultHttpAdapter)return this.httpAdapter;if(a===pt.NoRetryHttpPolicy)return this.httpRetryPolicy;if(a===Vr.InMemorySocketAdapter)return this.socketAdapter;if(a===kt.NoopActivitySink)return this.activitySink;if(a===Jn.NoopEncryptionAdapter)return this.encryptionAdapter;if(a===Zn.NoopChecksumAdapter)return this.checksumAdapter;if(a===$r.NoopNotificationAdapter)return this.notificationAdapter;if(a===Hr.DefaultExportAdapter)return this.exportAdapter;if(a===gt)return this.storageAdapter});return new r(...i)}};var mo=require("ofcore");var uo=require("ofcore");var lo=require("ofcore");var po=require("ofcore");var _i=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 Ti=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}}};0&&(module.exports={ActivityLogger,AdapterRegistry,ApiService,AuthorizationService,BackupScheduler,CONFLICT_POLICY_MATRIX,CURRENT_SYNC_PROTOCOL_VERSION,CartService,CartStore,CategoryService,ConfigService,ConsoleLoggerAdapter,CustomerGroupService,CustomerService,DEFAULT_GRANULAR_AUTH_POLICY,DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS,DefaultExportAdapter,DefaultHttpAdapter,DefaultPlatformAdapter,DomainServices,EncryptionService,ExpenseService,ExponentialBackoffHttpPolicy,ExportService,FinancialSettingService,HistoryService,InMemoryDbAdapter,InMemorySocketAdapter,IntegrationServices,InventoryLogService,InventoryService,MemoryActivitySink,MemoryStorage,NoRetryHttpPolicy,NoopActivitySink,NoopChecksumAdapter,NoopEncryptionAdapter,NoopNotificationAdapter,NoopSocketService,NoopSyncService,NotificationService,OrderService,POS_DOMAIN_TABLES,PayableService,PosCore,PriceHistoryService,PriceTierService,PricingService,ProductService,PromotionService,PurchaseOrderService,PurchaseService,ReceivableService,ReportScheduleService,ReportingService,ReturnService,RoleAdapter,SaleService,SessionStore,SettlementService,ShiftService,SocketService,StockAdjustmentService,StockOpnameService,SupplierService,SyncService,SyncStore,TASK_ID,TaxService,TransactionService,UIProductService,UITransactionService,UomService,UserService,applyPendingMigrations,bomTable,buildJournalDraftFromPosFinanceProjection,categoryTable,computeChecksum,createChangeQueuePort,createPosFinanceRuntimeOptions,customerGroupTable,customerTable,eventBus,executeHttpRequestWithRetry,expenseTable,financialSettingTable,getSyncProtocolContract,historyTable,initialSessionState,initialState,inventoryLogTable,isContractVersionCompatible,isFailureEnvelope,isServerProtocolCompatible,kitchenTicketItemTable,kitchenTicketTable,loyaltyAccountTable,loyaltyLedgerTable,migrations,orderItemTable,orderTable,payableTable,priceHistoryTable,priceTierTable,productTable,projectPosCashAdjustmentFinance,projectPosExpenseFinance,projectPosPurchaseFinance,projectPosReturnFinance,projectPosSettlementFinance,projectScopedPosSaleFinance,promotionTable,purchaseItemTable,purchaseOrderItemTable,purchaseOrderTable,purchaseTable,receivableTable,reportScheduleTable,returnItemTable,returnTable,roleTable,saleItemTable,saleTable,schemas,settlementTable,shiftTable,stockAdjustmentTable,stockOpnameItemTable,stockOpnameTable,supplierTable,taxRateTable,transactionTable,uomTable,userTable});
20
+ `,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"}]}],Ho=[{name:"branchId",type:"string",isOptional:!0,isIndexed:!0},{name:"tenantId",type:"string",isOptional:!0,isIndexed:!0}];function jo(d){let e=[...d.columns];for(let t of Ho)e.some(r=>r.name===t.name)||e.push({...t});return{...d,columns:e}}var yt=Uo.map(jo),$o=Object.freeze(yt.map(d=>d.name));for(let[d,e]of Object.entries(zi)){let t=yt.find(r=>r.name===d);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[d,e]of Object.entries(Vi)){let t=yt.find(r=>r.name===d);t.polymorphic=e}var ln=1,pn=[1,0];function zo(){return{currentVersion:1,compatibleServerVersions:[...pn]}}function vi(d,e){return e.includes(d)}var vr=(d,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:d,secret:t});if(n&&typeof n.then=="function")throw new Error("Shared-core checksum path requires synchronous ChecksumAdapter.compute");return String(n||"")};var xr=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(`
21
+ `)}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,u=s.getDocumentPath("sales_report.csv");await s.writeFile(u,o),await s.share(u)}async exportStockCSV(){let t=await this.dbAdapter.query("products"),r=["ID","Name","Stock"],n=await Promise.all(t.map(u=>this.inventoryService.getStock(u.id))),i=t.map((u,c)=>{var p;return[u.id,(p=u.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 u,c;return[s.id,s.name,(u=s.phone)!=null?u:"",(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 yt.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=yt.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 h,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(m=>this.isWithinPeriod(m.date,e.from,e.to)),o=r.filter(m=>this.isWithinPeriod(m.date,e.from,e.to)),s=n.filter(m=>this.isWithinPeriod(m.date,e.from,e.to)),u=i.filter(m=>this.isWithinPeriod(m.date,e.from,e.to)),c={sales:a.map(m=>({id:m.id,date:m.date,total:m.total,discount:m.discount,ppn:m.ppn,pph:m.pph,finalTotal:m.finalTotal,status:m.status,customerId:m.customerId,userId:m.userId})),returns:o.map(m=>({id:m.id,date:m.date,type:m.type,refundAmount:m.refundAmount,actualRefund:m.actualRefund,status:m.status,saleId:m.saleId,purchaseId:m.purchaseId,userId:m.userId})),purchases:s.map(m=>({id:m.id,date:m.date,total:m.total,supplierId:m.supplierId,userId:m.userId,purchaseOrderId:m.purchaseOrderId})),payments:u.map(m=>({id:m.id,date:m.date,amount:m.amount,method:m.method,direction:m.receivableId?"in":"out",receivableId:m.receivableId,payableId:m.payableId,reference:m.reference,userId:m.userId}))},p={salesFinalTotal:c.sales.reduce((m,g)=>m+g.finalTotal,0),salesPpnTotal:c.sales.reduce((m,g)=>m+g.ppn,0),salesPphTotal:c.sales.reduce((m,g)=>m+g.pph,0),returnsActualRefundTotal:c.returns.reduce((m,g)=>m+g.actualRefund,0),purchasesTotal:c.purchases.reduce((m,g)=>m+g.total,0),paymentInTotal:c.payments.filter(m=>m.direction==="in").reduce((m,g)=>m+g.amount,0),paymentOutTotal:c.payments.filter(m=>m.direction==="out").reduce((m,g)=>m+g.amount,0)},l={contractVersion:"tex-v1",generatedAt:new Date().toISOString(),sourceVersion:`sync-protocol-v${1}`,period:{from:(h=e.from)!=null?h: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=C(),s=new Date().toISOString(),u=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=vr(u,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:C(),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 Ar=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(Ue,{filters:a});s.sort((h,f)=>{let y=h.customerGroupId===r?0:1,b=f.customerGroupId===r?0:1;return y!==b?y-b:f.tierLevel-h.tierLevel});let u=s.find(h=>t>=h.tierLevel),c=await i.get(ce,e);if(!c)throw new Error(`Product with id ${e} not found`);let p=u?u.price:c.price,l=p;if(!u&&n){let h=c.baseUomId;if(h&&h!==n){let f=await this.uomService.getUom(h),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(m=>{if(m.code!==b)return!1;if(!m.expiresAt)return!0;let g=Date.parse(m.expiresAt);return Number.isNaN(g)?!1:g>=a})).filter(Boolean);if(!o.length)return 0;let s=this.roundValue(e.reduce((b,m)=>b+m.quantity*m.unitPrice,0)),u=this.context.config.allowPromotionStacking,c=this.context.config.promotionSelectionStrategy;if(!u){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,m=b.type==="percent"?s*b.value/100:b.value;return this.roundValue(Math.min(Math.max(0,m),s))}let p=this.context.config.promotionStackingOrder,l=[...o];p==="percent_then_fixed"?l.sort((b,m)=>b.type===m.type?0:b.type==="percent"?-1:1):p==="fixed_then_percent"&&l.sort((b,m)=>b.type===m.type?0:b.type==="fixed"?-1:1);let h=s,f=0;for(let b of l){let m=b.type==="percent"?h*b.value/100:b.value,g=Math.min(Math.max(0,this.roundValue(m)),h);h-=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,u)=>s+u.quantity*u.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 m=1+i+a;s=m>0?o/m:o}s=this.normalizePrecision(this.roundValue(s));let u=this.normalizePrecision(this.roundValue(s*i)),c=this.normalizePrecision(this.roundValue(s*a)),p=r==="exclusive"?this.normalizePrecision(this.roundValue(s+u+c)):this.normalizePrecision(this.roundValue(o)),l=this.normalizePrecision(this.roundValue(Number((t==null?void 0:t.correctionAmount)||0))),h=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:u,pph:c,totalBeforeCorrection:p,correctionAmount:l,totalAfterCorrection:h,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 Vo=Math.pow(10,8)*24*60*60*1e3,f0=-Vo;var Ko=3600;var Ki=Ko*24,g0=Ki*7,Go=Ki*365.2425,Wo=Go/12,y0=Wo*3,xi=Symbol.for("constructDateFrom");function mn(d,e){return typeof d=="function"?d(e):d&&typeof d=="object"&&xi in d?d[xi](e):d instanceof Date?new d.constructor(e):new Date(e)}function qt(d,e){return mn(e||d,d)}function Gi(d,e,t){let r=qt(d,t==null?void 0:t.in);return isNaN(e)?mn((t==null?void 0:t.in)||d,NaN):(e&&r.setDate(r.getDate()+e),r)}function hn(d,e){let t=qt(d,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Sr(d,e){let t=qt(d,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Wi(d,e,t){return Gi(d,-e,t)}var Ir=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 u of i)a+=(s=u.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 u=new Date(o.date).getUTCHours().toString().padStart(2,"0");a.set(u,(a.get(u)||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 u=o.referenceId,c=(s=o.amount)!=null?s:0;a.set(u,(a.get(u)||0)+c)}}),Array.from(a.entries()).map(([o,s])=>({customerId:o,revenue:s}))}async getTodaySales(){let e=hn(new Date).toISOString(),t=Sr(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=Sr(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=hn(new Date).toISOString(),r=Sr(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(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||""),h=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+=h,y.totalSales+=h*f,o.set(l,y)}if(!o.size)return[];let s=Array.from(o.keys()),u=await this.dbAdapter.query(ce,{filters:{and:[{field:"id",operator:"IN",value:s},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["id","name"]}}),c=new Map;for(let p of u){let l=String(p.t0_id||p.id||""),h=String(p.t0_name||p.name||"");l&&c.set(l,h||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=Wi(new Date,t),n=hn(r).toISOString(),i=Sr(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,h,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 u=Number(((l=i==null?void 0:i[0])==null?void 0:l.salesCash)||0),c=Number(((h=i==null?void 0:i[0])==null?void 0:h.returnsCash)||0),p=Number(((f=i==null?void 0:i[0])==null?void 0:f.expenses)||0);return{date:e,totalSalesCash:u,totalReturnsCash:c,totalExpenses:p,netCashMovement:u-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),u=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:u,netCashMovement:s-u,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(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(b=>b.id).filter(Boolean),u=s.length>0?await this.dbAdapter.query(Be,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:s},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],c=a.reduce((b,m)=>b+Math.abs(Number(m.cashDifference||0)),0),p=u.length,l=u.reduce((b,m)=>b+Math.abs(Number(m.difference||0)),0),h=[];return(i.salesCashIn>0?i.salesReturnCashOut/i.salesCashIn:0)>.1&&h.push("HIGH_REFUND_RATIO"),c>0&&h.push("SHIFT_CASH_DIFFERENCE"),p>0&&h.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:h}}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(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(c=>c.id).filter(Boolean),s=o.length>0?await this.dbAdapter.query(Be,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:o},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],u=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(u.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 u=Number(o.amount||0),c=Number(o.paidAmount||0),p=Math.max(0,u-c);if(p<=0)continue;let l=new Date(String(o.dueDate||"")),h=this.diffInDays(l,t),f=Number.isFinite(h)&&h>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,h)),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 u=String(s.customerId||"");if(!u)continue;let c=Number(s.amount||0),p=Number(s.paidAmount||0),l=Math.max(0,c-p);if(l<=0)continue;let h=new Date(String(s.dueDate||"")),f=this.diffInDays(h,t),y=Number.isFinite(f)&&f>0,b=(o=n.get(u))!=null?o:{customerId:u,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(u,b)}let i=this.context.config.customerCreditEscalationThresholdDays;return Array.from(n.values()).map(s=>{let u="none";return s.maxDaysPastDue>=i*2?u="critical":s.maxDaysPastDue>=i&&(u="warning"),{...s,escalationLevel:u}}).sort((s,u)=>u.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 u of n){let c=String(u.supplierId||"");c&&i.set(c,(i.get(c)||0)+1)}let a=new Map;for(let u of r)a.set(u.supplierId,(a.get(u.supplierId)||0)+1);let o=new Set([...t.map(u=>u.supplierId),...Array.from(i.keys())]),s=[];for(let u of o){let c=t.find(x=>x.supplierId===u),p=(c==null?void 0:c.openPayableCount)||0,l=c&&c.totalOutstanding>0?c.overdueOutstanding/c.totalOutstanding:0,h=i.get(u)||0,f=a.get(u)||0,y=h>0?f/h:0,b=Math.round(100-(l*60+y*40)*100),m=Math.max(0,Math.min(100,b)),g=m>=85?"A":m>=70?"B":m>=50?"C":"D";s.push({supplierId:u,rating:m,grade:g,openPayableCount:p,overduePayableRatio:Number(l.toFixed(4)),openPurchaseOrderCount:h,overdueOrderCount:f,overdueOrderRatio:Number(y.toFixed(4))})}return s.sort((u,c)=>c.rating-u.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 Nt=class Nt{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(Nt.KEY);return e?JSON.parse(e):{}}async saveAllCarts(e){await this.storage.setItem(Nt.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(Nt.KEY)}};Nt.KEY="carts";var Pr=Nt;var Dr=class{constructor(e){this.context=e;this.cartStore=new Pr(this.context)}async createCart(e){var n;let t=new Date().toISOString(),r={id:C(),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,u={...i.items[a],...r,id:t},c=u.quantity*u.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),u,...i.items.slice(a+1)],await this.cartStore.updateCart(i),i}};var Lt=null,Qt=null;function Yi(d){var t;let e=typeof((t=globalThis.crypto)==null?void 0:t.randomUUID)=="function"?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2,10)}`;return`tax-rate-${d}-${e}`}var Cr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,qe.on("taxRateChanged",this.clearTaxRateCache)}async getPpnRate(){if(Lt!==null)return Lt;let e=await this.dbAdapter.query(Ee,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});return Lt=e.length>0?e[0].rate:0,Lt}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,{id:Yi("ppn"),key:"ppn",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),qe.emit("taxRateChanged"),Lt=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,{id:Yi("pph"),key:"pph",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),qe.emit("taxRateChanged"),Qt=e}clearTaxRateCache(){Lt=null,Qt=null}};var fn=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:C(),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=C(),o=this.getActorId()||null;await this.dbAdapter.transaction(async u=>{await this.appendEvent(a,"stock_transfer_requested",{sourceBranchId:t,targetBranchId:r,status:"requested",items:n,notes:e.notes||null,requestedBy:o,requestedAt:i},u)});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 u=>{for(let c of r.items)await this.context.domainServices.inventory.updateStock(c.productId,-Number(c.quantity),"stock_transfer_out","stock_transfer",e,u);await this.appendEvent(e,"stock_transfer_shipped",{status:"shipped",shippedBy:i,shippedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},u)});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 u=>{for(let c of r.items)await this.context.domainServices.inventory.updateStock(c.productId,Number(c.quantity),"stock_transfer_in","stock_transfer",e,u);await this.appendEvent(e,"stock_transfer_received",{status:"received",receivedBy:i,receivedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},u)});let o=await this.getTransfer(e);if(!o)throw new Error("Stock transfer not found after receiving");return o}};var wr=class{constructor(e,t={},r={}){this.context=e;var n,i,a,o,s,u,c,p,l,h,f,y,b,m,g,x,v,A,S,M,I,F,E,O,N,Q,_,$,H,k,L,R,B,T,D,X,te,J,Y,be,se,Ne,pe,we;this.context.domainServices=this,this.bom=(n=t.bomService)!=null?n:new Jr(this.context),this.category=(i=t.categoryService)!=null?i:new jt(this.context),this.checkoutComputation=(a=t.checkoutComputationService)!=null?a:new $t(this.context),this.customer=(o=t.customerService)!=null?o:new zt(this.context),this.customerGroup=(s=t.customerGroupService)!=null?s:new Vt(this.context),this.history=(u=t.historyService)!=null?u:new Kt(this.context),this.order=(c=t.orderService)!=null?c:new Gt(this.context),this.orderItem=(p=t.orderItemService)!=null?p:new en(this.context),this.priceTier=(l=t.priceTierService)!=null?l:new Wt(this.context),this.product=(h=t.productService)!=null?h:new Yt(this.context),this.promotion=(f=t.promotionService)!=null?f:new Xt(this.context),this.returnService=(y=t.returnService)!=null?y:new er(this.context,r),this.returnItem=(b=t.returnItemService)!=null?b:new rn(this.context),this.role=(m=t.roleService)!=null?m:new nn(this.context),this.sale=(g=t.saleService)!=null?g:new tr(this.context,r),this.saleItem=(x=t.saleItemService)!=null?x:new an(this.context),this.shift=(v=t.shiftService)!=null?v:new rr(this.context),this.taxRate=(A=t.taxRateService)!=null?A:new on(this.context),this.transaction=(S=t.transactionService)!=null?S:new nr(this.context,r),this.uom=(M=t.uomService)!=null?M:new ir(this.context),this.user=(I=t.userService)!=null?I:new sn(this.context),this.supplier=(F=t.supplierService)!=null?F:new ar(this.context),this.purchaseOrder=(E=t.purchaseOrderService)!=null?E:new or(this.context),this.purchaseOrderItem=(O=t.purchaseOrderItemService)!=null?O:new cn(this.context),this.purchase=(N=t.purchaseService)!=null?N:new sr(this.context,r),this.purchaseItem=(Q=t.purchaseItemService)!=null?Q:new un(this.context),this.inventoryLog=(_=t.inventoryLogService)!=null?_:new cr(this.context),this.priceHistory=($=t.priceHistoryService)!=null?$:new ur(this.context),this.stockOpname=(H=t.stockOpnameService)!=null?H:new dr(this.context),this.stockOpnameItem=(k=t.stockOpnameItemService)!=null?k:new dn(this.context),this.stockAdjustment=(L=t.stockAdjustmentService)!=null?L:new lr(this.context),this.reportSchedule=(R=t.reportScheduleService)!=null?R:new pr(this.context),this.financialSetting=(B=t.financialSettingService)!=null?B:new mr(this.context),this.expense=(T=t.expenseService)!=null?T:new hr(this.context,r),this.receivable=(D=t.receivableService)!=null?D:new fr(this.context),this.payable=(X=t.payableService)!=null?X:new gr(this.context),this.settlement=(te=t.settlementService)!=null?te:new yr(this.context,r),this.inventory=(J=t.inventoryService)!=null?J:new br(this.context),this.exportService=(Y=t.exportService)!=null?Y:new xr(this.context),this.pricing=(be=t.pricingService)!=null?be:new Ar(this.context),this.reporting=(se=t.reportingService)!=null?se:new Ir(this.context),this.cart=(Ne=t.cartService)!=null?Ne:new Dr(this.context),this.tax=(pe=t.taxService)!=null?pe:new Cr(this.context),this.stockTransfer=(we=t.stockTransferService)!=null?we:new fn(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},Ai="sync-store",Er=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,m,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=(m=e==null?void 0:e.id)!=null?m: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),u=Date.parse(String((x=r==null?void 0:r.lastModified)!=null?x:"")),c=Number.isFinite(s)&&s>0?s:Number.isFinite(u)&&u>0?u:Date.now(),p=Number(e==null?void 0:e.firstQueuedAt),l=Number(e==null?void 0:e.retryCount),h=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(h)&&h>0?h: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(Ai)}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(Ai,JSON.stringify(this.state))}catch(e){this.context.logError(e,{message:"Gagal persist sync-store"})}}async load(){try{let e=await this.storage.getItem(Ai);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 u=s;return!!u.change&&typeof u.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 Or=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,u;let t=(u=(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?u: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,u;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,h=(r==null?void 0:r.tenantId)||null,f=(r==null?void 0:r.branchId)||null,y=h||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&&h&&String(h)!==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 m={...r||{},tenantId:y||null,branchId:b||null,deploymentMode:c};await((u=(s=this.context.registry)==null?void 0:s.activitySink)==null?void 0:u.publish({activityId:C(),activityType:e,occurredAt:i,scopeRef:{tenantId:y||void 0,branchId:b||void 0,domain:"ofpos"},actor:{userId:t,source:"shared-core"},payload:m})),this.context.logInfo(a,m);let g=this.inferTableName(e,r),x=this.resolveRecordId(r),v={...m};await(n||this.dbAdapter).create(ie,{id:C(),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 Rr=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:C().toString(),name:e.name,permissions:JSON.stringify(e.permissions),version:1,lastModified:t,deleted:!1},n=await this.db.create(De,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(De,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(De,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(De,e);if(!t)return;if(!await this.db.update(De,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(De,{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(De,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 Si={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"]}]},_r=class{constructor(e){this.context=e;this.roleAdapter=new Rr(e),this.changeQueue=j(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(De,{...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 Si}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,h,f;let t=C(),n=(e.policy||Si).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||((h=this.context.session)==null?void 0:h.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount,approvedBy:e.approval.approvedBy,approvalReason:e.approval.reason,approverRole:this.normalizeRole(e.approval.approverRole)}),y}let u={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:u.status,reasonCode:u.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)}),u}};var Jn=Mt(Di()),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=Jn.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=Jn.default.AES.decrypt(t.value,this.masterKey).toString(Jn.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 Br=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(He,{...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 Mr=require("ofcore"),pt=require("ofcore");var qr=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(!vi(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 u;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=(u=this.context.session)==null?void 0:u.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,pt.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 io={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(){}},Ci=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))}),qe.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,h,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((h=e==null?void 0:e.type)!=null?h:"").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:"")),u=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:u}}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 io[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 u=s==null?void 0:s.table,c=s==null?void 0:s.id;if(!u||!c){this.context.logError(new Error("Invalid remote change payload"),{change:s,...t||{}});continue}let p=this.getRemoteTimestamp(s),l=new Date(p).toISOString(),h=(i=s==null?void 0:s.record)!=null?i:{},f={...h,id:c,lastModified:(a=h==null?void 0:h.lastModified)!=null?a:l};try{let y=await r.get(u,c);if(!y)await r.create(u,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(u,c,f);else if(p!==b)if(this.getConflictResolutionStrategy(u)==="server_wins")await r.update(u,c,f),this.context.logInfo(`Auto-resolve konflik master data ${u}:${c}`,t);else{let m={table:u,id:c,localLastModified:y==null?void 0:y.lastModified,remoteUpdatedAt:p,local:y,remote:s,reason:"local_newer"};n.addConflict(m),this.context.logInfo(`Konflik terdeteksi ${u}:${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),u=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 u.get("customers",p),h={...c,lastModified:(r=c==null?void 0:c.lastModified)!=null?r:new Date().toISOString()};l?await u.update("customers",p,h):await u.create("customers",h)}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 u.get("boms",p),h={...c,lastModified:(i=c==null?void 0:c.lastModified)!=null?i:new Date().toISOString()};l?await u.update("boms",p,h):await u.create("boms",h)}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 u.get("uoms",p),h={...c,lastModified:(o=c==null?void 0:c.lastModified)!=null?o:new Date().toISOString()};l?await u.update("uoms",p,h):await u.create("uoms",h)}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),qe.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((h,f)=>{let y=Number(f==null?void 0:f.firstQueuedAt);return!Number.isFinite(y)||y<=0?h:h+Math.max(0,n-y)},0)/r.length):0,a=0,o=0,s=0,u=0;for(let h of r)try{a+=1;let f=this.normalizeOutgoingChange(h);if(!f){this.context.logError(new Error("Invalid queued change"),{change:h,...t}),e.removeQueuedChange(String((h==null?void 0:h.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(h.id,f);let y=e.getState().queue.find(b=>b.id===h.id);y&&y.retryCount>=this.context.config.syncMaxRetries&&e.moveToDeadLetter(h.id,"max_retry_exceeded",f)}let c=[];try{let h=e.getState().lastSyncAt;c=await this.backoff(()=>this.apiService.pullChanges({since:h},t)),await this.applyChanges(c,t),u=c.length}catch(h){this.context.logError(h,{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+u,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),qe.off("data_changed",this.onDataChanged),this.started=!1)}};var kt=class{getSocket(){}shutdown(){}},wi=class d{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=d.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 Nr=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 ao=require("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 ao.DefaultPlatformAdapter(this.context),this.storage=(n=t==null?void 0:t.storageAdapter)!=null?n:new gt(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=[...pn],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,we,me,We,Ye,Xe,st,bt,ct,Me,ke,Qe,vt,wt,ut,mt,ht,Et,Ot,dt,ot,P,w,q,U,W,he,ve,ee,z;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,u=(pe=e.returnFraudMaxEvents)!=null?pe:this.returnFraudMaxEvents,c=(we=e.syncProtocolVersion)!=null?we: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 h=(Ye=e.enableCustomerCreditPolicy)!=null?Ye:this.enableCustomerCreditPolicy,f=(Xe=e.customerCreditMaxOutstandingAmount)!=null?Xe:this.customerCreditMaxOutstandingAmount,y=(st=e.customerCreditOverdueGraceDays)!=null?st:this.customerCreditOverdueGraceDays,b=(bt=e.customerCreditEscalationThresholdDays)!=null?bt:this.customerCreditEscalationThresholdDays;if(h){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(u==null||u<=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(V=>Number.isInteger(V)&&V>=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 m=(ct=e.onlineAuthMaxFailedAttempts)!=null?ct:this.onlineAuthMaxFailedAttempts,g=(Me=e.onlineAuthLockoutSeconds)!=null?Me:this.onlineAuthLockoutSeconds,x=(ke=e.drRpoTargetMinutes)!=null?ke:this.drRpoTargetMinutes,v=(Qe=e.drRtoTargetMinutes)!=null?Qe:this.drRtoTargetMinutes,A=(vt=e.backupIntervalMinutes)!=null?vt:this.backupIntervalMinutes,S=(wt=e.backupRestoreDrillIntervalHours)!=null?wt:this.backupRestoreDrillIntervalHours,M=(ut=e.opsAlertSyncFailureRateThresholdPercent)!=null?ut:this.opsAlertSyncFailureRateThresholdPercent,I=(mt=e.opsAlertQueueLatencyThresholdMs)!=null?mt:this.opsAlertQueueLatencyThresholdMs,F=(ht=e.opsAlertDeadLetterCountThreshold)!=null?ht:this.opsAlertDeadLetterCountThreshold,E=(Et=e.opsAlertEscalationCooldownMinutes)!=null?Et:this.opsAlertEscalationCooldownMinutes,O=(Ot=e.auditLogRetentionDays)!=null?Ot:this.auditLogRetentionDays,N=(dt=e.auditLogPurgeBatchSize)!=null?dt:this.auditLogPurgeBatchSize;if(!Number.isInteger(m)||m<=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(S)||S<=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(M)||M<=0||M>100)throw new Error("Invalid config: opsAlertSyncFailureRateThresholdPercent must be an integer in range 1..100");if(!Number.isInteger(I)||I<=0)throw new Error("Invalid config: opsAlertQueueLatencyThresholdMs must be a positive integer");if(!Number.isInteger(F)||F<=0)throw new Error("Invalid config: opsAlertDeadLetterCountThreshold must be a positive integer");if(!Number.isInteger(E)||E<=0)throw new Error("Invalid config: opsAlertEscalationCooldownMinutes must be a positive integer");if(!Number.isInteger(O)||O<=0)throw new Error("Invalid config: auditLogRetentionDays must be a positive integer");if(!Number.isInteger(N)||N<=0)throw new Error("Invalid config: auditLogPurgeBatchSize must be a positive integer");let Q=(ot=e.sessionIdleTimeoutMinutes)!=null?ot:this.sessionIdleTimeoutMinutes,_=(P=e.sessionReauthTimeoutMinutes)!=null?P:this.sessionReauthTimeoutMinutes;if(!Number.isInteger(Q)||Q<=0)throw new Error("Invalid config: sessionIdleTimeoutMinutes must be positive");if(!Number.isInteger(_)||_<=0)throw new Error("Invalid config: sessionReauthTimeoutMinutes must be positive");let $=(w=e.apiTimeoutMs)!=null?w:this.apiTimeoutMs,H=(q=e.syncIntervalMs)!=null?q:this.syncIntervalMs,k=(U=e.syncMaxRetries)!=null?U:this.syncMaxRetries,L=(W=e.syncBackoffDelayMs)!=null?W:this.syncBackoffDelayMs,R=(he=e.syncDebounceMs)!=null?he:this.syncDebounceMs,B=(ve=e.reportingTopSellingLimit)!=null?ve:this.reportingTopSellingLimit,T=(ee=e.reportingLowStockLimit)!=null?ee:this.reportingLowStockLimit,D=(z=e.apiBackupListLimit)!=null?z:this.apiBackupListLimit;if(!Number.isInteger($)||$<=0)throw new Error("Invalid config: apiTimeoutMs must be positive");if(!Number.isInteger(H)||H<=0)throw new Error("Invalid config: syncIntervalMs must be positive");if(!Number.isInteger(k)||k<=0)throw new Error("Invalid config: syncMaxRetries must be positive");if(!Number.isInteger(L)||L<=0)throw new Error("Invalid config: syncBackoffDelayMs must be positive");if(!Number.isInteger(R)||R<=0)throw new Error("Invalid config: syncDebounceMs must be positive");if(!Number.isInteger(B)||B<=0)throw new Error("Invalid config: reportingTopSellingLimit must be positive");if(!Number.isInteger(T)||T<=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 oo="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 backupNow(e={}){var n;this.apiService||(this.apiService=(n=this.context.integrationServices)==null?void 0:n.api);let t={label:`manual-${new Date().toISOString()}`,reason:"manual-backup",...e},r=await this.apiService.createBackup(t);return this.lastBackupAt=Date.now(),r}async restoreBackup(e={}){var i;this.apiService||(this.apiService=(i=this.context.integrationServices)==null?void 0:i.api);let t=String(e.backupId||"").trim();if(!t){let a=await this.apiService.listBackups({limit:10}),o=this.normalizeBackupList(a);if(!Array.isArray(o)||o.length===0)throw new Error("No backups available");let s=o.find(u=>this.isReadyBackupStatus(u==null?void 0:u.status))||o[0];if(t=String((s==null?void 0:s.id)||(s==null?void 0:s.backupId)||"").trim(),!t)throw new Error("Backup id missing")}let r={backupId:t,reason:"manual-restore",...e},n=await this.apiService.restoreBackup(r);return this.lastRestoreDrillAt=Date.now(),n}async runBackupTask(){var t;this.apiService||(this.apiService=(t=this.context.integrationServices)==null?void 0:t.api);let e=oo;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}),r=this.normalizeBackupList(t);if(!Array.isArray(r)||r.length===0){this.context.logInfo("[BackupScheduler] Restore drill skipped: no backups available");return}let n=r.find(a=>this.isReadyBackupStatus(a==null?void 0:a.status))||r[0],i=String((n==null?void 0:n.id)||(n==null?void 0:n.backupId)||"").trim();if(!i){this.context.logInfo("[BackupScheduler] Restore drill skipped: backupId missing");return}await this.apiService.restoreBackup({backupId:i,dryRun:!0,reason:"scheduled-restore-drill"}),this.lastRestoreDrillAt=Date.now(),this.context.logInfo(`[BackupScheduler] Restore drill completed for backupId=${i}`)}catch(t){this.context.logError(t,{message:"[BackupScheduler] Restore drill failed"})}}normalizeBackupList(e){return Array.isArray(e)?e:Array.isArray(e==null?void 0:e.backups)?e.backups:[]}isReadyBackupStatus(e){let t=String(e||"ready").trim().toLowerCase();return t==="ready"||t==="created"||t==="restored"}};var Ur=class d{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,u,c,p,l;this.context.integrationServices=this,this.activityLogger=(r=t.activityLogger)!=null?r:new Or(this.context),this.config=(n=t.configService)!=null?n:new Lr(this.context),this.authorization=(i=t.authorizationService)!=null?i:new _r(this.context),this.encryption=(a=t.encryptionService)!=null?a:new Fr(this.context),this.api=(o=t.apiService)!=null?o:new qr(this.context),this.sync=(s=t.syncService)!=null?s:new Tt,this.socket=(u=t.socketService)!=null?u:new kt,this.notification=(c=t.notificationService)!=null?c:new Nr(this.context),this.user=(p=t.userService)!=null?p:new Br(this.context),this.backupScheduler=(l=t.backupScheduler)!=null?l:new Qr(this.context,{setInterval(h,f){let y=setInterval(h,f);return{clear:()=>clearInterval(y)}}})}static async create(e,t={}){let r=new d(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 so=3,Ei=[{toVersion:1,up:async d=>{for(let e of yt)await d.addTable(e)}},{toVersion:so,up:async d=>{for(let e of yt){await d.addTable(e);for(let t of e.columns)await d.addColumn(e.name,t)}}}];async function Oi(d,e){if(typeof d.getSchemaVersion!="function"||typeof d.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 d.getSchemaVersion();(t==null||t<0)&&(t=0);let r=[...Ei].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(d),await d.setSchemaVersion(i.toVersion),t=i.toVersion);e.logInfo("Database migration completed successfully")}catch(t){throw e.logError(t,{message:"Database migration failed"}),t}}var co={isLoggedIn:!1,userId:null,user:null,lastLoginAt:null,tenantId:null},Hr=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={...co},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 Ft=class{constructor(){this.eventBus=qe;this.domainServiceOverrides={};this.integrationServiceOverrides={};this.serviceRuntimeOptions={};this.pluginSpecs=[];this.authBridgePolicyMode="bridge-required";this.runtimeStateStore=(0,Zn.createStore)({phase:"idle",started:!1,startCount:0,stopCount:0,lastError:null,lastTransitionAt:new Date().toISOString()}),this.runtimeStore=(0,Zn.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 Ri}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 vr(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=uo.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 Oi(t,r)},onInit:async()=>{!this.domainChangeSink&&!this.syncStore&&(this.syncStore=new Er(this)),this.sessionStore||(this.sessionStore=new Hr(this))},createDomainServices:()=>(this.domainServices||(this.domainServices=new wr(this,this.domainServiceOverrides,this.serviceRuntimeOptions)),this.domainServices),createIntegrationServices:async()=>(this.integrationServices||(this.integrationServices=await Ur.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)}},Ri=class{constructor(){this.core=new Ft;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 kt}}build(e={runMigrations:!0}){return this.applySyncOrchestrationMode(),this.core.registry=new jr(this.core,this.adapterOpts),this.core}};var Ti=require("ofcore");var $r=require("ofcore");var zr=require("ofcore");var Bt=require("ofcore");var ei=require("ofcore");var ti=require("ofcore");var Vr=require("ofcore");var ri=Mt(Di()),ni=class{constructor(e){this.context=e}encrypt(e,t){let r=this.resolveSecretKey(t);return ri.default.AES.encrypt(String(e!=null?e:""),r).toString()}decrypt(e,t){let r=this.resolveSecretKey(t);return ri.default.AES.decrypt(String(e!=null?e:""),r).toString(ri.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 fo=Mt(po()),go=Mt(Ut()),_i=Mt(ho()),oi=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,fo.default)(t,i).toString(_i.default):""}return e.algorithm==="sha256"?(0,go.default)(t).toString(_i.default):""}verify(e,t){let r=String(this.compute(e)||"").trim().toLowerCase(),n=String(t||"").trim().toLowerCase();return r===n}};var ki=require("ofcore");var Kr=require("ofcore");var jr=class{constructor(e,t={}){this.context=e;this.opts=t;this.context.registry=this,this.platformAdapter=this.resolveAdapter(t.platformAdapter,ki.DefaultPlatformAdapter),this.dbAdapter=this.resolveAdapter(t.dbAdapter,Ti.InMemoryDbAdapter),this.loggerAdapter=this.resolveAdapter(t.loggerAdapter,zr.ConsoleLoggerAdapter),this.httpAdapter=this.resolveAdapter(t.httpAdapter,Mr.DefaultHttpAdapter),this.httpRetryPolicy=this.resolveAdapter(t.httpRetryPolicy,pt.NoRetryHttpPolicy),this.socketAdapter=this.resolveAdapter(t.socketAdapter,Kr.InMemorySocketAdapter),this.activitySink=this.resolveAdapter(t.activitySink,Bt.NoopActivitySink),this.encryptionAdapter=this.resolveAdapter(t.encryptionAdapter,ni),this.checksumAdapter=this.resolveAdapter(t.checksumAdapter,oi),this.notificationAdapter=this.resolveAdapter(t.notificationAdapter,Vr.NoopNotificationAdapter),this.exportAdapter=this.resolveAdapter(t.exportAdapter,$r.DefaultExportAdapter),this.storageAdapter=this.resolveAdapter(t.storageAdapter,gt)}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===Ft)return this.context;if(a===ki.DefaultPlatformAdapter)return this.platformAdapter;if(a===Ti.InMemoryDbAdapter)return this.dbAdapter;if(a===zr.ConsoleLoggerAdapter)return this.loggerAdapter;if(a===Mr.DefaultHttpAdapter)return this.httpAdapter;if(a===pt.NoRetryHttpPolicy)return this.httpRetryPolicy;if(a===Kr.InMemorySocketAdapter)return this.socketAdapter;if(a===Bt.NoopActivitySink)return this.activitySink;if(a===ei.NoopEncryptionAdapter)return this.encryptionAdapter;if(a===ti.NoopChecksumAdapter)return this.checksumAdapter;if(a===Vr.NoopNotificationAdapter)return this.notificationAdapter;if(a===$r.DefaultExportAdapter)return this.exportAdapter;if(a===gt)return this.storageAdapter});return new r(...i)}};var xo=require("ofcore");var yo=require("ofcore");var bo=require("ofcore");var vo=require("ofcore");var Fi=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 Bi=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:u,total:c}=await n(e,t,r),[p,l]=await Promise.all([i(c),a(c)]);return{pricedItems:o,subTotal:s,discount:u,total:c,ppn:p,pph:l,totalWithTax:c+p+l,payableToSeller:c+p-l}}};0&&(module.exports={ActivityLogger,AdapterRegistry,ApiService,AuthorizationService,BackupScheduler,CONFLICT_POLICY_MATRIX,CURRENT_SYNC_PROTOCOL_VERSION,CartService,CartStore,CategoryService,CheckoutComputationService,ConfigService,ConsoleLoggerAdapter,CustomerGroupService,CustomerService,DEFAULT_GRANULAR_AUTH_POLICY,DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS,DefaultExportAdapter,DefaultHttpAdapter,DefaultPlatformAdapter,DomainServices,EncryptionService,ExpenseService,ExponentialBackoffHttpPolicy,ExportService,FinancialSettingService,HistoryService,InMemoryDbAdapter,InMemorySocketAdapter,IntegrationServices,InventoryLogService,InventoryService,MemoryActivitySink,MemoryStorage,NoRetryHttpPolicy,NoopActivitySink,NoopChecksumAdapter,NoopEncryptionAdapter,NoopNotificationAdapter,NoopSocketService,NoopSyncService,NotificationService,OrderService,POS_DOMAIN_TABLES,POS_SCHEMA_VERSION,PayableService,PosCore,PriceHistoryService,PriceTierService,PricingService,ProductService,PromotionService,PurchaseOrderService,PurchaseService,ReceivableService,ReportScheduleService,ReportingService,ReturnService,RoleAdapter,SaleService,SessionStore,SettlementService,ShiftService,SocketService,StockAdjustmentService,StockOpnameService,SupplierService,SyncService,SyncStore,TASK_ID,TaxService,TransactionService,UIProductService,UITransactionService,UomService,UserService,applyPendingMigrations,bomTable,buildJournalDraftFromPosFinanceProjection,categoryTable,computeChecksum,createChangeQueuePort,createPosFinanceRuntimeOptions,customerGroupTable,customerTable,eventBus,executeHttpRequestWithRetry,expenseTable,financialSettingTable,getSyncProtocolContract,historyTable,initialSessionState,initialState,inventoryLogTable,isContractVersionCompatible,isFailureEnvelope,isServerProtocolCompatible,kitchenTicketItemTable,kitchenTicketTable,loyaltyAccountTable,loyaltyLedgerTable,migrations,orderItemTable,orderTable,payableTable,priceHistoryTable,priceTierTable,productTable,projectPosCashAdjustmentFinance,projectPosExpenseFinance,projectPosPurchaseFinance,projectPosReturnFinance,projectPosSettlementFinance,projectScopedPosSaleFinance,promotionTable,purchaseItemTable,purchaseOrderItemTable,purchaseOrderTable,purchaseTable,receivableTable,reportScheduleTable,returnItemTable,returnTable,roleTable,saleItemTable,saleTable,schemas,settlementTable,shiftTable,stockAdjustmentTable,stockOpnameItemTable,stockOpnameTable,supplierTable,taxRateTable,transactionTable,uomTable,userTable});
18
22
  /*! For license information please see index.cjs.js.LEGAL.txt */