ofpos-shared-core 1.1.0 → 2.0.0-alpha.0
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/IntegrationServices.d.ts +0 -4
- package/dist/PosCore.d.ts +46 -1
- package/dist/data/schema.d.ts +1 -3
- package/dist/finance/offinanceProjection.d.ts +37 -0
- package/dist/index.browser.mjs +4 -4
- package/dist/index.cjs.js +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.esm.js +4 -4
- package/dist/index.umd.js +4 -4
- package/dist/integration/NotificationAdapter.d.ts +6 -67
- package/dist/integration/authorizationService.d.ts +2 -19
- package/dist/integration/changeQueuePort.d.ts +5 -0
- package/dist/integration/loggerAdapter.d.ts +6 -43
- package/dist/integration/socket.d.ts +13 -0
- package/dist/integration/userService.d.ts +17 -32
- package/dist/models/User.d.ts +0 -6
- package/dist/services/bomService.d.ts +1 -1
- package/dist/services/categoryService.d.ts +1 -1
- package/dist/services/customerGroupService.d.ts +1 -1
- package/dist/services/customerService.d.ts +1 -1
- package/dist/services/expenseService.d.ts +1 -1
- package/dist/services/exportAdapter.d.ts +6 -46
- package/dist/services/financialSettingService.d.ts +1 -1
- package/dist/services/historyService.d.ts +1 -1
- package/dist/services/inventoryLogService.d.ts +2 -1
- package/dist/services/inventoryService.d.ts +7 -1
- package/dist/services/orderItemService.d.ts +1 -1
- package/dist/services/orderService.d.ts +1 -1
- package/dist/services/payableService.d.ts +1 -1
- package/dist/services/priceHistoryService.d.ts +1 -1
- package/dist/services/priceTierService.d.ts +1 -1
- package/dist/services/productService.d.ts +1 -1
- package/dist/services/promotionService.d.ts +1 -1
- package/dist/services/purchaseItemService.d.ts +1 -1
- package/dist/services/purchaseOrderItemService.d.ts +1 -1
- package/dist/services/purchaseOrderService.d.ts +1 -1
- package/dist/services/purchaseService.d.ts +3 -1
- package/dist/services/receivableService.d.ts +1 -1
- package/dist/services/reportScheduleService.d.ts +1 -1
- package/dist/services/reportingService.d.ts +1 -1
- package/dist/services/returnItemService.d.ts +1 -1
- package/dist/services/returnService.d.ts +1 -1
- package/dist/services/roleService.d.ts +1 -1
- package/dist/services/saleItemService.d.ts +1 -1
- package/dist/services/saleService.d.ts +2 -1
- package/dist/services/settlementService.d.ts +1 -1
- package/dist/services/shiftService.d.ts +1 -1
- package/dist/services/stockAdjustmentService.d.ts +1 -1
- package/dist/services/stockOpnameItemService.d.ts +1 -1
- package/dist/services/stockOpnameService.d.ts +1 -1
- package/dist/services/supplierService.d.ts +1 -1
- package/dist/services/taxRateService.d.ts +1 -1
- package/dist/services/transactionService.d.ts +1 -1
- package/dist/services/uiProductService.d.ts +0 -1
- package/dist/services/uomService.d.ts +1 -1
- package/dist/services/userService.d.ts +1 -1
- package/dist/stores/storageAdapter.d.ts +8 -39
- package/dist/stores/syncService.d.ts +16 -0
- package/package.json +27 -7
- package/dist/data/inMemoryDbAdapter.d.ts +0 -65
- package/dist/data/seed.d.ts +0 -370
- package/dist/integration/ofauthBridge.d.ts +0 -29
- package/dist/integration/ofauthCoreBridge.d.ts +0 -19
package/dist/index.browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var eo=Object.create;var mi=Object.defineProperty;var to=Object.getOwnPropertyDescriptor;var ro=Object.getOwnPropertyNames;var no=Object.getPrototypeOf,io=Object.prototype.hasOwnProperty;var Vt=(g=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(g,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):g)(function(g){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});var te=(g,e)=>()=>(e||g((e={exports:{}}).exports,e),e.exports);var ao=(g,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ro(e))!io.call(g,n)&&n!==t&&mi(g,n,{get:()=>e[n],enumerable:!(r=to(e,n))||r.enumerable});return g};var Ct=(g,e,t)=>(t=g!=null?eo(no(g)):{},ao(e||!g||!g.__esModule?mi(t,"default",{value:g,enumerable:!0}):t,g));var fi=te(()=>{var hi;(function(g){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:o(),r=n(g);typeof t.Reflect!="undefined"&&(r=n(t.Reflect,r)),e(r,t),typeof t.Reflect=="undefined"&&(t.Reflect=g);function n(s,d){return function(c,l){Object.defineProperty(s,c,{configurable:!0,writable:!0,value:l}),d&&d(c,l)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function o(){return i()||a()}})(function(e,t){var r=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",i=n&&typeof Symbol.toPrimitive!="undefined"?Symbol.toPrimitive:"@@toPrimitive",a=n&&typeof Symbol.iterator!="undefined"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",s={__proto__:[]}instanceof Array,d=!o&&!s,c={create:o?function(){return Xe(Object.create(null))}:s?function(){return Xe({__proto__:null})}:function(){return Xe({})},has:d?function(D,E){return r.call(D,E)}:function(D,E){return E in D},get:d?function(D,E){return r.call(D,E)?D[E]:void 0}:function(D,E){return D[E]}},l=Object.getPrototypeOf(Function),u=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Dt(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:wt(),m=typeof WeakMap=="function"?WeakMap:dt(),f=n?Symbol.for("@reflect-metadata:registry"):void 0,b=It(),p=ct(b);function y(D,E,k,N){if(I(k)){if(!we(D))throw new TypeError;if(!Ue(E))throw new TypeError;return M(D,E)}else{if(!we(D))throw new TypeError;if(!Y(E))throw new TypeError;if(!Y(N)&&!I(N)&&!Z(N))throw new TypeError;return Z(N)&&(N=void 0),k=be(k),U(D,E,k,N)}}e("decorate",y);function v(D,E){function k(N,K){if(!Y(N))throw new TypeError;if(!I(K)&&!je(K))throw new TypeError;B(D,E,N,K)}return k}e("metadata",v);function x(D,E,k,N){if(!Y(k))throw new TypeError;return I(N)||(N=be(N)),B(D,E,k,N)}e("defineMetadata",x);function S(D,E,k){if(!Y(E))throw new TypeError;return I(k)||(k=be(k)),F(D,E,k)}e("hasMetadata",S);function A(D,E,k){if(!Y(E))throw new TypeError;return I(k)||(k=be(k)),$(D,E,k)}e("hasOwnMetadata",A);function _(D,E,k){if(!Y(E))throw new TypeError;return I(k)||(k=be(k)),H(D,E,k)}e("getMetadata",_);function T(D,E,k){if(!Y(E))throw new TypeError;return I(k)||(k=be(k)),G(D,E,k)}e("getOwnMetadata",T);function q(D,E){if(!Y(D))throw new TypeError;return I(E)||(E=be(E)),P(D,E)}e("getMetadataKeys",q);function L(D,E){if(!Y(D))throw new TypeError;return I(E)||(E=be(E)),O(D,E)}e("getOwnMetadataKeys",L);function w(D,E,k){if(!Y(E))throw new TypeError;if(I(k)||(k=be(k)),!Y(E))throw new TypeError;I(k)||(k=be(k));var N=pt(E,k,!1);return I(N)?!1:N.OrdinaryDeleteMetadata(D,E,k)}e("deleteMetadata",w);function M(D,E){for(var k=D.length-1;k>=0;--k){var N=D[k],K=N(E);if(!I(K)&&!Z(K)){if(!Ue(K))throw new TypeError;E=K}}return E}function U(D,E,k,N){for(var K=D.length-1;K>=0;--K){var le=D[K],ve=le(E,k,N);if(!I(ve)&&!Z(ve)){if(!Y(ve))throw new TypeError;N=ve}}return N}function F(D,E,k){var N=$(D,E,k);if(N)return!0;var K=Le(E);return Z(K)?!1:F(D,K,k)}function $(D,E,k){var N=pt(E,k,!1);return I(N)?!1:me(N.OrdinaryHasOwnMetadata(D,E,k))}function H(D,E,k){var N=$(D,E,k);if(N)return G(D,E,k);var K=Le(E);if(!Z(K))return H(D,K,k)}function G(D,E,k){var N=pt(E,k,!1);if(!I(N))return N.OrdinaryGetOwnMetadata(D,E,k)}function B(D,E,k,N){var K=pt(k,N,!0);K.OrdinaryDefineOwnMetadata(D,E,k,N)}function P(D,E){var k=O(D,E),N=Le(D);if(N===null)return k;var K=P(N,E);if(K.length<=0)return k;if(k.length<=0)return K;for(var le=new h,ve=[],ee=0,Q=k;ee<Q.length;ee++){var V=Q[ee],j=le.has(V);j||(le.add(V),ve.push(V))}for(var z=0,re=K;z<re.length;z++){var V=re[z],j=le.has(V);j||(le.add(V),ve.push(V))}return ve}function O(D,E){var k=pt(D,E,!1);return k?k.OrdinaryOwnMetadataKeys(D,E):[]}function R(D){if(D===null)return 1;switch(typeof D){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return D===null?1:6;default:return 6}}function I(D){return D===void 0}function Z(D){return D===null}function J(D){return typeof D=="symbol"}function Y(D){return typeof D=="object"?D!==null:typeof D=="function"}function W(D,E){switch(R(D)){case 0:return D;case 1:return D;case 2:return D;case 3:return D;case 4:return D;case 5:return D}var k=E===3?"string":E===5?"number":"default",N=ze(D,i);if(N!==void 0){var K=N.call(D,k);if(Y(K))throw new TypeError;return K}return Re(D,k==="default"?"number":k)}function Re(D,E){if(E==="string"){var k=D.toString;if(ye(k)){var N=k.call(D);if(!Y(N))return N}var K=D.valueOf;if(ye(K)){var N=K.call(D);if(!Y(N))return N}}else{var K=D.valueOf;if(ye(K)){var N=K.call(D);if(!Y(N))return N}var le=D.toString;if(ye(le)){var N=le.call(D);if(!Y(N))return N}}throw new TypeError}function me(D){return!!D}function ue(D){return""+D}function be(D){var E=W(D,3);return J(E)?E:ue(E)}function we(D){return Array.isArray?Array.isArray(D):D instanceof Object?D instanceof Array:Object.prototype.toString.call(D)==="[object Array]"}function ye(D){return typeof D=="function"}function Ue(D){return typeof D=="function"}function je(D){switch(R(D)){case 3:return!0;case 4:return!0;default:return!1}}function He(D,E){return D===E||D!==D&&E!==E}function ze(D,E){var k=D[E];if(k!=null){if(!ye(k))throw new TypeError;return k}}function mt(D){var E=ze(D,a);if(!ye(E))throw new TypeError;var k=E.call(D);if(!Y(k))throw new TypeError;return k}function st(D){return D.value}function Be(D){var E=D.next();return E.done?!1:E}function Fe(D){var E=D.return;E&&E.call(D)}function Le(D){var E=Object.getPrototypeOf(D);if(typeof D!="function"||D===l||E!==l)return E;var k=D.prototype,N=k&&Object.getPrototypeOf(k);if(N==null||N===Object.prototype)return E;var K=N.constructor;return typeof K!="function"||K===D?E:K}function ht(){var D;!I(f)&&typeof t.Reflect!="undefined"&&!(f in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(D=lt(t.Reflect));var E,k,N,K=new m,le={registerProvider:ve,getProvider:Q,setProvider:j};return le;function ve(z){if(!Object.isExtensible(le))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case D===z:break;case I(E):E=z;break;case E===z:break;case I(k):k=z;break;case k===z:break;default:N===void 0&&(N=new h),N.add(z);break}}function ee(z,re){if(!I(E)){if(E.isProviderFor(z,re))return E;if(!I(k)){if(k.isProviderFor(z,re))return E;if(!I(N))for(var de=mt(N);;){var Se=Be(de);if(!Se)return;var Ke=st(Se);if(Ke.isProviderFor(z,re))return Fe(de),Ke}}}if(!I(D)&&D.isProviderFor(z,re))return D}function Q(z,re){var de=K.get(z),Se;return I(de)||(Se=de.get(re)),I(Se)&&(Se=ee(z,re),I(Se)||(I(de)&&(de=new u,K.set(z,de)),de.set(re,Se))),Se}function V(z){if(I(z))throw new TypeError;return E===z||k===z||!I(N)&&N.has(z)}function j(z,re,de){if(!V(de))throw new Error("Metadata provider not registered.");var Se=Q(z,re);if(Se!==de){if(!I(Se))return!1;var Ke=K.get(z);I(Ke)&&(Ke=new u,K.set(z,Ke)),Ke.set(re,de)}return!0}}function It(){var D;return!I(f)&&Y(t.Reflect)&&Object.isExtensible(t.Reflect)&&(D=t.Reflect[f]),I(D)&&(D=ht()),!I(f)&&Y(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:D}),D}function ct(D){var E=new m,k={isProviderFor:function(V,j){var z=E.get(V);return I(z)?!1:z.has(j)},OrdinaryDefineOwnMetadata:ve,OrdinaryHasOwnMetadata:K,OrdinaryGetOwnMetadata:le,OrdinaryOwnMetadataKeys:ee,OrdinaryDeleteMetadata:Q};return b.registerProvider(k),k;function N(V,j,z){var re=E.get(V),de=!1;if(I(re)){if(!z)return;re=new u,E.set(V,re),de=!0}var Se=re.get(j);if(I(Se)){if(!z)return;if(Se=new u,re.set(j,Se),!D.setProvider(V,j,k))throw re.delete(j),de&&E.delete(V),new Error("Wrong provider for target.")}return Se}function K(V,j,z){var re=N(j,z,!1);return I(re)?!1:me(re.has(V))}function le(V,j,z){var re=N(j,z,!1);if(!I(re))return re.get(V)}function ve(V,j,z,re){var de=N(z,re,!0);de.set(V,j)}function ee(V,j){var z=[],re=N(V,j,!1);if(I(re))return z;for(var de=re.keys(),Se=mt(de),Ke=0;;){var Bt=Be(Se);if(!Bt)return z.length=Ke,z;var Gn=st(Bt);try{z[Ke]=Gn}catch($t){try{Fe(Se)}finally{throw $t}}Ke++}}function Q(V,j,z){var re=N(j,z,!1);if(I(re)||!re.delete(V))return!1;if(re.size===0){var de=E.get(j);I(de)||(de.delete(z),de.size===0&&E.delete(de))}return!0}}function lt(D){var E=D.defineMetadata,k=D.hasOwnMetadata,N=D.getOwnMetadata,K=D.getOwnMetadataKeys,le=D.deleteMetadata,ve=new m,ee={isProviderFor:function(Q,V){var j=ve.get(Q);return!I(j)&&j.has(V)?!0:K(Q,V).length?(I(j)&&(j=new h,ve.set(Q,j)),j.add(V),!0):!1},OrdinaryDefineOwnMetadata:E,OrdinaryHasOwnMetadata:k,OrdinaryGetOwnMetadata:N,OrdinaryOwnMetadataKeys:K,OrdinaryDeleteMetadata:le};return ee}function pt(D,E,k){var N=b.getProvider(D,E);if(!I(N))return N;if(k){if(b.setProvider(D,E,p))return p;throw new Error("Illegal state.")}}function Dt(){var D={},E=[],k=(function(){function ee(Q,V,j){this._index=0,this._keys=Q,this._values=V,this._selector=j}return ee.prototype["@@iterator"]=function(){return this},ee.prototype[a]=function(){return this},ee.prototype.next=function(){var Q=this._index;if(Q>=0&&Q<this._keys.length){var V=this._selector(this._keys[Q],this._values[Q]);return Q+1>=this._keys.length?(this._index=-1,this._keys=E,this._values=E):this._index++,{value:V,done:!1}}return{value:void 0,done:!0}},ee.prototype.throw=function(Q){throw this._index>=0&&(this._index=-1,this._keys=E,this._values=E),Q},ee.prototype.return=function(Q){return this._index>=0&&(this._index=-1,this._keys=E,this._values=E),{value:Q,done:!0}},ee})(),N=(function(){function ee(){this._keys=[],this._values=[],this._cacheKey=D,this._cacheIndex=-2}return Object.defineProperty(ee.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),ee.prototype.has=function(Q){return this._find(Q,!1)>=0},ee.prototype.get=function(Q){var V=this._find(Q,!1);return V>=0?this._values[V]:void 0},ee.prototype.set=function(Q,V){var j=this._find(Q,!0);return this._values[j]=V,this},ee.prototype.delete=function(Q){var V=this._find(Q,!1);if(V>=0){for(var j=this._keys.length,z=V+1;z<j;z++)this._keys[z-1]=this._keys[z],this._values[z-1]=this._values[z];return this._keys.length--,this._values.length--,He(Q,this._cacheKey)&&(this._cacheKey=D,this._cacheIndex=-2),!0}return!1},ee.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=D,this._cacheIndex=-2},ee.prototype.keys=function(){return new k(this._keys,this._values,K)},ee.prototype.values=function(){return new k(this._keys,this._values,le)},ee.prototype.entries=function(){return new k(this._keys,this._values,ve)},ee.prototype["@@iterator"]=function(){return this.entries()},ee.prototype[a]=function(){return this.entries()},ee.prototype._find=function(Q,V){if(!He(this._cacheKey,Q)){this._cacheIndex=-1;for(var j=0;j<this._keys.length;j++)if(He(this._keys[j],Q)){this._cacheIndex=j;break}}return this._cacheIndex<0&&V&&(this._cacheIndex=this._keys.length,this._keys.push(Q),this._values.push(void 0)),this._cacheIndex},ee})();return N;function K(ee,Q){return ee}function le(ee,Q){return Q}function ve(ee,Q){return[ee,Q]}}function wt(){var D=(function(){function E(){this._map=new u}return Object.defineProperty(E.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),E.prototype.has=function(k){return this._map.has(k)},E.prototype.add=function(k){return this._map.set(k,k),this},E.prototype.delete=function(k){return this._map.delete(k)},E.prototype.clear=function(){this._map.clear()},E.prototype.keys=function(){return this._map.keys()},E.prototype.values=function(){return this._map.keys()},E.prototype.entries=function(){return this._map.entries()},E.prototype["@@iterator"]=function(){return this.keys()},E.prototype[a]=function(){return this.keys()},E})();return D}function dt(){var D=16,E=c.create(),k=N();return(function(){function Q(){this._key=N()}return Q.prototype.has=function(V){var j=K(V,!1);return j!==void 0?c.has(j,this._key):!1},Q.prototype.get=function(V){var j=K(V,!1);return j!==void 0?c.get(j,this._key):void 0},Q.prototype.set=function(V,j){var z=K(V,!0);return z[this._key]=j,this},Q.prototype.delete=function(V){var j=K(V,!1);return j!==void 0?delete j[this._key]:!1},Q.prototype.clear=function(){this._key=N()},Q})();function N(){var Q;do Q="@@WeakMap@@"+ee();while(c.has(E,Q));return E[Q]=!0,Q}function K(Q,V){if(!r.call(Q,k)){if(!V)return;Object.defineProperty(Q,k,{value:c.create()})}return Q[k]}function le(Q,V){for(var j=0;j<V;++j)Q[j]=Math.random()*255|0;return Q}function ve(Q){if(typeof Uint8Array=="function"){var V=new Uint8Array(Q);return typeof crypto!="undefined"?crypto.getRandomValues(V):typeof msCrypto!="undefined"?msCrypto.getRandomValues(V):le(V,Q),V}return le(new Array(Q),Q)}function ee(){var Q=ve(D);Q[6]=Q[6]&79|64,Q[8]=Q[8]&191|128;for(var V="",j=0;j<D;++j){var z=Q[j];(j===4||j===6||j===8)&&(V+="-"),z<16&&(V+="0"),V+=z.toString(16).toLowerCase()}return V}}function Xe(D){return D.__=void 0,delete D.__,D}})})(hi||(hi={}))});var ne=te((zr,Di)=>{(function(g,e){typeof zr=="object"?Di.exports=zr=e():typeof define=="function"&&define.amd?define([],e):g.CryptoJS=e()})(zr,function(){var g=g||(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 Vt=="function")try{r=Vt("crypto")}catch{}var n=function(){if(r){if(typeof r.getRandomValues=="function")try{return r.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof r.randomBytes=="function")try{return r.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},i=Object.create||(function(){function p(){}return function(y){var v;return p.prototype=y,v=new p,p.prototype=null,v}})(),a={},o=a.lib={},s=o.Base=(function(){return{extend:function(p){var y=i(this);return p&&y.mixIn(p),(!y.hasOwnProperty("init")||this.init===y.init)&&(y.init=function(){y.$super.init.apply(this,arguments)}),y.init.prototype=y,y.$super=this,y},create:function(){var p=this.extend();return p.init.apply(p,arguments),p},init:function(){},mixIn:function(p){for(var y in p)p.hasOwnProperty(y)&&(this[y]=p[y]);p.hasOwnProperty("toString")&&(this.toString=p.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),d=o.WordArray=s.extend({init:function(p,y){p=this.words=p||[],y!=t?this.sigBytes=y:this.sigBytes=p.length*4},toString:function(p){return(p||l).stringify(this)},concat:function(p){var y=this.words,v=p.words,x=this.sigBytes,S=p.sigBytes;if(this.clamp(),x%4)for(var A=0;A<S;A++){var _=v[A>>>2]>>>24-A%4*8&255;y[x+A>>>2]|=_<<24-(x+A)%4*8}else for(var T=0;T<S;T+=4)y[x+T>>>2]=v[T>>>2];return this.sigBytes+=S,this},clamp:function(){var p=this.words,y=this.sigBytes;p[y>>>2]&=4294967295<<32-y%4*8,p.length=e.ceil(y/4)},clone:function(){var p=s.clone.call(this);return p.words=this.words.slice(0),p},random:function(p){for(var y=[],v=0;v<p;v+=4)y.push(n());return new d.init(y,p)}}),c=a.enc={},l=c.Hex={stringify:function(p){for(var y=p.words,v=p.sigBytes,x=[],S=0;S<v;S++){var A=y[S>>>2]>>>24-S%4*8&255;x.push((A>>>4).toString(16)),x.push((A&15).toString(16))}return x.join("")},parse:function(p){for(var y=p.length,v=[],x=0;x<y;x+=2)v[x>>>3]|=parseInt(p.substr(x,2),16)<<24-x%8*4;return new d.init(v,y/2)}},u=c.Latin1={stringify:function(p){for(var y=p.words,v=p.sigBytes,x=[],S=0;S<v;S++){var A=y[S>>>2]>>>24-S%4*8&255;x.push(String.fromCharCode(A))}return x.join("")},parse:function(p){for(var y=p.length,v=[],x=0;x<y;x++)v[x>>>2]|=(p.charCodeAt(x)&255)<<24-x%4*8;return new d.init(v,y)}},h=c.Utf8={stringify:function(p){try{return decodeURIComponent(escape(u.stringify(p)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(p){return u.parse(unescape(encodeURIComponent(p)))}},m=o.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new d.init,this._nDataBytes=0},_append:function(p){typeof p=="string"&&(p=h.parse(p)),this._data.concat(p),this._nDataBytes+=p.sigBytes},_process:function(p){var y,v=this._data,x=v.words,S=v.sigBytes,A=this.blockSize,_=A*4,T=S/_;p?T=e.ceil(T):T=e.max((T|0)-this._minBufferSize,0);var q=T*A,L=e.min(q*4,S);if(q){for(var w=0;w<q;w+=A)this._doProcessBlock(x,w);y=x.splice(0,q),v.sigBytes-=L}return new d.init(y,L)},clone:function(){var p=s.clone.call(this);return p._data=this._data.clone(),p},_minBufferSize:0}),f=o.Hasher=m.extend({cfg:s.extend(),init:function(p){this.cfg=this.cfg.extend(p),this.reset()},reset:function(){m.reset.call(this),this._doReset()},update:function(p){return this._append(p),this._process(),this},finalize:function(p){p&&this._append(p);var y=this._doFinalize();return y},blockSize:512/32,_createHelper:function(p){return function(y,v){return new p.init(v).finalize(y)}},_createHmacHelper:function(p){return function(y,v){return new b.HMAC.init(p,v).finalize(y)}}}),b=a.algo={};return a})(Math);return g})});var Et=te((Kr,wi)=>{(function(g,e){typeof Kr=="object"?wi.exports=Kr=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(Kr,function(g){return(function(e){var t=g,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[],s=[];(function(){function l(f){for(var b=e.sqrt(f),p=2;p<=b;p++)if(!(f%p))return!1;return!0}function u(f){return(f-(f|0))*4294967296|0}for(var h=2,m=0;m<64;)l(h)&&(m<8&&(o[m]=u(e.pow(h,1/2))),s[m]=u(e.pow(h,1/3)),m++),h++})();var d=[],c=a.SHA256=i.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(l,u){for(var h=this._hash.words,m=h[0],f=h[1],b=h[2],p=h[3],y=h[4],v=h[5],x=h[6],S=h[7],A=0;A<64;A++){if(A<16)d[A]=l[u+A]|0;else{var _=d[A-15],T=(_<<25|_>>>7)^(_<<14|_>>>18)^_>>>3,q=d[A-2],L=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;d[A]=T+d[A-7]+L+d[A-16]}var w=y&v^~y&x,M=m&f^m&b^f&b,U=(m<<30|m>>>2)^(m<<19|m>>>13)^(m<<10|m>>>22),F=(y<<26|y>>>6)^(y<<21|y>>>11)^(y<<7|y>>>25),$=S+F+w+s[A]+d[A],H=U+M;S=x,x=v,v=y,y=p+$|0,p=b,b=f,f=m,m=$+H|0}h[0]=h[0]+m|0,h[1]=h[1]+f|0,h[2]=h[2]+b|0,h[3]=h[3]+p|0,h[4]=h[4]+y|0,h[5]=h[5]+v|0,h[6]=h[6]+x|0,h[7]=h[7]+S|0},_doFinalize:function(){var l=this._data,u=l.words,h=this._nDataBytes*8,m=l.sigBytes*8;return u[m>>>5]|=128<<24-m%32,u[(m+64>>>9<<4)+14]=e.floor(h/4294967296),u[(m+64>>>9<<4)+15]=h,l.sigBytes=u.length*4,this._process(),this._hash},clone:function(){var l=i.clone.call(this);return l._hash=this._hash.clone(),l}});t.SHA256=i._createHelper(c),t.HmacSHA256=i._createHmacHelper(c)})(Math),g.SHA256})});var qt=te((Wr,Ei)=>{(function(g,e){typeof Wr=="object"?Ei.exports=Wr=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(Wr,function(g){return(function(e){var t=g,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,l=[],u=0;u<c;u++){var h=d[u];l.push(h.high),l.push(h.low)}return i.create(l,this.sigBytes)},clone:function(){for(var d=n.clone.call(this),c=d.words=this.words.slice(0),l=c.length,u=0;u<l;u++)c[u]=c[u].clone();return d}})})(),g})});var Ri=te((Zr,Oi)=>{(function(g,e){typeof Zr=="object"?Oi.exports=Zr=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(Zr,function(g){return(function(){if(typeof ArrayBuffer=="function"){var e=g,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}})(),g.lib.WordArray})});var _i=te((Yr,Ti)=>{(function(g,e){typeof Yr=="object"?Ti.exports=Yr=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(Yr,function(g){return(function(){var e=g,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=[],l=0;l<d;l+=2){var u=s[l>>>2]>>>16-l%4*8&65535;c.push(String.fromCharCode(u))}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=[],l=0;l<d;l+=2){var u=a(s[l>>>2]>>>16-l%4*8&65535);c.push(String.fromCharCode(u))}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}})(),g.enc.Utf16})});var St=te((Xr,ki)=>{(function(g,e){typeof Xr=="object"?ki.exports=Xr=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(Xr,function(g){return(function(){var e=g,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 l=[],u=0;u<d;u+=3)for(var h=s[u>>>2]>>>24-u%4*8&255,m=s[u+1>>>2]>>>24-(u+1)%4*8&255,f=s[u+2>>>2]>>>24-(u+2)%4*8&255,b=h<<16|m<<8|f,p=0;p<4&&u+p*.75<d;p++)l.push(c.charAt(b>>>6*(3-p)&63));var y=c.charAt(64);if(y)for(;l.length%4;)l.push(y);return l.join("")},parse:function(o){var s=o.length,d=this._map,c=this._reverseMap;if(!c){c=this._reverseMap=[];for(var l=0;l<d.length;l++)c[d.charCodeAt(l)]=l}var u=d.charAt(64);if(u){var h=o.indexOf(u);h!==-1&&(s=h)}return a(o,s,c)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function a(o,s,d){for(var c=[],l=0,u=0;u<s;u++)if(u%4){var h=d[o.charCodeAt(u-1)]<<u%4*2,m=d[o.charCodeAt(u)]>>>6-u%4*2,f=h|m;c[l>>>2]|=f<<24-l%4*8,l++}return r.create(c,l)}})(),g.enc.Base64})});var Bi=te((Jr,Fi)=>{(function(g,e){typeof Jr=="object"?Fi.exports=Jr=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(Jr,function(g){return(function(){var e=g,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,l=s?this._safe_map:this._map;o.clamp();for(var u=[],h=0;h<c;h+=3)for(var m=d[h>>>2]>>>24-h%4*8&255,f=d[h+1>>>2]>>>24-(h+1)%4*8&255,b=d[h+2>>>2]>>>24-(h+2)%4*8&255,p=m<<16|f<<8|b,y=0;y<4&&h+y*.75<c;y++)u.push(l.charAt(p>>>6*(3-y)&63));var v=l.charAt(64);if(v)for(;u.length%4;)u.push(v);return u.join("")},parse:function(o,s){s===void 0&&(s=!0);var d=o.length,c=s?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var u=0;u<c.length;u++)l[c.charCodeAt(u)]=u}var h=c.charAt(64);if(h){var m=o.indexOf(h);m!==-1&&(d=m)}return a(o,d,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function a(o,s,d){for(var c=[],l=0,u=0;u<s;u++)if(u%4){var h=d[o.charCodeAt(u-1)]<<u%4*2,m=d[o.charCodeAt(u)]>>>6-u%4*2,f=h|m;c[l>>>2]|=f<<24-l%4*8,l++}return r.create(c,l)}})(),g.enc.Base64url})});var At=te((en,Mi)=>{(function(g,e){typeof en=="object"?Mi.exports=en=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(en,function(g){return(function(e){var t=g,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,m){for(var f=0;f<16;f++){var b=m+f,p=h[b];h[b]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360}var y=this._hash.words,v=h[m+0],x=h[m+1],S=h[m+2],A=h[m+3],_=h[m+4],T=h[m+5],q=h[m+6],L=h[m+7],w=h[m+8],M=h[m+9],U=h[m+10],F=h[m+11],$=h[m+12],H=h[m+13],G=h[m+14],B=h[m+15],P=y[0],O=y[1],R=y[2],I=y[3];P=d(P,O,R,I,v,7,o[0]),I=d(I,P,O,R,x,12,o[1]),R=d(R,I,P,O,S,17,o[2]),O=d(O,R,I,P,A,22,o[3]),P=d(P,O,R,I,_,7,o[4]),I=d(I,P,O,R,T,12,o[5]),R=d(R,I,P,O,q,17,o[6]),O=d(O,R,I,P,L,22,o[7]),P=d(P,O,R,I,w,7,o[8]),I=d(I,P,O,R,M,12,o[9]),R=d(R,I,P,O,U,17,o[10]),O=d(O,R,I,P,F,22,o[11]),P=d(P,O,R,I,$,7,o[12]),I=d(I,P,O,R,H,12,o[13]),R=d(R,I,P,O,G,17,o[14]),O=d(O,R,I,P,B,22,o[15]),P=c(P,O,R,I,x,5,o[16]),I=c(I,P,O,R,q,9,o[17]),R=c(R,I,P,O,F,14,o[18]),O=c(O,R,I,P,v,20,o[19]),P=c(P,O,R,I,T,5,o[20]),I=c(I,P,O,R,U,9,o[21]),R=c(R,I,P,O,B,14,o[22]),O=c(O,R,I,P,_,20,o[23]),P=c(P,O,R,I,M,5,o[24]),I=c(I,P,O,R,G,9,o[25]),R=c(R,I,P,O,A,14,o[26]),O=c(O,R,I,P,w,20,o[27]),P=c(P,O,R,I,H,5,o[28]),I=c(I,P,O,R,S,9,o[29]),R=c(R,I,P,O,L,14,o[30]),O=c(O,R,I,P,$,20,o[31]),P=l(P,O,R,I,T,4,o[32]),I=l(I,P,O,R,w,11,o[33]),R=l(R,I,P,O,F,16,o[34]),O=l(O,R,I,P,G,23,o[35]),P=l(P,O,R,I,x,4,o[36]),I=l(I,P,O,R,_,11,o[37]),R=l(R,I,P,O,L,16,o[38]),O=l(O,R,I,P,U,23,o[39]),P=l(P,O,R,I,H,4,o[40]),I=l(I,P,O,R,v,11,o[41]),R=l(R,I,P,O,A,16,o[42]),O=l(O,R,I,P,q,23,o[43]),P=l(P,O,R,I,M,4,o[44]),I=l(I,P,O,R,$,11,o[45]),R=l(R,I,P,O,B,16,o[46]),O=l(O,R,I,P,S,23,o[47]),P=u(P,O,R,I,v,6,o[48]),I=u(I,P,O,R,L,10,o[49]),R=u(R,I,P,O,G,15,o[50]),O=u(O,R,I,P,T,21,o[51]),P=u(P,O,R,I,$,6,o[52]),I=u(I,P,O,R,A,10,o[53]),R=u(R,I,P,O,U,15,o[54]),O=u(O,R,I,P,x,21,o[55]),P=u(P,O,R,I,w,6,o[56]),I=u(I,P,O,R,B,10,o[57]),R=u(R,I,P,O,q,15,o[58]),O=u(O,R,I,P,H,21,o[59]),P=u(P,O,R,I,_,6,o[60]),I=u(I,P,O,R,F,10,o[61]),R=u(R,I,P,O,S,15,o[62]),O=u(O,R,I,P,M,21,o[63]),y[0]=y[0]+P|0,y[1]=y[1]+O|0,y[2]=y[2]+R|0,y[3]=y[3]+I|0},_doFinalize:function(){var h=this._data,m=h.words,f=this._nDataBytes*8,b=h.sigBytes*8;m[b>>>5]|=128<<24-b%32;var p=e.floor(f/4294967296),y=f;m[(b+64>>>9<<4)+15]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,m[(b+64>>>9<<4)+14]=(y<<8|y>>>24)&16711935|(y<<24|y>>>8)&4278255360,h.sigBytes=(m.length+1)*4,this._process();for(var v=this._hash,x=v.words,S=0;S<4;S++){var A=x[S];x[S]=(A<<8|A>>>24)&16711935|(A<<24|A>>>8)&4278255360}return v},clone:function(){var h=i.clone.call(this);return h._hash=this._hash.clone(),h}});function d(h,m,f,b,p,y,v){var x=h+(m&f|~m&b)+p+v;return(x<<y|x>>>32-y)+m}function c(h,m,f,b,p,y,v){var x=h+(m&b|f&~b)+p+v;return(x<<y|x>>>32-y)+m}function l(h,m,f,b,p,y,v){var x=h+(m^f^b)+p+v;return(x<<y|x>>>32-y)+m}function u(h,m,f,b,p,y,v){var x=h+(f^(m|~b))+p+v;return(x<<y|x>>>32-y)+m}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)})(Math),g.MD5})});var ti=te((tn,qi)=>{(function(g,e){typeof tn=="object"?qi.exports=tn=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(tn,function(g){return(function(){var e=g,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,l=c[0],u=c[1],h=c[2],m=c[3],f=c[4],b=0;b<80;b++){if(b<16)a[b]=s[d+b]|0;else{var p=a[b-3]^a[b-8]^a[b-14]^a[b-16];a[b]=p<<1|p>>>31}var y=(l<<5|l>>>27)+f+a[b];b<20?y+=(u&h|~u&m)+1518500249:b<40?y+=(u^h^m)+1859775393:b<60?y+=(u&h|u&m|h&m)-1894007588:y+=(u^h^m)-899497514,f=m,m=h,h=u<<30|u>>>2,u=l,l=y}c[0]=c[0]+l|0,c[1]=c[1]+u|0,c[2]=c[2]+h|0,c[3]=c[3]+m|0,c[4]=c[4]+f|0},_doFinalize:function(){var s=this._data,d=s.words,c=this._nDataBytes*8,l=s.sigBytes*8;return d[l>>>5]|=128<<24-l%32,d[(l+64>>>9<<4)+14]=Math.floor(c/4294967296),d[(l+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)})(),g.SHA1})});var Ni=te((rn,Li)=>{(function(g,e,t){typeof rn=="object"?Li.exports=rn=e(ne(),Et()):typeof define=="function"&&define.amd?define(["./core","./sha256"],e):e(g.CryptoJS)})(rn,function(g){return(function(){var e=g,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)})(),g.SHA224})});var ri=te((nn,Ui)=>{(function(g,e,t){typeof nn=="object"?Ui.exports=nn=e(ne(),qt()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(g.CryptoJS)})(nn,function(g){return(function(){var e=g,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 u=0;u<80;u++)c[u]=s()})();var l=o.SHA512=r.extend({_doReset:function(){this._hash=new a.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(u,h){for(var m=this._hash.words,f=m[0],b=m[1],p=m[2],y=m[3],v=m[4],x=m[5],S=m[6],A=m[7],_=f.high,T=f.low,q=b.high,L=b.low,w=p.high,M=p.low,U=y.high,F=y.low,$=v.high,H=v.low,G=x.high,B=x.low,P=S.high,O=S.low,R=A.high,I=A.low,Z=_,J=T,Y=q,W=L,Re=w,me=M,ue=U,be=F,we=$,ye=H,Ue=G,je=B,He=P,ze=O,mt=R,st=I,Be=0;Be<80;Be++){var Fe,Le,ht=c[Be];if(Be<16)Le=ht.high=u[h+Be*2]|0,Fe=ht.low=u[h+Be*2+1]|0;else{var It=c[Be-15],ct=It.high,lt=It.low,pt=(ct>>>1|lt<<31)^(ct>>>8|lt<<24)^ct>>>7,Dt=(lt>>>1|ct<<31)^(lt>>>8|ct<<24)^(lt>>>7|ct<<25),wt=c[Be-2],dt=wt.high,Xe=wt.low,D=(dt>>>19|Xe<<13)^(dt<<3|Xe>>>29)^dt>>>6,E=(Xe>>>19|dt<<13)^(Xe<<3|dt>>>29)^(Xe>>>6|dt<<26),k=c[Be-7],N=k.high,K=k.low,le=c[Be-16],ve=le.high,ee=le.low;Fe=Dt+K,Le=pt+N+(Fe>>>0<Dt>>>0?1:0),Fe=Fe+E,Le=Le+D+(Fe>>>0<E>>>0?1:0),Fe=Fe+ee,Le=Le+ve+(Fe>>>0<ee>>>0?1:0),ht.high=Le,ht.low=Fe}var Q=we&Ue^~we&He,V=ye&je^~ye&ze,j=Z&Y^Z&Re^Y&Re,z=J&W^J&me^W&me,re=(Z>>>28|J<<4)^(Z<<30|J>>>2)^(Z<<25|J>>>7),de=(J>>>28|Z<<4)^(J<<30|Z>>>2)^(J<<25|Z>>>7),Se=(we>>>14|ye<<18)^(we>>>18|ye<<14)^(we<<23|ye>>>9),Ke=(ye>>>14|we<<18)^(ye>>>18|we<<14)^(ye<<23|we>>>9),Bt=d[Be],Gn=Bt.high,$t=Bt.low,Ge=st+Ke,vt=mt+Se+(Ge>>>0<st>>>0?1:0),Ge=Ge+V,vt=vt+Q+(Ge>>>0<V>>>0?1:0),Ge=Ge+$t,vt=vt+Gn+(Ge>>>0<$t>>>0?1:0),Ge=Ge+Fe,vt=vt+Le+(Ge>>>0<Fe>>>0?1:0),pi=de+z,Ja=re+j+(pi>>>0<de>>>0?1:0);mt=He,st=ze,He=Ue,ze=je,Ue=we,je=ye,ye=be+Ge|0,we=ue+vt+(ye>>>0<be>>>0?1:0)|0,ue=Re,be=me,Re=Y,me=W,Y=Z,W=J,J=Ge+pi|0,Z=vt+Ja+(J>>>0<Ge>>>0?1:0)|0}T=f.low=T+J,f.high=_+Z+(T>>>0<J>>>0?1:0),L=b.low=L+W,b.high=q+Y+(L>>>0<W>>>0?1:0),M=p.low=M+me,p.high=w+Re+(M>>>0<me>>>0?1:0),F=y.low=F+be,y.high=U+ue+(F>>>0<be>>>0?1:0),H=v.low=H+ye,v.high=$+we+(H>>>0<ye>>>0?1:0),B=x.low=B+je,x.high=G+Ue+(B>>>0<je>>>0?1:0),O=S.low=O+ze,S.high=P+He+(O>>>0<ze>>>0?1:0),I=A.low=I+st,A.high=R+mt+(I>>>0<st>>>0?1:0)},_doFinalize:function(){var u=this._data,h=u.words,m=this._nDataBytes*8,f=u.sigBytes*8;h[f>>>5]|=128<<24-f%32,h[(f+128>>>10<<5)+30]=Math.floor(m/4294967296),h[(f+128>>>10<<5)+31]=m,u.sigBytes=h.length*4,this._process();var b=this._hash.toX32();return b},clone:function(){var u=r.clone.call(this);return u._hash=this._hash.clone(),u},blockSize:1024/32});e.SHA512=r._createHelper(l),e.HmacSHA512=r._createHmacHelper(l)})(),g.SHA512})});var Qi=te((an,Hi)=>{(function(g,e,t){typeof an=="object"?Hi.exports=an=e(ne(),qt(),ri()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./sha512"],e):e(g.CryptoJS)})(an,function(g){return(function(){var e=g,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)})(),g.SHA384})});var Vi=te((on,$i)=>{(function(g,e,t){typeof on=="object"?$i.exports=on=e(ne(),qt()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(g.CryptoJS)})(on,function(g){return(function(e){var t=g,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.x64,o=a.Word,s=t.algo,d=[],c=[],l=[];(function(){for(var m=1,f=0,b=0;b<24;b++){d[m+5*f]=(b+1)*(b+2)/2%64;var p=f%5,y=(2*m+3*f)%5;m=p,f=y}for(var m=0;m<5;m++)for(var f=0;f<5;f++)c[m+5*f]=f+(2*m+3*f)%5*5;for(var v=1,x=0;x<24;x++){for(var S=0,A=0,_=0;_<7;_++){if(v&1){var T=(1<<_)-1;T<32?A^=1<<T:S^=1<<T-32}v&128?v=v<<1^113:v<<=1}l[x]=o.create(S,A)}})();var u=[];(function(){for(var m=0;m<25;m++)u[m]=o.create()})();var h=s.SHA3=i.extend({cfg:i.cfg.extend({outputLength:512}),_doReset:function(){for(var m=this._state=[],f=0;f<25;f++)m[f]=new o.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(m,f){for(var b=this._state,p=this.blockSize/2,y=0;y<p;y++){var v=m[f+2*y],x=m[f+2*y+1];v=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,x=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360;var S=b[y];S.high^=x,S.low^=v}for(var A=0;A<24;A++){for(var _=0;_<5;_++){for(var T=0,q=0,L=0;L<5;L++){var S=b[_+5*L];T^=S.high,q^=S.low}var w=u[_];w.high=T,w.low=q}for(var _=0;_<5;_++)for(var M=u[(_+4)%5],U=u[(_+1)%5],F=U.high,$=U.low,T=M.high^(F<<1|$>>>31),q=M.low^($<<1|F>>>31),L=0;L<5;L++){var S=b[_+5*L];S.high^=T,S.low^=q}for(var H=1;H<25;H++){var T,q,S=b[H],G=S.high,B=S.low,P=d[H];P<32?(T=G<<P|B>>>32-P,q=B<<P|G>>>32-P):(T=B<<P-32|G>>>64-P,q=G<<P-32|B>>>64-P);var O=u[c[H]];O.high=T,O.low=q}var R=u[0],I=b[0];R.high=I.high,R.low=I.low;for(var _=0;_<5;_++)for(var L=0;L<5;L++){var H=_+5*L,S=b[H],Z=u[H],J=u[(_+1)%5+5*L],Y=u[(_+2)%5+5*L];S.high=Z.high^~J.high&Y.high,S.low=Z.low^~J.low&Y.low}var S=b[0],W=l[A];S.high^=W.high,S.low^=W.low}},_doFinalize:function(){var m=this._data,f=m.words,b=this._nDataBytes*8,p=m.sigBytes*8,y=this.blockSize*32;f[p>>>5]|=1<<24-p%32,f[(e.ceil((p+1)/y)*y>>>5)-1]|=128,m.sigBytes=f.length*4,this._process();for(var v=this._state,x=this.cfg.outputLength/8,S=x/8,A=[],_=0;_<S;_++){var T=v[_],q=T.high,L=T.low;q=(q<<8|q>>>24)&16711935|(q<<24|q>>>8)&4278255360,L=(L<<8|L>>>24)&16711935|(L<<24|L>>>8)&4278255360,A.push(L),A.push(q)}return new n.init(A,x)},clone:function(){for(var m=i.clone.call(this),f=m._state=this._state.slice(0),b=0;b<25;b++)f[b]=f[b].clone();return m}});t.SHA3=i._createHelper(h),t.HmacSHA3=i._createHmacHelper(h)})(Math),g.SHA3})});var zi=te((sn,ji)=>{(function(g,e){typeof sn=="object"?ji.exports=sn=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(sn,function(g){return(function(e){var t=g,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]),l=n.create([0,1518500249,1859775393,2400959708,2840853838]),u=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(x,S){for(var A=0;A<16;A++){var _=S+A,T=x[_];x[_]=(T<<8|T>>>24)&16711935|(T<<24|T>>>8)&4278255360}var q=this._hash.words,L=l.words,w=u.words,M=o.words,U=s.words,F=d.words,$=c.words,H,G,B,P,O,R,I,Z,J,Y;R=H=q[0],I=G=q[1],Z=B=q[2],J=P=q[3],Y=O=q[4];for(var W,A=0;A<80;A+=1)W=H+x[S+M[A]]|0,A<16?W+=m(G,B,P)+L[0]:A<32?W+=f(G,B,P)+L[1]:A<48?W+=b(G,B,P)+L[2]:A<64?W+=p(G,B,P)+L[3]:W+=y(G,B,P)+L[4],W=W|0,W=v(W,F[A]),W=W+O|0,H=O,O=P,P=v(B,10),B=G,G=W,W=R+x[S+U[A]]|0,A<16?W+=y(I,Z,J)+w[0]:A<32?W+=p(I,Z,J)+w[1]:A<48?W+=b(I,Z,J)+w[2]:A<64?W+=f(I,Z,J)+w[3]:W+=m(I,Z,J)+w[4],W=W|0,W=v(W,$[A]),W=W+Y|0,R=Y,Y=J,J=v(Z,10),Z=I,I=W;W=q[1]+B+J|0,q[1]=q[2]+P+Y|0,q[2]=q[3]+O+R|0,q[3]=q[4]+H+I|0,q[4]=q[0]+G+Z|0,q[0]=W},_doFinalize:function(){var x=this._data,S=x.words,A=this._nDataBytes*8,_=x.sigBytes*8;S[_>>>5]|=128<<24-_%32,S[(_+64>>>9<<4)+14]=(A<<8|A>>>24)&16711935|(A<<24|A>>>8)&4278255360,x.sigBytes=(S.length+1)*4,this._process();for(var T=this._hash,q=T.words,L=0;L<5;L++){var w=q[L];q[L]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}return T},clone:function(){var x=i.clone.call(this);return x._hash=this._hash.clone(),x}});function m(x,S,A){return x^S^A}function f(x,S,A){return x&S|~x&A}function b(x,S,A){return(x|~S)^A}function p(x,S,A){return x&A|S&~A}function y(x,S,A){return x^(S|~A)}function v(x,S){return x<<S|x>>>32-S}t.RIPEMD160=i._createHelper(h),t.HmacRIPEMD160=i._createHmacHelper(h)})(Math),g.RIPEMD160})});var Lt=te((cn,Ki)=>{(function(g,e){typeof cn=="object"?Ki.exports=cn=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(cn,function(g){(function(){var e=g,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,l=c*4;d.sigBytes>l&&(d=s.finalize(d)),d.clamp();for(var u=this._oKey=d.clone(),h=this._iKey=d.clone(),m=u.words,f=h.words,b=0;b<c;b++)m[b]^=1549556828,f[b]^=909522486;u.sigBytes=h.sigBytes=l,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var d=this._hasher,c=d.finalize(s);d.reset();var l=d.finalize(this._oKey.clone().concat(c));return l}})})()})});var Wi=te((dn,Gi)=>{(function(g,e,t){typeof dn=="object"?Gi.exports=dn=e(ne(),Et(),Lt()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(g.CryptoJS)})(dn,function(g){return(function(){var e=g,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 l=this.cfg,u=o.create(l.hasher,d),h=n.create(),m=n.create([1]),f=h.words,b=m.words,p=l.keySize,y=l.iterations;f.length<p;){var v=u.update(c).finalize(m);u.reset();for(var x=v.words,S=x.length,A=v,_=1;_<y;_++){A=u.finalize(A),u.reset();for(var T=A.words,q=0;q<S;q++)x[q]^=T[q]}h.concat(v),b[0]++}return h.sigBytes=p*4,h}});e.PBKDF2=function(d,c,l){return s.create(l).compute(d,c)}})(),g.PBKDF2})});var bt=te((un,Zi)=>{(function(g,e,t){typeof un=="object"?Zi.exports=un=e(ne(),ti(),Lt()):typeof define=="function"&&define.amd?define(["./core","./sha1","./hmac"],e):e(g.CryptoJS)})(un,function(g){return(function(){var e=g,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,l=this.cfg,u=l.hasher.create(),h=n.create(),m=h.words,f=l.keySize,b=l.iterations;m.length<f;){c&&u.update(c),c=u.update(s).finalize(d),u.reset();for(var p=1;p<b;p++)c=u.finalize(c),u.reset();h.concat(c)}return h.sigBytes=f*4,h}});e.EvpKDF=function(s,d,c){return o.create(c).compute(s,d)}})(),g.EvpKDF})});var ke=te((ln,Yi)=>{(function(g,e,t){typeof ln=="object"?Yi.exports=ln=e(ne(),bt()):typeof define=="function"&&define.amd?define(["./core","./evpkdf"],e):e(g.CryptoJS)})(ln,function(g){g.lib.Cipher||(function(e){var t=g,r=t.lib,n=r.Base,i=r.WordArray,a=r.BufferedBlockAlgorithm,o=t.enc,s=o.Utf8,d=o.Base64,c=t.algo,l=c.EvpKDF,u=r.Cipher=a.extend({cfg:n.extend(),createEncryptor:function(w,M){return this.create(this._ENC_XFORM_MODE,w,M)},createDecryptor:function(w,M){return this.create(this._DEC_XFORM_MODE,w,M)},init:function(w,M,U){this.cfg=this.cfg.extend(U),this._xformMode=w,this._key=M,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(w){return this._append(w),this._process()},finalize:function(w){w&&this._append(w);var M=this._doFinalize();return M},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:(function(){function w(M){return typeof M=="string"?L:_}return function(M){return{encrypt:function(U,F,$){return w(F).encrypt(M,U,F,$)},decrypt:function(U,F,$){return w(F).decrypt(M,U,F,$)}}}})()}),h=r.StreamCipher=u.extend({_doFinalize:function(){var w=this._process(!0);return w},blockSize:1}),m=t.mode={},f=r.BlockCipherMode=n.extend({createEncryptor:function(w,M){return this.Encryptor.create(w,M)},createDecryptor:function(w,M){return this.Decryptor.create(w,M)},init:function(w,M){this._cipher=w,this._iv=M}}),b=m.CBC=(function(){var w=f.extend();w.Encryptor=w.extend({processBlock:function(U,F){var $=this._cipher,H=$.blockSize;M.call(this,U,F,H),$.encryptBlock(U,F),this._prevBlock=U.slice(F,F+H)}}),w.Decryptor=w.extend({processBlock:function(U,F){var $=this._cipher,H=$.blockSize,G=U.slice(F,F+H);$.decryptBlock(U,F),M.call(this,U,F,H),this._prevBlock=G}});function M(U,F,$){var H,G=this._iv;G?(H=G,this._iv=e):H=this._prevBlock;for(var B=0;B<$;B++)U[F+B]^=H[B]}return w})(),p=t.pad={},y=p.Pkcs7={pad:function(w,M){for(var U=M*4,F=U-w.sigBytes%U,$=F<<24|F<<16|F<<8|F,H=[],G=0;G<F;G+=4)H.push($);var B=i.create(H,F);w.concat(B)},unpad:function(w){var M=w.words[w.sigBytes-1>>>2]&255;w.sigBytes-=M}},v=r.BlockCipher=u.extend({cfg:u.cfg.extend({mode:b,padding:y}),reset:function(){var w;u.reset.call(this);var M=this.cfg,U=M.iv,F=M.mode;this._xformMode==this._ENC_XFORM_MODE?w=F.createEncryptor:(w=F.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==w?this._mode.init(this,U&&U.words):(this._mode=w.call(F,this,U&&U.words),this._mode.__creator=w)},_doProcessBlock:function(w,M){this._mode.processBlock(w,M)},_doFinalize:function(){var w,M=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(M.pad(this._data,this.blockSize),w=this._process(!0)):(w=this._process(!0),M.unpad(w)),w},blockSize:128/32}),x=r.CipherParams=n.extend({init:function(w){this.mixIn(w)},toString:function(w){return(w||this.formatter).stringify(this)}}),S=t.format={},A=S.OpenSSL={stringify:function(w){var M,U=w.ciphertext,F=w.salt;return F?M=i.create([1398893684,1701076831]).concat(F).concat(U):M=U,M.toString(d)},parse:function(w){var M,U=d.parse(w),F=U.words;return F[0]==1398893684&&F[1]==1701076831&&(M=i.create(F.slice(2,4)),F.splice(0,4),U.sigBytes-=16),x.create({ciphertext:U,salt:M})}},_=r.SerializableCipher=n.extend({cfg:n.extend({format:A}),encrypt:function(w,M,U,F){F=this.cfg.extend(F);var $=w.createEncryptor(U,F),H=$.finalize(M),G=$.cfg;return x.create({ciphertext:H,key:U,iv:G.iv,algorithm:w,mode:G.mode,padding:G.padding,blockSize:w.blockSize,formatter:F.format})},decrypt:function(w,M,U,F){F=this.cfg.extend(F),M=this._parse(M,F.format);var $=w.createDecryptor(U,F).finalize(M.ciphertext);return $},_parse:function(w,M){return typeof w=="string"?M.parse(w,this):w}}),T=t.kdf={},q=T.OpenSSL={execute:function(w,M,U,F,$){if(F||(F=i.random(64/8)),$)var H=l.create({keySize:M+U,hasher:$}).compute(w,F);else var H=l.create({keySize:M+U}).compute(w,F);var G=i.create(H.words.slice(M),U*4);return H.sigBytes=M*4,x.create({key:H,iv:G,salt:F})}},L=r.PasswordBasedCipher=_.extend({cfg:_.cfg.extend({kdf:q}),encrypt:function(w,M,U,F){F=this.cfg.extend(F);var $=F.kdf.execute(U,w.keySize,w.ivSize,F.salt,F.hasher);F.iv=$.iv;var H=_.encrypt.call(this,w,M,$.key,F);return H.mixIn($),H},decrypt:function(w,M,U,F){F=this.cfg.extend(F),M=this._parse(M,F.format);var $=F.kdf.execute(U,w.keySize,w.ivSize,M.salt,F.hasher);F.iv=$.iv;var H=_.decrypt.call(this,w,M,$.key,F);return H}})})()})});var Ji=te((pn,Xi)=>{(function(g,e,t){typeof pn=="object"?Xi.exports=pn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(pn,function(g){return g.mode.CFB=(function(){var e=g.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})(),g.mode.CFB})});var ta=te((mn,ea)=>{(function(g,e,t){typeof mn=="object"?ea.exports=mn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(mn,function(g){return g.mode.CTR=(function(){var e=g.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})(),g.mode.CTR})});var na=te((hn,ra)=>{(function(g,e,t){typeof hn=="object"?ra.exports=hn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(hn,function(g){return g.mode.CTRGladman=(function(){var e=g.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 l=c.slice(0);o.encryptBlock(l,0);for(var u=0;u<s;u++)i[a+u]^=l[u]}});return e.Decryptor=n,e})(),g.mode.CTRGladman})});var aa=te((fn,ia)=>{(function(g,e,t){typeof fn=="object"?ia.exports=fn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(fn,function(g){return g.mode.OFB=(function(){var e=g.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})(),g.mode.OFB})});var sa=te((yn,oa)=>{(function(g,e,t){typeof yn=="object"?oa.exports=yn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(yn,function(g){return g.mode.ECB=(function(){var e=g.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})(),g.mode.ECB})});var da=te((gn,ca)=>{(function(g,e,t){typeof gn=="object"?ca.exports=gn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(gn,function(g){return g.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}},g.pad.Ansix923})});var la=te((bn,ua)=>{(function(g,e,t){typeof bn=="object"?ua.exports=bn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(bn,function(g){return g.pad.Iso10126={pad:function(e,t){var r=t*4,n=r-e.sigBytes%r;e.concat(g.lib.WordArray.random(n-1)).concat(g.lib.WordArray.create([n<<24],1))},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},g.pad.Iso10126})});var ma=te((vn,pa)=>{(function(g,e,t){typeof vn=="object"?pa.exports=vn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(vn,function(g){return g.pad.Iso97971={pad:function(e,t){e.concat(g.lib.WordArray.create([2147483648],1)),g.pad.ZeroPadding.pad(e,t)},unpad:function(e){g.pad.ZeroPadding.unpad(e),e.sigBytes--}},g.pad.Iso97971})});var fa=te((xn,ha)=>{(function(g,e,t){typeof xn=="object"?ha.exports=xn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(xn,function(g){return g.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}}},g.pad.ZeroPadding})});var ga=te((Sn,ya)=>{(function(g,e,t){typeof Sn=="object"?ya.exports=Sn=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(Sn,function(g){return g.pad.NoPadding={pad:function(){},unpad:function(){}},g.pad.NoPadding})});var va=te((An,ba)=>{(function(g,e,t){typeof An=="object"?ba.exports=An=e(ne(),ke()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(g.CryptoJS)})(An,function(g){return(function(e){var t=g,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})}}})(),g.format.Hex})});var Sa=te((In,xa)=>{(function(g,e,t){typeof In=="object"?xa.exports=In=e(ne(),St(),At(),bt(),ke()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(g.CryptoJS)})(In,function(g){return(function(){var e=g,t=e.lib,r=t.BlockCipher,n=e.algo,i=[],a=[],o=[],s=[],d=[],c=[],l=[],u=[],h=[],m=[];(function(){for(var p=[],y=0;y<256;y++)y<128?p[y]=y<<1:p[y]=y<<1^283;for(var v=0,x=0,y=0;y<256;y++){var S=x^x<<1^x<<2^x<<3^x<<4;S=S>>>8^S&255^99,i[v]=S,a[S]=v;var A=p[v],_=p[A],T=p[_],q=p[S]*257^S*16843008;o[v]=q<<24|q>>>8,s[v]=q<<16|q>>>16,d[v]=q<<8|q>>>24,c[v]=q;var q=T*16843009^_*65537^A*257^v*16843008;l[S]=q<<24|q>>>8,u[S]=q<<16|q>>>16,h[S]=q<<8|q>>>24,m[S]=q,v?(v=A^p[p[p[T^A]]],x^=p[p[x]]):v=x=1}})();var f=[0,1,2,4,8,16,32,64,128,27,54],b=n.AES=r.extend({_doReset:function(){var p;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var y=this._keyPriorReset=this._key,v=y.words,x=y.sigBytes/4,S=this._nRounds=x+6,A=(S+1)*4,_=this._keySchedule=[],T=0;T<A;T++)T<x?_[T]=v[T]:(p=_[T-1],T%x?x>6&&T%x==4&&(p=i[p>>>24]<<24|i[p>>>16&255]<<16|i[p>>>8&255]<<8|i[p&255]):(p=p<<8|p>>>24,p=i[p>>>24]<<24|i[p>>>16&255]<<16|i[p>>>8&255]<<8|i[p&255],p^=f[T/x|0]<<24),_[T]=_[T-x]^p);for(var q=this._invKeySchedule=[],L=0;L<A;L++){var T=A-L;if(L%4)var p=_[T];else var p=_[T-4];L<4||T<=4?q[L]=p:q[L]=l[i[p>>>24]]^u[i[p>>>16&255]]^h[i[p>>>8&255]]^m[i[p&255]]}}},encryptBlock:function(p,y){this._doCryptBlock(p,y,this._keySchedule,o,s,d,c,i)},decryptBlock:function(p,y){var v=p[y+1];p[y+1]=p[y+3],p[y+3]=v,this._doCryptBlock(p,y,this._invKeySchedule,l,u,h,m,a);var v=p[y+1];p[y+1]=p[y+3],p[y+3]=v},_doCryptBlock:function(p,y,v,x,S,A,_,T){for(var q=this._nRounds,L=p[y]^v[0],w=p[y+1]^v[1],M=p[y+2]^v[2],U=p[y+3]^v[3],F=4,$=1;$<q;$++){var H=x[L>>>24]^S[w>>>16&255]^A[M>>>8&255]^_[U&255]^v[F++],G=x[w>>>24]^S[M>>>16&255]^A[U>>>8&255]^_[L&255]^v[F++],B=x[M>>>24]^S[U>>>16&255]^A[L>>>8&255]^_[w&255]^v[F++],P=x[U>>>24]^S[L>>>16&255]^A[w>>>8&255]^_[M&255]^v[F++];L=H,w=G,M=B,U=P}var H=(T[L>>>24]<<24|T[w>>>16&255]<<16|T[M>>>8&255]<<8|T[U&255])^v[F++],G=(T[w>>>24]<<24|T[M>>>16&255]<<16|T[U>>>8&255]<<8|T[L&255])^v[F++],B=(T[M>>>24]<<24|T[U>>>16&255]<<16|T[L>>>8&255]<<8|T[w&255])^v[F++],P=(T[U>>>24]<<24|T[L>>>16&255]<<16|T[w>>>8&255]<<8|T[M&255])^v[F++];p[y]=H,p[y+1]=G,p[y+2]=B,p[y+3]=P},keySize:256/32});e.AES=r._createHelper(b)})(),g.AES})});var Ia=te((Dn,Aa)=>{(function(g,e,t){typeof Dn=="object"?Aa.exports=Dn=e(ne(),St(),At(),bt(),ke()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(g.CryptoJS)})(Dn,function(g){return(function(){var e=g,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],l=i.DES=n.extend({_doReset:function(){for(var f=this._key,b=f.words,p=[],y=0;y<56;y++){var v=a[y]-1;p[y]=b[v>>>5]>>>31-v%32&1}for(var x=this._subKeys=[],S=0;S<16;S++){for(var A=x[S]=[],_=s[S],y=0;y<24;y++)A[y/6|0]|=p[(o[y]-1+_)%28]<<31-y%6,A[4+(y/6|0)]|=p[28+(o[y+24]-1+_)%28]<<31-y%6;A[0]=A[0]<<1|A[0]>>>31;for(var y=1;y<7;y++)A[y]=A[y]>>>(y-1)*4+3;A[7]=A[7]<<5|A[7]>>>27}for(var T=this._invSubKeys=[],y=0;y<16;y++)T[y]=x[15-y]},encryptBlock:function(f,b){this._doCryptBlock(f,b,this._subKeys)},decryptBlock:function(f,b){this._doCryptBlock(f,b,this._invSubKeys)},_doCryptBlock:function(f,b,p){this._lBlock=f[b],this._rBlock=f[b+1],u.call(this,4,252645135),u.call(this,16,65535),h.call(this,2,858993459),h.call(this,8,16711935),u.call(this,1,1431655765);for(var y=0;y<16;y++){for(var v=p[y],x=this._lBlock,S=this._rBlock,A=0,_=0;_<8;_++)A|=d[_][((S^v[_])&c[_])>>>0];this._lBlock=S,this._rBlock=x^A}var T=this._lBlock;this._lBlock=this._rBlock,this._rBlock=T,u.call(this,1,1431655765),h.call(this,8,16711935),h.call(this,2,858993459),u.call(this,16,65535),u.call(this,4,252645135),f[b]=this._lBlock,f[b+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function u(f,b){var p=(this._lBlock>>>f^this._rBlock)&b;this._rBlock^=p,this._lBlock^=p<<f}function h(f,b){var p=(this._rBlock>>>f^this._lBlock)&b;this._lBlock^=p,this._rBlock^=p<<f}e.DES=n._createHelper(l);var m=i.TripleDES=n.extend({_doReset:function(){var f=this._key,b=f.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 p=b.slice(0,2),y=b.length<4?b.slice(0,2):b.slice(2,4),v=b.length<6?b.slice(0,2):b.slice(4,6);this._des1=l.createEncryptor(r.create(p)),this._des2=l.createEncryptor(r.create(y)),this._des3=l.createEncryptor(r.create(v))},encryptBlock:function(f,b){this._des1.encryptBlock(f,b),this._des2.decryptBlock(f,b),this._des3.encryptBlock(f,b)},decryptBlock:function(f,b){this._des3.decryptBlock(f,b),this._des2.encryptBlock(f,b),this._des1.decryptBlock(f,b)},keySize:192/32,ivSize:64/32,blockSize:64/32});e.TripleDES=n._createHelper(m)})(),g.TripleDES})});var wa=te((wn,Da)=>{(function(g,e,t){typeof wn=="object"?Da.exports=wn=e(ne(),St(),At(),bt(),ke()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(g.CryptoJS)})(wn,function(g){return(function(){var e=g,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,l=this._S=[],u=0;u<256;u++)l[u]=u;for(var u=0,h=0;u<256;u++){var m=u%c,f=d[m>>>2]>>>24-m%4*8&255;h=(h+l[u]+f)%256;var b=l[u];l[u]=l[h],l[h]=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,l=0,u=0;u<4;u++){d=(d+1)%256,c=(c+s[d])%256;var h=s[d];s[d]=s[c],s[c]=h,l|=s[(s[d]+s[c])%256]<<24-u*8}return this._i=d,this._j=c,l}e.RC4=r._createHelper(i);var o=n.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var s=this.cfg.drop;s>0;s--)a.call(this)}});e.RC4Drop=r._createHelper(o)})(),g.RC4})});var Pa=te((Cn,Ca)=>{(function(g,e,t){typeof Cn=="object"?Ca.exports=Cn=e(ne(),St(),At(),bt(),ke()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(g.CryptoJS)})(Cn,function(g){return(function(){var e=g,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,l=this.cfg.iv,u=0;u<4;u++)c[u]=(c[u]<<8|c[u]>>>24)&16711935|(c[u]<<24|c[u]>>>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],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 u=0;u<4;u++)d.call(this);for(var u=0;u<8;u++)m[u]^=h[u+4&7];if(l){var f=l.words,b=f[0],p=f[1],y=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360,v=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,x=y>>>16|v&4294901760,S=v<<16|y&65535;m[0]^=y,m[1]^=x,m[2]^=v,m[3]^=S,m[4]^=y,m[5]^=x,m[6]^=v,m[7]^=S;for(var u=0;u<4;u++)d.call(this)}},_doProcessBlock:function(c,l){var u=this._X;d.call(this),i[0]=u[0]^u[5]>>>16^u[3]<<16,i[1]=u[2]^u[7]>>>16^u[5]<<16,i[2]=u[4]^u[1]>>>16^u[7]<<16,i[3]=u[6]^u[3]>>>16^u[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[l+h]^=i[h]},blockSize:128/32,ivSize:64/32});function d(){for(var c=this._X,l=this._C,u=0;u<8;u++)a[u]=l[u];l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0;for(var u=0;u<8;u++){var h=c[u]+l[u],m=h&65535,f=h>>>16,b=((m*m>>>17)+m*f>>>15)+f*f,p=((h&4294901760)*h|0)+((h&65535)*h|0);o[u]=b^p}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)})(),g.Rabbit})});var Oa=te((Pn,Ea)=>{(function(g,e,t){typeof Pn=="object"?Ea.exports=Pn=e(ne(),St(),At(),bt(),ke()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(g.CryptoJS)})(Pn,function(g){return(function(){var e=g,t=e.lib,r=t.StreamCipher,n=e.algo,i=[],a=[],o=[],s=n.RabbitLegacy=r.extend({_doReset:function(){var c=this._key.words,l=this.cfg.iv,u=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 m=0;m<4;m++)d.call(this);for(var m=0;m<8;m++)h[m]^=u[m+4&7];if(l){var f=l.words,b=f[0],p=f[1],y=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360,v=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,x=y>>>16|v&4294901760,S=v<<16|y&65535;h[0]^=y,h[1]^=x,h[2]^=v,h[3]^=S,h[4]^=y,h[5]^=x,h[6]^=v,h[7]^=S;for(var m=0;m<4;m++)d.call(this)}},_doProcessBlock:function(c,l){var u=this._X;d.call(this),i[0]=u[0]^u[5]>>>16^u[3]<<16,i[1]=u[2]^u[7]>>>16^u[5]<<16,i[2]=u[4]^u[1]>>>16^u[7]<<16,i[3]=u[6]^u[3]>>>16^u[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[l+h]^=i[h]},blockSize:128/32,ivSize:64/32});function d(){for(var c=this._X,l=this._C,u=0;u<8;u++)a[u]=l[u];l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0;for(var u=0;u<8;u++){var h=c[u]+l[u],m=h&65535,f=h>>>16,b=((m*m>>>17)+m*f>>>15)+f*f,p=((h&4294901760)*h|0)+((h&65535)*h|0);o[u]=b^p}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)})(),g.RabbitLegacy})});var Ta=te((En,Ra)=>{(function(g,e,t){typeof En=="object"?Ra.exports=En=e(ne(),St(),At(),bt(),ke()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(g.CryptoJS)})(En,function(g){return(function(){var e=g,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(m,f){let b=f>>24&255,p=f>>16&255,y=f>>8&255,v=f&255,x=m.sbox[0][b]+m.sbox[1][p];return x=x^m.sbox[2][y],x=x+m.sbox[3][v],x}function c(m,f,b){let p=f,y=b,v;for(let x=0;x<i;++x)p=p^m.pbox[x],y=d(m,p)^y,v=p,p=y,y=v;return v=p,p=y,y=v,y=y^m.pbox[i],p=p^m.pbox[i+1],{left:p,right:y}}function l(m,f,b){let p=f,y=b,v;for(let x=i+1;x>1;--x)p=p^m.pbox[x],y=d(m,p)^y,v=p,p=y,y=v;return v=p,p=y,y=v,y=y^m.pbox[1],p=p^m.pbox[0],{left:p,right:y}}function u(m,f,b){for(let S=0;S<4;S++){m.sbox[S]=[];for(let A=0;A<256;A++)m.sbox[S][A]=o[S][A]}let p=0;for(let S=0;S<i+2;S++)m.pbox[S]=a[S]^f[p],p++,p>=b&&(p=0);let y=0,v=0,x=0;for(let S=0;S<i+2;S+=2)x=c(m,y,v),y=x.left,v=x.right,m.pbox[S]=y,m.pbox[S+1]=v;for(let S=0;S<4;S++)for(let A=0;A<256;A+=2)x=c(m,y,v),y=x.left,v=x.right,m.sbox[S][A]=y,m.sbox[S][A+1]=v;return!0}var h=n.Blowfish=r.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var m=this._keyPriorReset=this._key,f=m.words,b=m.sigBytes/4;u(s,f,b)}},encryptBlock:function(m,f){var b=c(s,m[f],m[f+1]);m[f]=b.left,m[f+1]=b.right},decryptBlock:function(m,f){var b=l(s,m[f],m[f+1]);m[f]=b.left,m[f+1]=b.right},blockSize:64/32,keySize:128/32,ivSize:64/32});e.Blowfish=r._createHelper(h)})(),g.Blowfish})});var ni=te((On,_a)=>{(function(g,e,t){typeof On=="object"?_a.exports=On=e(ne(),qt(),Ri(),_i(),St(),Bi(),At(),ti(),Et(),Ni(),ri(),Qi(),Vi(),zi(),Lt(),Wi(),bt(),ke(),Ji(),ta(),na(),aa(),sa(),da(),la(),ma(),fa(),ga(),va(),Sa(),Ia(),wa(),Pa(),Oa(),Ta()):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):g.CryptoJS=e(g.CryptoJS)})(On,function(g){return g})});var Qa=te((jn,Ha)=>{(function(g,e,t){typeof jn=="object"?Ha.exports=jn=e(ne(),Et(),Lt()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(g.CryptoJS)})(jn,function(g){return g.HmacSHA256})});var Va=te((zn,$a)=>{(function(g,e){typeof zn=="object"?$a.exports=zn=e(ne()):typeof define=="function"&&define.amd?define(["./core"],e):e(g.CryptoJS)})(zn,function(g){return g.enc.Hex})});var Lf=Ct(fi());import{CoreRuntime as So}from"ofcore";import{asReadonlyStore as Ao,createStore as Io}from"ofcore";var jt="0123456789abcdef",zt=class g{constructor(e){this.bytes=e}static ofInner(e){if(e.length!==16)throw new TypeError("not 128-bit length");return new g(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 g(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 g(o)}else throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=jt.charAt(this.bytes[t]>>>4),e+=jt.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+=jt.charAt(this.bytes[t]>>>4),e+=jt.charAt(this.bytes[t]&15);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new g(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}},Wn=class{constructor(e){this.timestamp_biased=0,this.counter=0,this.random=e!=null?e:oo()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return r===void 0&&(this.timestamp_biased=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<0||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit unsigned integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e++,e>this.timestamp_biased)this.timestamp_biased=e,this.resetCounter();else if(e+t>=this.timestamp_biased)this.counter++,this.counter>4398046511103&&(this.timestamp_biased++,this.resetCounter());else return;return zt.fromFieldsV7(this.timestamp_biased-1,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,zt.ofInner(e)}},oo=()=>{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues!="undefined")return new Zn;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)}},Zn=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++]}},yi;var C=()=>so().toString(),so=()=>(yi||(yi=new Wn)).generateV4();var Me="boms";var Kt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addBom(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Me,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Me,record:a}),this.context.logActivity("AddBom",{id:r}),a}async updateBom(e,t,r){var s;let n=await(r||this.dbAdapter).get(Me,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(Me,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Me,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(Me,{...e,filters:i})}async getBom(e,t){return(t||this.dbAdapter).get(Me,e)}async deleteBom(e,t){var r;return await(t||this.dbAdapter).delete(Me,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Me,record:{id:e}}),this.context.logActivity("DeleteBom",{id:e}),{id:e,queued:!0}}async duplicateBom(e,t){var s;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(Me,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Me,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(Me,{filters:n})}async getBomsByComponentItemId(e,t){let r=t||this.dbAdapter,n={and:[{componentItemId:e},{deleted:!1}]};return r.query(Me,{filters:n})}async getBomsByProductId(e,t){return this.dbAdapter.query(Me,{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(Me,{filters:{parentItemId:n,deleted:!1}});for(let o of a){let s=o.quantity*i;if((await this.dbAdapter.query(Me,{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 Je="categories";var Gt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addCategory(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Je,record:a}),this.context.logActivity("AddCategory",{id:r}),a}async updateCategory(e,t,r){var s;let n=await(r||this.dbAdapter).get(Je,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(Je,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Je,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(Je,{...e,filters:i})}async getCategory(e,t){return(t||this.dbAdapter).get(Je,e)}async deleteCategory(e,t){var r;return await(t||this.dbAdapter).delete(Je,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Je,record:{id:e}}),this.context.logActivity("DeleteCategory",{id:e}),{id:e,queued:!0}}async duplicateCategory(e,t){var s;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(Je,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Je,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 We="customers";var Ot="loyalty_accounts";var ft="loyalty_ledgers";var Wt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}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:C(),customerId:t,pointsBalance:0,totalEarned:0,totalRedeemed:0,totalExpired:0,version:Date.now(),lastModified:n,deleted:!1})}async addCustomer(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(We,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:We,record:a}),this.context.logActivity("AddCustomer",{id:r}),a}async updateCustomer(e,t,r){var s;let n=await(r||this.dbAdapter).get(We,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(We,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:We,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(We,{...e,filters:i})}async getCustomer(e,t){return(t||this.dbAdapter).get(We,e)}async deleteCustomer(e,t){var r;return await(t||this.dbAdapter).delete(We,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:We,record:{id:e}}),this.context.logActivity("DeleteCustomer",{id:e}),{id:e,queued:!0}}async duplicateCustomer(e,t){var s;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(We,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:We,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(We,{...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 l=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:Number(o[0].points||0),balance:Number(l.pointsBalance||0)}}let s=Math.floor(e.baseAmount*e.earnRate);if(s<=0){let l=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:0,balance:Number(l.pointsBalance||0)}}await i.create(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 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 u of d){if(c<=0)break;let h=Number(u.availablePoints||0);if(h<=0)continue;let m=Math.min(h,c),f=h-m;await i.update(ft,u.id,{availablePoints:f,consumedAt:f===0?a:u.consumedAt,version:Date.now(),lastModified:a}),c-=m}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 l=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(l.pointsBalance||0)}})}async expireLoyaltyPoints(e){return this.runInTransaction(async t=>{let r=(e==null?void 0:e.asOfDate)||new Date().toISOString(),n=[{field:"entryType",operator:"=",value:"earn"},{field:"deleted",operator:"=",value:!1},{field:"availablePoints",operator:">",value:0},{field:"expiresAt",operator:"<=",value:r}];e!=null&&e.customerId&&n.push({field:"customerId",operator:"=",value:e.customerId});let i=await t.query(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:C(),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 Zt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addCustomerGroup(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:et,record:a}),this.context.logActivity("AddCustomerGroup",{id:r}),a}async updateCustomerGroup(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(et,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:et,record:{id:e}}),this.context.logActivity("DeleteCustomerGroup",{id:e}),{id:e,queued:!0}}async duplicateCustomerGroup(e,t){var s;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(et,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:et,record:a}),this.context.logActivity("DuplicateCustomerGroup",{originalId:e,newId:n}),o}};var ie="histories";var Yt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addHistory(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(ie,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:ie,record:a}),this.context.logActivity("AddHistory",{id:r}),a}async updateHistory(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(ie,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:ie,record:{id:e}}),this.context.logActivity("DeleteHistory",{id:e}),{id:e,queued:!0}}async duplicateHistory(e,t){var s;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(s=this.syncStore)==null||s.enqueueChange({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(l=>{let u=Date.parse(String(l.timestamp||""));return Number.isFinite(u)&&u<=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 l=(c=this.context.registry)==null?void 0:c.storageAdapter;d=`audit-archive:${e.toISOString().slice(0,10)}`;let h=await(l==null?void 0:l.getItem(d)),m=h?JSON.parse(h):[],f=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(l==null?void 0:l.setItem(d,JSON.stringify([...Array.isArray(m)?m:[],...f]))),s=f.length}for(let l of o)await this.dbAdapter.delete(ie,l.id);return this.context.logInfo("History retention enforcement completed",{scanned:a.length,archived:s,purged:o.length,retentionDays:t,archiveBeforePurge:r,archiveKey:d}),{scanned:a.length,archived:s,purged:o.length,archiveKey:d}}};var ae="orders";var Ae="order_items";var yt=class{constructor(e){this.context=e;this.map=new Map}getItem(e){var t;return(t=this.map.get(e))!=null?t:null}setItem(e,t){this.map.set(e,t)}removeItem(e){this.map.delete(e)}};var xt=class{constructor(e){this.context=e;this.queue=Promise.resolve();var t;this.storage=((t=this.context.registry)==null?void 0:t.storageAdapter)||new yt(this.context)}getBranchSegment(){return String(this.context.config.branchId||"LOCAL").trim().toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"LOCAL"}getDateSegment(e){let t=new Date(e),r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${r}${n}${i}`}getCounterKey(e,t){let r=this.getBranchSegment(),n=this.getDateSegment(t);return`docseq:${r}:${e}:${n}`}async withLock(e){let t=this.queue,r=()=>{};this.queue=new Promise(n=>{r=n}),await t;try{return await e()}finally{r()}}async next(e,t){return this.withLock(async()=>{let r=this.getCounterKey(e,t),n=await this.storage.getItem(r),i=Number(n||"0"),a=Number.isFinite(i)&&i>=0?i+1:1;await this.storage.setItem(r,String(a));let o=e.toUpperCase().slice(0,3),s=this.getBranchSegment(),d=this.getDateSegment(t);return`${o}-${s}-${d}-${String(a).padStart(6,"0")}`})}withNote(e,t){let r=String(e||"").trim(),n=`[DOC_NO=${t}]`;return r?r.includes("[DOC_NO=")?r:`${r} | ${n}`:n}extractDocNo(e){let r=String(e||"").match(/\[DOC_NO=([^\]]+)\]/);return r&&String(r[1]||"").trim()||null}};var gi="kitchen_ticket_items";var Yn="kitchen_tickets";var Xt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore(),this.docNumberPolicy=new xt(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(ae,t);if(!r||r.deleted)throw new Error(`Order with ID ${t} not found.`);let i=(await e.query(Ae,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((l,u)=>l+Number(u.unitPrice||0)*Number(u.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(ae,t,{total:i,finalTotal:c,version:Date.now(),lastModified:new Date().toISOString()})}async addOrder(e,t){var s,d,c,l,u,h,m,f,b;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:(d=e.parentOrderId)!=null?d:null,discountCode:e.discountCode,channel:(c=e.channel)!=null?c:null,status:e.status,saleId:e.saleId,scheduledAt:(l=e.scheduledAt)!=null?l:null,deliveryAddress:(u=e.deliveryAddress)!=null?u:null,tableNumber:(h=e.tableNumber)!=null?h:null,serviceChargeAmount:(m=e.serviceChargeAmount)!=null?m:null,gratuityAmount:(f=e.gratuityAmount)!=null?f: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(ae,a);return(b=this.syncStore)==null||b.enqueueChange({type:"create",model:ae,record:o}),this.context.logActivity("AddOrder",{id:r,channel:a.channel,status:a.status}),o}async updateOrder(e,t,r){var s;let n=await(r||this.dbAdapter).get(ae,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(ae,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:ae,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(ae,{...e,filters:i})}async getOrder(e,t){return(t||this.dbAdapter).get(ae,e)}async deleteOrder(e,t){var r;return await(t||this.dbAdapter).delete(ae,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:ae,record:{id:e}}),this.context.logActivity("DeleteOrder",{id:e}),{id:e,queued:!0}}async duplicateOrder(e,t){var s;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(ae,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:ae,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(ae,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(ae,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(ae,t,{status:n,version:Date.now(),lastModified:s});return await i.create(ie,{id:C(),tableName:ae,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(ae,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(Yn,{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 d=await t.get(Ae,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(gi,{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:Yn,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(ae,t);if(!i||i.deleted)throw new Error(`Order with ID ${t} not found.`);let a=await n.query(Ae,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}}),o=new Set(a.map(l=>String(l.id))),s=new Set,d=new Date().toISOString(),c=[];for(let l of e.splits){let u=(l.orderItemIds||[]).map(m=>String(m));if(u.length===0)continue;for(let m of u){if(!o.has(m))throw new Error(`Order item ${m} does not belong to parent order`);if(s.has(m))throw new Error(`Order item ${m} referenced by multiple splits`);s.add(m)}let h=await n.create(ae,{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:l.label?`SPLIT:${l.label}`:"SPLIT",version:Date.now(),lastModified:d,deleted:!1});c.push(h.id);for(let m of u)await n.get(Ae,m)&&await n.update(Ae,m,{orderId:h.id,version:Date.now(),lastModified:d});await this.recalculateOrderTotals(n,h.id)}return await this.recalculateOrderTotals(n,t),await n.create(ie,{id:C(),tableName:ae,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(ae,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(ae,s);if(!d||d.deleted)throw new Error(`Order with ID ${s} not found.`);let c=await i.query(Ae,{filters:{and:[{field:"orderId",operator:"=",value:s},{field:"deleted",operator:"=",value:!1}]}});for(let l of c)await i.update(Ae,l.id,{orderId:t,version:Date.now(),lastModified:o});await i.update(ae,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:C(),tableName:ae,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(ae,t);if(!n||n.deleted)throw new Error(`Order with ID ${t} not found.`);let a=(await r.query(Ae,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((l,u)=>l+Number(u.unitPrice||0)*Number(u.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(ae,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:C(),tableName:ae,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 Jt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addOrderItem(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ae,record:a}),this.context.logActivity("AddOrderItem",{id:r}),a}async updateOrderItem(e,t,r){var s;let n=await(r||this.dbAdapter).get(Ae,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(Ae,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Ae,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(Ae,{...e,filters:i})}async getOrderItem(e,t){return(t||this.dbAdapter).get(Ae,e)}async deleteOrderItem(e,t){var r;return await(t||this.dbAdapter).delete(Ae,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ae,record:{id:e}}),this.context.logActivity("DeleteOrderItem",{id:e}),{id:e,queued:!0}}async duplicateOrderItem(e,t){var s;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(Ae,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Ae,record:a}),this.context.logActivity("DuplicateOrderItem",{originalId:e,newId:n}),o}};var Qe="price_tiers";var er=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addPriceTier(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Qe,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Qe,record:a}),this.context.logActivity("AddPriceTier",{id:r}),a}async updatePriceTier(e,t,r){var s;let n=await(r||this.dbAdapter).get(Qe,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(Qe,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Qe,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(Qe,{...e,filters:i})}async getPriceTier(e,t){return(t||this.dbAdapter).get(Qe,e)}async deletePriceTier(e,t){var r;return await(t||this.dbAdapter).delete(Qe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Qe,record:{id:e}}),this.context.logActivity("DeletePriceTier",{id:e}),{id:e,queued:!0}}async duplicatePriceTier(e,t){var s;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(Qe,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Qe,record:a}),this.context.logActivity("DuplicatePriceTier",{originalId:e,newId:n}),o}};var se="products";var tr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addProduct(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(se,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:se,record:a}),this.context.logActivity("AddProduct",{id:r}),a}async updateProduct(e,t,r){var s;let n=await(r||this.dbAdapter).get(se,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(se,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:se,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(se,{...e,filters:i})}async getProduct(e,t){return(t||this.dbAdapter).get(se,e)}async deleteProduct(e,t){var r;return await(t||this.dbAdapter).delete(se,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:se,record:{id:e}}),this.context.logActivity("DeleteProduct",{id:e}),{id:e,queued:!0}}async duplicateProduct(e,t){var s;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(se,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:se,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(se,{filters:n})}async getProductsByQrCode(e,t){let r=t||this.dbAdapter,n={and:[{qrCode:e},{deleted:!1}]};return r.query(se,{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(se,{...t,filters:a})}};var tt="promotions";var rr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addPromotion(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:tt,record:a}),this.context.logActivity("AddPromotion",{id:r}),a}async updatePromotion(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(tt,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:tt,record:{id:e}}),this.context.logActivity("DeletePromotion",{id:e}),{id:e,queued:!0}}async duplicatePromotion(e,t){var s;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(tt,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:tt,record:a}),this.context.logActivity("DuplicatePromotion",{originalId:e,newId:n}),o}};var xe="returns";var he="sale_items";var Ie="purchase_items";var Oe="return_items";var X="transactions";var nr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addReturn(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:xe,record:a}),this.context.logActivity("AddReturn",{id:r}),a}async updateReturn(e,t,r){var s;let n=await(r||this.dbAdapter).get(xe,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(xe,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:xe,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(xe,{...e,filters:i})}async getReturn(e,t){return(t||this.dbAdapter).get(xe,e)}async deleteReturn(e,t){var r;return await(t||this.dbAdapter).delete(xe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:xe,record:{id:e}}),this.context.logActivity("DeleteReturn",{id:e}),{id:e,queued:!0}}async duplicateReturn(e,t){var s;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(xe,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:xe,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"?he:Ie,{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(xe,{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(X,{filters:{and:[{field:"userId",operator:"=",value:e},{field:"date",operator:">=",value:r},{field:"referenceType",operator:"IN",value:["sale_return_cancelled","purchase_return_cancelled"]},{field:"deleted",operator:"=",value:!1}]}})).length>=t.maxEvents}async processReturn(e){var $,H,G,B,P;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:d=s,refundMethod:c="cash",creditNoteNumber:l=null,refundNote:u,refundReceivedDate:h,approval:m}=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 f=this.context.config.requireReasonForReturnOperations,b=String(a||"").trim();if(f&&!b)throw new Error("Return reason is required by policy");let p=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),y=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),v=this.getCurrentRole(),x=!v||!p.includes(v),S=d>0&&this.context.config.requireApprovalForReturnRefund&&x,A=String(((G=this.context.session)==null?void 0:G.userId)||"").trim(),_=d>0&&await this.shouldTriggerFraudGuardForRefund(A),T=this.getFraudGuardPolicy();if(_&&T.action==="block")throw new Error("Fraud guard: repeat return pattern detected (refund blocked)");let q=_&&T.action==="require_approval",L=S||q?this.validateApproval(m,y,q?"Fraud guard return refund":"Return refund"):null,w=(B=this.context.domainServices)==null?void 0:B.uom,M=await w.getUomsMap(),U=this.context.domainServices.transaction;if(e.saleId){let O=await this.getReturnsByReference("sale_return",e.saleId);if(O.length>0){let R=await this.calculateTotalReturnedQty(O,e.items.map(I=>I.productId));for(let I of e.items){let Z=await this.getOriginalQuantity("sale",e.saleId,I.productId),J=Z-(R.get(I.productId)||0);if(I.quantity>J)throw new Error(`Produk ${I.productId} hanya bisa diretur ${J} lagi (sudah diretur ${R.get(I.productId)||0}/${Z})`)}}}if(e.purchaseId){let O=await this.getReturnsByReference("purchase_return",e.purchaseId);if(O.length>0){let R=await this.calculateTotalReturnedQty(O,e.items.map(I=>I.productId));for(let I of e.items){let Z=await this.getOriginalQuantity("purchase",e.purchaseId,I.productId),J=Z-(R.get(I.productId)||0);if(I.quantity>J)throw new Error(`Produk ${I.productId} hanya bisa diretur ${J} lagi (sudah diretur ${R.get(I.productId)||0}/${Z})`)}}}let F=await this.dbAdapter.transaction(async O=>{var Y,W,Re;let R=new Date().toISOString(),I=C(),Z=[],J={id:I,type:r,saleId:n,purchaseId:i,reason:b||null,refundAmount:s,actualRefund:d,refundMethod:d>0?c:null,creditNoteNumber:l,refundNote:d<s?typeof u=="number"?u:s-d:null,refundReceivedDate:d>0?h||R:null,status:d===s?"completed":d>0?"partially_refunded":"no_refund",date:R,userId:((Y=this.context.session)==null?void 0:Y.userId)||"",version:1,lastModified:R,deleted:!1};await O.create(xe,J),Z.push({type:"create",model:xe,record:J});for(let me of o){let ue=(W=me.restock)!=null?W:!0,be=me.quantity,we=await this.getReferenceItem(r,n||i,me.productId,O);if(!we)throw new Error(`Item not found in ${r==="sale_return"?"sale":"purchase"} ${n||i}`);let ye=r==="sale_return"?we.unitPrice:we.unitCost,Ue=we.uomId,je={id:C(),returnId:I,productId:me.productId,quantity:be,unitPrice:ye,uomId:Ue,restock:ue,restockNote:ue?null:me.restockNote||"Rusak / tidak bisa dijual",version:1,lastModified:R,deleted:!1};if(await O.create(Oe,je),Z.push({type:"create",model:Oe,record:je}),ue){let He=w.convertQuantity(be,{conversionFactor:Ue&&((Re=M.get(Ue))==null?void 0:Re.conversionFactor)||1},{conversionFactor:1}),ze=r==="sale_return"?+He:-He;await t.updateStock(me.productId,ze,r,xe,I,O)}}if(d>0)if((r==="sale_return"?"out":"in")==="in"){let ue=await U.recordCashIn({amount:d,method:c,data:{referenceType:r,referenceId:I,note:u}},O);Z.push({type:"create",model:X,record:ue})}else{let ue=await U.recordCashOut({amount:d,method:c,data:{referenceType:r,referenceId:I,note:u}},O);Z.push({type:"create",model:X,record:ue})}return L&&this.context.logActivity("ReturnRefundApproved",{returnId:I,approvedBy:L.approvedBy,approverRole:L.approverRole,reason:L.reason}),{returnId:I,queued:!0,type:r,actualRefund:d,syncChanges:Z}});for(let O of F.syncChanges)(P=this.syncStore)==null||P.enqueueChange(O);return this.context.eventBus.emit("return:processed",{returnId:F.returnId,type:F.type,actualRefund:F.actualRefund}),this.context.logActivity("processReturn",{returnId:F.returnId,type:F.type,actualRefund:F.actualRefund}),{returnId:F.returnId,queued:F.queued}}async cancelReturn(e,t="Cancelled by user"){var S,A,_,T,q;let r=(A=(S=this.context)==null?void 0:S.domainServices)==null?void 0:A.inventory,n=(_=this.context.domainServices)==null?void 0:_.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"]),l=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),u=this.getCurrentRole(),h=!u||!c.includes(u),m=this.context.config.requireApprovalForReturnCancel&&h,f=String(((T=this.context.session)==null?void 0:T.userId)||"").trim(),b=await this.shouldTriggerFraudGuardForCancel(f),p=this.getFraudGuardPolicy();if(b&&p.action==="block")throw new Error("Fraud guard: repeat return cancellation pattern detected (cancel blocked)");let y=b&&p.action==="require_approval",v=m||y?this.validateApproval(s,l,y?"Fraud guard return cancellation":"Return cancellation"):null,x=await this.dbAdapter.transaction(async L=>{var F;let w=await L.get(xe,e);if(!w||w.deleted)throw new Error("Return not found or already deleted");let M=[],U=await L.query(Oe,{filters:{returnId:e,deleted:!1}});for(let $ of U){if($.restock){let H=n.convertQuantity($.quantity,{conversionFactor:$.uomId&&((F=i.get($.uomId))==null?void 0:F.conversionFactor)||1},{conversionFactor:1}),G=w.type==="sale_return"?-H:+H;await r.updateStock($.productId,G,`${w.type}_cancelled`,xe,e,L)}await L.update(Oe,$.id,{deleted:!0,lastModified:new Date().toISOString()}),M.push({type:"delete",model:Oe,record:{id:$.id}})}if(w.actualRefund>0)if((w.type==="sale_return"?"in":"out")==="in"){let H=await a.recordCashIn({amount:w.actualRefund,method:w.refundMethod||"cash",data:{referenceType:`${w.type}_cancelled`,referenceId:e,note:o}},L);M.push({type:"create",model:X,record:H})}else{let H=await a.recordCashOut({amount:w.actualRefund,method:w.refundMethod||"cash",data:{referenceType:`${w.type}_cancelled`,referenceId:e,note:o}},L);M.push({type:"create",model:X,record:H})}return await L.update(xe,e,{deleted:!0,lastModified:new Date().toISOString()}),M.push({type:"delete",model:xe,record:{id:e}}),v&&this.context.logActivity("CancelReturnApproved",{returnId:e,approvedBy:v.approvedBy,approverRole:v.approverRole,reason:v.reason}),{returnId:e,queued:!0,syncChanges:M}});for(let L of x.syncChanges)(q=this.syncStore)==null||q.enqueueChange(L);return this.context.eventBus.emit("return:canceled",{returnId:x.returnId}),this.context.logActivity("cancelReturn",{returnId:x.returnId}),{returnId:x.returnId,queued:x.queued}}async getReturnsByReference(e,t){let r=e==="sale_return"?{saleId:t,deleted:!1}:{purchaseId:t,deleted:!1};return this.dbAdapter.query(xe,{filters:r})}async getReturnableQuantity(e,t,r){let n=e==="sale"?he:Ie,i=e==="sale"?"saleId":"purchaseId",a=await this.dbAdapter.query(n,{filters:{productId:r,[i]:t,deleted:!1}}),o=a.length?a[0]:null;if(!o)return 0;let s=o.quantity,d=await this.dbAdapter.query(Oe,{filters:{and:[{field:e==="sale"?"saleId":"purchaseId",alias:"rt",value:t},{productId:r,restock:!0,deleted:!1}]},joins:[{table:xe,alias:"rt",type:"left",conditions:[{left:{type:"column",tableAlias:"rt",field:"id"},operator:"=",right:{type:"column",tableAlias:"t0",field:"returnId"}}]}]});if(!d.length)return s;let c=d.reduce((u,h)=>u+h.quantity,0),l=s-c;return Math.max(0,l)}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"?he:Ie,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 ir=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addReturnItem(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Oe,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Oe,record:a}),this.context.logActivity("AddReturnItem",{id:r}),a}async updateReturnItem(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(Oe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Oe,record:{id:e}}),this.context.logActivity("DeleteReturnItem",{id:e}),{id:e,queued:!0}}async duplicateReturnItem(e,t){var s;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(Oe,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Oe,record:a}),this.context.logActivity("DuplicateReturnItem",{originalId:e,newId:n}),o}};var Ce="roles";var ar=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addRole(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ce,record:a}),this.context.logActivity("AddRole",{id:r}),a}async updateRole(e,t,r){var s;let n=await(r||this.dbAdapter).get(Ce,e);if(!n)throw new Error(`Role with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ce,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Ce,record:o}),this.context.logActivity("UpdateRole",{id:e}),o}async getRoles(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ce,{...e,filters:i})}async getRole(e,t){return(t||this.dbAdapter).get(Ce,e)}async deleteRole(e,t){var r;return await(t||this.dbAdapter).delete(Ce,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ce,record:{id:e}}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async duplicateRole(e,t){var s;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(Ce,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Ce,record:a}),this.context.logActivity("DuplicateRole",{originalId:e,newId:n}),o}};var ce="sales";var fe="receivables";var ut="inventory_lots";var or=class{constructor(e){this.context=e;this.defaultBaseCurrencyCode="IDR";var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore(),this.docNumberPolicy=new xt(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t,r){var d,c,l;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:(l=e.exchangeRateSource)!=null?l:"snapshot.manual",totalInBaseCurrency:o,finalTotalInBaseCurrency:s}}isExpiredLot(e,t){if(!e)return!1;let r=Date.parse(String(e));return Number.isFinite(r)?r<t:!1}diffInDays(e,t){let r=e.getTime(),n=t.getTime();return!Number.isFinite(r)||!Number.isFinite(n)?NaN:Math.floor((n-r)/(1440*60*1e3))}async enforceTempoCustomerCreditPolicy(e,t){if(!this.context.config.enableCustomerCreditPolicy)return;let r=String(t.customerId||"").trim();if(!r)throw new Error("Customer credit policy: customerId is required for tempo sale");let n=await e.query(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 l of n){let u=Number(l.amount||0),h=Number(l.paidAmount||0),m=Math.max(0,u-h);if(m<=0)continue;o+=m;let f=this.diffInDays(new Date(String(l.dueDate||"")),i);Number.isFinite(f)&&(s=Math.max(s,f))}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)}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(l=>l.docNo===a):!1,c=new Date().toISOString();return await this.dbAdapter.create(ie,{id:C(),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:C(),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,p,y;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&&((p=i.get(t.uomId))==null?void 0:p.conversionFactor)||1,o=n.convertQuantity(r,{conversionFactor:a},{conversionFactor:1});if(!Number.isFinite(o)||o<=0)return[];let s=await e.query(ut,{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(),l=[],u=[],h=0;for(let v of s){if(this.isExpiredLot(v.expiryDate,d)){if(v.status!=="expired"){let S=await e.update(ut,v.id,{status:"expired",version:Number(v.version||0)+1,lastModified:c});l.push({id:S.id,remainingQuantity:Number(S.remainingQuantity||0),status:String(S.status||"expired"),version:Number(S.version||0),lastModified:String(S.lastModified||c)})}continue}u.push(v),h+=Number(v.remainingQuantity||0)}if(h<o)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: insufficient non-expired lot stock`);let m=((y=this.context.config)==null?void 0:y.lotConsumptionPolicy)==="FIFO"?"FIFO":"FEFO";u.sort((v,x)=>{let S=Date.parse(v.lastModified||""),A=Date.parse(x.lastModified||"");if(m==="FIFO"){if(Number.isFinite(S)&&Number.isFinite(A)&&S!==A)return S-A}else{let _=v.expiryDate?Date.parse(v.expiryDate):Number.POSITIVE_INFINITY,T=x.expiryDate?Date.parse(x.expiryDate):Number.POSITIVE_INFINITY;if(Number.isFinite(_)&&Number.isFinite(T)&&_!==T)return _-T;if(Number.isFinite(_)!==Number.isFinite(T))return Number.isFinite(_)?-1:1}return Number.isFinite(S)&&Number.isFinite(A)&&S!==A?S-A:String(v.id).localeCompare(String(x.id))});let f=o;for(let v of u){if(f<=0)break;let x=Number(v.remainingQuantity||0);if(x<=0)continue;let S=Math.min(f,x),A=x-S,_=A<=0?"depleted":"active",T=await e.update(ut,v.id,{remainingQuantity:A,status:_,version:Number(v.version||0)+1,lastModified:c});l.push({id:T.id,remainingQuantity:Number(T.remainingQuantity||0),status:String(T.status||_),version:Number(T.version||0),lastModified:String(T.lastModified||c)}),f-=S}if(f>0)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: lot consumption incomplete`);return l}async addSale(e,t){var s;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(ce,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:ce,record:o}),this.context.logActivity("AddSale",{id:r}),o}async updateSale(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(ce,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:ce,record:{id:e}}),this.context.logActivity("DeleteSale",{id:e}),{id:e,queued:!0}}async duplicateSale(e,t){var s;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(ce,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:ce,record:a}),this.context.logActivity("DuplicateSale",{originalId:e,newId:n}),o}async createSale(e,t,r){var i;let n=await this.dbAdapter.transaction(async a=>{var h,m,f,b;let o=new Date().toISOString(),s=(h=e.id)!=null?h:C(),d=((m=this.context.config)==null?void 0:m.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",e.date||o):null,c={id:s,userId:e.userId,customerId:e.customerId,sourceOrderId:e.sourceOrderId,status:"completed",date:e.date,total:0,ppn:(f=e.ppn)!=null?f:0,pph:(b=e.pph)!=null?b:0,finalTotal:0,transactionCurrencyCode:null,exchangeRate:null,exchangeRateSource:null,totalInBaseCurrency:0,finalTotalInBaseCurrency:0,note:d?this.docNumberPolicy.withNote(e.note,d):e.note,version:1,lastModified:o,deleted:!1},l=[];if(t){let p=t.reduce((y,v)=>{var x;return y+((x=v.unitPrice)!=null?x:0)*v.quantity},0);c.total=p,c.finalTotal=p+c.ppn+c.pph}if(Object.assign(c,this.resolveCurrencySnapshot(e,c.total,c.finalTotal)),await a.create(ce,c),l.push({type:"create",model:ce,record:c}),!t)return{sale:c,syncChanges:l};let u=t.map(p=>({id:C(),saleId:s,...p,version:1,lastModified:o,deleted:!1}));await a.bulkCreate(he,u);for(let p of u)l.push({type:"create",model:he,record:p});if(r)if(r.method!=="tempo"){let p=await this.context.domainServices.transaction.recordCashIn({method:r.method,data:{...r.data,referenceType:"sale",referenceId:s},amount:c.finalTotal},a);l.push({type:"create",model:X,record:p})}else{let p=r.dueDate;await this.enforceTempoCustomerCreditPolicy(a,{customerId:c.customerId,receivableAmount:c.finalTotal,referenceId:c.id,dueDate:p,nowIso:o});let y=await this.context.domainServices.receivable.addReceivable({saleId:c.id,customerId:c.customerId,amount:c.finalTotal,dueDate:p,status:"unpaid",paidAmount:0,date:o},a);l.push({type:"create",model:fe,record:y})}for(let p of u){let y=await this.consumeInventoryLotsForSale(a,{saleId:c.id,saleDate:c.date,productId:p.productId,quantity:p.quantity,uomId:p.uomId});for(let v of y)l.push({type:"update",model:ut,record:v});await this.context.domainServices.inventory.updateStock(p.productId,-p.quantity,"sale",ce,c.id,a)}return{sale:c,items:u,syncChanges:l}});for(let a of n.syncChanges)(i=this.syncStore)==null||i.enqueueChange(a);return this.context.eventBus.emit("sale:finalized",n.sale.id),t?{sale:n.sale,items:n.items}:n.sale}async finalizeSale(e,t){var n;let r=await this.dbAdapter.transaction(async i=>{let a=await this.getSale(e,i);if(!a)throw new Error(`Sale not found for id ${e}`);let o=[];if(t)if(t.method!=="tempo"){let d=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:e},amount:a.finalTotal},i);o.push({type:"create",model:X,record:d})}else{let d=new Date().toISOString();await this.enforceTempoCustomerCreditPolicy(i,{customerId:a.customerId,receivableAmount:a.finalTotal,referenceId:a.id,dueDate:t.dueDate,nowIso:d});let c=await this.context.domainServices.receivable.addReceivable({saleId:a.id,customerId:a.customerId,amount:a.finalTotal,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:d},i);o.push({type:"create",model:fe,record:c})}let s=await i.query(he,{filters:{saleId:e}});for(let d of s){let c=await this.consumeInventoryLotsForSale(i,{saleId:e,saleDate:a.date,productId:d.productId,quantity:d.quantity,uomId:d.uomId});for(let l of c)o.push({type:"update",model:ut,record:l});await this.context.domainServices.inventory.updateStock(d.productId,-d.quantity,"sale",ce,e,i)}return{saleId:e,syncChanges:o}});for(let i of r.syncChanges)(n=this.syncStore)==null||n.enqueueChange(i);this.context.eventBus.emit("sale:finalized",r.saleId)}async createSaleFromOrder(e,t){var n;let r=await this.dbAdapter.transaction(async i=>{var v,x,S;let a=await i.get(ae,e);if(!a)throw new Error(`Order not found for id ${e}`);let o=await i.query(Ae,{filters:{orderId:e,deleted:!1}}),s=new Date().toISOString(),d=C(),c=((v=this.context.config)==null?void 0:v.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",a.date||s):null,l=[],u=o.reduce((A,_)=>A+(_.unitPrice||0)*_.quantity,0),h=(x=a.ppn)!=null?x:0,m=(S=a.pph)!=null?S:0,f=u+h+m,b=this.resolveCurrencySnapshot(a,u,f),p={id:d,userId:a.userId,customerId:a.customerId,sourceOrderId:a.id,discountCode:a.discountCode||null,status:"completed",date:a.date,total:u,discount:0,ppn:h,pph:m,finalTotal:f,...b,note:c?this.docNumberPolicy.withNote(a.note,c):a.note,version:1,lastModified:s,deleted:!1};await i.create(ce,p),l.push({type:"create",model:ce,record:p});let y=o.map(A=>({id:C(),saleId:d,productId:A.productId,quantity:A.quantity,uomId:A.uomId,unitPrice:A.unitPrice,version:1,lastModified:s,deleted:!1}));await i.bulkCreate(he,y);for(let A of y)l.push({type:"create",model:he,record:A});if(await i.update(ae,e,{status:"completed",saleId:d,lastModified:s}),l.push({type:"update",model:ae,record:{id:e,status:"completed",saleId:d,lastModified:s}}),t.method!=="tempo"){let A=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:d},amount:p.finalTotal},i);l.push({type:"create",model:X,record:A})}else{let A=t.dueDate;await this.enforceTempoCustomerCreditPolicy(i,{customerId:p.customerId,receivableAmount:p.finalTotal,referenceId:p.id,dueDate:A,nowIso:s});let _=await this.context.domainServices.receivable.addReceivable({saleId:p.id,customerId:p.customerId,amount:p.finalTotal,dueDate:A,status:"unpaid",paidAmount:0,date:s},i);l.push({type:"create",model:fe,record:_})}for(let A of y){let _=await this.consumeInventoryLotsForSale(i,{saleId:d,saleDate:p.date,productId:A.productId,quantity:A.quantity,uomId:A.uomId});for(let T of _)l.push({type:"update",model:ut,record:T});await this.context.domainServices.inventory.updateStock(A.productId,-A.quantity,"sale",ce,d,i)}return{sale:p,items:y,saleId:d,syncChanges:l}});for(let i of r.syncChanges)(n=this.syncStore)==null||n.enqueueChange(i);return this.context.eventBus.emit("sale:finalized",r.saleId),{sale:r.sale,items:r.items}}async createSaleFromCart(e,t){var s,d;let r=this.context.domainServices.pricing,n=await this.context.domainServices.cart.getCart(e);if(!n)throw new Error(`Cart not found for id ${e}`);let i=(s=this.context.domainServices)==null?void 0:s.uom,a=await i.getUomsMap(),o=await this.dbAdapter.transaction(async c=>{var _,T,q,L;let l=n.customerId?await this.context.domainServices.customer.getCustomer(n.customerId,c):void 0,u=await r.calculateOrderTotal(n.items,n.discountCode,(l==null?void 0:l.groupId)||void 0),h=await r.calculatePPN(u.subTotal),m=await r.calculatePPH(u.subTotal),f=u.total+h+m,b=this.resolveCurrencySnapshot(n,u.subTotal,f),p=new Date().toISOString(),y=C(),v=((_=this.context.config)==null?void 0:_.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",p):null,x={id:y,userId:((q=(T=this.context)==null?void 0:T.session)==null?void 0:q.userId)||"",customerId:n.customerId||null,sourceOrderId:null,discountCode:n.discountCode||null,status:"completed",date:p,total:u.subTotal,discount:u.discount,ppn:h,pph:m,finalTotal:f,...b,note:v?this.docNumberPolicy.withNote(n.note||null,v):n.note||null,version:1,lastModified:p,deleted:!1},S=n.items.map(w=>({id:C(),saleId:y,productId:w.productId,quantity:w.quantity,uomId:w.uomId||null,unitPrice:w.unitPrice,version:1,lastModified:p,deleted:!1})),A=[];await c.create(ce,x),await c.bulkCreate(he,S),A.push({type:"create",model:ce,record:x});for(let w of S)A.push({type:"create",model:he,record:w});if(t.method!=="tempo"){let w=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:y},amount:x.finalTotal},c);A.push({type:"create",model:X,record:w})}else{let w=t.dueDate;await this.enforceTempoCustomerCreditPolicy(c,{customerId:x.customerId,receivableAmount:x.finalTotal,referenceId:x.id,dueDate:w,nowIso:p});let M=await this.context.domainServices.receivable.addReceivable({saleId:x.id,customerId:x.customerId,amount:x.finalTotal,dueDate:w,status:"unpaid",paidAmount:0,date:p},c);A.push({type:"create",model:fe,record:M})}for(let w of S){let M=typeof w.uomId=="string"&&((L=a.get(w.uomId))==null?void 0:L.conversionFactor)||1,U=i.convertQuantity(w.quantity,{conversionFactor:M},{conversionFactor:1}),F=await this.consumeInventoryLotsForSale(c,{saleId:y,saleDate:x.date,productId:w.productId,quantity:w.quantity,uomId:w.uomId});for(let $ of F)A.push({type:"update",model:ut,record:$});await this.context.domainServices.inventory.updateStock(w.productId,-U,"sale",ce,x.id,c)}return{sale:x,items:S,syncChanges:A}});for(let c of o.syncChanges)(d=this.syncStore)==null||d.enqueueChange(c);this.context.eventBus.emit("sale:finalized",o.sale.id);try{await this.context.domainServices.cart.deleteCart(e)}catch(c){this.context.logError(c,{message:`Sale created but failed to delete cart ${e}`})}return{sale:o.sale,items:o.items}}};var sr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addSaleItem(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:he,record:a}),this.context.logActivity("AddSaleItem",{id:r}),a}async updateSaleItem(e,t,r){var s;let n=await(r||this.dbAdapter).get(he,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(he,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:he,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(he,{...e,filters:i})}async getSaleItem(e,t){return(t||this.dbAdapter).get(he,e)}async deleteSaleItem(e,t){var r;return await(t||this.dbAdapter).delete(he,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:he,record:{id:e}}),this.context.logActivity("DeleteSaleItem",{id:e}),{id:e,queued:!0}}async duplicateSaleItem(e,t){var s;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(he,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:he,record:a}),this.context.logActivity("DuplicateSaleItem",{originalId:e,newId:n}),o}};var pe="shifts";var cr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addShift(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:pe,record:a}),this.context.logActivity("AddShift",{id:r}),a}async updateShift(e,t,r){var s;let n=await(r||this.dbAdapter).get(pe,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(pe,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:pe,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(pe,{...e,filters:i})}async getShift(e,t){return(t||this.dbAdapter).get(pe,e)}async deleteShift(e,t){var r;return await(t||this.dbAdapter).delete(pe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:pe,record:{id:e}}),this.context.logActivity("DeleteShift",{id:e}),{id:e,queued:!0}}async duplicateShift(e,t){var s;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(pe,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:pe,record:a}),this.context.logActivity("DuplicateShift",{originalId:e,newId:n}),o}async openShift(e,t,r){return this.dbAdapter.transaction(async n=>{var d,c;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:((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(pe,s),(c=this.syncStore)==null||c.enqueueChange({type:"create",model:pe,record:s}),this.context.eventBus.emit("shift:opened",{shiftId:o,cashierId:e,startingCash:t}),s})}async closeShift(e,t,r){let n=typeof r=="string"?r:r==null?void 0:r.note,i=typeof r=="string"||r==null?void 0:r.approval;return this.dbAdapter.transaction(async a=>{var p,y,v,x,S;let o=await a.get(pe,e);if(!o||o.deleted||o.status!=="open")throw new Error("Shift tidak ditemukan atau sudah ditutup");let s=await a.query(X,{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=((p=s==null?void 0:s[0])==null?void 0:p.cashIn)||0,c=((y=s==null?void 0:s[0])==null?void 0:y.cashOut)||0,l=d-c,u=o.startingCash+l,h=t-u,m=Math.abs(h);if((v=this.context.config)!=null&&v.requireShiftCloseApprovalOnDifference){let A=(x=this.context.config)==null?void 0:x.shiftCloseDifferenceApprovalThreshold,_=typeof A=="number"&&A>=0?A:0;if(m>_){let T=String((i==null?void 0:i.approvedBy)||"").trim(),q=String((i==null?void 0:i.reason)||"").trim();if(!T||!q)throw new Error(`Shift close approval is required when cash difference exceeds ${_}`)}}let f=i?`[CLOSE_APPROVED_BY=${i.approvedBy}] [CLOSE_APPROVAL_REASON=${i.reason}]`:"",b={closedAt:new Date().toISOString(),endingCash:t,systemCash:u,cashDifference:h,status:"closed",note:[o.note||"",n||"",f].filter(Boolean).join(" | ")||null,lastModified:new Date().toISOString()};return await a.update(pe,e,b),(S=this.syncStore)==null||S.enqueueChange({type:"update",model:pe,id:e,record:b}),this.context.eventBus.emit("shift:closed",{shiftId:e,cashierId:o.cashierId,systemEndingCash:u,physicalEndingCash:t,difference:h}),i&&this.context.logActivity("CloseShiftApproval",{shiftId:e,cashierId:o.cashierId,approvedBy:i.approvedBy,reason:i.reason,cashDifference:h},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 h,m;let a=await i.get(pe,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=C(),c=t.startingCash!=null?t.startingCash:(h=a.endingCash)!=null?h:a.startingCash,l=[a.note||"",`[REOPEN_FROM=${e}]`,`[APPROVED_BY=${r}]`,`[REASON=${n}]`].filter(Boolean),u={id:d,cashierId:a.cashierId,cashierName:a.cashierName,openedAt:s,closedAt:null,startingCash:c,endingCash:null,systemCash:null,cashDifference:null,status:"open",note:l.join(" "),version:1,lastModified:s,deleted:!1};return await i.create(pe,u),(m=this.syncStore)==null||m.enqueueChange({type:"create",model:pe,record:u}),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}),u})}async getActiveShift(e){let t=await this.dbAdapter.query(pe,{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(pe,{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(pe,e);if(!t)throw new Error("Shift tidak ditemukan");let r=await this.dbAdapter.get(X,{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 u,h,m;let t=await this.getShiftsByDate(e),r=0,n=0,i=0;for(let f of t)r+=f.startingCash,f.status==="closed"&&(n+=f.endingCash||0,i+=f.systemCash||0);let a=`${e}T00:00:00.000Z`,o=`${e}T23:59:59.999Z`,s=await this.dbAdapter.query(X,{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=((u=s==null?void 0:s[0])==null?void 0:u.salesCash)||0,c=((h=s==null?void 0:s[0])==null?void 0:h.returnsCash)||0,l=((m=s==null?void 0:s[0])==null?void 0:m.expenses)||0;return{date:e,totalSalesCash:d,totalReturnsCash:c,totalExpenses:l,netCashMovement:d-c-l,startingCash:r,systemEndingCash:i,physicalEndingCash:n,cashDifference:n-i,shifts:t}}};var Ee="tax_rates";var dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addTaxRate(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ee,record:a}),this.context.logActivity("AddTaxRate",{id:r}),a}async updateTaxRate(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(Ee,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ee,record:{id:e}}),this.context.logActivity("DeleteTaxRate",{id:e}),{id:e,queued:!0}}async duplicateTaxRate(e,t){var s;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(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Ee,record:a}),this.context.logActivity("DuplicateTaxRate",{originalId:e,newId:n}),o}};var ur=class{constructor(e){this.context=e;this.allowedReferenceTypes=new Set(["sale","purchase","sale_return","purchase_return","sale_return_cancelled","purchase_return_cancelled","receivable_payment","payable_payment","cash_adjustment","expense"]);var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}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(X,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 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){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(X,i);return t||(o=this.syncStore)==null||o.enqueueChange({type:"create",model:X,record:a}),this.context.logActivity("AddTransaction",{id:r}),a}async updateTransaction(e,t,r){var s;let n=await(r||this.dbAdapter).get(X,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(X,e,a);return r||(s=this.syncStore)==null||s.enqueueChange({type:"update",model:X,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(X,{...e,filters:i})}async getTransaction(e,t){return(t||this.dbAdapter).get(X,e)}async deleteTransaction(e,t){var r;return await(t||this.dbAdapter).delete(X,e),t||(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:X,record:{id:e}}),this.context.logActivity("DeleteTransaction",{id:e}),{id:e,queued:!0}}async duplicateTransaction(e,t){var s;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(X,a);return t||(s=this.syncStore)==null||s.enqueueChange({type:"create",model:X,record:a}),this.context.logActivity("DuplicateTransaction",{originalId:e,newId:n}),o}async recordCashIn(e,t){var l,u,h;let r=(l=this.context.registry)==null?void 0:l.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((u=e==null?void 0:e.data)==null?void 0:u.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=C(),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(X,c);return n&&await this.saveIdempotencyMarker("cash_in",n,m.id,o),t||(h=this.syncStore)==null||h.enqueueChange({type:"create",model:X,record:m}),this.context.logActivity("RecordCashIn",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash in recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashIn"}),m}catch(m){throw r.logError("Error recording cash in",{id:a,method:e.method,amount:e.amount,error:m}),m}}async recordCashOut(e,t){var l,u,h;let r=(l=this.context.registry)==null?void 0:l.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((u=e==null?void 0:e.data)==null?void 0:u.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=C(),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(X,c);return n&&await this.saveIdempotencyMarker("cash_out",n,m.id,o),t||(h=this.syncStore)==null||h.enqueueChange({type:"create",model:X,record:m}),this.context.logActivity("RecordCashOut",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash out recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashOut"}),m}catch(m){throw r.logError("Error recording cash out",{id:a,method:e.method,amount:e.amount,error:m}),m}}async adjustCash(e,t,r,n){var o,s;if(e<=0)throw new Error("Amount must be positive");let a={method:"cash",data:{referenceType:"cash_adjustment",referenceId:`adj-${new Date().toISOString().split("T")[0]}-${Date.now()}`,reason:r,reasonCode:"manual_adjustment",adjustedBy:((o=this.context.session)==null?void 0:o.userId)||"",userId:((s=this.context.session)==null?void 0:s.userId)||""},amount:e};return t==="in"?this.recordCashIn(a,n):this.recordCashOut(a,n)}async getTransactionsByReference(e,t,r,n){let i=n||this.dbAdapter,a={deleted:!1,referenceType:e,...t!==void 0?{referenceId:t}:{}},o=r!=null&&r.filters?{and:[r.filters,a]}:a;return await i.query(X,{...r,filters:o})}async getDailySummary(e){let t=e||new Date().toISOString().slice(0,10),r=await this.dbAdapter.query(X,{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 co(g,e){return g*e}function uo(g,e){return e!==0?g/e:NaN}var lr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addUom(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:rt,record:a}),this.context.logActivity("AddUom",{id:r}),a}async updateUom(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(rt,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:rt,record:{id:e}}),this.context.logActivity("DeleteUom",{id:e}),{id:e,queued:!0}}async duplicateUom(e,t){var s;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(rt,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:rt,record:a}),this.context.logActivity("DuplicateUom",{originalId:e,newId:n}),o}convertQuantity(e,t,r){let n=co(e,t.conversionFactor);return uo(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 oe="users";var pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addUser(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(oe,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:oe,record:a}),this.context.logActivity("AddUser",{id:r}),a}async updateUser(e,t,r){var s;let n=await(r||this.dbAdapter).get(oe,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(oe,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:oe,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(oe,{...e,filters:i})}async getUser(e,t){return(t||this.dbAdapter).get(oe,e)}async deleteUser(e,t){var r;return await(t||this.dbAdapter).delete(oe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:oe,record:{id:e}}),this.context.logActivity("DeleteUser",{id:e}),{id:e,queued:!0}}async duplicateUser(e,t){var s;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(oe,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:oe,record:a}),this.context.logActivity("DuplicateUser",{originalId:e,newId:n}),o}};var Ze="suppliers";var mr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addSupplier(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ze,record:a}),this.context.logActivity("AddSupplier",{id:r}),a}async updateSupplier(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(Ze,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ze,record:{id:e}}),this.context.logActivity("DeleteSupplier",{id:e}),{id:e,queued:!0}}async duplicateSupplier(e,t){var s;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(Ze,a);return(s=this.syncStore)==null||s.enqueueChange({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 Te="purchase_orders";var hr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addPurchaseOrder(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Te,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Te,record:a}),this.context.logActivity("AddPurchaseOrder",{id:r}),a}async updatePurchaseOrder(e,t,r){var s;let n=await(r||this.dbAdapter).get(Te,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(Te,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Te,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(Te,{...e,filters:i})}async getPurchaseOrder(e,t){return(t||this.dbAdapter).get(Te,e)}async deletePurchaseOrder(e,t){var r;return await(t||this.dbAdapter).delete(Te,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Te,record:{id:e}}),this.context.logActivity("DeletePurchaseOrder",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrder(e,t){var s;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(Te,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Te,record:a}),this.context.logActivity("DuplicatePurchaseOrder",{originalId:e,newId:n}),o}};var $e="purchase_order_items";var fr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addPurchaseOrderItem(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:$e,record:a}),this.context.logActivity("AddPurchaseOrderItem",{id:r}),a}async updatePurchaseOrderItem(e,t,r){var s;let n=await(r||this.dbAdapter).get($e,e);if(!n)throw new Error(`PurchaseOrderItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update($e,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:$e,record:o}),this.context.logActivity("UpdatePurchaseOrderItem",{id:e}),o}async getPurchaseOrderItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query($e,{...e,filters:i})}async getPurchaseOrderItem(e,t){return(t||this.dbAdapter).get($e,e)}async deletePurchaseOrderItem(e,t){var r;return await(t||this.dbAdapter).delete($e,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:$e,record:{id:e}}),this.context.logActivity("DeletePurchaseOrderItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrderItem(e,t){var s;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($e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:$e,record:a}),this.context.logActivity("DuplicatePurchaseOrderItem",{originalId:e,newId:n}),o}};var De="purchases";var ge="payables";var Ve="financial_settings";var yr=class{constructor(e){this.context=e;this.defaultBaseCurrencyCode="IDR";var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore(),this.docNumberPolicy=new xt(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}}async getCostingMethod(e){var n;let t=await e.query(Ve,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}],limit:1});return String(((n=t[0])==null?void 0:n.costingMethod)||"FIFO").trim().toUpperCase()==="AVERAGE"?"AVERAGE":"FIFO"}async applyCostingPolicy(e,t){var a,o;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 s of t){let d=Number(s.quantity),c=Number(s.unitCost);if(!Number.isFinite(d)||!Number.isFinite(c)||d<=0)continue;let l=i.get(s.productId)||{quantity:0,totalCost:0};l.quantity+=d,l.totalCost+=d*c,i.set(s.productId,l)}for(let[s,d]of i.entries()){let c=await e.get(se,s);if(!c||c.deleted)continue;let l=d.totalCost/d.quantity,u=await r.getStock(s),h=c.cost;if(n==="AVERAGE"){let b=Math.max(0,Number(u)||0),p=b+d.quantity;p>0?h=(c.cost*b+d.totalCost)/p:h=l}else(Number(u)||0)<=0&&(h=l);if(!Number.isFinite(h)||h===c.cost)continue;let m=new Date().toISOString(),f=await e.update(se,s,{cost:h,version:c.version+1,lastModified:m});(o=this.syncStore)==null||o.enqueueChange({type:"update",model:se,record:f})}}async addPurchase(e,t){var d,c;let r=C(),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(De,o);return(c=this.syncStore)==null||c.enqueueChange({type:"create",model:De,record:s}),this.context.logActivity("AddPurchase",{id:r}),s}async updatePurchase(e,t,r){var s;let n=await(r||this.dbAdapter).get(De,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(De,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:De,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(De,{...e,filters:i})}async getPurchase(e,t){return(t||this.dbAdapter).get(De,e)}async deletePurchase(e,t){var r;return await(t||this.dbAdapter).delete(De,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:De,record:{id:e}}),this.context.logActivity("DeletePurchase",{id:e}),{id:e,queued:!0}}async duplicatePurchase(e,t){var s;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(De,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:De,record:a}),this.context.logActivity("DuplicatePurchase",{originalId:e,newId:n}),o}async finalizePurchase(e,t,r){var u,h,m;if(!r){let f=await this.dbAdapter.transaction(async b=>this.finalizePurchase(e,t,b));return this.context.eventBus.emit("purchase:finalized",e),f}let n=(h=(u=this.context)==null?void 0:u.domainServices)==null?void 0:h.inventory,i=await r.get(De,e);if(!i)throw new Error(`Purchase not found for id ${e}`);let a=await r.query(Ie,{filters:{and:[{field:"purchaseId",value:e},{field:"deleted",value:!1}]}}),o=a.reduce((f,b)=>f+b.unitCost*b.quantity,0),s=Date.now(),d=new Date().toISOString(),c=this.resolveCurrencySnapshot(i,o);await r.update(De,e,{total:o,...c,version:s,lastModified:d});let l={...i,total:o,...c,version:s,lastModified:d};await this.applyCostingPolicy(r,a.map(f=>({productId:f.productId,quantity:f.quantity,unitCost:f.unitCost})));for(let f of a)await n.updateStock(f.productId,f.quantity,"purchase",De,e,r);return await this.context.domainServices.priceHistory.recordPriceHistory(a.map(f=>({productId:f.productId,unitCost:f.unitCost,supplierId:i.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:l.supplierId,purchaseId:l.id,amount:l.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:l.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:l.total,method:t.method,data:{referenceType:"purchase",referenceId:l.id,...t.data||{}}},r),(m=this.syncStore)==null||m.enqueueChange({type:"update",model:De,record:l}),{purchase:l,queued:!0}}async receivePurchaseFromPO(e,t,r){var q,L,w,M,U,F,$,H,G;if(!r){let B=await this.dbAdapter.transaction(async P=>this.receivePurchaseFromPO(e,t,P));return this.context.eventBus.emit("purchase:finalized",B.purchase.id),B}let n=(L=(q=this.context)==null?void 0:q.domainServices)==null?void 0:L.inventory,i=await r.get(Te,e);if(!i)throw new Error(`PurchaseOrder not found for id ${e}`);if(i.status!=="draft"&&i.status!=="sent"&&i.status!=="partially_received")throw new Error(`PurchaseOrder with id ${e} cannot be received as it is not in draft/sent/partially_received status`);let a=await r.query($e,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}}),s=(await r.query(De,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}})).map(B=>B.id),d=new Map;if(s.length>0){let B=await r.query(Ie,{filters:{and:[{field:"deleted",value:!1},{or:s.map(P=>({field:"purchaseId",value:P}))}]}});for(let P of B)P.purchaseOrderItemId&&d.set(P.purchaseOrderItemId,(d.get(P.purchaseOrderItemId)||0)+Number(P.quantity||0))}let c=new Map(a.map(B=>[B.id,B])),l=new Map;for(let B of a){let P=l.get(B.productId)||[];P.push(B),l.set(B.productId,P)}let u=[],h=Array.isArray(t.receivedItems)?t.receivedItems:null;if(h&&h.length>0){let B=((w=this.context.config)==null?void 0:w.requireLotExpiryForPurchaseReceiving)===!0;for(let P of h){let R=P.purchaseOrderItemId?c.get(P.purchaseOrderItemId):void 0;if(!R&&P.productId){let ue=l.get(P.productId)||[];if(ue.length===1)R=ue[0];else if(ue.length>1)throw new Error(`Ambiguous productId ${P.productId}: provide purchaseOrderItemId for partial receiving`)}if(!R)throw new Error("Invalid partial receiving payload: source purchase order item not found");let I=Number(P.receivedQuantity);if(!Number.isFinite(I)||I<=0)throw new Error("Invalid partial receiving payload: receivedQuantity must be > 0");let Z=d.get(R.id)||0,J=u.filter(ue=>ue.sourceOrderItem.id===R.id).reduce((ue,be)=>ue+be.quantity,0),Y=Number(R.quantity)-Z-J;if(I>Y)throw new Error(`Partial receiving exceeds remaining quantity for PO item ${R.id}`);let W=P.unitCost!=null?Number(P.unitCost):Number(R.unitCost);if(!Number.isFinite(W)||W<0)throw new Error("Invalid partial receiving payload: unitCost must be >= 0");let Re=P.serialNumber!=null?String(P.serialNumber).trim():"";if(Re&&I!==1)throw new Error("Serial-number receiving currently requires receivedQuantity = 1");u.push({sourceOrderItem:R,quantity:I,unitCost:W,uomId:P.uomId!==void 0?P.uomId:R.uomId,lotNumber:P.lotNumber!=null&&String(P.lotNumber).trim()||null,serialNumber:Re||null,expiryDate:P.expiryDate!=null&&String(P.expiryDate).trim()||null,note:P.note!=null?String(P.note):null});let me=u[u.length-1];if(B){if(!me.lotNumber)throw new Error("Lot policy violation: lotNumber is required when requireLotExpiryForPurchaseReceiving=true");if(!me.expiryDate)throw new Error("Lot policy violation: expiryDate is required when requireLotExpiryForPurchaseReceiving=true")}}}else{if(((M=this.context.config)==null?void 0:M.requireLotExpiryForPurchaseReceiving)===!0)throw new Error("Lot policy violation: receivedItems with lotNumber and expiryDate are required when requireLotExpiryForPurchaseReceiving=true");for(let B of a){let P=d.get(B.id)||0,O=Number(B.quantity)-P;O<=0||u.push({sourceOrderItem:B,quantity:O,unitCost:Number(B.unitCost),uomId:B.uomId,lotNumber:null,serialNumber:null,expiryDate:null,note:null})}}if(u.length===0)throw new Error(`PurchaseOrder with id ${e} has no remaining receivable items`);let m=u.reduce((B,P)=>B+P.unitCost*P.quantity,0),f=C(),b=new Date().toISOString(),p=((U=this.context.config)==null?void 0:U.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",i.date||b):null,y={id:f,supplierId:i.supplierId,userId:i.userId,purchaseOrderId:e,date:i.date,total:m,...this.resolveCurrencySnapshot(i,m),note:p?this.docNumberPolicy.withNote(i.note,p):i.note,version:1,lastModified:b,deleted:!1};await r.create(De,y),(F=this.syncStore)==null||F.enqueueChange({type:"create",model:De,record:y});for(let B of u){let P=C(),O={id:P,purchaseId:f,purchaseOrderItemId:B.sourceOrderItem.id,productId:B.sourceOrderItem.productId,quantity:B.quantity,uomId:B.uomId,unitCost:B.unitCost,version:1,lastModified:b,deleted:!1};if(await r.create(Ie,O),($=this.syncStore)==null||$.enqueueChange({type:"create",model:Ie,record:O}),B.lotNumber||B.serialNumber||B.expiryDate){let R={id:C(),productId:B.sourceOrderItem.productId,purchaseId:f,purchaseItemId:P,purchaseOrderId:e,purchaseOrderItemId:B.sourceOrderItem.id,lotNumber:B.lotNumber,serialNumber:B.serialNumber,expiryDate:B.expiryDate,quantity:B.quantity,remainingQuantity:B.quantity,status:"active",note:B.note,version:1,lastModified:b,deleted:!1};await r.create(ut,R),(H=this.syncStore)==null||H.enqueueChange({type:"create",model:ut,record:R})}}let v=new Map(d);for(let B of u)v.set(B.sourceOrderItem.id,(v.get(B.sourceOrderItem.id)||0)+B.quantity);let S=a.every(B=>(v.get(B.id)||0)>=Number(B.quantity))?"received":"partially_received",A=Date.now(),_=new Date().toISOString();await r.update(Te,e,{status:S,version:A,lastModified:_}),(G=this.syncStore)==null||G.enqueueChange({type:"update",model:Te,record:{id:e,status:S,version:A,lastModified:_}});let T=u.filter(B=>Number(B.unitCost)!==Number(B.sourceOrderItem.unitCost)).map(B=>({purchaseOrderItemId:B.sourceOrderItem.id,productId:B.sourceOrderItem.productId,orderedUnitCost:B.sourceOrderItem.unitCost,receivedUnitCost:B.unitCost,quantity:B.quantity,varianceAmount:(B.unitCost-B.sourceOrderItem.unitCost)*B.quantity}));T.length>0&&await this.context.logActivity("PO_PRICE_VARIANCE_DETECTED",{purchaseOrderId:e,purchaseId:f,entries:T},r),await this.applyCostingPolicy(r,u.map(B=>({productId:B.sourceOrderItem.productId,quantity:B.quantity,unitCost:B.unitCost})));for(let B of u)await n.updateStock(B.sourceOrderItem.productId,B.quantity,"purchase",De,f,r);return await this.context.domainServices.priceHistory.recordPriceHistory(u.map(B=>({productId:B.sourceOrderItem.productId,unitCost:B.unitCost,supplierId:i.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:y.supplierId,purchaseId:y.id,amount:y.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:y.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:y.total,method:t.method,data:{referenceType:"purchase",referenceId:y.id,...t.data||{}}},r),{purchase:y,queued:!0}}async createPurchaseFromCart(e){var a,o,s,d;let t=(o=(a=this.context)==null?void 0:a.domainServices)==null?void 0:o.inventory,r=(s=this.context.domainServices)==null?void 0:s.uom,n=(await r.getUoms()).reduce((c,l)=>({...c,[l.id]:l}),{}),i;try{i=await this.dbAdapter.transaction(async c=>{var v,x;let l=new Date().toISOString(),u=C(),h=((v=this.context.config)==null?void 0:v.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",l):null,m=[],f=e.items.reduce((S,A)=>S+A.unitCost*A.quantity,0),b={id:u,supplierId:e.supplierId,userId:((x=this.context.session)==null?void 0:x.userId)||"",purchaseOrderId:null,date:l,total:f,...this.resolveCurrencySnapshot(e,f),note:h?this.docNumberPolicy.withNote(e.note||null,h):e.note||null,version:1,lastModified:l,deleted:!1};await c.create(De,b),m.push({type:"create",model:De,record:b});let p=e.items.map(S=>({id:C(),purchaseId:u,purchaseOrderItemId:null,productId:S.productId,quantity:S.quantity,uomId:S.uomId||null,unitCost:S.unitCost,version:1,lastModified:l,deleted:!1}));await c.bulkCreate(Ie,p);for(let S of p)m.push({type:"create",model:Ie,record:S});await this.applyCostingPolicy(c,p.map(S=>{let A=typeof S.uomId=="string"?n[S.uomId].conversionFactor:1;return{productId:S.productId,quantity:r.convertQuantity(S.quantity,{conversionFactor:A},{conversionFactor:1}),unitCost:r.convertUnitPrice(S.unitCost,{conversionFactor:A},{conversionFactor:1})}}));for(let S of p){let A=typeof S.uomId=="string"?n[S.uomId].conversionFactor:1;await t.updateStock(S.productId,r.convertQuantity(S.quantity,{conversionFactor:A},{conversionFactor:1}),"purchase",De,u,c)}let y=[];for(let S of p){let A=typeof S.uomId=="string"?n[S.uomId].conversionFactor:1;y.push({productId:S.productId,unitCost:r.convertUnitPrice(S.unitCost,{conversionFactor:A},{conversionFactor:1}),supplierId:e.supplierId,effectiveDate:l})}if(await this.context.domainServices.priceHistory.recordPriceHistory(y,c),e.paymentMethod==="tempo"){let S=await this.context.domainServices.payable.addPayable({supplierId:b.supplierId,purchaseId:b.id,amount:b.total,dueDate:e.dueDate,status:"unpaid",paidAmount:0,date:b.date||new Date().toISOString()},c);m.push({type:"create",model:ge,record:S})}else{let S=await this.context.domainServices.transaction.recordCashOut({amount:f,method:e.paymentMethod,data:{referenceType:"purchase",referenceId:u,...e.paymentData||{}}},c);m.push({type:"create",model:X,record:S})}return{purchase:b,items:p,purchaseId:u,syncChanges:m}})}catch(c){throw t.clearStockCache(),c}for(let c of i.syncChanges)(d=this.syncStore)==null||d.enqueueChange(c);return this.context.eventBus.emit("purchase:finalized",i.purchaseId),{purchase:i.purchase,items:i.items}}};var gr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addPurchaseItem(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ie,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ie,record:a}),this.context.logActivity("AddPurchaseItem",{id:r}),a}async updatePurchaseItem(e,t,r){var s;let n=await(r||this.dbAdapter).get(Ie,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(Ie,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Ie,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(Ie,{...e,filters:i})}async getPurchaseItem(e,t){return(t||this.dbAdapter).get(Ie,e)}async deletePurchaseItem(e,t){var r;return await(t||this.dbAdapter).delete(Ie,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ie,record:{id:e}}),this.context.logActivity("DeletePurchaseItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseItem(e,t){var s;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(Ie,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Ie,record:a}),this.context.logActivity("DuplicatePurchaseItem",{originalId:e,newId:n}),o}};var _e="inventory_logs";var br=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addInventoryLog(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(_e,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:_e,record:a}),this.context.logActivity("AddInventoryLog",{id:r}),a}async updateInventoryLog(e,t,r){var s;if(!await(r||this.dbAdapter).get(_e,e))throw new Error(`InventoryLog with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e},o=await(r||this.dbAdapter).update(_e,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:_e,record:o}),this.context.logActivity("UpdateInventoryLog",{id:e}),o}async getInventoryLogs(e,t){return(t||this.dbAdapter).query(_e,e)}async getInventoryLog(e,t){return(t||this.dbAdapter).get(_e,e)}async deleteInventoryLog(e,t){var r;return await(t||this.dbAdapter).delete(_e,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:_e,record:{id:e}}),this.context.logActivity("DeleteInventoryLog",{id:e}),{id:e,queued:!0}}async duplicateInventoryLog(e,t){var s;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(_e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:_e,record:a}),this.context.logActivity("DuplicateInventoryLog",{originalId:e,newId:n}),o}};var Ye="price_histories";var vr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addPriceHistory(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ye,record:a}),this.context.logActivity("AddPriceHistory",{id:r}),a}async updatePriceHistory(e,t,r){var s;let n=await(r||this.dbAdapter).get(Ye,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(Ye,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Ye,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(Ye,{...e,filters:i})}async getPriceHistory(e,t){return(t||this.dbAdapter).get(Ye,e)}async deletePriceHistory(e,t){var r;return await(t||this.dbAdapter).delete(Ye,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ye,record:{id:e}}),this.context.logActivity("DeletePriceHistory",{id:e}),{id:e,queued:!0}}async duplicatePriceHistory(e,t){var s;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(Ye,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Ye,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(Ye,a);this.context.logActivity("RecordPriceHistory",{productId:i.productId,unitCost:i.unitCost}),r.push(o)}return r}};var Pe="stock_opnames";var qe="stock_opname_items";var xr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addStockOpname(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Pe,record:a}),this.context.logActivity("AddStockOpname",{id:r}),a}async updateStockOpname(e,t,r){var s;let n=await(r||this.dbAdapter).get(Pe,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(Pe,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Pe,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(Pe,{...e,filters:i})}async getStockOpname(e,t){return(t||this.dbAdapter).get(Pe,e)}async deleteStockOpname(e,t){var r;return await(t||this.dbAdapter).delete(Pe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Pe,record:{id:e}}),this.context.logActivity("DeleteStockOpname",{id:e}),{id:e,queued:!0}}async duplicateStockOpname(e,t){var s;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(Pe,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Pe,record:a}),this.context.logActivity("DuplicateStockOpname",{originalId:e,newId:n}),o}async cancelOpname(e){var n;let t=await this.dbAdapter.get(Pe,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(Pe,e,r);try{(n=this.syncStore)==null||n.enqueueChange({type:"update",model:Pe,id:t.id,record:r})}catch{}}async completeOpname(e){await this.dbAdapter.transaction(async t=>{var o,s,d;let r=(s=(o=this.context)==null?void 0:o.domainServices)==null?void 0:s.inventory,n=await t.get(Pe,e);if(!n||n.deleted||n.status!=="pending")throw new Error("Stock opname tidak valid atau sudah selesai");let i=await t.query(qe,{filters:{stockOpnameId:e,deleted:!1}});for(let c of i)c.difference!==0&&await r.updateStock(c.productId,c.difference,"opname_adjustment",Pe,e,t);let a=await t.update(Pe,e,{status:"completed",lastModified:new Date().toISOString()});(d=this.syncStore)==null||d.enqueueChange({type:"update",model:Pe,id:e,record:a})})}};var Sr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addStockOpnameItem(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(qe,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:qe,record:a}),this.context.logActivity("AddStockOpnameItem",{id:r}),a}async updateStockOpnameItem(e,t,r){var s;let n=await(r||this.dbAdapter).get(qe,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(qe,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:qe,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(qe,{...e,filters:i})}async getStockOpnameItem(e,t){return(t||this.dbAdapter).get(qe,e)}async deleteStockOpnameItem(e,t){var r;return await(t||this.dbAdapter).delete(qe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:qe,record:{id:e}}),this.context.logActivity("DeleteStockOpnameItem",{id:e}),{id:e,queued:!0}}async duplicateStockOpnameItem(e,t){var s;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(qe,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:qe,record:a}),this.context.logActivity("DuplicateStockOpnameItem",{originalId:e,newId:n}),o}};var nt="stock_adjustments";var Ar=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addStockAdjustment(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:nt,record:a}),this.context.logActivity("AddStockAdjustment",{id:r}),a}async updateStockAdjustment(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(nt,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:nt,record:{id:e}}),this.context.logActivity("DeleteStockAdjustment",{id:e}),{id:e,queued:!0}}async duplicateStockAdjustment(e,t){var s;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(nt,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:nt,record:a}),this.context.logActivity("DuplicateStockAdjustment",{originalId:e,newId:n}),o}};var it="report_schedules";var Ir=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addReportSchedule(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:it,record:a}),this.context.logActivity("AddReportSchedule",{id:r}),a}async updateReportSchedule(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(it,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:it,record:{id:e}}),this.context.logActivity("DeleteReportSchedule",{id:e}),{id:e,queued:!0}}async duplicateReportSchedule(e,t){var s;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(s=this.syncStore)==null||s.enqueueChange({type:"create",model:it,record:a}),this.context.logActivity("DuplicateReportSchedule",{originalId:e,newId:n}),o}};var Dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addFinancialSetting(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ve,record:a}),this.context.logActivity("AddFinancialSetting",{id:r}),a}async updateFinancialSetting(e,t,r){var s;let n=await(r||this.dbAdapter).get(Ve,e);if(!n)throw new Error(`FinancialSetting with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ve,e,a);return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:Ve,record:o}),this.context.logActivity("UpdateFinancialSetting",{id:e}),o}async getFinancialSettings(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ve,{...e,filters:i})}async getFinancialSetting(e,t){return(t||this.dbAdapter).get(Ve,e)}async deleteFinancialSetting(e,t){var r;return await(t||this.dbAdapter).delete(Ve,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ve,record:{id:e}}),this.context.logActivity("DeleteFinancialSetting",{id:e}),{id:e,queued:!0}}async duplicateFinancialSetting(e,t){var s;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(Ve,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Ve,record:a}),this.context.logActivity("DuplicateFinancialSetting",{originalId:e,newId:n}),o}};var at="expenses";var wr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addExpense(e,t){var o;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(o=this.syncStore)==null||o.enqueueChange({type:"create",model:at,record:a}),this.context.logActivity("AddExpense",{id:r}),a}async updateExpense(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(at,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:at,record:{id:e}}),this.context.logActivity("DeleteExpense",{id:e}),{id:e,queued:!0}}async duplicateExpense(e,t){var s;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(s=this.syncStore)==null||s.enqueueChange({type:"create",model:at,record:a}),this.context.logActivity("DuplicateExpense",{originalId:e,newId:n}),o}};var Cr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addReceivable(e,t){var o;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||(o=this.syncStore)==null||o.enqueueChange({type:"create",model:fe,record:a}),this.context.logActivity("AddReceivable",{id:r}),a}async updateReceivable(e,t,r){var s;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||(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(fe,e),t||(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:fe,record:{id:e}}),this.context.logActivity("DeleteReceivable",{id:e}),{id:e,queued:!0}}async duplicateReceivable(e,t){var s;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||(s=this.syncStore)==null||s.enqueueChange({type:"create",model:fe,record:a}),this.context.logActivity("DuplicateReceivable",{originalId:e,newId:n}),o}};var Pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}async addPayable(e,t){var o;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 t||(o=this.syncStore)==null||o.enqueueChange({type:"create",model:ge,record:a}),this.context.logActivity("AddPayable",{id:r}),a}async updatePayable(e,t,r){var s;let n=await(r||this.dbAdapter).get(ge,e);if(!n)throw new Error(`Payable with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ge,e,a);return r||(s=this.syncStore)==null||s.enqueueChange({type:"update",model:ge,record:o}),this.context.logActivity("UpdatePayable",{id:e}),o}async getPayables(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ge,{...e,filters:i})}async getPayable(e,t){return(t||this.dbAdapter).get(ge,e)}async deletePayable(e,t){var r;return await(t||this.dbAdapter).delete(ge,e),t||(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:ge,record:{id:e}}),this.context.logActivity("DeletePayable",{id:e}),{id:e,queued:!0}}async duplicatePayable(e,t){var s;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(ge,a);return t||(s=this.syncStore)==null||s.enqueueChange({type:"create",model:ge,record:a}),this.context.logActivity("DuplicatePayable",{originalId:e,newId:n}),o}async updatePaidAmount(e,t){var s,d;let r=(s=this.context.registry)==null?void 0:s.loggerAdapter,n=await this.dbAdapter.get(ge,e);if(!n)throw r.logError("Payable not found",{payableId:e}),new Error(`Payable ${e} not found`);let i=(n.paidAmount||0)+t,a=i>=n.amount?"paid":"partial",o={paidAmount:i,status:a,version:Date.now(),lastModified:new Date().toISOString()};await this.dbAdapter.update(ge,e,o),(d=this.syncStore)==null||d.enqueueChange({type:"update",model:ge,record:{id:e,...o}}),this.context.logActivity("updatePaidAmount",{payableId:e,paidAmount:i,status:a}),r.logInfo("Payable updated",{payableId:e,paidAmount:i,status:a})}};var Ne="settlements";var Er=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.syncStore=e.getSyncStore()}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}async addSettlement(e,t){var o;let r=C(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ne,i);return(o=this.syncStore)==null||o.enqueueChange({type:"create",model:Ne,record:a}),this.context.logActivity("AddSettlement",{id:r}),a}async updateSettlement(e,t,r){var s;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(s=this.syncStore)==null||s.enqueueChange({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){var r;return await(t||this.dbAdapter).delete(Ne,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:Ne,record:{id:e}}),this.context.logActivity("DeleteSettlement",{id:e}),{id:e,queued:!0}}async duplicateSettlement(e,t){var s;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(Ne,a);return(s=this.syncStore)==null||s.enqueueChange({type:"create",model:Ne,record:a}),this.context.logActivity("DuplicateSettlement",{originalId:e,newId:n}),o}async createSettlement(e){var s,d,c,l;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 f=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(f.length){let b=f[0].changes||{},p=String(b.settlementId||"").trim();if(p){let y=await u.get(Ne,p);if(y)return y}}}if(e.receivableId){let f=await u.get(fe,e.receivableId);if(!f||f.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let b=f.amount-f.paidAmount;if(e.amount>b)throw new Error("Settlement amount exceeds remaining receivable amount")}if(e.payableId){let f=await u.get(ge,e.payableId);if(!f||f.deleted)throw new Error(`Payable ${e.payableId} not found`);let b=f.amount-f.paidAmount;if(e.amount>b)throw new Error("Settlement amount exceeds remaining payable amount")}let h={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},m=await u.create(Ne,h);if(e.receivableId){let f=await u.get(fe,e.receivableId);if(!f||f.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let b=f.paidAmount+e.amount,p={...f,paidAmount:b,status:b>=f.amount?"paid":"partial",version:Date.now(),lastModified:r};await u.update(fe,p.id,p)}if(e.payableId){let f=await u.get(ge,e.payableId);if(!f||f.deleted)throw new Error(`Payable ${e.payableId} not found`);let b=f.paidAmount+e.amount,p={...f,paidAmount:b,status:b>=f.amount?"paid":"partial",version:Date.now(),lastModified:r};await u.update(ge,p.id,p)}return n&&await u.create(ie,{id:C(),tableName:"idempotency_keys",recordId:n,action:"settlement_create",changes:{settlementId:m.id},userId:String(e.userId||"").trim()||null,timestamp:r}),m});if((d=this.syncStore)==null||d.enqueueChange({type:"create",model:Ne,record:o}),e.receivableId){let u=await this.dbAdapter.get(fe,e.receivableId);u&&((c=this.syncStore)==null||c.enqueueChange({type:"update",model:fe,record:u}))}if(e.payableId){let u=await this.dbAdapter.get(ge,e.payableId);u&&((l=this.syncStore)==null||l.enqueueChange({type:"update",model:ge,record:u}))}return this.context.logActivity("createSettlement",{id:o.id}),t.logInfo("Settlement created",{id:o.id}),o}};function Pt(g){return{all:g=g||new Map,on:function(e,t){var r=g.get(e);r?r.push(t):g.set(e,[t])},off:function(e,t){var r=g.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):g.set(e,[]))},emit:function(e,t){var r=g.get(e);r&&r.slice().map(function(n){n(t)}),(r=g.get("*"))&&r.slice().map(function(n){n(e,t)})}}}var ot=Pt();var Or=class{constructor(e){this.context=e;this.stockCache=new Map;this.isRebuilding=!1;var t;this.adapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.syncStore=this.context.getSyncStore()}async getStock(e){if(this.stockCache.has(e))return this.stockCache.get(e);let t=await this.computeStockFromLogs(e);return this.stockCache.set(e,t),t}async updateStock(e,t,r,n,i,a){var l,u,h;let o=a||this.adapter;if(t<0){let m=(l=this.context.domainServices)==null?void 0:l.bom;if(m&&(await m.getBomsByParentItemId(e)).length>0){let b=await m.expandBom(e),p=Math.abs(t);for(let y of b){let v=y.quantity*p;if(await this.getStock(y.componentItemId)<v)throw new Error(`Insufficient component ${y.componentItemId}`)}for(let y of b)await this.updateStock(y.componentItemId,-y.quantity*p,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:C(),productId:e,change:t,reason:r,referenceType:n,referenceId:i,userId:((u=this.context.session)==null?void 0:u.userId)||"",timestamp:new Date().toISOString()};await o.create(_e,d),(h=this.syncStore)==null||h.enqueueChange({type:"create",model:_e,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(_e,{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`),ot.emit("stockCache:rebuilt")}finally{this.isRebuilding=!1}}}clearStockCache(){this.stockCache.clear()}async computeStockFromLogs(e){var r;let[t]=await this.adapter.query(_e,{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(se,{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 bi={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 gt=[{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
|
+
var Ga=Object.create;var li=Object.defineProperty;var Wa=Object.getOwnPropertyDescriptor;var Ya=Object.getOwnPropertyNames;var Xa=Object.getPrototypeOf,Za=Object.prototype.hasOwnProperty;var Vn=(h=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(h,{get:(e,t)=>(typeof require!="undefined"?require:e)[t]}):h)(function(h){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+h+'" is not supported')});var re=(h,e)=>()=>(e||h((e={exports:{}}).exports,e),e.exports);var Ja=(h,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ya(e))!Za.call(h,n)&&n!==t&&li(h,n,{get:()=>e[n],enumerable:!(r=Wa(e,n))||r.enumerable});return h};var Ot=(h,e,t)=>(t=h!=null?Ga(Xa(h)):{},Ja(e||!h||!h.__esModule?li(t,"default",{value:h,enumerable:!0}):t,h));var mi=re(()=>{var pi;(function(h){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:o(),r=n(h);typeof t.Reflect!="undefined"&&(r=n(t.Reflect,r)),e(r,t),typeof t.Reflect=="undefined"&&(t.Reflect=h);function n(s,c){return function(u,l){Object.defineProperty(s,u,{configurable:!0,writable:!0,value:l}),c&&c(u,l)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function o(){return i()||a()}})(function(e,t){var r=Object.prototype.hasOwnProperty,n=typeof Symbol=="function",i=n&&typeof Symbol.toPrimitive!="undefined"?Symbol.toPrimitive:"@@toPrimitive",a=n&&typeof Symbol.iterator!="undefined"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",s={__proto__:[]}instanceof Array,c=!o&&!s,u={create:o?function(){return Je(Object.create(null))}:s?function(){return Je({__proto__:null})}:function(){return Je({})},has:c?function(S,C){return r.call(S,C)}:function(S,C){return C in S},get:c?function(S,C){return r.call(S,C)?S[C]:void 0}:function(S,C){return S[C]}},l=Object.getPrototypeOf(Function),d=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Pt(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Ct(),f=typeof WeakMap=="function"?WeakMap:dt(),y=n?Symbol.for("@reflect-metadata:registry"):void 0,v=Dt(),p=ct(v);function g(S,C,k,N){if(D(k)){if(!Oe(S))throw new TypeError;if(!ze(C))throw new TypeError;return L(S,C)}else{if(!Oe(S))throw new TypeError;if(!X(C))throw new TypeError;if(!X(N)&&!D(N)&&!Z(N))throw new TypeError;return Z(N)&&(N=void 0),k=ve(k),Q(S,C,k,N)}}e("decorate",g);function x(S,C){function k(N,W){if(!X(N))throw new TypeError;if(!D(W)&&!je(W))throw new TypeError;U(S,C,N,W)}return k}e("metadata",x);function b(S,C,k,N){if(!X(k))throw new TypeError;return D(N)||(N=ve(N)),U(S,C,k,N)}e("defineMetadata",b);function A(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),T(S,C,k)}e("hasMetadata",A);function I(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),j(S,C,k)}e("hasOwnMetadata",I);function F(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),z(S,C,k)}e("getMetadata",F);function w(S,C,k){if(!X(C))throw new TypeError;return D(k)||(k=ve(k)),B(S,C,k)}e("getOwnMetadata",w);function q(S,C){if(!X(S))throw new TypeError;return D(C)||(C=ve(C)),O(S,C)}e("getMetadataKeys",q);function M(S,C){if(!X(S))throw new TypeError;return D(C)||(C=ve(C)),_(S,C)}e("getOwnMetadataKeys",M);function E(S,C,k){if(!X(C))throw new TypeError;if(D(k)||(k=ve(k)),!X(C))throw new TypeError;D(k)||(k=ve(k));var N=mt(C,k,!1);return D(N)?!1:N.OrdinaryDeleteMetadata(S,C,k)}e("deleteMetadata",E);function L(S,C){for(var k=S.length-1;k>=0;--k){var N=S[k],W=N(C);if(!D(W)&&!Z(W)){if(!ze(W))throw new TypeError;C=W}}return C}function Q(S,C,k,N){for(var W=S.length-1;W>=0;--W){var pe=S[W],be=pe(C,k,N);if(!D(be)&&!Z(be)){if(!X(be))throw new TypeError;N=be}}return N}function T(S,C,k){var N=j(S,C,k);if(N)return!0;var W=Ne(C);return Z(W)?!1:T(S,W,k)}function j(S,C,k){var N=mt(C,k,!1);return D(N)?!1:se(N.OrdinaryHasOwnMetadata(S,C,k))}function z(S,C,k){var N=j(S,C,k);if(N)return B(S,C,k);var W=Ne(C);if(!Z(W))return z(S,W,k)}function B(S,C,k){var N=mt(C,k,!1);if(!D(N))return N.OrdinaryGetOwnMetadata(S,C,k)}function U(S,C,k,N){var W=mt(k,N,!0);W.OrdinaryDefineOwnMetadata(S,C,k,N)}function O(S,C){var k=_(S,C),N=Ne(S);if(N===null)return k;var W=O(N,C);if(W.length<=0)return k;if(k.length<=0)return W;for(var pe=new m,be=[],ee=0,H=k;ee<H.length;ee++){var V=H[ee],K=pe.has(V);K||(pe.add(V),be.push(V))}for(var G=0,ne=W;G<ne.length;G++){var V=ne[G],K=pe.has(V);K||(pe.add(V),be.push(V))}return be}function _(S,C){var k=mt(S,C,!1);return k?k.OrdinaryOwnMetadataKeys(S,C):[]}function R(S){if(S===null)return 1;switch(typeof S){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return S===null?1:6;default:return 6}}function D(S){return S===void 0}function Z(S){return S===null}function te(S){return typeof S=="symbol"}function X(S){return typeof S=="object"?S!==null:typeof S=="function"}function Y(S,C){switch(R(S)){case 0:return S;case 1:return S;case 2:return S;case 3:return S;case 4:return S;case 5:return S}var k=C===3?"string":C===5?"number":"default",N=st(S,i);if(N!==void 0){var W=N.call(S,k);if(X(W))throw new TypeError;return W}return ye(S,k==="default"?"number":k)}function ye(S,C){if(C==="string"){var k=S.toString;if(le(k)){var N=k.call(S);if(!X(N))return N}var W=S.valueOf;if(le(W)){var N=W.call(S);if(!X(N))return N}}else{var W=S.valueOf;if(le(W)){var N=W.call(S);if(!X(N))return N}var pe=S.toString;if(le(pe)){var N=pe.call(S);if(!X(N))return N}}throw new TypeError}function se(S){return!!S}function qe(S){return""+S}function ve(S){var C=Y(S,3);return te(C)?C:qe(C)}function Oe(S){return Array.isArray?Array.isArray(S):S instanceof Object?S instanceof Array:Object.prototype.toString.call(S)==="[object Array]"}function le(S){return typeof S=="function"}function ze(S){return typeof S=="function"}function je(S){switch(R(S)){case 3:return!0;case 4:return!0;default:return!1}}function Ke(S,C){return S===C||S!==S&&C!==C}function st(S,C){var k=S[C];if(k!=null){if(!le(k))throw new TypeError;return k}}function ht(S){var C=st(S,a);if(!le(C))throw new TypeError;var k=C.call(S);if(!X(k))throw new TypeError;return k}function ut(S){return S.value}function ke(S){var C=S.next();return C.done?!1:C}function Be(S){var C=S.return;C&&C.call(S)}function Ne(S){var C=Object.getPrototypeOf(S);if(typeof S!="function"||S===l||C!==l)return C;var k=S.prototype,N=k&&Object.getPrototypeOf(k);if(N==null||N===Object.prototype)return C;var W=N.constructor;return typeof W!="function"||W===S?C:W}function ft(){var S;!D(y)&&typeof t.Reflect!="undefined"&&!(y in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(S=pt(t.Reflect));var C,k,N,W=new f,pe={registerProvider:be,getProvider:H,setProvider:K};return pe;function be(G){if(!Object.isExtensible(pe))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case S===G:break;case D(C):C=G;break;case C===G:break;case D(k):k=G;break;case k===G:break;default:N===void 0&&(N=new m),N.add(G);break}}function ee(G,ne){if(!D(C)){if(C.isProviderFor(G,ne))return C;if(!D(k)){if(k.isProviderFor(G,ne))return C;if(!D(N))for(var ce=ht(N);;){var xe=ke(ce);if(!xe)return;var Ge=ut(xe);if(Ge.isProviderFor(G,ne))return Be(ce),Ge}}}if(!D(S)&&S.isProviderFor(G,ne))return S}function H(G,ne){var ce=W.get(G),xe;return D(ce)||(xe=ce.get(ne)),D(xe)&&(xe=ee(G,ne),D(xe)||(D(ce)&&(ce=new d,W.set(G,ce)),ce.set(ne,xe))),xe}function V(G){if(D(G))throw new TypeError;return C===G||k===G||!D(N)&&N.has(G)}function K(G,ne,ce){if(!V(ce))throw new Error("Metadata provider not registered.");var xe=H(G,ne);if(xe!==ce){if(!D(xe))return!1;var Ge=W.get(G);D(Ge)&&(Ge=new d,W.set(G,Ge)),Ge.set(ne,ce)}return!0}}function Dt(){var S;return!D(y)&&X(t.Reflect)&&Object.isExtensible(t.Reflect)&&(S=t.Reflect[y]),D(S)&&(S=ft()),!D(y)&&X(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,y,{enumerable:!1,configurable:!1,writable:!1,value:S}),S}function ct(S){var C=new f,k={isProviderFor:function(V,K){var G=C.get(V);return D(G)?!1:G.has(K)},OrdinaryDefineOwnMetadata:be,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:pe,OrdinaryOwnMetadataKeys:ee,OrdinaryDeleteMetadata:H};return v.registerProvider(k),k;function N(V,K,G){var ne=C.get(V),ce=!1;if(D(ne)){if(!G)return;ne=new d,C.set(V,ne),ce=!0}var xe=ne.get(K);if(D(xe)){if(!G)return;if(xe=new d,ne.set(K,xe),!S.setProvider(V,K,k))throw ne.delete(K),ce&&C.delete(V),new Error("Wrong provider for target.")}return xe}function W(V,K,G){var ne=N(K,G,!1);return D(ne)?!1:se(ne.has(V))}function pe(V,K,G){var ne=N(K,G,!1);if(!D(ne))return ne.get(V)}function be(V,K,G,ne){var ce=N(G,ne,!0);ce.set(V,K)}function ee(V,K){var G=[],ne=N(V,K,!1);if(D(ne))return G;for(var ce=ne.keys(),xe=ht(ce),Ge=0;;){var Nt=ke(xe);if(!Nt)return G.length=Ge,G;var $n=ut(Nt);try{G[Ge]=$n}catch($t){try{Be(xe)}finally{throw $t}}Ge++}}function H(V,K,G){var ne=N(K,G,!1);if(D(ne)||!ne.delete(V))return!1;if(ne.size===0){var ce=C.get(K);D(ce)||(ce.delete(G),ce.size===0&&C.delete(ce))}return!0}}function pt(S){var C=S.defineMetadata,k=S.hasOwnMetadata,N=S.getOwnMetadata,W=S.getOwnMetadataKeys,pe=S.deleteMetadata,be=new f,ee={isProviderFor:function(H,V){var K=be.get(H);return!D(K)&&K.has(V)?!0:W(H,V).length?(D(K)&&(K=new m,be.set(H,K)),K.add(V),!0):!1},OrdinaryDefineOwnMetadata:C,OrdinaryHasOwnMetadata:k,OrdinaryGetOwnMetadata:N,OrdinaryOwnMetadataKeys:W,OrdinaryDeleteMetadata:pe};return ee}function mt(S,C,k){var N=v.getProvider(S,C);if(!D(N))return N;if(k){if(v.setProvider(S,C,p))return p;throw new Error("Illegal state.")}}function Pt(){var S={},C=[],k=(function(){function ee(H,V,K){this._index=0,this._keys=H,this._values=V,this._selector=K}return ee.prototype["@@iterator"]=function(){return this},ee.prototype[a]=function(){return this},ee.prototype.next=function(){var H=this._index;if(H>=0&&H<this._keys.length){var V=this._selector(this._keys[H],this._values[H]);return H+1>=this._keys.length?(this._index=-1,this._keys=C,this._values=C):this._index++,{value:V,done:!1}}return{value:void 0,done:!0}},ee.prototype.throw=function(H){throw this._index>=0&&(this._index=-1,this._keys=C,this._values=C),H},ee.prototype.return=function(H){return this._index>=0&&(this._index=-1,this._keys=C,this._values=C),{value:H,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(H){return this._find(H,!1)>=0},ee.prototype.get=function(H){var V=this._find(H,!1);return V>=0?this._values[V]:void 0},ee.prototype.set=function(H,V){var K=this._find(H,!0);return this._values[K]=V,this},ee.prototype.delete=function(H){var V=this._find(H,!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--,Ke(H,this._cacheKey)&&(this._cacheKey=S,this._cacheIndex=-2),!0}return!1},ee.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=S,this._cacheIndex=-2},ee.prototype.keys=function(){return new k(this._keys,this._values,W)},ee.prototype.values=function(){return new k(this._keys,this._values,pe)},ee.prototype.entries=function(){return new k(this._keys,this._values,be)},ee.prototype["@@iterator"]=function(){return this.entries()},ee.prototype[a]=function(){return this.entries()},ee.prototype._find=function(H,V){if(!Ke(this._cacheKey,H)){this._cacheIndex=-1;for(var K=0;K<this._keys.length;K++)if(Ke(this._keys[K],H)){this._cacheIndex=K;break}}return this._cacheIndex<0&&V&&(this._cacheIndex=this._keys.length,this._keys.push(H),this._values.push(void 0)),this._cacheIndex},ee})();return N;function W(ee,H){return ee}function pe(ee,H){return H}function be(ee,H){return[ee,H]}}function Ct(){var S=(function(){function C(){this._map=new d}return Object.defineProperty(C.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),C.prototype.has=function(k){return this._map.has(k)},C.prototype.add=function(k){return this._map.set(k,k),this},C.prototype.delete=function(k){return this._map.delete(k)},C.prototype.clear=function(){this._map.clear()},C.prototype.keys=function(){return this._map.keys()},C.prototype.values=function(){return this._map.keys()},C.prototype.entries=function(){return this._map.entries()},C.prototype["@@iterator"]=function(){return this.keys()},C.prototype[a]=function(){return this.keys()},C})();return S}function dt(){var S=16,C=u.create(),k=N();return(function(){function H(){this._key=N()}return H.prototype.has=function(V){var K=W(V,!1);return K!==void 0?u.has(K,this._key):!1},H.prototype.get=function(V){var K=W(V,!1);return K!==void 0?u.get(K,this._key):void 0},H.prototype.set=function(V,K){var G=W(V,!0);return G[this._key]=K,this},H.prototype.delete=function(V){var K=W(V,!1);return K!==void 0?delete K[this._key]:!1},H.prototype.clear=function(){this._key=N()},H})();function N(){var H;do H="@@WeakMap@@"+ee();while(u.has(C,H));return C[H]=!0,H}function W(H,V){if(!r.call(H,k)){if(!V)return;Object.defineProperty(H,k,{value:u.create()})}return H[k]}function pe(H,V){for(var K=0;K<V;++K)H[K]=Math.random()*255|0;return H}function be(H){if(typeof Uint8Array=="function"){var V=new Uint8Array(H);return typeof crypto!="undefined"?crypto.getRandomValues(V):typeof msCrypto!="undefined"?msCrypto.getRandomValues(V):pe(V,H),V}return pe(new Array(H),H)}function ee(){var H=be(S);H[6]=H[6]&79|64,H[8]=H[8]&191|128;for(var V="",K=0;K<S;++K){var G=H[K];(K===4||K===6||K===8)&&(V+="-"),G<16&&(V+="0"),V+=G.toString(16).toLowerCase()}return V}}function Je(S){return S.__=void 0,delete S.__,S}})})(pi||(pi={}))});var ie=re((zr,Ii)=>{(function(h,e){typeof zr=="object"?Ii.exports=zr=e():typeof define=="function"&&define.amd?define([],e):h.CryptoJS=e()})(zr,function(){var h=h||(function(e,t){var r;if(typeof window!="undefined"&&window.crypto&&(r=window.crypto),typeof self!="undefined"&&self.crypto&&(r=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof window!="undefined"&&window.msCrypto&&(r=window.msCrypto),!r&&typeof globalThis!="undefined"&&globalThis.crypto&&(r=globalThis.crypto),!r&&typeof Vn=="function")try{r=Vn("crypto")}catch{}var n=function(){if(r){if(typeof r.getRandomValues=="function")try{return r.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof r.randomBytes=="function")try{return r.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},i=Object.create||(function(){function p(){}return function(g){var x;return p.prototype=g,x=new p,p.prototype=null,x}})(),a={},o=a.lib={},s=o.Base=(function(){return{extend:function(p){var g=i(this);return p&&g.mixIn(p),(!g.hasOwnProperty("init")||this.init===g.init)&&(g.init=function(){g.$super.init.apply(this,arguments)}),g.init.prototype=g,g.$super=this,g},create:function(){var p=this.extend();return p.init.apply(p,arguments),p},init:function(){},mixIn:function(p){for(var g in p)p.hasOwnProperty(g)&&(this[g]=p[g]);p.hasOwnProperty("toString")&&(this.toString=p.toString)},clone:function(){return this.init.prototype.extend(this)}}})(),c=o.WordArray=s.extend({init:function(p,g){p=this.words=p||[],g!=t?this.sigBytes=g:this.sigBytes=p.length*4},toString:function(p){return(p||l).stringify(this)},concat:function(p){var g=this.words,x=p.words,b=this.sigBytes,A=p.sigBytes;if(this.clamp(),b%4)for(var I=0;I<A;I++){var F=x[I>>>2]>>>24-I%4*8&255;g[b+I>>>2]|=F<<24-(b+I)%4*8}else for(var w=0;w<A;w+=4)g[b+w>>>2]=x[w>>>2];return this.sigBytes+=A,this},clamp:function(){var p=this.words,g=this.sigBytes;p[g>>>2]&=4294967295<<32-g%4*8,p.length=e.ceil(g/4)},clone:function(){var p=s.clone.call(this);return p.words=this.words.slice(0),p},random:function(p){for(var g=[],x=0;x<p;x+=4)g.push(n());return new c.init(g,p)}}),u=a.enc={},l=u.Hex={stringify:function(p){for(var g=p.words,x=p.sigBytes,b=[],A=0;A<x;A++){var I=g[A>>>2]>>>24-A%4*8&255;b.push((I>>>4).toString(16)),b.push((I&15).toString(16))}return b.join("")},parse:function(p){for(var g=p.length,x=[],b=0;b<g;b+=2)x[b>>>3]|=parseInt(p.substr(b,2),16)<<24-b%8*4;return new c.init(x,g/2)}},d=u.Latin1={stringify:function(p){for(var g=p.words,x=p.sigBytes,b=[],A=0;A<x;A++){var I=g[A>>>2]>>>24-A%4*8&255;b.push(String.fromCharCode(I))}return b.join("")},parse:function(p){for(var g=p.length,x=[],b=0;b<g;b++)x[b>>>2]|=(p.charCodeAt(b)&255)<<24-b%4*8;return new c.init(x,g)}},m=u.Utf8={stringify:function(p){try{return decodeURIComponent(escape(d.stringify(p)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(p){return d.parse(unescape(encodeURIComponent(p)))}},f=o.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new c.init,this._nDataBytes=0},_append:function(p){typeof p=="string"&&(p=m.parse(p)),this._data.concat(p),this._nDataBytes+=p.sigBytes},_process:function(p){var g,x=this._data,b=x.words,A=x.sigBytes,I=this.blockSize,F=I*4,w=A/F;p?w=e.ceil(w):w=e.max((w|0)-this._minBufferSize,0);var q=w*I,M=e.min(q*4,A);if(q){for(var E=0;E<q;E+=I)this._doProcessBlock(b,E);g=b.splice(0,q),x.sigBytes-=M}return new c.init(g,M)},clone:function(){var p=s.clone.call(this);return p._data=this._data.clone(),p},_minBufferSize:0}),y=o.Hasher=f.extend({cfg:s.extend(),init:function(p){this.cfg=this.cfg.extend(p),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(p){return this._append(p),this._process(),this},finalize:function(p){p&&this._append(p);var g=this._doFinalize();return g},blockSize:512/32,_createHelper:function(p){return function(g,x){return new p.init(x).finalize(g)}},_createHmacHelper:function(p){return function(g,x){return new v.HMAC.init(p,x).finalize(g)}}}),v=a.algo={};return a})(Math);return h})});var Ut=re((jr,Di)=>{(function(h,e){typeof jr=="object"?Di.exports=jr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(jr,function(h){return(function(e){var t=h,r=t.lib,n=r.Base,i=r.WordArray,a=t.x64={},o=a.Word=n.extend({init:function(c,u){this.high=c,this.low=u}}),s=a.WordArray=n.extend({init:function(c,u){c=this.words=c||[],u!=e?this.sigBytes=u:this.sigBytes=c.length*8},toX32:function(){for(var c=this.words,u=c.length,l=[],d=0;d<u;d++){var m=c[d];l.push(m.high),l.push(m.low)}return i.create(l,this.sigBytes)},clone:function(){for(var c=n.clone.call(this),u=c.words=this.words.slice(0),l=u.length,d=0;d<l;d++)u[d]=u[d].clone();return c}})})(),h})});var Ci=re((Kr,Pi)=>{(function(h,e){typeof Kr=="object"?Pi.exports=Kr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Kr,function(h){return(function(){if(typeof ArrayBuffer=="function"){var e=h,t=e.lib,r=t.WordArray,n=r.init,i=r.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||typeof Uint8ClampedArray!="undefined"&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var o=a.byteLength,s=[],c=0;c<o;c++)s[c>>>2]|=a[c]<<24-c%4*8;n.call(this,s,o)}else n.apply(this,arguments)};i.prototype=r}})(),h.lib.WordArray})});var Ei=re((Gr,wi)=>{(function(h,e){typeof Gr=="object"?wi.exports=Gr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Gr,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.enc,i=n.Utf16=n.Utf16BE={stringify:function(o){for(var s=o.words,c=o.sigBytes,u=[],l=0;l<c;l+=2){var d=s[l>>>2]>>>16-l%4*8&65535;u.push(String.fromCharCode(d))}return u.join("")},parse:function(o){for(var s=o.length,c=[],u=0;u<s;u++)c[u>>>1]|=o.charCodeAt(u)<<16-u%2*16;return r.create(c,s*2)}};n.Utf16LE={stringify:function(o){for(var s=o.words,c=o.sigBytes,u=[],l=0;l<c;l+=2){var d=a(s[l>>>2]>>>16-l%4*8&65535);u.push(String.fromCharCode(d))}return u.join("")},parse:function(o){for(var s=o.length,c=[],u=0;u<s;u++)c[u>>>1]|=a(o.charCodeAt(u)<<16-u%2*16);return r.create(c,s*2)}};function a(o){return o<<8&4278255360|o>>>8&16711935}})(),h.enc.Utf16})});var St=re((Wr,Oi)=>{(function(h,e){typeof Wr=="object"?Oi.exports=Wr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Wr,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64={stringify:function(o){var s=o.words,c=o.sigBytes,u=this._map;o.clamp();for(var l=[],d=0;d<c;d+=3)for(var m=s[d>>>2]>>>24-d%4*8&255,f=s[d+1>>>2]>>>24-(d+1)%4*8&255,y=s[d+2>>>2]>>>24-(d+2)%4*8&255,v=m<<16|f<<8|y,p=0;p<4&&d+p*.75<c;p++)l.push(u.charAt(v>>>6*(3-p)&63));var g=u.charAt(64);if(g)for(;l.length%4;)l.push(g);return l.join("")},parse:function(o){var s=o.length,c=this._map,u=this._reverseMap;if(!u){u=this._reverseMap=[];for(var l=0;l<c.length;l++)u[c.charCodeAt(l)]=l}var d=c.charAt(64);if(d){var m=o.indexOf(d);m!==-1&&(s=m)}return a(o,s,u)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function a(o,s,c){for(var u=[],l=0,d=0;d<s;d++)if(d%4){var m=c[o.charCodeAt(d-1)]<<d%4*2,f=c[o.charCodeAt(d)]>>>6-d%4*2,y=m|f;u[l>>>2]|=y<<24-l%4*8,l++}return r.create(u,l)}})(),h.enc.Base64})});var _i=re((Yr,Ri)=>{(function(h,e){typeof Yr=="object"?Ri.exports=Yr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Yr,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.enc,i=n.Base64url={stringify:function(o,s){s===void 0&&(s=!0);var c=o.words,u=o.sigBytes,l=s?this._safe_map:this._map;o.clamp();for(var d=[],m=0;m<u;m+=3)for(var f=c[m>>>2]>>>24-m%4*8&255,y=c[m+1>>>2]>>>24-(m+1)%4*8&255,v=c[m+2>>>2]>>>24-(m+2)%4*8&255,p=f<<16|y<<8|v,g=0;g<4&&m+g*.75<u;g++)d.push(l.charAt(p>>>6*(3-g)&63));var x=l.charAt(64);if(x)for(;d.length%4;)d.push(x);return d.join("")},parse:function(o,s){s===void 0&&(s=!0);var c=o.length,u=s?this._safe_map:this._map,l=this._reverseMap;if(!l){l=this._reverseMap=[];for(var d=0;d<u.length;d++)l[u.charCodeAt(d)]=d}var m=u.charAt(64);if(m){var f=o.indexOf(m);f!==-1&&(c=f)}return a(o,c,l)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function a(o,s,c){for(var u=[],l=0,d=0;d<s;d++)if(d%4){var m=c[o.charCodeAt(d-1)]<<d%4*2,f=c[o.charCodeAt(d)]>>>6-d%4*2,y=m|f;u[l>>>2]|=y<<24-l%4*8,l++}return r.create(u,l)}})(),h.enc.Base64url})});var It=re((Xr,Ti)=>{(function(h,e){typeof Xr=="object"?Ti.exports=Xr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Xr,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[];(function(){for(var m=0;m<64;m++)o[m]=e.abs(e.sin(m+1))*4294967296|0})();var s=a.MD5=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(m,f){for(var y=0;y<16;y++){var v=f+y,p=m[v];m[v]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360}var g=this._hash.words,x=m[f+0],b=m[f+1],A=m[f+2],I=m[f+3],F=m[f+4],w=m[f+5],q=m[f+6],M=m[f+7],E=m[f+8],L=m[f+9],Q=m[f+10],T=m[f+11],j=m[f+12],z=m[f+13],B=m[f+14],U=m[f+15],O=g[0],_=g[1],R=g[2],D=g[3];O=c(O,_,R,D,x,7,o[0]),D=c(D,O,_,R,b,12,o[1]),R=c(R,D,O,_,A,17,o[2]),_=c(_,R,D,O,I,22,o[3]),O=c(O,_,R,D,F,7,o[4]),D=c(D,O,_,R,w,12,o[5]),R=c(R,D,O,_,q,17,o[6]),_=c(_,R,D,O,M,22,o[7]),O=c(O,_,R,D,E,7,o[8]),D=c(D,O,_,R,L,12,o[9]),R=c(R,D,O,_,Q,17,o[10]),_=c(_,R,D,O,T,22,o[11]),O=c(O,_,R,D,j,7,o[12]),D=c(D,O,_,R,z,12,o[13]),R=c(R,D,O,_,B,17,o[14]),_=c(_,R,D,O,U,22,o[15]),O=u(O,_,R,D,b,5,o[16]),D=u(D,O,_,R,q,9,o[17]),R=u(R,D,O,_,T,14,o[18]),_=u(_,R,D,O,x,20,o[19]),O=u(O,_,R,D,w,5,o[20]),D=u(D,O,_,R,Q,9,o[21]),R=u(R,D,O,_,U,14,o[22]),_=u(_,R,D,O,F,20,o[23]),O=u(O,_,R,D,L,5,o[24]),D=u(D,O,_,R,B,9,o[25]),R=u(R,D,O,_,I,14,o[26]),_=u(_,R,D,O,E,20,o[27]),O=u(O,_,R,D,z,5,o[28]),D=u(D,O,_,R,A,9,o[29]),R=u(R,D,O,_,M,14,o[30]),_=u(_,R,D,O,j,20,o[31]),O=l(O,_,R,D,w,4,o[32]),D=l(D,O,_,R,E,11,o[33]),R=l(R,D,O,_,T,16,o[34]),_=l(_,R,D,O,B,23,o[35]),O=l(O,_,R,D,b,4,o[36]),D=l(D,O,_,R,F,11,o[37]),R=l(R,D,O,_,M,16,o[38]),_=l(_,R,D,O,Q,23,o[39]),O=l(O,_,R,D,z,4,o[40]),D=l(D,O,_,R,x,11,o[41]),R=l(R,D,O,_,I,16,o[42]),_=l(_,R,D,O,q,23,o[43]),O=l(O,_,R,D,L,4,o[44]),D=l(D,O,_,R,j,11,o[45]),R=l(R,D,O,_,U,16,o[46]),_=l(_,R,D,O,A,23,o[47]),O=d(O,_,R,D,x,6,o[48]),D=d(D,O,_,R,M,10,o[49]),R=d(R,D,O,_,B,15,o[50]),_=d(_,R,D,O,w,21,o[51]),O=d(O,_,R,D,j,6,o[52]),D=d(D,O,_,R,I,10,o[53]),R=d(R,D,O,_,Q,15,o[54]),_=d(_,R,D,O,b,21,o[55]),O=d(O,_,R,D,E,6,o[56]),D=d(D,O,_,R,U,10,o[57]),R=d(R,D,O,_,q,15,o[58]),_=d(_,R,D,O,z,21,o[59]),O=d(O,_,R,D,F,6,o[60]),D=d(D,O,_,R,T,10,o[61]),R=d(R,D,O,_,A,15,o[62]),_=d(_,R,D,O,L,21,o[63]),g[0]=g[0]+O|0,g[1]=g[1]+_|0,g[2]=g[2]+R|0,g[3]=g[3]+D|0},_doFinalize:function(){var m=this._data,f=m.words,y=this._nDataBytes*8,v=m.sigBytes*8;f[v>>>5]|=128<<24-v%32;var p=e.floor(y/4294967296),g=y;f[(v+64>>>9<<4)+15]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,f[(v+64>>>9<<4)+14]=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360,m.sigBytes=(f.length+1)*4,this._process();for(var x=this._hash,b=x.words,A=0;A<4;A++){var I=b[A];b[A]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360}return x},clone:function(){var m=i.clone.call(this);return m._hash=this._hash.clone(),m}});function c(m,f,y,v,p,g,x){var b=m+(f&y|~f&v)+p+x;return(b<<g|b>>>32-g)+f}function u(m,f,y,v,p,g,x){var b=m+(f&v|y&~v)+p+x;return(b<<g|b>>>32-g)+f}function l(m,f,y,v,p,g,x){var b=m+(f^y^v)+p+x;return(b<<g|b>>>32-g)+f}function d(m,f,y,v,p,g,x){var b=m+(y^(f|~v))+p+x;return(b<<g|b>>>32-g)+f}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)})(Math),h.MD5})});var Zn=re((Zr,Bi)=>{(function(h,e){typeof Zr=="object"?Bi.exports=Zr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Zr,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=t.Hasher,i=e.algo,a=[],o=i.SHA1=n.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(s,c){for(var u=this._hash.words,l=u[0],d=u[1],m=u[2],f=u[3],y=u[4],v=0;v<80;v++){if(v<16)a[v]=s[c+v]|0;else{var p=a[v-3]^a[v-8]^a[v-14]^a[v-16];a[v]=p<<1|p>>>31}var g=(l<<5|l>>>27)+y+a[v];v<20?g+=(d&m|~d&f)+1518500249:v<40?g+=(d^m^f)+1859775393:v<60?g+=(d&m|d&f|m&f)-1894007588:g+=(d^m^f)-899497514,y=f,f=m,m=d<<30|d>>>2,d=l,l=g}u[0]=u[0]+l|0,u[1]=u[1]+d|0,u[2]=u[2]+m|0,u[3]=u[3]+f|0,u[4]=u[4]+y|0},_doFinalize:function(){var s=this._data,c=s.words,u=this._nDataBytes*8,l=s.sigBytes*8;return c[l>>>5]|=128<<24-l%32,c[(l+64>>>9<<4)+14]=Math.floor(u/4294967296),c[(l+64>>>9<<4)+15]=u,s.sigBytes=c.length*4,this._process(),this._hash},clone:function(){var s=n.clone.call(this);return s._hash=this._hash.clone(),s}});e.SHA1=n._createHelper(o),e.HmacSHA1=n._createHmacHelper(o)})(),h.SHA1})});var Ft=re((Jr,ki)=>{(function(h,e){typeof Jr=="object"?ki.exports=Jr=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Jr,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=[],s=[];(function(){function l(y){for(var v=e.sqrt(y),p=2;p<=v;p++)if(!(y%p))return!1;return!0}function d(y){return(y-(y|0))*4294967296|0}for(var m=2,f=0;f<64;)l(m)&&(f<8&&(o[f]=d(e.pow(m,1/2))),s[f]=d(e.pow(m,1/3)),f++),m++})();var c=[],u=a.SHA256=i.extend({_doReset:function(){this._hash=new n.init(o.slice(0))},_doProcessBlock:function(l,d){for(var m=this._hash.words,f=m[0],y=m[1],v=m[2],p=m[3],g=m[4],x=m[5],b=m[6],A=m[7],I=0;I<64;I++){if(I<16)c[I]=l[d+I]|0;else{var F=c[I-15],w=(F<<25|F>>>7)^(F<<14|F>>>18)^F>>>3,q=c[I-2],M=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;c[I]=w+c[I-7]+M+c[I-16]}var E=g&x^~g&b,L=f&y^f&v^y&v,Q=(f<<30|f>>>2)^(f<<19|f>>>13)^(f<<10|f>>>22),T=(g<<26|g>>>6)^(g<<21|g>>>11)^(g<<7|g>>>25),j=A+T+E+s[I]+c[I],z=Q+L;A=b,b=x,x=g,g=p+j|0,p=v,v=y,y=f,f=j+z|0}m[0]=m[0]+f|0,m[1]=m[1]+y|0,m[2]=m[2]+v|0,m[3]=m[3]+p|0,m[4]=m[4]+g|0,m[5]=m[5]+x|0,m[6]=m[6]+b|0,m[7]=m[7]+A|0},_doFinalize:function(){var l=this._data,d=l.words,m=this._nDataBytes*8,f=l.sigBytes*8;return d[f>>>5]|=128<<24-f%32,d[(f+64>>>9<<4)+14]=e.floor(m/4294967296),d[(f+64>>>9<<4)+15]=m,l.sigBytes=d.length*4,this._process(),this._hash},clone:function(){var l=i.clone.call(this);return l._hash=this._hash.clone(),l}});t.SHA256=i._createHelper(u),t.HmacSHA256=i._createHmacHelper(u)})(Math),h.SHA256})});var Mi=re((en,Fi)=>{(function(h,e,t){typeof en=="object"?Fi.exports=en=e(ie(),Ft()):typeof define=="function"&&define.amd?define(["./core","./sha256"],e):e(h.CryptoJS)})(en,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=e.algo,i=n.SHA256,a=n.SHA224=i.extend({_doReset:function(){this._hash=new r.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var o=i._doFinalize.call(this);return o.sigBytes-=4,o}});e.SHA224=i._createHelper(a),e.HmacSHA224=i._createHmacHelper(a)})(),h.SHA224})});var Jn=re((tn,qi)=>{(function(h,e,t){typeof tn=="object"?qi.exports=tn=e(ie(),Ut()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(h.CryptoJS)})(tn,function(h){return(function(){var e=h,t=e.lib,r=t.Hasher,n=e.x64,i=n.Word,a=n.WordArray,o=e.algo;function s(){return i.create.apply(i,arguments)}var c=[s(1116352408,3609767458),s(1899447441,602891725),s(3049323471,3964484399),s(3921009573,2173295548),s(961987163,4081628472),s(1508970993,3053834265),s(2453635748,2937671579),s(2870763221,3664609560),s(3624381080,2734883394),s(310598401,1164996542),s(607225278,1323610764),s(1426881987,3590304994),s(1925078388,4068182383),s(2162078206,991336113),s(2614888103,633803317),s(3248222580,3479774868),s(3835390401,2666613458),s(4022224774,944711139),s(264347078,2341262773),s(604807628,2007800933),s(770255983,1495990901),s(1249150122,1856431235),s(1555081692,3175218132),s(1996064986,2198950837),s(2554220882,3999719339),s(2821834349,766784016),s(2952996808,2566594879),s(3210313671,3203337956),s(3336571891,1034457026),s(3584528711,2466948901),s(113926993,3758326383),s(338241895,168717936),s(666307205,1188179964),s(773529912,1546045734),s(1294757372,1522805485),s(1396182291,2643833823),s(1695183700,2343527390),s(1986661051,1014477480),s(2177026350,1206759142),s(2456956037,344077627),s(2730485921,1290863460),s(2820302411,3158454273),s(3259730800,3505952657),s(3345764771,106217008),s(3516065817,3606008344),s(3600352804,1432725776),s(4094571909,1467031594),s(275423344,851169720),s(430227734,3100823752),s(506948616,1363258195),s(659060556,3750685593),s(883997877,3785050280),s(958139571,3318307427),s(1322822218,3812723403),s(1537002063,2003034995),s(1747873779,3602036899),s(1955562222,1575990012),s(2024104815,1125592928),s(2227730452,2716904306),s(2361852424,442776044),s(2428436474,593698344),s(2756734187,3733110249),s(3204031479,2999351573),s(3329325298,3815920427),s(3391569614,3928383900),s(3515267271,566280711),s(3940187606,3454069534),s(4118630271,4000239992),s(116418474,1914138554),s(174292421,2731055270),s(289380356,3203993006),s(460393269,320620315),s(685471733,587496836),s(852142971,1086792851),s(1017036298,365543100),s(1126000580,2618297676),s(1288033470,3409855158),s(1501505948,4234509866),s(1607167915,987167468),s(1816402316,1246189591)],u=[];(function(){for(var d=0;d<80;d++)u[d]=s()})();var l=o.SHA512=r.extend({_doReset:function(){this._hash=new a.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(d,m){for(var f=this._hash.words,y=f[0],v=f[1],p=f[2],g=f[3],x=f[4],b=f[5],A=f[6],I=f[7],F=y.high,w=y.low,q=v.high,M=v.low,E=p.high,L=p.low,Q=g.high,T=g.low,j=x.high,z=x.low,B=b.high,U=b.low,O=A.high,_=A.low,R=I.high,D=I.low,Z=F,te=w,X=q,Y=M,ye=E,se=L,qe=Q,ve=T,Oe=j,le=z,ze=B,je=U,Ke=O,st=_,ht=R,ut=D,ke=0;ke<80;ke++){var Be,Ne,ft=u[ke];if(ke<16)Ne=ft.high=d[m+ke*2]|0,Be=ft.low=d[m+ke*2+1]|0;else{var Dt=u[ke-15],ct=Dt.high,pt=Dt.low,mt=(ct>>>1|pt<<31)^(ct>>>8|pt<<24)^ct>>>7,Pt=(pt>>>1|ct<<31)^(pt>>>8|ct<<24)^(pt>>>7|ct<<25),Ct=u[ke-2],dt=Ct.high,Je=Ct.low,S=(dt>>>19|Je<<13)^(dt<<3|Je>>>29)^dt>>>6,C=(Je>>>19|dt<<13)^(Je<<3|dt>>>29)^(Je>>>6|dt<<26),k=u[ke-7],N=k.high,W=k.low,pe=u[ke-16],be=pe.high,ee=pe.low;Be=Pt+W,Ne=mt+N+(Be>>>0<Pt>>>0?1:0),Be=Be+C,Ne=Ne+S+(Be>>>0<C>>>0?1:0),Be=Be+ee,Ne=Ne+be+(Be>>>0<ee>>>0?1:0),ft.high=Ne,ft.low=Be}var H=Oe&ze^~Oe&Ke,V=le&je^~le&st,K=Z&X^Z&ye^X&ye,G=te&Y^te&se^Y&se,ne=(Z>>>28|te<<4)^(Z<<30|te>>>2)^(Z<<25|te>>>7),ce=(te>>>28|Z<<4)^(te<<30|Z>>>2)^(te<<25|Z>>>7),xe=(Oe>>>14|le<<18)^(Oe>>>18|le<<14)^(Oe<<23|le>>>9),Ge=(le>>>14|Oe<<18)^(le>>>18|Oe<<14)^(le<<23|Oe>>>9),Nt=c[ke],$n=Nt.high,$t=Nt.low,We=ut+Ge,bt=ht+xe+(We>>>0<ut>>>0?1:0),We=We+V,bt=bt+H+(We>>>0<V>>>0?1:0),We=We+$t,bt=bt+$n+(We>>>0<$t>>>0?1:0),We=We+Be,bt=bt+Ne+(We>>>0<Be>>>0?1:0),di=ce+G,Ka=ne+K+(di>>>0<ce>>>0?1:0);ht=Ke,ut=st,Ke=ze,st=je,ze=Oe,je=le,le=ve+We|0,Oe=qe+bt+(le>>>0<ve>>>0?1:0)|0,qe=ye,ve=se,ye=X,se=Y,X=Z,Y=te,te=We+di|0,Z=bt+Ka+(te>>>0<We>>>0?1:0)|0}w=y.low=w+te,y.high=F+Z+(w>>>0<te>>>0?1:0),M=v.low=M+Y,v.high=q+X+(M>>>0<Y>>>0?1:0),L=p.low=L+se,p.high=E+ye+(L>>>0<se>>>0?1:0),T=g.low=T+ve,g.high=Q+qe+(T>>>0<ve>>>0?1:0),z=x.low=z+le,x.high=j+Oe+(z>>>0<le>>>0?1:0),U=b.low=U+je,b.high=B+ze+(U>>>0<je>>>0?1:0),_=A.low=_+st,A.high=O+Ke+(_>>>0<st>>>0?1:0),D=I.low=D+ut,I.high=R+ht+(D>>>0<ut>>>0?1:0)},_doFinalize:function(){var d=this._data,m=d.words,f=this._nDataBytes*8,y=d.sigBytes*8;m[y>>>5]|=128<<24-y%32,m[(y+128>>>10<<5)+30]=Math.floor(f/4294967296),m[(y+128>>>10<<5)+31]=f,d.sigBytes=m.length*4,this._process();var v=this._hash.toX32();return v},clone:function(){var d=r.clone.call(this);return d._hash=this._hash.clone(),d},blockSize:1024/32});e.SHA512=r._createHelper(l),e.HmacSHA512=r._createHmacHelper(l)})(),h.SHA512})});var Ni=re((rn,Li)=>{(function(h,e,t){typeof rn=="object"?Li.exports=rn=e(ie(),Ut(),Jn()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./sha512"],e):e(h.CryptoJS)})(rn,function(h){return(function(){var e=h,t=e.x64,r=t.Word,n=t.WordArray,i=e.algo,a=i.SHA512,o=i.SHA384=a.extend({_doReset:function(){this._hash=new n.init([new r.init(3418070365,3238371032),new r.init(1654270250,914150663),new r.init(2438529370,812702999),new r.init(355462360,4144912697),new r.init(1731405415,4290775857),new r.init(2394180231,1750603025),new r.init(3675008525,1694076839),new r.init(1203062813,3204075428)])},_doFinalize:function(){var s=a._doFinalize.call(this);return s.sigBytes-=16,s}});e.SHA384=a._createHelper(o),e.HmacSHA384=a._createHmacHelper(o)})(),h.SHA384})});var Ui=re((nn,Qi)=>{(function(h,e,t){typeof nn=="object"?Qi.exports=nn=e(ie(),Ut()):typeof define=="function"&&define.amd?define(["./core","./x64-core"],e):e(h.CryptoJS)})(nn,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.x64,o=a.Word,s=t.algo,c=[],u=[],l=[];(function(){for(var f=1,y=0,v=0;v<24;v++){c[f+5*y]=(v+1)*(v+2)/2%64;var p=y%5,g=(2*f+3*y)%5;f=p,y=g}for(var f=0;f<5;f++)for(var y=0;y<5;y++)u[f+5*y]=y+(2*f+3*y)%5*5;for(var x=1,b=0;b<24;b++){for(var A=0,I=0,F=0;F<7;F++){if(x&1){var w=(1<<F)-1;w<32?I^=1<<w:A^=1<<w-32}x&128?x=x<<1^113:x<<=1}l[b]=o.create(A,I)}})();var d=[];(function(){for(var f=0;f<25;f++)d[f]=o.create()})();var m=s.SHA3=i.extend({cfg:i.cfg.extend({outputLength:512}),_doReset:function(){for(var f=this._state=[],y=0;y<25;y++)f[y]=new o.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(f,y){for(var v=this._state,p=this.blockSize/2,g=0;g<p;g++){var x=f[y+2*g],b=f[y+2*g+1];x=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360,b=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;var A=v[g];A.high^=b,A.low^=x}for(var I=0;I<24;I++){for(var F=0;F<5;F++){for(var w=0,q=0,M=0;M<5;M++){var A=v[F+5*M];w^=A.high,q^=A.low}var E=d[F];E.high=w,E.low=q}for(var F=0;F<5;F++)for(var L=d[(F+4)%5],Q=d[(F+1)%5],T=Q.high,j=Q.low,w=L.high^(T<<1|j>>>31),q=L.low^(j<<1|T>>>31),M=0;M<5;M++){var A=v[F+5*M];A.high^=w,A.low^=q}for(var z=1;z<25;z++){var w,q,A=v[z],B=A.high,U=A.low,O=c[z];O<32?(w=B<<O|U>>>32-O,q=U<<O|B>>>32-O):(w=U<<O-32|B>>>64-O,q=B<<O-32|U>>>64-O);var _=d[u[z]];_.high=w,_.low=q}var R=d[0],D=v[0];R.high=D.high,R.low=D.low;for(var F=0;F<5;F++)for(var M=0;M<5;M++){var z=F+5*M,A=v[z],Z=d[z],te=d[(F+1)%5+5*M],X=d[(F+2)%5+5*M];A.high=Z.high^~te.high&X.high,A.low=Z.low^~te.low&X.low}var A=v[0],Y=l[I];A.high^=Y.high,A.low^=Y.low}},_doFinalize:function(){var f=this._data,y=f.words,v=this._nDataBytes*8,p=f.sigBytes*8,g=this.blockSize*32;y[p>>>5]|=1<<24-p%32,y[(e.ceil((p+1)/g)*g>>>5)-1]|=128,f.sigBytes=y.length*4,this._process();for(var x=this._state,b=this.cfg.outputLength/8,A=b/8,I=[],F=0;F<A;F++){var w=x[F],q=w.high,M=w.low;q=(q<<8|q>>>24)&16711935|(q<<24|q>>>8)&4278255360,M=(M<<8|M>>>24)&16711935|(M<<24|M>>>8)&4278255360,I.push(M),I.push(q)}return new n.init(I,b)},clone:function(){for(var f=i.clone.call(this),y=f._state=this._state.slice(0),v=0;v<25;v++)y[v]=y[v].clone();return f}});t.SHA3=i._createHelper(m),t.HmacSHA3=i._createHmacHelper(m)})(Math),h.SHA3})});var $i=re((an,Hi)=>{(function(h,e){typeof an=="object"?Hi.exports=an=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(an,function(h){return(function(e){var t=h,r=t.lib,n=r.WordArray,i=r.Hasher,a=t.algo,o=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),s=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),c=n.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),u=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),l=n.create([0,1518500249,1859775393,2400959708,2840853838]),d=n.create([1352829926,1548603684,1836072691,2053994217,0]),m=a.RIPEMD160=i.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(b,A){for(var I=0;I<16;I++){var F=A+I,w=b[F];b[F]=(w<<8|w>>>24)&16711935|(w<<24|w>>>8)&4278255360}var q=this._hash.words,M=l.words,E=d.words,L=o.words,Q=s.words,T=c.words,j=u.words,z,B,U,O,_,R,D,Z,te,X;R=z=q[0],D=B=q[1],Z=U=q[2],te=O=q[3],X=_=q[4];for(var Y,I=0;I<80;I+=1)Y=z+b[A+L[I]]|0,I<16?Y+=f(B,U,O)+M[0]:I<32?Y+=y(B,U,O)+M[1]:I<48?Y+=v(B,U,O)+M[2]:I<64?Y+=p(B,U,O)+M[3]:Y+=g(B,U,O)+M[4],Y=Y|0,Y=x(Y,T[I]),Y=Y+_|0,z=_,_=O,O=x(U,10),U=B,B=Y,Y=R+b[A+Q[I]]|0,I<16?Y+=g(D,Z,te)+E[0]:I<32?Y+=p(D,Z,te)+E[1]:I<48?Y+=v(D,Z,te)+E[2]:I<64?Y+=y(D,Z,te)+E[3]:Y+=f(D,Z,te)+E[4],Y=Y|0,Y=x(Y,j[I]),Y=Y+X|0,R=X,X=te,te=x(Z,10),Z=D,D=Y;Y=q[1]+U+te|0,q[1]=q[2]+O+X|0,q[2]=q[3]+_+R|0,q[3]=q[4]+z+D|0,q[4]=q[0]+B+Z|0,q[0]=Y},_doFinalize:function(){var b=this._data,A=b.words,I=this._nDataBytes*8,F=b.sigBytes*8;A[F>>>5]|=128<<24-F%32,A[(F+64>>>9<<4)+14]=(I<<8|I>>>24)&16711935|(I<<24|I>>>8)&4278255360,b.sigBytes=(A.length+1)*4,this._process();for(var w=this._hash,q=w.words,M=0;M<5;M++){var E=q[M];q[M]=(E<<8|E>>>24)&16711935|(E<<24|E>>>8)&4278255360}return w},clone:function(){var b=i.clone.call(this);return b._hash=this._hash.clone(),b}});function f(b,A,I){return b^A^I}function y(b,A,I){return b&A|~b&I}function v(b,A,I){return(b|~A)^I}function p(b,A,I){return b&I|A&~I}function g(b,A,I){return b^(A|~I)}function x(b,A){return b<<A|b>>>32-A}t.RIPEMD160=i._createHelper(m),t.HmacRIPEMD160=i._createHmacHelper(m)})(Math),h.RIPEMD160})});var Ht=re((on,Vi)=>{(function(h,e){typeof on=="object"?Vi.exports=on=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(on,function(h){(function(){var e=h,t=e.lib,r=t.Base,n=e.enc,i=n.Utf8,a=e.algo,o=a.HMAC=r.extend({init:function(s,c){s=this._hasher=new s.init,typeof c=="string"&&(c=i.parse(c));var u=s.blockSize,l=u*4;c.sigBytes>l&&(c=s.finalize(c)),c.clamp();for(var d=this._oKey=c.clone(),m=this._iKey=c.clone(),f=d.words,y=m.words,v=0;v<u;v++)f[v]^=1549556828,y[v]^=909522486;d.sigBytes=m.sigBytes=l,this.reset()},reset:function(){var s=this._hasher;s.reset(),s.update(this._iKey)},update:function(s){return this._hasher.update(s),this},finalize:function(s){var c=this._hasher,u=c.finalize(s);c.reset();var l=c.finalize(this._oKey.clone().concat(u));return l}})})()})});var ji=re((sn,zi)=>{(function(h,e,t){typeof sn=="object"?zi.exports=sn=e(ie(),Ft(),Ht()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(h.CryptoJS)})(sn,function(h){return(function(){var e=h,t=e.lib,r=t.Base,n=t.WordArray,i=e.algo,a=i.SHA256,o=i.HMAC,s=i.PBKDF2=r.extend({cfg:r.extend({keySize:128/32,hasher:a,iterations:25e4}),init:function(c){this.cfg=this.cfg.extend(c)},compute:function(c,u){for(var l=this.cfg,d=o.create(l.hasher,c),m=n.create(),f=n.create([1]),y=m.words,v=f.words,p=l.keySize,g=l.iterations;y.length<p;){var x=d.update(u).finalize(f);d.reset();for(var b=x.words,A=b.length,I=x,F=1;F<g;F++){I=d.finalize(I),d.reset();for(var w=I.words,q=0;q<A;q++)b[q]^=w[q]}m.concat(x),v[0]++}return m.sigBytes=p*4,m}});e.PBKDF2=function(c,u,l){return s.create(l).compute(c,u)}})(),h.PBKDF2})});var vt=re((un,Ki)=>{(function(h,e,t){typeof un=="object"?Ki.exports=un=e(ie(),Zn(),Ht()):typeof define=="function"&&define.amd?define(["./core","./sha1","./hmac"],e):e(h.CryptoJS)})(un,function(h){return(function(){var e=h,t=e.lib,r=t.Base,n=t.WordArray,i=e.algo,a=i.MD5,o=i.EvpKDF=r.extend({cfg:r.extend({keySize:128/32,hasher:a,iterations:1}),init:function(s){this.cfg=this.cfg.extend(s)},compute:function(s,c){for(var u,l=this.cfg,d=l.hasher.create(),m=n.create(),f=m.words,y=l.keySize,v=l.iterations;f.length<y;){u&&d.update(u),u=d.update(s).finalize(c),d.reset();for(var p=1;p<v;p++)u=d.finalize(u),d.reset();m.concat(u)}return m.sigBytes=y*4,m}});e.EvpKDF=function(s,c,u){return o.create(u).compute(s,c)}})(),h.EvpKDF})});var Te=re((cn,Gi)=>{(function(h,e,t){typeof cn=="object"?Gi.exports=cn=e(ie(),vt()):typeof define=="function"&&define.amd?define(["./core","./evpkdf"],e):e(h.CryptoJS)})(cn,function(h){h.lib.Cipher||(function(e){var t=h,r=t.lib,n=r.Base,i=r.WordArray,a=r.BufferedBlockAlgorithm,o=t.enc,s=o.Utf8,c=o.Base64,u=t.algo,l=u.EvpKDF,d=r.Cipher=a.extend({cfg:n.extend(),createEncryptor:function(E,L){return this.create(this._ENC_XFORM_MODE,E,L)},createDecryptor:function(E,L){return this.create(this._DEC_XFORM_MODE,E,L)},init:function(E,L,Q){this.cfg=this.cfg.extend(Q),this._xformMode=E,this._key=L,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(E){return this._append(E),this._process()},finalize:function(E){E&&this._append(E);var L=this._doFinalize();return L},keySize:128/32,ivSize:128/32,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:(function(){function E(L){return typeof L=="string"?M:F}return function(L){return{encrypt:function(Q,T,j){return E(T).encrypt(L,Q,T,j)},decrypt:function(Q,T,j){return E(T).decrypt(L,Q,T,j)}}}})()}),m=r.StreamCipher=d.extend({_doFinalize:function(){var E=this._process(!0);return E},blockSize:1}),f=t.mode={},y=r.BlockCipherMode=n.extend({createEncryptor:function(E,L){return this.Encryptor.create(E,L)},createDecryptor:function(E,L){return this.Decryptor.create(E,L)},init:function(E,L){this._cipher=E,this._iv=L}}),v=f.CBC=(function(){var E=y.extend();E.Encryptor=E.extend({processBlock:function(Q,T){var j=this._cipher,z=j.blockSize;L.call(this,Q,T,z),j.encryptBlock(Q,T),this._prevBlock=Q.slice(T,T+z)}}),E.Decryptor=E.extend({processBlock:function(Q,T){var j=this._cipher,z=j.blockSize,B=Q.slice(T,T+z);j.decryptBlock(Q,T),L.call(this,Q,T,z),this._prevBlock=B}});function L(Q,T,j){var z,B=this._iv;B?(z=B,this._iv=e):z=this._prevBlock;for(var U=0;U<j;U++)Q[T+U]^=z[U]}return E})(),p=t.pad={},g=p.Pkcs7={pad:function(E,L){for(var Q=L*4,T=Q-E.sigBytes%Q,j=T<<24|T<<16|T<<8|T,z=[],B=0;B<T;B+=4)z.push(j);var U=i.create(z,T);E.concat(U)},unpad:function(E){var L=E.words[E.sigBytes-1>>>2]&255;E.sigBytes-=L}},x=r.BlockCipher=d.extend({cfg:d.cfg.extend({mode:v,padding:g}),reset:function(){var E;d.reset.call(this);var L=this.cfg,Q=L.iv,T=L.mode;this._xformMode==this._ENC_XFORM_MODE?E=T.createEncryptor:(E=T.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==E?this._mode.init(this,Q&&Q.words):(this._mode=E.call(T,this,Q&&Q.words),this._mode.__creator=E)},_doProcessBlock:function(E,L){this._mode.processBlock(E,L)},_doFinalize:function(){var E,L=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(L.pad(this._data,this.blockSize),E=this._process(!0)):(E=this._process(!0),L.unpad(E)),E},blockSize:128/32}),b=r.CipherParams=n.extend({init:function(E){this.mixIn(E)},toString:function(E){return(E||this.formatter).stringify(this)}}),A=t.format={},I=A.OpenSSL={stringify:function(E){var L,Q=E.ciphertext,T=E.salt;return T?L=i.create([1398893684,1701076831]).concat(T).concat(Q):L=Q,L.toString(c)},parse:function(E){var L,Q=c.parse(E),T=Q.words;return T[0]==1398893684&&T[1]==1701076831&&(L=i.create(T.slice(2,4)),T.splice(0,4),Q.sigBytes-=16),b.create({ciphertext:Q,salt:L})}},F=r.SerializableCipher=n.extend({cfg:n.extend({format:I}),encrypt:function(E,L,Q,T){T=this.cfg.extend(T);var j=E.createEncryptor(Q,T),z=j.finalize(L),B=j.cfg;return b.create({ciphertext:z,key:Q,iv:B.iv,algorithm:E,mode:B.mode,padding:B.padding,blockSize:E.blockSize,formatter:T.format})},decrypt:function(E,L,Q,T){T=this.cfg.extend(T),L=this._parse(L,T.format);var j=E.createDecryptor(Q,T).finalize(L.ciphertext);return j},_parse:function(E,L){return typeof E=="string"?L.parse(E,this):E}}),w=t.kdf={},q=w.OpenSSL={execute:function(E,L,Q,T,j){if(T||(T=i.random(64/8)),j)var z=l.create({keySize:L+Q,hasher:j}).compute(E,T);else var z=l.create({keySize:L+Q}).compute(E,T);var B=i.create(z.words.slice(L),Q*4);return z.sigBytes=L*4,b.create({key:z,iv:B,salt:T})}},M=r.PasswordBasedCipher=F.extend({cfg:F.cfg.extend({kdf:q}),encrypt:function(E,L,Q,T){T=this.cfg.extend(T);var j=T.kdf.execute(Q,E.keySize,E.ivSize,T.salt,T.hasher);T.iv=j.iv;var z=F.encrypt.call(this,E,L,j.key,T);return z.mixIn(j),z},decrypt:function(E,L,Q,T){T=this.cfg.extend(T),L=this._parse(L,T.format);var j=T.kdf.execute(Q,E.keySize,E.ivSize,L.salt,T.hasher);T.iv=j.iv;var z=F.decrypt.call(this,E,L,j.key,T);return z}})})()})});var Yi=re((dn,Wi)=>{(function(h,e,t){typeof dn=="object"?Wi.exports=dn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(dn,function(h){return h.mode.CFB=(function(){var e=h.lib.BlockCipherMode.extend();e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize;t.call(this,r,n,a,i),this._prevBlock=r.slice(n,n+a)}}),e.Decryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=r.slice(n,n+a);t.call(this,r,n,a,i),this._prevBlock=o}});function t(r,n,i,a){var o,s=this._iv;s?(o=s.slice(0),this._iv=void 0):o=this._prevBlock,a.encryptBlock(o,0);for(var c=0;c<i;c++)r[n+c]^=o[c]}return e})(),h.mode.CFB})});var Zi=re((ln,Xi)=>{(function(h,e,t){typeof ln=="object"?Xi.exports=ln=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(ln,function(h){return h.mode.CTR=(function(){var e=h.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=this._iv,s=this._counter;o&&(s=this._counter=o.slice(0),this._iv=void 0);var c=s.slice(0);i.encryptBlock(c,0),s[a-1]=s[a-1]+1|0;for(var u=0;u<a;u++)r[n+u]^=c[u]}});return e.Decryptor=t,e})(),h.mode.CTR})});var ea=re((pn,Ji)=>{(function(h,e,t){typeof pn=="object"?Ji.exports=pn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(pn,function(h){return h.mode.CTRGladman=(function(){var e=h.lib.BlockCipherMode.extend();function t(i){if((i>>24&255)===255){var a=i>>16&255,o=i>>8&255,s=i&255;a===255?(a=0,o===255?(o=0,s===255?s=0:++s):++o):++a,i=0,i+=a<<16,i+=o<<8,i+=s}else i+=1<<24;return i}function r(i){return(i[0]=t(i[0]))===0&&(i[1]=t(i[1])),i}var n=e.Encryptor=e.extend({processBlock:function(i,a){var o=this._cipher,s=o.blockSize,c=this._iv,u=this._counter;c&&(u=this._counter=c.slice(0),this._iv=void 0),r(u);var l=u.slice(0);o.encryptBlock(l,0);for(var d=0;d<s;d++)i[a+d]^=l[d]}});return e.Decryptor=n,e})(),h.mode.CTRGladman})});var ra=re((mn,ta)=>{(function(h,e,t){typeof mn=="object"?ta.exports=mn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(mn,function(h){return h.mode.OFB=(function(){var e=h.lib.BlockCipherMode.extend(),t=e.Encryptor=e.extend({processBlock:function(r,n){var i=this._cipher,a=i.blockSize,o=this._iv,s=this._keystream;o&&(s=this._keystream=o.slice(0),this._iv=void 0),i.encryptBlock(s,0);for(var c=0;c<a;c++)r[n+c]^=s[c]}});return e.Decryptor=t,e})(),h.mode.OFB})});var ia=re((hn,na)=>{(function(h,e,t){typeof hn=="object"?na.exports=hn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(hn,function(h){return h.mode.ECB=(function(){var e=h.lib.BlockCipherMode.extend();return e.Encryptor=e.extend({processBlock:function(t,r){this._cipher.encryptBlock(t,r)}}),e.Decryptor=e.extend({processBlock:function(t,r){this._cipher.decryptBlock(t,r)}}),e})(),h.mode.ECB})});var oa=re((fn,aa)=>{(function(h,e,t){typeof fn=="object"?aa.exports=fn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(fn,function(h){return h.pad.AnsiX923={pad:function(e,t){var r=e.sigBytes,n=t*4,i=n-r%n,a=r+i-1;e.clamp(),e.words[a>>>2]|=i<<24-a%4*8,e.sigBytes+=i},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},h.pad.Ansix923})});var ua=re((gn,sa)=>{(function(h,e,t){typeof gn=="object"?sa.exports=gn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(gn,function(h){return h.pad.Iso10126={pad:function(e,t){var r=t*4,n=r-e.sigBytes%r;e.concat(h.lib.WordArray.random(n-1)).concat(h.lib.WordArray.create([n<<24],1))},unpad:function(e){var t=e.words[e.sigBytes-1>>>2]&255;e.sigBytes-=t}},h.pad.Iso10126})});var da=re((yn,ca)=>{(function(h,e,t){typeof yn=="object"?ca.exports=yn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(yn,function(h){return h.pad.Iso97971={pad:function(e,t){e.concat(h.lib.WordArray.create([2147483648],1)),h.pad.ZeroPadding.pad(e,t)},unpad:function(e){h.pad.ZeroPadding.unpad(e),e.sigBytes--}},h.pad.Iso97971})});var pa=re((vn,la)=>{(function(h,e,t){typeof vn=="object"?la.exports=vn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(vn,function(h){return h.pad.ZeroPadding={pad:function(e,t){var r=t*4;e.clamp(),e.sigBytes+=r-(e.sigBytes%r||r)},unpad:function(e){for(var t=e.words,r=e.sigBytes-1,r=e.sigBytes-1;r>=0;r--)if(t[r>>>2]>>>24-r%4*8&255){e.sigBytes=r+1;break}}},h.pad.ZeroPadding})});var ha=re((bn,ma)=>{(function(h,e,t){typeof bn=="object"?ma.exports=bn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(bn,function(h){return h.pad.NoPadding={pad:function(){},unpad:function(){}},h.pad.NoPadding})});var ga=re((xn,fa)=>{(function(h,e,t){typeof xn=="object"?fa.exports=xn=e(ie(),Te()):typeof define=="function"&&define.amd?define(["./core","./cipher-core"],e):e(h.CryptoJS)})(xn,function(h){return(function(e){var t=h,r=t.lib,n=r.CipherParams,i=t.enc,a=i.Hex,o=t.format,s=o.Hex={stringify:function(c){return c.ciphertext.toString(a)},parse:function(c){var u=a.parse(c);return n.create({ciphertext:u})}}})(),h.format.Hex})});var va=re((An,ya)=>{(function(h,e,t){typeof An=="object"?ya.exports=An=e(ie(),St(),It(),vt(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(An,function(h){return(function(){var e=h,t=e.lib,r=t.BlockCipher,n=e.algo,i=[],a=[],o=[],s=[],c=[],u=[],l=[],d=[],m=[],f=[];(function(){for(var p=[],g=0;g<256;g++)g<128?p[g]=g<<1:p[g]=g<<1^283;for(var x=0,b=0,g=0;g<256;g++){var A=b^b<<1^b<<2^b<<3^b<<4;A=A>>>8^A&255^99,i[x]=A,a[A]=x;var I=p[x],F=p[I],w=p[F],q=p[A]*257^A*16843008;o[x]=q<<24|q>>>8,s[x]=q<<16|q>>>16,c[x]=q<<8|q>>>24,u[x]=q;var q=w*16843009^F*65537^I*257^x*16843008;l[A]=q<<24|q>>>8,d[A]=q<<16|q>>>16,m[A]=q<<8|q>>>24,f[A]=q,x?(x=I^p[p[p[w^I]]],b^=p[p[b]]):x=b=1}})();var y=[0,1,2,4,8,16,32,64,128,27,54],v=n.AES=r.extend({_doReset:function(){var p;if(!(this._nRounds&&this._keyPriorReset===this._key)){for(var g=this._keyPriorReset=this._key,x=g.words,b=g.sigBytes/4,A=this._nRounds=b+6,I=(A+1)*4,F=this._keySchedule=[],w=0;w<I;w++)w<b?F[w]=x[w]:(p=F[w-1],w%b?b>6&&w%b==4&&(p=i[p>>>24]<<24|i[p>>>16&255]<<16|i[p>>>8&255]<<8|i[p&255]):(p=p<<8|p>>>24,p=i[p>>>24]<<24|i[p>>>16&255]<<16|i[p>>>8&255]<<8|i[p&255],p^=y[w/b|0]<<24),F[w]=F[w-b]^p);for(var q=this._invKeySchedule=[],M=0;M<I;M++){var w=I-M;if(M%4)var p=F[w];else var p=F[w-4];M<4||w<=4?q[M]=p:q[M]=l[i[p>>>24]]^d[i[p>>>16&255]]^m[i[p>>>8&255]]^f[i[p&255]]}}},encryptBlock:function(p,g){this._doCryptBlock(p,g,this._keySchedule,o,s,c,u,i)},decryptBlock:function(p,g){var x=p[g+1];p[g+1]=p[g+3],p[g+3]=x,this._doCryptBlock(p,g,this._invKeySchedule,l,d,m,f,a);var x=p[g+1];p[g+1]=p[g+3],p[g+3]=x},_doCryptBlock:function(p,g,x,b,A,I,F,w){for(var q=this._nRounds,M=p[g]^x[0],E=p[g+1]^x[1],L=p[g+2]^x[2],Q=p[g+3]^x[3],T=4,j=1;j<q;j++){var z=b[M>>>24]^A[E>>>16&255]^I[L>>>8&255]^F[Q&255]^x[T++],B=b[E>>>24]^A[L>>>16&255]^I[Q>>>8&255]^F[M&255]^x[T++],U=b[L>>>24]^A[Q>>>16&255]^I[M>>>8&255]^F[E&255]^x[T++],O=b[Q>>>24]^A[M>>>16&255]^I[E>>>8&255]^F[L&255]^x[T++];M=z,E=B,L=U,Q=O}var z=(w[M>>>24]<<24|w[E>>>16&255]<<16|w[L>>>8&255]<<8|w[Q&255])^x[T++],B=(w[E>>>24]<<24|w[L>>>16&255]<<16|w[Q>>>8&255]<<8|w[M&255])^x[T++],U=(w[L>>>24]<<24|w[Q>>>16&255]<<16|w[M>>>8&255]<<8|w[E&255])^x[T++],O=(w[Q>>>24]<<24|w[M>>>16&255]<<16|w[E>>>8&255]<<8|w[L&255])^x[T++];p[g]=z,p[g+1]=B,p[g+2]=U,p[g+3]=O},keySize:256/32});e.AES=r._createHelper(v)})(),h.AES})});var xa=re((Sn,ba)=>{(function(h,e,t){typeof Sn=="object"?ba.exports=Sn=e(ie(),St(),It(),vt(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(Sn,function(h){return(function(){var e=h,t=e.lib,r=t.WordArray,n=t.BlockCipher,i=e.algo,a=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],s=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],c=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],u=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],l=i.DES=n.extend({_doReset:function(){for(var y=this._key,v=y.words,p=[],g=0;g<56;g++){var x=a[g]-1;p[g]=v[x>>>5]>>>31-x%32&1}for(var b=this._subKeys=[],A=0;A<16;A++){for(var I=b[A]=[],F=s[A],g=0;g<24;g++)I[g/6|0]|=p[(o[g]-1+F)%28]<<31-g%6,I[4+(g/6|0)]|=p[28+(o[g+24]-1+F)%28]<<31-g%6;I[0]=I[0]<<1|I[0]>>>31;for(var g=1;g<7;g++)I[g]=I[g]>>>(g-1)*4+3;I[7]=I[7]<<5|I[7]>>>27}for(var w=this._invSubKeys=[],g=0;g<16;g++)w[g]=b[15-g]},encryptBlock:function(y,v){this._doCryptBlock(y,v,this._subKeys)},decryptBlock:function(y,v){this._doCryptBlock(y,v,this._invSubKeys)},_doCryptBlock:function(y,v,p){this._lBlock=y[v],this._rBlock=y[v+1],d.call(this,4,252645135),d.call(this,16,65535),m.call(this,2,858993459),m.call(this,8,16711935),d.call(this,1,1431655765);for(var g=0;g<16;g++){for(var x=p[g],b=this._lBlock,A=this._rBlock,I=0,F=0;F<8;F++)I|=c[F][((A^x[F])&u[F])>>>0];this._lBlock=A,this._rBlock=b^I}var w=this._lBlock;this._lBlock=this._rBlock,this._rBlock=w,d.call(this,1,1431655765),m.call(this,8,16711935),m.call(this,2,858993459),d.call(this,16,65535),d.call(this,4,252645135),y[v]=this._lBlock,y[v+1]=this._rBlock},keySize:64/32,ivSize:64/32,blockSize:64/32});function d(y,v){var p=(this._lBlock>>>y^this._rBlock)&v;this._rBlock^=p,this._lBlock^=p<<y}function m(y,v){var p=(this._rBlock>>>y^this._lBlock)&v;this._lBlock^=p,this._rBlock^=p<<y}e.DES=n._createHelper(l);var f=i.TripleDES=n.extend({_doReset:function(){var y=this._key,v=y.words;if(v.length!==2&&v.length!==4&&v.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var p=v.slice(0,2),g=v.length<4?v.slice(0,2):v.slice(2,4),x=v.length<6?v.slice(0,2):v.slice(4,6);this._des1=l.createEncryptor(r.create(p)),this._des2=l.createEncryptor(r.create(g)),this._des3=l.createEncryptor(r.create(x))},encryptBlock:function(y,v){this._des1.encryptBlock(y,v),this._des2.decryptBlock(y,v),this._des3.encryptBlock(y,v)},decryptBlock:function(y,v){this._des3.decryptBlock(y,v),this._des2.encryptBlock(y,v),this._des1.decryptBlock(y,v)},keySize:192/32,ivSize:64/32,blockSize:64/32});e.TripleDES=n._createHelper(f)})(),h.TripleDES})});var Sa=re((In,Aa)=>{(function(h,e,t){typeof In=="object"?Aa.exports=In=e(ie(),St(),It(),vt(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(In,function(h){return(function(){var e=h,t=e.lib,r=t.StreamCipher,n=e.algo,i=n.RC4=r.extend({_doReset:function(){for(var s=this._key,c=s.words,u=s.sigBytes,l=this._S=[],d=0;d<256;d++)l[d]=d;for(var d=0,m=0;d<256;d++){var f=d%u,y=c[f>>>2]>>>24-f%4*8&255;m=(m+l[d]+y)%256;var v=l[d];l[d]=l[m],l[m]=v}this._i=this._j=0},_doProcessBlock:function(s,c){s[c]^=a.call(this)},keySize:256/32,ivSize:0});function a(){for(var s=this._S,c=this._i,u=this._j,l=0,d=0;d<4;d++){c=(c+1)%256,u=(u+s[c])%256;var m=s[c];s[c]=s[u],s[u]=m,l|=s[(s[c]+s[u])%256]<<24-d*8}return this._i=c,this._j=u,l}e.RC4=r._createHelper(i);var o=n.RC4Drop=i.extend({cfg:i.cfg.extend({drop:192}),_doReset:function(){i._doReset.call(this);for(var s=this.cfg.drop;s>0;s--)a.call(this)}});e.RC4Drop=r._createHelper(o)})(),h.RC4})});var Da=re((Dn,Ia)=>{(function(h,e,t){typeof Dn=="object"?Ia.exports=Dn=e(ie(),St(),It(),vt(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(Dn,function(h){return(function(){var e=h,t=e.lib,r=t.StreamCipher,n=e.algo,i=[],a=[],o=[],s=n.Rabbit=r.extend({_doReset:function(){for(var u=this._key.words,l=this.cfg.iv,d=0;d<4;d++)u[d]=(u[d]<<8|u[d]>>>24)&16711935|(u[d]<<24|u[d]>>>8)&4278255360;var m=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],f=this._C=[u[2]<<16|u[2]>>>16,u[0]&4294901760|u[1]&65535,u[3]<<16|u[3]>>>16,u[1]&4294901760|u[2]&65535,u[0]<<16|u[0]>>>16,u[2]&4294901760|u[3]&65535,u[1]<<16|u[1]>>>16,u[3]&4294901760|u[0]&65535];this._b=0;for(var d=0;d<4;d++)c.call(this);for(var d=0;d<8;d++)f[d]^=m[d+4&7];if(l){var y=l.words,v=y[0],p=y[1],g=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,x=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,b=g>>>16|x&4294901760,A=x<<16|g&65535;f[0]^=g,f[1]^=b,f[2]^=x,f[3]^=A,f[4]^=g,f[5]^=b,f[6]^=x,f[7]^=A;for(var d=0;d<4;d++)c.call(this)}},_doProcessBlock:function(u,l){var d=this._X;c.call(this),i[0]=d[0]^d[5]>>>16^d[3]<<16,i[1]=d[2]^d[7]>>>16^d[5]<<16,i[2]=d[4]^d[1]>>>16^d[7]<<16,i[3]=d[6]^d[3]>>>16^d[1]<<16;for(var m=0;m<4;m++)i[m]=(i[m]<<8|i[m]>>>24)&16711935|(i[m]<<24|i[m]>>>8)&4278255360,u[l+m]^=i[m]},blockSize:128/32,ivSize:64/32});function c(){for(var u=this._X,l=this._C,d=0;d<8;d++)a[d]=l[d];l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0;for(var d=0;d<8;d++){var m=u[d]+l[d],f=m&65535,y=m>>>16,v=((f*f>>>17)+f*y>>>15)+y*y,p=((m&4294901760)*m|0)+((m&65535)*m|0);o[d]=v^p}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.Rabbit=r._createHelper(s)})(),h.Rabbit})});var Ca=re((Pn,Pa)=>{(function(h,e,t){typeof Pn=="object"?Pa.exports=Pn=e(ie(),St(),It(),vt(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(Pn,function(h){return(function(){var e=h,t=e.lib,r=t.StreamCipher,n=e.algo,i=[],a=[],o=[],s=n.RabbitLegacy=r.extend({_doReset:function(){var u=this._key.words,l=this.cfg.iv,d=this._X=[u[0],u[3]<<16|u[2]>>>16,u[1],u[0]<<16|u[3]>>>16,u[2],u[1]<<16|u[0]>>>16,u[3],u[2]<<16|u[1]>>>16],m=this._C=[u[2]<<16|u[2]>>>16,u[0]&4294901760|u[1]&65535,u[3]<<16|u[3]>>>16,u[1]&4294901760|u[2]&65535,u[0]<<16|u[0]>>>16,u[2]&4294901760|u[3]&65535,u[1]<<16|u[1]>>>16,u[3]&4294901760|u[0]&65535];this._b=0;for(var f=0;f<4;f++)c.call(this);for(var f=0;f<8;f++)m[f]^=d[f+4&7];if(l){var y=l.words,v=y[0],p=y[1],g=(v<<8|v>>>24)&16711935|(v<<24|v>>>8)&4278255360,x=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360,b=g>>>16|x&4294901760,A=x<<16|g&65535;m[0]^=g,m[1]^=b,m[2]^=x,m[3]^=A,m[4]^=g,m[5]^=b,m[6]^=x,m[7]^=A;for(var f=0;f<4;f++)c.call(this)}},_doProcessBlock:function(u,l){var d=this._X;c.call(this),i[0]=d[0]^d[5]>>>16^d[3]<<16,i[1]=d[2]^d[7]>>>16^d[5]<<16,i[2]=d[4]^d[1]>>>16^d[7]<<16,i[3]=d[6]^d[3]>>>16^d[1]<<16;for(var m=0;m<4;m++)i[m]=(i[m]<<8|i[m]>>>24)&16711935|(i[m]<<24|i[m]>>>8)&4278255360,u[l+m]^=i[m]},blockSize:128/32,ivSize:64/32});function c(){for(var u=this._X,l=this._C,d=0;d<8;d++)a[d]=l[d];l[0]=l[0]+1295307597+this._b|0,l[1]=l[1]+3545052371+(l[0]>>>0<a[0]>>>0?1:0)|0,l[2]=l[2]+886263092+(l[1]>>>0<a[1]>>>0?1:0)|0,l[3]=l[3]+1295307597+(l[2]>>>0<a[2]>>>0?1:0)|0,l[4]=l[4]+3545052371+(l[3]>>>0<a[3]>>>0?1:0)|0,l[5]=l[5]+886263092+(l[4]>>>0<a[4]>>>0?1:0)|0,l[6]=l[6]+1295307597+(l[5]>>>0<a[5]>>>0?1:0)|0,l[7]=l[7]+3545052371+(l[6]>>>0<a[6]>>>0?1:0)|0,this._b=l[7]>>>0<a[7]>>>0?1:0;for(var d=0;d<8;d++){var m=u[d]+l[d],f=m&65535,y=m>>>16,v=((f*f>>>17)+f*y>>>15)+y*y,p=((m&4294901760)*m|0)+((m&65535)*m|0);o[d]=v^p}u[0]=o[0]+(o[7]<<16|o[7]>>>16)+(o[6]<<16|o[6]>>>16)|0,u[1]=o[1]+(o[0]<<8|o[0]>>>24)+o[7]|0,u[2]=o[2]+(o[1]<<16|o[1]>>>16)+(o[0]<<16|o[0]>>>16)|0,u[3]=o[3]+(o[2]<<8|o[2]>>>24)+o[1]|0,u[4]=o[4]+(o[3]<<16|o[3]>>>16)+(o[2]<<16|o[2]>>>16)|0,u[5]=o[5]+(o[4]<<8|o[4]>>>24)+o[3]|0,u[6]=o[6]+(o[5]<<16|o[5]>>>16)+(o[4]<<16|o[4]>>>16)|0,u[7]=o[7]+(o[6]<<8|o[6]>>>24)+o[5]|0}e.RabbitLegacy=r._createHelper(s)})(),h.RabbitLegacy})});var Ea=re((Cn,wa)=>{(function(h,e,t){typeof Cn=="object"?wa.exports=Cn=e(ie(),St(),It(),vt(),Te()):typeof define=="function"&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(h.CryptoJS)})(Cn,function(h){return(function(){var e=h,t=e.lib,r=t.BlockCipher,n=e.algo;let i=16,a=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],o=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var s={pbox:[],sbox:[]};function c(f,y){let v=y>>24&255,p=y>>16&255,g=y>>8&255,x=y&255,b=f.sbox[0][v]+f.sbox[1][p];return b=b^f.sbox[2][g],b=b+f.sbox[3][x],b}function u(f,y,v){let p=y,g=v,x;for(let b=0;b<i;++b)p=p^f.pbox[b],g=c(f,p)^g,x=p,p=g,g=x;return x=p,p=g,g=x,g=g^f.pbox[i],p=p^f.pbox[i+1],{left:p,right:g}}function l(f,y,v){let p=y,g=v,x;for(let b=i+1;b>1;--b)p=p^f.pbox[b],g=c(f,p)^g,x=p,p=g,g=x;return x=p,p=g,g=x,g=g^f.pbox[1],p=p^f.pbox[0],{left:p,right:g}}function d(f,y,v){for(let A=0;A<4;A++){f.sbox[A]=[];for(let I=0;I<256;I++)f.sbox[A][I]=o[A][I]}let p=0;for(let A=0;A<i+2;A++)f.pbox[A]=a[A]^y[p],p++,p>=v&&(p=0);let g=0,x=0,b=0;for(let A=0;A<i+2;A+=2)b=u(f,g,x),g=b.left,x=b.right,f.pbox[A]=g,f.pbox[A+1]=x;for(let A=0;A<4;A++)for(let I=0;I<256;I+=2)b=u(f,g,x),g=b.left,x=b.right,f.sbox[A][I]=g,f.sbox[A][I+1]=x;return!0}var m=n.Blowfish=r.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var f=this._keyPriorReset=this._key,y=f.words,v=f.sigBytes/4;d(s,y,v)}},encryptBlock:function(f,y){var v=u(s,f[y],f[y+1]);f[y]=v.left,f[y+1]=v.right},decryptBlock:function(f,y){var v=l(s,f[y],f[y+1]);f[y]=v.left,f[y+1]=v.right},blockSize:64/32,keySize:128/32,ivSize:64/32});e.Blowfish=r._createHelper(m)})(),h.Blowfish})});var ei=re((wn,Oa)=>{(function(h,e,t){typeof wn=="object"?Oa.exports=wn=e(ie(),Ut(),Ci(),Ei(),St(),_i(),It(),Zn(),Ft(),Mi(),Jn(),Ni(),Ui(),$i(),Ht(),ji(),vt(),Te(),Yi(),Zi(),ea(),ra(),ia(),oa(),ua(),da(),pa(),ha(),ga(),va(),xa(),Sa(),Da(),Ca(),Ea()):typeof define=="function"&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./enc-base64url","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy","./blowfish"],e):h.CryptoJS=e(h.CryptoJS)})(wn,function(h){return h})});var La=re((Qn,qa)=>{(function(h,e,t){typeof Qn=="object"?qa.exports=Qn=e(ie(),Ft(),Ht()):typeof define=="function"&&define.amd?define(["./core","./sha256","./hmac"],e):e(h.CryptoJS)})(Qn,function(h){return h.HmacSHA256})});var Qa=re((Un,Na)=>{(function(h,e){typeof Un=="object"?Na.exports=Un=e(ie()):typeof define=="function"&&define.amd?define(["./core"],e):e(h.CryptoJS)})(Un,function(h){return h.enc.Hex})});var iy=Ot(mi());import{CoreRuntime as yo}from"ofcore";import{asReadonlyStore as vo,createStore as bo}from"ofcore";var Vt="0123456789abcdef",zt=class h{constructor(e){this.bytes=e}static ofInner(e){if(e.length!==16)throw new TypeError("not 128-bit length");return new h(e)}static fromFieldsV7(e,t,r,n){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||e<0||t<0||r<0||n<0||e>0xffffffffffff||t>4095||r>1073741823||n>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/2**8,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=n>>>24,i[13]=n>>>16,i[14]=n>>>8,i[15]=n,new h(i)}static parse(e){var t,r,n,i;let a;switch(e.length){case 32:a=(t=/^[0-9a-f]{32}$/i.exec(e))===null||t===void 0?void 0:t[0];break;case 36:a=(r=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||r===void 0?void 0:r.slice(1,6).join("");break;case 38:a=(n=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e))===null||n===void 0?void 0:n.slice(1,6).join("");break;case 45:a=(i=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e))===null||i===void 0?void 0:i.slice(1,6).join("");break;default:break}if(a){let o=new Uint8Array(16);for(let s=0;s<16;s+=4){let c=parseInt(a.substring(2*s,2*s+8),16);o[s+0]=c>>>24,o[s+1]=c>>>16,o[s+2]=c>>>8,o[s+3]=c}return new h(o)}else throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Vt.charAt(this.bytes[t]>>>4),e+=Vt.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+=Vt.charAt(this.bytes[t]>>>4),e+=Vt.charAt(this.bytes[t]&15);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new h(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}},zn=class{constructor(e){this.timestamp_biased=0,this.counter=0,this.random=e!=null?e:eo()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return r===void 0&&(this.timestamp_biased=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<0||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit unsigned integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e++,e>this.timestamp_biased)this.timestamp_biased=e,this.resetCounter();else if(e+t>=this.timestamp_biased)this.counter++,this.counter>4398046511103&&(this.timestamp_biased++,this.resetCounter());else return;return zt.fromFieldsV7(this.timestamp_biased-1,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=this.random.nextUint32()*1024+(this.random.nextUint32()&1023)}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,zt.ofInner(e)}},eo=()=>{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues!="undefined")return new jn;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)}},jn=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++]}},hi;var P=()=>to().toString(),to=()=>(hi||(hi=new zn)).generateV4();var Kn=class{constructor(e){this.context=e}enqueue(e){this.context.enqueueDomainChange(e)}};function $(h){return new Kn(h)}var Fe="boms";var jt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addBom(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Fe,i);return this.changeQueue.enqueue({type:"create",model:Fe,record:a}),this.context.logActivity("AddBom",{id:r}),a}async updateBom(e,t,r){let n=await(r||this.dbAdapter).get(Fe,e);if(!n)throw new Error(`Bom with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Fe,e,a);return this.changeQueue.enqueue({type:"update",model:Fe,record:o}),this.context.logActivity("UpdateBom",{id:e}),o}async getBoms(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Fe,{...e,filters:i})}async getBom(e,t){return(t||this.dbAdapter).get(Fe,e)}async deleteBom(e,t){return await(t||this.dbAdapter).delete(Fe,e),this.changeQueue.enqueue({type:"delete",model:Fe,record:{id:e}}),this.context.logActivity("DeleteBom",{id:e}),{id:e,queued:!0}}async duplicateBom(e,t){let r=await this.getBom(e,t);if(!r)throw new Error(`Bom with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Fe,a);return this.changeQueue.enqueue({type:"create",model:Fe,record:a}),this.context.logActivity("DuplicateBom",{originalId:e,newId:n}),o}async getBomsByParentItemId(e,t){let r=t||this.dbAdapter,n={and:[{parentItemId:e},{deleted:!1}]};return r.query(Fe,{filters:n})}async getBomsByComponentItemId(e,t){let r=t||this.dbAdapter,n={and:[{componentItemId:e},{deleted:!1}]};return r.query(Fe,{filters:n})}async getBomsByProductId(e,t){return this.dbAdapter.query(Fe,{filters:{or:[{and:[{field:"parentItemId",value:e},{field:"deleted",value:!1}]},{and:[{field:"componentItemId",value:e},{field:"deleted",value:!1}]}]}})}async expandBom(e){let t=new Map,r=async(n,i)=>{let a=await this.dbAdapter.query(Fe,{filters:{parentItemId:n,deleted:!1}});for(let o of a){let s=o.quantity*i;if((await this.dbAdapter.query(Fe,{filters:{parentItemId:o.componentItemId,deleted:!1}})).length>0)await r(o.componentItemId,s);else{let u=t.get(o.componentItemId);u?u.quantity+=s:t.set(o.componentItemId,{componentItemId:o.componentItemId,quantity:s,uomId:o.uomId})}}};return await r(e,1),Array.from(t.values())}};var et="categories";var Kt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addCategory(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(et,i);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("AddCategory",{id:r}),a}async updateCategory(e,t,r){let n=await(r||this.dbAdapter).get(et,e);if(!n)throw new Error(`Category with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(et,e,a);return this.changeQueue.enqueue({type:"update",model:et,record:o}),this.context.logActivity("UpdateCategory",{id:e}),o}async getCategories(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(et,{...e,filters:i})}async getCategory(e,t){return(t||this.dbAdapter).get(et,e)}async deleteCategory(e,t){return await(t||this.dbAdapter).delete(et,e),this.changeQueue.enqueue({type:"delete",model:et,record:{id:e}}),this.context.logActivity("DeleteCategory",{id:e}),{id:e,queued:!0}}async duplicateCategory(e,t){let r=await this.getCategory(e,t);if(!r)throw new Error(`Category with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(et,a);return this.changeQueue.enqueue({type:"create",model:et,record:a}),this.context.logActivity("DuplicateCategory",{originalId:e,newId:n}),o}async fetchNestedCategories(){let e=await this.getCategories(),t={};e.forEach(n=>{t[n.id]={...n,children:[]}});let r=[];return e.forEach(n=>{var a;let i=(a=n.parentId)!=null?a:null;i&&t[i]?t[i].children.push(t[n.id]):r.push(t[n.id])}),r}};var Ye="customers";var Rt="loyalty_accounts";var gt="loyalty_ledgers";var Gt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}async getOrCreateLoyaltyAccount(e,t){let r=await e.query(Rt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]},limit:1});if(r.length>0)return r[0];let n=new Date().toISOString();return e.create(Rt,{id:P(),customerId:t,pointsBalance:0,totalEarned:0,totalRedeemed:0,totalExpired:0,version:Date.now(),lastModified:n,deleted:!1})}async addCustomer(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ye,i);return this.changeQueue.enqueue({type:"create",model:Ye,record:a}),this.context.logActivity("AddCustomer",{id:r}),a}async updateCustomer(e,t,r){let n=await(r||this.dbAdapter).get(Ye,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(Ye,e,a);return this.changeQueue.enqueue({type:"update",model:Ye,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(Ye,{...e,filters:i})}async getCustomer(e,t){return(t||this.dbAdapter).get(Ye,e)}async deleteCustomer(e,t){return await(t||this.dbAdapter).delete(Ye,e),this.changeQueue.enqueue({type:"delete",model:Ye,record:{id:e}}),this.context.logActivity("DeleteCustomer",{id:e}),{id:e,queued:!0}}async duplicateCustomer(e,t){let r=await this.getCustomer(e,t);if(!r)throw new Error(`Customer with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ye,a);return this.changeQueue.enqueue({type:"create",model:Ye,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(Ye,{...t,filters:a})}async earnLoyaltyPoints(e){let t=String(e.customerId||"").trim(),r=String(e.referenceType||"").trim(),n=String(e.referenceId||"").trim();if(!t)throw new Error("Loyalty: customerId is required");if(!r||!n)throw new Error("Loyalty: referenceType/referenceId are required");if(!Number.isFinite(e.baseAmount)||e.baseAmount<=0)throw new Error("Loyalty: baseAmount must be > 0");if(!Number.isFinite(e.earnRate)||e.earnRate<=0)throw new Error("Loyalty: earnRate must be > 0");return this.runInTransaction(async i=>{let a=e.date||new Date().toISOString(),o=await i.query(gt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"entryType",operator:"=",value:"earn"},{field:"referenceType",operator:"=",value:r},{field:"referenceId",operator:"=",value:n},{field:"deleted",operator:"=",value:!1}]},limit:1});if(o.length>0){let l=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:Number(o[0].points||0),balance:Number(l.pointsBalance||0)}}let s=Math.floor(e.baseAmount*e.earnRate);if(s<=0){let l=await this.getOrCreateLoyaltyAccount(i,t);return{earnedPoints:0,balance:Number(l.pointsBalance||0)}}await i.create(gt,{id:P(),customerId:t,entryType:"earn",points:s,availablePoints:s,expiresAt:e.expiresAt||null,consumedAt:null,referenceType:r,referenceId:n,note:e.note||null,date:a,version:Date.now(),lastModified:a,deleted:!1});let c=await this.getOrCreateLoyaltyAccount(i,t),u=await i.update(Rt,c.id,{pointsBalance:Number(c.pointsBalance||0)+s,totalEarned:Number(c.totalEarned||0)+s,version:Date.now(),lastModified:a});return this.context.logActivity("LoyaltyEarnPoints",{customerId:t,referenceType:r,referenceId:n,earnedPoints:s}),{earnedPoints:s,balance:Number(u.pointsBalance||0)}})}async redeemLoyaltyPoints(e){let t=String(e.customerId||"").trim(),r=String(e.referenceType||"").trim(),n=String(e.referenceId||"").trim();if(!t)throw new Error("Loyalty: customerId is required");if(!r||!n)throw new Error("Loyalty: referenceType/referenceId are required");if(!Number.isInteger(e.points)||e.points<=0)throw new Error("Loyalty: redeem points must be positive integer");return this.runInTransaction(async i=>{let a=e.date||new Date().toISOString(),o=await this.getOrCreateLoyaltyAccount(i,t),s=Number(o.pointsBalance||0);if(s<e.points)throw new Error(`Loyalty: insufficient points, required=${e.points}, available=${s}`);let c=await i.query(gt,{filters:{and:[{field:"customerId",operator:"=",value:t},{field:"entryType",operator:"=",value:"earn"},{field:"deleted",operator:"=",value:!1},{field:"availablePoints",operator:">",value:0}]},sort:[{field:"expiresAt",direction:"asc"},{field:"date",direction:"asc"}]}),u=e.points;for(let d of c){if(u<=0)break;let m=Number(d.availablePoints||0);if(m<=0)continue;let f=Math.min(m,u),y=m-f;await i.update(gt,d.id,{availablePoints:y,consumedAt:y===0?a:d.consumedAt,version:Date.now(),lastModified:a}),u-=f}if(u>0)throw new Error(`Loyalty: redeem allocation failed, remaining=${u}`);await i.create(gt,{id:P(),customerId:t,entryType:"redeem",points:e.points,availablePoints:0,expiresAt:null,consumedAt:a,referenceType:r,referenceId:n,note:e.note||null,date:a,version:Date.now(),lastModified:a,deleted:!1});let l=await i.update(Rt,o.id,{pointsBalance:s-e.points,totalRedeemed:Number(o.totalRedeemed||0)+e.points,version:Date.now(),lastModified:a});return this.context.logActivity("LoyaltyRedeemPoints",{customerId:t,referenceType:r,referenceId:n,redeemedPoints:e.points}),{redeemedPoints:e.points,balance:Number(l.pointsBalance||0)}})}async expireLoyaltyPoints(e){return this.runInTransaction(async t=>{let r=(e==null?void 0:e.asOfDate)||new Date().toISOString(),n=[{field:"entryType",operator:"=",value:"earn"},{field:"deleted",operator:"=",value:!1},{field:"availablePoints",operator:">",value:0},{field:"expiresAt",operator:"<=",value:r}];e!=null&&e.customerId&&n.push({field:"customerId",operator:"=",value:e.customerId});let i=await t.query(gt,{filters:{and:n}});if(!i.length)return{expiredPoints:0,affectedCustomers:0};let a=0,o=new Map;for(let s of i){let c=Number(s.availablePoints||0);c<=0||(a+=c,o.set(s.customerId,(o.get(s.customerId)||0)+c),await t.update(gt,s.id,{availablePoints:0,consumedAt:r,version:Date.now(),lastModified:r}),await t.create(gt,{id:P(),customerId:s.customerId,entryType:"expire",points:c,availablePoints:0,expiresAt:s.expiresAt,consumedAt:r,referenceType:"loyalty_expiry",referenceId:s.id,note:"auto expiry",date:r,version:Date.now(),lastModified:r,deleted:!1}))}for(let[s,c]of o.entries()){let u=await this.getOrCreateLoyaltyAccount(t,s);await t.update(Rt,u.id,{pointsBalance:Math.max(0,Number(u.pointsBalance||0)-c),totalExpired:Number(u.totalExpired||0)+c,version:Date.now(),lastModified:r})}return this.context.logActivity("LoyaltyExpirePoints",{asOfDate:r,expiredPoints:a,affectedCustomers:o.size}),{expiredPoints:a,affectedCustomers:o.size}})}async getLoyaltySummary(e){let t=String(e||"").trim();if(!t)throw new Error("Loyalty: customerId is required");let r=await this.getOrCreateLoyaltyAccount(this.dbAdapter,t);return{customerId:t,pointsBalance:Number(r.pointsBalance||0),totalEarned:Number(r.totalEarned||0),totalRedeemed:Number(r.totalRedeemed||0),totalExpired:Number(r.totalExpired||0)}}};var tt="customer_groups";var Wt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addCustomerGroup(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(tt,i);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("AddCustomerGroup",{id:r}),a}async updateCustomerGroup(e,t,r){let n=await(r||this.dbAdapter).get(tt,e);if(!n)throw new Error(`CustomerGroup with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(tt,e,a);return this.changeQueue.enqueue({type:"update",model:tt,record:o}),this.context.logActivity("UpdateCustomerGroup",{id:e}),o}async getCustomerGroups(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(tt,{...e,filters:i})}async getCustomerGroup(e,t){return(t||this.dbAdapter).get(tt,e)}async deleteCustomerGroup(e,t){return await(t||this.dbAdapter).delete(tt,e),this.changeQueue.enqueue({type:"delete",model:tt,record:{id:e}}),this.context.logActivity("DeleteCustomerGroup",{id:e}),{id:e,queued:!0}}async duplicateCustomerGroup(e,t){let r=await this.getCustomerGroup(e,t);if(!r)throw new Error(`CustomerGroup with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(tt,a);return this.changeQueue.enqueue({type:"create",model:tt,record:a}),this.context.logActivity("DuplicateCustomerGroup",{originalId:e,newId:n}),o}};var ae="histories";var Yt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addHistory(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e},a=await(t||this.dbAdapter).create(ae,i);return this.changeQueue.enqueue({type:"create",model:ae,record:a}),this.context.logActivity("AddHistory",{id:r}),a}async updateHistory(e,t,r){if(!await(r||this.dbAdapter).get(ae,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(ae,e,a);return this.changeQueue.enqueue({type:"update",model:ae,record:o}),this.context.logActivity("UpdateHistory",{id:e}),o}async getHistories(e,t){return(t||this.dbAdapter).query(ae,e)}async getHistory(e,t){return(t||this.dbAdapter).get(ae,e)}async deleteHistory(e,t){return await(t||this.dbAdapter).delete(ae,e),this.changeQueue.enqueue({type:"delete",model:ae,record:{id:e}}),this.context.logActivity("DeleteHistory",{id:e}),{id:e,queued:!0}}async duplicateHistory(e,t){let r=await this.getHistory(e,t);if(!r)throw new Error(`History with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ae,a);return this.changeQueue.enqueue({type:"create",model:ae,record:a}),this.context.logActivity("DuplicateHistory",{originalId:e,newId:n}),o}async enforceRetentionPolicy(e=new Date){var u;let t=this.context.config.auditLogRetentionDays,r=this.context.config.auditLogArchiveBeforePurge,n=this.context.config.auditLogPurgeBatchSize,i=e.getTime()-t*24*60*60*1e3,a=await this.dbAdapter.query(ae,{sort:[{field:"timestamp",direction:"asc"}]}),o=a.filter(l=>{let d=Date.parse(String(l.timestamp||""));return Number.isFinite(d)&&d<=i}).slice(0,n);if(o.length===0)return{scanned:a.length,archived:0,purged:0,archiveKey:null};let s=0,c=null;if(r){let l=(u=this.context.registry)==null?void 0:u.storageAdapter;c=`audit-archive:${e.toISOString().slice(0,10)}`;let m=await(l==null?void 0:l.getItem(c)),f=m?JSON.parse(m):[],y=o.map(v=>({id:v.id,tableName:v.tableName,recordId:v.recordId,action:v.action,userId:v.userId,timestamp:v.timestamp,changes:v.changes}));await(l==null?void 0:l.setItem(c,JSON.stringify([...Array.isArray(f)?f:[],...y]))),s=y.length}for(let l of o)await this.dbAdapter.delete(ae,l.id);return this.context.logInfo("History retention enforcement completed",{scanned:a.length,archived:s,purged:o.length,retentionDays:t,archiveBeforePurge:r,archiveKey:c}),{scanned:a.length,archived:s,purged:o.length,archiveKey:c}}};var oe="orders";var Ae="order_items";import{MemoryStorageAdapter as ro}from"ofcore";var yt=class extends ro{};var xt=class{constructor(e){this.context=e;this.queue=Promise.resolve();var t;this.storage=((t=this.context.registry)==null?void 0:t.storageAdapter)||new yt(this.context)}getBranchSegment(){return String(this.context.config.branchId||"LOCAL").trim().toUpperCase().replace(/[^A-Z0-9]/g,"").slice(0,8)||"LOCAL"}getDateSegment(e){let t=new Date(e),r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${r}${n}${i}`}getCounterKey(e,t){let r=this.getBranchSegment(),n=this.getDateSegment(t);return`docseq:${r}:${e}:${n}`}async withLock(e){let t=this.queue,r=()=>{};this.queue=new Promise(n=>{r=n}),await t;try{return await e()}finally{r()}}async next(e,t){return this.withLock(async()=>{let r=this.getCounterKey(e,t),n=await this.storage.getItem(r),i=Number(n||"0"),a=Number.isFinite(i)&&i>=0?i+1:1;await this.storage.setItem(r,String(a));let o=e.toUpperCase().slice(0,3),s=this.getBranchSegment(),c=this.getDateSegment(t);return`${o}-${s}-${c}-${String(a).padStart(6,"0")}`})}withNote(e,t){let r=String(e||"").trim(),n=`[DOC_NO=${t}]`;return r?r.includes("[DOC_NO=")?r:`${r} | ${n}`:n}extractDocNo(e){let r=String(e||"").match(/\[DOC_NO=([^\]]+)\]/);return r&&String(r[1]||"").trim()||null}};var fi="kitchen_ticket_items";var Gn="kitchen_tickets";var Xt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e),this.docNumberPolicy=new xt(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(Ae,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((l,d)=>l+Number(d.unitPrice||0)*Number(d.quantity||0),0),a=Number(r.serviceChargeAmount||0),o=Number(r.gratuityAmount||0),s=Number(r.ppn||0),c=Number(r.pph||0),u=i+a+o+s+c;return e.update(oe,t,{total:i,finalTotal:u,version:Date.now(),lastModified:new Date().toISOString()})}async addOrder(e,t){var s,c,u,l,d,m,f,y;this.validateOmnichannelInput(e);let r=P(),n=new Date().toISOString(),i=((s=this.context.config)==null?void 0:s.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("order",e.date||n):null,a={id:r,userId:e.userId,customerId:e.customerId,parentOrderId:(c=e.parentOrderId)!=null?c:null,discountCode:e.discountCode,channel:(u=e.channel)!=null?u:null,status:e.status,saleId:e.saleId,scheduledAt:(l=e.scheduledAt)!=null?l:null,deliveryAddress:(d=e.deliveryAddress)!=null?d:null,tableNumber:(m=e.tableNumber)!=null?m:null,serviceChargeAmount:(f=e.serviceChargeAmount)!=null?f:null,gratuityAmount:(y=e.gratuityAmount)!=null?y:null,date:e.date,total:e.total,ppn:e.ppn,pph:e.pph,finalTotal:e.finalTotal,note:i?this.docNumberPolicy.withNote(e.note,i):e.note,version:1,lastModified:n,deleted:!1},o=await(t||this.dbAdapter).create(oe,a);return this.changeQueue.enqueue({type:"create",model:oe,record:o}),this.context.logActivity("AddOrder",{id:r,channel:a.channel,status:a.status}),o}async updateOrder(e,t,r){let n=await(r||this.dbAdapter).get(oe,e);if(!n)throw new Error(`Order with ID ${e} not found.`);this.validateOmnichannelInput({...n,...t});let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(oe,e,a);return this.changeQueue.enqueue({type:"update",model:oe,record:o}),this.context.logActivity("UpdateOrder",{id:e}),o}async getOrders(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(oe,{...e,filters:i})}async getOrder(e,t){return(t||this.dbAdapter).get(oe,e)}async deleteOrder(e,t){return await(t||this.dbAdapter).delete(oe,e),this.changeQueue.enqueue({type:"delete",model:oe,record:{id:e}}),this.context.logActivity("DeleteOrder",{id:e}),{id:e,queued:!0}}async duplicateOrder(e,t){let r=await this.getOrder(e,t);if(!r)throw new Error(`Order with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,status:"draft",saleId:null,version:1,lastModified:i,deleted:!1},o=await(t||this.dbAdapter).create(oe,a);return this.changeQueue.enqueue({type:"create",model:oe,record:a}),this.context.logActivity("DuplicateOrder",{originalId:e,newId:n}),o}async finalizeOrder(e){return await this.runInTransaction(async t=>{await this.recalculateOrderTotals(t,e),await t.update(oe,e,{status:"completed",version:Date.now(),lastModified:new Date().toISOString()})}),this.context.eventBus.emit("order:finalized",e),{id:e,queued:!0}}async transitionOrderLifecycle(e){let t=String(e.orderId||"").trim(),r=String(e.actorId||"").trim(),n=String(e.toStatus||"").trim();if(!t)throw new Error("orderId is required");if(!r)throw new Error("actorId is required");if(!n)throw new Error("toStatus is required");return this.runInTransaction(async i=>{let a=await i.get(oe,t);if(!a||a.deleted)throw new Error(`Order with ID ${t} not found.`);let o=a.channel||null;if(!this.isValidTransition(o,a.status,n))throw new Error(`Invalid order lifecycle transition: ${a.status} -> ${n}`);let s=new Date().toISOString(),c=await i.update(oe,t,{status:n,version:Date.now(),lastModified:s});return await i.create(ae,{id:P(),tableName:oe,recordId:t,action:"lifecycle_transition",changes:{fromStatus:a.status,toStatus:n,actorId:r,reason:e.reason||null,channel:o},userId:r,timestamp:s}),c})}async createKitchenTicket(e){if(!String(e.orderId||"").trim())throw new Error("orderId is required");if(!String(e.station||"").trim())throw new Error("station is required");if(!String(e.actorId||"").trim())throw new Error("actorId is required");if(!Array.isArray(e.items)||e.items.length===0)throw new Error("items is required");return this.runInTransaction(async t=>{let r=await t.get(oe,e.orderId);if(!r||r.deleted)throw new Error(`Order with ID ${e.orderId} not found.`);let n=new Date().toISOString(),i=await t.create(Gn,{id:P(),orderId:e.orderId,station:e.station,status:"queued",note:e.note||null,createdBy:e.actorId,createdAt:n,version:Date.now(),lastModified:n,deleted:!1}),a=[];for(let o of e.items){let s=String(o.orderItemId||"").trim();if(!s)throw new Error("orderItemId is required");let c=await t.get(Ae,s);if(!c||c.deleted||String(c.orderId)!==e.orderId)throw new Error(`Order item ${s} does not belong to order ${e.orderId}`);let u=await t.create(fi,{id:P(),ticketId:i.id,orderItemId:s,course:o.course||null,status:"queued",note:o.note||null,version:Date.now(),lastModified:n,deleted:!1});a.push(u)}return await t.create(ae,{id:P(),tableName:Gn,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(Ae,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}}),o=new Set(a.map(l=>String(l.id))),s=new Set,c=new Date().toISOString(),u=[];for(let l of e.splits){let d=(l.orderItemIds||[]).map(f=>String(f));if(d.length===0)continue;for(let f of d){if(!o.has(f))throw new Error(`Order item ${f} does not belong to parent order`);if(s.has(f))throw new Error(`Order item ${f} referenced by multiple splits`);s.add(f)}let m=await n.create(oe,{id:P(),userId:i.userId,customerId:i.customerId,parentOrderId:t,discountCode:i.discountCode,channel:i.channel,status:"draft",saleId:null,scheduledAt:i.scheduledAt,deliveryAddress:i.deliveryAddress,tableNumber:i.tableNumber,serviceChargeAmount:0,gratuityAmount:0,date:i.date,total:0,ppn:0,pph:0,finalTotal:0,note:l.label?`SPLIT:${l.label}`:"SPLIT",version:Date.now(),lastModified:c,deleted:!1});u.push(m.id);for(let f of d)await n.get(Ae,f)&&await n.update(Ae,f,{orderId:m.id,version:Date.now(),lastModified:c});await this.recalculateOrderTotals(n,m.id)}return await this.recalculateOrderTotals(n,t),await n.create(ae,{id:P(),tableName:oe,recordId:t,action:"bill_split",changes:{actorId:r,childOrderIds:u,movedItems:Array.from(s)},userId:r,timestamp:c}),{parentOrderId:t,childOrderIds:u}})}async mergeOrderBills(e){let t=String(e.targetOrderId||"").trim(),r=String(e.actorId||"").trim();if(!t)throw new Error("targetOrderId is required");if(!r)throw new Error("actorId is required");let n=Array.from(new Set((e.sourceOrderIds||[]).map(i=>String(i).trim()).filter(Boolean)));if(!n.length)throw new Error("sourceOrderIds is required");if(n.includes(t))throw new Error("targetOrderId cannot be included in sourceOrderIds");return this.runInTransaction(async i=>{let a=await i.get(oe,t);if(!a||a.deleted)throw new Error(`Order with ID ${t} not found.`);let o=new Date().toISOString();for(let s of n){let c=await i.get(oe,s);if(!c||c.deleted)throw new Error(`Order with ID ${s} not found.`);let u=await i.query(Ae,{filters:{and:[{field:"orderId",operator:"=",value:s},{field:"deleted",operator:"=",value:!1}]}});for(let l of u)await i.update(Ae,l.id,{orderId:t,version:Date.now(),lastModified:o});await i.update(oe,s,{status:"merged",version:Date.now(),lastModified:o,note:[c.note,`MERGED_INTO:${t}`].filter(Boolean).join(" | ")})}return await this.recalculateOrderTotals(i,t),await i.create(ae,{id:P(),tableName:oe,recordId:t,action:"bill_merge",changes:{actorId:r,mergedOrderIds:n},userId:r,timestamp:o}),{targetOrderId:t,mergedOrderIds:n}})}async applyServiceChargeAndGratuity(e){let t=String(e.orderId||"").trim();if(!t)throw new Error("orderId is required");if(!String(e.actorId||"").trim())throw new Error("actorId is required");if(!Number.isFinite(e.serviceChargeRate)||e.serviceChargeRate<0)throw new Error("serviceChargeRate must be >= 0");if(!Number.isFinite(e.gratuityRate)||e.gratuityRate<0)throw new Error("gratuityRate must be >= 0");return this.runInTransaction(async r=>{let n=await r.get(oe,t);if(!n||n.deleted)throw new Error(`Order with ID ${t} not found.`);let a=(await r.query(Ae,{filters:{and:[{field:"orderId",operator:"=",value:t},{field:"deleted",operator:"=",value:!1}]}})).reduce((l,d)=>l+Number(d.unitPrice||0)*Number(d.quantity||0),0),o=Math.round(a*e.serviceChargeRate*100)/100,s=Math.round(a*e.gratuityRate*100)/100,c=new Date().toISOString(),u=await r.update(oe,t,{serviceChargeAmount:o,gratuityAmount:s,total:a,finalTotal:a+o+s+Number(n.ppn||0)+Number(n.pph||0),version:Date.now(),lastModified:c});return await r.create(ae,{id:P(),tableName:oe,recordId:t,action:"service_charge_gratuity_applied",changes:{actorId:e.actorId,serviceChargeRate:e.serviceChargeRate,gratuityRate:e.gratuityRate,serviceChargeAmount:o,gratuityAmount:s},userId:e.actorId,timestamp:c}),u})}};var Zt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addOrderItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ae,i);return this.changeQueue.enqueue({type:"create",model:Ae,record:a}),this.context.logActivity("AddOrderItem",{id:r}),a}async updateOrderItem(e,t,r){let n=await(r||this.dbAdapter).get(Ae,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(Ae,e,a);return this.changeQueue.enqueue({type:"update",model:Ae,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(Ae,{...e,filters:i})}async getOrderItem(e,t){return(t||this.dbAdapter).get(Ae,e)}async deleteOrderItem(e,t){return await(t||this.dbAdapter).delete(Ae,e),this.changeQueue.enqueue({type:"delete",model:Ae,record:{id:e}}),this.context.logActivity("DeleteOrderItem",{id:e}),{id:e,queued:!0}}async duplicateOrderItem(e,t){let r=await this.getOrderItem(e,t);if(!r)throw new Error(`OrderItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ae,a);return this.changeQueue.enqueue({type:"create",model:Ae,record:a}),this.context.logActivity("DuplicateOrderItem",{originalId:e,newId:n}),o}};var Ue="price_tiers";var Jt=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addPriceTier(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(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=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ue,a);return this.changeQueue.enqueue({type:"create",model:Ue,record:a}),this.context.logActivity("DuplicatePriceTier",{originalId:e,newId:n}),o}};var de="products";var er=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addProduct(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(de,i);return this.changeQueue.enqueue({type:"create",model:de,record:a}),this.context.logActivity("AddProduct",{id:r}),a}async updateProduct(e,t,r){let n=await(r||this.dbAdapter).get(de,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(de,e,a);return this.changeQueue.enqueue({type:"update",model:de,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(de,{...e,filters:i})}async getProduct(e,t){return(t||this.dbAdapter).get(de,e)}async deleteProduct(e,t){return await(t||this.dbAdapter).delete(de,e),this.changeQueue.enqueue({type:"delete",model:de,record:{id:e}}),this.context.logActivity("DeleteProduct",{id:e}),{id:e,queued:!0}}async duplicateProduct(e,t){let r=await this.getProduct(e,t);if(!r)throw new Error(`Product with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(de,a);return this.changeQueue.enqueue({type:"create",model:de,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(de,{filters:n})}async getProductsByQrCode(e,t){let r=t||this.dbAdapter,n={and:[{qrCode:e},{deleted:!1}]};return r.query(de,{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(de,{...t,filters:a})}};var rt="promotions";var tr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addPromotion(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(rt,i);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("AddPromotion",{id:r}),a}async updatePromotion(e,t,r){let n=await(r||this.dbAdapter).get(rt,e);if(!n)throw new Error(`Promotion with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(rt,e,a);return this.changeQueue.enqueue({type:"update",model:rt,record:o}),this.context.logActivity("UpdatePromotion",{id:e}),o}async getPromotions(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(rt,{...e,filters:i})}async getPromotion(e,t){return(t||this.dbAdapter).get(rt,e)}async deletePromotion(e,t){return await(t||this.dbAdapter).delete(rt,e),this.changeQueue.enqueue({type:"delete",model:rt,record:{id:e}}),this.context.logActivity("DeletePromotion",{id:e}),{id:e,queued:!0}}async duplicatePromotion(e,t){let r=await this.getPromotion(e,t);if(!r)throw new Error(`Promotion with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(rt,a);return this.changeQueue.enqueue({type:"create",model:rt,record:a}),this.context.logActivity("DuplicatePromotion",{originalId:e,newId:n}),o}};var Se="returns";var fe="sale_items";var De="purchase_items";var Re="return_items";var J="transactions";var rr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addReturn(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Se,i);return this.changeQueue.enqueue({type:"create",model:Se,record:a}),this.context.logActivity("AddReturn",{id:r}),a}async updateReturn(e,t,r){let n=await(r||this.dbAdapter).get(Se,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(Se,e,a);return this.changeQueue.enqueue({type:"update",model:Se,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(Se,{...e,filters:i})}async getReturn(e,t){return(t||this.dbAdapter).get(Se,e)}async deleteReturn(e,t){return await(t||this.dbAdapter).delete(Se,e),this.changeQueue.enqueue({type:"delete",model:Se,record:{id:e}}),this.context.logActivity("DeleteReturn",{id:e}),{id:e,queued:!0}}async duplicateReturn(e,t){let r=await this.getReturn(e,t);if(!r)throw new Error(`Return with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Se,a);return this.changeQueue.enqueue({type:"create",model:Se,record:a}),this.context.logActivity("DuplicateReturn",{originalId:e,newId:n}),o}async getReferenceItem(e,t,r,n){let i=await n.query(e==="sale_return"?fe:De,{filters:{deleted:!1,productId:r,...e==="sale_return"?{saleId:t}:{purchaseId:t}}});return i.length?i[0]:null}getCurrentRole(){var t,r;let e=(r=(t=this.context.session)==null?void 0:t.user)==null?void 0:r.role;return e?String(e).trim().toLowerCase():null}normalizeRoles(e,t){if(!Array.isArray(e))return t;let r=e.map(n=>String(n||"").trim().toLowerCase()).filter(Boolean);return r.length>0?r:t}validateApproval(e,t,r){let n=String((e==null?void 0:e.approvedBy)||"").trim(),i=String((e==null?void 0:e.reason)||"").trim(),a=String((e==null?void 0:e.approverRole)||"").trim().toLowerCase();if(!n||!i||!a)throw new Error(`${r} approval is required with approvedBy, reason, and approverRole`);if(!t.includes(a))throw new Error(`${r} approval approverRole is not allowed`);return{approvedBy:n,reason:i,approverRole:a}}getFraudGuardPolicy(){var i,a,o,s;let e=((i=this.context.config)==null?void 0:i.enableReturnFraudGuard)===!0,t=Number(((a=this.context.config)==null?void 0:a.returnFraudWindowMinutes)||60),r=Number(((o=this.context.config)==null?void 0:o.returnFraudMaxEvents)||3),n=((s=this.context.config)==null?void 0:s.returnFraudAction)==="block"?"block":"require_approval";return{enabled:e,windowMinutes:t>0?t:60,maxEvents:r>0?r:3,action:n}}async shouldTriggerFraudGuardForRefund(e){let t=this.getFraudGuardPolicy();if(!t.enabled||!e)return!1;let r=new Date(Date.now()-t.windowMinutes*60*1e3).toISOString();return(await this.dbAdapter.query(Se,{filters:{and:[{field:"userId",operator:"=",value:e},{field:"date",operator:">=",value:r},{field:"deleted",operator:"=",value:!1}]}})).filter(a=>Number(a.actualRefund||0)>0).length>=t.maxEvents}async shouldTriggerFraudGuardForCancel(e){let t=this.getFraudGuardPolicy();if(!t.enabled||!e)return!1;let r=new Date(Date.now()-t.windowMinutes*60*1e3).toISOString();return(await this.dbAdapter.query(J,{filters:{and:[{field:"userId",operator:"=",value:e},{field:"date",operator:">=",value:r},{field:"referenceType",operator:"IN",value:["sale_return_cancelled","purchase_return_cancelled"]},{field:"deleted",operator:"=",value:!1}]}})).length>=t.maxEvents}async processReturn(e){var j,z,B,U;let t=(z=(j=this.context)==null?void 0:j.domainServices)==null?void 0:z.inventory,{type:r,saleId:n=null,purchaseId:i=null,reason:a="",items:o,refundAmount:s,actualRefund:c=s,refundMethod:u="cash",creditNoteNumber:l=null,refundNote:d,refundReceivedDate:m,approval:f}=e;if(!n&&!i)throw new Error("saleId or purchaseId is required");if(r==="sale_return"&&!n)throw new Error("saleId required for sale_return");if(r==="purchase_return"&&!i)throw new Error("purchaseId required for purchase_return");let y=this.context.config.requireReasonForReturnOperations,v=String(a||"").trim();if(y&&!v)throw new Error("Return reason is required by policy");let p=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),g=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),x=this.getCurrentRole(),b=!x||!p.includes(x),A=c>0&&this.context.config.requireApprovalForReturnRefund&&b,I=String(((B=this.context.session)==null?void 0:B.userId)||"").trim(),F=c>0&&await this.shouldTriggerFraudGuardForRefund(I),w=this.getFraudGuardPolicy();if(F&&w.action==="block")throw new Error("Fraud guard: repeat return pattern detected (refund blocked)");let q=F&&w.action==="require_approval",M=A||q?this.validateApproval(f,g,q?"Fraud guard return refund":"Return refund"):null,E=(U=this.context.domainServices)==null?void 0:U.uom,L=await E.getUomsMap(),Q=this.context.domainServices.transaction;if(e.saleId){let O=await this.getReturnsByReference("sale_return",e.saleId);if(O.length>0){let _=await this.calculateTotalReturnedQty(O,e.items.map(R=>R.productId));for(let R of e.items){let D=await this.getOriginalQuantity("sale",e.saleId,R.productId),Z=D-(_.get(R.productId)||0);if(R.quantity>Z)throw new Error(`Produk ${R.productId} hanya bisa diretur ${Z} lagi (sudah diretur ${_.get(R.productId)||0}/${D})`)}}}if(e.purchaseId){let O=await this.getReturnsByReference("purchase_return",e.purchaseId);if(O.length>0){let _=await this.calculateTotalReturnedQty(O,e.items.map(R=>R.productId));for(let R of e.items){let D=await this.getOriginalQuantity("purchase",e.purchaseId,R.productId),Z=D-(_.get(R.productId)||0);if(R.quantity>Z)throw new Error(`Produk ${R.productId} hanya bisa diretur ${Z} lagi (sudah diretur ${_.get(R.productId)||0}/${D})`)}}}let T=await this.dbAdapter.transaction(async O=>{var te,X,Y;let _=new Date().toISOString(),R=P(),D=[],Z={id:R,type:r,saleId:n,purchaseId:i,reason:v||null,refundAmount:s,actualRefund:c,refundMethod:c>0?u:null,creditNoteNumber:l,refundNote:c<s?typeof d=="number"?d:s-c:null,refundReceivedDate:c>0?m||_:null,status:c===s?"completed":c>0?"partially_refunded":"no_refund",date:_,userId:((te=this.context.session)==null?void 0:te.userId)||"",version:1,lastModified:_,deleted:!1};await O.create(Se,Z),D.push({type:"create",model:Se,record:Z});for(let ye of o){let se=(X=ye.restock)!=null?X:!0,qe=ye.quantity,ve=await this.getReferenceItem(r,n||i,ye.productId,O);if(!ve)throw new Error(`Item not found in ${r==="sale_return"?"sale":"purchase"} ${n||i}`);let Oe=r==="sale_return"?ve.unitPrice:ve.unitCost,le=ve.uomId,ze={id:P(),returnId:R,productId:ye.productId,quantity:qe,unitPrice:Oe,uomId:le,restock:se,restockNote:se?null:ye.restockNote||"Rusak / tidak bisa dijual",version:1,lastModified:_,deleted:!1};if(await O.create(Re,ze),D.push({type:"create",model:Re,record:ze}),se){let je=E.convertQuantity(qe,{conversionFactor:le&&((Y=L.get(le))==null?void 0:Y.conversionFactor)||1},{conversionFactor:1}),Ke=r==="sale_return"?+je:-je;await t.updateStock(ye.productId,Ke,r,Se,R,O)}}if(c>0)if((r==="sale_return"?"out":"in")==="in"){let se=await Q.recordCashIn({amount:c,method:u,data:{referenceType:r,referenceId:R,note:d}},O);D.push({type:"create",model:J,record:se})}else{let se=await Q.recordCashOut({amount:c,method:u,data:{referenceType:r,referenceId:R,note:d}},O);D.push({type:"create",model:J,record:se})}return M&&this.context.logActivity("ReturnRefundApproved",{returnId:R,approvedBy:M.approvedBy,approverRole:M.approverRole,reason:M.reason}),{returnId:R,queued:!0,type:r,actualRefund:c,syncChanges:D}});for(let O of T.syncChanges)this.changeQueue.enqueue(O);return this.context.eventBus.emit("return:processed",{returnId:T.returnId,type:T.type,actualRefund:T.actualRefund}),this.context.logActivity("processReturn",{returnId:T.returnId,type:T.type,actualRefund:T.actualRefund}),{returnId:T.returnId,queued:T.queued}}async cancelReturn(e,t="Cancelled by user"){var A,I,F,w;let r=(I=(A=this.context)==null?void 0:A.domainServices)==null?void 0:I.inventory,n=(F=this.context.domainServices)==null?void 0:F.uom,i=await n.getUomsMap(),a=this.context.domainServices.transaction,o=typeof t=="string"?String(t||"").trim()||"Cancelled by user":t.reason===void 0?"Cancelled by user":String(t.reason||"").trim(),s=typeof t=="string"?void 0:t.approval;if(this.context.config.requireReasonForReturnOperations&&!String(o||"").trim())throw new Error("Return cancellation reason is required by policy");let u=this.normalizeRoles(this.context.config.returnApprovalBypassRoles,["owner","admin","manager"]),l=this.normalizeRoles(this.context.config.returnApprovalApproverRoles,["owner","admin","manager"]),d=this.getCurrentRole(),m=!d||!u.includes(d),f=this.context.config.requireApprovalForReturnCancel&&m,y=String(((w=this.context.session)==null?void 0:w.userId)||"").trim(),v=await this.shouldTriggerFraudGuardForCancel(y),p=this.getFraudGuardPolicy();if(v&&p.action==="block")throw new Error("Fraud guard: repeat return cancellation pattern detected (cancel blocked)");let g=v&&p.action==="require_approval",x=f||g?this.validateApproval(s,l,g?"Fraud guard return cancellation":"Return cancellation"):null,b=await this.dbAdapter.transaction(async q=>{var Q;let M=await q.get(Se,e);if(!M||M.deleted)throw new Error("Return not found or already deleted");let E=[],L=await q.query(Re,{filters:{returnId:e,deleted:!1}});for(let T of L){if(T.restock){let j=n.convertQuantity(T.quantity,{conversionFactor:T.uomId&&((Q=i.get(T.uomId))==null?void 0:Q.conversionFactor)||1},{conversionFactor:1}),z=M.type==="sale_return"?-j:+j;await r.updateStock(T.productId,z,`${M.type}_cancelled`,Se,e,q)}await q.update(Re,T.id,{deleted:!0,lastModified:new Date().toISOString()}),E.push({type:"delete",model:Re,record:{id:T.id}})}if(M.actualRefund>0)if((M.type==="sale_return"?"in":"out")==="in"){let j=await a.recordCashIn({amount:M.actualRefund,method:M.refundMethod||"cash",data:{referenceType:`${M.type}_cancelled`,referenceId:e,note:o}},q);E.push({type:"create",model:J,record:j})}else{let j=await a.recordCashOut({amount:M.actualRefund,method:M.refundMethod||"cash",data:{referenceType:`${M.type}_cancelled`,referenceId:e,note:o}},q);E.push({type:"create",model:J,record:j})}return await q.update(Se,e,{deleted:!0,lastModified:new Date().toISOString()}),E.push({type:"delete",model:Se,record:{id:e}}),x&&this.context.logActivity("CancelReturnApproved",{returnId:e,approvedBy:x.approvedBy,approverRole:x.approverRole,reason:x.reason}),{returnId:e,queued:!0,syncChanges:E}});for(let q of b.syncChanges)this.changeQueue.enqueue(q);return this.context.eventBus.emit("return:canceled",{returnId:b.returnId}),this.context.logActivity("cancelReturn",{returnId:b.returnId}),{returnId:b.returnId,queued:b.queued}}async getReturnsByReference(e,t){let r=e==="sale_return"?{saleId:t,deleted:!1}:{purchaseId:t,deleted:!1};return this.dbAdapter.query(Se,{filters:r})}async getReturnableQuantity(e,t,r){let n=await this.getOriginalQuantity(e,t,r);if(n<=0)return 0;let i=e==="sale"?"sale_return":"purchase_return",a=await this.getReturnsByReference(i,t);if(!a.length)return n;let s=(await this.calculateTotalReturnedQty(a,[r])).get(r)||0;return Math.max(0,n-s)}async calculateTotalReturnedQty(e,t){let r=new Map;for(let n of e){let i=await this.dbAdapter.query(Re,{filters:{returnId:n.id,deleted:!1,restock:!0}});for(let a of i)t.includes(a.productId)&&r.set(a.productId,(r.get(a.productId)||0)+a.quantity)}return r}async getOriginalQuantity(e,t,r){let n=e==="sale"?fe:De,i=e==="sale"?"saleId":"purchaseId",a=await this.dbAdapter.query(n,{filters:{[i]:t,productId:r,deleted:!1}});return a.length?a[0].quantity:0}};var nr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addReturnItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Re,i);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("AddReturnItem",{id:r}),a}async updateReturnItem(e,t,r){let n=await(r||this.dbAdapter).get(Re,e);if(!n)throw new Error(`ReturnItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Re,e,a);return this.changeQueue.enqueue({type:"update",model:Re,record:o}),this.context.logActivity("UpdateReturnItem",{id:e}),o}async getReturnItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Re,{...e,filters:i})}async getReturnItem(e,t){return(t||this.dbAdapter).get(Re,e)}async deleteReturnItem(e,t){return await(t||this.dbAdapter).delete(Re,e),this.changeQueue.enqueue({type:"delete",model:Re,record:{id:e}}),this.context.logActivity("DeleteReturnItem",{id:e}),{id:e,queued:!0}}async duplicateReturnItem(e,t){let r=await this.getReturnItem(e,t);if(!r)throw new Error(`ReturnItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Re,a);return this.changeQueue.enqueue({type:"create",model:Re,record:a}),this.context.logActivity("DuplicateReturnItem",{originalId:e,newId:n}),o}};var Pe="roles";var ir=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addRole(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Pe,i);return this.changeQueue.enqueue({type:"create",model:Pe,record:a}),this.context.logActivity("AddRole",{id:r}),a}async updateRole(e,t,r){let n=await(r||this.dbAdapter).get(Pe,e);if(!n)throw new Error(`Role with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Pe,e,a);return this.changeQueue.enqueue({type:"update",model:Pe,record:o}),this.context.logActivity("UpdateRole",{id:e}),o}async getRoles(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Pe,{...e,filters:i})}async getRole(e,t){return(t||this.dbAdapter).get(Pe,e)}async deleteRole(e,t){return await(t||this.dbAdapter).delete(Pe,e),this.changeQueue.enqueue({type:"delete",model:Pe,record:{id:e}}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async duplicateRole(e,t){let r=await this.getRole(e,t);if(!r)throw new Error(`Role with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Pe,a);return this.changeQueue.enqueue({type:"create",model:Pe,record:a}),this.context.logActivity("DuplicateRole",{originalId:e,newId:n}),o}};var ue="sales";var he="receivables";var lt="inventory_lots";var ar=class{constructor(e){this.context=e;this.defaultBaseCurrencyCode="IDR";var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e),this.docNumberPolicy=new xt(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t,r){var c,u,l;let n=(c=e.transactionCurrencyCode)!=null?c:this.defaultBaseCurrencyCode,i=(u=e.exchangeRate)!=null?u:1,a=Number.isFinite(i)&&i>0?Number(i):1,o=this.roundCurrencyAmount(e.totalInBaseCurrency!=null?Number(e.totalInBaseCurrency):t*a),s=this.roundCurrencyAmount(e.finalTotalInBaseCurrency!=null?Number(e.finalTotalInBaseCurrency):r*a);return{transactionCurrencyCode:n,exchangeRate:a,exchangeRateSource:(l=e.exchangeRateSource)!=null?l:"snapshot.manual",totalInBaseCurrency:o,finalTotalInBaseCurrency:s}}isExpiredLot(e,t){if(!e)return!1;let r=Date.parse(String(e));return Number.isFinite(r)?r<t:!1}diffInDays(e,t){let r=e.getTime(),n=t.getTime();return!Number.isFinite(r)||!Number.isFinite(n)?NaN:Math.floor((n-r)/(1440*60*1e3))}async enforceTempoCustomerCreditPolicy(e,t){if(!this.context.config.enableCustomerCreditPolicy)return;let r=String(t.customerId||"").trim();if(!r)throw new Error("Customer credit policy: customerId is required for tempo sale");let n=await e.query(he,{filters:{and:[{field:"customerId",operator:"=",value:r},{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),i=new Date(t.nowIso),a=this.context.config.customerCreditOverdueGraceDays,o=0,s=0;for(let l of n){let d=Number(l.amount||0),m=Number(l.paidAmount||0),f=Math.max(0,d-m);if(f<=0)continue;o+=f;let y=this.diffInDays(new Date(String(l.dueDate||"")),i);Number.isFinite(y)&&(s=Math.max(s,y))}let c=this.context.config.customerCreditMaxOutstandingAmount;if(c!=null&&o+t.receivableAmount>c)throw new Error(`Customer credit policy: limit exceeded for customer ${r}`);if(this.context.config.customerCreditBlockOnOverdue&&s>a)throw new Error(`Customer credit policy: overdue receivable exceeds grace period for customer ${r}`);let u=this.context.config.customerCreditEscalationThresholdDays;s>=u&&this.context.logActivity("customerCreditEscalationDetected",{customerId:r,maxDaysPastDue:s,referenceId:t.referenceId,dueDate:t.dueDate})}normalizeDocNo(e){return this.docNumberPolicy.extractDocNo(e)}toBaseQuantity(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertQuantity(e,{conversionFactor:i},{conversionFactor:1}):e}async getDuplicateDocumentNumbers(e){let t=[{field:"deleted",operator:"=",value:!1}];e!=null&&e.dateFrom&&t.push({field:"date",operator:">=",value:e.dateFrom}),e!=null&&e.dateTo&&t.push({field:"date",operator:"<=",value:e.dateTo});let r=await this.dbAdapter.query(ue,{filters:{and:t}}),n=new Map;for(let i of r){let a=this.normalizeDocNo(i.note);if(!a)continue;let o=n.get(a)||[];o.push(String(i.id)),n.set(a,o)}return Array.from(n.entries()).filter(([,i])=>i.length>1).map(([i,a])=>({docNo:i,saleIds:a}))}async requestReprint(e,t){let r=String(t.actorId||"").trim(),n=String(t.reason||"").trim();if(!r)throw new Error("Reprint policy: actorId is required");if(!n)throw new Error("Reprint policy: reason is required");let i=await this.dbAdapter.get(ue,e);if(!i||i.deleted)throw new Error(`Sale ${e} not found`);let a=this.normalizeDocNo(i.note),s=(await this.dbAdapter.query(ae,{filters:{and:[{field:"tableName",operator:"=",value:ue},{field:"recordId",operator:"=",value:e},{field:"action",operator:"=",value:"reprint"}]}})).length+1,c=a?(await this.getDuplicateDocumentNumbers()).some(l=>l.docNo===a):!1,u=new Date().toISOString();return await this.dbAdapter.create(ae,{id:P(),tableName:ue,recordId:e,action:"reprint",changes:{actorId:r,reason:n,terminalId:t.terminalId||null,docNo:a,reprintCount:s,duplicateDocNoDetected:c},userId:r,timestamp:u}),c&&await this.dbAdapter.create(ae,{id:P(),tableName:ue,recordId:e,action:"duplicate_doc_detected",changes:{docNo:a,detector:"sale.requestReprint",detectedAt:u},userId:r,timestamp:u}),{saleId:e,docNo:a,reprintCount:s,duplicateDocNoDetected:c}}async consumeInventoryLotsForSale(e,t){var v,p,g;let r=Number(t.quantity||0);if(!Number.isFinite(r)||r<=0)return[];let n=(v=this.context.domainServices)==null?void 0:v.uom,i=await n.getUomsMap(),a=t.uomId&&((p=i.get(t.uomId))==null?void 0:p.conversionFactor)||1,o=n.convertQuantity(r,{conversionFactor:a},{conversionFactor:1});if(!Number.isFinite(o)||o<=0)return[];let s=await e.query(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 c=Number.isFinite(Date.parse(t.saleDate))?Date.parse(t.saleDate):Date.now(),u=new Date().toISOString(),l=[],d=[],m=0;for(let x of s){if(this.isExpiredLot(x.expiryDate,c)){if(x.status!=="expired"){let A=await e.update(lt,x.id,{status:"expired",version:Number(x.version||0)+1,lastModified:u});l.push({id:A.id,remainingQuantity:Number(A.remainingQuantity||0),status:String(A.status||"expired"),version:Number(A.version||0),lastModified:String(A.lastModified||u)})}continue}d.push(x),m+=Number(x.remainingQuantity||0)}if(m<o)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: insufficient non-expired lot stock`);let f=((g=this.context.config)==null?void 0:g.lotConsumptionPolicy)==="FIFO"?"FIFO":"FEFO";d.sort((x,b)=>{let A=Date.parse(x.lastModified||""),I=Date.parse(b.lastModified||"");if(f==="FIFO"){if(Number.isFinite(A)&&Number.isFinite(I)&&A!==I)return A-I}else{let F=x.expiryDate?Date.parse(x.expiryDate):Number.POSITIVE_INFINITY,w=b.expiryDate?Date.parse(b.expiryDate):Number.POSITIVE_INFINITY;if(Number.isFinite(F)&&Number.isFinite(w)&&F!==w)return F-w;if(Number.isFinite(F)!==Number.isFinite(w))return Number.isFinite(F)?-1:1}return Number.isFinite(A)&&Number.isFinite(I)&&A!==I?A-I:String(x.id).localeCompare(String(b.id))});let y=o;for(let x of d){if(y<=0)break;let b=Number(x.remainingQuantity||0);if(b<=0)continue;let A=Math.min(y,b),I=b-A,F=I<=0?"depleted":"active",w=await e.update(lt,x.id,{remainingQuantity:I,status:F,version:Number(x.version||0)+1,lastModified:u});l.push({id:w.id,remainingQuantity:Number(w.remainingQuantity||0),status:String(w.status||F),version:Number(w.version||0),lastModified:String(w.lastModified||u)}),y-=A}if(y>0)throw new Error(`Sale blocked by expiry policy for product ${t.productId}: lot consumption incomplete`);return l}async addSale(e,t){let r=P(),n=new Date().toISOString(),i=this.resolveCurrencySnapshot(e,Number(e.total||0),Number(e.finalTotal||0)),a={id:r,...e,...i,version:1,lastModified:n,deleted:!1},o=await(t||this.dbAdapter).create(ue,a);return this.changeQueue.enqueue({type:"create",model:ue,record:o}),this.context.logActivity("AddSale",{id:r}),o}async updateSale(e,t,r){let n=await(r||this.dbAdapter).get(ue,e);if(!n)throw new Error(`Sale with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ue,e,a);return this.changeQueue.enqueue({type:"update",model:ue,record:o}),this.context.logActivity("UpdateSale",{id:e}),o}async getSales(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ue,{...e,filters:i})}async getSale(e,t){return(t||this.dbAdapter).get(ue,e)}async deleteSale(e,t){return await(t||this.dbAdapter).delete(ue,e),this.changeQueue.enqueue({type:"delete",model:ue,record:{id:e}}),this.context.logActivity("DeleteSale",{id:e}),{id:e,queued:!0}}async duplicateSale(e,t){let r=await this.getSale(e,t);if(!r)throw new Error(`Sale with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ue,a);return this.changeQueue.enqueue({type:"create",model:ue,record:a}),this.context.logActivity("DuplicateSale",{originalId:e,newId:n}),o}async createSale(e,t,r){let n=await this.dbAdapter.transaction(async i=>{var f,y,v,p,g;let a=((f=this.context.domainServices)==null?void 0:f.uom)||null,o=a?await a.getUomsMap():new Map,s=new Date().toISOString(),c=(y=e.id)!=null?y:P(),u=((v=this.context.config)==null?void 0:v.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",e.date||s):null,l={id:c,userId:e.userId,customerId:e.customerId,sourceOrderId:e.sourceOrderId,status:"completed",date:e.date||s,total:0,ppn:(p=e.ppn)!=null?p:0,pph:(g=e.pph)!=null?g:0,finalTotal:0,transactionCurrencyCode:null,exchangeRate:null,exchangeRateSource:null,totalInBaseCurrency:0,finalTotalInBaseCurrency:0,note:u?this.docNumberPolicy.withNote(e.note,u):e.note,version:1,lastModified:s,deleted:!1},d=[];if(t){let x=t.reduce((b,A)=>{var I;return b+((I=A.unitPrice)!=null?I:0)*A.quantity},0);l.total=x,l.finalTotal=x+l.ppn+l.pph}if(Object.assign(l,this.resolveCurrencySnapshot(e,l.total,l.finalTotal)),await i.create(ue,l),d.push({type:"create",model:ue,record:l}),!t)return{sale:l,syncChanges:d};let m=t.map(x=>({id:P(),saleId:c,...x,version:1,lastModified:s,deleted:!1}));await i.bulkCreate(fe,m);for(let x of m)d.push({type:"create",model:fe,record:x});if(r)if(r.method!=="tempo"){let x=await this.context.domainServices.transaction.recordCashIn({method:r.method,data:{...r.data,referenceType:"sale",referenceId:c},amount:l.finalTotal},i);d.push({type:"create",model:J,record:x})}else{let x=r.dueDate;await this.enforceTempoCustomerCreditPolicy(i,{customerId:l.customerId,receivableAmount:l.finalTotal,referenceId:l.id,dueDate:x,nowIso:s});let b=await this.context.domainServices.receivable.addReceivable({saleId:l.id,customerId:l.customerId,amount:l.finalTotal,dueDate:x,status:"unpaid",paidAmount:0,date:s},i);d.push({type:"create",model:he,record:b})}for(let x of m){let b=this.toBaseQuantity(x.quantity,x.uomId,a,o),A=await this.consumeInventoryLotsForSale(i,{saleId:l.id,saleDate:l.date,productId:x.productId,quantity:x.quantity,uomId:x.uomId});for(let I of A)d.push({type:"update",model:lt,record:I});await this.context.domainServices.inventory.updateStock(x.productId,-b,"sale",ue,l.id,i)}return{sale:l,items:m,syncChanges:d}});for(let i of n.syncChanges)this.changeQueue.enqueue(i);return this.context.eventBus.emit("sale:finalized",n.sale.id),t?{sale:n.sale,items:n.items}:n.sale}async finalizeSale(e,t){let r=await this.dbAdapter.transaction(async n=>{var u;let i=((u=this.context.domainServices)==null?void 0:u.uom)||null,a=i?await i.getUomsMap():new Map,o=await this.getSale(e,n);if(!o)throw new Error(`Sale not found for id ${e}`);let s=[];if(t)if(t.method!=="tempo"){let l=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:e},amount:o.finalTotal},n);s.push({type:"create",model:J,record:l})}else{let l=new Date().toISOString();await this.enforceTempoCustomerCreditPolicy(n,{customerId:o.customerId,receivableAmount:o.finalTotal,referenceId:o.id,dueDate:t.dueDate,nowIso:l});let d=await this.context.domainServices.receivable.addReceivable({saleId:o.id,customerId:o.customerId,amount:o.finalTotal,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:l},n);s.push({type:"create",model:he,record:d})}let c=await n.query(fe,{filters:{saleId:e}});for(let l of c){let d=this.toBaseQuantity(l.quantity,l.uomId,i,a),m=await this.consumeInventoryLotsForSale(n,{saleId:e,saleDate:o.date,productId:l.productId,quantity:l.quantity,uomId:l.uomId});for(let f of m)s.push({type:"update",model:lt,record:f});await this.context.domainServices.inventory.updateStock(l.productId,-d,"sale",ue,e,n)}return{saleId:e,syncChanges:s}});for(let n of r.syncChanges)this.changeQueue.enqueue(n);this.context.eventBus.emit("sale:finalized",r.saleId)}async createSaleFromOrder(e,t){let r=await this.dbAdapter.transaction(async n=>{var b,A,I,F;let i=((b=this.context.domainServices)==null?void 0:b.uom)||null,a=i?await i.getUomsMap():new Map,o=await n.get(oe,e);if(!o)throw new Error(`Order not found for id ${e}`);let s=await n.query(Ae,{filters:{orderId:e,deleted:!1}}),c=new Date().toISOString(),u=P(),l=((A=this.context.config)==null?void 0:A.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",o.date||c):null,d=[],m=s.reduce((w,q)=>w+(q.unitPrice||0)*q.quantity,0),f=(I=o.ppn)!=null?I:0,y=(F=o.pph)!=null?F:0,v=m+f+y,p=this.resolveCurrencySnapshot(o,m,v),g={id:u,userId:o.userId,customerId:o.customerId,sourceOrderId:o.id,discountCode:o.discountCode||null,status:"completed",date:o.date,total:m,discount:0,ppn:f,pph:y,finalTotal:v,...p,note:l?this.docNumberPolicy.withNote(o.note,l):o.note,version:1,lastModified:c,deleted:!1};await n.create(ue,g),d.push({type:"create",model:ue,record:g});let x=s.map(w=>({id:P(),saleId:u,productId:w.productId,quantity:w.quantity,uomId:w.uomId,unitPrice:w.unitPrice,version:1,lastModified:c,deleted:!1}));await n.bulkCreate(fe,x);for(let w of x)d.push({type:"create",model:fe,record:w});if(await n.update(oe,e,{status:"completed",saleId:u,lastModified:c}),d.push({type:"update",model:oe,record:{id:e,status:"completed",saleId:u,lastModified:c}}),t.method!=="tempo"){let w=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:u},amount:g.finalTotal},n);d.push({type:"create",model:J,record:w})}else{let w=t.dueDate;await this.enforceTempoCustomerCreditPolicy(n,{customerId:g.customerId,receivableAmount:g.finalTotal,referenceId:g.id,dueDate:w,nowIso:c});let q=await this.context.domainServices.receivable.addReceivable({saleId:g.id,customerId:g.customerId,amount:g.finalTotal,dueDate:w,status:"unpaid",paidAmount:0,date:c},n);d.push({type:"create",model:he,record:q})}for(let w of x){let q=this.toBaseQuantity(w.quantity,w.uomId,i,a),M=await this.consumeInventoryLotsForSale(n,{saleId:u,saleDate:g.date,productId:w.productId,quantity:w.quantity,uomId:w.uomId});for(let E of M)d.push({type:"update",model:lt,record:E});await this.context.domainServices.inventory.updateStock(w.productId,-q,"sale",ue,u,n)}return{sale:g,items:x,saleId:u,syncChanges:d}});for(let n of r.syncChanges)this.changeQueue.enqueue(n);return this.context.eventBus.emit("sale:finalized",r.saleId),{sale:r.sale,items:r.items}}async createSaleFromCart(e,t){var s;let r=this.context.domainServices.pricing,n=await this.context.domainServices.cart.getCart(e);if(!n)throw new Error(`Cart not found for id ${e}`);let i=(s=this.context.domainServices)==null?void 0:s.uom,a=await i.getUomsMap(),o=await this.dbAdapter.transaction(async c=>{var I,F,w,q;let u=n.customerId?await this.context.domainServices.customer.getCustomer(n.customerId,c):void 0,l=await r.calculateOrderTotal(n.items,n.discountCode,(u==null?void 0:u.groupId)||void 0),d=await r.calculatePPN(l.subTotal),m=await r.calculatePPH(l.subTotal),f=l.total+d+m,y=this.resolveCurrencySnapshot(n,l.subTotal,f),v=new Date().toISOString(),p=P(),g=((I=this.context.config)==null?void 0:I.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("sale",v):null,x={id:p,userId:((w=(F=this.context)==null?void 0:F.session)==null?void 0:w.userId)||"",customerId:n.customerId||null,sourceOrderId:null,discountCode:n.discountCode||null,status:"completed",date:v,total:l.subTotal,discount:l.discount,ppn:d,pph:m,finalTotal:f,...y,note:g?this.docNumberPolicy.withNote(n.note||null,g):n.note||null,version:1,lastModified:v,deleted:!1},b=n.items.map(M=>({id:P(),saleId:p,productId:M.productId,quantity:M.quantity,uomId:M.uomId||null,unitPrice:M.unitPrice,version:1,lastModified:v,deleted:!1})),A=[];await c.create(ue,x),await c.bulkCreate(fe,b),A.push({type:"create",model:ue,record:x});for(let M of b)A.push({type:"create",model:fe,record:M});if(t.method!=="tempo"){let M=await this.context.domainServices.transaction.recordCashIn({method:t.method,data:{...t.data,referenceType:"sale",referenceId:p},amount:x.finalTotal},c);A.push({type:"create",model:J,record:M})}else{let M=t.dueDate;await this.enforceTempoCustomerCreditPolicy(c,{customerId:x.customerId,receivableAmount:x.finalTotal,referenceId:x.id,dueDate:M,nowIso:v});let E=await this.context.domainServices.receivable.addReceivable({saleId:x.id,customerId:x.customerId,amount:x.finalTotal,dueDate:M,status:"unpaid",paidAmount:0,date:v},c);A.push({type:"create",model:he,record:E})}for(let M of b){let E=typeof M.uomId=="string"&&((q=a.get(M.uomId))==null?void 0:q.conversionFactor)||1,L=i.convertQuantity(M.quantity,{conversionFactor:E},{conversionFactor:1}),Q=await this.consumeInventoryLotsForSale(c,{saleId:p,saleDate:x.date,productId:M.productId,quantity:M.quantity,uomId:M.uomId});for(let T of Q)A.push({type:"update",model:lt,record:T});await this.context.domainServices.inventory.updateStock(M.productId,-L,"sale",ue,x.id,c)}return{sale:x,items:b,syncChanges:A}});for(let c of o.syncChanges)this.changeQueue.enqueue(c);this.context.eventBus.emit("sale:finalized",o.sale.id);try{await this.context.domainServices.cart.deleteCart(e)}catch(c){this.context.logError(c,{message:`Sale created but failed to delete cart ${e}`})}return{sale:o.sale,items:o.items}}};var or=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addSaleItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(fe,i);return this.changeQueue.enqueue({type:"create",model:fe,record:a}),this.context.logActivity("AddSaleItem",{id:r}),a}async updateSaleItem(e,t,r){let n=await(r||this.dbAdapter).get(fe,e);if(!n)throw new Error(`SaleItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(fe,e,a);return this.changeQueue.enqueue({type:"update",model:fe,record:o}),this.context.logActivity("UpdateSaleItem",{id:e}),o}async getSaleItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(fe,{...e,filters:i})}async getSaleItem(e,t){return(t||this.dbAdapter).get(fe,e)}async deleteSaleItem(e,t){return await(t||this.dbAdapter).delete(fe,e),this.changeQueue.enqueue({type:"delete",model:fe,record:{id:e}}),this.context.logActivity("DeleteSaleItem",{id:e}),{id:e,queued:!0}}async duplicateSaleItem(e,t){let r=await this.getSaleItem(e,t);if(!r)throw new Error(`SaleItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(fe,a);return this.changeQueue.enqueue({type:"create",model:fe,record:a}),this.context.logActivity("DuplicateSaleItem",{originalId:e,newId:n}),o}};var me="shifts";var sr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addShift(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(me,i);return this.changeQueue.enqueue({type:"create",model:me,record:a}),this.context.logActivity("AddShift",{id:r}),a}async updateShift(e,t,r){let n=await(r||this.dbAdapter).get(me,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(me,e,a);return this.changeQueue.enqueue({type:"update",model:me,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(me,{...e,filters:i})}async getShift(e,t){return(t||this.dbAdapter).get(me,e)}async deleteShift(e,t){return await(t||this.dbAdapter).delete(me,e),this.changeQueue.enqueue({type:"delete",model:me,record:{id:e}}),this.context.logActivity("DeleteShift",{id:e}),{id:e,queued:!0}}async duplicateShift(e,t){let r=await this.getShift(e,t);if(!r)throw new Error(`Shift with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(me,a);return this.changeQueue.enqueue({type:"create",model:me,record:a}),this.context.logActivity("DuplicateShift",{originalId:e,newId:n}),o}async openShift(e,t,r){return this.dbAdapter.transaction(async n=>{var c;if(await this.getActiveShift(e))throw new Error("Kasir ini masih memiliki shift yang aktif");let a=new Date().toISOString(),o=P(),s={id:o,cashierId:e,cashierName:((c=this.context.session)==null?void 0:c.userId)||"Unknown",openedAt:a,closedAt:null,startingCash:t,endingCash:null,systemCash:null,cashDifference:null,status:"open",note:r||null,version:1,lastModified:a,deleted:!1};return await n.create(me,s),this.changeQueue.enqueue({type:"create",model:me,record:s}),this.context.eventBus.emit("shift:opened",{shiftId:o,cashierId:e,startingCash:t}),s})}async closeShift(e,t,r){let n=typeof r=="string"?r:r==null?void 0:r.note,i=typeof r=="string"||r==null?void 0:r.approval;return this.dbAdapter.transaction(async a=>{var p,g,x,b;let o=await a.get(me,e);if(!o||o.deleted||o.status!=="open")throw new Error("Shift tidak ditemukan atau sudah ditutup");let s=await a.query(J,{aggregates:[{function:"SUM",field:"amount",as:"cashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashOut",filter:{and:[{field:"referenceType",operator:"IN",value:["sale_return","expense"]},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:o.openedAt},{field:"date",operator:"<",value:new Date(new Date().getTime()+1e3).toISOString()},{field:"deleted",operator:"=",value:!1}]}}),c=((p=s==null?void 0:s[0])==null?void 0:p.cashIn)||0,u=((g=s==null?void 0:s[0])==null?void 0:g.cashOut)||0,l=c-u,d=o.startingCash+l,m=t-d,f=Math.abs(m);if((x=this.context.config)!=null&&x.requireShiftCloseApprovalOnDifference){let A=(b=this.context.config)==null?void 0:b.shiftCloseDifferenceApprovalThreshold,I=typeof A=="number"&&A>=0?A:0;if(f>I){let F=String((i==null?void 0:i.approvedBy)||"").trim(),w=String((i==null?void 0:i.reason)||"").trim();if(!F||!w)throw new Error(`Shift close approval is required when cash difference exceeds ${I}`)}}let y=i?`[CLOSE_APPROVED_BY=${i.approvedBy}] [CLOSE_APPROVAL_REASON=${i.reason}]`:"",v={closedAt:new Date().toISOString(),endingCash:t,systemCash:d,cashDifference:m,status:"closed",note:[o.note||"",n||"",y].filter(Boolean).join(" | ")||null,lastModified:new Date().toISOString()};return await a.update(me,e,v),this.changeQueue.enqueue({type:"update",model:me,id:e,record:v}),this.context.eventBus.emit("shift:closed",{shiftId:e,cashierId:o.cashierId,systemEndingCash:d,physicalEndingCash:t,difference:m}),i&&this.context.logActivity("CloseShiftApproval",{shiftId:e,cashierId:o.cashierId,approvedBy:i.approvedBy,reason:i.reason,cashDifference:m},a),{...o,...v}})}async reopenShift(e,t){let r=String(t.approvedBy||"").trim(),n=String(t.reason||"").trim();if(!r)throw new Error("approvedBy is required to reopen shift");if(!n)throw new Error("reason is required to reopen shift");return this.dbAdapter.transaction(async i=>{var m;let a=await i.get(me,e);if(!a||a.deleted)throw new Error("Shift tidak ditemukan");if(a.status!=="closed")throw new Error("Hanya shift berstatus closed yang dapat di-reopen");if(await this.getActiveShift(a.cashierId))throw new Error("Kasir ini masih memiliki shift yang aktif");let s=new Date().toISOString(),c=P(),u=t.startingCash!=null?t.startingCash:(m=a.endingCash)!=null?m:a.startingCash,l=[a.note||"",`[REOPEN_FROM=${e}]`,`[APPROVED_BY=${r}]`,`[REASON=${n}]`].filter(Boolean),d={id:c,cashierId:a.cashierId,cashierName:a.cashierName,openedAt:s,closedAt:null,startingCash:u,endingCash:null,systemCash:null,cashDifference:null,status:"open",note:l.join(" "),version:1,lastModified:s,deleted:!1};return await i.create(me,d),this.changeQueue.enqueue({type:"create",model:me,record:d}),this.context.logActivity("ReopenShiftApproved",{fromShiftId:e,reopenedShiftId:c,cashierId:a.cashierId,approvedBy:r,reason:n},i),this.context.eventBus.emit("shift:reopened",{fromShiftId:e,reopenedShiftId:c,cashierId:a.cashierId,approvedBy:r}),d})}async getActiveShift(e){let t=await this.dbAdapter.query(me,{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(me,{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(me,e);if(!t)throw new Error("Shift tidak ditemukan");let r=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"cashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashOut",filter:{and:[{field:"referenceType",operator:"IN",value:["sale_return","expense"]},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:t.openedAt},{field:"deleted",operator:"=",value:!1}]}});return{cashIn:(r==null?void 0:r.cashIn)||0,cashOut:(r==null?void 0:r.cashOut)||0}}async getDailyReport(e){var d,m,f;let t=await this.getShiftsByDate(e),r=0,n=0,i=0;for(let y of t)r+=y.startingCash,y.status==="closed"&&(n+=y.endingCash||0,i+=y.systemCash||0);let a=`${e}T00:00:00.000Z`,o=`${e}T23:59:59.999Z`,s=await this.dbAdapter.query(J,{aggregates:[{function:"SUM",field:"amount",as:"salesCash",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"returnsCash",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"expenses",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:a},{field:"date",operator:"<=",value:o},{field:"deleted",operator:"=",value:!1}]}}),c=((d=s==null?void 0:s[0])==null?void 0:d.salesCash)||0,u=((m=s==null?void 0:s[0])==null?void 0:m.returnsCash)||0,l=((f=s==null?void 0:s[0])==null?void 0:f.expenses)||0;return{date:e,totalSalesCash:c,totalReturnsCash:u,totalExpenses:l,netCashMovement:c-u-l,startingCash:r,systemEndingCash:i,physicalEndingCash:n,cashDifference:n-i,shifts:t}}};var we="tax_rates";var ur=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addTaxRate(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(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=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(we,a);return this.changeQueue.enqueue({type:"create",model:we,record:a}),this.context.logActivity("DuplicateTaxRate",{originalId:e,newId:n}),o}};var cr=class{constructor(e){this.context=e;this.allowedReferenceTypes=new Set(["sale","purchase","sale_return","purchase_return","sale_return_cancelled","purchase_return_cancelled","receivable_payment","payable_payment","cash_adjustment","expense"]);var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async getIdempotentTransaction(e,t,r){let n=r||this.dbAdapter,i=await n.query(ae,{filters:{and:[{field:"tableName",operator:"=",value:"idempotency_keys"},{field:"recordId",operator:"=",value:t},{field:"action",operator:"=",value:`transaction_${e}`}]},sort:[{field:"timestamp",direction:"desc"}],limit:1});if(!i.length)return null;let a=i[0].changes||{},o=String(a.transactionId||"").trim();return o?n.get(J,o):null}async saveIdempotencyMarker(e,t,r,n){var i;await n.create(ae,{id:P(),tableName:"idempotency_keys",recordId:t,action:`transaction_${e}`,changes:{transactionId:r,action:e},userId:String(((i=this.context.session)==null?void 0:i.userId)||"").trim()||null,timestamp:new Date().toISOString()})}getActorId(e){var n,i,a;let t=String(((n=this.context.session)==null?void 0:n.userId)||"").trim();return t||String(((i=e==null?void 0:e.data)==null?void 0:i.userId)||((a=e==null?void 0:e.data)==null?void 0:a.cashierId)||"").trim()}isShiftGuardEnabled(){var e;return((e=this.context.config)==null?void 0:e.requireActiveShiftForCash)===!0}shouldRequireActiveShift(e){return["sale","purchase","sale_return","purchase_return","receivable_payment","payable_payment","expense","cash_adjustment"].includes(e)}async assertActiveShiftGuard(e,t){var o;let r=String(((o=e==null?void 0:e.data)==null?void 0:o.referenceType)||"").trim();if(!this.isShiftGuardEnabled()||!this.shouldRequireActiveShift(r))return;let n=this.getActorId(e);if(!n)throw new Error("Active shift guard: actor userId/cashierId is required");let a=await(t||this.dbAdapter).query("shifts",{filters:{and:[{field:"cashierId",operator:"=",value:n},{field:"status",operator:"=",value:"open"},{field:"deleted",operator:"=",value:!1}]},limit:1});if(!a||a.length===0)throw new Error(`Active shift guard: no open shift for cashier ${n}`)}assertCashPolicy(e){var n,i,a;if(!this.isShiftGuardEnabled())return;let t=String(((n=e==null?void 0:e.data)==null?void 0:n.referenceType)||"").trim(),r=String(((i=e==null?void 0:e.data)==null?void 0:i.reasonCode)||"").trim();if((t==="expense"||t==="cash_adjustment")&&!r)throw new Error(`Cash policy: reasonCode is required for ${t}`);if(t==="cash_adjustment"){let o=(a=this.context.config)==null?void 0:a.maxCashAdjustmentAmount;if(typeof o=="number"&&o>0&&e.amount>o)throw new Error(`Cash policy: cash adjustment exceeds max limit (${o})`)}}assertReferenceIntegrity(e){var n,i;let t=String(((n=e==null?void 0:e.data)==null?void 0:n.referenceType)||"").trim(),r=String(((i=e==null?void 0:e.data)==null?void 0:i.referenceId)||"").trim();if(!t)throw new Error("Cash movement requires referenceType");if(!r)throw new Error("Cash movement requires referenceId");if(!this.allowedReferenceTypes.has(t))throw new Error(`Cash movement referenceType is invalid: ${t}`)}assertIdempotentReplayConsistency(e,t,r){var c,u;let n=t==="cash_in"?"in":"out",i=String(((c=r==null?void 0:r.data)==null?void 0:c.referenceType)||"").trim(),a=String(((u=r==null?void 0:r.data)==null?void 0:u.referenceId)||"").trim(),o=String((r==null?void 0:r.method)||"").trim();if(e.direction!==n||e.amount!==r.amount||String(e.referenceType||"")!==i||String(e.referenceId||"")!==a||String(e.method||"")!==o)throw new Error("Idempotency key reused with different cash transaction payload")}async addTransaction(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(J,i);return t||this.changeQueue.enqueue({type:"create",model:J,record:a}),this.context.logActivity("AddTransaction",{id:r}),a}async updateTransaction(e,t,r){let n=await(r||this.dbAdapter).get(J,e);if(!n)throw new Error(`Transaction with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(J,e,a);return r||this.changeQueue.enqueue({type:"update",model:J,record:o}),this.context.logActivity("UpdateTransaction",{id:e}),o}async getTransactions(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(J,{...e,filters:i})}async getTransaction(e,t){return(t||this.dbAdapter).get(J,e)}async deleteTransaction(e,t){return await(t||this.dbAdapter).delete(J,e),t||this.changeQueue.enqueue({type:"delete",model:J,record:{id:e}}),this.context.logActivity("DeleteTransaction",{id:e}),{id:e,queued:!0}}async duplicateTransaction(e,t){let r=await this.getTransaction(e,t);if(!r)throw new Error(`Transaction with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(J,a);return t||this.changeQueue.enqueue({type:"create",model:J,record:a}),this.context.logActivity("DuplicateTransaction",{originalId:e,newId:n}),o}async recordCashIn(e,t){var l,d;let r=(l=this.context.registry)==null?void 0:l.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((d=e==null?void 0:e.data)==null?void 0:d.idempotencyKey)||"").trim();if(n){let m=await this.getIdempotentTransaction("cash_in",n,t);if(m)return this.assertIdempotentReplayConsistency(m,"cash_in",e),m}let i=this.getActorId(e),a=P(),o=t||this.dbAdapter,s=1,c=new Date().toISOString(),u={id:a,referenceType:e.data.referenceType,referenceId:e.data.referenceId,direction:"in",amount:e.amount,method:e.method,metadata:e.data,date:new Date().toISOString(),description:e.method,userId:i,version:s,lastModified:c,deleted:!1};try{let m=await o.create(J,u);return n&&await this.saveIdempotencyMarker("cash_in",n,m.id,o),t||this.changeQueue.enqueue({type:"create",model:J,record:m}),this.context.logActivity("RecordCashIn",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash in recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashIn"}),m}catch(m){throw r.logError("Error recording cash in",{id:a,method:e.method,amount:e.amount,error:m}),m}}async recordCashOut(e,t){var l,d;let r=(l=this.context.registry)==null?void 0:l.loggerAdapter;if(e.amount<=0)throw new Error("Amount must be positive");this.assertReferenceIntegrity(e),this.assertCashPolicy(e),await this.assertActiveShiftGuard(e,t);let n=String(((d=e==null?void 0:e.data)==null?void 0:d.idempotencyKey)||"").trim();if(n){let m=await this.getIdempotentTransaction("cash_out",n,t);if(m)return this.assertIdempotentReplayConsistency(m,"cash_out",e),m}let i=this.getActorId(e),a=P(),o=t||this.dbAdapter,s=1,c=new Date().toISOString(),u={id:a,referenceType:e.data.referenceType,referenceId:e.data.referenceId,direction:"out",amount:e.amount,method:e.method,metadata:e.data,date:new Date().toISOString(),description:e.method,userId:i,version:s,lastModified:c,deleted:!1};try{let m=await o.create(J,u);return n&&await this.saveIdempotencyMarker("cash_out",n,m.id,o),t||this.changeQueue.enqueue({type:"create",model:J,record:m}),this.context.logActivity("RecordCashOut",{method:e.method,amount:e.amount,id:m.id},t),r.logInfo("Cash out recorded",{id:a,method:e.method,amount:e.amount,by:"system",reason:"recordCashOut"}),m}catch(m){throw r.logError("Error recording cash out",{id:a,method:e.method,amount:e.amount,error:m}),m}}async adjustCash(e,t,r,n){var o,s;if(e<=0)throw new Error("Amount must be positive");let a={method:"cash",data:{referenceType:"cash_adjustment",referenceId:`adj-${new Date().toISOString().split("T")[0]}-${Date.now()}`,reason:r,reasonCode:"manual_adjustment",adjustedBy:((o=this.context.session)==null?void 0:o.userId)||"",userId:((s=this.context.session)==null?void 0:s.userId)||""},amount:e};return t==="in"?this.recordCashIn(a,n):this.recordCashOut(a,n)}async getTransactionsByReference(e,t,r,n){let i=n||this.dbAdapter,a={deleted:!1,referenceType:e,...t!==void 0?{referenceId:t}:{}},o=r!=null&&r.filters?{and:[r.filters,a]}:a;return await i.query(J,{...r,filters:o})}async getDailySummary(e){let t=e||new Date().toISOString().slice(0,10),r=await this.dbAdapter.query(J,{filters:{field:"date",operator:"LIKE",value:`${t}%`}}),n=r.filter(a=>a.direction==="in").reduce((a,o)=>a+o.amount,0),i=r.filter(a=>a.direction==="out").reduce((a,o)=>a+o.amount,0);return{totalIn:n,totalOut:i,net:n-i,date:t}}};var nt="uoms";function no(h,e){return h*e}function io(h,e){return e!==0?h/e:NaN}var dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addUom(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(nt,i);return this.changeQueue.enqueue({type:"create",model:nt,record:a}),this.context.logActivity("AddUom",{id:r}),a}async updateUom(e,t,r){let n=await(r||this.dbAdapter).get(nt,e);if(!n)throw new Error(`Uom with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(nt,e,a);return this.changeQueue.enqueue({type:"update",model:nt,record:o}),this.context.logActivity("UpdateUom",{id:e}),o}async getUoms(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(nt,{...e,filters:i})}async getUom(e,t){return(t||this.dbAdapter).get(nt,e)}async deleteUom(e,t){return await(t||this.dbAdapter).delete(nt,e),this.changeQueue.enqueue({type:"delete",model:nt,record:{id:e}}),this.context.logActivity("DeleteUom",{id:e}),{id:e,queued:!0}}async duplicateUom(e,t){let r=await this.getUom(e,t);if(!r)throw new Error(`Uom with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(nt,a);return this.changeQueue.enqueue({type:"create",model:nt,record:a}),this.context.logActivity("DuplicateUom",{originalId:e,newId:n}),o}convertQuantity(e,t,r){let n=no(e,t.conversionFactor);return io(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 lr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addUser(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(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=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(He,a);return this.changeQueue.enqueue({type:"create",model:He,record:a}),this.context.logActivity("DuplicateUser",{originalId:e,newId:n}),o}};var Xe="suppliers";var pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addSupplier(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Xe,i);return this.changeQueue.enqueue({type:"create",model:Xe,record:a}),this.context.logActivity("AddSupplier",{id:r}),a}async updateSupplier(e,t,r){let n=await(r||this.dbAdapter).get(Xe,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(Xe,e,a);return this.changeQueue.enqueue({type:"update",model:Xe,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(Xe,{...e,filters:i})}async getSupplier(e,t){return(t||this.dbAdapter).get(Xe,e)}async deleteSupplier(e,t){return await(t||this.dbAdapter).delete(Xe,e),this.changeQueue.enqueue({type:"delete",model:Xe,record:{id:e}}),this.context.logActivity("DeleteSupplier",{id:e}),{id:e,queued:!0}}async duplicateSupplier(e,t){let r=await this.getSupplier(e,t);if(!r)throw new Error(`Supplier with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Xe,a);return this.changeQueue.enqueue({type:"create",model:Xe,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(Xe,{...t,filters:a})}};var _e="purchase_orders";var mr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addPurchaseOrder(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(_e,i);return this.changeQueue.enqueue({type:"create",model:_e,record:a}),this.context.logActivity("AddPurchaseOrder",{id:r}),a}async updatePurchaseOrder(e,t,r){let n=await(r||this.dbAdapter).get(_e,e);if(!n)throw new Error(`PurchaseOrder with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(_e,e,a);return this.changeQueue.enqueue({type:"update",model:_e,record:o}),this.context.logActivity("UpdatePurchaseOrder",{id:e}),o}async getPurchaseOrders(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(_e,{...e,filters:i})}async getPurchaseOrder(e,t){return(t||this.dbAdapter).get(_e,e)}async deletePurchaseOrder(e,t){return await(t||this.dbAdapter).delete(_e,e),this.changeQueue.enqueue({type:"delete",model:_e,record:{id:e}}),this.context.logActivity("DeletePurchaseOrder",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrder(e,t){let r=await this.getPurchaseOrder(e,t);if(!r)throw new Error(`PurchaseOrder with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(_e,a);return this.changeQueue.enqueue({type:"create",model:_e,record:a}),this.context.logActivity("DuplicatePurchaseOrder",{originalId:e,newId:n}),o}};var $e="purchase_order_items";var hr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addPurchaseOrderItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create($e,i);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("AddPurchaseOrderItem",{id:r}),a}async updatePurchaseOrderItem(e,t,r){let n=await(r||this.dbAdapter).get($e,e);if(!n)throw new Error(`PurchaseOrderItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update($e,e,a);return this.changeQueue.enqueue({type:"update",model:$e,record:o}),this.context.logActivity("UpdatePurchaseOrderItem",{id:e}),o}async getPurchaseOrderItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query($e,{...e,filters:i})}async getPurchaseOrderItem(e,t){return(t||this.dbAdapter).get($e,e)}async deletePurchaseOrderItem(e,t){return await(t||this.dbAdapter).delete($e,e),this.changeQueue.enqueue({type:"delete",model:$e,record:{id:e}}),this.context.logActivity("DeletePurchaseOrderItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseOrderItem(e,t){let r=await this.getPurchaseOrderItem(e,t);if(!r)throw new Error(`PurchaseOrderItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create($e,a);return this.changeQueue.enqueue({type:"create",model:$e,record:a}),this.context.logActivity("DuplicatePurchaseOrderItem",{originalId:e,newId:n}),o}};var Ie="purchases";var ge="payables";var Ve="financial_settings";var fr=class{constructor(e){this.context=e;this.defaultBaseCurrencyCode="IDR";var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e),this.docNumberPolicy=new xt(e)}roundCurrencyAmount(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}resolveCurrencySnapshot(e,t){var o,s,c;let r=(o=e.transactionCurrencyCode)!=null?o:this.defaultBaseCurrencyCode,n=(s=e.exchangeRate)!=null?s:1,i=Number.isFinite(n)&&n>0?Number(n):1,a=this.roundCurrencyAmount(e.totalInBaseCurrency!=null?Number(e.totalInBaseCurrency):t*i);return{transactionCurrencyCode:r,exchangeRate:i,exchangeRateSource:(c=e.exchangeRateSource)!=null?c:"snapshot.manual",totalInBaseCurrency:a}}toBaseQuantity(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertQuantity(e,{conversionFactor:i},{conversionFactor:1}):e}toBaseUnitCost(e,t,r,n){var a;let i=typeof t=="string"&&((a=n.get(t))==null?void 0:a.conversionFactor)||1;return r?r.convertUnitPrice(e,{conversionFactor:i},{conversionFactor:1}):e}async getCostingMethod(e){var n;let t=await e.query(Ve,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}],limit:1});return String(((n=t[0])==null?void 0:n.costingMethod)||"FIFO").trim().toUpperCase()==="AVERAGE"?"AVERAGE":"FIFO"}async applyCostingPolicy(e,t){var a;if(!t.length)return;let r=(a=this.context.domainServices)==null?void 0:a.inventory,n=await this.getCostingMethod(e),i=new Map;for(let o of t){let s=Number(o.quantity),c=Number(o.unitCost);if(!Number.isFinite(s)||!Number.isFinite(c)||s<=0)continue;let u=i.get(o.productId)||{quantity:0,totalCost:0};u.quantity+=s,u.totalCost+=s*c,i.set(o.productId,u)}for(let[o,s]of i.entries()){let c=await e.get(de,o);if(!c||c.deleted)continue;let u=s.totalCost/s.quantity,l=await r.getStock(o),d=c.cost;if(n==="AVERAGE"){let y=Math.max(0,Number(l)||0),v=y+s.quantity;v>0?d=(c.cost*y+s.totalCost)/v:d=u}else(Number(l)||0)<=0&&(d=u);if(!Number.isFinite(d)||d===c.cost)continue;let m=new Date().toISOString(),f=await e.update(de,o,{cost:d,version:c.version+1,lastModified:m});this.changeQueue.enqueue({type:"update",model:de,record:f})}}async addPurchase(e,t){var c;let r=P(),n=new Date().toISOString(),i=((c=this.context.config)==null?void 0:c.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",e.date||n):null,a=this.resolveCurrencySnapshot(e,Number(e.total||0)),o={id:r,...e,...a,note:i?this.docNumberPolicy.withNote(e.note,i):e.note,version:1,lastModified:n,deleted:!1},s=await(t||this.dbAdapter).create(Ie,o);return this.changeQueue.enqueue({type:"create",model:Ie,record:s}),this.context.logActivity("AddPurchase",{id:r}),s}async updatePurchase(e,t,r){let n=await(r||this.dbAdapter).get(Ie,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(Ie,e,a);return this.changeQueue.enqueue({type:"update",model:Ie,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(Ie,{...e,filters:i})}async getPurchase(e,t){return(t||this.dbAdapter).get(Ie,e)}async deletePurchase(e,t){return await(t||this.dbAdapter).delete(Ie,e),this.changeQueue.enqueue({type:"delete",model:Ie,record:{id:e}}),this.context.logActivity("DeletePurchase",{id:e}),{id:e,queued:!0}}async duplicatePurchase(e,t){let r=await this.getPurchase(e,t);if(!r)throw new Error(`Purchase with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ie,a);return this.changeQueue.enqueue({type:"create",model:Ie,record:a}),this.context.logActivity("DuplicatePurchase",{originalId:e,newId:n}),o}async finalizePurchase(e,t,r){var f,y,v;if(!r){let p=await this.dbAdapter.transaction(async g=>this.finalizePurchase(e,t,g));return this.context.eventBus.emit("purchase:finalized",e),p}let n=(y=(f=this.context)==null?void 0:f.domainServices)==null?void 0:y.inventory,i=((v=this.context.domainServices)==null?void 0:v.uom)||null,a=i?await i.getUomsMap():new Map,o=await r.get(Ie,e);if(!o)throw new Error(`Purchase not found for id ${e}`);let s=await r.query(De,{filters:{and:[{field:"purchaseId",value:e},{field:"deleted",value:!1}]}}),c=s.reduce((p,g)=>p+g.unitCost*g.quantity,0),u=Date.now(),l=new Date().toISOString(),d=this.resolveCurrencySnapshot(o,c);await r.update(Ie,e,{total:c,...d,version:u,lastModified:l});let m={...o,total:c,...d,version:u,lastModified:l};await this.applyCostingPolicy(r,s.map(p=>({productId:p.productId,quantity:this.toBaseQuantity(p.quantity,p.uomId,i,a),unitCost:this.toBaseUnitCost(p.unitCost,p.uomId,i,a)})));for(let p of s)await n.updateStock(p.productId,this.toBaseQuantity(p.quantity,p.uomId,i,a),"purchase",Ie,e,r);return await this.context.domainServices.priceHistory.recordPriceHistory(s.map(p=>({productId:p.productId,unitCost:this.toBaseUnitCost(p.unitCost,p.uomId,i,a),supplierId:o.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:m.supplierId,purchaseId:m.id,amount:m.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:m.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:m.total,method:t.method,data:{referenceType:"purchase",referenceId:m.id,...t.data||{}}},r),this.changeQueue.enqueue({type:"update",model:Ie,record:m}),{purchase:m,queued:!0}}async receivePurchaseFromPO(e,t,r){var E,L,Q,T,j,z;if(!r){let B=await this.dbAdapter.transaction(async U=>this.receivePurchaseFromPO(e,t,U));return this.context.eventBus.emit("purchase:finalized",B.purchase.id),B}let n=(L=(E=this.context)==null?void 0:E.domainServices)==null?void 0:L.inventory,i=((Q=this.context.domainServices)==null?void 0:Q.uom)||null,a=i?await i.getUomsMap():new Map,o=await r.get(_e,e);if(!o)throw new Error(`PurchaseOrder not found for id ${e}`);if(o.status!=="draft"&&o.status!=="sent"&&o.status!=="partially_received")throw new Error(`PurchaseOrder with id ${e} cannot be received as it is not in draft/sent/partially_received status`);let s=await r.query($e,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}}),u=(await r.query(Ie,{filters:{and:[{field:"purchaseOrderId",value:e},{field:"deleted",value:!1}]}})).map(B=>B.id),l=new Map;if(u.length>0){let B=await r.query(De,{filters:{and:[{field:"deleted",value:!1},{or:u.map(U=>({field:"purchaseId",value:U}))}]}});for(let U of B)U.purchaseOrderItemId&&l.set(U.purchaseOrderItemId,(l.get(U.purchaseOrderItemId)||0)+Number(U.quantity||0))}let d=new Map(s.map(B=>[B.id,B])),m=new Map;for(let B of s){let U=m.get(B.productId)||[];U.push(B),m.set(B.productId,U)}let f=[],y=Array.isArray(t.receivedItems)?t.receivedItems:null;if(y&&y.length>0){let B=((T=this.context.config)==null?void 0:T.requireLotExpiryForPurchaseReceiving)===!0;for(let U of y){let _=U.purchaseOrderItemId?d.get(U.purchaseOrderItemId):void 0;if(!_&&U.productId){let se=m.get(U.productId)||[];if(se.length===1)_=se[0];else if(se.length>1)throw new Error(`Ambiguous productId ${U.productId}: provide purchaseOrderItemId for partial receiving`)}if(!_)throw new Error("Invalid partial receiving payload: source purchase order item not found");let R=Number(U.receivedQuantity);if(!Number.isFinite(R)||R<=0)throw new Error("Invalid partial receiving payload: receivedQuantity must be > 0");let D=l.get(_.id)||0,Z=f.filter(se=>se.sourceOrderItem.id===_.id).reduce((se,qe)=>se+qe.quantity,0),te=Number(_.quantity)-D-Z;if(R>te)throw new Error(`Partial receiving exceeds remaining quantity for PO item ${_.id}`);let X=U.unitCost!=null?Number(U.unitCost):Number(_.unitCost);if(!Number.isFinite(X)||X<0)throw new Error("Invalid partial receiving payload: unitCost must be >= 0");let Y=U.serialNumber!=null?String(U.serialNumber).trim():"";if(Y&&R!==1)throw new Error("Serial-number receiving currently requires receivedQuantity = 1");f.push({sourceOrderItem:_,quantity:R,unitCost:X,uomId:U.uomId!==void 0?U.uomId:_.uomId,lotNumber:U.lotNumber!=null&&String(U.lotNumber).trim()||null,serialNumber:Y||null,expiryDate:U.expiryDate!=null&&String(U.expiryDate).trim()||null,note:U.note!=null?String(U.note):null});let ye=f[f.length-1];if(B){if(!ye.lotNumber)throw new Error("Lot policy violation: lotNumber is required when requireLotExpiryForPurchaseReceiving=true");if(!ye.expiryDate)throw new Error("Lot policy violation: expiryDate is required when requireLotExpiryForPurchaseReceiving=true")}}}else{if(((j=this.context.config)==null?void 0:j.requireLotExpiryForPurchaseReceiving)===!0)throw new Error("Lot policy violation: receivedItems with lotNumber and expiryDate are required when requireLotExpiryForPurchaseReceiving=true");for(let B of s){let U=l.get(B.id)||0,O=Number(B.quantity)-U;O<=0||f.push({sourceOrderItem:B,quantity:O,unitCost:Number(B.unitCost),uomId:B.uomId,lotNumber:null,serialNumber:null,expiryDate:null,note:null})}}if(f.length===0)throw new Error(`PurchaseOrder with id ${e} has no remaining receivable items`);let v=f.reduce((B,U)=>B+U.unitCost*U.quantity,0),p=P(),g=new Date().toISOString(),x=((z=this.context.config)==null?void 0:z.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",o.date||g):null,b={id:p,supplierId:o.supplierId,userId:o.userId,purchaseOrderId:e,date:o.date,total:v,...this.resolveCurrencySnapshot(o,v),note:x?this.docNumberPolicy.withNote(o.note,x):o.note,version:1,lastModified:g,deleted:!1};await r.create(Ie,b),this.changeQueue.enqueue({type:"create",model:Ie,record:b});for(let B of f){let U=P(),O={id:U,purchaseId:p,purchaseOrderItemId:B.sourceOrderItem.id,productId:B.sourceOrderItem.productId,quantity:B.quantity,uomId:B.uomId,unitCost:B.unitCost,version:1,lastModified:g,deleted:!1};if(await r.create(De,O),this.changeQueue.enqueue({type:"create",model:De,record:O}),B.lotNumber||B.serialNumber||B.expiryDate){let _=this.toBaseQuantity(B.quantity,B.uomId,i,a),R={id:P(),productId:B.sourceOrderItem.productId,purchaseId:p,purchaseItemId:U,purchaseOrderId:e,purchaseOrderItemId:B.sourceOrderItem.id,lotNumber:B.lotNumber,serialNumber:B.serialNumber,expiryDate:B.expiryDate,quantity:_,remainingQuantity:_,status:"active",note:B.note,version:1,lastModified:g,deleted:!1};await r.create(lt,R),this.changeQueue.enqueue({type:"create",model:lt,record:R})}}let A=new Map(l);for(let B of f)A.set(B.sourceOrderItem.id,(A.get(B.sourceOrderItem.id)||0)+B.quantity);let F=s.every(B=>(A.get(B.id)||0)>=Number(B.quantity))?"received":"partially_received",w=Date.now(),q=new Date().toISOString();await r.update(_e,e,{status:F,version:w,lastModified:q}),this.changeQueue.enqueue({type:"update",model:_e,record:{id:e,status:F,version:w,lastModified:q}});let M=f.filter(B=>Number(B.unitCost)!==Number(B.sourceOrderItem.unitCost)).map(B=>({purchaseOrderItemId:B.sourceOrderItem.id,productId:B.sourceOrderItem.productId,orderedUnitCost:B.sourceOrderItem.unitCost,receivedUnitCost:B.unitCost,quantity:B.quantity,varianceAmount:(B.unitCost-B.sourceOrderItem.unitCost)*B.quantity}));M.length>0&&await this.context.logActivity("PO_PRICE_VARIANCE_DETECTED",{purchaseOrderId:e,purchaseId:p,entries:M},r),await this.applyCostingPolicy(r,f.map(B=>({productId:B.sourceOrderItem.productId,quantity:this.toBaseQuantity(B.quantity,B.uomId,i,a),unitCost:this.toBaseUnitCost(B.unitCost,B.uomId,i,a)})));for(let B of f)await n.updateStock(B.sourceOrderItem.productId,this.toBaseQuantity(B.quantity,B.uomId,i,a),"purchase",Ie,p,r);return await this.context.domainServices.priceHistory.recordPriceHistory(f.map(B=>({productId:B.sourceOrderItem.productId,unitCost:this.toBaseUnitCost(B.unitCost,B.uomId,i,a),supplierId:o.supplierId})),r),t.method==="tempo"?await this.context.domainServices.payable.addPayable({supplierId:b.supplierId,purchaseId:b.id,amount:b.total,dueDate:t.dueDate,status:"unpaid",paidAmount:0,date:b.date||new Date().toISOString()},r):await this.context.domainServices.transaction.recordCashOut({amount:b.total,method:t.method,data:{referenceType:"purchase",referenceId:b.id,...t.data||{}}},r),{purchase:b,queued:!0}}async createPurchaseFromCart(e){var a,o,s;let t=(o=(a=this.context)==null?void 0:a.domainServices)==null?void 0:o.inventory,r=(s=this.context.domainServices)==null?void 0:s.uom,n=(await r.getUoms()).reduce((c,u)=>({...c,[u.id]:u}),{}),i;try{i=await this.dbAdapter.transaction(async c=>{var g,x;let u=new Date().toISOString(),l=P(),d=((g=this.context.config)==null?void 0:g.enableSequentialDocumentNumbers)===!0?await this.docNumberPolicy.next("purchase",u):null,m=[],f=e.items.reduce((b,A)=>b+A.unitCost*A.quantity,0),y={id:l,supplierId:e.supplierId,userId:((x=this.context.session)==null?void 0:x.userId)||"",purchaseOrderId:null,date:u,total:f,...this.resolveCurrencySnapshot(e,f),note:d?this.docNumberPolicy.withNote(e.note||null,d):e.note||null,version:1,lastModified:u,deleted:!1};await c.create(Ie,y),m.push({type:"create",model:Ie,record:y});let v=e.items.map(b=>({id:P(),purchaseId:l,purchaseOrderItemId:null,productId:b.productId,quantity:b.quantity,uomId:b.uomId||null,unitCost:b.unitCost,version:1,lastModified:u,deleted:!1}));await c.bulkCreate(De,v);for(let b of v)m.push({type:"create",model:De,record:b});await this.applyCostingPolicy(c,v.map(b=>{let A=typeof b.uomId=="string"?n[b.uomId].conversionFactor:1;return{productId:b.productId,quantity:r.convertQuantity(b.quantity,{conversionFactor:A},{conversionFactor:1}),unitCost:r.convertUnitPrice(b.unitCost,{conversionFactor:A},{conversionFactor:1})}}));for(let b of v){let A=typeof b.uomId=="string"?n[b.uomId].conversionFactor:1;await t.updateStock(b.productId,r.convertQuantity(b.quantity,{conversionFactor:A},{conversionFactor:1}),"purchase",Ie,l,c)}let p=[];for(let b of v){let A=typeof b.uomId=="string"?n[b.uomId].conversionFactor:1;p.push({productId:b.productId,unitCost:r.convertUnitPrice(b.unitCost,{conversionFactor:A},{conversionFactor:1}),supplierId:e.supplierId,effectiveDate:u})}if(await this.context.domainServices.priceHistory.recordPriceHistory(p,c),e.paymentMethod==="tempo"){let b=await this.context.domainServices.payable.addPayable({supplierId:y.supplierId,purchaseId:y.id,amount:y.total,dueDate:e.dueDate,status:"unpaid",paidAmount:0,date:y.date||new Date().toISOString()},c);m.push({type:"create",model:ge,record:b})}else{let b=await this.context.domainServices.transaction.recordCashOut({amount:f,method:e.paymentMethod,data:{referenceType:"purchase",referenceId:l,...e.paymentData||{}}},c);m.push({type:"create",model:J,record:b})}return{purchase:y,items:v,purchaseId:l,syncChanges:m}})}catch(c){throw t.clearStockCache(),c}for(let c of i.syncChanges)this.changeQueue.enqueue(c);return this.context.eventBus.emit("purchase:finalized",i.purchaseId),{purchase:i.purchase,items:i.items}}};var gr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addPurchaseItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(De,i);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("AddPurchaseItem",{id:r}),a}async updatePurchaseItem(e,t,r){let n=await(r||this.dbAdapter).get(De,e);if(!n)throw new Error(`PurchaseItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(De,e,a);return this.changeQueue.enqueue({type:"update",model:De,record:o}),this.context.logActivity("UpdatePurchaseItem",{id:e}),o}async getPurchaseItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(De,{...e,filters:i})}async getPurchaseItem(e,t){return(t||this.dbAdapter).get(De,e)}async deletePurchaseItem(e,t){return await(t||this.dbAdapter).delete(De,e),this.changeQueue.enqueue({type:"delete",model:De,record:{id:e}}),this.context.logActivity("DeletePurchaseItem",{id:e}),{id:e,queued:!0}}async duplicatePurchaseItem(e,t){let r=await this.getPurchaseItem(e,t);if(!r)throw new Error(`PurchaseItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(De,a);return this.changeQueue.enqueue({type:"create",model:De,record:a}),this.context.logActivity("DuplicatePurchaseItem",{originalId:e,newId:n}),o}};var Ee="inventory_logs";function wt(h){return{all:h=h||new Map,on:function(e,t){var r=h.get(e);r?r.push(t):h.set(e,[t])},off:function(e,t){var r=h.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):h.set(e,[]))},emit:function(e,t){var r=h.get(e);r&&r.slice().map(function(n){n(t)}),(r=h.get("*"))&&r.slice().map(function(n){n(e,t)})}}}var Le=wt();var yr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addInventoryLog(e,t){let r=P(),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=P(),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),Le.emit("stock:changed",{productId:e,delta:0})}};var Ze="price_histories";var vr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addPriceHistory(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ze,i);return this.changeQueue.enqueue({type:"create",model:Ze,record:a}),this.context.logActivity("AddPriceHistory",{id:r}),a}async updatePriceHistory(e,t,r){let n=await(r||this.dbAdapter).get(Ze,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(Ze,e,a);return this.changeQueue.enqueue({type:"update",model:Ze,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(Ze,{...e,filters:i})}async getPriceHistory(e,t){return(t||this.dbAdapter).get(Ze,e)}async deletePriceHistory(e,t){return await(t||this.dbAdapter).delete(Ze,e),this.changeQueue.enqueue({type:"delete",model:Ze,record:{id:e}}),this.context.logActivity("DeletePriceHistory",{id:e}),{id:e,queued:!0}}async duplicatePriceHistory(e,t){let r=await this.getPriceHistory(e,t);if(!r)throw new Error(`PriceHistory with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ze,a);return this.changeQueue.enqueue({type:"create",model:Ze,record:a}),this.context.logActivity("DuplicatePriceHistory",{originalId:e,newId:n}),o}async recordPriceHistory(e,t){var n;let r=[];for(let i of e){let a={id:P(),productId:i.productId,unitCost:i.unitCost,supplierId:i.supplierId,effectiveDate:(n=i.effectiveDate)!=null?n:new Date().toISOString(),version:1,lastModified:new Date().toISOString(),deleted:!1},o=await(t||this.dbAdapter).create(Ze,a);this.context.logActivity("RecordPriceHistory",{productId:i.productId,unitCost:i.unitCost}),r.push(o)}return r}};var Ce="stock_opnames";var Me="stock_opname_items";var br=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addStockOpname(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ce,i);return this.changeQueue.enqueue({type:"create",model:Ce,record:a}),this.context.logActivity("AddStockOpname",{id:r}),a}async updateStockOpname(e,t,r){let n=await(r||this.dbAdapter).get(Ce,e);if(!n)throw new Error(`StockOpname with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ce,e,a);return this.changeQueue.enqueue({type:"update",model:Ce,record:o}),this.context.logActivity("UpdateStockOpname",{id:e}),o}async getStockOpnames(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ce,{...e,filters:i})}async getStockOpname(e,t){return(t||this.dbAdapter).get(Ce,e)}async deleteStockOpname(e,t){return await(t||this.dbAdapter).delete(Ce,e),this.changeQueue.enqueue({type:"delete",model:Ce,record:{id:e}}),this.context.logActivity("DeleteStockOpname",{id:e}),{id:e,queued:!0}}async duplicateStockOpname(e,t){let r=await this.getStockOpname(e,t);if(!r)throw new Error(`StockOpname with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ce,a);return this.changeQueue.enqueue({type:"create",model:Ce,record:a}),this.context.logActivity("DuplicateStockOpname",{originalId:e,newId:n}),o}async cancelOpname(e){let t=await this.dbAdapter.get(Ce,e);if(!t||t.deleted||t.status!=="pending")throw new Error("Stock opname tidak valid atau sudah selesai");let r={...t,status:"cancelled",version:t.version+1,lastModified:new Date().toISOString(),deleted:!1};await this.dbAdapter.update(Ce,e,r);try{this.changeQueue.enqueue({type:"update",model:Ce,id:t.id,record:r})}catch{}}async completeOpname(e){await this.dbAdapter.transaction(async t=>{var o,s;let r=(s=(o=this.context)==null?void 0:o.domainServices)==null?void 0:s.inventory,n=await t.get(Ce,e);if(!n||n.deleted||n.status!=="pending")throw new Error("Stock opname tidak valid atau sudah selesai");let i=await t.query(Me,{filters:{stockOpnameId:e,deleted:!1}});for(let c of i)c.difference!==0&&await r.updateStock(c.productId,c.difference,"opname_adjustment",Ce,e,t);let a=await t.update(Ce,e,{status:"completed",lastModified:new Date().toISOString()});this.changeQueue.enqueue({type:"update",model:Ce,id:e,record:a})})}};var xr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addStockOpnameItem(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Me,i);return this.changeQueue.enqueue({type:"create",model:Me,record:a}),this.context.logActivity("AddStockOpnameItem",{id:r}),a}async updateStockOpnameItem(e,t,r){let n=await(r||this.dbAdapter).get(Me,e);if(!n)throw new Error(`StockOpnameItem with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Me,e,a);return this.changeQueue.enqueue({type:"update",model:Me,record:o}),this.context.logActivity("UpdateStockOpnameItem",{id:e}),o}async getStockOpnameItems(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Me,{...e,filters:i})}async getStockOpnameItem(e,t){return(t||this.dbAdapter).get(Me,e)}async deleteStockOpnameItem(e,t){return await(t||this.dbAdapter).delete(Me,e),this.changeQueue.enqueue({type:"delete",model:Me,record:{id:e}}),this.context.logActivity("DeleteStockOpnameItem",{id:e}),{id:e,queued:!0}}async duplicateStockOpnameItem(e,t){let r=await this.getStockOpnameItem(e,t);if(!r)throw new Error(`StockOpnameItem with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Me,a);return this.changeQueue.enqueue({type:"create",model:Me,record:a}),this.context.logActivity("DuplicateStockOpnameItem",{originalId:e,newId:n}),o}};var it="stock_adjustments";var Ar=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addStockAdjustment(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(it,i);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("AddStockAdjustment",{id:r}),a}async updateStockAdjustment(e,t,r){let n=await(r||this.dbAdapter).get(it,e);if(!n)throw new Error(`StockAdjustment with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(it,e,a);return this.changeQueue.enqueue({type:"update",model:it,record:o}),this.context.logActivity("UpdateStockAdjustment",{id:e}),o}async getStockAdjustments(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(it,{...e,filters:i})}async getStockAdjustment(e,t){return(t||this.dbAdapter).get(it,e)}async deleteStockAdjustment(e,t){return await(t||this.dbAdapter).delete(it,e),this.changeQueue.enqueue({type:"delete",model:it,record:{id:e}}),this.context.logActivity("DeleteStockAdjustment",{id:e}),{id:e,queued:!0}}async duplicateStockAdjustment(e,t){let r=await this.getStockAdjustment(e,t);if(!r)throw new Error(`StockAdjustment with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(it,a);return this.changeQueue.enqueue({type:"create",model:it,record:a}),this.context.logActivity("DuplicateStockAdjustment",{originalId:e,newId:n}),o}};var at="report_schedules";var Sr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addReportSchedule(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(at,i);return this.changeQueue.enqueue({type:"create",model:at,record:a}),this.context.logActivity("AddReportSchedule",{id:r}),a}async updateReportSchedule(e,t,r){let n=await(r||this.dbAdapter).get(at,e);if(!n)throw new Error(`ReportSchedule with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(at,e,a);return this.changeQueue.enqueue({type:"update",model:at,record:o}),this.context.logActivity("UpdateReportSchedule",{id:e}),o}async getReportSchedules(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(at,{...e,filters:i})}async getReportSchedule(e,t){return(t||this.dbAdapter).get(at,e)}async deleteReportSchedule(e,t){return await(t||this.dbAdapter).delete(at,e),this.changeQueue.enqueue({type:"delete",model:at,record:{id:e}}),this.context.logActivity("DeleteReportSchedule",{id:e}),{id:e,queued:!0}}async duplicateReportSchedule(e,t){let r=await this.getReportSchedule(e,t);if(!r)throw new Error(`ReportSchedule with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(at,a);return this.changeQueue.enqueue({type:"create",model:at,record:a}),this.context.logActivity("DuplicateReportSchedule",{originalId:e,newId:n}),o}};var Ir=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addFinancialSetting(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Ve,i);return this.changeQueue.enqueue({type:"create",model:Ve,record:a}),this.context.logActivity("AddFinancialSetting",{id:r}),a}async updateFinancialSetting(e,t,r){let n=await(r||this.dbAdapter).get(Ve,e);if(!n)throw new Error(`FinancialSetting with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Ve,e,a);return this.changeQueue.enqueue({type:"update",model:Ve,record:o}),this.context.logActivity("UpdateFinancialSetting",{id:e}),o}async getFinancialSettings(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Ve,{...e,filters:i})}async getFinancialSetting(e,t){return(t||this.dbAdapter).get(Ve,e)}async deleteFinancialSetting(e,t){return await(t||this.dbAdapter).delete(Ve,e),this.changeQueue.enqueue({type:"delete",model:Ve,record:{id:e}}),this.context.logActivity("DeleteFinancialSetting",{id:e}),{id:e,queued:!0}}async duplicateFinancialSetting(e,t){let r=await this.getFinancialSetting(e,t);if(!r)throw new Error(`FinancialSetting with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Ve,a);return this.changeQueue.enqueue({type:"create",model:Ve,record:a}),this.context.logActivity("DuplicateFinancialSetting",{originalId:e,newId:n}),o}};var ot="expenses";var Dr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addExpense(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ot,i);return this.changeQueue.enqueue({type:"create",model:ot,record:a}),this.context.logActivity("AddExpense",{id:r}),a}async updateExpense(e,t,r){let n=await(r||this.dbAdapter).get(ot,e);if(!n)throw new Error(`Expense with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ot,e,a);return this.changeQueue.enqueue({type:"update",model:ot,record:o}),this.context.logActivity("UpdateExpense",{id:e}),o}async getExpenses(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ot,{...e,filters:i})}async getExpense(e,t){return(t||this.dbAdapter).get(ot,e)}async deleteExpense(e,t){return await(t||this.dbAdapter).delete(ot,e),this.changeQueue.enqueue({type:"delete",model:ot,record:{id:e}}),this.context.logActivity("DeleteExpense",{id:e}),{id:e,queued:!0}}async duplicateExpense(e,t){let r=await this.getExpense(e,t);if(!r)throw new Error(`Expense with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ot,a);return this.changeQueue.enqueue({type:"create",model:ot,record:a}),this.context.logActivity("DuplicateExpense",{originalId:e,newId:n}),o}};var Pr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addReceivable(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(he,i);return t||this.changeQueue.enqueue({type:"create",model:he,record:a}),this.context.logActivity("AddReceivable",{id:r}),a}async updateReceivable(e,t,r){let n=await(r||this.dbAdapter).get(he,e);if(!n)throw new Error(`Receivable with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(he,e,a);return r||this.changeQueue.enqueue({type:"update",model:he,record:o}),this.context.logActivity("UpdateReceivable",{id:e}),o}async getReceivables(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(he,{...e,filters:i})}async getReceivable(e,t){return(t||this.dbAdapter).get(he,e)}async deleteReceivable(e,t){return await(t||this.dbAdapter).delete(he,e),t||this.changeQueue.enqueue({type:"delete",model:he,record:{id:e}}),this.context.logActivity("DeleteReceivable",{id:e}),{id:e,queued:!0}}async duplicateReceivable(e,t){let r=await this.getReceivable(e,t);if(!r)throw new Error(`Receivable with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(he,a);return t||this.changeQueue.enqueue({type:"create",model:he,record:a}),this.context.logActivity("DuplicateReceivable",{originalId:e,newId:n}),o}};var Cr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}async addPayable(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(ge,i);return t||this.changeQueue.enqueue({type:"create",model:ge,record:a}),this.context.logActivity("AddPayable",{id:r}),a}async updatePayable(e,t,r){let n=await(r||this.dbAdapter).get(ge,e);if(!n)throw new Error(`Payable with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(ge,e,a);return r||this.changeQueue.enqueue({type:"update",model:ge,record:o}),this.context.logActivity("UpdatePayable",{id:e}),o}async getPayables(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(ge,{...e,filters:i})}async getPayable(e,t){return(t||this.dbAdapter).get(ge,e)}async deletePayable(e,t){return await(t||this.dbAdapter).delete(ge,e),t||this.changeQueue.enqueue({type:"delete",model:ge,record:{id:e}}),this.context.logActivity("DeletePayable",{id:e}),{id:e,queued:!0}}async duplicatePayable(e,t){let r=await this.getPayable(e,t);if(!r)throw new Error(`Payable with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(ge,a);return t||this.changeQueue.enqueue({type:"create",model:ge,record:a}),this.context.logActivity("DuplicatePayable",{originalId:e,newId:n}),o}async updatePaidAmount(e,t){var s;let r=(s=this.context.registry)==null?void 0:s.loggerAdapter,n=await this.dbAdapter.get(ge,e);if(!n)throw r.logError("Payable not found",{payableId:e}),new Error(`Payable ${e} not found`);let i=(n.paidAmount||0)+t,a=i>=n.amount?"paid":"partial",o={paidAmount:i,status:a,version:Date.now(),lastModified:new Date().toISOString()};await this.dbAdapter.update(ge,e,o),this.changeQueue.enqueue({type:"update",model:ge,record:{id:e,...o}}),this.context.logActivity("updatePaidAmount",{payableId:e,paidAmount:i,status:a}),r.logInfo("Payable updated",{payableId:e,paidAmount:i,status:a})}};var Qe="settlements";var wr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.changeQueue=$(e)}runInTransaction(e){let t=this.dbAdapter;return typeof t.transaction=="function"?t.transaction(e):e(this.dbAdapter)}async addSettlement(e,t){let r=P(),n=new Date().toISOString(),i={id:r,...e,version:1,lastModified:n,deleted:!1},a=await(t||this.dbAdapter).create(Qe,i);return this.changeQueue.enqueue({type:"create",model:Qe,record:a}),this.context.logActivity("AddSettlement",{id:r}),a}async updateSettlement(e,t,r){let n=await(r||this.dbAdapter).get(Qe,e);if(!n)throw new Error(`Settlement with ID ${e} not found.`);let i=new Date().toISOString(),a={...t,id:e,version:n.version+1,lastModified:i,deleted:!1},o=await(r||this.dbAdapter).update(Qe,e,a);return this.changeQueue.enqueue({type:"update",model:Qe,record:o}),this.context.logActivity("UpdateSettlement",{id:e}),o}async getSettlements(e,t){let r=t||this.dbAdapter,n={deleted:!1},i=e!=null&&e.filters?{and:[e.filters,n]}:n;return r.query(Qe,{...e,filters:i})}async getSettlement(e,t){return(t||this.dbAdapter).get(Qe,e)}async deleteSettlement(e,t){return await(t||this.dbAdapter).delete(Qe,e),this.changeQueue.enqueue({type:"delete",model:Qe,record:{id:e}}),this.context.logActivity("DeleteSettlement",{id:e}),{id:e,queued:!0}}async duplicateSettlement(e,t){let r=await this.getSettlement(e,t);if(!r)throw new Error(`Settlement with ID ${e} not found.`);let n=P(),i=new Date().toISOString(),a={...r,id:n,version:1,lastModified:i,deleted:!1};a.name&&(a.name=`${a.name} (Copy)`);let o=await(t||this.dbAdapter).create(Qe,a);return this.changeQueue.enqueue({type:"create",model:Qe,record:a}),this.context.logActivity("DuplicateSettlement",{originalId:e,newId:n}),o}async createSettlement(e){var s;let t=(s=this.context.registry)==null?void 0:s.loggerAdapter,r=new Date().toISOString(),n=String(e.idempotencyKey||"").trim(),i=!!String(e.receivableId||"").trim(),a=!!String(e.payableId||"").trim();if(e.amount<=0)throw new Error("Settlement amount must be positive");if(i===a)throw new Error("Settlement must reference exactly one of receivableId or payableId");let o=await this.runInTransaction(async c=>{if(n){let d=await c.query(ae,{filters:{and:[{field:"tableName",operator:"=",value:"idempotency_keys"},{field:"recordId",operator:"=",value:n},{field:"action",operator:"=",value:"settlement_create"}]},sort:[{field:"timestamp",direction:"desc"}],limit:1});if(d.length){let m=d[0].changes||{},f=String(m.settlementId||"").trim();if(f){let y=await c.get(Qe,f);if(y)return y}}}if(e.receivableId){let d=await c.get(he,e.receivableId);if(!d||d.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let m=d.amount-d.paidAmount;if(e.amount>m)throw new Error("Settlement amount exceeds remaining receivable amount")}if(e.payableId){let d=await c.get(ge,e.payableId);if(!d||d.deleted)throw new Error(`Payable ${e.payableId} not found`);let m=d.amount-d.paidAmount;if(e.amount>m)throw new Error("Settlement amount exceeds remaining payable amount")}let u={id:P(),receivableId:e.receivableId||null,payableId:e.payableId||null,amount:e.amount,method:e.method,date:e.date,reference:e.reference||null,userId:e.userId,version:Date.now(),lastModified:r,deleted:!1},l=await c.create(Qe,u);if(e.receivableId){let d=await c.get(he,e.receivableId);if(!d||d.deleted)throw new Error(`Receivable ${e.receivableId} not found`);let m=d.paidAmount+e.amount,f={...d,paidAmount:m,status:m>=d.amount?"paid":"partial",version:Date.now(),lastModified:r};await c.update(he,f.id,f)}if(e.payableId){let d=await c.get(ge,e.payableId);if(!d||d.deleted)throw new Error(`Payable ${e.payableId} not found`);let m=d.paidAmount+e.amount,f={...d,paidAmount:m,status:m>=d.amount?"paid":"partial",version:Date.now(),lastModified:r};await c.update(ge,f.id,f)}return n&&await c.create(ae,{id:P(),tableName:"idempotency_keys",recordId:n,action:"settlement_create",changes:{settlementId:l.id},userId:String(e.userId||"").trim()||null,timestamp:r}),l});if(this.changeQueue.enqueue({type:"create",model:Qe,record:o}),e.receivableId){let c=await this.dbAdapter.get(he,e.receivableId);c&&this.changeQueue.enqueue({type:"update",model:he,record:c})}if(e.payableId){let c=await this.dbAdapter.get(ge,e.payableId);c&&this.changeQueue.enqueue({type:"update",model:ge,record:c})}return this.context.logActivity("createSettlement",{id:o.id}),t.logInfo("Settlement created",{id:o.id}),o}};var Er=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=$(this.context),Le.on("stock:changed",this.onStockChanged),Le.on("stock:rebuild",this.onStockRebuild)}async getStock(e){if(this.stockCache.has(e))return this.stockCache.get(e);let t=await this.computeStockFromLogs(e);return this.stockCache.set(e,t),t}async updateStock(e,t,r,n,i,a){var l,d;let o=a||this.adapter;if(t<0){let m=(l=this.context.domainServices)==null?void 0:l.bom;if(m&&(await m.getBomsByParentItemId(e)).length>0){let y=await m.expandBom(e),v=Math.abs(t);for(let p of y){let g=p.quantity*v;if(await this.getStock(p.componentItemId)<g)throw new Error(`Insufficient component ${p.componentItemId}`)}for(let p of y)await this.updateStock(p.componentItemId,-p.quantity*v,r,n,i,o);return}}let s;if(this.stockCache.has(e)?s=this.stockCache.get(e):(s=await this.computeStockFromLogs(e),this.stockCache.set(e,s)),t<0&&s+t<0)throw new Error(`Insufficient stock for product ${e}`);let c={id:P(),productId:e,change:t,reason:r,referenceType:n,referenceId:i,userId:((d=this.context.session)==null?void 0:d.userId)||"",timestamp:new Date().toISOString()};await o.create(Ee,c),this.changeQueue.enqueue({type:"create",model:Ee,record:c});let u=Math.max(0,s+t);this.stockCache.set(e,u)}async rebuildStockCache(){if(!this.isRebuilding){this.isRebuilding=!0;try{let e=await this.adapter.query(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`),Le.emit("stockCache:rebuilt")}finally{this.isRebuilding=!1}}}invalidateProductStock(e){e&&this.stockCache.delete(e)}invalidateProductsStock(e){for(let t of e)this.invalidateProductStock(t)}clearStockCache(){this.stockCache.clear()}async computeStockFromLogs(e){var r;let[t]=await this.adapter.query(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,c]of this.stockCache.entries())c<e&&r.push({productId:s,stock:c});r.sort((s,c)=>s.stock-c.stock);let n=r.slice(0,t),i=n.map(s=>s.productId);if(i.length===0)return[];let a=await this.adapter.query(de,{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 gi={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"}}},yi={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 ao=[{name:"boms",columns:[{name:"id",type:"string"},{name:"parentItemId",type:"string",isOptional:!0,isPrimarySearchKey:!0},{name:"componentItemId",type:"string",isOptional:!0,isPrimarySearchKey:!0},{name:"quantity",type:"number"},{name:"uomId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"categories",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"parentId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"customers",columns:[{name:"id",type:"string"},{name:"name",type:"string",isFullTextSearchable:!0},{name:"phone",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"email",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"groupId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"customer_groups",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"loyalty_accounts",columns:[{name:"id",type:"string"},{name:"customerId",type:"string",isIndexed:!0},{name:"pointsBalance",type:"number"},{name:"totalEarned",type:"number"},{name:"totalRedeemed",type:"number"},{name:"totalExpired",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"loyalty_ledgers",columns:[{name:"id",type:"string"},{name:"customerId",type:"string",isIndexed:!0},{name:"entryType",type:"string",enum:["earn","redeem","expire","adjustment"]},{name:"points",type:"number"},{name:"availablePoints",type:"number"},{name:"expiresAt",type:"string",isOptional:!0,isIndexed:!0},{name:"consumedAt",type:"string",isOptional:!0,isIndexed:!0},{name:"referenceType",type:"string",isOptional:!0},{name:"referenceId",type:"string",isOptional:!0},{name:"note",type:"string",isOptional:!0},{name:"date",type:"string",isIndexed:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"histories",columns:[{name:"id",type:"string"},{name:"tableName",type:"string"},{name:"recordId",type:"string"},{name:"action",type:"string"},{name:"changes",type:"json"},{name:"userId",type:"string",isOptional:!0},{name:"timestamp",type:"string"}],skipMetadataColumns:!0},{name:"orders",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"customerId",type:"string",isOptional:!0},{name:"parentOrderId",type:"string",isOptional:!0},{name:"discountCode",type:"string",isOptional:!0},{name:"channel",type:"string",enum:["dine_in","takeaway","delivery","preorder"],isOptional:!0},{name:"status",type:"string"},{name:"saleId",type:"string",isOptional:!0},{name:"scheduledAt",type:"string",isOptional:!0},{name:"deliveryAddress",type:"string",isOptional:!0},{name:"tableNumber",type:"string",isOptional:!0,isIndexed:!0},{name:"serviceChargeAmount",type:"number",isOptional:!0},{name:"gratuityAmount",type:"number",isOptional:!0},{name:"date",type:"string"},{name:"total",type:"number"},{name:"ppn",type:"number"},{name:"pph",type:"number"},{name:"finalTotal",type:"number"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"order_items",columns:[{name:"id",type:"string"},{name:"orderId",type:"string"},{name:"productId",type:"string"},{name:"quantity",type:"number"},{name:"uomId",type:"string",isOptional:!0},{name:"unitPrice",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"kitchen_tickets",columns:[{name:"id",type:"string"},{name:"orderId",type:"string"},{name:"station",type:"string"},{name:"status",type:"string",enum:["queued","in_progress","ready","served","canceled"]},{name:"note",type:"string",isOptional:!0},{name:"createdBy",type:"string",isOptional:!0},{name:"createdAt",type:"string",isIndexed:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"kitchen_ticket_items",columns:[{name:"id",type:"string"},{name:"ticketId",type:"string"},{name:"orderItemId",type:"string"},{name:"course",type:"string",isOptional:!0},{name:"status",type:"string",enum:["queued","in_progress","ready","served","canceled"]},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"price_tiers",columns:[{name:"id",type:"string"},{name:"tierLevel",type:"number"},{name:"price",type:"number"},{name:"productId",type:"string"},{name:"uom",type:"string",isOptional:!0},{name:"customerGroupId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"products",columns:[{name:"id",type:"string"},{name:"name",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"description",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"barcode",type:"string",isOptional:!0,isFullTextSearchable:!0,isPrimarySearchKey:!0},{name:"qrCode",type:"string",isOptional:!0,isIndexed:!0,isFullTextSearchable:!0,isPrimarySearchKey:!0},{name:"price",type:"number"},{name:"cost",type:"number"},{name:"categoryId",type:"string"},{name:"baseUomId",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"promotions",columns:[{name:"id",type:"string"},{name:"code",type:"string"},{name:"type",type:"string"},{name:"value",type:"number"},{name:"name",type:"string",isOptional:!0},{name:"description",type:"string",isOptional:!0},{name:"targetType",type:"string"},{name:"targetIds",type:"string[]"},{name:"expiresAt",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"returns",notes:`
|
|
2
2
|
referenceType | Arah Stok | Arah Kas | Catatan
|
|
3
3
|
-----------------+----------------+----------------------+-----------------------
|
|
4
4
|
sale | - (out) | + (in) | Penjualan
|
|
@@ -8,11 +8,11 @@ purchase_return | - (out) | + (in) | Retur pembelian
|
|
|
8
8
|
cash_adjustment | \u2014 | tergantung direction | Hanya di transactions
|
|
9
9
|
expense | \u2014 | - (out) | Pengeluaran lain (Expense -> transactions)
|
|
10
10
|
stock_adjustment | explisit (-/+) | \u2014 | StockAdjustment/StockOpname -> inventoryLog
|
|
11
|
-
`,columns:[{name:"id",type:"string"},{name:"saleId",type:"string",isOptional:!0,isIndexed:!0},{name:"purchaseId",type:"string",isOptional:!0,isIndexed:!0},{name:"type",type:"string",enum:["sale_return","purchase_return"]},{name:"refundAmount",type:"number",notes:"jumlah yang SEHARUSNYA direfund (100%)"},{name:"actualRefund",type:"number",notes:"jumlah yang BENAR-BENAR diterima dari supplier"},{name:"refundMethod",type:"string",enum:["cash","bank_transfer","voucher","credit_note","deduct_next_purchase"],isOptional:!0},{name:"creditNoteNumber",type:"string",isOptional:!0,notes:"kalau supplier kasih nota kredit"},{name:"refundReceivedDate",type:"string",isOptional:!0,notes:"kapan uang/voucher benar-benar masuk"},{name:"refundNote",type:"number",isOptional:!0,notes:'"Hanya diganti 80%", "Potong di PO berikutnya", dll'},{name:"date",type:"string"},{name:"userId",type:"string"},{name:"reason",type:"string",isOptional:!0},{name:"status",type:"string",enum:["draft","completed","partially_refunded","no_refund","canceled"]},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"return_items",columns:[{name:"id",type:"string"},{name:"returnId",type:"string"},{name:"productId",type:"string"},{name:"quantity",type:"number"},{name:"uomId",type:"string",isOptional:!0,notes:"satuan yang digunakan saat transaksi aslis"},{name:"unitPrice",type:"number",notes:"harga asli saat dijual/dibeli (bukan harga sekarang)"},{name:"restock",type:"boolean",notes:"default: true"},{name:"restockNote",type:"string",isOptional:!0,notes:'"Rusak berat", "Kadaluarsa", "Display rusak", dll'},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"roles",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"permissions",type:"string[]"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"sales",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"customerId",type:"string",isOptional:!0},{name:"sourceOrderId",type:"string",isOptional:!0},{name:"discountCode",type:"string",isOptional:!0},{name:"status",type:"string"},{name:"date",type:"string"},{name:"total",type:"number"},{name:"discount",type:"number"},{name:"ppn",type:"number"},{name:"pph",type:"number"},{name:"finalTotal",type:"number"},{name:"transactionCurrencyCode",type:"string",isOptional:!0},{name:"exchangeRate",type:"number",isOptional:!0},{name:"exchangeRateSource",type:"string",isOptional:!0},{name:"totalInBaseCurrency",type:"number",isOptional:!0},{name:"finalTotalInBaseCurrency",type:"number",isOptional:!0},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"sale_items",columns:[{name:"id",type:"string"},{name:"saleId",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:"shifts",columns:[{name:"id",type:"string"},{name:"cashierId",type:"string",isIndexed:!0},{name:"cashierName",type:"string"},{name:"openedAt",type:"string",isIndexed:!0,notes:"ISO"},{name:"closedAt",type:"string",isOptional:!0,notes:"null = masih buka"},{name:"startingCash",type:"number",notes:"saldo awal"},{name:"endingCash",type:"number",isOptional:!0,notes:"saldo akhir"},{name:"systemCash",type:"number",isOptional:!0,notes:"dihitung otomatis saat tutup"},{name:"cashDifference",type:"number",isOptional:!0,notes:"endingCash - systemCash"},{name:"status",type:"string"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"tax_rates",columns:[{name:"id",type:"string"},{name:"key",type:"string",isIndexed:!0},{name:"rate",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"transactions",columns:[{name:"id",type:"string"},{name:"amount",type:"number",notes:"selalu positif"},{name:"method",type:"string",enum:["cash","card","voucher","bank_transfer"]},{name:"referenceType",type:"string",enum:["sale","purchase","sale_return","purchase_return","receivable_payment","payable_payment","cash_adjustment","expense"]},{name:"referenceId",type:"string"},{name:"direction",type:"string",enum:["in","out"]},{name:"metadata",type:"json",isOptional:!0},{name:"date",type:"string"},{name:"description",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"uoms",columns:[{name:"id",type:"string"},{name:"code",type:"string"},{name:"name",type:"string"},{name:"conversionFactor",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"users",columns:[{name:"id",type:"string"},{name:"username",type:"string"},{name:"
|
|
11
|
+
`,columns:[{name:"id",type:"string"},{name:"saleId",type:"string",isOptional:!0,isIndexed:!0},{name:"purchaseId",type:"string",isOptional:!0,isIndexed:!0},{name:"type",type:"string",enum:["sale_return","purchase_return"]},{name:"refundAmount",type:"number",notes:"jumlah yang SEHARUSNYA direfund (100%)"},{name:"actualRefund",type:"number",notes:"jumlah yang BENAR-BENAR diterima dari supplier"},{name:"refundMethod",type:"string",enum:["cash","bank_transfer","voucher","credit_note","deduct_next_purchase"],isOptional:!0},{name:"creditNoteNumber",type:"string",isOptional:!0,notes:"kalau supplier kasih nota kredit"},{name:"refundReceivedDate",type:"string",isOptional:!0,notes:"kapan uang/voucher benar-benar masuk"},{name:"refundNote",type:"number",isOptional:!0,notes:'"Hanya diganti 80%", "Potong di PO berikutnya", dll'},{name:"date",type:"string"},{name:"userId",type:"string"},{name:"reason",type:"string",isOptional:!0},{name:"status",type:"string",enum:["draft","completed","partially_refunded","no_refund","canceled"]},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"return_items",columns:[{name:"id",type:"string"},{name:"returnId",type:"string"},{name:"productId",type:"string"},{name:"quantity",type:"number"},{name:"uomId",type:"string",isOptional:!0,notes:"satuan yang digunakan saat transaksi aslis"},{name:"unitPrice",type:"number",notes:"harga asli saat dijual/dibeli (bukan harga sekarang)"},{name:"restock",type:"boolean",notes:"default: true"},{name:"restockNote",type:"string",isOptional:!0,notes:'"Rusak berat", "Kadaluarsa", "Display rusak", dll'},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"roles",columns:[{name:"id",type:"string"},{name:"name",type:"string"},{name:"permissions",type:"string[]"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"sales",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"customerId",type:"string",isOptional:!0},{name:"sourceOrderId",type:"string",isOptional:!0},{name:"discountCode",type:"string",isOptional:!0},{name:"status",type:"string"},{name:"date",type:"string"},{name:"total",type:"number"},{name:"discount",type:"number"},{name:"ppn",type:"number"},{name:"pph",type:"number"},{name:"finalTotal",type:"number"},{name:"transactionCurrencyCode",type:"string",isOptional:!0},{name:"exchangeRate",type:"number",isOptional:!0},{name:"exchangeRateSource",type:"string",isOptional:!0},{name:"totalInBaseCurrency",type:"number",isOptional:!0},{name:"finalTotalInBaseCurrency",type:"number",isOptional:!0},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"sale_items",columns:[{name:"id",type:"string"},{name:"saleId",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:"shifts",columns:[{name:"id",type:"string"},{name:"cashierId",type:"string",isIndexed:!0},{name:"cashierName",type:"string"},{name:"openedAt",type:"string",isIndexed:!0,notes:"ISO"},{name:"closedAt",type:"string",isOptional:!0,notes:"null = masih buka"},{name:"startingCash",type:"number",notes:"saldo awal"},{name:"endingCash",type:"number",isOptional:!0,notes:"saldo akhir"},{name:"systemCash",type:"number",isOptional:!0,notes:"dihitung otomatis saat tutup"},{name:"cashDifference",type:"number",isOptional:!0,notes:"endingCash - systemCash"},{name:"status",type:"string"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"tax_rates",columns:[{name:"id",type:"string"},{name:"key",type:"string",isIndexed:!0},{name:"rate",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"transactions",columns:[{name:"id",type:"string"},{name:"amount",type:"number",notes:"selalu positif"},{name:"method",type:"string",enum:["cash","card","voucher","bank_transfer"]},{name:"referenceType",type:"string",enum:["sale","purchase","sale_return","purchase_return","receivable_payment","payable_payment","cash_adjustment","expense"]},{name:"referenceId",type:"string"},{name:"direction",type:"string",enum:["in","out"]},{name:"metadata",type:"json",isOptional:!0},{name:"date",type:"string"},{name:"description",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"uoms",columns:[{name:"id",type:"string"},{name:"code",type:"string"},{name:"name",type:"string"},{name:"conversionFactor",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"users",columns:[{name:"id",type:"string"},{name:"username",type:"string"},{name:"role",type:"string"},{name:"email",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"suppliers",columns:[{name:"id",type:"string"},{name:"name",type:"string",isFullTextSearchable:!0},{name:"contactPerson",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"phone",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"email",type:"string",isOptional:!0,isFullTextSearchable:!0},{name:"address",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"purchase_orders",columns:[{name:"id",type:"string"},{name:"supplierId",type:"string"},{name:"userId",type:"string"},{name:"status",type:"string"},{name:"date",type:"string"},{name:"expectedDeliveryDate",type:"string",isOptional:!0},{name:"total",type:"number"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"purchase_order_items",columns:[{name:"id",type:"string"},{name:"purchaseOrderId",type:"string"},{name:"productId",type:"string"},{name:"quantity",type:"number"},{name:"uomId",type:"string",isOptional:!0},{name:"unitCost",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"purchases",columns:[{name:"id",type:"string"},{name:"supplierId",type:"string"},{name:"userId",type:"string"},{name:"purchaseOrderId",type:"string",isOptional:!0},{name:"date",type:"string"},{name:"total",type:"number"},{name:"transactionCurrencyCode",type:"string",isOptional:!0},{name:"exchangeRate",type:"number",isOptional:!0},{name:"exchangeRateSource",type:"string",isOptional:!0},{name:"totalInBaseCurrency",type:"number",isOptional:!0},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"purchase_items",columns:[{name:"id",type:"string"},{name:"purchaseId",type:"string"},{name:"purchaseOrderItemId",type:"string",isOptional:!0},{name:"productId",type:"string"},{name:"quantity",type:"number"},{name:"uomId",type:"string",isOptional:!0},{name:"unitCost",type:"number"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"inventory_lots",columns:[{name:"id",type:"string"},{name:"productId",type:"string"},{name:"purchaseId",type:"string"},{name:"purchaseItemId",type:"string"},{name:"purchaseOrderId",type:"string",isOptional:!0},{name:"purchaseOrderItemId",type:"string",isOptional:!0},{name:"lotNumber",type:"string",isOptional:!0,isIndexed:!0},{name:"serialNumber",type:"string",isOptional:!0,isIndexed:!0},{name:"expiryDate",type:"string",isOptional:!0,isIndexed:!0},{name:"quantity",type:"number"},{name:"remainingQuantity",type:"number"},{name:"status",type:"string",enum:["active","depleted","expired"]},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"inventory_logs",columns:[{name:"id",type:"string"},{name:"productId",type:"string"},{name:"change",type:"number"},{name:"reason",type:"string"},{name:"referenceType",type:"string",enum:["sale","purchase","sale_return","purchase_return","stock_adjustment","stock_opname"]},{name:"referenceId",type:"string"},{name:"userId",type:"string"},{name:"timestamp",type:"string",isIndexed:!0},{name:"note",type:"string",isOptional:!0}],skipMetadataColumns:!0},{name:"price_histories",columns:[{name:"id",type:"string"},{name:"productId",type:"string"},{name:"unitCost",type:"number"},{name:"supplierId",type:"string",isOptional:!0},{name:"effectiveDate",type:"string",isIndexed:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"stock_opnames",notes:`
|
|
12
12
|
referenceType untuk inventory_logs:
|
|
13
13
|
'reason': 'opname_adjustment'
|
|
14
14
|
'referenceType': 'stock_opname'
|
|
15
15
|
'referenceId': stockOpnameId
|
|
16
|
-
`,columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"date",type:"string"},{name:"status",type:"string",enum:["pending","completed","cancelled"]},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"stock_opname_items",columns:[{name:"id",type:"string"},{name:"stockOpnameId",type:"string"},{name:"productId",type:"string"},{name:"systemStock",type:"number",notes:"stok sistem (base UOM)"},{name:"physicalStock",type:"number",notes:"hasil hitung fisik (base UOM)"},{name:"difference",type:"number",notes:"physical - system"},{name:"note",type:"string",isOptional:!0},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"stock_adjustments",columns:[{name:"id",type:"string"},{name:"productId",type:"string"},{name:"change",type:"number"},{name:"reasonType",type:"string"},{name:"note",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"report_schedules",columns:[{name:"id",type:"string"},{name:"reportType",type:"string"},{name:"frequency",type:"string"},{name:"recipients",type:"string[]"},{name:"lastRunAt",type:"string",isOptional:!0},{name:"nextRunAt",type:"string"},{name:"isActive",type:"boolean"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"financial_settings",columns:[{name:"id",type:"string"},{name:"costingMethod",type:"string"},{name:"defaultExpenseAccount",type:"string",isOptional:!0},{name:"fiscalYearStart",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string"}]},{name:"expenses",columns:[{name:"id",type:"string"},{name:"userId",type:"string"},{name:"amount",type:"number"},{name:"category",type:"string"},{name:"description",type:"string",isOptional:!0},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"receivables",columns:[{name:"id",type:"string"},{name:"customerId",type:"string"},{name:"saleId",type:"string"},{name:"amount",type:"number"},{name:"dueDate",type:"string"},{name:"status",type:"string"},{name:"paidAmount",type:"number"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"payables",columns:[{name:"id",type:"string"},{name:"supplierId",type:"string"},{name:"purchaseId",type:"string"},{name:"amount",type:"number"},{name:"dueDate",type:"string"},{name:"status",type:"string"},{name:"paidAmount",type:"number"},{name:"date",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]},{name:"settlements",columns:[{name:"id",type:"string"},{name:"receivableId",type:"string",isOptional:!0},{name:"payableId",type:"string",isOptional:!0},{name:"amount",type:"number"},{name:"method",type:"string"},{name:"date",type:"string"},{name:"reference",type:"string",isOptional:!0},{name:"userId",type:"string"},{name:"version",type:"number"},{name:"lastModified",type:"string",isIndexed:!0},{name:"deleted",type:"boolean"}]}];for(let[
|
|
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 l;return[d.id,(l=d.name)!=null?l:"",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 gt.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=gt.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,m,f,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(p=>this.isWithinPeriod(p.date,e.from,e.to)),o=r.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),s=n.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),d=i.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),c={sales:a.map(p=>({id:p.id,date:p.date,total:p.total,discount:p.discount,ppn:p.ppn,pph:p.pph,finalTotal:p.finalTotal,status:p.status,customerId:p.customerId,userId:p.userId})),returns:o.map(p=>({id:p.id,date:p.date,type:p.type,refundAmount:p.refundAmount,actualRefund:p.actualRefund,status:p.status,saleId:p.saleId,purchaseId:p.purchaseId,userId:p.userId})),purchases:s.map(p=>({id:p.id,date:p.date,total:p.total,supplierId:p.supplierId,userId:p.userId,purchaseOrderId:p.purchaseOrderId})),payments:d.map(p=>({id:p.id,date:p.date,amount:p.amount,method:p.method,direction:p.receivableId?"in":"out",receivableId:p.receivableId,payableId:p.payableId,reference:p.reference,userId:p.userId}))},l={salesFinalTotal:c.sales.reduce((p,y)=>p+y.finalTotal,0),salesPpnTotal:c.sales.reduce((p,y)=>p+y.ppn,0),salesPphTotal:c.sales.reduce((p,y)=>p+y.pph,0),returnsActualRefundTotal:c.returns.reduce((p,y)=>p+y.actualRefund,0),purchasesTotal:c.purchases.reduce((p,y)=>p+y.total,0),paymentInTotal:c.payments.filter(p=>p.direction==="in").reduce((p,y)=>p+y.amount,0),paymentOutTotal:c.payments.filter(p=>p.direction==="out").reduce((p,y)=>p+y.amount,0)},u={contractVersion:"tex-v1",generatedAt:new Date().toISOString(),sourceVersion:`sync-protocol-v${1}`,period:{from:(h=e.from)!=null?h:null,to:(m=e.to)!=null?m:null,label:(f=e.periodLabel)!=null?f:null},currency:{baseCurrencyCode:(b=e.baseCurrencyCode)!=null?b:"IDR"},records:c,summary:l};return e.compatibilityTarget==="N-1"?{contractVersion:"tex-v0",generatedAt:u.generatedAt,sourceVersion:u.sourceVersion,period:u.period,currency:u.currency,records:{sales:u.records.sales.map(y=>({id:y.id,date:y.date,total:y.total,discount:y.discount,taxTotal:y.ppn+y.pph,finalTotal:y.finalTotal,status:y.status,customerId:y.customerId,userId:y.userId})),returns:u.records.returns,purchases:u.records.purchases,payments:u.records.payments.map(y=>({id:y.id,date:y.date,amount:y.amount,method:y.method,flow:y.direction==="in"?"receipt":"disbursement",receivableId:y.receivableId,payableId:y.payableId,reference:y.reference,userId:y.userId}))},summary:{salesFinalTotal:u.summary.salesFinalTotal,salesTaxTotal:u.summary.salesPpnTotal+u.summary.salesPphTotal,returnsActualRefundTotal:u.summary.returnsActualRefundTotal,purchasesTotal:u.summary.purchasesTotal,paymentInTotal:u.summary.paymentInTotal,paymentOutTotal:u.summary.paymentOutTotal}}:u}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(),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=Tr(d,this.context),l={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:l}}isWithinPeriod(e,t,r){let n=new Date(e).getTime();if(!Number.isFinite(n))return!1;if(t){let i=new Date(t).getTime();if(Number.isFinite(i)&&n<i)return!1}if(r){let i=new Date(r).getTime();if(Number.isFinite(i)&&n>i)return!1}return!0}};var kr=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(Qe,{filters:a});s.sort((h,m)=>{let f=h.customerGroupId===r?0:1,b=m.customerGroupId===r?0:1;return f!==b?f-b:m.tierLevel-h.tierLevel});let d=s.find(h=>t>=h.tierLevel),c=await i.get(se,e);if(!c)throw new Error(`Product with id ${e} not found`);let l=d?d.price:c.price,u=l;if(!d&&n){let h=c.baseUomId;if(h&&h!==n){let m=await this.uomService.getUom(h),f=await this.uomService.getUom(n);m&&f&&(u=this.uomService.convertUnitPrice(l,m,f))}}return this.context.config.pricingRoundingScope==="line"&&(u=this.roundValue(u)),this.context.logActivity("TieredPrice",{productId:e,quantity:t,uom:n,price:u}),u}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 f;let r=((f=this.context.domainServices)==null?void 0:f.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(p=>{if(p.code!==b)return!1;if(!p.expiresAt)return!0;let y=Date.parse(p.expiresAt);return Number.isNaN(y)?!1:y>=a})).filter(Boolean);if(!o.length)return 0;let s=this.roundValue(e.reduce((b,p)=>b+p.quantity*p.unitPrice,0)),d=this.context.config.allowPromotionStacking,c=this.context.config.promotionSelectionStrategy;if(!d){let b=c==="first_valid"?o[0]:o.map(y=>{let v=y.type==="percent"?s*y.value/100:y.value;return{promo:y,discount:Math.min(Math.max(0,v),s)}}).sort((y,v)=>v.discount-y.discount)[0].promo,p=b.type==="percent"?s*b.value/100:b.value;return this.roundValue(Math.min(Math.max(0,p),s))}let l=this.context.config.promotionStackingOrder,u=[...o];l==="percent_then_fixed"?u.sort((b,p)=>b.type===p.type?0:b.type==="percent"?-1:1):l==="fixed_then_percent"&&u.sort((b,p)=>b.type===p.type?0:b.type==="fixed"?-1:1);let h=s,m=0;for(let b of u){let p=b.type==="percent"?h*b.value/100:b.value,y=Math.min(Math.max(0,this.roundValue(p)),h);h-=y,m+=y}return this.roundValue(m)}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 p=1+i+a;s=p>0?o/p:o}s=this.normalizePrecision(this.roundValue(s));let d=this.normalizePrecision(this.roundValue(s*i)),c=this.normalizePrecision(this.roundValue(s*a)),l=r==="exclusive"?this.normalizePrecision(this.roundValue(s+d+c)):this.normalizePrecision(this.roundValue(o)),u=this.normalizePrecision(this.roundValue(Number((t==null?void 0:t.correctionAmount)||0))),h=this.normalizePrecision(this.roundValue(l+u)),m=String((t==null?void 0:t.correctionReason)||"").trim(),f=u!==0?`[TAX_CORRECTION=${u>=0?"+":""}${u}${m?`|reason=${m}`:""}]`:null;return{mode:r,inputAmount:o,taxBase:s,ppn:d,pph:c,totalBeforeCorrection:l,correctionAmount:u,totalAfterCorrection:h,correctionNote:f}}async calculateReturnTaxImpact(e,t){let r=(t==null?void 0:t.mode)==="inclusive"?"inclusive":"exclusive",n=await this.calculateTaxBreakdown(e,{mode:r});return{mode:r,returnAmount:Number(e||0),taxBaseImpact:this.normalizePrecision(this.roundValue(-n.taxBase)),ppnImpact:this.normalizePrecision(this.roundValue(-n.ppn)),pphImpact:this.normalizePrecision(this.roundValue(-n.pph)),grossImpact:this.normalizePrecision(this.roundValue(-n.totalBeforeCorrection))}}};var lo=Math.pow(10,8)*24*60*60*1e3,pp=-lo;var po=3600;var Si=po*24,mp=Si*7,mo=Si*365.2425,ho=mo/12,hp=ho*3,Jn=Symbol.for("constructDateFrom");function Fr(g,e){return typeof g=="function"?g(e):g&&typeof g=="object"&&Jn in g?g[Jn](e):g instanceof Date?new g.constructor(e):new Date(e)}function Rt(g,e){return Fr(e||g,g)}function Ai(g,e,t){let r=Rt(g,t==null?void 0:t.in);return isNaN(e)?Fr((t==null?void 0:t.in)||g,NaN):(e&&r.setDate(r.getDate()+e),r)}function Br(g,e){let t=Rt(g,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Mt(g,e){let t=Rt(g,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Ii(g,e,t){return Ai(g,-e,t)}var Mr=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(X,{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(X,{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(X,{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=Br(new Date).toISOString(),t=Mt(new Date).toISOString(),r=await this.dbAdapter.get(X,{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=Mt(e).toISOString(),a=await this.dbAdapter.get(X,{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(pe,{filters:{field:"status",operator:"=",value:"open"},limit:1}))[0]||null}async getTopSellingProducts(e=this.context.config.reportingTopSellingLimit){let t=Br(new Date).toISOString(),r=Mt(new Date).toISOString(),n=await this.dbAdapter.query(he,{mainAlias:"si",fields:{si:["productId","quantity","unitPrice"],p:["name"]},joins:[{table:ce,alias:"s",conditions:[{left:{type:"column",tableAlias:"si",field:"saleId"},operator:"=",right:{type:"column",tableAlias:"s",field:"id"}}]},{table:se,alias:"p",conditions:[{left:{type:"column",tableAlias:"si",field:"productId"},operator:"=",right:{type:"column",tableAlias:"p",field:"id"}}]}],filters:{and:[{field:"date",operator:">=",value:t,alias:"s"},{field:"date",operator:"<=",value:r,alias:"s"},{field:"deleted",operator:"=",value:!1,alias:"s"},{field:"deleted",operator:"=",value:!1,alias:"si"}]}}),i=new Map,a=new Set;for(let d of n){let c=d.si_productId||d.productId,l=Number(d.si_quantity||d.quantity||0),u=Number(d.si_unitPrice||d.unitPrice||0),h=d.p_name,m=l*u;if(!c)continue;a.add(c),i.has(c)||i.set(c,{productId:c,productName:h||"Unknown",quantity:0,totalSales:0});let f=i.get(c);f.quantity+=l,f.totalSales+=m}let o=Array.from(a).filter(d=>{let c=i.get(d);return!c||!c.productName||c.productName==="Unknown"});return o.length>0&&(await Promise.all(o.map(c=>this.dbAdapter.get(se,c)))).forEach((c,l)=>{if(c&&c.name){let u=o[l],h=i.get(u);h&&(h.productName=c.name)}}),Array.from(i.values()).sort((d,c)=>c.quantity-d.quantity).slice(0,e)}async getDailySalesLast7Days(){let e=[];for(let t=6;t>=0;t--){let r=Ii(new Date,t),n=Br(r).toISOString(),i=Mt(r).toISOString(),a=await this.dbAdapter.get(X,{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 u,h,m;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(pe,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r}]}}),this.dbAdapter.query(X,{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 f of n)a+=f.startingCash||0,f.status==="closed"&&(o+=f.endingCash||0,s+=f.systemCash||0);let d=Number(((u=i==null?void 0:i[0])==null?void 0:u.salesCash)||0),c=Number(((h=i==null?void 0:i[0])==null?void 0:h.returnsCash)||0),l=Number(((m=i==null?void 0:i[0])==null?void 0:m.expenses)||0);return{date:e,totalSalesCash:d,totalReturnsCash:c,totalExpenses:l,netCashMovement:d-c-l,startingCash:a,systemEndingCash:s,physicalEndingCash:o,cashDifference:o-s,shifts:n}}async getDailyReconciliationPack(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(X,{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(_e,{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 f;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,n=String(((f=this.context.config)==null?void 0:f.branchId)||"LOCAL"),i=await this.getDailyReconciliationPack(e),[a,o]=await Promise.all([this.dbAdapter.query(pe,{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(Pe,{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(qe,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:s},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],c=a.reduce((b,p)=>b+Math.abs(Number(p.cashDifference||0)),0),l=d.length,u=d.reduce((b,p)=>b+Math.abs(Number(p.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"),l>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:l,stockDiscrepancyAbsQty:u,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(X,{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(xe,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Pe,{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(qe,{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 l;return{stockOpnameId:String(c.stockOpnameId),productId:String(c.productId),difference:Number((l=c.difference)!=null?l: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(ge,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),n=new Map;for(let o of r){let s=String(o.supplierId||"");if(!s)continue;let d=Number(o.amount||0),c=Number(o.paidAmount||0),l=Math.max(0,d-c);if(l<=0)continue;let u=new Date(String(o.dueDate||"")),h=this.diffInDays(u,t),m=Number.isFinite(h)&&h>0,f=(a=n.get(s))!=null?a:{supplierId:s,openPayableCount:0,totalOutstanding:0,overduePayableCount:0,overdueOutstanding:0,maxDaysPastDue:0,avgDaysPastDue:0};f.openPayableCount+=1,f.totalOutstanding+=l,m&&(f.overduePayableCount+=1,f.overdueOutstanding+=l,f.maxDaysPastDue=Math.max(f.maxDaysPastDue,h)),n.set(s,f)}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),l=Number(s.paidAmount||0),u=Math.max(0,c-l);if(u<=0)continue;let h=new Date(String(s.dueDate||"")),m=this.diffInDays(h,t),f=Number.isFinite(m)&&m>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+=u,f&&(b.overdueReceivableCount+=1,b.overdueOutstanding+=u,b.maxDaysPastDue=Math.max(b.maxDaysPastDue,m)),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(Te,{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(Te,{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(v=>v.supplierId===d),l=(c==null?void 0:c.openPayableCount)||0,u=c&&c.totalOutstanding>0?c.overdueOutstanding/c.totalOutstanding:0,h=i.get(d)||0,m=a.get(d)||0,f=h>0?m/h:0,b=Math.round(100-(u*60+f*40)*100),p=Math.max(0,Math.min(100,b)),y=p>=85?"A":p>=70?"B":p>=50?"C":"D";s.push({supplierId:d,rating:p,grade:y,openPayableCount:l,overduePayableRatio:Number(u.toFixed(4)),openPurchaseOrderCount:h,overdueOrderCount:m,overdueOrderRatio:Number(f.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 Tt=class Tt{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(Tt.KEY);return e?JSON.parse(e):{}}async saveAllCarts(e){await this.storage.setItem(Tt.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(Tt.KEY)}};Tt.KEY="carts";var qr=Tt;var Lr=class{constructor(e){this.context=e;this.cartStore=new qr(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(l=>l.id===t);if(a===-1)throw new Error("Item not found in cart");let o=i.items[a],s=o.quantity*o.unitPrice,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 _t=null,kt=null,Nr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,ot.on("taxRateChanged",this.clearTaxRateCache)}async getPpnRate(){if(_t!==null)return _t;let e=await this.dbAdapter.query(Ee,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});return _t=e.length>0?e[0].rate:0,_t}async getPphRate(){if(kt!==null)return kt;let e=await this.dbAdapter.query(Ee,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});return kt=e.length>0?e[0].rate:0,kt}async setPpnRate(e){if(e<0)throw new Error("PPN rate must be non-negative");await this.dbAdapter.transaction(async t=>{let r=await t.query(Ee,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(Ee,n.id))),await t.create(Ee,{key:"ppn",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),ot.emit("taxRateChanged"),_t=e}async setPphRate(e){if(e<0)throw new Error("PPH rate must be non-negative");await this.dbAdapter.transaction(async t=>{let r=await t.query(Ee,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});await Promise.all(r.map(n=>t.delete(Ee,n.id))),await t.create(Ee,{key:"pph",rate:e,version:1,lastModified:new Date().toISOString(),deleted:!1})}),ot.emit("taxRateChanged"),kt=e}clearTaxRateCache(){_t=null,kt=null}};var Ur=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 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 Hr=class{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,d,c,l,u,h,m,f,b,p,y,v,x,S,A,_,T,q,L,w,M,U,F,$,H,G,B,P,O,R,I,Z,J,Y,W,Re,me,ue;this.context.domainServices=this,this.bom=(r=t.bomService)!=null?r:new Kt(this.context),this.category=(n=t.categoryService)!=null?n:new Gt(this.context),this.customer=(i=t.customerService)!=null?i:new Wt(this.context),this.customerGroup=(a=t.customerGroupService)!=null?a:new Zt(this.context),this.history=(o=t.historyService)!=null?o:new Yt(this.context),this.order=(s=t.orderService)!=null?s:new Xt(this.context),this.orderItem=(d=t.orderItemService)!=null?d:new Jt(this.context),this.priceTier=(c=t.priceTierService)!=null?c:new er(this.context),this.product=(l=t.productService)!=null?l:new tr(this.context),this.promotion=(u=t.promotionService)!=null?u:new rr(this.context),this.returnService=(h=t.returnService)!=null?h:new nr(this.context),this.returnItem=(m=t.returnItemService)!=null?m:new ir(this.context),this.role=(f=t.roleService)!=null?f:new ar(this.context),this.sale=(b=t.saleService)!=null?b:new or(this.context),this.saleItem=(p=t.saleItemService)!=null?p:new sr(this.context),this.shift=(y=t.shiftService)!=null?y:new cr(this.context),this.taxRate=(v=t.taxRateService)!=null?v:new dr(this.context),this.transaction=(x=t.transactionService)!=null?x:new ur(this.context),this.uom=(S=t.uomService)!=null?S:new lr(this.context),this.user=(A=t.userService)!=null?A:new pr(this.context),this.supplier=(_=t.supplierService)!=null?_:new mr(this.context),this.purchaseOrder=(T=t.purchaseOrderService)!=null?T:new hr(this.context),this.purchaseOrderItem=(q=t.purchaseOrderItemService)!=null?q:new fr(this.context),this.purchase=(L=t.purchaseService)!=null?L:new yr(this.context),this.purchaseItem=(w=t.purchaseItemService)!=null?w:new gr(this.context),this.inventoryLog=(M=t.inventoryLogService)!=null?M:new br(this.context),this.priceHistory=(U=t.priceHistoryService)!=null?U:new vr(this.context),this.stockOpname=(F=t.stockOpnameService)!=null?F:new xr(this.context),this.stockOpnameItem=($=t.stockOpnameItemService)!=null?$:new Sr(this.context),this.stockAdjustment=(H=t.stockAdjustmentService)!=null?H:new Ar(this.context),this.reportSchedule=(G=t.reportScheduleService)!=null?G:new Ir(this.context),this.financialSetting=(B=t.financialSettingService)!=null?B:new Dr(this.context),this.expense=(P=t.expenseService)!=null?P:new wr(this.context),this.receivable=(O=t.receivableService)!=null?O:new Cr(this.context),this.payable=(R=t.payableService)!=null?R:new Pr(this.context),this.settlement=(I=t.settlementService)!=null?I:new Er(this.context),this.inventory=(Z=t.inventoryService)!=null?Z:new Or(this.context),this.exportService=(J=t.exportService)!=null?J:new _r(this.context),this.pricing=(Y=t.pricingService)!=null?Y:new kr(this.context),this.reporting=(W=t.reportingService)!=null?W:new Mr(this.context),this.cart=(Re=t.cartService)!=null?Re:new Lr(this.context),this.tax=(me=t.taxService)!=null?me:new Nr(this.context),this.stockTransfer=(ue=t.stockTransferService)!=null?ue:new Ur(this.context)}};var Qr={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},ei="sync-store",$r=class{constructor(e){this.context=e;var t;this.emitter=Pt(),this.storage=(t=this.context.registry)==null?void 0:t.storageAdapter,this.state={...Qr},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 f,b,p,y,v;let t=(f=e==null?void 0:e.table)!=null?f: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=(p=e==null?void 0:e.id)!=null?p:n;if(typeof t!="string"||!t||typeof i!="string"||!i)return this.context.logError(new Error("Invalid sync change payload"),{raw:e}),null;let a=String((y=e==null?void 0:e.type)!=null?y:"").toUpperCase(),o=a==="CREATE"||a==="UPDATE"||a==="DELETE"?a:"UPDATE",s=Number(e==null?void 0:e.updated_at),d=Date.parse(String((v=r==null?void 0:r.lastModified)!=null?v:"")),c=Number.isFinite(s)&&s>0?s:Number.isFinite(d)&&d>0?d:Date.now(),l=Number(e==null?void 0:e.firstQueuedAt),u=Number(e==null?void 0:e.retryCount),h=Number(e==null?void 0:e.lastAttemptAt),m=e==null?void 0:e.lastErrorMessage;return{id:i,table:t,type:o,record:r,updated_at:c,firstQueuedAt:Number.isFinite(l)&&l>0?l:Date.now(),retryCount:Number.isFinite(u)&&u>=0?Math.floor(u):0,lastAttemptAt:Number.isFinite(h)&&h>0?h:null,lastErrorMessage:typeof m=="string"&&m.trim()?m.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={...Qr};try{this.storage.removeItem(ei)}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(ei,JSON.stringify(this.state))}catch(e){this.context.logError(e,{message:"Gagal persist sync-store"})}}async load(){try{let e=await this.storage.getItem(ei);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={...Qr.metrics,...a};return{...Qr,...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=Pt()}};var Vr=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,l=((o=this.context.session)==null?void 0:o.tenantId)||null,u=this.context.config.branchId||null,h=(r==null?void 0:r.tenantId)||null,m=(r==null?void 0:r.branchId)||null,f=h||l,b=m||u;if(c==="saas"&&(!f||!String(f).trim()))throw new Error("Tenant context is required for audit log entries in SaaS mode (missing tenantId)");if(c==="saas"&&l&&h&&String(h)!==String(l))throw new Error("Tenant isolation violation in audit log context (tenant override mismatch)");if(u&&m&&String(m)!==String(u))throw new Error("Branch isolation violation in audit log context (branch override mismatch)");let p={...r||{},tenantId:f||null,branchId:b||null,deploymentMode:c};await((d=(s=this.context.registry)==null?void 0:s.activitySink)==null?void 0:d.publish({activityId:C(),activityType:e,occurredAt:i,scopeRef:{tenantId:f||void 0,branchId:b||void 0,domain:"ofpos"},actor:{userId:t,source:"shared-core"},payload:p})),this.context.logInfo(a,p);let y=this.inferTableName(e,r),v=this.resolveRecordId(r),x={...p};await(n||this.dbAdapter).create(ie,{id:C(),userId:t,action:e,tableName:y,recordId:v,changes:x,timestamp:i})}catch(c){this.context.logError(c,{action:e,userId:t,extraContext:r})}}};var jr=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(Ce,r),i=this.denormalize(n);return this.recordCache.set(i.id,i),this.allCache=null,i}async update(e,t){if(!e)throw new Error("Missing role id for update");let r=await this.db.get(Ce,e);if(!r)throw new Error(`Role not found: ${e}`);let n=new Date().toISOString(),a={version:r.version+1,lastModified:n};t.name!==void 0&&(a.name=t.name),t.permissions!==void 0&&(a.permissions=JSON.stringify(t.permissions));let o=await this.db.update(Ce,e,a);if(!o)throw new Error(`Role not found: ${e}`);let s=this.denormalize(o);return this.recordCache.set(e,s),this.allCache=null,s}async delete(e){if(!e)throw new Error("Missing role id for delete");let t=await this.db.get(Ce,e);if(!t)return;if(!await this.db.update(Ce,e,{deleted:!0,version:t.version+1,lastModified:new Date().toISOString()}))throw new Error(`Role not found: ${e}`);this.recordCache.delete(e),this.allCache=null}async queryAll(){if(this.allCache)return this.allCache;let t=(await this.db.query(Ce,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}]})).map(this.denormalize);this.recordCache.clear();for(let r of t)this.recordCache.set(r.id,r);return this.allCache=t,t}async getById(e){if(!e)return null;let t=this.recordCache.get(e);if(t&&!t.deleted)return t;let r=await this.db.get(Ce,e);if(!r||r.deleted)return null;let n=this.denormalize(r);return this.recordCache.set(e,n),n}denormalize(e){return{...e,permissions:JSON.parse(e.permissions)}}validateData(e,t){for(let r of t)if(e[r]===void 0)throw new Error(`Field '${r}' is required`)}};var Pi=Ct(Et());var Ci={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"]}]},Gr=class{constructor(e){this.context=e;this.roleAdapter=new jr(e),this.syncStore=this.context.getSyncStore()}enqueue(e,t,r){var n;(n=this.syncStore)==null||n.enqueueChange({type:e,model:t,record:r})}async addRole(e,t){let r=await this.roleAdapter.create(e);return this.enqueue("create","roles",r),this.context.logActivity("AddRole",{id:r.id}),r}async updateRole(e,t,r){let n=await this.roleAdapter.update(e,t);return this.enqueue("update","roles",n),this.context.logActivity("UpdateRole",{id:e}),n}async deleteRole(e,t){return await this.roleAdapter.delete(e),this.enqueue("delete","roles",{id:e}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async getRoles(e){var a;let t=(a=this.context.registry)==null?void 0:a.dbAdapter,r={deleted:!1},n=e!=null&&e.filters?{and:[e.filters,r]}:r;return await t.query(Ce,{...e,filters:n})}async getRoleById(e){return this.roleAdapter.getById(e)}hasPermission(e,t){return Array.isArray(e.permissions)&&(e.permissions.includes("all")||e.permissions.includes(t))}async can(e,t){let r=await this.getRoleById(e.role);return this.hasPermission(r,t)}verifyLocalPin(e,t){if(!e.pinHash)return!1;try{return(0,Pi.default)(t).toString()===e.pinHash}catch{return!1}}getGranularPolicy(){return Ci}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,l,u,h,m;let t=C(),n=(e.policy||Ci).rules.find(f=>f.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 f={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:f.status,reasonCode:f.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}),f}if(!(n.approvalRequiredAboveThreshold&&i>n.thresholdAmount)){let f={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:f.status,reasonCode:f.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}),f}if(!e.approval){let f={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:f.status,reasonCode:f.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((u=this.context.session)==null?void 0:u.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),f}if(!this.isApprovalValid(e.approval,n.approverRoles.map(f=>this.normalizeRole(f)))){let f={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:f.status,reasonCode:f.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)}),f}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||((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)}),d}};var Rn=Ct(ni()),Tn=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=Rn.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=Rn.default.AES.decrypt(t.value,this.masterKey).toString(Rn.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 ka=3,_n=class{constructor(e){this.context=e;this.onlineAuthAttemptState=new Map;this.legacyAuthFallbackEnvKey="LEGACY_AUTH_EMERGENCY_FALLBACK";this.ofauthBridgeRequiredEnvKey="OFAUTH_BRIDGE_REQUIRED";var t,r;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.syncStore=this.context.getSyncStore(),this.platformAdapter=(r=this.context.registry)==null?void 0:r.platformAdapter}get ofauthBridge(){var e;return(e=this.context.integrationServices)==null?void 0:e.ofauthBridge}isLegacyEmergencyFallbackEnabled(){let e=this.platformAdapter.getEnvVar(this.legacyAuthFallbackEnvKey);return e==="1"||String(e).toLowerCase()==="true"}isOfauthBridgeRequired(){let e=this.platformAdapter.getEnvVar(this.ofauthBridgeRequiredEnvKey);return e==="1"||String(e).toLowerCase()==="true"}async addUser(e){var o;let t=this.dbAdapter,r=C(),n=new Date().toISOString(),i=await this.platformAdapter.hashPin(e.password),a={id:r,username:e.username,pinHash:i,role:e.role,version:1,lastModified:n,deleted:!1,failedAttempts:0,isLocked:!1};return await t.create(oe,a),(o=this.syncStore)==null||o.enqueueChange({type:"create",model:oe,record:a}),this.context.logActivity(`Added user ${r}`,{id:r}),a}async updateUser(e,t){var s;let r=this.dbAdapter,n=await r.get(oe,e);if(!n)throw new Error(`User not found: ${e}`);let i=new Date().toISOString(),a={username:t.username,role:t.role,version:n.version+1,lastModified:i};t.password&&(a.pinHash=await this.platformAdapter.hashPin(t.password)),await r.update(oe,t.id,a);let o={id:t.id,...a};return(s=this.syncStore)==null||s.enqueueChange({type:"update",model:oe,record:o}),this.context.logActivity(`Updated user ${t.id}`,{id:t.id}),o}async deleteUser(e){var r;return await this.dbAdapter.delete(oe,e),(r=this.syncStore)==null||r.enqueueChange({type:"delete",model:oe,record:{id:e}}),this.context.logActivity(`Deleted user ${e}`,{id:e}),{id:e,queued:!0}}async fetchUsers(e){let t=this.dbAdapter,r={deleted:!1},n=e!=null&&e.filters?{and:[e.filters,r]}:r;return await t.query(oe,{...e,filters:n})}async loginLocal(e,t){var l,u,h,m,f,b,p;let r=this.ofauthBridge;if(r){let y;try{let x=await r.login({username:e,secret:t,verifyMethod:"pin"});if(x.status==="authenticated")return this.activeSession=x.user,(h=(u=(l=this.context).getSessionStore)==null?void 0:u.call(l))==null||h.login(x.user),x.user;if(x.status==="rejected")return null;y=x.reasonCode}catch{y="OFAUTH_RUNTIME_FAILURE"}if(!(this.isOfauthBridgeRequired()?this.isLegacyEmergencyFallbackEnabled():y==="OFAUTH_BRIDGE_NOT_CONFIGURED"||this.isLegacyEmergencyFallbackEnabled()))return null}let n=this.dbAdapter,i=await n.query(oe,{filters:{username:e,deleted:!1}});if(!i||i.length===0)return null;let a=i[0],o=(m=a.failedAttempts)!=null?m:0;if(a.isLocked||o>=ka)return null;let s=new Date().toISOString();if(a.pinHash&&await this.platformAdapter.verifyPin(t,a.pinHash)){await n.update(oe,a.id,{failedAttempts:0,version:a.version+1,lastModified:s});let y=await n.get(oe,a.id);return this.activeSession=y,(p=(b=(f=this.context).getSessionStore)==null?void 0:b.call(f))==null||p.login(y),y}let d=o+1,c={failedAttempts:d,version:a.version+1,lastModified:s};return d>=ka&&(c.isLocked=!0),await n.update(oe,a.id,c),null}async loginOnline(e,t){var o,s,d,c,l,u,h;let r=this.ofauthBridge;if(r){let m;try{let b=await r.login({username:e,secret:t,verifyMethod:"password"});if(b.status==="authenticated")return this.activeSession=b.user,(d=(s=(o=this.context).getSessionStore)==null?void 0:s.call(o))==null||d.login(b.user),this.onlineAuthAttemptState.delete(String(e||"").trim().toLowerCase()),b.user;if(b.status==="rejected")return null;m=b.reasonCode}catch{m="OFAUTH_RUNTIME_FAILURE"}if(!(this.isOfauthBridgeRequired()?this.isLegacyEmergencyFallbackEnabled():m==="OFAUTH_BRIDGE_NOT_CONFIGURED"||this.isLegacyEmergencyFallbackEnabled()))return null}let n=String(e||"").trim().toLowerCase(),i=Date.now(),a=this.onlineAuthAttemptState.get(n);if(a!=null&&a.lockUntilMs&&a.lockUntilMs>i)return null;try{let f=(await this.context.integrationServices.api.login({username:e,password:t})).user;if(!f||!f.id)throw new Error("Authentication failed: invalid user data");let b=await this.platformAdapter.hashPin(t),p=Date.now(),y=new Date().toISOString(),v={...f,pinHash:b,failedAttempts:0,isLocked:!1};return await this.dbAdapter.get(oe,f.id)?await this.dbAdapter.update(oe,f.id,{username:v.username,role:v.role,email:v.email,pinHash:b,failedAttempts:0,isLocked:!1,version:f.version,lastModified:y,deleted:!1}):v=await this.dbAdapter.create(oe,{id:v.id,username:v.username,role:v.role,email:v.email,pinHash:b,failedAttempts:0,isLocked:!1,version:f.version,lastModified:y,deleted:!1}),this.activeSession=v,(u=(l=(c=this.context).getSessionStore)==null?void 0:l.call(c))==null||u.login(v),this.onlineAuthAttemptState.delete(n),v}catch(m){if(m.response&&m.response.status===401){let f=this.context.config.onlineAuthMaxFailedAttempts,b=this.context.config.onlineAuthLockoutSeconds*1e3,y=((h=this.onlineAuthAttemptState.get(n))!=null?h:{failedAttempts:0,lockUntilMs:null}).failedAttempts+1;return y>=f?this.onlineAuthAttemptState.set(n,{failedAttempts:y,lockUntilMs:i+b}):this.onlineAuthAttemptState.set(n,{failedAttempts:y,lockUntilMs:null}),null}throw m}}logoutLocal(){var t,r,n;let e=this.activeSession;e&&this.ofauthBridge&&this.ofauthBridge.logout({userId:e.id,reasonCode:"LOGOUT_LOCAL"}).catch(()=>{}),this.activeSession=void 0,(n=(r=(t=this.context).getSessionStore)==null?void 0:r.call(t))==null||n.logout()}getActiveSession(){return this.activeSession}};import{DefaultHttpAdapter as ii}from"ofcore";import{executeHttpRequestWithRetry as Fa,NoRetryHttpPolicy as ai,ExponentialBackoffHttpPolicy as mh}from"ofcore";var kn=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(!xi(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),l=this.context.checksum(c);if(!l)throw new Error("paymentSigningKey is required for sync push checksum");i["X-Data-Checksum"]=l}return o&&(i["X-Sync-Protocol-Version"]=String(this.context.config.syncProtocolVersion),i["X-Sync-Compatible-Versions"]=this.context.config.syncCompatibleServerVersions.join(",")),i}async requestData(e,t,r={}){let n=await this.buildHeaders(e,t,r.data,r.headers),i=this.context.config.apiUrl||"",a=t.startsWith("http")?t:`${i}${t}`,o=await Fa(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 fo={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"},Fn=class{constructor(e){this.context=e;this.lastAlertAtByCode=new Map;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.unsubscribeStore=this.syncStore.subscribe(n=>{n.queueLength>0&&(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.syncLoop().catch(i=>this.context.logError(i,{message:"Debounced sync gagal"}))},this.context.config.syncDebounceMs))}),this.onDataChanged=()=>{this.syncLoop().catch(n=>this.context.logError(n,{message:"Socket-triggered sync gagal"}))},ot.on("data_changed",this.onDataChanged),this.periodicTimer=setInterval(()=>{this.context.isOnline()&&this.syncLoop().catch(n=>this.context.logError(n,{message:"Periodic sync gagal"}))},this.context.config.syncIntervalMs)}normalizeOutgoingChange(e){var c,l,u,h,m;let t=(c=e==null?void 0:e.table)!=null?c:e==null?void 0:e.model,r=(l=e==null?void 0:e.record)!=null?l:{},n=(u=e==null?void 0:e.id)!=null?u: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((m=r==null?void 0:r.lastModified)!=null?m:"")),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 fo[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 l=this.getRemoteTimestamp(s),u=new Date(l).toISOString(),h=(i=s==null?void 0:s.record)!=null?i:{},m={...h,id:c,lastModified:(a=h==null?void 0:h.lastModified)!=null?a:u};try{let f=await r.get(d,c);if(!f)await r.create(d,m);else{let b=Date.parse(String((o=f==null?void 0:f.lastModified)!=null?o:""));if(!Number.isFinite(b)||l>b)await r.update(d,c,m);else if(l!==b)if(this.getConflictResolutionStrategy(d)==="server_wins")await r.update(d,c,m),this.context.logInfo(`Auto-resolve konflik master data ${d}:${c}`,t);else{let p={table:d,id:c,localLastModified:f==null?void 0:f.lastModified,remoteUpdatedAt:l,local:f,remote:s,reason:"local_newer"};n.addConflict(p),this.context.logInfo(`Konflik terdeteksi ${d}:${c}, dicatat untuk resolusi manual`,t)}}}catch(f){this.context.logError(f,{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 l=c==null?void 0:c.id;if(!l)continue;let u=await d.get("customers",l),h={...c,lastModified:(r=c==null?void 0:c.lastModified)!=null?r:new Date().toISOString()};u?await d.update("customers",l,h):await d.create("customers",h)}for(let c of(n=s==null?void 0:s.boms)!=null?n:[]){let l=c==null?void 0:c.id;if(!l)continue;let u=await d.get("boms",l),h={...c,lastModified:(i=c==null?void 0:c.lastModified)!=null?i:new Date().toISOString()};u?await d.update("boms",l,h):await d.create("boms",h)}for(let c of(a=s==null?void 0:s.uoms)!=null?a:[]){let l=c==null?void 0:c.id;if(!l)continue;let u=await d.get("uoms",l),h={...c,lastModified:(o=c==null?void 0:c.lastModified)!=null?o:new Date().toISOString()};u?await d.update("uoms",l,h):await d.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),ot.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,m)=>{let f=Number(m==null?void 0:m.firstQueuedAt);return!Number.isFinite(f)||f<=0?h:h+Math.max(0,n-f)},0)/r.length):0,a=0,o=0,s=0,d=0;for(let h of r)try{a+=1;let m=this.normalizeOutgoingChange(h);if(!m){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:[m]},t)),e.removeQueuedChange(m.id),o+=1}catch(m){this.context.logError(m,{message:"Gagal push change",...t}),s+=1,e.markRetryAttempt(h.id,m);let f=e.getState().queue.find(b=>b.id===h.id);f&&f.retryCount>=this.context.config.syncMaxRetries&&e.moveToDeadLetter(h.id,"max_retry_exceeded",m)}let c=[];try{let h=e.getState().lastSyncAt;c=await this.backoff(()=>this.apiService.pullChanges({since:h},t)),await this.applyChanges(c,t),d=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 l=Date.now(),u=e.getState().metrics;e.recordSyncMetrics({totalPushAttempted:u.totalPushAttempted+a,totalPushSucceeded:u.totalPushSucceeded+o,totalPushFailed:u.totalPushFailed+s,totalPullApplied:u.totalPullApplied+d,lastQueueLatencyMs:i,lastRunDurationMs:Math.max(0,l-n),lastRunAt:l}),this.evaluateOperationalAlerts({traceContext:t,pushAttempted:a,pushFailed:s,queueLatencyMs:i,deadLetterCount:e.getState().deadLetters.length})}catch(r){this.context.logError(r,{message:"Sync loop error",...t}),e.setError(r,t)}finally{e.finishSync(t),this.context.logInfo("Sync loop selesai",t)}}shutdown(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.periodicTimer&&clearInterval(this.periodicTimer),this.unsubscribeStore&&(this.unsubscribeStore(),this.unsubscribeStore=void 0),ot.off("data_changed",this.onDataChanged)}};var Bn=class g{constructor(e,t="http://localhost:3000"){this.context=e;this.url=t;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=g.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");this.initSocket().catch(o=>{var s;(s=this.syncStore)==null||s.setError(o instanceof Error?o:new Error(String(o)))})}static debounce(e,t=1e3){let r;return((...n)=>{r&&clearTimeout(r),r=setTimeout(()=>e(...n),t)})}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;(e=this.unsubscribeDataChanged)==null||e.call(this),(t=this.unsubscribeConnect)==null||t.call(this),(r=this.unsubscribeDisconnect)==null||r.call(this),(i=(n=this.socketAdapter)==null?void 0:n.disconnect)==null||i.call(n).catch(()=>{})}};var Mn=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})}}};import{DefaultPlatformAdapter as yo}from"ofcore";var qn=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 yo(this.context),this.storage=(n=t==null?void 0:t.storageAdapter)!=null?n:new yt(this.context)}async init(){let e=await this.storage.getItem("config");if(e)try{let t=JSON.parse(e);this._lowStockThreshold=t.lowStockThreshold?Number(t.lowStockThreshold):this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=t.paymentSigningKey?t.paymentSigningKey:this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=t.apiUrl?t.apiUrl:this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=t.branchId?t.branchId:this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=t.demoMode!=null?!!t.demoMode:this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let r=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE"),n=t.deploymentMode==="saas"||t.deploymentMode==="standalone"?t.deploymentMode:r==="saas"||r==="standalone"?r:null;this._deploymentMode=n,this._requireActiveShiftForCash=t.requireActiveShiftForCash!=null?!!t.requireActiveShiftForCash:null,this._maxCashAdjustmentAmount=t.maxCashAdjustmentAmount!=null?Number(t.maxCashAdjustmentAmount):null,this._requireShiftCloseApprovalOnDifference=t.requireShiftCloseApprovalOnDifference!=null?!!t.requireShiftCloseApprovalOnDifference:null,this._shiftCloseDifferenceApprovalThreshold=t.shiftCloseDifferenceApprovalThreshold!=null?Number(t.shiftCloseDifferenceApprovalThreshold):null,this._requireReasonForReturnOperations=t.requireReasonForReturnOperations!=null?!!t.requireReasonForReturnOperations:null,this._requireApprovalForReturnRefund=t.requireApprovalForReturnRefund!=null?!!t.requireApprovalForReturnRefund:null,this._requireApprovalForReturnCancel=t.requireApprovalForReturnCancel!=null?!!t.requireApprovalForReturnCancel:null,this._requireLotExpiryForPurchaseReceiving=t.requireLotExpiryForPurchaseReceiving!=null?!!t.requireLotExpiryForPurchaseReceiving:null,this._lotConsumptionPolicy=t.lotConsumptionPolicy==="FEFO"||t.lotConsumptionPolicy==="FIFO"?t.lotConsumptionPolicy:null,this._enableCustomerCreditPolicy=t.enableCustomerCreditPolicy!=null?!!t.enableCustomerCreditPolicy:null,this._customerCreditMaxOutstandingAmount=t.customerCreditMaxOutstandingAmount!=null?Number(t.customerCreditMaxOutstandingAmount):null,this._customerCreditBlockOnOverdue=t.customerCreditBlockOnOverdue!=null?!!t.customerCreditBlockOnOverdue:null,this._customerCreditOverdueGraceDays=t.customerCreditOverdueGraceDays!=null?Number(t.customerCreditOverdueGraceDays):null,this._customerCreditEscalationThresholdDays=t.customerCreditEscalationThresholdDays!=null?Number(t.customerCreditEscalationThresholdDays):null,this._enableReturnFraudGuard=t.enableReturnFraudGuard!=null?!!t.enableReturnFraudGuard:null,this._returnFraudWindowMinutes=t.returnFraudWindowMinutes!=null?Number(t.returnFraudWindowMinutes):null,this._returnFraudMaxEvents=t.returnFraudMaxEvents!=null?Number(t.returnFraudMaxEvents):null,this._returnFraudAction=t.returnFraudAction==="require_approval"||t.returnFraudAction==="block"?t.returnFraudAction:null,this._returnApprovalBypassRoles=Array.isArray(t.returnApprovalBypassRoles)?t.returnApprovalBypassRoles.map(i=>String(i)):null,this._returnApprovalApproverRoles=Array.isArray(t.returnApprovalApproverRoles)?t.returnApprovalApproverRoles.map(i=>String(i)):null,this._allowPromotionStacking=t.allowPromotionStacking!=null?!!t.allowPromotionStacking:null,this._promotionSelectionStrategy=t.promotionSelectionStrategy==="best_discount"||t.promotionSelectionStrategy==="first_valid"?t.promotionSelectionStrategy:null,this._promotionStackingOrder=t.promotionStackingOrder==="input_order"||t.promotionStackingOrder==="percent_then_fixed"||t.promotionStackingOrder==="fixed_then_percent"?t.promotionStackingOrder:null,this._pricingRoundingIncrement=t.pricingRoundingIncrement!=null?Number(t.pricingRoundingIncrement):null,this._pricingRoundingScope=t.pricingRoundingScope==="line"||t.pricingRoundingScope==="total"?t.pricingRoundingScope:null,this._enableSequentialDocumentNumbers=t.enableSequentialDocumentNumbers!=null?!!t.enableSequentialDocumentNumbers:null,this._syncProtocolVersion=Number.isInteger(t.syncProtocolVersion)&&Number(t.syncProtocolVersion)>=0?Number(t.syncProtocolVersion):null,this._syncCompatibleServerVersions=Array.isArray(t.syncCompatibleServerVersions)?t.syncCompatibleServerVersions.map(i=>Number(i)).filter(i=>Number.isInteger(i)&&i>=0):null,this._enforceSyncProtocolHandshake=t.enforceSyncProtocolHandshake!=null?!!t.enforceSyncProtocolHandshake:null,this._onlineAuthMaxFailedAttempts=t.onlineAuthMaxFailedAttempts!=null?Number(t.onlineAuthMaxFailedAttempts):null,this._onlineAuthLockoutSeconds=t.onlineAuthLockoutSeconds!=null?Number(t.onlineAuthLockoutSeconds):null,this._drRpoTargetMinutes=t.drRpoTargetMinutes!=null?Number(t.drRpoTargetMinutes):null,this._drRtoTargetMinutes=t.drRtoTargetMinutes!=null?Number(t.drRtoTargetMinutes):null,this._backupIntervalMinutes=t.backupIntervalMinutes!=null?Number(t.backupIntervalMinutes):null,this._backupRestoreDrillIntervalHours=t.backupRestoreDrillIntervalHours!=null?Number(t.backupRestoreDrillIntervalHours):null,this._opsAlertSyncFailureRateThresholdPercent=t.opsAlertSyncFailureRateThresholdPercent!=null?Number(t.opsAlertSyncFailureRateThresholdPercent):null,this._opsAlertQueueLatencyThresholdMs=t.opsAlertQueueLatencyThresholdMs!=null?Number(t.opsAlertQueueLatencyThresholdMs):null,this._opsAlertDeadLetterCountThreshold=t.opsAlertDeadLetterCountThreshold!=null?Number(t.opsAlertDeadLetterCountThreshold):null,this._opsAlertEscalationCooldownMinutes=t.opsAlertEscalationCooldownMinutes!=null?Number(t.opsAlertEscalationCooldownMinutes):null,this._auditLogRetentionDays=t.auditLogRetentionDays!=null?Number(t.auditLogRetentionDays):null,this._auditLogArchiveBeforePurge=t.auditLogArchiveBeforePurge!=null?!!t.auditLogArchiveBeforePurge:null,this._auditLogPurgeBatchSize=t.auditLogPurgeBatchSize!=null?Number(t.auditLogPurgeBatchSize):null,this._sessionIdleTimeoutMinutes=t.sessionIdleTimeoutMinutes!=null?Number(t.sessionIdleTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=t.sessionReauthTimeoutMinutes!=null?Number(t.sessionReauthTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=t.apiTimeoutMs!=null?Number(t.apiTimeoutMs):this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=t.syncIntervalMs!=null?Number(t.syncIntervalMs):this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=t.syncMaxRetries!=null?Number(t.syncMaxRetries):this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=t.syncBackoffDelayMs!=null?Number(t.syncBackoffDelayMs):this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=t.syncDebounceMs!=null?Number(t.syncDebounceMs):this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=t.reportingTopSellingLimit!=null?Number(t.reportingTopSellingLimit):this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=t.reportingLowStockLimit!=null?Number(t.reportingLowStockLimit):this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=t.apiBackupListLimit!=null?Number(t.apiBackupListLimit):this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=t.encryptionKey?t.encryptionKey:this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=t.encryptionPassphrase?t.encryptionPassphrase:this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}catch(t){this.context.logError(t,{message:"Gagal mengurai konfigurasi dari storage"})}else{this._lowStockThreshold=this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let t=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE");this._deploymentMode=t==="saas"||t==="standalone"?t:null,this._requireActiveShiftForCash=null,this._maxCashAdjustmentAmount=null,this._requireShiftCloseApprovalOnDifference=null,this._shiftCloseDifferenceApprovalThreshold=null,this._requireReasonForReturnOperations=null,this._requireApprovalForReturnRefund=null,this._requireApprovalForReturnCancel=null,this._requireLotExpiryForPurchaseReceiving=null,this._lotConsumptionPolicy=null,this._enableCustomerCreditPolicy=null,this._customerCreditMaxOutstandingAmount=null,this._customerCreditBlockOnOverdue=null,this._customerCreditOverdueGraceDays=null,this._customerCreditEscalationThresholdDays=null,this._enableReturnFraudGuard=null,this._returnFraudWindowMinutes=null,this._returnFraudMaxEvents=null,this._returnFraudAction=null,this._returnApprovalBypassRoles=null,this._returnApprovalApproverRoles=null,this._allowPromotionStacking=null,this._promotionSelectionStrategy=null,this._promotionStackingOrder=null,this._pricingRoundingIncrement=null,this._pricingRoundingScope=null,this._enableSequentialDocumentNumbers=null,this._syncProtocolVersion=null,this._syncCompatibleServerVersions=null,this._enforceSyncProtocolHandshake=null,this._onlineAuthMaxFailedAttempts=null,this._onlineAuthLockoutSeconds=null,this._drRpoTargetMinutes=null,this._drRtoTargetMinutes=null,this._backupIntervalMinutes=null,this._backupRestoreDrillIntervalHours=null,this._opsAlertSyncFailureRateThresholdPercent=null,this._opsAlertQueueLatencyThresholdMs=null,this._opsAlertDeadLetterCountThreshold=null,this._opsAlertEscalationCooldownMinutes=null,this._auditLogRetentionDays=null,this._auditLogArchiveBeforePurge=null,this._auditLogPurgeBatchSize=null,this._sessionIdleTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}}get apiUrl(){return this._apiUrl||"https://localhost:3000/api"}get lowStockThreshold(){return this._lowStockThreshold!=null?this._lowStockThreshold:10}get paymentSigningKey(){return this._paymentSigningKey||""}get demoMode(){return this._demoMode===!0}get branchId(){return this._branchId}get deploymentMode(){var e;return(e=this._deploymentMode)!=null?e:"standalone"}get requireActiveShiftForCash(){return this._requireActiveShiftForCash===!0}get maxCashAdjustmentAmount(){return this._maxCashAdjustmentAmount}get requireShiftCloseApprovalOnDifference(){return this._requireShiftCloseApprovalOnDifference===!0}get shiftCloseDifferenceApprovalThreshold(){return this._shiftCloseDifferenceApprovalThreshold}get requireReasonForReturnOperations(){return this._requireReasonForReturnOperations===!0}get requireApprovalForReturnRefund(){return this._requireApprovalForReturnRefund===!0}get requireApprovalForReturnCancel(){return this._requireApprovalForReturnCancel===!0}get requireLotExpiryForPurchaseReceiving(){return this._requireLotExpiryForPurchaseReceiving===!0}get lotConsumptionPolicy(){var e;return(e=this._lotConsumptionPolicy)!=null?e:"FEFO"}get enableCustomerCreditPolicy(){return this._enableCustomerCreditPolicy===!0}get customerCreditMaxOutstandingAmount(){return this._customerCreditMaxOutstandingAmount!=null&&this._customerCreditMaxOutstandingAmount>=0?this._customerCreditMaxOutstandingAmount:null}get customerCreditBlockOnOverdue(){return this._customerCreditBlockOnOverdue===!0}get customerCreditOverdueGraceDays(){return this._customerCreditOverdueGraceDays!=null&&this._customerCreditOverdueGraceDays>=0?this._customerCreditOverdueGraceDays:0}get customerCreditEscalationThresholdDays(){return this._customerCreditEscalationThresholdDays!=null&&this._customerCreditEscalationThresholdDays>0?this._customerCreditEscalationThresholdDays:14}get enableReturnFraudGuard(){return this._enableReturnFraudGuard===!0}get returnFraudWindowMinutes(){return this._returnFraudWindowMinutes!=null&&this._returnFraudWindowMinutes>0?this._returnFraudWindowMinutes:60}get returnFraudMaxEvents(){return this._returnFraudMaxEvents!=null&&this._returnFraudMaxEvents>0?this._returnFraudMaxEvents:3}get returnFraudAction(){var e;return(e=this._returnFraudAction)!=null?e:"require_approval"}get returnApprovalBypassRoles(){return this._returnApprovalBypassRoles}get returnApprovalApproverRoles(){return this._returnApprovalApproverRoles}get allowPromotionStacking(){return this._allowPromotionStacking===!0}get promotionSelectionStrategy(){var e;return(e=this._promotionSelectionStrategy)!=null?e:"best_discount"}get promotionStackingOrder(){var e;return(e=this._promotionStackingOrder)!=null?e:"input_order"}get pricingRoundingIncrement(){return this._pricingRoundingIncrement}get pricingRoundingScope(){var e;return(e=this._pricingRoundingScope)!=null?e:"total"}get enableSequentialDocumentNumbers(){return this._enableSequentialDocumentNumbers===!0}get syncProtocolVersion(){return this._syncProtocolVersion!=null&&Number.isInteger(this._syncProtocolVersion)&&this._syncProtocolVersion>=0?this._syncProtocolVersion:1}get syncCompatibleServerVersions(){let e=this._syncCompatibleServerVersions,t=[...Xn],r=Array.isArray(e)?e.filter(i=>Number.isInteger(i)&&i>=0):t,n=r.includes(this.syncProtocolVersion)?r:[this.syncProtocolVersion,...r];return Array.from(new Set(n))}get enforceSyncProtocolHandshake(){return this._enforceSyncProtocolHandshake===!0}get onlineAuthMaxFailedAttempts(){return this._onlineAuthMaxFailedAttempts!=null&&this._onlineAuthMaxFailedAttempts>0?this._onlineAuthMaxFailedAttempts:5}get onlineAuthLockoutSeconds(){return this._onlineAuthLockoutSeconds!=null&&this._onlineAuthLockoutSeconds>0?this._onlineAuthLockoutSeconds:60}get drRpoTargetMinutes(){return this._drRpoTargetMinutes!=null&&this._drRpoTargetMinutes>0?this._drRpoTargetMinutes:1440}get drRtoTargetMinutes(){return this._drRtoTargetMinutes!=null&&this._drRtoTargetMinutes>0?this._drRtoTargetMinutes:240}get backupIntervalMinutes(){return this._backupIntervalMinutes!=null&&this._backupIntervalMinutes>0?this._backupIntervalMinutes:360}get backupRestoreDrillIntervalHours(){return this._backupRestoreDrillIntervalHours!=null&&this._backupRestoreDrillIntervalHours>0?this._backupRestoreDrillIntervalHours:168}get opsAlertSyncFailureRateThresholdPercent(){return this._opsAlertSyncFailureRateThresholdPercent!=null&&this._opsAlertSyncFailureRateThresholdPercent>0?this._opsAlertSyncFailureRateThresholdPercent:30}get opsAlertQueueLatencyThresholdMs(){return this._opsAlertQueueLatencyThresholdMs!=null&&this._opsAlertQueueLatencyThresholdMs>0?this._opsAlertQueueLatencyThresholdMs:300*1e3}get opsAlertDeadLetterCountThreshold(){return this._opsAlertDeadLetterCountThreshold!=null&&this._opsAlertDeadLetterCountThreshold>0?this._opsAlertDeadLetterCountThreshold:10}get opsAlertEscalationCooldownMinutes(){return this._opsAlertEscalationCooldownMinutes!=null&&this._opsAlertEscalationCooldownMinutes>0?this._opsAlertEscalationCooldownMinutes:15}get auditLogRetentionDays(){return this._auditLogRetentionDays!=null&&this._auditLogRetentionDays>0?this._auditLogRetentionDays:365}get auditLogArchiveBeforePurge(){return this._auditLogArchiveBeforePurge!==!1}get auditLogPurgeBatchSize(){return this._auditLogPurgeBatchSize!=null&&this._auditLogPurgeBatchSize>0?this._auditLogPurgeBatchSize:500}get sessionIdleTimeoutMinutes(){return this._sessionIdleTimeoutMinutes!=null&&this._sessionIdleTimeoutMinutes>0?this._sessionIdleTimeoutMinutes:5}get sessionReauthTimeoutMinutes(){return this._sessionReauthTimeoutMinutes!=null&&this._sessionReauthTimeoutMinutes>0?this._sessionReauthTimeoutMinutes:1}get apiTimeoutMs(){return this._apiTimeoutMs!=null&&this._apiTimeoutMs>0?this._apiTimeoutMs:5e3}get syncIntervalMs(){return this._syncIntervalMs!=null&&this._syncIntervalMs>0?this._syncIntervalMs:300*1e3}get syncMaxRetries(){return this._syncMaxRetries!=null&&this._syncMaxRetries>0?this._syncMaxRetries:5}get syncBackoffDelayMs(){return this._syncBackoffDelayMs!=null&&this._syncBackoffDelayMs>0?this._syncBackoffDelayMs:1e3}get syncDebounceMs(){return this._syncDebounceMs!=null&&this._syncDebounceMs>0?this._syncDebounceMs:2e3}get reportingTopSellingLimit(){return this._reportingTopSellingLimit!=null&&this._reportingTopSellingLimit>0?this._reportingTopSellingLimit:5}get reportingLowStockLimit(){return this._reportingLowStockLimit!=null&&this._reportingLowStockLimit>0?this._reportingLowStockLimit:10}get apiBackupListLimit(){return this._apiBackupListLimit!=null&&this._apiBackupListLimit>0?this._apiBackupListLimit:10}get encryptionKey(){return this._encryptionKey||"default_secret_key"}get encryptionPassphrase(){return this._encryptionPassphrase||"default_passphrase"}validateConfig(e){var Z,J,Y,W,Re,me,ue,be,we,ye,Ue,je,He,ze,mt,st,Be,Fe,Le,ht,It,ct,lt,pt,Dt,wt,dt,Xe,D,E,k,N,K,le,ve,ee,Q;let t=(Z=e.requireShiftCloseApprovalOnDifference)!=null?Z:this.requireShiftCloseApprovalOnDifference,r=(J=e.shiftCloseDifferenceApprovalThreshold)!=null?J:this.shiftCloseDifferenceApprovalThreshold,n=(Y=e.requireApprovalForReturnRefund)!=null?Y:this.requireApprovalForReturnRefund,i=(W=e.requireApprovalForReturnCancel)!=null?W:this.requireApprovalForReturnCancel,a=(Re=e.returnApprovalApproverRoles)!=null?Re:this.returnApprovalApproverRoles,o=(me=e.enableReturnFraudGuard)!=null?me:this.enableReturnFraudGuard,s=(ue=e.returnFraudWindowMinutes)!=null?ue:this.returnFraudWindowMinutes,d=(be=e.returnFraudMaxEvents)!=null?be:this.returnFraudMaxEvents,c=(we=e.syncProtocolVersion)!=null?we:this.syncProtocolVersion,l=(ye=e.syncCompatibleServerVersions)!=null?ye:this.syncCompatibleServerVersions,u=(Ue=e.enforceSyncProtocolHandshake)!=null?Ue: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=(je=e.enableCustomerCreditPolicy)!=null?je:this.enableCustomerCreditPolicy,m=(He=e.customerCreditMaxOutstandingAmount)!=null?He:this.customerCreditMaxOutstandingAmount,f=(ze=e.customerCreditOverdueGraceDays)!=null?ze:this.customerCreditOverdueGraceDays,b=(mt=e.customerCreditEscalationThresholdDays)!=null?mt:this.customerCreditEscalationThresholdDays;if(h){if(m!=null&&m<0)throw new Error("Invalid config: customerCreditMaxOutstandingAmount must be >= 0");if(!Number.isInteger(f)||f<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(l)||l.length===0)throw new Error("Invalid config: syncCompatibleServerVersions must contain at least one version");if(!l.every(V=>Number.isInteger(V)&&V>=0))throw new Error("Invalid config: syncCompatibleServerVersions must contain only non-negative integers");if(!l.includes(c))throw new Error("Invalid config: syncCompatibleServerVersions must include syncProtocolVersion");if(u===!0&&l.length===0)throw new Error("Invalid config: enforceSyncProtocolHandshake requires non-empty syncCompatibleServerVersions");let p=(st=e.onlineAuthMaxFailedAttempts)!=null?st:this.onlineAuthMaxFailedAttempts,y=(Be=e.onlineAuthLockoutSeconds)!=null?Be:this.onlineAuthLockoutSeconds,v=(Fe=e.drRpoTargetMinutes)!=null?Fe:this.drRpoTargetMinutes,x=(Le=e.drRtoTargetMinutes)!=null?Le:this.drRtoTargetMinutes,S=(ht=e.backupIntervalMinutes)!=null?ht:this.backupIntervalMinutes,A=(It=e.backupRestoreDrillIntervalHours)!=null?It:this.backupRestoreDrillIntervalHours,_=(ct=e.opsAlertSyncFailureRateThresholdPercent)!=null?ct:this.opsAlertSyncFailureRateThresholdPercent,T=(lt=e.opsAlertQueueLatencyThresholdMs)!=null?lt:this.opsAlertQueueLatencyThresholdMs,q=(pt=e.opsAlertDeadLetterCountThreshold)!=null?pt:this.opsAlertDeadLetterCountThreshold,L=(Dt=e.opsAlertEscalationCooldownMinutes)!=null?Dt:this.opsAlertEscalationCooldownMinutes,w=(wt=e.auditLogRetentionDays)!=null?wt:this.auditLogRetentionDays,M=(dt=e.auditLogPurgeBatchSize)!=null?dt:this.auditLogPurgeBatchSize;if(!Number.isInteger(p)||p<=0)throw new Error("Invalid config: onlineAuthMaxFailedAttempts must be a positive integer");if(!Number.isInteger(y)||y<=0)throw new Error("Invalid config: onlineAuthLockoutSeconds must be a positive integer");if(!Number.isInteger(v)||v<=0)throw new Error("Invalid config: drRpoTargetMinutes must be a positive integer");if(!Number.isInteger(x)||x<=0)throw new Error("Invalid config: drRtoTargetMinutes must be a positive integer");if(!Number.isInteger(S)||S<=0)throw new Error("Invalid config: backupIntervalMinutes must be a positive integer");if(!Number.isInteger(A)||A<=0)throw new Error("Invalid config: backupRestoreDrillIntervalHours must be a positive integer");if(S>v)throw new Error("Invalid config: backupIntervalMinutes must be <= drRpoTargetMinutes");if(!Number.isInteger(_)||_<=0||_>100)throw new Error("Invalid config: opsAlertSyncFailureRateThresholdPercent must be an integer in range 1..100");if(!Number.isInteger(T)||T<=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(L)||L<=0)throw new Error("Invalid config: opsAlertEscalationCooldownMinutes must be a positive integer");if(!Number.isInteger(w)||w<=0)throw new Error("Invalid config: auditLogRetentionDays must be a positive integer");if(!Number.isInteger(M)||M<=0)throw new Error("Invalid config: auditLogPurgeBatchSize must be a positive integer");let U=(Xe=e.sessionIdleTimeoutMinutes)!=null?Xe:this.sessionIdleTimeoutMinutes,F=(D=e.sessionReauthTimeoutMinutes)!=null?D:this.sessionReauthTimeoutMinutes;if(!Number.isInteger(U)||U<=0)throw new Error("Invalid config: sessionIdleTimeoutMinutes must be positive");if(!Number.isInteger(F)||F<=0)throw new Error("Invalid config: sessionReauthTimeoutMinutes must be positive");let $=(E=e.apiTimeoutMs)!=null?E:this.apiTimeoutMs,H=(k=e.syncIntervalMs)!=null?k:this.syncIntervalMs,G=(N=e.syncMaxRetries)!=null?N:this.syncMaxRetries,B=(K=e.syncBackoffDelayMs)!=null?K:this.syncBackoffDelayMs,P=(le=e.syncDebounceMs)!=null?le:this.syncDebounceMs,O=(ve=e.reportingTopSellingLimit)!=null?ve:this.reportingTopSellingLimit,R=(ee=e.reportingLowStockLimit)!=null?ee:this.reportingLowStockLimit,I=(Q=e.apiBackupListLimit)!=null?Q: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(G)||G<=0)throw new Error("Invalid config: syncMaxRetries must be positive");if(!Number.isInteger(B)||B<=0)throw new Error("Invalid config: syncBackoffDelayMs must be positive");if(!Number.isInteger(P)||P<=0)throw new Error("Invalid config: syncDebounceMs must be positive");if(!Number.isInteger(O)||O<=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(I)||I<=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 go="com.offlinepos.backup",Ln=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=go;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 Nn=class{async login(){return{status:"fallback",reasonCode:"OFAUTH_BRIDGE_NOT_CONFIGURED"}}async logout(){}};var Un=class g{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,d,c,l,u,h;this.context.integrationServices=this,this.activityLogger=(r=t.activityLogger)!=null?r:new Vr(this.context),this.config=(n=t.configService)!=null?n:new qn(this.context),this.authorization=(i=t.authorizationService)!=null?i:new Gr(this.context),this.encryption=(a=t.encryptionService)!=null?a:new Tn(this.context),this.api=(o=t.apiService)!=null?o:new kn(this.context),this.sync=(s=t.syncService)!=null?s:new Fn(this.context),this.socket=(d=t.socketService)!=null?d:new Bn(this.context),this.notification=(c=t.notificationService)!=null?c:new Mn(this.context),this.user=(l=t.userService)!=null?l:new _n(this.context),this.backupScheduler=(u=t.backupScheduler)!=null?u:new Ln(this.context,{setInterval(m,f){let b=setInterval(m,f);return{clear:()=>clearInterval(b)}}}),this.ofauthBridge=(h=t.ofauthBridge)!=null?h:new Nn}static async create(e,t={}){let r=new g(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 Ba=[{toVersion:1,up:async g=>{for(let e of gt)await g.addTable(e)}},{toVersion:2,up:async g=>{let e=gt.find(n=>n.name==="purchase_items"),t=gt.find(n=>n.name==="inventory_lots");if(!e||!t)throw new Error("Migration v2 requires purchase_items and inventory_lots schema definitions");let r=e.columns.find(n=>n.name==="purchaseOrderItemId");if(!r)throw new Error("Migration v2 requires purchase_items.purchaseOrderItemId column");await g.addColumn("purchase_items",r),await g.addTable(t)}}];async function Ma(g,e){if(typeof g.getSchemaVersion!="function"||typeof g.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 g.getSchemaVersion();(t==null||t<0)&&(t=0);let r=[...Ba].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(g),await g.setSchemaVersion(i.toVersion),t=i.toVersion);e.logInfo("Database migration completed successfully")}catch(t){throw e.logError(t,{message:"Database migration failed"}),t}}var bo={isLoggedIn:!1,userId:null,user:null,lastLoginAt:null,tenantId:null},Hn=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=Pt(),this.state={...bo},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 qa="$2b$10$qdMM2dCcdCN2bRY4IZpUOOCEA0rXwYUr3akj5tKLyRltqXqCngFVi",oi="$2b$10$v1hStIAsm0bTu.1fqaJ1nuOi24w.W.fAdpasYKULQ6O4KGGvuYpVG",si="$2b$10$8uL4qUbRFUmNNO4hsm9mOOk7GQbRlAMjcYuvaXP.TX2ZHDUQpUzoO",vo="888df25ae35772424a560c7152a1de794440e0ea5cfee62828333a456a506e05",xo={boms:[],users:[{id:"user-1",username:"admin1",pinHash:qa,role:"admin",email:"alice@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-01T00:00:00.000Z",deleted:!1},{id:"user-2",username:"kasir1",pinHash:si,role:"cashier",email:"bob@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-01T00:00:00.000Z",deleted:!1},{id:"user-3",username:"manager1",pinHash:oi,role:"manager",email:"charlie@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-01T00:00:00.000Z",deleted:!1},{id:"user-4",username:"admin2",pinHash:qa,role:"admin",email:"admin2@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1},{id:"user-5",username:"manager_ops",pinHash:oi,role:"manager",email:"manager.ops@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1},{id:"user-6",username:"manager_fin",pinHash:oi,role:"manager",email:"manager.fin@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1},{id:"user-7",username:"kasir2",pinHash:si,role:"cashier",email:"kasir2@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1},{id:"user-8",username:"kasir3",pinHash:si,role:"cashier",email:"kasir3@example.com",failedAttempts:0,isLocked:!1,version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1},{id:"user-9",username:"locked_user",pinHash:vo,role:"cashier",email:"locked@example.com",failedAttempts:5,isLocked:!0,version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1}],roles:[{id:"admin",name:"Admin",permissions:["all"],version:1,lastModified:"2023-01-01T00:00:00.000Z",deleted:!1},{id:"manager",name:"Manager",permissions:["user:create","user:update","user:delete","user:view","role:create","role:update","role:delete","role:view","product:create","product:update","product:delete","product:view","category:create","category:update","category:delete","category:view","uom:create","uom:update","uom:delete","uom:view","customer_group:create","customer_group:update","customer_group:delete","customer_group:view","customer:create","customer:update","customer:delete","customer:view","sale:create","sale:update","sale:delete","sale:view","purchase:create","purchase:update","purchase:delete","purchase:view","purchase_return:create","purchase_return:update","purchase_return:delete","purchase_return:view","stock_opname:create","stock_opname:update","stock_opname:delete","stock_opname:view","stock_adjustment:create","stock_adjustment:update","stock_adjustment:delete","stock_adjustment:view","expense:create","expense:update","expense:delete","expense:view","financial_setting:create","financial_setting:update","financial_setting:delete","financial_setting:view","report_schedule:create","report_schedule:update","report_schedule:delete","report_schedule:view","settlement:create","settlement:update","settlement:delete","settlement:view","receivable:create","receivable:update","receivable:delete","receivable:view","payable:create","payable:update","payable:delete","payable:view","transaction:create","transaction:update","transaction:delete","transaction:view","history:create","history:update","history:delete","history:view"],version:1,lastModified:"2023-01-01T00:00:00.000Z",deleted:!1},{id:"cashier",name:"Cashier",permissions:["sale:create","sale:view"],version:1,lastModified:"2023-01-01T00:00:00.000Z",deleted:!1}],customer_groups:[{id:"cg-1",name:"Retail",version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1},{id:"cg-2",name:"Wholesale",version:1,lastModified:"2023-01-02T00:00:00.000Z",deleted:!1}],customers:[{id:"cust-1",name:"John Doe",phone:"081234567890",email:"john@example.com",groupId:"cg-1",version:1,lastModified:"2023-01-02T01:00:00.000Z",deleted:!1},{id:"cust-2",name:"Acme Corp",phone:"021987654",email:"contact@acme.com",groupId:"cg-2",version:1,lastModified:"2023-01-02T01:00:00.000Z",deleted:!1}],categories:[{id:"cat-1",name:"Beverages",parentId:null,version:1,lastModified:"2023-01-03T00:00:00.000Z",deleted:!1},{id:"cat-2",name:"Snacks",parentId:null,version:1,lastModified:"2023-01-03T00:00:00.000Z",deleted:!1}],uoms:[{id:"uom-1",code:"pcs",name:"Pieces",conversionFactor:1,version:1,lastModified:"2023-01-03T01:00:00.000Z",deleted:!1},{id:"uom-2",code:"box",name:"Box",conversionFactor:10,version:1,lastModified:"2023-01-03T01:00:00.000Z",deleted:!1}],products:[{id:"prod-1",name:"Coca Cola",description:"330ml can",barcode:"1234567890123",qrCode:"QR123",price:1.5,cost:1,categoryId:"cat-1",baseUomId:"uom-1",version:1,lastModified:"2023-01-04T00:00:00.000Z",deleted:!1},{id:"prod-2",name:"Potato Chips",description:"Salt flavor",barcode:"9876543210987",qrCode:"QR456",price:2,cost:1.2,categoryId:"cat-2",baseUomId:"uom-1",version:1,lastModified:"2023-01-04T00:00:00.000Z",deleted:!1},{id:"prod-3",name:"Indomie",description:"Instant noodles",barcode:"1234567890124",qrCode:"QR124",price:2,cost:1.2,categoryId:"cat-2",baseUomId:"uom-1",version:1,lastModified:"2023-01-04T00:00:00.000Z",deleted:!1},{id:"prod-4",name:"Teh Pucuk Harum",description:"Teh pucuk harum",barcode:"1234567890125",qrCode:"QR125",price:2,cost:1.2,categoryId:"cat-1",baseUomId:"uom-1",version:1,lastModified:"2023-01-04T00:00:00.000Z",deleted:!1},{id:"prod-5",name:"Kopi Kapal Api",description:"Kopi kapal api",barcode:"1234567890126",qrCode:"QR127",price:2,cost:1.2,categoryId:"cat-1",baseUomId:"uom-1",version:1,lastModified:"2023-01-04T00:00:00.000Z",deleted:!1},{id:"prod-6",name:"Susu Capil",description:"Susu capil",barcode:"1234567890128",qrCode:"QR128",price:2,cost:1.2,categoryId:"cat-1",baseUomId:"uom-1",version:1,lastModified:"2023-01-04T00:00:00.000Z",deleted:!1}],price_tiers:[{id:"pt-1",tierLevel:1,price:1.5,productId:"prod-1",uom:"pcs",customerGroupId:"cg-1",version:1,lastModified:"2023-01-04T01:00:00.000Z",deleted:!1},{id:"pt-2",tierLevel:2,price:1.3,productId:"prod-1",uom:"pcs",customerGroupId:"cg-2",version:1,lastModified:"2023-01-04T01:00:00.000Z",deleted:!1}],promotions:[{id:"promo-1",code:"DISC10",type:"percentage",value:10,name:"10% Off",description:"10% discount on beverages",targetType:"category",targetIds:["cat-1"],expiresAt:"2023-12-31T23:59:59.000Z",version:1,lastModified:"2023-01-05T00:00:00.000Z",deleted:!1}],suppliers:[{id:"sup-1",name:"Beverage Supplier",contactPerson:"Jane Roe",phone:"081122334455",email:"jane@supplier.com",address:"123 Supplier St.",version:1,lastModified:"2023-01-06T00:00:00.000Z",deleted:!1}],purchase_orders:[{id:"po-1",supplierId:"sup-1",userId:"user-1",status:"draft",date:"2023-01-07T00:00:00.000Z",expectedDeliveryDate:"2023-01-10T00:00:00.000Z",total:100,note:"",version:1,lastModified:"2023-01-07T00:00:00.000Z",deleted:!1}],purchase_order_items:[{id:"poi-1",purchaseOrderId:"po-1",productId:"prod-1",quantity:50,uomId:"uom-1",unitCost:1,version:1,lastModified:"2023-01-07T01:00:00.000Z",deleted:!1}],purchases:[{id:"purch-1",supplierId:"sup-1",userId:"user-1",purchaseOrderId:"po-1",date:"2023-01-08T00:00:00.000Z",total:100,note:"",version:1,lastModified:"2023-01-08T00:00:00.000Z",deleted:!1}],purchase_items:[{id:"pi-1",purchaseId:"purch-1",productId:"prod-1",quantity:50,uomId:"uom-1",unitCost:1,version:1,lastModified:"2023-01-08T01:00:00.000Z",deleted:!1}],orders:[{id:"order-1",userId:"user-2",customerId:"cust-1",status:"pending",saleId:null,date:"2023-01-08T00:00:00.000Z",total:20,ppn:2,pph:0,finalTotal:22,note:"",version:1,lastModified:"2023-01-08T00:00:00.000Z",deleted:!1}],order_items:[{id:"oi-1",orderId:"order-1",productId:"prod-2",quantity:10,uomId:"uom-1",unitPrice:2,version:1,lastModified:"2023-01-08T01:00:00.000Z",deleted:!1}],sales:[{id:"sale-1",userId:"user-2",customerId:"cust-1",sourceOrderId:"order-1",status:"completed",date:"2023-01-08T02:00:00.000Z",total:20,discount:20,ppn:2,pph:0,finalTotal:22,note:"",version:1,lastModified:"2023-01-08T02:00:00.000Z",deleted:!1}],sale_items:[{id:"si-1",saleId:"sale-1",productId:"prod-2",quantity:10,uomId:"uom-1",unitPrice:2,version:1,lastModified:"2023-01-08T02:30:00.000Z",deleted:!1}],tax_rates:[{id:"tax-1",key:"VAT",rate:10,version:1,lastModified:"2023-01-09T00:00:00.000Z",deleted:!1}],financial_settings:[{id:"fs-1",costingMethod:"FIFO",defaultExpenseAccount:"exp-1",fiscalYearStart:"2023-01-01",version:1,lastModified:"2023-01-09T01:00:00.000Z"}],stock_opnames:[{id:"so-1",userId:"user-1",date:"2023-01-09T02:00:00.000Z",status:"completed",note:"Initial stock count",version:1,lastModified:"2023-01-09T02:30:00.000Z",deleted:!1}],stock_opname_items:[{id:"soi-1",stockOpnameId:"so-1",productId:"prod-1",systemStock:100,physicalStock:98,difference:-2,note:"Shrinkage",version:1,lastModified:"2023-01-09T02:35:00.000Z",deleted:!1}],inventory_logs:[{id:"log-1",productId:"prod-1",change:100,reason:"stock opname",referenceType:"stock_adjustments",referenceId:"sa-1",userId:"user-1",timestamp:"2023-01-09T02:35:00.000Z",note:"Shrinkage"},{id:"log-2",productId:"prod-1",change:-2,reason:"stock opname",referenceType:"stock_opname",referenceId:"so-1",userId:"user-1",timestamp:"2023-01-09T02:35:00.000Z",note:"Shrinkage"},{id:"log-3",productId:"prod-2",change:100,reason:"stock opname",referenceType:"stock_adjustments",referenceId:"sa-2",userId:"user-1",timestamp:"2023-01-09T02:35:00.000Z",note:"Shrinkage"}],price_histories:[{id:"ph-1",productId:"prod-1",unitCost:1,supplierId:"sup-1",effectiveDate:"2023-01-04T00:00:00.000Z",version:1,lastModified:"2023-01-04T00:00:00.000Z",deleted:!1}],expenses:[{id:"exp-1",userId:"user-1",amount:50,category:"Utility",description:"Electric bill",date:"2023-01-10T00:00:00.000Z",version:1,lastModified:"2023-01-10T00:00:00.000Z",deleted:!1}],stock_adjustments:[{id:"sa-1",productId:"prod-1",change:100,reasonType:"transfer",note:"initial data",userId:"user-1",date:"2023-01-11T00:00:00.000Z",version:1,lastModified:"2023-01-11T00:00:00.000Z",deleted:!1},{id:"sa-2",productId:"prod-2",change:100,reasonType:"transfer",note:"initial data",userId:"user-1",date:"2023-01-11T00:00:00.000Z",version:1,lastModified:"2023-01-11T00:00:00.000Z",deleted:!1}],settlements:[{id:"settle-1",receivableId:"rec-1",payableId:null,amount:22,method:"cash",date:"2023-01-08T02:30:00.000Z",reference:"",userId:"user-2",version:1,lastModified:"2023-01-08T02:30:00.000Z",deleted:!1}],receivables:[{id:"rec-1",customerId:"cust-1",saleId:"sale-1",amount:22,dueDate:"2023-01-15T00:00:00.000Z",status:"unpaid",paidAmount:0,date:"2023-01-08T02:00:00.000Z",version:1,lastModified:"2023-01-08T02:00:00.000Z",deleted:!1}],payables:[{id:"pay-1",supplierId:"sup-1",purchaseId:"purch-1",amount:100,dueDate:"2023-01-20T00:00:00.000Z",status:"unpaid",paidAmount:0,date:"2023-01-08T00:00:00.000Z",version:1,lastModified:"2023-01-08T00:00:00.000Z",deleted:!1}],transactions:[{id:"trans-1",userId:"user-1",amount:22,method:"cash",referenceType:"sale",referenceId:"sale-1",direction:"in",metadata:{},date:"2023-01-08T02:05:00.000Z",description:"Sale payment",version:1,lastModified:"2023-01-08T02:05:00.000Z",deleted:!1}],histories:[{id:"hist-1",tableName:"products",recordId:"prod-1",action:"create",changes:{},userId:"user-1",timestamp:"2023-01-04T00:00:00.000Z"}],report_schedules:[{id:"rs-1",reportType:"sales",frequency:"daily",recipients:["admin@example.com"],lastRunAt:null,nextRunAt:"2023-01-12T00:00:00.000Z",isActive:!0,version:1,lastModified:"2023-01-10T00:00:00.000Z",deleted:!1}]},La=async(g,e)=>{e&&e.logInfo("Starting seed..."),g.transaction(async t=>{for(let[r,n]of Object.entries(xo))for(let i of n)await t.create(r,i)}),e&&e.logInfo("seed finish")};var Ft=class{constructor(){this.eventBus=ot;this.domainServiceOverrides={};this.integrationServiceOverrides={};this.pluginSpecs=[];this.runtimeStateStore=Io({phase:"idle",started:!1,startCount:0,stopCount:0,lastError:null,lastTransitionAt:new Date().toISOString()}),this.runtimeStore=Ao(this.runtimeStateStore),this.runtime=this.createRuntime()}getSyncStore(){return this.syncStore}getSessionStore(){return this.sessionStore}get session(){var e;return(e=this.sessionStore)==null?void 0:e.getState()}static builder(){return new ci}use(e,t,r=[]){if(this.pluginSpecs.some(i=>i.name===e))return this;let n={name:e,init:t,deps:r};return this.pluginSpecs.push(n),this.runtime.use(e,async()=>{await t(this)},r),this}async stop(){this.runtimeStateStore.setState({phase:"stopping",started:this.runtime.isStarted(),lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.stop(),this.runtimeStateStore.setState(e=>({...e,phase:"stopped",started:!1,stopCount:e.stopCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(e){throw this.runtimeStateStore.setState({phase:"error",started:this.runtime.isStarted(),lastError:e instanceof Error?e.message:String(e),lastTransitionAt:new Date().toISOString()}),e}}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.syncStore=void 0,this.sessionStore=void 0,this.pluginSpecs=[],this.domainServiceOverrides={},this.integrationServiceOverrides={},this.runtime=this.createRuntime()}async restart(){let e=[...this.pluginSpecs],t={...this.domainServiceOverrides},r={...this.integrationServiceOverrides};await this.reset(),this.domainServiceOverrides=t,this.integrationServiceOverrides=r,this.runtime=this.createRuntime();for(let n of e)this.use(n.name,n.init,n.deps);return this.start()}async init(e={runMigrations:!0}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.init({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}async start(e={}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.start({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}checksum(e){return Tr(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=So.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 Ma(t,r)},onInit:async()=>{this.syncStore||(this.syncStore=new $r(this)),this.sessionStore||(this.sessionStore=new Hn(this))},createDomainServices:()=>(this.domainServices||(this.domainServices=new Hr(this,this.domainServiceOverrides)),this.domainServices),createIntegrationServices:async()=>(this.integrationServices||(this.integrationServices=await Un.create(this,this.integrationServiceOverrides)),this.integrationServices),runSeed:async()=>{var t,r,n,i;await((t=this.registry)==null?void 0:t.storageAdapter.getItem("seed_data_loaded"))||(await La((r=this.registry)==null?void 0:r.dbAdapter,(n=this.registry)==null?void 0:n.loggerAdapter),await((i=this.registry)==null?void 0:i.storageAdapter.setItem("seed_data_loaded","true")))},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)}},ci=class{constructor(){this.core=new Ft;this.adapterOpts={}}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}build(e={runMigrations:!0}){return this.core.registry=new Qn(this.core,this.adapterOpts),this.core}};var Nt=class{constructor(){this.schema={version:0,tables:[]};this.data={};this.transactionDepth=0;this.snapshots=[]}async setUpWithSchema(e){this.schema={...e},this.data={},e.tables.forEach(t=>{this.data[t.name]=[]})}normalizeForComparison(e){if(e instanceof Date)return e.getTime();if(typeof e=="boolean")return e?1:0;if(typeof e=="string"||typeof e=="number"||e==null)return e;if(Array.isArray(e))return e.map(t=>this.normalizeForComparison(t));if(typeof e=="object"&&e!==null)try{return JSON.stringify(e)}catch{return String(e)}return e}evalValueExpr(e,t,r,n="t0"){if(r.type==="column"){let i=r.tableAlias||n,a=i===n?e:t[i]||{};return this.normalizeForComparison(a[r.field])}if(r.type==="literal")return this.normalizeForComparison(r.value);throw new Error(`Unsupported ValueExpression type: ${r.type}`)}buildFieldCondition(e,t){if("field"in e){let n={type:"column",tableAlias:e.alias||t,field:e.field},i={type:"literal",value:e.value};return{left:n,operator:e.operator||"=",right:i,...e.operator==="BETWEEN"?{}:{likeMode:e.likeMode}}}if("left"in e)return e;throw new Error("Invalid FieldCondition")}matchFilterExpression(e,t,r,n="t0"){if(r&&typeof r=="object"&&!Array.isArray(r)&&"and"in r)return r.and.every(i=>this.matchFilterExpression(e,t,i,n));if(r&&typeof r=="object"&&!Array.isArray(r)&&"or"in r)return r.or.some(i=>this.matchFilterExpression(e,t,i,n));if(r!==null&&typeof r=="object"&&!Array.isArray(r)){if("left"in r||"field"in r){let i=this.buildFieldCondition(r,n),a=this.evalValueExpr(e,t,i.left,n),o=this.evalValueExpr(e,t,i.right,n);if(i.operator==="IS NULL")return a==null;if(i.operator==="IS NOT NULL")return a!=null;if(i.operator==="IN"||i.operator==="NOT IN"){if(!Array.isArray(o))throw new Error("IN/NOT IN requires array on right side");let s=o.includes(a);return i.operator==="IN"?s:!s}switch(i.operator){case"=":return a===o;case"!=":return a!==o;case"<":return a<o;case"<=":return a<=o;case">":return a>o;case">=":return a>=o;case"LIKE":{if(typeof a!="string"||typeof o!="string")return!1;let s=o.replace(/%/g,".*").replace(/_/g,"."),d=i.likeMode;return new RegExp(`^${s}$`,d==="case-insensitive"?"i":"").test(a)}default:throw new Error(`Unsupported operator: ${i.operator}`)}}return Object.entries(r).every(([i,a])=>{let o=this.normalizeForComparison(e[i]),s=this.normalizeForComparison(a);return o===s})}throw new Error(`Invalid filter expression: ${JSON.stringify(r)}`)}simulateJoins(e,t,r){if(r.length===0)return t.map(i=>({record:i,joined:{}}));let n=[];for(let i of t){let a={},o=!0;for(let s of r){let d=s.table,c=this.data[d]||[],l=null;if(s.conditions.length===1){let u=s.conditions[0];if(u.operator==="="&&u.left.type==="column"&&u.right.type==="column"){let h=u.left.tableAlias||"t0",m=u.right.tableAlias;if(h==="t0"&&m===s.alias){let f=u.left.field,b=u.right.field,p=i[f];l=c.find(y=>this.normalizeForComparison(y[b])===this.normalizeForComparison(p))}}}if(!l&&(s.type==="inner"||s.type===void 0)){o=!1;break}a[s.alias]=l||null}o&&n.push({record:i,joined:a})}return n}extractField(e,t,r,n="t0"){if(typeof r=="string")return this.normalizeForComparison(e[r]);let i=r.tableAlias||n,a=i===n?e:t[i]||{};return this.normalizeForComparison(a[r.field])}extractAggregateField(e,t,r,n="t0"){if(typeof r=="string")return this.normalizeForComparison(e[r]);let i=r.tableAlias||n,a=i===n?e:t[i]||{};return this.normalizeForComparison(a[r.field])}async getSchemaVersion(){return this.schema.version}async setSchemaVersion(e){this.schema.version=e}async addTable(e){this.data[e.name]||(this.data[e.name]=[]),this.schema.tables.find(t=>t.name===e.name)||this.schema.tables.push(e)}async addColumn(e,t){}async get(e,t){var n;if(typeof t=="string"){let a=(this.data[e]||[]).find(o=>o.id===t);return a||null}return(n=(await this.query(e,{...t,limit:1}))[0])!=null?n:null}async query(e,t={}){var d;let n=[...this.data[e]||[]],i=this.simulateJoins(e,n,t.joins||[]);if(t.filters&&(i=i.filter(({record:c,joined:l})=>this.matchFilterExpression(c,l,t.filters,"t0"))),t.aggregates&&t.aggregates.length>0){let c={};for(let l of t.aggregates){let u=i;l.filter&&(u=u.filter(({record:b,joined:p})=>this.matchFilterExpression(b,p,l.filter,"t0")));let h=u.map(({record:b,joined:p})=>this.extractAggregateField(b,p,l.field,"t0")),m=h.map(b=>typeof b=="number"?b:Number(b)).filter(b=>Number.isFinite(b)),f=null;switch(l.function){case"COUNT":f=h.filter(b=>b!=null).length;break;case"SUM":f=m.reduce((b,p)=>b+p,0);break;case"AVG":f=m.length?m.reduce((b,p)=>b+p,0)/m.length:0;break;case"MIN":f=m.length?Math.min(...m):null;break;case"MAX":f=m.length?Math.max(...m):null;break;default:throw new Error(`Unsupported aggregate function: ${l.function}`)}c[l.as]=f}return[c]}let a=i.map(({record:c,joined:l})=>{if(t.fields){let u={};for(let[h,m]of Object.entries(t.fields)){let f=h==="t0"?c:l[h]||{};for(let b of m)u[`${h}_${b}`]=f[b]}return u}return c});t.sort&&t.sort.length>0&&a.sort((c,l)=>{for(let u of t.sort){let h=this.extractField(c,{},u.field,"t0"),m=this.extractField(l,{},u.field,"t0");if(h<m)return u.direction==="asc"?-1:1;if(h>m)return u.direction==="asc"?1:-1}return 0});let o=(d=t.offset)!=null?d:0,s=t.limit!=null?o+t.limit:void 0;return a.slice(o,s)}async create(e,t){this.data[e]||(this.data[e]=[]);let r={...t};return this.data[e].push(r),r}async update(e,t,r){let n=this.data[e]||[],i=n.findIndex(o=>o.id===t);if(i===-1)throw new Error(`Record not found: ${e} with id ${t}`);let a={...n[i],...r};return n[i]=a,a}async delete(e,t){let r=this.data[e]||[],n=r.findIndex(i=>i.id===t);n>=0&&r.splice(n,1)}async bulkCreate(e,t){this.data[e]||(this.data[e]=[]);let r=[...this.data[e]];try{let n=[];for(let i of t){let a={...i};this.data[e].push(a),n.push(a)}return n}catch(n){throw this.data[e]=r,n}}async bulkUpdate(e,t){let r=[...this.data[e]||[]];try{let n=[];for(let{id:i,updates:a}of t){let o=await this.update(e,i,a);n.push(o)}return n}catch(n){throw this.data[e]=r,n}}takeSnapshot(){let e={};for(let t in this.data)e[t]=[...this.data[t]];return e}async transaction(e){let t=this.transactionDepth===0;t&&this.snapshots.push(this.takeSnapshot()),this.transactionDepth++;try{let r=await e(this);return t&&this.snapshots.pop(),this.transactionDepth--,r}catch(r){if(t){let n=this.snapshots.pop();n&&(this.data=n)}throw this.transactionDepth--,r}}};var Ut=class{constructor(e){this.context=e}getDocumentPath(e){return e}async writeFile(e,t){throw new Error("exportAdapter.writeFile is not implemented for this platform")}async share(e){throw new Error("exportAdapter.share is not implemented for this platform")}};var Ht=class{constructor(e){this.context=e}init(e){}logInfo(e,t){console.log(e,t)}logError(e,t){console.error(e)}};import{NoopActivitySink as di,MemoryActivitySink as Ef}from"ofcore";import{NoopEncryptionAdapter as Na}from"ofcore";import{NoopChecksumAdapter as Ua}from"ofcore";var Qt=class{constructor(e){this.context=e}configure(e){}createChannel(e){}localNotification(e){}};var $n=Ct(ni()),Vn=class{constructor(e){this.context=e}encrypt(e,t){let r=this.resolveSecretKey(t);return $n.default.AES.encrypt(String(e!=null?e:""),r).toString()}decrypt(e,t){let r=this.resolveSecretKey(t);return $n.default.AES.decrypt(String(e!=null?e:""),r).toString($n.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 ja=Ct(Qa()),za=Ct(Et()),ui=Ct(Va()),Kn=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,ja.default)(t,i).toString(ui.default):""}return e.algorithm==="sha256"?(0,za.default)(t).toString(ui.default):""}verify(e,t){let r=String(this.compute(e)||"").trim().toLowerCase(),n=String(t||"").trim().toLowerCase();return r===n}};import{DefaultPlatformAdapter as Ka}from"ofcore";import{InMemorySocketAdapter as li}from"ofcore";var Qn=class{constructor(e,t={}){this.context=e;this.opts=t;this.context.registry=this,this.platformAdapter=this.resolveAdapter(t.platformAdapter,Ka),this.dbAdapter=this.resolveAdapter(t.dbAdapter,Nt),this.loggerAdapter=this.resolveAdapter(t.loggerAdapter,Ht),this.httpAdapter=this.resolveAdapter(t.httpAdapter,ii),this.httpRetryPolicy=this.resolveAdapter(t.httpRetryPolicy,ai),this.socketAdapter=this.resolveAdapter(t.socketAdapter,li),this.activitySink=this.resolveAdapter(t.activitySink,di),this.encryptionAdapter=this.resolveAdapter(t.encryptionAdapter,Vn),this.checksumAdapter=this.resolveAdapter(t.checksumAdapter,Kn),this.notificationAdapter=this.resolveAdapter(t.notificationAdapter,Qt),this.exportAdapter=this.resolveAdapter(t.exportAdapter,Ut),this.storageAdapter=this.resolveAdapter(t.storageAdapter,yt)}resolveAdapter(e,t){if(!e)return new t(this.context);if(typeof e=="object")return e;if(typeof e=="function"&&e.prototype===void 0)try{return e(this.context)}catch{}let r=e,i=(Reflect.getMetadata("design:paramtypes",r)||[]).map(a=>{if(a===Ft)return this.context;if(a===Ka)return this.platformAdapter;if(a===Nt)return this.dbAdapter;if(a===Ht)return this.loggerAdapter;if(a===ii)return this.httpAdapter;if(a===ai)return this.httpRetryPolicy;if(a===li)return this.socketAdapter;if(a===di)return this.activitySink;if(a===Na)return this.encryptionAdapter;if(a===Ua)return this.checksumAdapter;if(a===Qt)return this.notificationAdapter;if(a===Ut)return this.exportAdapter;if(a===yt)return this.storageAdapter});return new r(...i)}};function Ga(){return new Date().toISOString()}function Wa(g){return`${g}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Za=class{constructor(e){this.context=e;this.sessionByUserId=new Map}get db(){var e;return(e=this.context.registry)==null?void 0:e.dbAdapter}loadOfauthModule(){return Vt("ofauth-shared-core")}async ensureRuntime(){if(this.runtime)return this.runtime;let e=this.loadOfauthModule();this.ofauthTables=e.OFAUTH_TABLES;let t=e.OfauthCore.builder().withDbAdapter(()=>{var r;return(r=this.context.registry)==null?void 0:r.dbAdapter}).withPlatformAdapter(()=>{var r;return(r=this.context.registry)==null?void 0:r.platformAdapter}).withLoggerAdapter(()=>{var r;return(r=this.context.registry)==null?void 0:r.loggerAdapter}).withActivitySink(()=>{var r;return(r=this.context.registry)==null?void 0:r.activitySink}).build();return await t.start({runMigrations:!0,useSeedData:!1}),this.runtime=t,t}get tables(){if(!this.ofauthTables){let e=this.loadOfauthModule();this.ofauthTables=e.OFAUTH_TABLES}return this.ofauthTables}async findLocalUser(e){var r;return(r=(await this.db.query(oe,{filters:{username:e,deleted:!1},limit:1}))[0])!=null?r:null}async findIdentityByPrincipal(e){var r;return(r=(await this.db.query(this.tables.identities,{filters:{principal:e,deleted:!1},limit:1}))[0])!=null?r:null}async ensureIdentityFromUser(e,t){var a;let r=Ga(),n=e.pinHash||"",i=await this.findIdentityByPrincipal(e.username);return i?i.secretHash!==n||i.verifyMethod!==t||i.status!=="active"?this.db.update(this.tables.identities,i.id,{secretHash:n,verifyMethod:t,status:"active",version:i.version+1,lastModified:r}):i:this.db.create(this.tables.identities,{id:Wa("ofauth-identity"),principal:e.username,secretHash:n,verifyMethod:t,status:"active",failedAttempts:(a=e.failedAttempts)!=null?a:0,lockoutUntil:null,version:1,lastModified:r,deleted:!1})}async ensureAssignment(e,t){var s,d,c,l,u,h;let r=Ga(),n=((s=this.context.config)==null?void 0:s.deploymentMode)==="saas"&&(u=(l=(c=(d=this.context).getSessionStore)==null?void 0:c.call(d))==null?void 0:l.getState().tenantId)!=null?u:null,i=((h=this.context.config)==null?void 0:h.branchId)||null,o=(await this.db.query(this.tables.assignments,{filters:{identityId:e.id,deleted:!1},limit:1}))[0];return o?o.roleRef!==t.role||o.tenantId!==n||o.branchId!==i?this.db.update(this.tables.assignments,o.id,{roleRef:t.role,tenantId:n,branchId:i,version:o.version+1,lastModified:r}):o:this.db.create(this.tables.assignments,{id:Wa("ofauth-assignment"),identityId:e.id,roleRef:t.role,tenantId:n,branchId:i,scopeAttributes:{source:"ofpos-shared-core"},version:1,lastModified:r,deleted:!1})}async login(e){var n,i,a,o,s,d;let t=await this.findLocalUser(e.username);if(!t||!t.pinHash)return{status:"fallback",reasonCode:"LOCAL_USER_NOT_FOUND"};let r=await this.ensureRuntime();await this.ensureAssignment(await this.ensureIdentityFromUser(t,e.verifyMethod),t);try{let c=await r.domainServices.identityService.login({principal:e.username,secret:e.secret,verifyMethod:e.verifyMethod});this.sessionByUserId.set(t.id,c.sessionId);let l=await r.domainServices.sessionService.getActiveSession(c.sessionId),u=await r.domainServices.contextService.getActiveContext(c.sessionId),h=(a=(n=u==null?void 0:u.scopeRef)==null?void 0:n.tenantId)!=null?a:(i=l==null?void 0:l.activeScopeRef)==null?void 0:i.tenantId,m=(d=(o=u==null?void 0:u.scopeRef)==null?void 0:o.branchId)!=null?d:(s=l==null?void 0:l.activeScopeRef)==null?void 0:s.branchId;return{status:"authenticated",user:{...t,...h?{tenantId:h}:{},...m?{branchId:m}:{}}}}catch(c){return(c==null?void 0:c.code)==="AUTH_INVALID_CREDENTIAL"||(c==null?void 0:c.code)==="AUTH_STEP_UP_REQUIRED"?{status:"rejected",reasonCode:c.code}:{status:"fallback",reasonCode:"OFAUTH_RUNTIME_FAILURE"}}}async logout(e){if(!e.userId)return;let t=this.sessionByUserId.get(e.userId);if(!t)return;await(await this.ensureRuntime()).domainServices.identityService.logout(t),this.sessionByUserId.delete(e.userId)}};import{DefaultPlatformAdapter as gy}from"ofcore";import{isFailureEnvelope as xy}from"ofcore";import{isContractVersionCompatible as Iy}from"ofcore";var Ya=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,this.syncStore=e.getSyncStore()}async listProducts(){let e={field:"deleted",value:!1};return(await this.dbAdapter.query(se,{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(se,{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 Xa=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),[l,u]=await Promise.all([i(c),a(c)]);return{pricedItems:o,subTotal:s,discount:d,total:c,ppn:l,pph:u,totalWithTax:c+l+u,payableToSeller:c+l-u}}};export{Vr as ActivityLogger,Qn as AdapterRegistry,kn as ApiService,Gr as AuthorizationService,Ln as BackupScheduler,fo as CONFLICT_POLICY_MATRIX,Rr as CURRENT_SYNC_PROTOCOL_VERSION,Lr as CartService,qr as CartStore,Gt as CategoryService,qn as ConfigService,Ht as ConsoleLoggerAdapter,Zt as CustomerGroupService,Wt as CustomerService,Ci as DEFAULT_GRANULAR_AUTH_POLICY,Xn as DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS,Ut as DefaultExportAdapter,ii as DefaultHttpAdapter,gy as DefaultPlatformAdapter,Hr as DomainServices,Tn as EncryptionService,wr as ExpenseService,mh as ExponentialBackoffHttpPolicy,_r as ExportService,Dr as FinancialSettingService,Yt as HistoryService,Nt as InMemoryDbAdapter,li as InMemorySocketAdapter,Un as IntegrationServices,br as InventoryLogService,Or as InventoryService,Ef as MemoryActivitySink,yt as MemoryStorage,ai as NoRetryHttpPolicy,di as NoopActivitySink,Ua as NoopChecksumAdapter,Na as NoopEncryptionAdapter,Qt as NoopNotificationAdapter,Nn as NoopOfauthBridge,Mn as NotificationService,Za as OfauthCoreBridge,Xt as OrderService,Pr as PayableService,Ft as PosCore,vr as PriceHistoryService,er as PriceTierService,kr as PricingService,tr as ProductService,rr as PromotionService,hr as PurchaseOrderService,yr as PurchaseService,Cr as ReceivableService,Ir as ReportScheduleService,Mr as ReportingService,nr as ReturnService,jr as RoleAdapter,or as SaleService,Hn as SessionStore,Er as SettlementService,cr as ShiftService,Bn as SocketService,Ar as StockAdjustmentService,xr as StockOpnameService,mr as SupplierService,Fn as SyncService,$r as SyncStore,go as TASK_ID,Nr as TaxService,ur as TransactionService,Ya as UIProductService,Xa as UITransactionService,lr as UomService,_n as UserService,Ma as applyPendingMigrations,Me as bomTable,Je as categoryTable,Tr as computeChecksum,et as customerGroupTable,We as customerTable,ot as eventBus,Fa as executeHttpRequestWithRetry,at as expenseTable,Ve as financialSettingTable,Jl as getSyncProtocolContract,ie as historyTable,bo as initialSessionState,Qr as initialState,_e as inventoryLogTable,Iy as isContractVersionCompatible,xy as isFailureEnvelope,xi as isServerProtocolCompatible,gi as kitchenTicketItemTable,Yn as kitchenTicketTable,Ot as loyaltyAccountTable,ft as loyaltyLedgerTable,Ba as migrations,Ae as orderItemTable,ae as orderTable,ge as payableTable,Ye as priceHistoryTable,Qe as priceTierTable,se as productTable,tt as promotionTable,Ie as purchaseItemTable,$e as purchaseOrderItemTable,Te as purchaseOrderTable,De as purchaseTable,fe as receivableTable,it as reportScheduleTable,Oe as returnItemTable,xe as returnTable,Ce as roleTable,he as saleItemTable,ce as saleTable,gt as schemas,La as seed,xo as seedData,Ne as settlementTable,pe as shiftTable,nt as stockAdjustmentTable,qe as stockOpnameItemTable,Pe as stockOpnameTable,Ze as supplierTable,Ee as taxRateTable,X as transactionTable,rt as uomTable,oe as userTable};
|
|
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"}]}],oo=[{name:"branchId",type:"string",isOptional:!0,isIndexed:!0},{name:"tenantId",type:"string",isOptional:!0,isIndexed:!0}];function so(h){let e=[...h.columns];for(let t of oo)e.some(r=>r.name===t.name)||e.push({...t});return{...h,columns:e}}var At=ao.map(so),ym=Object.freeze(At.map(h=>h.name));for(let[h,e]of Object.entries(gi)){let t=At.find(r=>r.name===h);for(let[r,n]of Object.entries(e)){let i=t==null?void 0:t.columns.find(a=>a.name===r);i&&(i.relation=n)}}for(let[h,e]of Object.entries(yi)){let t=At.find(r=>r.name===h);t.polymorphic=e}var Or=1,Wn=[1,0];function bm(){return{currentVersion:1,compatibleServerVersions:[...Wn]}}function vi(h,e){return e.includes(h)}var Rr=(h,e)=>{var i;let t=e.config.paymentSigningKey;if(!t)return"";let r=(i=e.registry)==null?void 0:i.checksumAdapter;if(!r)throw new Error("ChecksumAdapter is not initialized in AdapterRegistry");let n=r.compute({algorithm:"hmac-sha256",payload:h,secret:t});if(n&&typeof n.then=="function")throw new Error("Shared-core checksum path requires synchronous ChecksumAdapter.compute");return String(n||"")};var _r=class{constructor(e){this.context=e;var t,r,n;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter,this.exportAdapter=(r=this.context.registry)==null?void 0:r.exportAdapter,this.inventoryService=(n=this.context.domainServices)==null?void 0:n.inventory}toCsv(e,t){let r=i=>`"${i.replace(/"/g,'""')}"`,n=[e.map(r).join(",")];return t.forEach(i=>n.push(i.map(r).join(","))),n.join(`
|
|
17
|
+
`)}async exportSalesReportCSV(e){let t=this.dbAdapter,r=e!=null&&e.date?{field:"date",value:e.date}:e!=null&&e.from&&(e!=null&&e.to)?{and:[{field:"date",operator:">=",value:e.from},{field:"date",operator:"<=",value:e.to}]}:void 0,n=await t.query("orders",{filters:r}),i=["Date","Total","PPN","PPH","FinalTotal"],a=n.map(u=>[u.date,u.total.toString(),u.ppn.toString(),u.pph.toString(),u.finalTotal.toString()]),o=this.toCsv(i,a),s=this.exportAdapter,c=s.getDocumentPath("sales_report.csv");await s.writeFile(c,o),await s.share(c)}async exportStockCSV(){let t=await this.dbAdapter.query("products"),r=["ID","Name","Stock"],n=await Promise.all(t.map(c=>this.inventoryService.getStock(c.id))),i=t.map((c,u)=>{var l;return[c.id,(l=c.name)!=null?l:"",n[u].toString()]}),a=this.toCsv(r,i),o=this.exportAdapter,s=o.getDocumentPath("stock_report.csv");await o.writeFile(s,a),await o.share(s)}async exportCustomersCSV(){let t=await this.dbAdapter.query("customers"),r=["ID","Name","Phone","Email"],n=t.map(s=>{var c,u;return[s.id,s.name,(c=s.phone)!=null?c:"",(u=s.email)!=null?u:""]}),i=this.toCsv(r,n),a=this.exportAdapter,o=a.getDocumentPath("customers_report.csv");await a.writeFile(o,i),await a.share(o)}async createLocalBackupSnapshot(){let e={};for(let t of At.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=At.map(n=>n.name);await this.dbAdapter.transaction(async n=>{for(let i of[...r].reverse()){let a=await n.query(i,{});for(let o of a)o!=null&&o.id&&await n.delete(i,o.id)}for(let i of r){let a=Array.isArray(t.tables[i])?t.tables[i]:[];for(let o of a)await n.create(i,o)}})}async createTaxReadyExportContract(e={}){var m,f,y,v;let t=await this.dbAdapter.query("sales",{filters:{deleted:!1}}),r=await this.dbAdapter.query("returns",{filters:{deleted:!1}}),n=await this.dbAdapter.query("purchases",{filters:{deleted:!1}}),i=await this.dbAdapter.query("settlements",{filters:{deleted:!1}}),a=t.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),o=r.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),s=n.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),c=i.filter(p=>this.isWithinPeriod(p.date,e.from,e.to)),u={sales:a.map(p=>({id:p.id,date:p.date,total:p.total,discount:p.discount,ppn:p.ppn,pph:p.pph,finalTotal:p.finalTotal,status:p.status,customerId:p.customerId,userId:p.userId})),returns:o.map(p=>({id:p.id,date:p.date,type:p.type,refundAmount:p.refundAmount,actualRefund:p.actualRefund,status:p.status,saleId:p.saleId,purchaseId:p.purchaseId,userId:p.userId})),purchases:s.map(p=>({id:p.id,date:p.date,total:p.total,supplierId:p.supplierId,userId:p.userId,purchaseOrderId:p.purchaseOrderId})),payments:c.map(p=>({id:p.id,date:p.date,amount:p.amount,method:p.method,direction:p.receivableId?"in":"out",receivableId:p.receivableId,payableId:p.payableId,reference:p.reference,userId:p.userId}))},l={salesFinalTotal:u.sales.reduce((p,g)=>p+g.finalTotal,0),salesPpnTotal:u.sales.reduce((p,g)=>p+g.ppn,0),salesPphTotal:u.sales.reduce((p,g)=>p+g.pph,0),returnsActualRefundTotal:u.returns.reduce((p,g)=>p+g.actualRefund,0),purchasesTotal:u.purchases.reduce((p,g)=>p+g.total,0),paymentInTotal:u.payments.filter(p=>p.direction==="in").reduce((p,g)=>p+g.amount,0),paymentOutTotal:u.payments.filter(p=>p.direction==="out").reduce((p,g)=>p+g.amount,0)},d={contractVersion:"tex-v1",generatedAt:new Date().toISOString(),sourceVersion:`sync-protocol-v${1}`,period:{from:(m=e.from)!=null?m:null,to:(f=e.to)!=null?f:null,label:(y=e.periodLabel)!=null?y:null},currency:{baseCurrencyCode:(v=e.baseCurrencyCode)!=null?v:"IDR"},records:u,summary:l};return e.compatibilityTarget==="N-1"?{contractVersion:"tex-v0",generatedAt:d.generatedAt,sourceVersion:d.sourceVersion,period:d.period,currency:d.currency,records:{sales:d.records.sales.map(g=>({id:g.id,date:g.date,total:g.total,discount:g.discount,taxTotal:g.ppn+g.pph,finalTotal:g.finalTotal,status:g.status,customerId:g.customerId,userId:g.userId})),returns:d.records.returns,purchases:d.records.purchases,payments:d.records.payments.map(g=>({id:g.id,date:g.date,amount:g.amount,method:g.method,flow:g.direction==="in"?"receipt":"disbursement",receivableId:g.receivableId,payableId:g.payableId,reference:g.reference,userId:g.userId}))},summary:{salesFinalTotal:d.summary.salesFinalTotal,salesTaxTotal:d.summary.salesPpnTotal+d.summary.salesPphTotal,returnsActualRefundTotal:d.summary.returnsActualRefundTotal,purchasesTotal:d.summary.purchasesTotal,paymentInTotal:d.summary.paymentInTotal,paymentOutTotal:d.summary.paymentOutTotal}}:d}async createTaxReadyExportCsvBundle(e={}){let t=await this.createTaxReadyExportContract(e),r=this.normalizeTaxReadyExportContract(t),n={};return n["tax_ready_manifest.json"]=JSON.stringify({contractVersion:t.contractVersion,generatedAt:t.generatedAt,sourceVersion:t.sourceVersion,period:t.period,currency:t.currency,summary:r.summary}),n["tax_ready_sales.csv"]=this.toCsv(["id","date","total","discount","ppn","pph","finalTotal","status","customerId","userId"],r.records.sales.map(i=>{var a;return[i.id,i.date,i.total.toString(),i.discount.toString(),i.ppn.toString(),i.pph.toString(),i.finalTotal.toString(),i.status,(a=i.customerId)!=null?a:"",i.userId]})),n["tax_ready_returns.csv"]=this.toCsv(["id","date","type","refundAmount","actualRefund","status","saleId","purchaseId","userId"],r.records.returns.map(i=>{var a,o;return[i.id,i.date,i.type,i.refundAmount.toString(),i.actualRefund.toString(),i.status,(a=i.saleId)!=null?a:"",(o=i.purchaseId)!=null?o:"",i.userId]})),n["tax_ready_purchases.csv"]=this.toCsv(["id","date","total","supplierId","userId","purchaseOrderId"],r.records.purchases.map(i=>{var a;return[i.id,i.date,i.total.toString(),i.supplierId,i.userId,(a=i.purchaseOrderId)!=null?a:""]})),n["tax_ready_payments.csv"]=this.toCsv(["id","date","amount","method","direction","receivableId","payableId","reference","userId"],r.records.payments.map(i=>{var a,o,s;return[i.id,i.date,i.amount.toString(),i.method,i.direction,(a=i.receivableId)!=null?a:"",(o=i.payableId)!=null?o:"",(s=i.reference)!=null?s:"",i.userId]})),n}normalizeTaxReadyExportContract(e){return e.contractVersion==="tex-v1"?e:{contractVersion:"tex-v1",generatedAt:e.generatedAt,sourceVersion:e.sourceVersion,period:e.period,currency:e.currency,records:{sales:e.records.sales.map(t=>({id:t.id,date:t.date,total:t.total,discount:t.discount,ppn:t.taxTotal,pph:0,finalTotal:t.finalTotal,status:t.status,customerId:t.customerId,userId:t.userId})),returns:e.records.returns,purchases:e.records.purchases,payments:e.records.payments.map(t=>({id:t.id,date:t.date,amount:t.amount,method:t.method,direction:t.flow==="receipt"?"in":"out",receivableId:t.receivableId,payableId:t.payableId,reference:t.reference,userId:t.userId}))},summary:{salesFinalTotal:e.summary.salesFinalTotal,salesPpnTotal:e.summary.salesTaxTotal,salesPphTotal:0,returnsActualRefundTotal:e.summary.returnsActualRefundTotal,purchasesTotal:e.summary.purchasesTotal,paymentInTotal:e.summary.paymentInTotal,paymentOutTotal:e.summary.paymentOutTotal}}}async createFiscalArchiveSnapshot(e){let t=String(e.actorId||"").trim(),r=String(e.reason||"").trim();if(!t)throw new Error("Fiscal archive policy: actorId is required");if(!r)throw new Error("Fiscal archive policy: reason is required");let n=await this.createTaxReadyExportContract(e),i=this.normalizeTaxReadyExportContract(n),a=await this.createTaxReadyExportCsvBundle(e),o=P(),s=new Date().toISOString(),c=JSON.stringify({archiveId:o,generatedAt:s,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,period:n.period,currency:n.currency,summary:i.summary,actorId:t,reason:r}),u=Rr(c,this.context),l={archiveId:o,generatedAt:s,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,period:n.period,currency:n.currency,summary:i.summary,checksum:u,actorId:t,reason:r};return await this.dbAdapter.create(ae,{id:P(),tableName:"fiscal_archives",recordId:o,action:"snapshot_created",changes:{period:n.period,contractVersion:n.contractVersion,sourceVersion:n.sourceVersion,fileNames:Object.keys(a),checksum:u,reason:r},userId:t,timestamp:s}),{archiveId:o,generatedAt:s,period:n.period,files:a,manifest:l}}isWithinPeriod(e,t,r){let n=new Date(e).getTime();if(!Number.isFinite(n))return!1;if(t){let i=new Date(t).getTime();if(Number.isFinite(i)&&n<i)return!1}if(r){let i=new Date(r).getTime();if(Number.isFinite(i)&&n>i)return!1}return!0}};var Tr=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,v=f.customerGroupId===r?0:1;return y!==v?y-v:f.tierLevel-m.tierLevel});let c=s.find(m=>t>=m.tierLevel),u=await i.get(de,e);if(!u)throw new Error(`Product with id ${e} not found`);let l=c?c.price:u.price,d=l;if(!c&&n){let m=u.baseUomId;if(m&&m!==n){let f=await this.uomService.getUom(m),y=await this.uomService.getUom(n);f&&y&&(d=this.uomService.convertUnitPrice(l,f,y))}}return this.context.config.pricingRoundingScope==="line"&&(d=this.roundValue(d)),this.context.logActivity("TieredPrice",{productId:e,quantity:t,uom:n,price:d}),d}async applyTieredPricing(e,t){return await Promise.all(e.map(async n=>({...n,unitPrice:await this.getTieredPrice(n.productId,n.quantity,t,n.uomId)})))}async calculatePromotionDiscount(e,t){var y;let r=((y=this.context.domainServices)==null?void 0:y.promotion)||this.promotionService,n=this.normalizeDiscountCodes(t);if(!n.length)return 0;let i=await(r==null?void 0:r.getPromotions());if(!(i!=null&&i.length))return 0;let a=Date.now(),o=n.map(v=>i.find(p=>{if(p.code!==v)return!1;if(!p.expiresAt)return!0;let g=Date.parse(p.expiresAt);return Number.isNaN(g)?!1:g>=a})).filter(Boolean);if(!o.length)return 0;let s=this.roundValue(e.reduce((v,p)=>v+p.quantity*p.unitPrice,0)),c=this.context.config.allowPromotionStacking,u=this.context.config.promotionSelectionStrategy;if(!c){let v=u==="first_valid"?o[0]:o.map(g=>{let x=g.type==="percent"?s*g.value/100:g.value;return{promo:g,discount:Math.min(Math.max(0,x),s)}}).sort((g,x)=>x.discount-g.discount)[0].promo,p=v.type==="percent"?s*v.value/100:v.value;return this.roundValue(Math.min(Math.max(0,p),s))}let l=this.context.config.promotionStackingOrder,d=[...o];l==="percent_then_fixed"?d.sort((v,p)=>v.type===p.type?0:v.type==="percent"?-1:1):l==="fixed_then_percent"&&d.sort((v,p)=>v.type===p.type?0:v.type==="fixed"?-1:1);let m=s,f=0;for(let v of d){let p=v.type==="percent"?m*v.value/100:v.value,g=Math.min(Math.max(0,this.roundValue(p)),m);m-=g,f+=g}return this.roundValue(f)}async calculateOrderTotal(e,t,r){let n=await this.applyTieredPricing(e,r),i=this.roundValue(n.reduce((s,c)=>s+c.quantity*c.unitPrice,0)),a=this.roundValue(await this.calculatePromotionDiscount(n,t)),o=this.roundValue(Math.max(0,i-a));return{items:n,subTotal:i,discount:a,total:o}}async calculatePPN(e){var r;let t=((r=this.context.domainServices)==null?void 0:r.tax)||this.taxService;return this.roundValue(e*await t.getPpnRate())}async calculatePPH(e){var r;let t=((r=this.context.domainServices)==null?void 0:r.tax)||this.taxService;return this.roundValue(e*await t.getPphRate())}async calculateTaxBreakdown(e,t){var v;let r=(t==null?void 0:t.mode)==="inclusive"?"inclusive":"exclusive",n=((v=this.context.domainServices)==null?void 0:v.tax)||this.taxService,i=await n.getPpnRate(),a=await n.getPphRate(),o=Number(e||0),s=o;if(r==="inclusive"){let p=1+i+a;s=p>0?o/p:o}s=this.normalizePrecision(this.roundValue(s));let c=this.normalizePrecision(this.roundValue(s*i)),u=this.normalizePrecision(this.roundValue(s*a)),l=r==="exclusive"?this.normalizePrecision(this.roundValue(s+c+u)):this.normalizePrecision(this.roundValue(o)),d=this.normalizePrecision(this.roundValue(Number((t==null?void 0:t.correctionAmount)||0))),m=this.normalizePrecision(this.roundValue(l+d)),f=String((t==null?void 0:t.correctionReason)||"").trim(),y=d!==0?`[TAX_CORRECTION=${d>=0?"+":""}${d}${f?`|reason=${f}`:""}]`:null;return{mode:r,inputAmount:o,taxBase:s,ppn:c,pph:u,totalBeforeCorrection:l,correctionAmount:d,totalAfterCorrection:m,correctionNote:y}}async calculateReturnTaxImpact(e,t){let r=(t==null?void 0:t.mode)==="inclusive"?"inclusive":"exclusive",n=await this.calculateTaxBreakdown(e,{mode:r});return{mode:r,returnAmount:Number(e||0),taxBaseImpact:this.normalizePrecision(this.roundValue(-n.taxBase)),ppnImpact:this.normalizePrecision(this.roundValue(-n.ppn)),pphImpact:this.normalizePrecision(this.roundValue(-n.pph)),grossImpact:this.normalizePrecision(this.roundValue(-n.totalBeforeCorrection))}}};var uo=Math.pow(10,8)*24*60*60*1e3,Tm=-uo;var co=3600;var bi=co*24,Bm=bi*7,lo=bi*365.2425,po=lo/12,km=po*3,Yn=Symbol.for("constructDateFrom");function Br(h,e){return typeof h=="function"?h(e):h&&typeof h=="object"&&Yn in h?h[Yn](e):h instanceof Date?new h.constructor(e):new Date(e)}function _t(h,e){return Br(e||h,h)}function xi(h,e,t){let r=_t(h,t==null?void 0:t.in);return isNaN(e)?Br((t==null?void 0:t.in)||h,NaN):(e&&r.setDate(r.getDate()+e),r)}function kr(h,e){let t=_t(h,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Qt(h,e){let t=_t(h,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Ai(h,e,t){return xi(h,-e,t)}var Fr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter}validateDateRange(e,t){if(!(e instanceof Date)||isNaN(e.getTime()))throw new TypeError("startDate bukan Date yang valid");if(!(t instanceof Date)||isNaN(t.getTime()))throw new TypeError("endDate bukan Date yang valid");if(e>t)throw new RangeError("startDate harus \u2264 endDate")}async getSalesAggregate(e,t){var s;this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=0,o=i.length;for(let c of i)a+=(s=c.amount)!=null?s:0;return{totalTransactions:o,totalRevenue:a}}async getTransactionsByHour(e,t){this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=new Map;return i.forEach(o=>{let c=new Date(o.date).getUTCHours().toString().padStart(2,"0");a.set(c,(a.get(c)||0)+1)}),Array.from(a.entries()).sort(([o],[s])=>o.localeCompare(s)).map(([o,s])=>({hour:o,count:s}))}async getRevenueByCustomer(e,t){this.validateDateRange(e,t);let r=e.toISOString(),n=t.toISOString(),i=await this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:r},{field:"date",operator:"<=",value:n},{field:"deleted",operator:"=",value:!1}]}}),a=new Map;return i.forEach(o=>{var s;if(o.referenceType){let c=o.referenceId,u=(s=o.amount)!=null?s:0;a.set(c,(a.get(c)||0)+u)}}),Array.from(a.entries()).map(([o,s])=>({customerId:o,revenue:s}))}async getTodaySales(){let e=kr(new Date).toISOString(),t=Qt(new Date).toISOString(),r=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:e},{field:"date",operator:"<=",value:t},{field:"deleted",operator:"=",value:!1}]}}]});return{total:Number((r==null?void 0:r.total)||0)}}async getSalesThisMonth(){let e=new Date,t=e.getFullYear(),r=(e.getMonth()+1).toString().padStart(2,"0"),n=`${t}-${r}-01T00:00:00.000Z`,i=Qt(e).toISOString(),a=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:n},{field:"date",operator:"<=",value:i},{field:"deleted",operator:"=",value:!1}]}}]});return{total:Number((a==null?void 0:a.total)||0)}}async getLowStockProducts(e=this.context.config.reportingLowStockLimit,t=this.context.config.lowStockThreshold){return this.context.domainServices.inventory.getLowStockProducts(t,e)}async getActiveShift(){return(await this.dbAdapter.query(me,{filters:{field:"status",operator:"=",value:"open"},limit:1}))[0]||null}async getTopSellingProducts(e=this.context.config.reportingTopSellingLimit){let t=kr(new Date).toISOString(),r=Qt(new Date).toISOString(),i=(await this.dbAdapter.query(ue,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["id"]}})).map(l=>String(l.t0_id||l.id||"")).filter(l=>l.length>0);if(!i.length)return[];let a=await this.dbAdapter.query(fe,{filters:{and:[{field:"saleId",operator:"IN",value:i},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["productId","quantity","unitPrice"]}}),o=new Map;for(let l of a){let d=String(l.t0_productId||l.productId||""),m=Number(l.t0_quantity||l.quantity||0),f=Number(l.t0_unitPrice||l.unitPrice||0);if(!d)continue;let y=o.get(d)||{productId:d,quantity:0,totalSales:0};y.quantity+=m,y.totalSales+=m*f,o.set(d,y)}if(!o.size)return[];let s=Array.from(o.keys()),c=await this.dbAdapter.query(de,{filters:{and:[{field:"id",operator:"IN",value:s},{field:"deleted",operator:"=",value:!1}]},fields:{t0:["id","name"]}}),u=new Map;for(let l of c){let d=String(l.t0_id||l.id||""),m=String(l.t0_name||l.name||"");d&&u.set(d,m||d)}return Array.from(o.values()).map(l=>({productId:l.productId,productName:u.get(l.productId)||l.productId,quantity:l.quantity,totalSales:l.totalSales})).sort((l,d)=>d.quantity-l.quantity).slice(0,e)}async getDailySalesLast7Days(){let e=[];for(let t=6;t>=0;t--){let r=Ai(new Date,t),n=kr(r).toISOString(),i=Qt(r).toISOString(),a=await this.dbAdapter.get(J,{aggregates:[{function:"SUM",field:"amount",as:"total",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"},{field:"date",operator:">=",value:n},{field:"date",operator:"<=",value:i},{field:"deleted",operator:"=",value:!1}]}}]});e.push({date:r.toISOString(),total:Number((a==null?void 0:a.total)||0)})}return e}async getDailyReport(e){var d,m,f;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(me,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r}]}}),this.dbAdapter.query(J,{aggregates:[{function:"SUM",field:"amount",as:"salesCash",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"returnsCash",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"expenses",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}}],filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}})]),a=0,o=0,s=0;for(let y of n)a+=y.startingCash||0,y.status==="closed"&&(o+=y.endingCash||0,s+=y.systemCash||0);let c=Number(((d=i==null?void 0:i[0])==null?void 0:d.salesCash)||0),u=Number(((m=i==null?void 0:i[0])==null?void 0:m.returnsCash)||0),l=Number(((f=i==null?void 0:i[0])==null?void 0:f.expenses)||0);return{date:e,totalSalesCash:c,totalReturnsCash:u,totalExpenses:l,netCashMovement:c-u-l,startingCash:a,systemEndingCash:s,physicalEndingCash:o,cashDifference:o-s,shifts:n}}async getDailyReconciliationPack(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i]=await Promise.all([this.dbAdapter.query(J,{aggregates:[{function:"SUM",field:"amount",as:"salesCashIn",filter:{and:[{field:"referenceType",operator:"IN",value:["sale","receivable_payment"]},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"salesReturnCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"sale_return"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"purchaseCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"purchase"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"purchaseReturnCashIn",filter:{and:[{field:"referenceType",operator:"=",value:"purchase_return"},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"expenseCashOut",filter:{and:[{field:"referenceType",operator:"=",value:"expense"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"cashAdjustmentIn",filter:{and:[{field:"referenceType",operator:"=",value:"cash_adjustment"},{field:"direction",operator:"=",value:"in"}]}},{function:"SUM",field:"amount",as:"cashAdjustmentOut",filter:{and:[{field:"referenceType",operator:"=",value:"cash_adjustment"},{field:"direction",operator:"=",value:"out"}]}},{function:"SUM",field:"amount",as:"totalCashIn",filter:{field:"direction",operator:"=",value:"in"}},{function:"SUM",field:"amount",as:"totalCashOut",filter:{field:"direction",operator:"=",value:"out"}}],filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(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),c=Number(a.totalCashOut||0),u=Math.abs(Number(o.inventoryAdjustmentOutQtyNegative||0));return{date:e,salesCashIn:Number(a.salesCashIn||0),salesReturnCashOut:Number(a.salesReturnCashOut||0),purchaseCashOut:Number(a.purchaseCashOut||0),purchaseReturnCashIn:Number(a.purchaseReturnCashIn||0),expenseCashOut:Number(a.expenseCashOut||0),cashAdjustmentIn:Number(a.cashAdjustmentIn||0),cashAdjustmentOut:Number(a.cashAdjustmentOut||0),totalCashIn:s,totalCashOut:c,netCashMovement:s-c,inventoryAdjustmentEntries:Number(o.inventoryAdjustmentEntries||0),inventoryAdjustmentInQty:Number(o.inventoryAdjustmentInQty||0),inventoryAdjustmentOutQty:u,inventoryAdjustmentNetQty:Number(o.inventoryAdjustmentNetQty||0)}}async getBranchPerformancePack(e){var y;let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,n=String(((y=this.context.config)==null?void 0:y.branchId)||"LOCAL"),i=await this.getDailyReconciliationPack(e),[a,o]=await Promise.all([this.dbAdapter.query(me,{filters:{and:[{field:"openedAt",operator:">=",value:t},{field:"openedAt",operator:"<=",value:r},{field:"status",operator:"=",value:"closed"},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Ce,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"status",operator:"=",value:"completed"},{field:"deleted",operator:"=",value:!1}]}})]),s=o.map(v=>v.id).filter(Boolean),c=s.length>0?await this.dbAdapter.query(Me,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:s},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],u=a.reduce((v,p)=>v+Math.abs(Number(p.cashDifference||0)),0),l=c.length,d=c.reduce((v,p)=>v+Math.abs(Number(p.difference||0)),0),m=[];return(i.salesCashIn>0?i.salesReturnCashOut/i.salesCashIn:0)>.1&&m.push("HIGH_REFUND_RATIO"),u>0&&m.push("SHIFT_CASH_DIFFERENCE"),l>0&&m.push("STOCK_DISCREPANCY"),{date:e,branchId:n,totalSalesCash:i.salesCashIn,totalReturnsCash:i.salesReturnCashOut,totalExpenses:i.expenseCashOut,totalCashIn:i.totalCashIn,totalCashOut:i.totalCashOut,netCashMovement:i.netCashMovement,shiftsClosed:a.length,totalCashDifferenceAbs:u,stockDiscrepancyItems:l,stockDiscrepancyAbsQty:d,anomalyIndicators:m}}async getDailyExceptionReport(e){let t=`${e}T00:00:00.000Z`,r=`${e}T23:59:59.999Z`,[n,i,a]=await Promise.all([this.dbAdapter.query(J,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"referenceType",operator:"IN",value:["sale_return_cancelled","purchase_return_cancelled"]},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Se,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"deleted",operator:"=",value:!1}]}}),this.dbAdapter.query(Ce,{filters:{and:[{field:"date",operator:">=",value:t},{field:"date",operator:"<=",value:r},{field:"status",operator:"=",value:"completed"},{field:"deleted",operator:"=",value:!1}]}})]),o=(a||[]).map(u=>u.id).filter(Boolean),s=o.length>0?await this.dbAdapter.query(Me,{filters:{and:[{field:"stockOpnameId",operator:"IN",value:o},{field:"difference",operator:"!=",value:0},{field:"deleted",operator:"=",value:!1}]}}):[],c=new Map((a||[]).map(u=>[String(u.id),String(u.date)]));return{date:e,voidEvents:(n||[]).map(u=>({transactionId:String(u.id),referenceType:String(u.referenceType),referenceId:String(u.referenceId),amount:Number(u.amount||0),date:String(u.date)})),refundExceptions:(i||[]).filter(u=>["partially_refunded","no_refund"].includes(String(u.status||""))||Number(u.actualRefund||0)<Number(u.refundAmount||0)).map(u=>({returnId:String(u.id),type:String(u.type),refundAmount:Number(u.refundAmount||0),actualRefund:Number(u.actualRefund||0),status:String(u.status),date:String(u.date)})),stockDiscrepancies:s.map(u=>{var l;return{stockOpnameId:String(u.stockOpnameId),productId:String(u.productId),difference:Number((l=u.difference)!=null?l:0),date:String(c.get(String(u.stockOpnameId))||"")}})}}async getSupplierPayableAging(e=new Date().toISOString()){var a;let t=new Date(e),r=await this.dbAdapter.query(ge,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),n=new Map;for(let o of r){let s=String(o.supplierId||"");if(!s)continue;let c=Number(o.amount||0),u=Number(o.paidAmount||0),l=Math.max(0,c-u);if(l<=0)continue;let d=new Date(String(o.dueDate||"")),m=this.diffInDays(d,t),f=Number.isFinite(m)&&m>0,y=(a=n.get(s))!=null?a:{supplierId:s,openPayableCount:0,totalOutstanding:0,overduePayableCount:0,overdueOutstanding:0,maxDaysPastDue:0,avgDaysPastDue:0};y.openPayableCount+=1,y.totalOutstanding+=l,f&&(y.overduePayableCount+=1,y.overdueOutstanding+=l,y.maxDaysPastDue=Math.max(y.maxDaysPastDue,m)),n.set(s,y)}return Array.from(n.values()).map(o=>{let s=o.overduePayableCount>0?Math.round(o.maxDaysPastDue+o.overdueOutstanding/Math.max(1,o.totalOutstanding)*o.maxDaysPastDue)/2:0;return{...o,avgDaysPastDue:s}}).sort((o,s)=>s.overdueOutstanding-o.overdueOutstanding)}async getCustomerReceivableAging(e=new Date().toISOString()){var o;let t=new Date(e),r=await this.dbAdapter.query(he,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"!=",value:"paid"}]}}),n=new Map;for(let s of r){let c=String(s.customerId||"");if(!c)continue;let u=Number(s.amount||0),l=Number(s.paidAmount||0),d=Math.max(0,u-l);if(d<=0)continue;let m=new Date(String(s.dueDate||"")),f=this.diffInDays(m,t),y=Number.isFinite(f)&&f>0,v=(o=n.get(c))!=null?o:{customerId:c,openReceivableCount:0,totalOutstanding:0,overdueReceivableCount:0,overdueOutstanding:0,maxDaysPastDue:0};v.openReceivableCount+=1,v.totalOutstanding+=d,y&&(v.overdueReceivableCount+=1,v.overdueOutstanding+=d,v.maxDaysPastDue=Math.max(v.maxDaysPastDue,f)),n.set(c,v)}let i=this.context.config.customerCreditEscalationThresholdDays;return Array.from(n.values()).map(s=>{let c="none";return s.maxDaysPastDue>=i*2?c="critical":s.maxDaysPastDue>=i&&(c="warning"),{...s,escalationLevel:c}}).sort((s,c)=>c.overdueOutstanding-s.overdueOutstanding)}async getOverduePurchaseOrderAlerts(e=new Date().toISOString()){let t=new Date(e),r=await this.dbAdapter.query(_e,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"NOT IN",value:["received","cancelled"]}]}}),n=[];for(let i of r){if(!i.expectedDeliveryDate)continue;let a=new Date(String(i.expectedDeliveryDate)),o=this.diffInDays(a,t);!Number.isFinite(o)||o<=0||n.push({purchaseOrderId:String(i.id),supplierId:String(i.supplierId),status:String(i.status),expectedDeliveryDate:String(i.expectedDeliveryDate),daysOverdue:o,total:Number(i.total||0)})}return n.sort((i,a)=>a.daysOverdue-i.daysOverdue)}async getSupplierPerformanceBaseline(e=new Date().toISOString()){let[t,r,n]=await Promise.all([this.getSupplierPayableAging(e),this.getOverduePurchaseOrderAlerts(e),this.dbAdapter.query(_e,{filters:{and:[{field:"deleted",operator:"=",value:!1},{field:"status",operator:"NOT IN",value:["received","cancelled"]}]}})]),i=new Map;for(let c of n){let u=String(c.supplierId||"");u&&i.set(u,(i.get(u)||0)+1)}let a=new Map;for(let c of r)a.set(c.supplierId,(a.get(c.supplierId)||0)+1);let o=new Set([...t.map(c=>c.supplierId),...Array.from(i.keys())]),s=[];for(let c of o){let u=t.find(x=>x.supplierId===c),l=(u==null?void 0:u.openPayableCount)||0,d=u&&u.totalOutstanding>0?u.overdueOutstanding/u.totalOutstanding:0,m=i.get(c)||0,f=a.get(c)||0,y=m>0?f/m:0,v=Math.round(100-(d*60+y*40)*100),p=Math.max(0,Math.min(100,v)),g=p>=85?"A":p>=70?"B":p>=50?"C":"D";s.push({supplierId:c,rating:p,grade:g,openPayableCount:l,overduePayableRatio:Number(d.toFixed(4)),openPurchaseOrderCount:m,overdueOrderCount:f,overdueOrderRatio:Number(y.toFixed(4))})}return s.sort((c,u)=>u.rating-c.rating)}diffInDays(e,t){let r=e.getTime(),n=t.getTime();return!Number.isFinite(r)||!Number.isFinite(n)?NaN:Math.floor((n-r)/(1440*60*1e3))}};var Tt=class Tt{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(Tt.KEY);return e?JSON.parse(e):{}}async saveAllCarts(e){await this.storage.setItem(Tt.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(Tt.KEY)}};Tt.KEY="carts";var Mr=Tt;var qr=class{constructor(e){this.context=e;this.cartStore=new Mr(this.context)}async createCart(e){var n;let t=new Date().toISOString(),r={id:P(),createdAt:t,lastModified:t,items:[],subtotal:0,totalDiscount:0,ppn:0,pph:0,finalTotal:0,userId:((n=this.context.session)==null?void 0:n.userId)||void 0,...e};return await this.cartStore.createCart(r),r}async updateCart(e){await this.cartStore.updateCart(e)}async deleteCart(e){await this.cartStore.deleteCart(e)}async getCart(e){return(await this.cartStore.getAllCarts())[e]}async getAllCarts(){return await this.cartStore.getAllCarts()}async clearAllCarts(){await this.cartStore.clearAllCarts()}async getActiveCarts(){let e=await this.cartStore.getAllCarts();return Object.values(e).filter(t=>!t.isLocked)}async getCartByCustomerId(e){let t=await this.cartStore.getAllCarts();return Object.values(t).filter(r=>r.customerId===e)}async getCartByTableNumber(e){let t=await this.cartStore.getAllCarts();return Object.values(t).filter(r=>r.tableNumber===e)}async addItemToCart(e,t){let r=await this.cartStore.getAllCarts();if(!r[e])throw new Error("Cart not found");let n=r[e];return n.items.push({...t}),n.subtotal+=t.quantity*t.unitPrice,n.finalTotal=n.subtotal+n.ppn+n.pph-n.totalDiscount,await this.cartStore.updateCart(n),n}async removeItemFromCart(e,t){let r=await this.cartStore.getAllCarts();if(!r[e])throw new Error("Cart not found");let n=r[e],i=n.items.findIndex(o=>o.id===t);if(i===-1)throw new Error("Item not found in cart");let a=n.items[i];return n.subtotal-=a.quantity*a.unitPrice,n.finalTotal=n.subtotal+n.ppn+n.pph-n.totalDiscount,n.items.splice(i,1),await this.cartStore.updateCart(n),n}async updateCartItem(e,t,r){let n=await this.cartStore.getAllCarts();if(!n[e])throw new Error("Cart not found");let i=n[e],a=i.items.findIndex(l=>l.id===t);if(a===-1)throw new Error("Item not found in cart");let o=i.items[a],s=o.quantity*o.unitPrice,c={...i.items[a],...r,id:t},u=c.quantity*c.unitPrice;return i.subtotal=i.subtotal-s+u,i.finalTotal=i.subtotal+i.ppn+i.pph-i.totalDiscount,i.items=[...i.items.slice(0,a),c,...i.items.slice(a+1)],await this.cartStore.updateCart(i),i}};var Bt=null,kt=null,Lr=class{constructor(e){this.context=e;var t;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,Le.on("taxRateChanged",this.clearTaxRateCache)}async getPpnRate(){if(Bt!==null)return Bt;let e=await this.dbAdapter.query(we,{filters:{and:[{field:"key",value:"ppn"},{field:"deleted",value:!1}]}});return Bt=e.length>0?e[0].rate:0,Bt}async getPphRate(){if(kt!==null)return kt;let e=await this.dbAdapter.query(we,{filters:{and:[{field:"key",value:"pph"},{field:"deleted",value:!1}]}});return kt=e.length>0?e[0].rate:0,kt}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})}),Le.emit("taxRateChanged"),Bt=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})}),Le.emit("taxRateChanged"),kt=e}clearTaxRateCache(){Bt=null,kt=null}};var Nr=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(ae,{id:P(),tableName:"stock_transfers",recordId:e,action:t,changes:r,userId:this.getActorId()||null,timestamp:i})}mergeState(e,t){let r=t.changes||{},n=e||{id:String(t.recordId),sourceBranchId:String(r.sourceBranchId||""),targetBranchId:String(r.targetBranchId||""),status:"requested",items:Array.isArray(r.items)?r.items:[],notes:null};return{...n,...r,id:String(t.recordId),status:String(r.status||n.status),items:Array.isArray(r.items)?r.items:n.items}}async getTransfer(e){let t=await this.dbAdapter.query(ae,{filters:{and:[{field:"tableName",operator:"=",value:"stock_transfers"},{field:"recordId",operator:"=",value:e}]},sort:[{field:"timestamp",direction:"asc"}]});if(!t.length)return null;let r=null;for(let n of t)r=this.mergeState(r,n);return r}async requestTransfer(e){let t=this.normalizeBranch(e.sourceBranchId),r=this.normalizeBranch(e.targetBranchId);if(t===r)throw new Error("sourceBranchId and targetBranchId must be different");let n=this.ensureItems(e.items),i=new Date().toISOString(),a=P(),o=this.getActorId()||null;await this.dbAdapter.transaction(async c=>{await this.appendEvent(a,"stock_transfer_requested",{sourceBranchId:t,targetBranchId:r,status:"requested",items:n,notes:e.notes||null,requestedBy:o,requestedAt:i},c)});let s=await this.getTransfer(a);if(!s)throw new Error("Failed to persist stock transfer request");return s}async approveTransfer(e,t){let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="requested")throw new Error("Stock transfer can only be approved from requested status");let n=new Date().toISOString(),i=this.getActorId()||null;await this.dbAdapter.transaction(async o=>{await this.appendEvent(e,"stock_transfer_approved",{status:"approved",approvedBy:i,approvedAt:n,notes:(t==null?void 0:t.notes)||r.notes||null},o)});let a=await this.getTransfer(e);if(!a)throw new Error("Stock transfer not found after approval");return a}async shipTransfer(e,t){var s;let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="approved")throw new Error("Stock transfer can only be shipped from approved status");let n=String(((s=this.context.config)==null?void 0:s.branchId)||"").trim();if(!n||n!==r.sourceBranchId)throw new Error("Ship operation is only allowed on source branch context");let i=this.getActorId()||null,a=new Date().toISOString();await this.dbAdapter.transaction(async c=>{for(let u of r.items)await this.context.domainServices.inventory.updateStock(u.productId,-Number(u.quantity),"stock_transfer_out","stock_transfer",e,c);await this.appendEvent(e,"stock_transfer_shipped",{status:"shipped",shippedBy:i,shippedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},c)});let o=await this.getTransfer(e);if(!o)throw new Error("Stock transfer not found after shipping");return o}async receiveTransfer(e,t){var s;let r=await this.getTransfer(e);if(!r)throw new Error("Stock transfer not found");if(r.status!=="shipped")throw new Error("Stock transfer can only be received from shipped status");let n=String(((s=this.context.config)==null?void 0:s.branchId)||"").trim();if(!n||n!==r.targetBranchId)throw new Error("Receive operation is only allowed on target branch context");let i=this.getActorId()||null,a=new Date().toISOString();await this.dbAdapter.transaction(async c=>{for(let u of r.items)await this.context.domainServices.inventory.updateStock(u.productId,Number(u.quantity),"stock_transfer_in","stock_transfer",e,c);await this.appendEvent(e,"stock_transfer_received",{status:"received",receivedBy:i,receivedAt:a,notes:(t==null?void 0:t.notes)||r.notes||null},c)});let o=await this.getTransfer(e);if(!o)throw new Error("Stock transfer not found after receiving");return o}};var Qr=class{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,c,u,l,d,m,f,y,v,p,g,x,b,A,I,F,w,q,M,E,L,Q,T,j,z,B,U,O,_,R,D,Z,te,X,Y,ye,se,qe;this.context.domainServices=this,this.bom=(r=t.bomService)!=null?r:new jt(this.context),this.category=(n=t.categoryService)!=null?n:new Kt(this.context),this.customer=(i=t.customerService)!=null?i:new Gt(this.context),this.customerGroup=(a=t.customerGroupService)!=null?a:new Wt(this.context),this.history=(o=t.historyService)!=null?o:new Yt(this.context),this.order=(s=t.orderService)!=null?s:new Xt(this.context),this.orderItem=(c=t.orderItemService)!=null?c:new Zt(this.context),this.priceTier=(u=t.priceTierService)!=null?u:new Jt(this.context),this.product=(l=t.productService)!=null?l:new er(this.context),this.promotion=(d=t.promotionService)!=null?d:new tr(this.context),this.returnService=(m=t.returnService)!=null?m:new rr(this.context),this.returnItem=(f=t.returnItemService)!=null?f:new nr(this.context),this.role=(y=t.roleService)!=null?y:new ir(this.context),this.sale=(v=t.saleService)!=null?v:new ar(this.context),this.saleItem=(p=t.saleItemService)!=null?p:new or(this.context),this.shift=(g=t.shiftService)!=null?g:new sr(this.context),this.taxRate=(x=t.taxRateService)!=null?x:new ur(this.context),this.transaction=(b=t.transactionService)!=null?b:new cr(this.context),this.uom=(A=t.uomService)!=null?A:new dr(this.context),this.user=(I=t.userService)!=null?I:new lr(this.context),this.supplier=(F=t.supplierService)!=null?F:new pr(this.context),this.purchaseOrder=(w=t.purchaseOrderService)!=null?w:new mr(this.context),this.purchaseOrderItem=(q=t.purchaseOrderItemService)!=null?q:new hr(this.context),this.purchase=(M=t.purchaseService)!=null?M:new fr(this.context),this.purchaseItem=(E=t.purchaseItemService)!=null?E:new gr(this.context),this.inventoryLog=(L=t.inventoryLogService)!=null?L:new yr(this.context),this.priceHistory=(Q=t.priceHistoryService)!=null?Q:new vr(this.context),this.stockOpname=(T=t.stockOpnameService)!=null?T:new br(this.context),this.stockOpnameItem=(j=t.stockOpnameItemService)!=null?j:new xr(this.context),this.stockAdjustment=(z=t.stockAdjustmentService)!=null?z:new Ar(this.context),this.reportSchedule=(B=t.reportScheduleService)!=null?B:new Sr(this.context),this.financialSetting=(U=t.financialSettingService)!=null?U:new Ir(this.context),this.expense=(O=t.expenseService)!=null?O:new Dr(this.context),this.receivable=(_=t.receivableService)!=null?_:new Pr(this.context),this.payable=(R=t.payableService)!=null?R:new Cr(this.context),this.settlement=(D=t.settlementService)!=null?D:new wr(this.context),this.inventory=(Z=t.inventoryService)!=null?Z:new Er(this.context),this.exportService=(te=t.exportService)!=null?te:new _r(this.context),this.pricing=(X=t.pricingService)!=null?X:new Tr(this.context),this.reporting=(Y=t.reportingService)!=null?Y:new Fr(this.context),this.cart=(ye=t.cartService)!=null?ye:new qr(this.context),this.tax=(se=t.taxService)!=null?se:new Lr(this.context),this.stockTransfer=(qe=t.stockTransferService)!=null?qe:new Nr(this.context)}};var Et={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},Xn="sync-store",Ur=class{constructor(e){this.context=e;var t;this.emitter=wt(),this.storage=(t=this.context.registry)==null?void 0:t.storageAdapter,this.state={...Et},this.load().then(r=>{r&&(this.state=r,this.emitter.emit("update",this.getState()))})}subscribe(e){return e(this.state),this.emitter.on("update",e),()=>this.emitter.off("update",e)}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.save(),this.emitter.emit("update",this.getState())}normalizeChange(e){var y,v,p,g,x;let t=(y=e==null?void 0:e.table)!=null?y:e==null?void 0:e.model,r=(v=e==null?void 0:e.record)!=null?v:{},n=typeof(r==null?void 0:r.id)=="string"?r.id:void 0,i=(p=e==null?void 0:e.id)!=null?p:n;if(typeof t!="string"||!t||typeof i!="string"||!i)return this.context.logError(new Error("Invalid sync change payload"),{raw:e}),null;let a=String((g=e==null?void 0:e.type)!=null?g:"").toUpperCase(),o=a==="CREATE"||a==="UPDATE"||a==="DELETE"?a:"UPDATE",s=Number(e==null?void 0:e.updated_at),c=Date.parse(String((x=r==null?void 0:r.lastModified)!=null?x:"")),u=Number.isFinite(s)&&s>0?s:Number.isFinite(c)&&c>0?c:Date.now(),l=Number(e==null?void 0:e.firstQueuedAt),d=Number(e==null?void 0:e.retryCount),m=Number(e==null?void 0:e.lastAttemptAt),f=e==null?void 0:e.lastErrorMessage;return{id:i,table:t,type:o,record:r,updated_at:u,firstQueuedAt:Number.isFinite(l)&&l>0?l:Date.now(),retryCount:Number.isFinite(d)&&d>=0?Math.floor(d):0,lastAttemptAt:Number.isFinite(m)&&m>0?m:null,lastErrorMessage:typeof f=="string"&&f.trim()?f.trim():null}}startSync(e){this.setState({status:"syncing",lastError:null}),this.context.logInfo("Sync started",e)}setError(e,t){this.setState({status:"error",lastError:e}),this.context.logError(e,{message:"Sync error",...t||{}})}clearError(){this.state.lastError&&(this.setState({lastError:null}),this.context.logInfo("Error cleared"))}enqueueChange(e){let t=this.normalizeChange(e);if(!t)return;let r=[...this.state.queue,t];this.setState({queue:r,queueLength:r.length}),this.context.logInfo("Enqueued change, queueLength: "+r.length)}dequeueChange(){if(this.state.queue.length===0)return;let[,...e]=this.state.queue;this.setState({queue:e,queueLength:e.length}),this.context.logInfo("Dequeued change, queueLength: "+e.length)}removeQueuedChange(e){if(!e)return;let t=this.state.queue.filter(r=>r.id!==e);t.length!==this.state.queue.length&&(this.setState({queue:t,queueLength:t.length}),this.context.logInfo(`Removed queued change ${e}, queueLength: ${t.length}`))}addConflict(e){let t=[...this.state.conflicts,e];this.setState({conflicts:t,metrics:{...this.state.metrics,totalConflictsRecorded:this.state.metrics.totalConflictsRecorded+1}}),this.context.logInfo("Conflict added, total conflicts: "+t.length)}markRetryAttempt(e,t){let r=Date.now(),n=this.state.queue.map(i=>i.id!==e?i:{...i,retryCount:i.retryCount+1,lastAttemptAt:r,lastErrorMessage:t instanceof Error?t.message:String(t||"")});this.setState({queue:n,queueLength:n.length})}moveToDeadLetter(e,t,r){let n=this.state.queue.find(o=>o.id===e);if(!n)return;let i=this.state.queue.filter(o=>o.id!==e),a=[...this.state.deadLetters,{movedAt:Date.now(),reason:t,attempts:n.retryCount,errorMessage:r instanceof Error?r.message:String(r||""),change:n}];this.setState({queue:i,queueLength:i.length,deadLetters:a}),this.context.logInfo(`Change ${e} moved to dead-letter queue (${t})`)}requeueDeadLetter(e){let t=this.state.deadLetters.findIndex(a=>a.change.id===e);if(t<0)return!1;let r=this.state.deadLetters[t],n=this.state.deadLetters.filter((a,o)=>o!==t),i=[...this.state.queue,{...r.change,retryCount:0,lastAttemptAt:null,lastErrorMessage:null,firstQueuedAt:Date.now()}];return this.setState({deadLetters:n,queue:i,queueLength:i.length}),this.context.logInfo(`Dead-letter ${e} requeued`),!0}recordSyncMetrics(e){this.setState({metrics:{...this.state.metrics,...e}})}clearConflicts(){this.state.conflicts.length>0&&(this.setState({conflicts:[]}),this.context.logInfo("Conflicts cleared"))}setLastSyncAt(e){this.setState({lastSyncAt:e}),this.context.logInfo("Last sync at set to "+e)}finishSync(e){this.setState({status:"idle"}),this.context.logInfo("Sync finished",e)}logoutLocal(){this.state={...Et};try{this.storage.removeItem(Xn)}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(Xn,JSON.stringify(this.state))}catch(e){this.context.logError(e,{message:"Gagal persist sync-store"})}}async load(){try{let e=await this.storage.getItem(Xn);if(!e)return null;let t=JSON.parse(e),r=Array.isArray(t.queue)?t.queue.map(s=>this.normalizeChange(s)).filter(s=>s!==null):[],n=Array.isArray(t.conflicts)?t.conflicts.filter(s=>typeof s=="object"&&s!==null):[],i=Array.isArray(t.deadLetters)?t.deadLetters.filter(s=>{if(!s||typeof s!="object")return!1;let c=s;return!!c.change&&typeof c.change.id=="string"}):[],a=t.metrics||{},o={...Et.metrics,...a};return{...Et,...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=wt()}};var Hr=class{constructor(e){this.context=e;this.explicitActionTableMap={createSettlement:"settlements",RecordCashIn:"transactions",RecordCashOut:"transactions",processReturn:"returns",cancelReturn:"returns",ReturnRefundApproved:"returns",CancelReturnApproved:"returns",CloseShiftApproval:"shifts",ReopenShiftApproved:"shifts",PO_PRICE_VARIANCE_DETECTED:"purchases",customerCreditEscalationDetected:"sales",TieredPrice:"products",LoyaltyEarnPoints:"loyalty_ledgers",LoyaltyRedeemPoints:"loyalty_ledgers",LoyaltyExpirePoints:"loyalty_ledgers"};this.entityTableMap={Bom:"boms",Category:"categories",Customer:"customers",CustomerGroup:"customer_groups",Expense:"expenses",FinancialSetting:"financial_settings",History:"histories",InventoryLog:"inventory_logs",InventoryLot:"inventory_lots",KitchenTicket:"kitchen_tickets",KitchenTicketItem:"kitchen_ticket_items",LoyaltyAccount:"loyalty_accounts",LoyaltyLedger:"loyalty_ledgers",Order:"orders",OrderItem:"order_items",Payable:"payables",PriceHistory:"price_histories",PriceTier:"price_tiers",Product:"products",Promotion:"promotions",Purchase:"purchases",PurchaseItem:"purchase_items",PurchaseOrder:"purchase_orders",PurchaseOrderItem:"purchase_order_items",Receivable:"receivables",ReportSchedule:"report_schedules",Return:"returns",ReturnItem:"return_items",Role:"roles",Sale:"sales",SaleItem:"sale_items",Settlement:"settlements",Shift:"shifts",StockAdjustment:"stock_adjustments",StockOpname:"stock_opnames",StockOpnameItem:"stock_opname_items",Supplier:"suppliers",TaxRate:"tax_rates",Transaction:"transactions",Uom:"uoms",User:"users"};var t;this.dbAdapter=(t=this.context.registry)==null?void 0:t.dbAdapter}inferEntityFromAction(e){let t=String(e||"").trim();if(!t)return null;let r=t.match(/^(Add|Update|Delete|Duplicate)([A-Z].*)$/);if(r)return r[2];let n=t.match(/^(create|record|process|cancel|close|reopen)([A-Z].*)$/);return n?n[2]:null}inferTableName(e,t){let r=String((t==null?void 0:t.tableName)||"").trim();if(r)return r;let n=(t==null?void 0:t.itemType)==="productId"?"products":(t==null?void 0:t.itemType)==="promotionId"?"promotions":(t==null?void 0:t.itemType)==="bomId"?"boms":"";if(n)return n;let i=this.explicitActionTableMap[e];if(i)return i;let a=this.inferEntityFromAction(e);return a&&this.entityTableMap[a]?this.entityTableMap[a]:"system_events"}resolveRecordId(e){var r,n,i,a,o,s,c;let t=(c=(s=(o=(a=(i=(n=(r=e==null?void 0:e.recordId)!=null?r:e==null?void 0:e.id)!=null?n:e==null?void 0:e.itemId)!=null?i:e==null?void 0:e.productId)!=null?a:e==null?void 0:e.promotionId)!=null?o:e==null?void 0:e.bomId)!=null?s:e==null?void 0:e.newId)!=null?c:e==null?void 0:e.originalId;return t==null||String(t).trim()===""?`activity-${Date.now()}`:String(t)}async logActivity(e,t,r,n){var o,s,c;let i=new Date().toISOString(),a=`${t} | ${e} | ${i}`;try{let u=this.context.config.deploymentMode,l=((o=this.context.session)==null?void 0:o.tenantId)||null,d=this.context.config.branchId||null,m=(r==null?void 0:r.tenantId)||null,f=(r==null?void 0:r.branchId)||null,y=m||l,v=f||d;if(u==="saas"&&(!y||!String(y).trim()))throw new Error("Tenant context is required for audit log entries in SaaS mode (missing tenantId)");if(u==="saas"&&l&&m&&String(m)!==String(l))throw new Error("Tenant isolation violation in audit log context (tenant override mismatch)");if(d&&f&&String(f)!==String(d))throw new Error("Branch isolation violation in audit log context (branch override mismatch)");let p={...r||{},tenantId:y||null,branchId:v||null,deploymentMode:u};await((c=(s=this.context.registry)==null?void 0:s.activitySink)==null?void 0:c.publish({activityId:P(),activityType:e,occurredAt:i,scopeRef:{tenantId:y||void 0,branchId:v||void 0,domain:"ofpos"},actor:{userId:t,source:"shared-core"},payload:p})),this.context.logInfo(a,p);let g=this.inferTableName(e,r),x=this.resolveRecordId(r),b={...p};await(n||this.dbAdapter).create(ae,{id:P(),userId:t,action:e,tableName:g,recordId:x,changes:b,timestamp:i})}catch(u){this.context.logError(u,{action:e,userId:t,extraContext:r})}}};var $r=class{constructor(e){this.context=e;this.recordCache=new Map;this.allCache=null;var t;this.db=(t=this.context.registry)==null?void 0:t.dbAdapter}async create(e){this.validateData(e,["name","permissions"]);let t=new Date().toISOString(),r={id:P().toString(),name:e.name,permissions:JSON.stringify(e.permissions),version:1,lastModified:t,deleted:!1},n=await this.db.create(Pe,r),i=this.denormalize(n);return this.recordCache.set(i.id,i),this.allCache=null,i}async update(e,t){if(!e)throw new Error("Missing role id for update");let r=await this.db.get(Pe,e);if(!r)throw new Error(`Role not found: ${e}`);let n=new Date().toISOString(),a={version:r.version+1,lastModified:n};t.name!==void 0&&(a.name=t.name),t.permissions!==void 0&&(a.permissions=JSON.stringify(t.permissions));let o=await this.db.update(Pe,e,a);if(!o)throw new Error(`Role not found: ${e}`);let s=this.denormalize(o);return this.recordCache.set(e,s),this.allCache=null,s}async delete(e){if(!e)throw new Error("Missing role id for delete");let t=await this.db.get(Pe,e);if(!t)return;if(!await this.db.update(Pe,e,{deleted:!0,version:t.version+1,lastModified:new Date().toISOString()}))throw new Error(`Role not found: ${e}`);this.recordCache.delete(e),this.allCache=null}async queryAll(){if(this.allCache)return this.allCache;let t=(await this.db.query(Pe,{filters:{deleted:!1},sort:[{field:"lastModified",direction:"desc"}]})).map(this.denormalize);this.recordCache.clear();for(let r of t)this.recordCache.set(r.id,r);return this.allCache=t,t}async getById(e){if(!e)return null;let t=this.recordCache.get(e);if(t&&!t.deleted)return t;let r=await this.db.get(Pe,e);if(!r||r.deleted)return null;let n=this.denormalize(r);return this.recordCache.set(e,n),n}denormalize(e){return{...e,permissions:JSON.parse(e.permissions)}}validateData(e,t){for(let r of t)if(e[r]===void 0)throw new Error(`Field '${r}' is required`)}};var 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"]}]},Vr=class{constructor(e){this.context=e;this.roleAdapter=new $r(e),this.changeQueue=$(this.context)}enqueue(e,t,r){this.changeQueue.enqueue({type:e,model:t,record:r})}async addRole(e,t){let r=await this.roleAdapter.create(e);return this.enqueue("create","roles",r),this.context.logActivity("AddRole",{id:r.id}),r}async updateRole(e,t,r){let n=await this.roleAdapter.update(e,t);return this.enqueue("update","roles",n),this.context.logActivity("UpdateRole",{id:e}),n}async deleteRole(e,t){return await this.roleAdapter.delete(e),this.enqueue("delete","roles",{id:e}),this.context.logActivity("DeleteRole",{id:e}),{id:e,queued:!0}}async getRoles(e){var a;let t=(a=this.context.registry)==null?void 0:a.dbAdapter,r={deleted:!1},n=e!=null&&e.filters?{and:[e.filters,r]}:r;return await t.query(Pe,{...e,filters:n})}async getRoleById(e){return this.roleAdapter.getById(e)}hasPermission(e,t){return Array.isArray(e.permissions)&&(e.permissions.includes("all")||e.permissions.includes(t))}async can(e,t){let r=await this.getRoleById(e.role);return this.hasPermission(r,t)}getGranularPolicy(){return 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 u,l,d,m,f;let t=P(),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||((u=this.context.session)==null?void 0:u.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!(n.approvalRequiredAboveThreshold&&i>n.thresholdAmount)){let y={decisionId:t,action:e.action,status:"allow",reasonCode:"ALLOW_BELOW_THRESHOLD",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((l=this.context.session)==null?void 0:l.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!e.approval){let y={decisionId:t,action:e.action,status:"require_approval",reasonCode:"THRESHOLD_APPROVAL_REQUIRED",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((d=this.context.session)==null?void 0:d.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount}),y}if(!this.isApprovalValid(e.approval,n.approverRoles.map(y=>this.normalizeRole(y)))){let y={decisionId:t,action:e.action,status:"deny",reasonCode:"APPROVAL_INVALID",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:y.status,reasonCode:y.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((m=this.context.session)==null?void 0:m.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount,approvedBy:e.approval.approvedBy,approvalReason:e.approval.reason,approverRole:this.normalizeRole(e.approval.approverRole)}),y}let c={decisionId:t,action:e.action,status:"allow",reasonCode:"ALLOW_WITH_APPROVAL",thresholdAmount:n.thresholdAmount,amount:i};return await this.context.logActivity("AuthorizationDecision",{...e.metadata,decisionId:t,action:e.action,status:c.status,reasonCode:c.reasonCode,actorRole:this.normalizeRole(e.actor.role),actorUserId:e.actor.userId||((f=this.context.session)==null?void 0:f.userId)||"system",amount:i,thresholdAmount:n.thresholdAmount,approvedBy:e.approval.approvedBy,approvalReason:e.approval.reason,approverRole:this.normalizeRole(e.approval.approverRole)}),c}};var En=Ot(ei()),On=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=En.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=En.default.AES.decrypt(t.value,this.masterKey).toString(En.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 Rn=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}};import{DefaultHttpAdapter as ti}from"ofcore";import{executeHttpRequestWithRetry as Ra,NoRetryHttpPolicy as ri,ExponentialBackoffHttpPolicy as Ff}from"ofcore";var _n=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 c;let i={...n},a=await this.encryptionService.getItem("auth_token");a&&(i.Authorization=`Bearer ${a}`);let o=t.includes("/sync/push")||t.includes("/sync/pull"),s=t.startsWith("/sync/")||t.startsWith("/erp")||t.startsWith("/shifts/")||t.startsWith("/backup/");try{let u=this.context.config.branchId;u&&(i["X-Branch-ID"]=u)}catch{}if(s&&this.context.config.deploymentMode==="saas"){let u=(c=this.context.session)==null?void 0:c.tenantId;if(!u||!String(u).trim())throw new Error("Tenant context is required for tenant-scoped requests in SaaS mode (missing tenantId)");i["X-Tenant-ID"]=u}if(e==="POST"&&t.includes("/sync/push")&&r){let u=typeof r=="string"?r:JSON.stringify(r),l=this.context.checksum(u);if(!l)throw new Error("paymentSigningKey is required for sync push checksum");i["X-Data-Checksum"]=l}return o&&(i["X-Sync-Protocol-Version"]=String(this.context.config.syncProtocolVersion),i["X-Sync-Compatible-Versions"]=this.context.config.syncCompatibleServerVersions.join(",")),i}async requestData(e,t,r={}){let n=await this.buildHeaders(e,t,r.data,r.headers),i=this.context.config.apiUrl||"",a=t.startsWith("http")?t:`${i}${t}`,o=await Ra(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 mo={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"},Mt=class{async backoff(e){return e()}async applyChanges(){}async syncWithErp(){}async syncLoop(){}},_a=class{constructor(e){this.context=e;this.lastAlertAtByCode=new Map;this.started=!1;var t,r;this.dbAdapter=(t=e.registry)==null?void 0:t.dbAdapter,this.apiService=(r=e.integrationServices)==null?void 0:r.api,this.syncStore=e.getSyncStore(),this.onDataChanged=()=>{this.syncLoop().catch(n=>this.context.logError(n,{message:"Socket-triggered sync gagal"}))}}start(){this.started||(this.unsubscribeStore=this.syncStore.subscribe(e=>{e.queueLength>0&&(this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.syncLoop().catch(t=>this.context.logError(t,{message:"Debounced sync gagal"}))},this.context.config.syncDebounceMs))}),Le.on("data_changed",this.onDataChanged),this.periodicTimer=setInterval(()=>{this.context.isOnline()&&this.syncLoop().catch(e=>this.context.logError(e,{message:"Periodic sync gagal"}))},this.context.config.syncIntervalMs),this.started=!0)}normalizeOutgoingChange(e){var u,l,d,m,f;let t=(u=e==null?void 0:e.table)!=null?u:e==null?void 0:e.model,r=(l=e==null?void 0:e.record)!=null?l:{},n=(d=e==null?void 0:e.id)!=null?d:r==null?void 0:r.id;if(!t||!n)return null;let i=String((m=e==null?void 0:e.type)!=null?m:"").toUpperCase(),a=i==="CREATE"||i==="UPDATE"||i==="DELETE"?i:"UPDATE",o=Number(e==null?void 0:e.updated_at),s=Date.parse(String((f=r==null?void 0:r.lastModified)!=null?f:"")),c=Number.isFinite(o)&&o>0?o:Number.isFinite(s)&&s>0?s:Date.now();return{id:n,table:t,type:a,record:r,updated_at:c}}getRemoteTimestamp(e){var n,i,a;let t=Number(e==null?void 0:e.updated_at);if(Number.isFinite(t)&&t>0)return t;let r=Date.parse(String((a=(i=(n=e==null?void 0:e.record)==null?void 0:n.lastModified)!=null?i:e==null?void 0:e.lastModified)!=null?a:""));return Number.isFinite(r)&&r>0?r:Date.now()}getConflictResolutionStrategy(e){return mo[e]||"local_wins_manual"}requireBranchContext(){var t;if(!String((t=this.context.config.branchId)!=null?t:"").trim())throw new Error("Branch context is required for sync operations (missing branchId)")}async backoff(e,t=this.context.config.syncMaxRetries,r=this.context.config.syncBackoffDelayMs){let n=0;for(;;)try{return await e()}catch(i){if(n++,n>t)throw i;let a=r*Math.pow(2,n)+Math.random()*100;await new Promise(o=>setTimeout(o,a))}}async applyChanges(e,t){var i,a,o;let r=this.dbAdapter,n=this.syncStore;for(let s of e){let c=s==null?void 0:s.table,u=s==null?void 0:s.id;if(!c||!u){this.context.logError(new Error("Invalid remote change payload"),{change:s,...t||{}});continue}let l=this.getRemoteTimestamp(s),d=new Date(l).toISOString(),m=(i=s==null?void 0:s.record)!=null?i:{},f={...m,id:u,lastModified:(a=m==null?void 0:m.lastModified)!=null?a:d};try{let y=await r.get(c,u);if(!y)await r.create(c,f);else{let v=Date.parse(String((o=y==null?void 0:y.lastModified)!=null?o:""));if(!Number.isFinite(v)||l>v)await r.update(c,u,f);else if(l!==v)if(this.getConflictResolutionStrategy(c)==="server_wins")await r.update(c,u,f),this.context.logInfo(`Auto-resolve konflik master data ${c}:${u}`,t);else{let p={table:c,id:u,localLastModified:y==null?void 0:y.lastModified,remoteUpdatedAt:l,local:y,remote:s,reason:"local_newer"};n.addConflict(p),this.context.logInfo(`Konflik terdeteksi ${c}:${u}, dicatat untuk resolusi manual`,t)}}}catch(y){this.context.logError(y,{message:`Error applyChange ${s.table}:${s.id}`,...t||{}})}}}async syncWithErp(e){var t,r,n,i,a,o;try{this.context.logInfo("Mulai sinkronisasi ERP",e);let s=await this.apiService.getErpData(void 0,void 0,e),c=this.dbAdapter;for(let u of(t=s==null?void 0:s.customers)!=null?t:[]){let l=u==null?void 0:u.id;if(!l)continue;let d=await c.get("customers",l),m={...u,lastModified:(r=u==null?void 0:u.lastModified)!=null?r:new Date().toISOString()};d?await c.update("customers",l,m):await c.create("customers",m)}for(let u of(n=s==null?void 0:s.boms)!=null?n:[]){let l=u==null?void 0:u.id;if(!l)continue;let d=await c.get("boms",l),m={...u,lastModified:(i=u==null?void 0:u.lastModified)!=null?i:new Date().toISOString()};d?await c.update("boms",l,m):await c.create("boms",m)}for(let u of(a=s==null?void 0:s.uoms)!=null?a:[]){let l=u==null?void 0:u.id;if(!l)continue;let d=await c.get("uoms",l),m={...u,lastModified:(o=u==null?void 0:u.lastModified)!=null?o:new Date().toISOString()};d?await c.update("uoms",l,m):await c.create("uoms",m)}this.context.logInfo("Sinkronisasi ERP selesai",e)}catch(s){this.context.logError(s,{message:"Sinkronisasi ERP gagal",...e||{}})}}async cleanupDeleted(){this.context.logInfo("cleanupDeleted: belum diimplementasi")}shouldTriggerAlert(e){let t=this.context.config.opsAlertEscalationCooldownMinutes*60*1e3,r=Date.now(),n=this.lastAlertAtByCode.get(e)||0;return r-n<t?!1:(this.lastAlertAtByCode.set(e,r),!0)}emitOperationalAlert(e){if(!this.shouldTriggerAlert(e.code))return;let t={...e.correlationId?{correlationId:e.correlationId}:{},...e.syncBatchId?{syncBatchId:e.syncBatchId}:{},...e.metrics?{metrics:e.metrics}:{},code:e.code,category:e.category,severity:e.severity,at:e.at};e.severity==="critical"?this.context.logError(new Error(e.message),t):this.context.logInfo(e.message,t),Le.emit("ops:alert",e)}evaluateOperationalAlerts(e){let{traceContext:t,pushAttempted:r,pushFailed:n,queueLatencyMs:i,deadLetterCount:a}=e;if(r>0){let o=Math.round(n/r*100);o>=this.context.config.opsAlertSyncFailureRateThresholdPercent&&this.emitOperationalAlert({severity:o>=75?"critical":"warning",category:"sync",code:"SYNC_FAILURE_RATE",message:`Sync failure rate breached threshold (${o}%)`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{failureRatePercent:o,pushAttempted:r,pushFailed:n},at:new Date().toISOString()})}i>=this.context.config.opsAlertQueueLatencyThresholdMs&&this.emitOperationalAlert({severity:i>=this.context.config.opsAlertQueueLatencyThresholdMs*2?"critical":"warning",category:"sync",code:"SYNC_QUEUE_LATENCY",message:`Sync queue latency breached threshold (${i} ms)`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{queueLatencyMs:i},at:new Date().toISOString()}),a>=this.context.config.opsAlertDeadLetterCountThreshold&&this.emitOperationalAlert({severity:a>=this.context.config.opsAlertDeadLetterCountThreshold*2?"critical":"warning",category:"sync",code:"SYNC_DEAD_LETTER",message:`Dead-letter count breached threshold (${a})`,correlationId:t.correlationId,syncBatchId:t.syncBatchId,metrics:{deadLetterCount:a},at:new Date().toISOString()})}async syncLoop(){if(this.context.config.demoMode){this.context.logInfo("Demo mode enabled: skipping sync");return}let e=this.syncStore,t={correlationId:this.context.createCorrelationId("sync"),syncBatchId:this.context.createCorrelationId("sync-batch")};try{if(!this.context.isOnline()){this.context.logInfo("Offline. Lewati sinkronisasi.",t);return}this.requireBranchContext(),e.startSync(t),e.clearError();let r=e.getState().queue||[],n=Date.now(),i=r.length?Math.round(r.reduce((m,f)=>{let y=Number(f==null?void 0:f.firstQueuedAt);return!Number.isFinite(y)||y<=0?m:m+Math.max(0,n-y)},0)/r.length):0,a=0,o=0,s=0,c=0;for(let m of r)try{a+=1;let f=this.normalizeOutgoingChange(m);if(!f){this.context.logError(new Error("Invalid queued change"),{change:m,...t}),e.removeQueuedChange(String((m==null?void 0:m.id)||"")),s+=1;continue}await this.backoff(()=>this.apiService.pushChange({changes:[f]},t)),e.removeQueuedChange(f.id),o+=1}catch(f){this.context.logError(f,{message:"Gagal push change",...t}),s+=1,e.markRetryAttempt(m.id,f);let y=e.getState().queue.find(v=>v.id===m.id);y&&y.retryCount>=this.context.config.syncMaxRetries&&e.moveToDeadLetter(m.id,"max_retry_exceeded",f)}let u=[];try{let m=e.getState().lastSyncAt;u=await this.backoff(()=>this.apiService.pullChanges({since:m},t)),await this.applyChanges(u,t),c=u.length}catch(m){this.context.logError(m,{message:"Gagal pull/apply changes",...t})}await this.syncWithErp(t),e.setLastSyncAt(Date.now()),await this.cleanupDeleted();let l=Date.now(),d=e.getState().metrics;e.recordSyncMetrics({totalPushAttempted:d.totalPushAttempted+a,totalPushSucceeded:d.totalPushSucceeded+o,totalPushFailed:d.totalPushFailed+s,totalPullApplied:d.totalPullApplied+c,lastQueueLatencyMs:i,lastRunDurationMs:Math.max(0,l-n),lastRunAt:l}),this.evaluateOperationalAlerts({traceContext:t,pushAttempted:a,pushFailed:s,queueLatencyMs:i,deadLetterCount:e.getState().deadLetters.length})}catch(r){this.context.logError(r,{message:"Sync loop error",...t}),e.setError(r,t)}finally{e.finishSync(t),this.context.logInfo("Sync loop selesai",t)}}shutdown(){this.started&&(this.debounceTimer&&clearTimeout(this.debounceTimer),this.periodicTimer&&clearInterval(this.periodicTimer),this.unsubscribeStore&&(this.unsubscribeStore(),this.unsubscribeStore=void 0),Le.off("data_changed",this.onDataChanged),this.started=!1)}};var qt=class{getSocket(){}shutdown(){}},Ta=class h{constructor(e,t="http://localhost:3000"){this.context=e;this.url=t;this.started=!1;var r,n,i,a;if(this.syncStore=(n=(r=this.context).getSyncStore)==null?void 0:n.call(r),this.syncService=(i=this.context.integrationServices)==null?void 0:i.sync,this.debouncedSync=h.debounce(()=>{var o;(o=this.syncService)==null||o.syncLoop()}),this.socketAdapter=(a=this.context.registry)==null?void 0:a.socketAdapter,!this.socketAdapter)throw new Error("SocketService requires SocketAdapter from registry")}static debounce(e,t=1e3){let r;return((...n)=>{r&&clearTimeout(r),r=setTimeout(()=>e(...n),t)})}async start(){this.started||(await this.initSocket(),this.started=!0)}async initSocket(){var r;let e=(r=this.context.integrationServices)==null?void 0:r.encryption,t=await(e==null?void 0:e.getItem("auth_token"));await this.socketAdapter.connect({url:this.url,headers:{...t?{Authorization:`Bearer ${t}`}:{},"X-Branch-ID":this.context.config.branchId||""}}),this.unsubscribeConnect=this.socketAdapter.subscribe("connect",()=>{this.debouncedSync()}),this.unsubscribeDisconnect=this.socketAdapter.subscribe("disconnect",n=>{var a;let i=typeof n=="string"?n:"unknown";(a=this.syncStore)==null||a.setError(new Error(`Socket disconnected: ${i}`))}),this.unsubscribeDataChanged=this.socketAdapter.subscribe("data_changed",()=>{this.debouncedSync()})}getSocket(){return this.socketAdapter}shutdown(){var e,t,r,n,i;this.started&&((e=this.unsubscribeDataChanged)==null||e.call(this),(t=this.unsubscribeConnect)==null||t.call(this),(r=this.unsubscribeDisconnect)==null||r.call(this),this.unsubscribeDataChanged=void 0,this.unsubscribeConnect=void 0,this.unsubscribeDisconnect=void 0,(i=(n=this.socketAdapter)==null?void 0:n.disconnect)==null||i.call(n).catch(()=>{}),this.started=!1)}};var Tn=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})}}};import{DefaultPlatformAdapter as ho}from"ofcore";var Bn=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 ho(this.context),this.storage=(n=t==null?void 0:t.storageAdapter)!=null?n:new yt(this.context)}async init(){let e=await this.storage.getItem("config");if(e)try{let t=JSON.parse(e);this._lowStockThreshold=t.lowStockThreshold?Number(t.lowStockThreshold):this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=t.paymentSigningKey?t.paymentSigningKey:this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=t.apiUrl?t.apiUrl:this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=t.branchId?t.branchId:this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=t.demoMode!=null?!!t.demoMode:this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let r=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE"),n=t.deploymentMode==="saas"||t.deploymentMode==="standalone"?t.deploymentMode:r==="saas"||r==="standalone"?r:null;this._deploymentMode=n,this._requireActiveShiftForCash=t.requireActiveShiftForCash!=null?!!t.requireActiveShiftForCash:null,this._maxCashAdjustmentAmount=t.maxCashAdjustmentAmount!=null?Number(t.maxCashAdjustmentAmount):null,this._requireShiftCloseApprovalOnDifference=t.requireShiftCloseApprovalOnDifference!=null?!!t.requireShiftCloseApprovalOnDifference:null,this._shiftCloseDifferenceApprovalThreshold=t.shiftCloseDifferenceApprovalThreshold!=null?Number(t.shiftCloseDifferenceApprovalThreshold):null,this._requireReasonForReturnOperations=t.requireReasonForReturnOperations!=null?!!t.requireReasonForReturnOperations:null,this._requireApprovalForReturnRefund=t.requireApprovalForReturnRefund!=null?!!t.requireApprovalForReturnRefund:null,this._requireApprovalForReturnCancel=t.requireApprovalForReturnCancel!=null?!!t.requireApprovalForReturnCancel:null,this._requireLotExpiryForPurchaseReceiving=t.requireLotExpiryForPurchaseReceiving!=null?!!t.requireLotExpiryForPurchaseReceiving:null,this._lotConsumptionPolicy=t.lotConsumptionPolicy==="FEFO"||t.lotConsumptionPolicy==="FIFO"?t.lotConsumptionPolicy:null,this._enableCustomerCreditPolicy=t.enableCustomerCreditPolicy!=null?!!t.enableCustomerCreditPolicy:null,this._customerCreditMaxOutstandingAmount=t.customerCreditMaxOutstandingAmount!=null?Number(t.customerCreditMaxOutstandingAmount):null,this._customerCreditBlockOnOverdue=t.customerCreditBlockOnOverdue!=null?!!t.customerCreditBlockOnOverdue:null,this._customerCreditOverdueGraceDays=t.customerCreditOverdueGraceDays!=null?Number(t.customerCreditOverdueGraceDays):null,this._customerCreditEscalationThresholdDays=t.customerCreditEscalationThresholdDays!=null?Number(t.customerCreditEscalationThresholdDays):null,this._enableReturnFraudGuard=t.enableReturnFraudGuard!=null?!!t.enableReturnFraudGuard:null,this._returnFraudWindowMinutes=t.returnFraudWindowMinutes!=null?Number(t.returnFraudWindowMinutes):null,this._returnFraudMaxEvents=t.returnFraudMaxEvents!=null?Number(t.returnFraudMaxEvents):null,this._returnFraudAction=t.returnFraudAction==="require_approval"||t.returnFraudAction==="block"?t.returnFraudAction:null,this._returnApprovalBypassRoles=Array.isArray(t.returnApprovalBypassRoles)?t.returnApprovalBypassRoles.map(i=>String(i)):null,this._returnApprovalApproverRoles=Array.isArray(t.returnApprovalApproverRoles)?t.returnApprovalApproverRoles.map(i=>String(i)):null,this._allowPromotionStacking=t.allowPromotionStacking!=null?!!t.allowPromotionStacking:null,this._promotionSelectionStrategy=t.promotionSelectionStrategy==="best_discount"||t.promotionSelectionStrategy==="first_valid"?t.promotionSelectionStrategy:null,this._promotionStackingOrder=t.promotionStackingOrder==="input_order"||t.promotionStackingOrder==="percent_then_fixed"||t.promotionStackingOrder==="fixed_then_percent"?t.promotionStackingOrder:null,this._pricingRoundingIncrement=t.pricingRoundingIncrement!=null?Number(t.pricingRoundingIncrement):null,this._pricingRoundingScope=t.pricingRoundingScope==="line"||t.pricingRoundingScope==="total"?t.pricingRoundingScope:null,this._enableSequentialDocumentNumbers=t.enableSequentialDocumentNumbers!=null?!!t.enableSequentialDocumentNumbers:null,this._syncProtocolVersion=Number.isInteger(t.syncProtocolVersion)&&Number(t.syncProtocolVersion)>=0?Number(t.syncProtocolVersion):null,this._syncCompatibleServerVersions=Array.isArray(t.syncCompatibleServerVersions)?t.syncCompatibleServerVersions.map(i=>Number(i)).filter(i=>Number.isInteger(i)&&i>=0):null,this._enforceSyncProtocolHandshake=t.enforceSyncProtocolHandshake!=null?!!t.enforceSyncProtocolHandshake:null,this._onlineAuthMaxFailedAttempts=t.onlineAuthMaxFailedAttempts!=null?Number(t.onlineAuthMaxFailedAttempts):null,this._onlineAuthLockoutSeconds=t.onlineAuthLockoutSeconds!=null?Number(t.onlineAuthLockoutSeconds):null,this._drRpoTargetMinutes=t.drRpoTargetMinutes!=null?Number(t.drRpoTargetMinutes):null,this._drRtoTargetMinutes=t.drRtoTargetMinutes!=null?Number(t.drRtoTargetMinutes):null,this._backupIntervalMinutes=t.backupIntervalMinutes!=null?Number(t.backupIntervalMinutes):null,this._backupRestoreDrillIntervalHours=t.backupRestoreDrillIntervalHours!=null?Number(t.backupRestoreDrillIntervalHours):null,this._opsAlertSyncFailureRateThresholdPercent=t.opsAlertSyncFailureRateThresholdPercent!=null?Number(t.opsAlertSyncFailureRateThresholdPercent):null,this._opsAlertQueueLatencyThresholdMs=t.opsAlertQueueLatencyThresholdMs!=null?Number(t.opsAlertQueueLatencyThresholdMs):null,this._opsAlertDeadLetterCountThreshold=t.opsAlertDeadLetterCountThreshold!=null?Number(t.opsAlertDeadLetterCountThreshold):null,this._opsAlertEscalationCooldownMinutes=t.opsAlertEscalationCooldownMinutes!=null?Number(t.opsAlertEscalationCooldownMinutes):null,this._auditLogRetentionDays=t.auditLogRetentionDays!=null?Number(t.auditLogRetentionDays):null,this._auditLogArchiveBeforePurge=t.auditLogArchiveBeforePurge!=null?!!t.auditLogArchiveBeforePurge:null,this._auditLogPurgeBatchSize=t.auditLogPurgeBatchSize!=null?Number(t.auditLogPurgeBatchSize):null,this._sessionIdleTimeoutMinutes=t.sessionIdleTimeoutMinutes!=null?Number(t.sessionIdleTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=t.sessionReauthTimeoutMinutes!=null?Number(t.sessionReauthTimeoutMinutes):this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=t.apiTimeoutMs!=null?Number(t.apiTimeoutMs):this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=t.syncIntervalMs!=null?Number(t.syncIntervalMs):this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=t.syncMaxRetries!=null?Number(t.syncMaxRetries):this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=t.syncBackoffDelayMs!=null?Number(t.syncBackoffDelayMs):this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=t.syncDebounceMs!=null?Number(t.syncDebounceMs):this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=t.reportingTopSellingLimit!=null?Number(t.reportingTopSellingLimit):this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=t.reportingLowStockLimit!=null?Number(t.reportingLowStockLimit):this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=t.apiBackupListLimit!=null?Number(t.apiBackupListLimit):this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=t.encryptionKey?t.encryptionKey:this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=t.encryptionPassphrase?t.encryptionPassphrase:this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}catch(t){this.context.logError(t,{message:"Gagal mengurai konfigurasi dari storage"})}else{this._lowStockThreshold=this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")?Number(this.platformAdapter.getEnvVar("LOW_STOCK_THRESHOLD")):null,this._paymentSigningKey=this.platformAdapter.getEnvVar("PAYMENT_SIGNING_KEY")||null,this._apiUrl=this.platformAdapter.getEnvVar("API_URL")||null,this._branchId=this.platformAdapter.getEnvVar("BRANCH_ID")||null,this._demoMode=this.platformAdapter.getEnvVar("DEMO_MODE")==="true"||this.platformAdapter.getEnvVar("DEMO_MODE")==="1"?!0:null;let t=this.platformAdapter.getEnvVar("APP_DEPLOYMENT_MODE");this._deploymentMode=t==="saas"||t==="standalone"?t:null,this._requireActiveShiftForCash=null,this._maxCashAdjustmentAmount=null,this._requireShiftCloseApprovalOnDifference=null,this._shiftCloseDifferenceApprovalThreshold=null,this._requireReasonForReturnOperations=null,this._requireApprovalForReturnRefund=null,this._requireApprovalForReturnCancel=null,this._requireLotExpiryForPurchaseReceiving=null,this._lotConsumptionPolicy=null,this._enableCustomerCreditPolicy=null,this._customerCreditMaxOutstandingAmount=null,this._customerCreditBlockOnOverdue=null,this._customerCreditOverdueGraceDays=null,this._customerCreditEscalationThresholdDays=null,this._enableReturnFraudGuard=null,this._returnFraudWindowMinutes=null,this._returnFraudMaxEvents=null,this._returnFraudAction=null,this._returnApprovalBypassRoles=null,this._returnApprovalApproverRoles=null,this._allowPromotionStacking=null,this._promotionSelectionStrategy=null,this._promotionStackingOrder=null,this._pricingRoundingIncrement=null,this._pricingRoundingScope=null,this._enableSequentialDocumentNumbers=null,this._syncProtocolVersion=null,this._syncCompatibleServerVersions=null,this._enforceSyncProtocolHandshake=null,this._onlineAuthMaxFailedAttempts=null,this._onlineAuthLockoutSeconds=null,this._drRpoTargetMinutes=null,this._drRtoTargetMinutes=null,this._backupIntervalMinutes=null,this._backupRestoreDrillIntervalHours=null,this._opsAlertSyncFailureRateThresholdPercent=null,this._opsAlertQueueLatencyThresholdMs=null,this._opsAlertDeadLetterCountThreshold=null,this._opsAlertEscalationCooldownMinutes=null,this._auditLogRetentionDays=null,this._auditLogArchiveBeforePurge=null,this._auditLogPurgeBatchSize=null,this._sessionIdleTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_IDLE_TIMEOUT_MINUTES")):null,this._sessionReauthTimeoutMinutes=this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")?Number(this.platformAdapter.getEnvVar("SESSION_REAUTH_TIMEOUT_MINUTES")):null,this._apiTimeoutMs=this.platformAdapter.getEnvVar("API_TIMEOUT_MS")?Number(this.platformAdapter.getEnvVar("API_TIMEOUT_MS")):null,this._syncIntervalMs=this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")?Number(this.platformAdapter.getEnvVar("SYNC_INTERVAL_MS")):null,this._syncMaxRetries=this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")?Number(this.platformAdapter.getEnvVar("SYNC_MAX_RETRIES")):null,this._syncBackoffDelayMs=this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")?Number(this.platformAdapter.getEnvVar("SYNC_BACKOFF_DELAY_MS")):null,this._syncDebounceMs=this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")?Number(this.platformAdapter.getEnvVar("SYNC_DEBOUNCE_MS")):null,this._reportingTopSellingLimit=this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_TOP_SELLING_LIMIT")):null,this._reportingLowStockLimit=this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")?Number(this.platformAdapter.getEnvVar("REPORTING_LOW_STOCK_LIMIT")):null,this._apiBackupListLimit=this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")?Number(this.platformAdapter.getEnvVar("API_BACKUP_LIST_LIMIT")):null,this._encryptionKey=this.platformAdapter.getEnvVar("ENCRYPTION_KEY")||null,this._encryptionPassphrase=this.platformAdapter.getEnvVar("ENCRYPTION_PASSPHRASE")||null}}get apiUrl(){return this._apiUrl||"https://localhost:3000/api"}get lowStockThreshold(){return this._lowStockThreshold!=null?this._lowStockThreshold:10}get paymentSigningKey(){return this._paymentSigningKey||""}get demoMode(){return this._demoMode===!0}get branchId(){return this._branchId}get deploymentMode(){var e;return(e=this._deploymentMode)!=null?e:"standalone"}get requireActiveShiftForCash(){return this._requireActiveShiftForCash===!0}get maxCashAdjustmentAmount(){return this._maxCashAdjustmentAmount}get requireShiftCloseApprovalOnDifference(){return this._requireShiftCloseApprovalOnDifference===!0}get shiftCloseDifferenceApprovalThreshold(){return this._shiftCloseDifferenceApprovalThreshold}get requireReasonForReturnOperations(){return this._requireReasonForReturnOperations===!0}get requireApprovalForReturnRefund(){return this._requireApprovalForReturnRefund===!0}get requireApprovalForReturnCancel(){return this._requireApprovalForReturnCancel===!0}get requireLotExpiryForPurchaseReceiving(){return this._requireLotExpiryForPurchaseReceiving===!0}get lotConsumptionPolicy(){var e;return(e=this._lotConsumptionPolicy)!=null?e:"FEFO"}get enableCustomerCreditPolicy(){return this._enableCustomerCreditPolicy===!0}get customerCreditMaxOutstandingAmount(){return this._customerCreditMaxOutstandingAmount!=null&&this._customerCreditMaxOutstandingAmount>=0?this._customerCreditMaxOutstandingAmount:null}get customerCreditBlockOnOverdue(){return this._customerCreditBlockOnOverdue===!0}get customerCreditOverdueGraceDays(){return this._customerCreditOverdueGraceDays!=null&&this._customerCreditOverdueGraceDays>=0?this._customerCreditOverdueGraceDays:0}get customerCreditEscalationThresholdDays(){return this._customerCreditEscalationThresholdDays!=null&&this._customerCreditEscalationThresholdDays>0?this._customerCreditEscalationThresholdDays:14}get enableReturnFraudGuard(){return this._enableReturnFraudGuard===!0}get returnFraudWindowMinutes(){return this._returnFraudWindowMinutes!=null&&this._returnFraudWindowMinutes>0?this._returnFraudWindowMinutes:60}get returnFraudMaxEvents(){return this._returnFraudMaxEvents!=null&&this._returnFraudMaxEvents>0?this._returnFraudMaxEvents:3}get returnFraudAction(){var e;return(e=this._returnFraudAction)!=null?e:"require_approval"}get returnApprovalBypassRoles(){return this._returnApprovalBypassRoles}get returnApprovalApproverRoles(){return this._returnApprovalApproverRoles}get allowPromotionStacking(){return this._allowPromotionStacking===!0}get promotionSelectionStrategy(){var e;return(e=this._promotionSelectionStrategy)!=null?e:"best_discount"}get promotionStackingOrder(){var e;return(e=this._promotionStackingOrder)!=null?e:"input_order"}get pricingRoundingIncrement(){return this._pricingRoundingIncrement}get pricingRoundingScope(){var e;return(e=this._pricingRoundingScope)!=null?e:"total"}get enableSequentialDocumentNumbers(){return this._enableSequentialDocumentNumbers===!0}get syncProtocolVersion(){return this._syncProtocolVersion!=null&&Number.isInteger(this._syncProtocolVersion)&&this._syncProtocolVersion>=0?this._syncProtocolVersion:1}get syncCompatibleServerVersions(){let e=this._syncCompatibleServerVersions,t=[...Wn],r=Array.isArray(e)?e.filter(i=>Number.isInteger(i)&&i>=0):t,n=r.includes(this.syncProtocolVersion)?r:[this.syncProtocolVersion,...r];return Array.from(new Set(n))}get enforceSyncProtocolHandshake(){return this._enforceSyncProtocolHandshake===!0}get onlineAuthMaxFailedAttempts(){return this._onlineAuthMaxFailedAttempts!=null&&this._onlineAuthMaxFailedAttempts>0?this._onlineAuthMaxFailedAttempts:5}get onlineAuthLockoutSeconds(){return this._onlineAuthLockoutSeconds!=null&&this._onlineAuthLockoutSeconds>0?this._onlineAuthLockoutSeconds:60}get drRpoTargetMinutes(){return this._drRpoTargetMinutes!=null&&this._drRpoTargetMinutes>0?this._drRpoTargetMinutes:1440}get drRtoTargetMinutes(){return this._drRtoTargetMinutes!=null&&this._drRtoTargetMinutes>0?this._drRtoTargetMinutes:240}get backupIntervalMinutes(){return this._backupIntervalMinutes!=null&&this._backupIntervalMinutes>0?this._backupIntervalMinutes:360}get backupRestoreDrillIntervalHours(){return this._backupRestoreDrillIntervalHours!=null&&this._backupRestoreDrillIntervalHours>0?this._backupRestoreDrillIntervalHours:168}get opsAlertSyncFailureRateThresholdPercent(){return this._opsAlertSyncFailureRateThresholdPercent!=null&&this._opsAlertSyncFailureRateThresholdPercent>0?this._opsAlertSyncFailureRateThresholdPercent:30}get opsAlertQueueLatencyThresholdMs(){return this._opsAlertQueueLatencyThresholdMs!=null&&this._opsAlertQueueLatencyThresholdMs>0?this._opsAlertQueueLatencyThresholdMs:300*1e3}get opsAlertDeadLetterCountThreshold(){return this._opsAlertDeadLetterCountThreshold!=null&&this._opsAlertDeadLetterCountThreshold>0?this._opsAlertDeadLetterCountThreshold:10}get opsAlertEscalationCooldownMinutes(){return this._opsAlertEscalationCooldownMinutes!=null&&this._opsAlertEscalationCooldownMinutes>0?this._opsAlertEscalationCooldownMinutes:15}get auditLogRetentionDays(){return this._auditLogRetentionDays!=null&&this._auditLogRetentionDays>0?this._auditLogRetentionDays:365}get auditLogArchiveBeforePurge(){return this._auditLogArchiveBeforePurge!==!1}get auditLogPurgeBatchSize(){return this._auditLogPurgeBatchSize!=null&&this._auditLogPurgeBatchSize>0?this._auditLogPurgeBatchSize:500}get sessionIdleTimeoutMinutes(){return this._sessionIdleTimeoutMinutes!=null&&this._sessionIdleTimeoutMinutes>0?this._sessionIdleTimeoutMinutes:5}get sessionReauthTimeoutMinutes(){return this._sessionReauthTimeoutMinutes!=null&&this._sessionReauthTimeoutMinutes>0?this._sessionReauthTimeoutMinutes:1}get apiTimeoutMs(){return this._apiTimeoutMs!=null&&this._apiTimeoutMs>0?this._apiTimeoutMs:5e3}get syncIntervalMs(){return this._syncIntervalMs!=null&&this._syncIntervalMs>0?this._syncIntervalMs:300*1e3}get syncMaxRetries(){return this._syncMaxRetries!=null&&this._syncMaxRetries>0?this._syncMaxRetries:5}get syncBackoffDelayMs(){return this._syncBackoffDelayMs!=null&&this._syncBackoffDelayMs>0?this._syncBackoffDelayMs:1e3}get syncDebounceMs(){return this._syncDebounceMs!=null&&this._syncDebounceMs>0?this._syncDebounceMs:2e3}get reportingTopSellingLimit(){return this._reportingTopSellingLimit!=null&&this._reportingTopSellingLimit>0?this._reportingTopSellingLimit:5}get reportingLowStockLimit(){return this._reportingLowStockLimit!=null&&this._reportingLowStockLimit>0?this._reportingLowStockLimit:10}get apiBackupListLimit(){return this._apiBackupListLimit!=null&&this._apiBackupListLimit>0?this._apiBackupListLimit:10}get encryptionKey(){return this._encryptionKey||"default_secret_key"}get encryptionPassphrase(){return this._encryptionPassphrase||"default_passphrase"}validateConfig(e){var Z,te,X,Y,ye,se,qe,ve,Oe,le,ze,je,Ke,st,ht,ut,ke,Be,Ne,ft,Dt,ct,pt,mt,Pt,Ct,dt,Je,S,C,k,N,W,pe,be,ee,H;let t=(Z=e.requireShiftCloseApprovalOnDifference)!=null?Z:this.requireShiftCloseApprovalOnDifference,r=(te=e.shiftCloseDifferenceApprovalThreshold)!=null?te:this.shiftCloseDifferenceApprovalThreshold,n=(X=e.requireApprovalForReturnRefund)!=null?X:this.requireApprovalForReturnRefund,i=(Y=e.requireApprovalForReturnCancel)!=null?Y:this.requireApprovalForReturnCancel,a=(ye=e.returnApprovalApproverRoles)!=null?ye:this.returnApprovalApproverRoles,o=(se=e.enableReturnFraudGuard)!=null?se:this.enableReturnFraudGuard,s=(qe=e.returnFraudWindowMinutes)!=null?qe:this.returnFraudWindowMinutes,c=(ve=e.returnFraudMaxEvents)!=null?ve:this.returnFraudMaxEvents,u=(Oe=e.syncProtocolVersion)!=null?Oe:this.syncProtocolVersion,l=(le=e.syncCompatibleServerVersions)!=null?le:this.syncCompatibleServerVersions,d=(ze=e.enforceSyncProtocolHandshake)!=null?ze: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=(je=e.enableCustomerCreditPolicy)!=null?je:this.enableCustomerCreditPolicy,f=(Ke=e.customerCreditMaxOutstandingAmount)!=null?Ke:this.customerCreditMaxOutstandingAmount,y=(st=e.customerCreditOverdueGraceDays)!=null?st:this.customerCreditOverdueGraceDays,v=(ht=e.customerCreditEscalationThresholdDays)!=null?ht:this.customerCreditEscalationThresholdDays;if(m){if(f!=null&&f<0)throw new Error("Invalid config: customerCreditMaxOutstandingAmount must be >= 0");if(!Number.isInteger(y)||y<0)throw new Error("Invalid config: customerCreditOverdueGraceDays must be integer >= 0");if(!Number.isInteger(v)||v<=0)throw new Error("Invalid config: customerCreditEscalationThresholdDays must be integer > 0")}if((n===!0||i===!0)&&(!a||a.length===0))throw new Error("Invalid config: returnApprovalApproverRoles is required when return approval is enabled");if(o===!0){if(s==null||s<=0)throw new Error("Invalid config: returnFraudWindowMinutes must be greater than 0 when enableReturnFraudGuard=true");if(c==null||c<=0)throw new Error("Invalid config: returnFraudMaxEvents must be greater than 0 when enableReturnFraudGuard=true")}if(!Number.isInteger(u)||u<0)throw new Error("Invalid config: syncProtocolVersion must be a non-negative integer");if(!Array.isArray(l)||l.length===0)throw new Error("Invalid config: syncCompatibleServerVersions must contain at least one version");if(!l.every(V=>Number.isInteger(V)&&V>=0))throw new Error("Invalid config: syncCompatibleServerVersions must contain only non-negative integers");if(!l.includes(u))throw new Error("Invalid config: syncCompatibleServerVersions must include syncProtocolVersion");if(d===!0&&l.length===0)throw new Error("Invalid config: enforceSyncProtocolHandshake requires non-empty syncCompatibleServerVersions");let p=(ut=e.onlineAuthMaxFailedAttempts)!=null?ut:this.onlineAuthMaxFailedAttempts,g=(ke=e.onlineAuthLockoutSeconds)!=null?ke:this.onlineAuthLockoutSeconds,x=(Be=e.drRpoTargetMinutes)!=null?Be:this.drRpoTargetMinutes,b=(Ne=e.drRtoTargetMinutes)!=null?Ne:this.drRtoTargetMinutes,A=(ft=e.backupIntervalMinutes)!=null?ft:this.backupIntervalMinutes,I=(Dt=e.backupRestoreDrillIntervalHours)!=null?Dt:this.backupRestoreDrillIntervalHours,F=(ct=e.opsAlertSyncFailureRateThresholdPercent)!=null?ct:this.opsAlertSyncFailureRateThresholdPercent,w=(pt=e.opsAlertQueueLatencyThresholdMs)!=null?pt:this.opsAlertQueueLatencyThresholdMs,q=(mt=e.opsAlertDeadLetterCountThreshold)!=null?mt:this.opsAlertDeadLetterCountThreshold,M=(Pt=e.opsAlertEscalationCooldownMinutes)!=null?Pt:this.opsAlertEscalationCooldownMinutes,E=(Ct=e.auditLogRetentionDays)!=null?Ct:this.auditLogRetentionDays,L=(dt=e.auditLogPurgeBatchSize)!=null?dt:this.auditLogPurgeBatchSize;if(!Number.isInteger(p)||p<=0)throw new Error("Invalid config: onlineAuthMaxFailedAttempts must be a positive integer");if(!Number.isInteger(g)||g<=0)throw new Error("Invalid config: onlineAuthLockoutSeconds must be a positive integer");if(!Number.isInteger(x)||x<=0)throw new Error("Invalid config: drRpoTargetMinutes must be a positive integer");if(!Number.isInteger(b)||b<=0)throw new Error("Invalid config: drRtoTargetMinutes must be a positive integer");if(!Number.isInteger(A)||A<=0)throw new Error("Invalid config: backupIntervalMinutes must be a positive integer");if(!Number.isInteger(I)||I<=0)throw new Error("Invalid config: backupRestoreDrillIntervalHours must be a positive integer");if(A>x)throw new Error("Invalid config: backupIntervalMinutes must be <= drRpoTargetMinutes");if(!Number.isInteger(F)||F<=0||F>100)throw new Error("Invalid config: opsAlertSyncFailureRateThresholdPercent must be an integer in range 1..100");if(!Number.isInteger(w)||w<=0)throw new Error("Invalid config: opsAlertQueueLatencyThresholdMs must be a positive integer");if(!Number.isInteger(q)||q<=0)throw new Error("Invalid config: opsAlertDeadLetterCountThreshold must be a positive integer");if(!Number.isInteger(M)||M<=0)throw new Error("Invalid config: opsAlertEscalationCooldownMinutes must be a positive integer");if(!Number.isInteger(E)||E<=0)throw new Error("Invalid config: auditLogRetentionDays must be a positive integer");if(!Number.isInteger(L)||L<=0)throw new Error("Invalid config: auditLogPurgeBatchSize must be a positive integer");let Q=(Je=e.sessionIdleTimeoutMinutes)!=null?Je:this.sessionIdleTimeoutMinutes,T=(S=e.sessionReauthTimeoutMinutes)!=null?S:this.sessionReauthTimeoutMinutes;if(!Number.isInteger(Q)||Q<=0)throw new Error("Invalid config: sessionIdleTimeoutMinutes must be positive");if(!Number.isInteger(T)||T<=0)throw new Error("Invalid config: sessionReauthTimeoutMinutes must be positive");let j=(C=e.apiTimeoutMs)!=null?C:this.apiTimeoutMs,z=(k=e.syncIntervalMs)!=null?k:this.syncIntervalMs,B=(N=e.syncMaxRetries)!=null?N:this.syncMaxRetries,U=(W=e.syncBackoffDelayMs)!=null?W:this.syncBackoffDelayMs,O=(pe=e.syncDebounceMs)!=null?pe:this.syncDebounceMs,_=(be=e.reportingTopSellingLimit)!=null?be:this.reportingTopSellingLimit,R=(ee=e.reportingLowStockLimit)!=null?ee:this.reportingLowStockLimit,D=(H=e.apiBackupListLimit)!=null?H:this.apiBackupListLimit;if(!Number.isInteger(j)||j<=0)throw new Error("Invalid config: apiTimeoutMs must be positive");if(!Number.isInteger(z)||z<=0)throw new Error("Invalid config: syncIntervalMs must be positive");if(!Number.isInteger(B)||B<=0)throw new Error("Invalid config: syncMaxRetries must be positive");if(!Number.isInteger(U)||U<=0)throw new Error("Invalid config: syncBackoffDelayMs must be positive");if(!Number.isInteger(O)||O<=0)throw new Error("Invalid config: syncDebounceMs must be positive");if(!Number.isInteger(_)||_<=0)throw new Error("Invalid config: reportingTopSellingLimit must be positive");if(!Number.isInteger(R)||R<=0)throw new Error("Invalid config: reportingLowStockLimit must be positive");if(!Number.isInteger(D)||D<=0)throw new Error("Invalid config: apiBackupListLimit must be positive")}async setConfig(e){this.validateConfig(e),e.lowStockThreshold!==void 0&&(this._lowStockThreshold=e.lowStockThreshold),e.paymentSigningKey!==void 0&&(this._paymentSigningKey=e.paymentSigningKey),e.apiUrl!==void 0&&(this._apiUrl=e.apiUrl),e.branchId!==void 0&&(this._branchId=e.branchId),e.demoMode!==void 0&&(this._demoMode=e.demoMode),e.deploymentMode!==void 0&&(this._deploymentMode=e.deploymentMode),e.requireActiveShiftForCash!==void 0&&(this._requireActiveShiftForCash=e.requireActiveShiftForCash),e.maxCashAdjustmentAmount!==void 0&&(this._maxCashAdjustmentAmount=e.maxCashAdjustmentAmount),e.requireShiftCloseApprovalOnDifference!==void 0&&(this._requireShiftCloseApprovalOnDifference=e.requireShiftCloseApprovalOnDifference),e.shiftCloseDifferenceApprovalThreshold!==void 0&&(this._shiftCloseDifferenceApprovalThreshold=e.shiftCloseDifferenceApprovalThreshold),e.requireReasonForReturnOperations!==void 0&&(this._requireReasonForReturnOperations=e.requireReasonForReturnOperations),e.requireApprovalForReturnRefund!==void 0&&(this._requireApprovalForReturnRefund=e.requireApprovalForReturnRefund),e.requireApprovalForReturnCancel!==void 0&&(this._requireApprovalForReturnCancel=e.requireApprovalForReturnCancel),e.requireLotExpiryForPurchaseReceiving!==void 0&&(this._requireLotExpiryForPurchaseReceiving=e.requireLotExpiryForPurchaseReceiving),e.lotConsumptionPolicy!==void 0&&(this._lotConsumptionPolicy=e.lotConsumptionPolicy),e.enableCustomerCreditPolicy!==void 0&&(this._enableCustomerCreditPolicy=e.enableCustomerCreditPolicy),e.customerCreditMaxOutstandingAmount!==void 0&&(this._customerCreditMaxOutstandingAmount=e.customerCreditMaxOutstandingAmount),e.customerCreditBlockOnOverdue!==void 0&&(this._customerCreditBlockOnOverdue=e.customerCreditBlockOnOverdue),e.customerCreditOverdueGraceDays!==void 0&&(this._customerCreditOverdueGraceDays=e.customerCreditOverdueGraceDays),e.customerCreditEscalationThresholdDays!==void 0&&(this._customerCreditEscalationThresholdDays=e.customerCreditEscalationThresholdDays),e.enableReturnFraudGuard!==void 0&&(this._enableReturnFraudGuard=e.enableReturnFraudGuard),e.returnFraudWindowMinutes!==void 0&&(this._returnFraudWindowMinutes=e.returnFraudWindowMinutes),e.returnFraudMaxEvents!==void 0&&(this._returnFraudMaxEvents=e.returnFraudMaxEvents),e.returnFraudAction!==void 0&&(this._returnFraudAction=e.returnFraudAction),e.returnApprovalBypassRoles!==void 0&&(this._returnApprovalBypassRoles=e.returnApprovalBypassRoles),e.returnApprovalApproverRoles!==void 0&&(this._returnApprovalApproverRoles=e.returnApprovalApproverRoles),e.allowPromotionStacking!==void 0&&(this._allowPromotionStacking=e.allowPromotionStacking),e.promotionSelectionStrategy!==void 0&&(this._promotionSelectionStrategy=e.promotionSelectionStrategy),e.promotionStackingOrder!==void 0&&(this._promotionStackingOrder=e.promotionStackingOrder),e.pricingRoundingIncrement!==void 0&&(this._pricingRoundingIncrement=e.pricingRoundingIncrement),e.pricingRoundingScope!==void 0&&(this._pricingRoundingScope=e.pricingRoundingScope),e.enableSequentialDocumentNumbers!==void 0&&(this._enableSequentialDocumentNumbers=e.enableSequentialDocumentNumbers),e.syncProtocolVersion!==void 0&&(this._syncProtocolVersion=e.syncProtocolVersion),e.syncCompatibleServerVersions!==void 0&&(this._syncCompatibleServerVersions=e.syncCompatibleServerVersions),e.enforceSyncProtocolHandshake!==void 0&&(this._enforceSyncProtocolHandshake=e.enforceSyncProtocolHandshake),e.onlineAuthMaxFailedAttempts!==void 0&&(this._onlineAuthMaxFailedAttempts=e.onlineAuthMaxFailedAttempts),e.onlineAuthLockoutSeconds!==void 0&&(this._onlineAuthLockoutSeconds=e.onlineAuthLockoutSeconds),e.drRpoTargetMinutes!==void 0&&(this._drRpoTargetMinutes=e.drRpoTargetMinutes),e.drRtoTargetMinutes!==void 0&&(this._drRtoTargetMinutes=e.drRtoTargetMinutes),e.backupIntervalMinutes!==void 0&&(this._backupIntervalMinutes=e.backupIntervalMinutes),e.backupRestoreDrillIntervalHours!==void 0&&(this._backupRestoreDrillIntervalHours=e.backupRestoreDrillIntervalHours),e.opsAlertSyncFailureRateThresholdPercent!==void 0&&(this._opsAlertSyncFailureRateThresholdPercent=e.opsAlertSyncFailureRateThresholdPercent),e.opsAlertQueueLatencyThresholdMs!==void 0&&(this._opsAlertQueueLatencyThresholdMs=e.opsAlertQueueLatencyThresholdMs),e.opsAlertDeadLetterCountThreshold!==void 0&&(this._opsAlertDeadLetterCountThreshold=e.opsAlertDeadLetterCountThreshold),e.opsAlertEscalationCooldownMinutes!==void 0&&(this._opsAlertEscalationCooldownMinutes=e.opsAlertEscalationCooldownMinutes),e.auditLogRetentionDays!==void 0&&(this._auditLogRetentionDays=e.auditLogRetentionDays),e.auditLogArchiveBeforePurge!==void 0&&(this._auditLogArchiveBeforePurge=e.auditLogArchiveBeforePurge),e.auditLogPurgeBatchSize!==void 0&&(this._auditLogPurgeBatchSize=e.auditLogPurgeBatchSize),e.sessionIdleTimeoutMinutes!==void 0&&(this._sessionIdleTimeoutMinutes=e.sessionIdleTimeoutMinutes),e.sessionReauthTimeoutMinutes!==void 0&&(this._sessionReauthTimeoutMinutes=e.sessionReauthTimeoutMinutes),e.apiTimeoutMs!==void 0&&(this._apiTimeoutMs=e.apiTimeoutMs),e.syncIntervalMs!==void 0&&(this._syncIntervalMs=e.syncIntervalMs),e.syncMaxRetries!==void 0&&(this._syncMaxRetries=e.syncMaxRetries),e.syncBackoffDelayMs!==void 0&&(this._syncBackoffDelayMs=e.syncBackoffDelayMs),e.syncDebounceMs!==void 0&&(this._syncDebounceMs=e.syncDebounceMs),e.reportingTopSellingLimit!==void 0&&(this._reportingTopSellingLimit=e.reportingTopSellingLimit),e.reportingLowStockLimit!==void 0&&(this._reportingLowStockLimit=e.reportingLowStockLimit),e.apiBackupListLimit!==void 0&&(this._apiBackupListLimit=e.apiBackupListLimit),e.encryptionKey!==void 0&&(this._encryptionKey=e.encryptionKey),e.encryptionPassphrase!==void 0&&(this._encryptionPassphrase=e.encryptionPassphrase);let t={lowStockThreshold:this._lowStockThreshold,paymentSigningKey:this._paymentSigningKey,apiUrl:this._apiUrl,branchId:this._branchId,demoMode:this._demoMode,deploymentMode:this._deploymentMode,requireActiveShiftForCash:this._requireActiveShiftForCash,maxCashAdjustmentAmount:this._maxCashAdjustmentAmount,requireShiftCloseApprovalOnDifference:this._requireShiftCloseApprovalOnDifference,shiftCloseDifferenceApprovalThreshold:this._shiftCloseDifferenceApprovalThreshold,requireReasonForReturnOperations:this._requireReasonForReturnOperations,requireApprovalForReturnRefund:this._requireApprovalForReturnRefund,requireApprovalForReturnCancel:this._requireApprovalForReturnCancel,requireLotExpiryForPurchaseReceiving:this._requireLotExpiryForPurchaseReceiving,lotConsumptionPolicy:this._lotConsumptionPolicy,enableCustomerCreditPolicy:this._enableCustomerCreditPolicy,customerCreditMaxOutstandingAmount:this._customerCreditMaxOutstandingAmount,customerCreditBlockOnOverdue:this._customerCreditBlockOnOverdue,customerCreditOverdueGraceDays:this._customerCreditOverdueGraceDays,customerCreditEscalationThresholdDays:this._customerCreditEscalationThresholdDays,enableReturnFraudGuard:this._enableReturnFraudGuard,returnFraudWindowMinutes:this._returnFraudWindowMinutes,returnFraudMaxEvents:this._returnFraudMaxEvents,returnFraudAction:this._returnFraudAction,returnApprovalBypassRoles:this._returnApprovalBypassRoles,returnApprovalApproverRoles:this._returnApprovalApproverRoles,allowPromotionStacking:this._allowPromotionStacking,promotionSelectionStrategy:this._promotionSelectionStrategy,promotionStackingOrder:this._promotionStackingOrder,pricingRoundingIncrement:this._pricingRoundingIncrement,pricingRoundingScope:this._pricingRoundingScope,enableSequentialDocumentNumbers:this._enableSequentialDocumentNumbers,syncProtocolVersion:this._syncProtocolVersion,syncCompatibleServerVersions:this._syncCompatibleServerVersions,enforceSyncProtocolHandshake:this._enforceSyncProtocolHandshake,onlineAuthMaxFailedAttempts:this._onlineAuthMaxFailedAttempts,onlineAuthLockoutSeconds:this._onlineAuthLockoutSeconds,drRpoTargetMinutes:this._drRpoTargetMinutes,drRtoTargetMinutes:this._drRtoTargetMinutes,backupIntervalMinutes:this._backupIntervalMinutes,backupRestoreDrillIntervalHours:this._backupRestoreDrillIntervalHours,opsAlertSyncFailureRateThresholdPercent:this._opsAlertSyncFailureRateThresholdPercent,opsAlertQueueLatencyThresholdMs:this._opsAlertQueueLatencyThresholdMs,opsAlertDeadLetterCountThreshold:this._opsAlertDeadLetterCountThreshold,opsAlertEscalationCooldownMinutes:this._opsAlertEscalationCooldownMinutes,auditLogRetentionDays:this._auditLogRetentionDays,auditLogArchiveBeforePurge:this._auditLogArchiveBeforePurge,auditLogPurgeBatchSize:this._auditLogPurgeBatchSize,sessionIdleTimeoutMinutes:this._sessionIdleTimeoutMinutes,sessionReauthTimeoutMinutes:this._sessionReauthTimeoutMinutes,apiTimeoutMs:this._apiTimeoutMs,syncIntervalMs:this._syncIntervalMs,syncMaxRetries:this._syncMaxRetries,syncBackoffDelayMs:this._syncBackoffDelayMs,syncDebounceMs:this._syncDebounceMs,reportingTopSellingLimit:this._reportingTopSellingLimit,reportingLowStockLimit:this._reportingLowStockLimit,apiBackupListLimit:this._apiBackupListLimit,encryptionKey:this._encryptionKey,encryptionPassphrase:this._encryptionPassphrase};return await this.storage.setItem("config",JSON.stringify(t)),t}};var fo="com.offlinepos.backup",kn=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=fo;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 Fn=class h{constructor(e,t={}){this.context=e;var r,n,i,a,o,s,c,u,l,d;this.context.integrationServices=this,this.activityLogger=(r=t.activityLogger)!=null?r:new Hr(this.context),this.config=(n=t.configService)!=null?n:new Bn(this.context),this.authorization=(i=t.authorizationService)!=null?i:new Vr(this.context),this.encryption=(a=t.encryptionService)!=null?a:new On(this.context),this.api=(o=t.apiService)!=null?o:new _n(this.context),this.sync=(s=t.syncService)!=null?s:new Mt,this.socket=(c=t.socketService)!=null?c:new qt,this.notification=(u=t.notificationService)!=null?u:new Tn(this.context),this.user=(l=t.userService)!=null?l:new Rn(this.context),this.backupScheduler=(d=t.backupScheduler)!=null?d:new kn(this.context,{setInterval(m,f){let y=setInterval(m,f);return{clear:()=>clearInterval(y)}}})}static async create(e,t={}){let r=new h(e,t);return r.config.init&&await r.config.init(),r}async shutdown(){var n;let e=this.sync;e&&typeof e.shutdown=="function"&&await e.shutdown();let t=this.socket;if(t&&typeof t.shutdown=="function")t.shutdown();else if(t&&typeof t.getSocket=="function"){let i=t.getSocket();(n=i==null?void 0:i.disconnect)==null||n.call(i)}let r=this.backupScheduler;r&&typeof r.stop=="function"&&r.stop()}};var Ba=[{toVersion:1,up:async h=>{for(let e of At)await h.addTable(e)}}];async function ka(h,e){if(typeof h.getSchemaVersion!="function"||typeof h.setSchemaVersion!="function"){let t="Adapter does not support schema versioning (getSchemaVersion/setSchemaVersion required)";throw e.logError(new Error(t),{message:t}),new Error(t)}e.logInfo("Starting database migration process");try{let t=await h.getSchemaVersion();(t==null||t<0)&&(t=0);let r=[...Ba].sort((i,a)=>i.toVersion-a.toVersion),n=r.length>0?r[r.length-1].toVersion:0;if(t>=n){e.logInfo(`Database is already up-to-date at v${t}`);return}e.logInfo(`Migrating database from v${t} to v${n}`);for(let i of r)i.toVersion>t&&(e.logInfo(`Applying migration: v${i.toVersion}`),await i.up(h),await h.setSchemaVersion(i.toVersion),t=i.toVersion);e.logInfo("Database migration completed successfully")}catch(t){throw e.logError(t,{message:"Database migration failed"}),t}}var go={isLoggedIn:!1,userId:null,user:null,lastLoginAt:null,tenantId:null},Mn=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=wt(),this.state={...go},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 Lt=class{constructor(){this.eventBus=Le;this.domainServiceOverrides={};this.integrationServiceOverrides={};this.pluginSpecs=[];this.authBridgePolicyMode="bridge-required";this.runtimeStateStore=bo({phase:"idle",started:!1,startCount:0,stopCount:0,lastError:null,lastTransitionAt:new Date().toISOString()}),this.runtimeStore=vo(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:{...Et}}subscribeDomainChangeQueue(e){return this.syncStore?this.syncStore.subscribe(e):(e({...Et}),()=>{})}getQueuedDomainChanges(){return[...this.getDomainChangeQueueState().queue]}enqueueDomainChange(e){var t;if(this.domainChangeSink){this.domainChangeSink(e);return}(t=this.syncStore)==null||t.enqueueChange(e)}removeDomainQueuedChange(e){var t;(t=this.syncStore)==null||t.removeQueuedChange(e)}setDomainChangeSink(e){this.domainChangeSink=e}getSessionStore(){return this.sessionStore}get session(){var e;return(e=this.sessionStore)==null?void 0:e.getState()}static builder(){return new ni}use(e,t,r=[]){if(this.pluginSpecs.some(i=>i.name===e))return this;let n={name:e,init:t,deps:r};return this.pluginSpecs.push(n),this.runtime.use(e,async()=>{await t(this)},r),this}async stop(){this.runtimeStateStore.setState({phase:"stopping",started:this.runtime.isStarted(),lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.stop(),this.runtimeStateStore.setState(e=>({...e,phase:"stopped",started:!1,stopCount:e.stopCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(e){throw this.runtimeStateStore.setState({phase:"error",started:this.runtime.isStarted(),lastError:e instanceof Error?e.message:String(e),lastTransitionAt:new Date().toISOString()}),e}}async reset(){await this.stop(),this.domainServices=void 0,this.integrationServices=void 0,this.syncStore=void 0,this.sessionStore=void 0,this.pluginSpecs=[],this.domainServiceOverrides={},this.integrationServiceOverrides={},this.runtime=this.createRuntime()}async restart(){let e=[...this.pluginSpecs],t={...this.domainServiceOverrides},r={...this.integrationServiceOverrides};await this.reset(),this.domainServiceOverrides=t,this.integrationServiceOverrides=r,this.runtime=this.createRuntime();for(let n of e)this.use(n.name,n.init,n.deps);return this.start()}async init(e={runMigrations:!0}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.init({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}async start(e={}){this.runtimeStateStore.setState({phase:"starting",started:!1,lastError:null,lastTransitionAt:new Date().toISOString()});try{await this.runtime.start({runMigrations:e.runMigrations,useSeedData:this.resolveUseSeedData(e)}),this.runtimeStateStore.setState(t=>({...t,phase:"started",started:!0,startCount:t.startCount+1,lastError:null,lastTransitionAt:new Date().toISOString()}))}catch(t){throw this.runtimeStateStore.setState({phase:"error",started:!1,lastError:t instanceof Error?t.message:String(t),lastTransitionAt:new Date().toISOString()}),t}}checksum(e){return Rr(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=yo.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 ka(t,r)},onInit:async()=>{!this.domainChangeSink&&!this.syncStore&&(this.syncStore=new Ur(this)),this.sessionStore||(this.sessionStore=new Mn(this))},createDomainServices:()=>(this.domainServices||(this.domainServices=new Qr(this,this.domainServiceOverrides)),this.domainServices),createIntegrationServices:async()=>(this.integrationServices||(this.integrationServices=await Fn.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)}},ni=class{constructor(){this.core=new Lt;this.adapterOpts={};this.syncOrchestrationMode="host-managed"}withPlatformAdapter(e){return this.adapterOpts.platformAdapter=e,this}withDbAdapter(e){return this.adapterOpts.dbAdapter=e,this}withLoggerAdapter(e){return this.adapterOpts.loggerAdapter=e,this}withHttpAdapter(e){return this.adapterOpts.httpAdapter=e,this}withHttpRetryPolicy(e){return this.adapterOpts.httpRetryPolicy=e,this}withSocketAdapter(e){return this.adapterOpts.socketAdapter=e,this}withEncryptionAdapter(e){return this.adapterOpts.encryptionAdapter=e,this}withChecksumAdapter(e){return this.adapterOpts.checksumAdapter=e,this}withActivitySink(e){return this.adapterOpts.activitySink=e,this}withNotificationAdapter(e){return this.adapterOpts.notificationAdapter=e,this}withExportAdapter(e){return this.adapterOpts.exportAdapter=e,this}withStorageAdapter(e){return this.adapterOpts.storageAdapter=e,this}overrideDomainServices(e){return this.core.domainServiceOverrides={...this.core.domainServiceOverrides,...e},this}overrideIntegrationServices(e){return this.core.integrationServiceOverrides={...this.core.integrationServiceOverrides,...e},this}withSyncOrchestrationMode(e){return this.syncOrchestrationMode=e,this}withDomainChangeSink(e){return this.core.setDomainChangeSink(e),this}disableInternalSyncOrchestration(){return this.syncOrchestrationMode="host-managed",this}applySyncOrchestrationMode(){var e,t;if(this.syncOrchestrationMode!=="host-managed")throw new Error("Only host-managed sync orchestration is supported");this.core.integrationServiceOverrides={...this.core.integrationServiceOverrides,syncService:(e=this.core.integrationServiceOverrides.syncService)!=null?e:new Mt,socketService:(t=this.core.integrationServiceOverrides.socketService)!=null?t:new qt}}build(e={runMigrations:!0}){return this.applySyncOrchestrationMode(),this.core.registry=new qn(this.core,this.adapterOpts),this.core}};import{InMemoryDbAdapter as $a}from"ofcore";import{DefaultExportAdapter as ii}from"ofcore";import{ConsoleLoggerAdapter as ai}from"ofcore";import{NoopActivitySink as oi,MemoryActivitySink as Kg}from"ofcore";import{NoopEncryptionAdapter as Fa}from"ofcore";import{NoopChecksumAdapter as Ma}from"ofcore";import{NoopNotificationAdapter as si}from"ofcore";var Ln=Ot(ei()),Nn=class{constructor(e){this.context=e}encrypt(e,t){let r=this.resolveSecretKey(t);return Ln.default.AES.encrypt(String(e!=null?e:""),r).toString()}decrypt(e,t){let r=this.resolveSecretKey(t);return Ln.default.AES.decrypt(String(e!=null?e:""),r).toString(Ln.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 Ua=Ot(La()),Ha=Ot(Ft()),ui=Ot(Qa()),Hn=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,Ua.default)(t,i).toString(ui.default):""}return e.algorithm==="sha256"?(0,Ha.default)(t).toString(ui.default):""}verify(e,t){let r=String(this.compute(e)||"").trim().toLowerCase(),n=String(t||"").trim().toLowerCase();return r===n}};import{DefaultPlatformAdapter as Va}from"ofcore";import{InMemorySocketAdapter as ci}from"ofcore";var qn=class{constructor(e,t={}){this.context=e;this.opts=t;this.context.registry=this,this.platformAdapter=this.resolveAdapter(t.platformAdapter,Va),this.dbAdapter=this.resolveAdapter(t.dbAdapter,$a),this.loggerAdapter=this.resolveAdapter(t.loggerAdapter,ai),this.httpAdapter=this.resolveAdapter(t.httpAdapter,ti),this.httpRetryPolicy=this.resolveAdapter(t.httpRetryPolicy,ri),this.socketAdapter=this.resolveAdapter(t.socketAdapter,ci),this.activitySink=this.resolveAdapter(t.activitySink,oi),this.encryptionAdapter=this.resolveAdapter(t.encryptionAdapter,Nn),this.checksumAdapter=this.resolveAdapter(t.checksumAdapter,Hn),this.notificationAdapter=this.resolveAdapter(t.notificationAdapter,si),this.exportAdapter=this.resolveAdapter(t.exportAdapter,ii),this.storageAdapter=this.resolveAdapter(t.storageAdapter,yt)}resolveAdapter(e,t){if(!e)return new t(this.context);if(typeof e=="object")return e;if(typeof e=="function"&&e.prototype===void 0)try{return e(this.context)}catch{}let r=e,i=(Reflect.getMetadata("design:paramtypes",r)||[]).map(a=>{if(a===Lt)return this.context;if(a===Va)return this.platformAdapter;if(a===$a)return this.dbAdapter;if(a===ai)return this.loggerAdapter;if(a===ti)return this.httpAdapter;if(a===ri)return this.httpRetryPolicy;if(a===ci)return this.socketAdapter;if(a===oi)return this.activitySink;if(a===Fa)return this.encryptionAdapter;if(a===Ma)return this.checksumAdapter;if(a===si)return this.notificationAdapter;if(a===ii)return this.exportAdapter;if(a===yt)return this.storageAdapter});return new r(...i)}};import{InMemoryDbAdapter as nv}from"ofcore";import{DefaultPlatformAdapter as Fy}from"ofcore";import{isFailureEnvelope as Ly}from"ofcore";import{isContractVersionCompatible as Uy}from"ofcore";var za=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(de,{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(de,{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 ja=class{constructor(e){this.context=e;var t;this.pricingService=(t=this.context.domainServices)==null?void 0:t.pricing}async calculateTransactionTotals(e,t,r){let{calculateOrderTotal:n,calculatePPN:i,calculatePPH:a}=this.pricingService,{items:o,subTotal:s,discount:c,total:u}=await n(e,t,r),[l,d]=await Promise.all([i(u),a(u)]);return{pricedItems:o,subTotal:s,discount:c,total:u,ppn:l,pph:d,totalWithTax:u+l+d,payableToSeller:u+l-d}}};function zy(h){var t,r;let e=h.sale.date||new Date().toISOString();return{context:{journalId:(t=h.journalId)!=null?t:`journal-sale-${h.sale.id}`,tenantId:h.tenantId,branchId:h.branchId,occurredAt:e,reference:`${(r=h.referencePrefix)!=null?r:"sale"}:${h.sale.id}`},input:{grossAmount:h.sale.total,discountAmount:h.sale.discount,taxAmount:h.sale.ppn,scopedAccountMapping:h.scopedAccountMapping}}}export{Hr as ActivityLogger,qn as AdapterRegistry,_n as ApiService,Vr as AuthorizationService,kn as BackupScheduler,mo as CONFLICT_POLICY_MATRIX,Or as CURRENT_SYNC_PROTOCOL_VERSION,qr as CartService,Mr as CartStore,Kt as CategoryService,Bn as ConfigService,ai as ConsoleLoggerAdapter,Wt as CustomerGroupService,Gt as CustomerService,Si as DEFAULT_GRANULAR_AUTH_POLICY,Wn as DEFAULT_SYNC_COMPATIBLE_SERVER_VERSIONS,ii as DefaultExportAdapter,ti as DefaultHttpAdapter,Fy as DefaultPlatformAdapter,Qr as DomainServices,On as EncryptionService,Dr as ExpenseService,Ff as ExponentialBackoffHttpPolicy,_r as ExportService,Ir as FinancialSettingService,Yt as HistoryService,nv as InMemoryDbAdapter,ci as InMemorySocketAdapter,Fn as IntegrationServices,yr as InventoryLogService,Er as InventoryService,Kg as MemoryActivitySink,yt as MemoryStorage,ri as NoRetryHttpPolicy,oi as NoopActivitySink,Ma as NoopChecksumAdapter,Fa as NoopEncryptionAdapter,si as NoopNotificationAdapter,qt as NoopSocketService,Mt as NoopSyncService,Tn as NotificationService,Xt as OrderService,ym as POS_DOMAIN_TABLES,Cr as PayableService,Lt as PosCore,vr as PriceHistoryService,Jt as PriceTierService,Tr as PricingService,er as ProductService,tr as PromotionService,mr as PurchaseOrderService,fr as PurchaseService,Pr as ReceivableService,Sr as ReportScheduleService,Fr as ReportingService,rr as ReturnService,$r as RoleAdapter,ar as SaleService,Mn as SessionStore,wr as SettlementService,sr as ShiftService,Ta as SocketService,Ar as StockAdjustmentService,br as StockOpnameService,pr as SupplierService,_a as SyncService,Ur as SyncStore,fo as TASK_ID,Lr as TaxService,cr as TransactionService,za as UIProductService,ja as UITransactionService,dr as UomService,Rn as UserService,ka as applyPendingMigrations,Fe as bomTable,et as categoryTable,Rr as computeChecksum,$ as createChangeQueuePort,tt as customerGroupTable,Ye as customerTable,Le as eventBus,Ra as executeHttpRequestWithRetry,ot as expenseTable,Ve as financialSettingTable,bm as getSyncProtocolContract,ae as historyTable,go as initialSessionState,Et as initialState,Ee as inventoryLogTable,Uy as isContractVersionCompatible,Ly as isFailureEnvelope,vi as isServerProtocolCompatible,fi as kitchenTicketItemTable,Gn as kitchenTicketTable,Rt as loyaltyAccountTable,gt as loyaltyLedgerTable,Ba as migrations,Ae as orderItemTable,oe as orderTable,ge as payableTable,Ze as priceHistoryTable,Ue as priceTierTable,de as productTable,zy as projectScopedPosSaleFinance,rt as promotionTable,De as purchaseItemTable,$e as purchaseOrderItemTable,_e as purchaseOrderTable,Ie as purchaseTable,he as receivableTable,at as reportScheduleTable,Re as returnItemTable,Se as returnTable,Pe as roleTable,fe as saleItemTable,ue as saleTable,At as schemas,Qe as settlementTable,me as shiftTable,it as stockAdjustmentTable,Me as stockOpnameItemTable,Ce as stockOpnameTable,Xe as supplierTable,we as taxRateTable,J as transactionTable,nt as uomTable,He as userTable};
|
|
18
18
|
/*! For license information please see index.browser.mjs.LEGAL.txt */
|