@questwork/q-store-model 0.1.44 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/q-store-model.cjs +2 -2
- package/dist/q-store-model.esm.js +1588 -1162
- package/dist/q-store-model.iife.js +2 -2
- package/dist/q-store-model.umd.js +2 -2
- package/dist/v2/evaluation/acquisition.d.ts +48 -0
- package/dist/v2/evaluation/effectiveRules.d.ts +7 -0
- package/dist/v2/evaluation/index.d.ts +4 -0
- package/dist/v2/evaluation/ruleEvaluators.d.ts +48 -0
- package/dist/v2/evaluation/shared.d.ts +28 -0
- package/dist/v2/index.d.ts +11 -0
- package/dist/v2/internal/StoreContract.d.ts +10 -0
- package/dist/v2/internal/StoreContractValidationError.d.ts +9 -0
- package/dist/v2/internal/StoreEntity.d.ts +12 -0
- package/dist/v2/internal/validation.d.ts +12 -0
- package/dist/v2/models/AcquisitionSnapshot.d.ts +5 -0
- package/dist/v2/models/Category.d.ts +5 -0
- package/dist/v2/models/Currency.d.ts +5 -0
- package/dist/v2/models/EligibilityFact.d.ts +4 -0
- package/dist/v2/models/Merchandise.d.ts +5 -0
- package/dist/v2/models/MerchandiseComponent.d.ts +4 -0
- package/dist/v2/models/PriceEvaluationContext.d.ts +4 -0
- package/dist/v2/models/PriceMatchCriteria.d.ts +4 -0
- package/dist/v2/models/PriceRow.d.ts +4 -0
- package/dist/v2/models/PriceSchedule.d.ts +5 -0
- package/dist/v2/models/PriceScheduleRef.d.ts +4 -0
- package/dist/v2/models/Product.d.ts +5 -0
- package/dist/v2/models/PublishedRule.d.ts +5 -0
- package/dist/v2/models/PublishedRuleRef.d.ts +4 -0
- package/dist/v2/models/RefundPolicy.d.ts +5 -0
- package/dist/v2/models/RefundPolicyRef.d.ts +4 -0
- package/dist/v2/models/RequirementPlan.d.ts +4 -0
- package/dist/v2/models/SalesPeriod.d.ts +5 -0
- package/dist/v2/models/SalesPeriodRef.d.ts +4 -0
- package/dist/v2/models/Variant.d.ts +5 -0
- package/dist/v2/models/VariantRef.d.ts +4 -0
- package/dist/v2/models/WalletItem.d.ts +5 -0
- package/dist/v2/models/index.d.ts +24 -0
- package/dist/v2/models/ruleDetails/EligibilityRuleDetails.d.ts +4 -0
- package/dist/v2/models/ruleDetails/InventoryRuleDetails.d.ts +4 -0
- package/dist/v2/models/ruleDetails/PrerequisiteRuleDetails.d.ts +4 -0
- package/dist/v2/models/ruleDetails/QuantityRuleDetails.d.ts +4 -0
- package/dist/v2/models/ruleDetails/RefundRuleDetails.d.ts +4 -0
- package/dist/v2/models/ruleDetails/RequirementDefinition.d.ts +4 -0
- package/dist/v2/models/ruleDetails/RequirementFieldDefinition.d.ts +4 -0
- package/dist/v2/models/ruleDetails/RequirementRuleDetails.d.ts +4 -0
- package/dist/v2/models/ruleDetails/index.d.ts +1 -0
- package/dist/v2/models/ruleDetails/shared.d.ts +8 -0
- package/dist/v2/q-store-model-v2.cjs +2 -0
- package/dist/v2/q-store-model-v2.esm.js +1855 -0
- package/dist/v2/ruleVocabulary.d.ts +75 -0
- package/package.json +14 -6
package/dist/q-store-model.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("@questwork/q-utilities"),B=require("lodash");class p{constructor(t={}){t=t||{},this.currencyCode=t.currencyCode||t.currency,this.value=t.value,this.default=t.default||0}static dummyData(){return{currencyCode:"USD",value:100}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Amount"}static get _superclass(){return"Amount"}static getAmountsByCurrency(t,e){return t.filter(r=>r.currencyCode===e)}static getAmountsByCurrencyCode(t,e){return t.filter(r=>r.currencyCode===e)}get isValid(){return typeof this.currencyCode=="string"&&!!this.currencyCode&&typeof this.value=="number"}displayAmount(t){return!this.value===0?t||"":`${this.currencyCode}${this.value}`}getCurrencyCode(){return this.currencyCode}update(t){return Object.keys(t).forEach(e=>{this[e]=t[e]}),this}}function j(s,t){return ce(t).map(i=>i.reduce((n,a)=>{if(n.qty===0)return n;let u;a.recursing?u=bt:u=ue;const c=u(a,s);return n.value+=c.value,n.qty=c.qty,n.priceStrategy=c.priceStrategy,n},{priceStrategy:null,value:0,qty:s}))}function ue(s,t){const e=s;if(t<e.min)return{value:0,qty:t};const r=s.max===null?t:Math.min(s.max,t);return{priceStrategy:e.priceStrategy,value:wt(s,r),qty:s.max===null||s.max>=t?0:t-s.max}}function bt(s,t,e=0,r=0){const i=s;if(t<i.min)return{amount:0,qty:t};const n=wt(s,s.min),a=t-s.min;return a===0||s.max!==null&&s.max-a<s.min?{priceStrategy:i.priceStrategy,value:r+r,qty:a}:bt(s,a,e+s.min,r+n)}function wt(s,t){const e=s.value*t*(1-s.discount)-s.deduction;return e<0?0:e}function ce(s=[]){const t=[],e=[];function r(i){let n,a;for(n=0;n<i.length;n++)a=i.splice(n,1)[0],e.push(a),i.length===0&&t.push(e.slice()),r(i),i.splice(n,0,a),e.pop();return t}return r(s)}class I{constructor(t={}){t=t||{},this.options=t}addException(t,e){return this.chainManager.addException(t,e),this}exitChain(t){}async handleRequest(t){throw new Error("should implement by subclass")}hasException(){return this.chainManager.hasException()}async next(t){return this.chainManager.exitOnErr&&t.hasException()?this.exitChain(t):(this.successor&&await this.successor.handleRequest(t),this.exitChain(t))}setChainManager(t){return this.chainManager=t,this}setSuccessor(t){return this.successor=t,this}}class lt{constructor(t){t=t||{},this.exitOnErr=t.exitOnErr||!1,this.runAllChains=typeof t.runAllChains<"u"?!!t.runAllChains:!0,this.chains=t.chains||[],this.chainTarget=t.chainTarget}appendChains(t){return t.forEach(e=>{e.setChainManager(this);const r=this.chains.length;r>0&&t[r-1].setSuccessor(e),this.chains.push(e)}),this}addException(t,e){if(typeof e>"u")return this.exceptionHandler.setProp(t),this;const r=this.exceptionHandler.getResult(t);return Array.isArray(r)?this.exceptionHandler.setProp({[t]:r.concat(e)}):this.exceptionHandler.setProp({[t]:Array.isArray(e)?e:[e]}),this}createChains({chains:t=[]}={}){if(t.find(e=>!(e instanceof I)))throw new Error("every chain must be an instance of Chain");return this.appendChains(t)}getResult(){const t={data:this.chainTarget.getResult()};return this.chainTarget.hasException()&&(t.err=this.chainTarget.getException()),t}async handleRequest(){await this.chains[0].handleRequest(this.chainTarget)}hasException(){return this.exceptionHandler.isNotEmpty()}resetHandlers(){return this.exceptionHandler.clear(),this.resultHandler.clear(),this}}class de{constructor(){this.result={}}getResult(t){return t?this.result[t]:this.result}isNotEmpty(){return Object.keys(this.result).length>0}reset(){return this.result={},this}setProp(t){return this.result=Object.assign(this.result,t),this}unsetProp(t){return typeof this.result[t]<"u"&&delete this.result[t],this}}class ht{constructor(t){t=t||{},this.exceptionHandler=t.exceptionHandler||new de}addException(t,e){if(typeof e>"u")return this.exceptionHandler.setProp(t),this;const r=this.exceptionHandler.getResult(t),i=e instanceof Error?e.message:e;return Array.isArray(r)?this.exceptionHandler.setProp({[t]:r.concat(i)}):this.exceptionHandler.setProp({[t]:Array.isArray(i)?i:[i]}),this}getException(){return this.exceptionHandler.getResult()}getResult(){throw new Error("should implement by subclass")}hasException(){return this.exceptionHandler.isNotEmpty()}reset(){return this.exceptionHandler.reset(),this}setProp(t){return Object.assign(this,t),this}unsetProp(t){return t!=="exceptionHandler"&&typeof this[t]<"u"&&delete this[t],this}}function mt({coupon:s,price:t,currencyCode:e}){const{couponDetails:r}=s;if(!r)return 0;const{type:i,item:n}=r;if(n)switch(i){case"Deduction":return oe({price:t,couponDetails:r,currencyCode:e});case"Percentage":return le({price:t,couponDetails:r});default:return 0}}function oe({price:s,couponDetails:t,currencyCode:e}){const{value:r}=t;return o.KeyValueObject.foundValueByKey(r,e)}function le({price:s,couponDetails:t}){const{value:e}=t;return s.value*(e/100)}class he extends I{constructor(t={}){super(t),this.groupCategory=t.groupCategory,this.categories=t.categories,this.walletItems=t.walletItems}async handleRequest(t){try{const{lines:e,users:r}=t,i=me(this.categories,this.walletItems);e.forEach(n=>{pe(n,i)}),await this.next(t)}catch(e){t.addException("calculate categories limit fail",e.message),this.exitChain()}}}function me(s=[],t=[]){return s.reduce((e,r)=>{const{categoryCode:i,codes:n,name:a,max:u,min:c,productCodes:d=[]}=r,l=t.filter(h=>h.status.cancelled!==null?!1:d.includes(h.productCode));return e.push({categoryCode:i,codes:n,max:u,min:c,name:a,owned:l.length,productCodes:d,used:0}),e},[])}function pe(s,t){const{productsQty:e,updatedItem:r}=s;Object.keys(e).forEach(i=>{const n=t.find(a=>a.productCodes.includes(i)&&a.codes.includes(r.merchandiseCode));if(n){const a=n.max-(n.used+n.owned);if(a===0)r.qty=0,s.disabled=!0;else{e[i]*r.qty>a&&(r.qty=0,s.errors.push(`You have exceeded the maximum number of category "${n.name}".`));const c=fe(r,a,e[i]);n.used+=c}}})}function fe(s,t,e){let r;const i=e*s.qty;return t-i>=0?r=i:(s.qty=t,r=t),r}class ye extends I{constructor(t={}){super(t),this.currency=t.currency,this.dateTime=t.dateTime,this.entitlements=t.entitlements||[],this.merchandises=t.merchandises}async handleRequest(t){try{const{lines:e,user:r}=t,i=B.cloneDeep(this.entitlements);e.forEach(n=>{const a=Ae(n,this.dateTime),u=ve(a,n,r),c=Ce(this.currency.code,u,n),d=_e(c,this.currency.code,n);Object.assign(n.updatedItem,d||{})}),ge(e,i,this.currency.code),await this.next(t)}catch(e){t.addException("get price fail",e.message),this.exitChain()}}}function ge(s,t=[],e){Array.from(s).sort((i,n)=>n.updatedItem.price&&i.updatedItem.price?n.updatedItem.price.value-i.updatedItem.price.value:1).forEach(i=>{const{merchandise:n,updatedItem:a}=i,{priceStrategies:u=[],qty:c}=a,{merchandiseCode:d,productCodes:l}=n,{waived:h,entitlementsRemarkValue:m}=Oe(t,l,c),f=u.map(F=>F.toCalculatorRule({currencyCode:e})),y=c-h;let g=j(y,f);g.length===0&&(a.qty=0,i.disabled=!0,i.errors.push("No available price.")),g=(g||[]).sort((F,dt)=>F.value-dt.value);const[C={}]=g;C.qty>0&&i.errors.push("Exceed maximum quantity per transaction."),C.qty<0&&i.errors.push("No available price.");const{priceStrategy:_,value:v}=C,b=_||u[0],w=p.init(b?b.getAmountByCurrencyCode(e):null),S=p.init({value:v,currencyCode:e}),at=(w?w.value:0)*y-(S?S.value:0)+(w?w.value:0)*h,ut=p.init({value:at,currencyCode:e});let x=o.KeyValueObject.initOnlyValidFromArray([...a.remarks||[]]);x=o.KeyValueObject.updateOrInsertRecord(x,"entitlements",m);let M=o.Metadata.initOnlyValidFromArray([...a.metadata||[]]);M=o.Metadata.updateOrInsertRecord(M,"entitlements",m);const ct={merchandiseCode:d,price:w,discount:ut,subTotal:S,qty:c,waived:h,remarks:x,metadata:M,priceStrategies:u,priceStrategy:b};Object.assign(i.updatedItem,ct)})}function Ce(s,t,e){if(t.length===0)return[];const{updatedItem:r}=e,i=t.filter(n=>n.hasCurrencyCode(s));return i.length===0&&(r.qty=0,e.disabled=!0,e.errors.push(`Not support currency "${s}".`)),i}function _e(s,t,e){if(s.length===0)return null;const{merchandise:r,updatedItem:i}=e,{qty:n}=i,{merchandiseCode:a}=r,u=s.map(_=>_.toCalculatorRule({currencyCode:t}));let c=j(n,u);if(c.length===0)return i.qty=0,e.disabled=!0,e.errors.push("No available price."),null;c=c.sort((_,v)=>_.value-v.value);const[d={}]=c;if(d.qty>0)return e.errors.push("Exceed maximum quantity per transaction."),null;if(d.qty<0)return e.errors.push("No available price."),null;const{priceStrategy:l,value:h}=d,m=l||s[0],f=p.init(m.getAmountByCurrencyCode(t)),y=p.init({value:h,currencyCode:t}),g=f.value*n-y.value,C=p.init({value:g,currencyCode:t});return{merchandiseCode:a,price:f,discount:C,subTotal:y,qty:n,priceStrategies:s,priceStrategy:m}}function Oe(s,t,e){if(s.length===0)return{waived:0,entitlementsRemarkValue:[]};const r=Array.from({length:e}).map(()=>[...t]),{waived:i,entitlementsRemarkValue:n}=r.reduce((a,u)=>{if(a.continue===!1)return a;const{entitlementKeyValues:c}=u.reduce((d,l)=>{const h=s.findIndex(m=>(m.value||[]).includes(l));if(h!==-1){const[m]=s.splice(h,1);d.cutEntitlements.push(m),d.entitlementKeyValues.push({key:l,value:m.key})}return d},{cutEntitlements:[],entitlementKeyValues:[]});return u.length!==c.length?a.continue=!1:(a.waived+=1,a.entitlementsRemarkValue.push(...c)),a},{continue:!0,waived:0,entitlementsRemarkValue:[]});return{waived:i,entitlementsRemarkValue:n}}function Ae(s,t){const{merchandise:e,updatedItem:r}=s,i=e.getPricesByTime(t);return i.length===0&&(r.qty=0,s.disabled=!0,s.errors.push("Currently not available for sale.")),i.sort((n,a)=>n.dateBegin-a.dateBegin)}function ve(s,t,e){const{updatedItem:r}=t;let i=[];return s.length!==0&&(i=s.reduce((n,a)=>{const u=a.getStrategiesByRestrictions({user:e});return n.concat(u)},[])),i.length===0&&(r.qty=0,t.available=!1,t.errors.push("You are not entitled to this item.")),i}class be extends I{constructor(t={}){super(t),this.currency=t.currency,this.dateTime=t.dateTime,this.entitlements=t.entitlements||[],this.merchandises=t.merchandises}async handleRequest(t){try{const{lines:e}=t,r=B.cloneDeep(this.entitlements);e.forEach(i=>{const n=Re(i,this.dateTime),a=Ve(n),u=Ie(this.currency.code,a,i),c=Pe(u,this.currency.code,i);Object.assign(i.updatedItem,c||{})}),we(e,r,this.currency.code),await this.next(t)}catch(e){t.addException("get price fail",e.message),this.exitChain()}}}function we(s,t=[],e){Array.from(s).sort((i,n)=>n.updatedItem.price.value-i.updatedItem.price.value).forEach(i=>{const{merchandise:n,updatedItem:a}=i,{priceStrategies:u,qty:c}=a,{merchandiseCode:d,productCodes:l}=n,{waived:h,entitlementsRemarkValue:m}=Se(t,l,c),f=u.map(F=>F.toCalculatorRule({currencyCode:e}));It({rules:f,max:9999});const y=c-h;let g=j(y,f);g.length===0&&(a.qty=0,i.disabled=!0,i.errors.push("No available price.")),g=g.sort((F,dt)=>F.value-dt.value);const[C={}]=g;C.qty>0&&i.errors.push("Exceed maximum quantity per transaction."),C.qty<0&&i.errors.push("No available price.");const{priceStrategy:_,value:v}=C,b=_||u[0],w=p.init(b.getAmountByCurrencyCode(e)),S=p.init({value:v,currencyCode:e}),at=w.value*y-S.value+w.value*h,ut=p.init({value:at,currencyCode:e});let x=o.KeyValueObject.initOnlyValidFromArray([...a.remarks||[]]);x=o.KeyValueObject.updateOrInsertRecord(x,"entitlements",m);let M=o.Metadata.initOnlyValidFromArray([...a.metadata||[]]);M=o.Metadata.updateOrInsertRecord(M,"entitlements",m);const ct={merchandiseCode:d,price:w,discount:ut,subTotal:S,qty:c,waived:h,remarks:x,metadata:M,priceStrategies:u,priceStrategy:b};Object.assign(i.updatedItem,ct)})}function Ie(s,t,e){if(t.length===0)return[];const{updatedItem:r}=e,i=t.filter(n=>n.hasCurrencyCode(s));return i.length===0&&(r.qty=0,e.disabled=!0,e.errors.push(`Not support currency "${s}".`)),i}function Pe(s,t,e){if(s.length===0)return null;const{merchandise:r,updatedItem:i}=e,{qty:n}=i,{merchandiseCode:a}=r,u=s.map(_=>_.toCalculatorRule({currencyCode:t}));It({rules:u,max:9999});let c=j(n,u);if(c.length===0)return i.qty=0,e.disabled=!0,e.errors.push("No available price."),null;c=c.sort((_,v)=>_.value-v.value);const[d={}]=c;if(d.qty>0)return e.errors.push("Exceed maximum quantity per transaction."),null;if(d.qty<0)return e.errors.push("No available price."),null;const{priceStrategy:l,value:h}=d,m=l||s[0],f=p.init(m.getAmountByCurrencyCode(t)),y=p.init({value:h,currencyCode:t}),g=f.value*n-y.value,C=p.init({value:g,currencyCode:t});return{merchandiseCode:a,price:f,discount:C,subTotal:y,qty:n,priceStrategies:s,priceStrategy:m}}function Se(s,t,e){if(s.length===0)return{waived:0,entitlementsRemarkValue:[]};const r=Array.from({length:e}).map(()=>[...t]),{waived:i,entitlementsRemarkValue:n}=r.reduce((a,u)=>{if(a.continue===!1)return a;const{entitlementKeyValues:c}=u.reduce((d,l)=>{const h=s.findIndex(m=>(m.value||[]).includes(l));if(h!==-1){const[m]=s.splice(h,1);d.cutEntitlements.push(m),d.entitlementKeyValues.push({key:l,value:m.key})}return d},{cutEntitlements:[],entitlementKeyValues:[]});return u.length!==c.length?a.continue=!1:(a.waived+=1,a.entitlementsRemarkValue.push(...c)),a},{continue:!0,waived:0,entitlementsRemarkValue:[]});return{waived:i,entitlementsRemarkValue:n}}function Re(s,t){const{merchandise:e,updatedItem:r}=s,i=e.getPricesByTime(t);return i.length===0&&(r.qty=0,s.disabled=!0,s.errors.push("Currently not available for sale.")),i.sort((n,a)=>n.dateBegin-a.dateBegin)}function Ve(s){return s.length===0?[]:s.reduce((e,r)=>{const i=r.priceStrategies;return e.concat(i)},[])}function It({rules:s,max:t}){return s.forEach(e=>{const r=e;r.max=t}),s}class Pt extends I{constructor(t={}){super(t)}async handleRequest(t){try{const{lines:e}=t;e.forEach(r=>{const{item:i={}}=r;r.updatedItem={...i,waived:0,remarks:o.KeyValueObject.initOnlyValidFromArray(i.remarks),metadata:o.Metadata.initOnlyValidFromArray(i.metadata),price:p.init(i.price),discount:p.init(i.discount),subTotal:p.init(i.subTotal),priceStrategy:null},r.available=!0,r.disabled=!1,r.errors=[],r.messages=[],r.validated=!0}),await this.next(t)}catch(e){t.addException("init lines fail",e.message),this.exitChain()}}}class St extends I{constructor(t={}){super(t)}async handleRequest(t){try{const{lines:e,users:r}=t;e.forEach(i=>{const{updatedItem:n,merchandise:a}=i,u=a.getStock();if(u===0)i.disabled=!0,i.errors.push("Full.");else{const{qty:c}=n;n.qty=c>u?u:c}}),await this.next(t)}catch(e){t.addException("calculate merchansises limit fail",e.message),this.exitChain()}}}class Ee extends I{constructor(t={}){super(t),this.currency=t.currency}async handleRequest(t){try{const{lines:e}=t;e.forEach(r=>{Te({line:r,currency:this.currency})}),await this.next(t)}catch(e){t.addException("handle related coupons fail",e.message),this.exitChain()}}}function Te({line:s,currency:t}){const{updatedItem:e}=s,{price:r,qty:i,discount:n,purchaseOptions:a,remarks:u,subTotal:c}=e;if(a.length===0||e.qty===0)return;const d=De(a);if(!d)return;const l=c.value+d*(t.factor||1),h={subTotal:p.init({value:l,currencyCode:t.code})};Object.assign(e,h)}function De(s){var t;for(const e of s){const r=(t=e.value)==null?void 0:t.find(i=>i.key==="priceAdjustment");if(r)return Number(r.value)}return null}class Rt extends I{constructor(t={}){super(t),this.products=t.products||[]}async handleRequest(t){try{const{lines:e,users:r}=t,i=Le(this.products);e.forEach(n=>{const{merchandise:a,productsQty:u,updatedItem:c}=n,{qty:d}=c;Object.keys(u).forEach(l=>{const h=u[l],m=i[l];if(!m)throw new Error(`Invalid merchandise "${a.name}": no productCode "${l}"`);const{name:f,stock:y,used:g}=m,C=y-g;if(C===0)c.qty=0;else{const _=h*d;if(C-_>0)m.used+=_;else{const b=Math.floor(C/h);b===0?(c.qty=0,n.disabled=!0,n.errors.push(`"${f}" does not have enough stock`)):(m.used+=b*h,c.qty=Math.min(c.qty,b))}}})}),await this.next(t)}catch(e){t.addException("calculate products limit fail",e.message),this.exitChain()}}}function Le(s){return s.reduce((t,e)=>{const{productCode:r,name:i,stock:n}=e;return t[r]={name:i,stock:n,used:0},t},{})}class xe extends I{constructor(t={}){super(t),this.products=t.products||[],this.walletItems=t.walletItems||[]}async handleRequest(t){try{const{lines:e,users:r}=t,i=this.walletItems.filter(u=>u.status.cancelled===null).map(u=>u.productCode),n=e.reduce((u,c)=>{const{merchandise:d,updatedItem:l}=c;return l.qty>0?u.concat(d.productCodes):u},[]),a=[...new Set(n.concat(i))];e.forEach(u=>{const{item:c,updatedItem:d,merchandise:l}=u,{productCodes:h}=l;this.products.filter(f=>h.includes(f.productCode)).forEach(f=>{const y=i.reduce((v,b)=>b===f.productCode?v+1:v,0);f.maxPerWallet>y||(u.disabled=!0);const[g=[]]=o.KeyValueObject.getValuesByKey(f.remarks,"restrictions"),[C=[]]=o.KeyValueObject.getValuesByKey(g,"requiredProductCodes");if(C.length===0)return;C.some(v=>a.includes(v))||(u.disabled=!0,d.qty=0)})}),await this.next(t)}catch(e){t.addException("check product restriction fail",e.message),this.exitChain()}}}class Me extends I{constructor(t={}){super(t)}async handleRequest(t){try{const{lines:e,users:r}=t;e.forEach(i=>{const{updatedItem:n}=i,{purchaseOptions:a=[]}=n;if(a.length===0||n.qty===0)return;let u=!1,c=!1;a.forEach(d=>{(d.value||[]).forEach(l=>{const{required:h,validated:m,value:f}=l;h&&!f&&!u&&(u=!0,i.validated=!1,i.errors.push("Please fill in the option(s).")),m&&!c&&(c=!0,i.errors.push("Invalid option(s)."))})})}),await this.next(t)}catch(e){t.addException("Check product restriction failed.",e.message),this.exitChain()}}}class Fe extends I{constructor(t={}){super(t),this.autoUseCoupon=t.autoUseCoupon||!1,this.currency=t.currency,this.walletItems=t.walletItems}async handleRequest(t){try{const{lines:e,relatedTotalCoupons:r=[],users:i}=t,n=this.walletItems.filter(a=>a.isCoupon);e.forEach(a=>{qe({line:a,currencyCode:this.currency.code}),Ue(a,n,this.autoUseCoupon,this.currency.code)}),e.forEach(a=>{Ne(a)}),Be({lines:e,currencyCode:this.currency.code,relatedTotalCoupons:r}),$e({lines:e,autoUseCoupon:this.autoUseCoupon,currencyCode:this.currency.code,relatedTotalCoupons:r}),await this.next(t)}catch(e){t.addException("handle related coupons fail",e.message),this.exitChain()}}}function $e({lines:s,autoUseCoupon:t,currencyCode:e,relatedTotalCoupons:r}){t&&r.forEach(i=>{const n=Vt(i,s,e);Object.assign(i,n)})}function Vt(s,t,e){const{availableCoupons:r,usedCoupons:i,product:n}=s;if(r.length>0&&t.filter(c=>n.isApplicableCoupon(c.merchandise)).reduce((c,d)=>{const{updatedItem:l={}}=d,{subTotal:h={}}=l;return h&&h.value&&(c+=h.value),c},0)>0){const[c]=r.splice(0,1);return c.setOnHold(),i.push(c),Et({lines:t,currencyCode:e,coupon:c}),Vt(s,t,e)}return s}function qe({line:s,currencyCode:t}){const{usedCoupons:e={},updatedItem:r}=s;Object.keys(e).forEach(i=>{e[i].forEach(n=>{const a=Tt({updatedItem:r,coupon:n,currencyCode:t});Object.assign(r,a)})})}function Be({lines:s,currencyCode:t,relatedTotalCoupons:e}){e.forEach(r=>{const{usedCoupons:i}=r;i.forEach(n=>{Et({lines:s,currencyCode:t,coupon:n})})})}function Et({lines:s,currencyCode:t,coupon:e}){const r=s.filter(u=>e.isApplicableCoupon(u.merchandise)),i=r.reduce((u,c)=>{const{price:d={},qty:l}=c.updatedItem||{};return u+=d.value*l},0),{couponDetails:n,walletItemCode:a}=e;if(n){const{type:u,total:c}=n,{value:d}=n;switch(u){case"Deduction":{const l=o.KeyValueObject.foundValueByKey(d,t);r.forEach(h=>{const{updatedItem:m}=h,{price:f,qty:y,discount:g,remarks:C,subTotal:_}=m,v=l*(f.value*y/i)+g.value,b=_.value>l?_.value-l:0,w=o.KeyValueObject.foundValueByKey(C,"USED_TOTAL_COUPONS")||[];w.push(a);const S={discount:p.init({value:v,currencyCode:t}),remarks:o.KeyValueObject.insertOrUpdateRecord(C,"USED_TOTAL_COUPONS",w),subTotal:p.init({value:b,currencyCode:t})};Object.assign(m,S)});break}case"Percentage":{r.forEach(l=>{const{updatedItem:h}=l,{price:m,qty:f,discount:y,remarks:g,subTotal:C}=h,_=m.value*(d/100)*f,v=_+y.value,b=C.value>_?C.value-_:0,w=o.KeyValueObject.foundValueByKey(g,"USED_TOTAL_COUPONS")||[];w.push(a);const S={discount:p.init({value:v,currencyCode:t}),remarks:o.KeyValueObject.insertOrUpdateRecord(g,"USED_TOTAL_COUPONS",w),subTotal:p.init({value:b,currencyCode:t})};Object.assign(h,S)});break}}}}function Tt({updatedItem:s,coupon:t,currencyCode:e}){const{couponDetails:r,walletItemCode:i}=t;if(!r)return s;const{price:n,qty:a,discount:u,remarks:c,subTotal:d}=s,l=mt({coupon:t,price:n,currencyCode:e}),h=l+u.value,m=d.value>l?d.value-l:0,f=o.KeyValueObject.foundValueByKey(c,"USED_ITEM_COUPONS")||[];return f.push(i),{...s,discount:p.init({value:h,currencyCode:e}),remarks:o.KeyValueObject.insertOrUpdateRecord(c,"USED_ITEM_COUPONS",f),subTotal:p.init({value:m,currencyCode:e})}}function Ne(s){const{relatedCoupons:t=[]}=s;s.relatedCoupons=t.map(e=>({...e,availableCoupons:e.coupons.filter(r=>!r.isOnHold)}))}function je(s,t,e,r){const{merchandise:i,usedCoupons:n={},updatedItem:a={}}=s;return t.filter(c=>c.isApplicableCoupon(i)&&c.isItemCoupon).reduce((c,d)=>{const l=d.product.productCode;let h=c.find(g=>g.productCode===l);const m=d.isOnHold;h||(h={coupons:[],product:d.product,productCode:l,usedQty:(n[l]||[]).length},c.push(h)),h.coupons.push(d);const{qty:f,subTotal:y}=a;if(e&&!m&&h.usedQty<f&&y.value>0){d.setOnHold(),n[l]=[...n[l]||[],d];const g=Tt({updatedItem:a,currencyCode:r,coupon:d});Object.assign(a,g),h.usedQty=n[l].length}return c},[])}function Ue(s,t,e,r){t.length>0&&(s.relatedCoupons=je(s,t,e,r))}class Ke extends ht{constructor(t={}){super(t),this.lines=t.lines,this.relatedTotalCoupons=t.relatedTotalCoupons,this.user=t.user}getResult(){return{lines:this.lines,relatedTotalCoupons:this.relatedTotalCoupons}}}class pt{static getChainManager({payload:t={},serviceAppName:e,type:r}={}){let i=[];switch(r){case"CALCULATE_AMOUNT":return i=He(t),this.calculateAmount({chains:i,payload:t,serviceAppName:e});case"CALCULATE_AMOUNT_FOR_GROUP":return i=We(t),this.calculateAmount({chains:i,payload:t,serviceAppName:e});default:throw new Error("invalid type")}}static calculateAmount({chains:t=[],payload:e={},serviceAppName:r}){const{lines:i,relatedTotalCoupons:n,user:a}=e,u=new Ke({lines:i,relatedTotalCoupons:n,user:a}),c=new lt({chainTarget:u});return c.createChains({chains:t}),c}}function He(s){const{autoUseCoupon:t,categories:e,currency:r,dateTime:i,entitlements:n,merchandises:a,products:u,walletItems:c}=s;return[new Pt,new he({categories:e,walletItems:c}),new xe({products:u,walletItems:c}),new Me,new St,new Rt({products:u}),new ye({currency:r,dateTime:i,entitlements:n,merchandises:a}),new Fe({currency:r,autoUseCoupon:t,walletItems:c}),new Ee({currency:r})]}function We(s){const{currency:t,dateTime:e,entitlements:r,merchandises:i,products:n}=s;return[new Pt,new St,new Rt({products:n}),new be({currency:t,dateTime:e,entitlements:r,merchandises:i})]}const Qe=Object.freeze(Object.defineProperty({__proto__:null,ChainManagerFactory:pt},Symbol.toStringTag,{value:"Module"}));function Dt({adminSettleFormData:s={},component:t,eventRegistration:e,invoice:r,payeeName:i,payeeAddress:n,payeeCountry:a,cb:u}){const c=e||t.registration;t.invoice=r,t.adminSettleFormData={...r,...s,email:c&&c.getEmail()||"",payeeName:i,payeeAddress:n,payeeCountry:a,paidDate:new Date().valueOf(),totalAmount:Ge(r)},u()}function Ge(s){if(!s.amount)return"";const{amount:t}=s;return`${t.currencyCode} ${(t.value/100).toFixed(2)}`}async function Lt(s){const{currency:t,merchandises:e=[],lines:r,products:i,user:n}=s,a={lines:r,merchandises:e,products:i,currency:t,dateTime:Date.now(),categories:[],entitlements:[],walletItems:[],user:{}},u=pt.getChainManager({payload:a,type:"CALCULATE_AMOUNT"});await u.handleRequest();const{data:c={},err:d}=u.getResult();if(d)throw d;if((c.lines||[]).find(m=>Array.isArray(m.errors)&&m.errors.length>0))throw new Error("has invalid line");return{data:c,err:d}}function ft(s){return s.charAt(0).toLowerCase()+s.slice(1)}function xt(s){const t=s.name,e=`${ft(t)}Type`;class r extends s{constructor(n){const a=n||{};super(a),this[e]=a[e]||`${t}Event`}get isValid(){return super.isValid}static init(n){const a=new r(n);return a.isValid?a:null}static dummyData(){return{...super.dummyData(),[e]:`${t}Event`}}}return r}function Mt(){class s{constructor(e){const r=e||{};this._type="Fake",this.fakeCode=r.fakeCode,this.fakeType=r.fakeType||"Fake"}static dummyData(){return{fakeCode:"fakeCode"}}static init(e){const r=new s(e);return r.isValid?r:null}get isValid(){return!!this.fakeCode}}return s}class ke{constructor(t={}){var e,r;this.mapping=(e=t.rule)==null?void 0:e.mapping,this.makeWalletItemHandler=t.makeWalletItemHandler,this.tiers=(r=t.rule)==null?void 0:r.tiers}get complimentaryCategories(){return this.mapping.map(t=>t.key)}get countableCategories(){const t=this.mapping.reduce((e,r)=>{const{value:i}=r;return Array.isArray(i)&&i.forEach(n=>e.add(n)),e},new Set);return Array.from(t)}process({walletItems:t}){const{complimentaryWalletItems:e,countableWalletItems:r}=ze({complimentaryCategories:this.complimentaryCategories,countableCategories:this.countableCategories,walletItems:t}),i=Je({tiers:this.tiers,total:r.length}),{toBeAssignedItems:n,entitlements:a}=Ye({complimentaryWalletItems:e,tier:i,countableWalletItems:r,mapping:this.mapping});return{walletItems:this.makeWalletItemHandler(n),entitlements:a,tier:i}}}function Ye({complimentaryWalletItems:s,tier:t,countableWalletItems:e,mapping:r}){const{numOfComplimentaryItem:i}=t,n=i-s.length,a=e.map(d=>d.productCode),u=s.reduce((d,l)=>{const{productCode:h}=l,m=d.get(h)||0;return d.set(h,m+1),d},new Map),c=[];if(n>0){const l=r.find(m=>{const{value:f}=m;return f.find(y=>a.includes(y))}).key,h=u.get(l)||0;u.set(l,h+n),c.push({productCode:l,qty:n})}return{toBeAssignedItems:c,entitlements:Array.from(u,([d,l])=>({productCode:d,qty:l}))}}function Je({tiers:s,total:t}){const e=[...s].sort((i,n)=>i.gte-n.gte);let r=e[0];return e.forEach(i=>{t>=i.gte&&(r=i)}),r}function ze({complimentaryCategories:s,countableCategories:t,walletItems:e}){return e.reduce((r,i)=>{const{productCode:n}=i;return s.includes(n)&&r.complimentaryWalletItems.push(i),t.includes(n)&&r.countableWalletItems.push(i),r},{complimentaryWalletItems:[],countableWalletItems:[]})}class Ft{constructor(t){this.makeWalletItemHandler=t.makeWalletItemHandler,this.rule=t.rule,this.type=t.type,this.handler=this.getHandler()}getHandler(){switch(this.type){case"TIER_MAPPING":return new ke({rule:this.rule,makeWalletItemHandler:this.makeWalletItemHandler})}}process({walletItems:t}){return this.handler.process({walletItems:t})}}function Xe({newRoles:s,originalRoles:t}){const e=Ct(s),r=Ct(t),i=new Set([...Object.keys(e),...Object.keys(r)]);return Array.from(i).reduce((n,a)=>{const u=e[a]||0,c=r[a]||0,d=u-c;return d!==0&&n.push({key:a,value:{delta:d,newValue:u,originalValue:c}}),n},[])}function Ct(s){return s.reduce((t,e)=>(e.getCouponCodes().forEach(i=>{const{key:n,value:a}=i;t[n]=t[n]?t[n]+a:a}),t),{})}class $t{constructor(t){this.products=t.products||[],this.walletItems=t.walletItems||[],this.originalRoles=t.originalRoles||[],this.newRoles=t.newRoles||[]}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}get isValid(){return!!this}get couponProducts(){return this.products.filter(t=>t.isCoupon)}get couponWalletItems(){return this.walletItems.filter(t=>t.isCoupon)}get roleRelatedCoupons(){return Xe({newRoles:this.newRoles,originalRoles:this.originalRoles})}get couponItemList(){return this.couponProducts.map(t=>{const e=this.walletItems.filter(d=>d.productCode===t.productCode),r=e.filter(d=>d.isUsed);r.forEach(d=>{d.useForWalletItems=this.walletItems.filter(l=>(d.useFor||[]).includes(l.walletItemCode))});const i=e.filter(d=>!d.isAvailableCoupon),n=o.KeyValueObject.foundValueByKey(this.roleRelatedCoupons,t.productCode)||{},a=t.maxPerWallet-(r.length+i.length),{qty:u,remarks:c}=Ze({product:t,availableCoupons:i,roleBase:n,remainingQuota:a});return{product:t,usedCoupons:r,availableCoupons:i,alreadyHave:r.length+i.length,maxLimit:t.maxPerWallet,remainingQuota:a,qty:u,roleBase:n,remarks:c}})}setNewRoles(t){this.newRoles=t}}function Ze({product:s,remainingQuota:t,availableCoupons:e,roleBase:r}){const{delta:i=0}=r,{maxPerWallet:n}=s;let a=i;const u=[];return i>0&&n&&i>t&&(a=0,u.push(`max ${n}`)),i<0&&n&&e.length<i&&(a=e.length,u.push(`only ${e.length} could be cancelled`)),{qty:a,remarks:u}}const ts=["value"];class K{constructor(t={}){t=t||{},this.target=t.target,this.targetCode=t.targetCode,this.key=t.key,this.value=t.value||[]}static dummyData(){return{target:"Merchandise",targetCode:"code",key:"color"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"ItemOptionFillIn"}static get _superclass(){return"ItemOptionFillIn"}static getItemOptionFillInsByTarget({itemOptionFillIns:t=[],target:e,targetCode:r}){if(!e)throw new Error("no target");return r?t.filter(i=>i.target===e&&i.targetCode===r):t.filter(i=>i.target===e)}get isValid(){return!!this.target&&!!this.targetCode&&!!this.key}getKey(){return this.key}getValue(){return this.value}update(t){return Object.keys(t).forEach(e=>{ts.includes(e)&&(this[e]=t[e])}),this}}function yt(s,t,e){e=e||{};let r;if(e.operation&&e.props&&(r=e.props.reduce((i,n)=>{const{prop:a,compareFn:u}=n,c=typeof u=="function"?u(s,t,a):gt(s,t,a);return i===null?c:_t(c,i,e.operation)},null),e.subOperation&&e.subOperation.operation)){const i=yt(s,t,e.subOperation);r=_t(i,r,e.operation)}return r}function gt(s,t,e){return s[e]===null||s[e]===void 0?!1:s[e]===t[e]}function qt(s,t,e){if(s[e]===null||s[e]===void 0)return!1;if(!Array.isArray(s[e])&&!Array.isArray(t[e]))throw new TypeError("This function can only compare array.");return es(s[e],t[e])>0}function Bt(s,t,e){return s[e]===null||s[e]===void 0?!1:s[e].isSame(t[e])}function Nt(s,t,e){if(s[e]===null||s[e]===void 0)return!1;if(!Array.isArray(s[e])&&!Array.isArray(t[e]))throw new TypeError("This function can only compare array.");return s[e].reduce((r,i)=>{const n=i.isSameIn(t[e]);return r===null?n:n&&r},null)}function jt(s,t,e){if(s[e]===null||s[e]===void 0)return!1;if(!Array.isArray(s[e])&&!Array.isArray(t[e]))throw new TypeError("This function can only compare array.");return s[e].length!==t[e].length?!1:s[e].reduce((r,i,n)=>{const a=i.isSame(t[e][n]);return r===null?a:a&&r},null)}function _t(s,t,e){if(e.toLowerCase()==="or")return s||t;if(e.toLowerCase()==="and")return s&&t;throw new Error("The operation does not conform to the specification.")}function es(s,t){const e=new Set(t);return s.filter(r=>e.has(r))}const ss="20200130",rs=[{data:[],err:null,isNew:null,message:null,total:0,version:"20200130"}];class is{constructor(t={}){this.standardResponseObj=ns(t.responseVer)}get isValid(){return!!this.standardResponseObj}standardizeResponse(t={}){let e,r;return t.message&&(e=t.message),t.err&&(r={hasError:!0,message:t.err.message||t.err}),{...this.standardResponseObj,...t,err:r,message:e}}}function ns(s=ss){return s?rs.find(t=>t.version===s):null}function Ut(s){const t=new is(s);if(!t.isValid)throw new TypeError("Invalid options for responseHelper");return t}function Kt({ctx:s,ids:t}){const{clientApp:e}=s.state,{query:r}=s.request,{id:i}=s.params;if(s.isAuthenticated()&&!e)return{id:i,ids:t,...r};const n=e?e.name:null;return!n||n==="com.questwork.questwork-admin"?{id:i,ids:t,...r}:{id:i,ids:t,...r,clientAppName:n}}function as(s,t=34){const e=cs(t);return us(s,e)}function us(s,t){const e=t.byCode;if(s===0)return e[0];let r="";const i=t.length;for(;s>0;)r=e[s%i]+r,s=Math.floor(s/i);return r}function cs(s){let t="9876543210ABCDEFGHJKLMNPQRSTUVWXYZ";return s===58&&(t="9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz"),ds(t)}function ds(s){const t={},e={},r=s.length;let i,n;for(i=0;i<r;i++)n=s[i],t[i]=n,e[n]=i;return{byCode:t,byChar:e,length:r}}function os({len:s=16,pattern:t="a1"}={}){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r="abcdefghijklmnopqrstuvwxyz",i="1234567890",n="~!@#$%^&*_+-=";let a="";t.includes("A")&&(a+=e),t.includes("a")&&(a+=r),t.includes("1")&&(a+=i),t.includes("#")&&(a+=n);const u=[...a];return[...new Array(s)].map(c=>u[Math.random()*u.length|0]).join``}function ls(s){return typeof s!="string"&&(s=s.toString()),s.split("").reverse().join("")}function hs(s=34){const t=new Date().valueOf(),e=os({len:8,pattern:"1"}),r=ls(`${t}${e}`);return as(r,s)}const A={setCode:hs},ms=["label","locale","value"];class J{constructor(t={}){t=t||{},this.locale=t.locale,this.label=t.label,this.value=t.value||""}static dummyData(){return{}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"ItemOptionLocale"}static get _superclass(){return"ItemOptionLocale"}get isValid(){return!!this}update(t){return Object.keys(t).forEach(e=>{ms.includes(e)&&(this[e]=t[e])}),this}}const ps=["description","key","label","type","value","locales"];class E{constructor(t={}){t=t||{};const{_ItemOptionLocale:e}=t._constructor||{};this._ItemOptionLocale=e&&e._superclass===J._superclass?e:J,this.approved=t.approved||!1,this.description=t.description,this.itemOptionCode=fs(t,"itemOptionCode"),this.itemOptionType=t.itemOptionType||"ItemOption",this.key=t.key,this.label=t.label,this.layout=t.layout,this.required=t.required||!1,this.type=t.type,this.value=t.value||"",this.locales=this._ItemOptionLocale.initOnlyValidFromArray(t.locales)}static dummyData(){return{key:"firstName"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"ItemOption"}static get _superclass(){return"ItemOption"}get isRequired(){return this.required}get isValid(){return!!this.key}isValidFillInValue(t){if(!Array.isArray(t))return!1;if(t.length===0)return!this.isRequired;if(t.length===1){const e=typeof t[0]=="string";return this.isRequired?e&&!!t[0]:e}return!1}update(t){return Object.keys(t).forEach(e=>{ps.includes(e)&&(e==="locales"?this[e]=this._ItemOptionLocale.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this}}function fs(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}class U{constructor(t={}){t=t||{},this.description=t.description,this.header=t.header,this.key=t.key,this.type=t.type}static dummyData(){return{header:"First Name",key:"firstName",type:"TextInput"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"MerchandiseOption"}static get _superclass(){return"MerchandiseOption"}static convertToFormData(t=[]){const e={};return t.map(r=>{let i=!1;r.values.map(n=>{n.default&&(e[r.key]=n.value,i=!0)}),i||(e[r.key]="")}),e}static convertToInputs(t=[]){return t.map(e=>({type:e.type,label:e.header,name:e.key,values:e.values}))}static convertToPurchaseOptions(t=[]){const e=[];return t.map(r=>{let i=!1;r.values.map(n=>{n.default&&(e.push({key:r.key,value:n.value}),i=!0)}),i||e.push({key:r.key,value:""})}),e}get isValid(){return!!this.key}updateMerchandiseOption(t){Object.keys(t).forEach(e=>{this[e]=t[e]})}}const ys=["min","max"];class Ot{constructor(t={}){t=t||{},this.max=t.max===null||t.max>0?t.max:1,this.min=t.min===null||t.min>=0?t.min:0}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"QtyPerTransaction"}static get _superclass(){return"QtyPerTransaction"}get isValid(){return typeof this.min=="number"&&(this.max===null||typeof this.max=="number"&&this.max>=this.min)}update(t){return Object.keys(t).forEach(e=>{ys.includes(e)&&(this[e]=t[e])}),this}}const gs=["active","amounts","deductions","discount","metadata","name","qtyPerTransaction","remarks"];class k{constructor(t={}){t=t||{};const{_Amount:e,_QtyPerTransaction:r}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._QtyPerTransaction=r&&r._superclass===Ot._superclass?r:Ot,this.active=typeof t.active<"u"?!!t.active:!0,this.amounts=this._Amount.initOnlyValidFromArray(t.amounts),this.deductions=this._Amount.initOnlyValidFromArray(t.deductions),this.discount=t.discount||0,this.metadata=o.Metadata.initOnlyValidFromArray(t.metadata),this.name=t.name,this.qtyPerTransaction=this._QtyPerTransaction.init(t.qtyPerTransaction),this.priceStrategyType=t.priceStrategyType||"PriceStrategy",this.remarks=o.KeyValueObject.initOnlyValidFromArray(t.remarks)}static dummyData(){return{amounts:[p.dummyData()],name:"name"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"PriceStrategy"}static get _superclass(){return"PriceStrategy"}get isValid(){return this.amounts.length>0&&typeof this.discount=="number"&&this.discount>=0&&this.discount<=100}get defaultAmount(){return this.amounts&&this.amounts.length===1?this.amounts[0]:null}get restrictions(){let t=[];return t=o.Metadata.getValuesByKey(this.metadata,"RESTRICTIONS"),t.length===0&&(t=o.KeyValueObject.getValuesByKey(this.remarks,"restrictions")),t[0]||[]}getAmount({currencyCode:t,qty:e}){const r=this.getAmountByCurrencyCode(t);if(r){const{value:i}=r;return i*e}return null}getAmountByCurrencyCode(t){const e=this._Amount.getAmountsByCurrencyCode(this.amounts,t);return e.length===0?null:e[0]}getDeductionByCurrencyCode(t){const e=this._Amount.getAmountsByCurrencyCode(this.deductions,t);return e.length===0?null:e[0]}getRemarks(){return this.remarks?this.remarks:[]}deductionHasCurrencyCode(t){return this.deductions.length===0?!0:this.getDeductionByCurrencyCode(t)!==null}hasCurrencyCode(t){return this._Amount.getAmountsByCurrencyCode(this.amounts,t).length!==0}hasCurrencyCodeWithQty(t,e){return!(this.qtyPerTransaction.min>e||this._Amount.getAmountsByCurrencyCode(this.amounts,t).length===0)}isMatchedRestrictions(t={}){return this.restrictions.length===0?!0:this.restrictions.reduce((r,i)=>{const{key:n,value:a={}}=i;return r=r||Cs(n,a,t),r},!1)||!1}isQtyValid(t){return!(this.qtyPerTransaction.min>t)}setRemarks(t){return Array.isArray(t)&&(this.remarks=o.KeyValueObject.initFromArray(t)),this}toCalculatorRule({currencyCode:t,qty:e}){const r=this.getAmountByCurrencyCode(t);return{deduction:0,discount:0,min:this.qtyPerTransaction.min,max:this.qtyPerTransaction.max,value:r.value||r.default,recursing:!1,recursingStartQty:null,priceStrategy:this}}update(t){return Object.keys(t).forEach(e=>{gs.includes(e)&&(e==="amounts"||e==="deductions"?this[e]=this._Amount.initOnlyValidFromArray(t[e]):e==="qtyPerTransaction"?this[e]=this._QtyPerTransaction.init(t[e]):this[e]=t[e])}),this}}function Cs(s,t,e){return Object.keys(t).reduce((r,i)=>{const n=B.get(e[s],i),a=Object.keys(t[i]);return r=r&&Ht(n,t[i],a,!0),r},!0)}function Ht(s,t={},e=[],r=!0){if(!r||e.length===0)return r;const i=e.shift(),n=t[i];return r=_s({action:i,formulaValue:n,val:s}),Ht(s,t,e,r)}function _s({action:s,formulaValue:t,val:e}){switch(s){case"elemMatch":case"$elemMatch":return(e||[]).some(r=>Object.keys(t).filter(i=>Object.prototype.hasOwnProperty.call(r,i)&&r[i]===t[i]).length>0);case"eq":case"$eq":return B.isEqual(e,t);case"gt":case"$gt":return e>t;case"gte":case"$gte":return e>=t;case"$in":return Array.isArray(e)?!!e.find(r=>t.includes(r)):typeof e!="object"?!!t.includes(e):!1;case"$nin":return Array.isArray(e)?!e.some(r=>t.includes(r)):typeof e!="object"?!t.includes(e):!0;case"$includes":return e&&e.includes(t);case"$keyValue":return Array.isArray(e)?e.find(r=>t.key===r.key&&t.values.includes(r.value))!==void 0:e.key?t.key===e.key&&t.values.includes(e.value):!1;case"lt":case"$lt":return e<t;case"lte":case"$lte":return e<=t;case"ne":case"$ne":return e!==t;default:return!0}}const Os=["dateBegin","dateEnd","name","priceStrategies"];class P{constructor(t){t=t||{};const{_PriceStrategy:e}=t._constructor||{};this._PriceStrategy=e&&e._superclass===k._superclass?e:k,this.created=t.created||new Date().valueOf(),this.dateBegin=t.dateBegin||new Date().valueOf(),this.dateEnd=t.dateEnd||null,this.modified=t.modified||new Date().valueOf(),this.name=t.name||"",this.priceStrategies=this._PriceStrategy.initOnlyValidFromArray(t.priceStrategies),this.remarks=o.KeyValueObject.initOnlyValidFromArray(t.remarks)}static dummyData(){return{name:"Standard",dateBegin:new Date().valueOf(),dateEnd:new Date().valueOf()+1,priceStrategies:[k.dummyData()]}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Price"}static get _superclass(){return"Price"}static getPricesByTime(t=[],e){return t.filter(i=>i.isAvailableByDate(e))}get isValid(){return this.priceStrategies.length>0}get defaultAmount(){return this.defaultStrategy?this.defaultStrategy.defaultAmount:null}get defaultStrategy(){return this.getStrategies().length===1?this.priceStrategies[0]:null}getStrategies(){return this.priceStrategies?this.priceStrategies:[]}getStrategiesByRestrictions(t){return this.priceStrategies.filter(e=>e.isMatchedRestrictions(t))}getStrategiesByCurrencyAndQty(t,e){let r=this.getStrategiesByCurrencyCode(t,this.priceStrategies);return r=this.getStrategiesByQty(e,r),r}getStrategiesByCurrencyCode(t,e){return(e||this.priceStrategies).reduce((i,n)=>(n.hasCurrencyCode(t)&&n.deductionHasCurrencyCode(t)&&i.push(n),i),[])}getStrategiesByQty(t,e){return(e||this.priceStrategies).reduce((i,n)=>(n.isQtyValid(t)&&i.push(n),i),[])}isAvailableByDate(t){const e=t||new Date().valueOf();return e>=this.dateBegin&&(e<this.dateEnd||this.dateEnd===null)}hasCurrencyCodeWithQty(t,e){return this.priceStrategies.reduce((r,i)=>(r=i.hasCurrencyCodeWithQty(t,e)?!0:r,r),!1)}setModified(){return this.modified=new Date().valueOf(),this}setStrategies(t){return Array.isArray(t)&&(this.priceStrategies=this._PriceStrategy.initOnlyValidFromArray(t)),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Os.includes(e)&&(e==="remarks"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):e==="priceStrategies"?this[e]=this._PriceStrategy.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this.setModified()}}const As=["couponDetails","description","entitlements","intangible","limitPercentage","lineOptions","maxPerWallet","name","originalStock","printable","printLayoutCodes","printLayoutMappingCodes","productCategories","productGroupName","productOptions","requiredProductCode","stock"];class T extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_ItemOption:e}=t._constructor||{};this._ItemOption=e&&e._superclass===E?e:E;const r=t._id||t.id;this.id=vs(r),this._type=t._type||"Product",this.couponDetails=t.couponDetails,this.description=t.description||"",this.entitlements=t.entitlements,this.intangible=t.intangible||!1,this.limitPercentage=t.limitPercentage||100,this.lineOptions=this._ItemOption.initOnlyValidFromArray(t.lineOptions),this.maxPerWallet=t.maxPerWallet||1,this.name=t.name||"",this.originalStock=t.originalStock||0,this.printable=t.printable||!1,this.printLayoutCodes=t.printLayoutCodes||[],this.printLayoutMappingCodes=t.printLayoutMappingCodes||[],this.productCategories=t.productCategories||[],this.productCode=bs(t,"productCode"),this.productGroupName=typeof t.productGroupName<"u"?t.productGroupName.toUpperCase():t.productGroupName||"DEFAULT",this.productOptions=this._ItemOption.initOnlyValidFromArray(t.productOptions),this.productType=t.productType||"Product",this.requiredProductCode=t.requiredProductCode,this.stock=t.stock||0}static dummyData(){return{name:"badge",tenantCode:"tenantCode"}}static get _classname(){return"Product"}static get _superclass(){return"Product"}get isValid(){return super.isValid&&!!this.name}get isBadge(){return this.productGroupName==="BADGE"}get isCoupon(){return this.productGroupName==="COUPON"}get isItemCoupon(){return this.couponDetails?this.couponDetails.item:!1}get isPrintable(){return this.printLayoutMappingCodes.length>0}get isReachedLimitPercentage(){return this.soldPercentage>=this.limitPercentage}get isTotalCoupon(){return this.couponDetails?this.couponDetails.total:!1}get soldPercentage(){return(this.originalStock-this.stock)/this.originalStock*100}get summary(){return{product:this,productCode:this.productCode,name:this.name}}ableToHave(t){return this.maxPerWallet>=t}checkProductItemOptions(t=[]){return K.getItemOptionFillInsByTarget({itemOptionFillIns:t,target:"Product",targetCode:this.productCode}).reduce((r,i)=>{const n=i.getKey(),a=this.getProductOptionByKey(n);return a?(a.isValidFillInValue(i.getValue())||r.errMsgs.push(`the product(${this.productCode}) option's(${n}) fillInValue is invalid`),r):(r.errMsgs.push(`options of the product(${this.productCode}) does not contain key: "${n}"`),r)},{errMsgs:[]})}getCode(){return this.productCode}getPreservedData(){return{metadata:this.metadata,name:this.name,productCode:this.productCode,productGroupName:this.productGroupName,productType:this.productType,tenantCode:this.tenantCode}}getMetadataValueByKey(t){return o.Metadata.getValueByKey(this.metadata||[],t)}getProductOptionByKey(t){const e=this._ItemOption.getByKey(this.productOptions,t);return e.length===1?e[0]:null}hasStock(t){return this.stock>=t}isApplicableCoupon(t){if(!this.couponDetails)return!1;const{merchandiseCodes:e=[]}=this.couponDetails;return e.length>0?e.includes(t.merchandiseCode):!0}isQualified(t){const e=this.getMetadataValueByKey("RULES")||[];return e.length===0?!0:e.reduce((r,i)=>r||o.getValidation(i,t,ws,o.KeyValueObject),!1)}isTicket(){return!1}update(t){return Object.keys(t).forEach(e=>{As.includes(e)&&(e==="productOptions"||e==="lineOptions"?this[e]=this._ItemOption.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}function vs(s){return s&&typeof s.toString=="function"?s.toString():s}function bs(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function ws(s,t){return o.getValueByKeys(s.split("."),t)}const Is=["allowEditQty","allowEditUnitPrice","defaultCurrency","description","eventSessionCode","intangible","locales","max","merchandiseCategoryCodes","merchandiseOptions","name","onlyFor","prices","priority","productCodes","sku","stock","visibleBy"];class R extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_ItemOption:e,_ItemOptionFillIn:r,_MerchandiseOption:i,_Price:n,_Product:a}=t._constructor||{};this._ItemOption=e&&e._superclass===E._superclass?e:E,this._ItemOptionFillIn=r&&r._superclass===K._superclass?r:K,this._MerchandiseOption=i&&i._superclass===U._superclass?i:U,this._Price=n&&n._superclass===P._superclass?n:P,this._Product=a&&a._superclass===T._superclass?a:T,this._products=t._products||[],this._type=t._type||"Merchandise";const u=t._id||t.id;this.id=Rs(u),this.allowEditQty=t.allowEditQty||!1,this.allowEditUnitPrice=t.allowEditUnitPrice||!1,this.defaultCurrency=t.defaultCurrency||"HKD",this.description=t.description,this.free=t.free||!1,this.intangible=t.intangible||!1,this.max=t.max||1,this.merchandiseCategoryCodes=t.merchandiseCategoryCodes||[],this.merchandiseCode=Ss(t,"merchandiseCode"),this.merchandiseOptions=Ps(this,t),this.merchandiseType=t.merchandiseType||"Merchandise",this.name=t.name||"",this.prices=this._Price.initOnlyValidFromArray(t.prices),this.productCodes=t.productCodes||[],this.priority=t.priority||100,this.sku=t.sku||"",this.stock=t.stock||0,this.targets=t.targets||[]}static dummyData(){return{name:"delegate badge",sku:"20190430",productCodes:["123456"],merchandiseOptions:[E.init({itemOptionType:"ItemOptionText",type:"TextInput",key:"firstName",label:"First Name"})],prices:[P.dummyData()],stock:100,tenantCode:"85223977000"}}static get _classname(){return"Merchandise"}static get _superclass(){return"Merchandise"}get afterEnd(){return this.getBeginAndEndDates().dateEnd>Date.now()}get beforeBegin(){return this.getBeginAndEndDates().dateBegin<=Date.now()}get currentPrice(){if(this.free)return null;const t=Date.now(),e=this.prices.filter(r=>r.isAvailableByDate(t));if(e.length===1)return e[0];if(e.length===0)return null;if(e.length>1)throw new Error("Incorrect price settings for merchandise")}get hasStock(){return this.stock>0||!!this.intangible}get isActive(){return this.active===!0}get isDeleted(){return this.deleted===!0}get isAvailable(){return this.isActive&&!this.isDeleted&&this.hasStock&&(this.free||this.currentPrice)}get isAvailableByDate(){return!this.afterEnd&&!this.beforeBegin}get isForPersonal(){return!Array.isArray(this.targets)||this.targets.length===0}get isForGroup(){return Array.isArray(this.targets)&&this.targets.includes("GROUP")}get isPrintable(){return this.printOut.isPrintable}get isValid(){return super.isValid&&!!this.name&&!!this.productCodes&&this.productCodes.length>0}get products(){return this._Product.initOnlyValidFromArray(this._products||[])}get summary(){return{currentPrice:this.currentPrice,free:this.free,max:this.max,merchandise:this,merchandiseCode:this.merchandiseCode,name:this.name,stock:this.stock}}checkHasStock(t){return this.stock>=t}checkMerchandiseItemOptions(t=[]){return this._ItemOptionFillIn.getItemOptionFillInsByTarget({itemOptionFillIns:t,target:"Merchandise",targetCode:this.merchandiseCode}).reduce((r,i)=>{const n=i.getKey(),a=this.getMerchandiseOptionByKey(n);return a?(a.isValidFillInValue(i.getValue())||r.errMsgs.push(`the merchandise(${this.merchandiseCode}) option's(${n}) fillInValue is invalid`),r):(r.errMsgs.push(`options of the merchandise(${this.merchandiseCode}) does not contain key: "${n}"`),r)},{errMsgs:[]})}checkProductsItemOptions(t=[]){return this.getProducts().reduce((e,r)=>{const{errMsgs:i}=r.checkProductItemOptions(t);return e.errMsgs.push(...i),e},{errMsgs:[]})}convertMerchandiseOptionsToFormData(){return U.convertToFormData(this.merchandiseOptions)}convertMerchandiseOptionsToInputs(){return U.convertToInputs(this.merchandiseOptions)}convertMerchandiseOptionsToPurchaseOptions(){return U.convertToPurchaseOptions(this.merchandiseOptions)}getAmountFromPrice({cartItems:t,currency:e,dateTimestamp:r=Date.now(),qty:i,roleCodes:n}){const a={cartItems:t,errorMessages:[],merchandise:this,price:null,qty:i,value:null},u=e||this.defaultCurrency,c=this.getPriceByTimeAndRoleCodes(r,n);if(!c)return a.errorMessages.push("Can't get available price for you."),a;a.price=c;const d=c.getStrategiesByCurrencyAndQty(u,i);if(d.length===0)return a.errorMessages.push("Can't get available strategies from price."),a;const{convertedPriceStrategies:l,maxQty:h}=d.reduce((y,g)=>{const C=g.toCalculatorRule({currency:u,qty:i});return y.convertedPriceStrategies.push(C),C.max===null&&(y.maxQty=null),C.max!==null&&y.maxQty!==null&&(y.maxQty+=C.max),y},{convertedPriceStrategies:[],maxQty:0});if(h!==null&&h<i)return a.errorMessages.push(`Currently you can only purchase a maximum of ${h} pieces of this merchandise.`),a;let m=j(i,l);if(m.length===0)return a.errorMessages.push("No amount"),a;m=m.sort((y,g)=>y.value-g.value);const[f]=m;return f.qty>0?(a.errorMessages.push("Exceed maximum quantity per transaction."),a):f.qty<0?(a.errorMessages.push("No amount."),a):(a.value=f.value,a)}getAvailableInfo({cartItems:t,currency:e,dateTimestamp:r=Date.now(),roleCodes:i}={}){const n={available:!1,unavailableMessages:[],merchandise:this,cartItemInfos:[],cartItems:t,qty:t.reduce((l,h)=>l+h.getQty(),0)};this.stock<n.qty&&n.unavailableMessages.push(`The quantity(${n.qty}) you selected is less than the stock(${this.stock}).`),this.isActive||n.unavailableMessages.push("Inactive."),this.isDeleted&&n.unavailableMessages.push("Deleted.");const a=this.getPriceByTimeAndRoleCodes(r,i);a||n.unavailableMessages.push("No available price for you in this time."),n.price=a;const u=e||this.defaultCurrency;a.getStrategiesByCurrencyAndQty(u,n.qty).length===0&&n.unavailableMessages.push(`The price not support currency '${u}'.`);const{cartItemInfos:c,hasProblem:d}=this.getItemOptionInfos(t);return n.cartItemInfos=c,d&&n.unavailableMessages.push("Cart item has problem, please check."),n.unavailableMessages.length===0&&(n.available=!0),n}getBeginAndEndDates(){const t={dateBegin:null,dateEnd:null};return this.prices.reduce((e,r)=>((!e.dateBegin||r.dateBegin>e.dateBegin)&&(e.dateBegin=r.dateBegin),(!e.dateEnd||r.dateEnd<=e.dateEnd)&&(e.dateEnd=r.dateEnd),e),t)}getCode(){return this.merchandiseCode}getCurrentAmount({currencyCode:t,payload:e,ignoreRestriction:r=!1}){if(!this.currentPrice)return null;let i=r?this.currentPrice.priceStrategies:this.currentPrice.getStrategiesByRestrictions(e);return i=this.currentPrice.getStrategiesByCurrencyCode(t,i),i.length===0?null:i[0].getAmountByCurrencyCode(t)}getCurrentPrice(t){const e=t||Date.now(),r=this.getPricesByTime(e);return r.length===1?r[0]:null}getCurrentPriceByRoleCodes(t){const e=Date.now();let r=this.getPricesByTime(e);return r=P.getPricesByRoleCodes(r,t),r.length===1?r[0]:null}getItemOptionInfos(t=[]){return t.reduce((e,r)=>{const i=r.getItemOptionFillIns(),n={available:!0,cartItem:r,unavailableMessages:[]},a=this.checkMerchandiseItemOptions(i),{errMsgs:u}=this.checkProductsItemOptions(i);return n.unavailableMessages.push(...a.errMsgs),n.unavailableMessages.push(...u),n.available=!(n.unavailableMessages.length>0),e.hasProblem=n.available?e.hasProblem:!0,e.cartItemInfos.push(n),e},{cartItemInfos:[],hasProblem:!1})}getMerchandiseOptionByKey(t){const e=this._ItemOption.getByKey(this.merchandiseOptions,t);return e.length===1?e[0]:null}getPreservedData(){return{allowEditQty:this.allowEditQty,allowEditUnitPrice:this.allowEditUnitPrice,defaultCurrency:this.defaultCurrency,description:this.description,merchandiseCategoryCodes:this.merchandiseCategoryCodes,merchandiseCode:this.merchandiseCode,merchandiseOptions:this.merchandiseOptions,merchandiseType:this.merchandiseType,metadata:this.metadata,name:this.name,priority:this.priority,productCodes:this.productCodes,sku:this.sku,stock:this.stock,tenantCode:this.tenantCode}}getPrices(){return this.prices?this.prices:[]}getPricesByTime(t){const e=t||Date.now();return P.getPricesByTime(this.prices,e)}getPriceByTimeAndRoleCodes(t,e){let r=this.getPricesByTime(t);return r=P.getPricesByRoleCodes(r,e),r.length===1?r[0]:null}getProducts(){return this.products||[]}getProductsMetadataValuesByKey(t){return this.products.map(e=>e.getMetadataValueByKey(t)).filter(e=>e)}getProductsQty(t=1){return this.productCodes.reduce((e,r)=>(e[r]?e[r]+=1*t:e[r]=1*t,e),{})}getRemarksByKey(t){return o.KeyValueObject.getValuesByKey(this.remarks,t)}getStock(){return this.stock||0}getSummary(t){return{...this.summary,currentAmount:this.getCurrentAmount(t)}}reachLimit(t){return this.max<t}setPrices(t){return Array.isArray(t)&&(this.prices=P.initOnlyValidFromArray(t)),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Is.includes(e)&&(e==="merchandiseOptions"&&this.tenantCode?this[e]=this._ItemOption.initOnlyValidFromArray(t[e]):e==="merchandiseOptions"&&this.tenantCode?this[e]=U.initOnlyValidFromArray(t[e]):e==="prices"?this[e]=P.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}function Ps(s,t){return t.tenantCode?s._ItemOption.initOnlyValidFromArray(t.merchandiseOptions):s._MerchandiseOption.initOnlyValidFromArray(t.merchandiseOptions)}function Ss(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Rs(s){return s&&typeof s.toString=="function"?s.toString():s}const Vs=["paidAmount","purchaseOptions","qty","itemOptionFillIns","remarks"];class Y{constructor(t={}){t=t||{};const{_Amount:e,_ItemOptionFillIn:r,_Merchandise:i}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._ItemOptionFillIn=r&&r._superclass===K._superclass?r:K,this._Merchandise=i&&i._superclass===R._superclass?i:R,this._merchandise=t._merchandise,this.cartItemCode=Es(t,"cartItemCode"),this.created=t.created||new Date().valueOf(),this.discount=this._Amount.init(t.discount),this.itemOptionFillIns=this._ItemOptionFillIn.initOnlyValidFromArray(t.itemOptionFillIns),this.merchandiseCode=t.merchandiseCode,this.metadata=o.Metadata.initOnlyValidFromArray(t.metadata),this.price=this._Amount.init(t.price),this.purchaseOptions=o.KeyValueObject.initOnlyValidFromArray(t.purchaseOptions),this.qty=t.qty,this.remarks=o.KeyValueObject.initOnlyValidFromArray(t.remarks),this.subTotal=this._Amount.init(t.subTotal),this.waived=t.waived||0}static dummyData(){return{merchandiseCode:"merchandiseCode",qty:1}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"CartItem"}static get _superclass(){return"CartItem"}static getByMerchandiseCode(t=[],e){return t.filter(r=>r.merchandiseCode===e)}static mergeDuplicateCartItems(t){return Wt(t)}get isValid(){return!!this.merchandiseCode&&this.qty>0}get merchandise(){return this._Merchandise.init(this._merchandise)}createInvoiceLine(){return{amount:this.subTotal,unitPrice:this.price,deduction:this.discount,qty:this.qty,merchandiseCode:this.merchandiseCode,metadata:this.metadata,purchaseOptions:this.purchaseOptions,remarks:this.remarks,waived:this.waived}}getCurrencyCode(){return this.price?this.price.getCurrencyCode():null}getItemOptionFillIns(){return this.itemOptionFillIns}getMerchandiseCode(){return this.merchandiseCode}getQty(){return this.qty}toCaculateAmountItem(){return{merchandiseCode:this.getMerchandiseCode(),qty:this.qty,price:this.price,discount:this.discount,subTotal:this.subTotal,priceStrategy:null,purchaseOptions:this.purchaseOptions,remarks:this.remarks,waived:this.waived}}update(t){return Object.keys(t).forEach(e=>{Vs.includes(e)&&(e==="discount"||e==="price"||e==="subTotal"?this[e]=this._Amount.init(t[e]):e==="itemOptionFillIns"?this[e]=this._ItemOptionFillIn.initOnlyValidFromArray(t[e]):e==="metadata"?this[e]=o.Metadata.initOnlyValidFromArray(t[e]):e==="purchaseOptions"||e==="remarks"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this}}function Wt(s,t=[]){const e=s.shift(),{matched:r}=s.reduce((i,n)=>{if(i.matched)return i;if(e.merchandiseCode===n.merchandiseCode&&e.itemOptionFillIns.length===n.itemOptionFillIns.length){const{itemOptionFillIns:a}=n;B.intersectionWith(a,e.itemOptionFillIns,(c,d)=>c.target===d.target&&c.targetCode===d.targetCode&&c.key===d.key&&B.intersection(c.value,d.value).length===c.value.length).length===a.length&&(i.matched=n)}return i},{matched:null});return r?r.qty+=e.qty:t.push(e),s.length===0?t:Wt(s,t)}function Es(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}const Ts=["created"];class O{constructor(t){t=t||{},this.absent=t.absent||null,this.assigned=t.assigned||null,this.cancelled=t.cancelled||null,this.completed=t.completed||null,this.confirmed=t.confirmed||null,this.created=t.created||new Date().valueOf(),this.delivered=t.delivered||null,this.expired=t.expired||null,this.failed=t.failed||null,this.onHold=t.onHold||null,this.processing=t.processing||null,this.paid=t.paid||null,this.payLater=t.payLater||null,this.pending=t.pending,this.redeemed=t.redeemed||null,this.refunded=t.refunded||null,this.refundRequested=t.refundRequested||null,this.rejected=t.rejected||null,this.shared=t.shared||null,this.submitted=t.submitted||null,this.terminated=t.terminated||null,this.used=t.used||null,this.waived=t.waived||null}static dummyData(){return{created:new Date().valueOf(),modified:new Date().valueOf()}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Status"}static get _superclass(){return"Status"}get isValid(){return this}get isAbsent(){return this.absent!==null}get isAssigned(){return this.assigned!==null}get isCancelled(){return this.cancelled!==null}get isCompleted(){return this.completed!==null}get isConfirmed(){return this.confirmed!==null}get isDelivered(){return this.delivered!==null}get isExpired(){return this.expired!==null}get isFailed(){return this.failed!==null}get isOnHold(){return this.onHold!==null}get isProcessing(){return this.processing!==null}get isPaid(){return this.paid!==null}get isPayLater(){return this.payLater!==null}get isPending(){return!this.isSettled&&!this.isCancelled&&!this.isRefundRequested}get isRedeemed(){return this.redeemed!==null}get isRefunded(){return this.refunded!==null}get isRefundRequested(){return this.refundRequested!==null}get isRejected(){return this.rejected!==null}get isSettled(){return this.isPaid||this.isWaived||this.isRedeemed}get isShared(){return this.shared!==null}get isSubmitted(){return this.submitted!==null}get isTerminated(){return this.terminated!==null}get isUsed(){return this.used!==null}get isWaived(){return this.waived!==null}get lastStatus(){return this.modified}get modified(){return this.statusLast?this.statusLast.value:""}get statusLast(){return this.statusList.length===0?null:this.statusList[this.statusList.length-1]}get statusList(){return Object.keys(this).reduce((e,r)=>(this[r]&&e.push({key:r,value:this[r]}),e),[]).sort((e,r)=>e.value>r.value?1:-1)}allowCancel(){return this.isPending||this.isWaived}allowRefundRequest(){return this.isPaid&&!this.isCancelled}setAbsent(t){return this.absent=t||new Date().valueOf(),this}setAssigned(t){return this.assigned=t||new Date().valueOf(),this}setCancelled(t){return this.cancelled=t||new Date().valueOf(),this}setCompleted(t){return this.completed=t||new Date().valueOf(),this}setConfirmed(t){return this.confirmed=t||new Date().valueOf(),this}setDelivered(t){return this.delivered=t||new Date().valueOf(),this}setExpired(t){return this.expired=t||new Date().valueOf(),this}setFailed(t){return this.failed=t||new Date().valueOf(),this}setOnHold(){return this.onHold=new Date().valueOf(),this}setProcessing(){return this.processing=new Date().valueOf(),this}setPaid(t){return this.paid=t||new Date().valueOf(),this.waived=null,this}setPayLater(t){return this.payLater=t||new Date().valueOf(),this}setPending(t){return this.pending=t||new Date().valueOf(),this}setRedeemed(t){return this.redeemed=t||new Date().valueOf(),this}setRefunded(t){return this.refunded=t||new Date().valueOf(),this}setRefundRequested(t){return this.refundRequested=t||new Date().valueOf(),this}setRejected(t){return this.rejected=t||new Date().valueOf(),this}setShared(t){return this.shared=t||new Date().valueOf(),this}setSubmitted(t){return this.submitted=t||new Date().valueOf(),this}setTerminated(t){return this.terminated=t||new Date().valueOf(),this}setUsed(t){return this.used=t||new Date().valueOf(),this.delivered=this.delivered||this.used,this}setWaived(t){return this.waived=t||new Date().valueOf(),this.paid=null,this}unSetAssigned(){this.assigned=null}unsetDelivered(){this.delivered=null}unSetOnHold(){this.onHold=null}unSetRefundRequested(){this.refundRequested=null}unsetUsed(){this.used=null}update(t){return Object.keys(t).forEach(e=>{Ts.includes(e)||(this[e]=t[e])}),this}}const Ds=[];class z extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_CartItem:e,_Merchandise:r,_Status:i}=t._constructor||{};this._CartItem=e&&e._superclass===Y._superclass?e:Y,this._Merchandise=r&&r._superclass===R._superclass?r:R,this._Status=i&&i._superclass===O._superclass?i:O;const n=t._id||t.id;this.id=xs(n),this._merchandises=t._merchandises,this._type=t._type||"Cart",this.cartCode=Ls(t,"cartCode"),this.cartItems=this._CartItem.initOnlyValidFromArray(t.cartItems),this.status=this._Status.init(t.status)}static dummyData(){return{cartItems:[Y.dummyData()],tenantCode:"tenantCode"}}static get _classname(){return"Cart"}static get _superclass(){return"Cart"}get isValid(){return super.isValid}get isActive(){return!!this.active}get merchandises(){return this._Merchandise.initOnlyValidFromArray(this._merchandises||[])}get merchandisesSummary(){return this.merchandises.reduce((t,e)=>{const r=t.find(i=>i.merchandiseCode===e.merchandiseCode);return r?r.qty+=1:t.push({...e.summary,qty:1}),t},[])}checkoutAvailable({ownedWalletItems:t,selectCartItems:e,isCoordinator:r=!1}){try{return r?this.checkHasStock({selectCartItems:e}):this.checkHasStock({selectCartItems:e})&&!this.checkWalletItemReachLimit({ownedWalletItems:t,selectCartItems:e})&&!this.checkMerchandiseReachLimit({selectCartItems:e})}catch(i){throw i}}checkHasStock({selectCartItems:t}){try{return t.forEach(e=>{const{qty:r}=e;if(this.merchandises&&this.merchandises.length===0)throw new Error("not have merchandises array object");const[i]=this.merchandises.filter(a=>a.merchandiseCode===e.merchandiseCode),{products:n}=i;if(n&&n.length===0)throw new Error("merchandise not have products array object");if(!i.checkHasStock(r))throw new Error("merchandise not enough stock");n.forEach(a=>{if(!a.hasStock(r))throw new Error("product not enough stock")})}),!0}catch(e){throw e}}checkWalletItemReachLimit({ownedWalletItems:t,selectCartItems:e}){try{return e.forEach(r=>{const{qty:i}=r,[n]=this.merchandises.filter(u=>u.merchandiseCode===r.merchandiseCode),{products:a}=n;if(a&&a.length===0)throw new Error("merchandise not have products array object");a.forEach(u=>{const d=t.filter(l=>l.productCode===u.productCode).length||0;if(!u.ableToHave(d+i))throw new Error("walletItem reach limit")})}),!1}catch(r){throw r}}checkMerchandiseReachLimit({selectCartItems:t}){try{return t.forEach(e=>{const{qty:r}=e,[i]=this.merchandises.filter(n=>n.merchandiseCode===e.merchandiseCode);if(r>i.max)throw new Error("merchandise reach limit")}),!1}catch(e){throw e}}clearCartItems(){return this.cartItems=[],this}createInvoiceLines(){return this.cartItems.map(t=>Object.assign(t.createInvoiceLine(),{cartCode:this.cartCode,tenantCode:this.tenantCode}))}getCartItems(){return this.cartItems}getCartItemCodes(){return this.cartItems.map(t=>t.cartItemCode)}getCode(){return this.cartCode}getCurrencyCode(){return this.cartItems.length>0?this.cartItems[0].getCurrencyCode():null}getMerchandiseAvailableInfos({cartItems:t,currency:e,roleCodes:r}){if(this.cartItems.length>0&&this.merchandises.length===0)throw new Error("No merchandises");const i=this;if(t=t||i.cartItems,t=this._CartItem.initOnlyValidFromArray(t),t.length===0)throw new Error("No cartItems");return i.merchandises.reduce((n,a)=>{const u=this._CartItem.getByMerchandiseCode(t,a.merchandiseCode),c=a.getAvailableInfo({cartItems:u,currency:e,roleCodes:r});return n.push(c),n},[])}getRelatedRegistrationGroupCode(){return o.KeyValueObject.getValueByKey(this.remarks||[],"registrationGroupCode")}setCartItems(t){return this.cartItems=this._CartItem.initOnlyValidFromArray(t),this}setCompleted(){return this.status.setCompleted(),this.setModified()}updateAvailable({isCoordinator:t,selectCartItems:e}){try{return t?this.checkHasStock({selectCartItems:e}):this.checkHasStock({selectCartItems:e})&&!this.checkMerchandiseReachLimit({selectCartItems:e})}catch(r){throw r}}update(t){return Object.keys(t).forEach(e=>{Ds.includes(e)&&(this[e]=t[e])}),super.update(t)}updateStock(){if(this.cartItems.length===0)throw new Error("No cartItems");let t=[],e=[];return this.cartItems.forEach(r=>{const{merchandiseCode:i,qty:n}=r,[a]=this.merchandises.filter(d=>d.merchandiseCode===i),u=a.stock-n,{products:c}=a;c.forEach(d=>{const l=d.stock-r.qty;d.updateProduct({stock:l})}),t=t.concat(c),a.update({stock:u}),e=e.concat(a)}),{newProducts:t,newMerchandises:e}}}function Ls(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function xs(s){return s&&typeof s.toString=="function"?s.toString():s}function Qt(s){const{delimiter:t=": ",key:e,purchaseOptions:r,tag:i="div"}=s||{};if(!e)return r.reduce((a,u)=>{const c=At({delimiter:t,purchaseOption:u,tag:i});return i?a.push(`<${i}>${c.join("")}</${i}>`):a.push(`${c.join("; ")}`),a},[]);const n=(r||[]).find(a=>!!e&&a.key===e);return n?At({delimiter:t,purchaseOption:n,tag:i}):[]}function At({delimiter:s=": ",purchaseOption:t,tag:e="div"}){return(t.value||[]).reduce((r,i)=>{const{label:n,value:a={}}=i||{},u=n??"";return Array.isArray(a)?e?r.push(`<${e}>${u}${s}${a.join(s)}</${e}>`):r.push(`${u}${s}${a.join(s)}`):typeof a=="object"?Object.keys(a).map(c=>{e?r.push(`<${e}>${c}${s}${a[c]}</${e}>`):r.push(`${c}${s}${a[c]}`)}):e?r.push(`<${e}>${u}${s}${a}</${e}>`):r.push(`${u}${s}${a}`),r},[])}const Ms=["label","logoUrl","name","sandbox","setting","surchargeBillingAccountCode","surchargeBillingProjectCode","surcharges"];class H extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Price:e}=t._constructor||{};this._Price=e&&e._superclass===P._superclass?e:P;const r=t._id||t.id;this.id=$s(r),this._type=t._type||"PaymentGateway",this.hasWebhook=t.hasWebhook||!1,this.label=t.label,this.logoUrl=t.logoUrl,this.name=t.name||"",this.paymentGatewayCode=Fs(t,"paymentGatewayCode"),this.paymentGatewayType=t.paymentGatewayType||"PaymentGateway",this.paymentResultType=t.paymentResultType||"PaymentResult",this.sandbox=t.sandbox||!1,this.setting=t.setting||null,this.surchargeBillingAccountCode=t.surchargeBillingAccountCode,this.surchargeBillingProjectCode=t.surchargeBillingProjectCode,this.surcharges=this._Price.initOnlyValidFromArray(t.surcharges)}static dummyData(){return{name:"name",tenantCode:"tenantCode"}}static get _classname(){return"PaymentGateway"}static get _superclass(){return"PaymentGateway"}get isValid(){return super.isValid&&!!this.name}async createPayment(){throw new Error(`${this._classname} subclass should implement createPayment`)}async getAppPayParams(){throw new Error(`${this._classname} subclass should implement getAppPayParams`)}getCode(){return this.paymentGatewayCode}async updatePayment(){throw new Error(`${this._classname} subclass should implement updatePayment`)}async query(){throw new Error(`${this._classname} subclass should implement query`)}async submit(){throw new Error(`${this._classname} subclass should implement submit`)}setCompletedRelatedStatus(t){throw new Error(`${this.name} subclass should implement setCompletedRelatedStatus`)}update(t){return Object.keys(t).forEach(e=>{Ms.includes(e)&&(e==="surcharges"?this[e]=this._Price.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}function Fs(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function $s(s){return s&&typeof s.toString=="function"?s.toString():s}class V extends o.Status{constructor(t){t=t||{},super(t),this.cancelled=this._ActionRecord.init(t.cancelled),this.completed=this._ActionRecord.init(t.completed),this.confirmed=this._ActionRecord.init(t.confirmed),this.deleted=this._ActionRecord.init(t.deleted),this.terminated=this._ActionRecord.init(t.terminated)}static get _classname(){return"StatusQStore"}get _classname(){return"StatusQStore"}get isCancelled(){var t;return((t=this.cancelled)==null?void 0:t.timestamp)>0}get isCompleted(){var t;return((t=this.completed)==null?void 0:t.timestamp)>0}get isConfirmed(){var t;return((t=this.confirmed)==null?void 0:t.timestamp)>0}get isDeleted(){var t;return((t=this.deleted)==null?void 0:t.timestamp)>0}get isTerminated(){var t;return((t=this.terminated)==null?void 0:t.timestamp)>0}get isValid(){return super.isValid}setCancelled(t,e){return this.setValue(t,e,"cancelled")}setCompleted(t,e){return this.setValue(t,e,"completed")}setConfirmed(t,e){return this.setValue(t,e,"confirmed")}setDeleted(t,e){return this.setValue(t,e,"deleted")}setTerminated(t,e){return this.setValue(t,e,"terminated")}}class Gt extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.open=this._ActionRecord.init(t.open),this.revised=this._ActionRecord.init(t.revised),this.void=this._ActionRecord.init(t.void)}static get _classname(){return"StatusQStoreInvoice"}get _classname(){return"StatusQStoreInvoice"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}get isRevised(){var t;return((t=this.revised)==null?void 0:t.timestamp)>0}get isValid(){return super.isValid}get isVoid(){var t;return((t=this.void)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setOpen(t,e){return this.setValue(t,e,"open")}setRevised(t,e){return this.setValue(t,e,"revised")}setVoid(t,e){return this.setValue(t,e,"void")}}class kt extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.open=this._ActionRecord.init(t.open),this.revised=this._ActionRecord.init(t.revised),this.void=this._ActionRecord.init(t.void)}static get _classname(){return"StatusQStoreInvoiceLine"}get _classname(){return"StatusQStoreInvoiceLine"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}get isRevised(){var t;return((t=this.revised)==null?void 0:t.timestamp)>0}get isValid(){return super.isValid}get isVoid(){var t;return((t=this.void)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setOpen(t,e){return this.setValue(t,e,"open")}setRevised(t,e){return this.setValue(t,e,"revised")}setVoid(t,e){return this.setValue(t,e,"void")}}class X extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.expired=this._ActionRecord.init(t.expired),this.invalid=this._ActionRecord.init(t.invalid),this.open=this._ActionRecord.init(t.open)}static get _classname(){return"StatusQStoreOrder"}get _classname(){return"StatusQStoreOrder"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isExpired(){var t;return((t=this.expired)==null?void 0:t.timestamp)<Date.now()}get isInvalid(){var t;return((t=this.invalid)==null?void 0:t.timestamp)<Date.now()}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setExpired(t,e){return this.setValue(t,e,"expired")}setInvalid(t,e){return this.setValue(t,e,"invalid")}setOpen(t,e){return this.setValue(t,e,"open")}}class Z extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.expired=this._ActionRecord.init(t.expired),this.fulfilled=this._ActionRecord.init(t.fulfilled),this.invalid=this._ActionRecord.init(t.invalid),this.open=this._ActionRecord.init(t.open)}static get _classname(){return"StatusQStoreOrderLine"}get _classname(){return"StatusQStoreOrderLine"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isExpired(){var t;return((t=this.expired)==null?void 0:t.timestamp)<Date.now()}get isFulfilled(){var t;return((t=this.fulfilled)==null?void 0:t.timestamp)>0}get isInvalid(){var t;return((t=this.invalid)==null?void 0:t.timestamp)<Date.now()}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setExpired(t,e){return this.setValue(t,e,"expired")}setFulfilled(t,e){return this.setValue(t,e,"fulfilled")}setInvalid(t,e){return this.setValue(t,e,"invalid")}setOpen(t,e){return this.setValue(t,e,"open")}}const qs=["amount"];class tt extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_PaymentGateway:r,_Receipt:i,_ReceiptLine:n}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._PaymentGateway=r&&r._superclass===H._superclass?r:H,this._Receipt=i&&i._superclass===L._superclass?i:L,this._ReceiptLine=n&&n._superclass===D._superclass?n:D,this._paymentGateway=t._paymentGateway,this._receipt=t._receipt,this._receiptLine=t._receiptLine;const a=t._id||t.id;this.id=Bs(a),this._type=t._type||"PaymentCharge",this.amount=this._Amount.init(t.amount),this.billingAccountCode=t.billingAccountCode,this.billingProjectCode=t.billingProjectCode,this.paymentGatewayCode=t.paymentGatewayCode,this.paymentChargeCode=t.paymentChargeCode,this.paymentChargeType="PaymentCharge",this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptLineCode=t.receiptLineCode}static dummyData(){return{billingAccountCode:"billingAccountCode",paymentGatewayCode:"paymentGatewayCode",receiptCode:"receiptCode",receiptLineCode:"receiptLineCode",tenantCode:"tenantCode"}}static get _classname(){return"PaymentCharge"}static get _superclass(){return"PaymentCharge"}get isValid(){return super.isValid&&!!this.billingAccountCode&&!!this.paymentGatewayCode&&!!this.receiptCode&&!!this.receiptLineCode}get paymentGateway(){return this._PaymentGateway.init(this._paymentGateway)}get receipt(){return this._Receipt.init(this._receipt)}get receiptLines(){return this._ReceiptLine.initOnlyValidFromArray(this._receiptLines||[])}update(t){return Object.keys(t).forEach(e=>{qs.includes(e)&&(e==="amount"?this[e]=this.amount instanceof this._Amount?this.amount.update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function Bs(s){return s&&typeof s.toString=="function"?s.toString():s}const Ns=["additionalData","amount","paidAmount","paymentGatewayCode","receiptDate","status","surcharge"];class D extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_PaymentCharge:r,_PaymentItem:i,_Receipt:n,_Status:a}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._PaymentCharge=r&&r._superclass===tt._superclass?r:tt,this._PaymentItem=i&&i._superclass===W._superclass?i:W,this._Receipt=n&&n._superclass===L._superclass?n:L,this._Status=a&&a._superclass===V._superclass?a:V,this._paymentCharge=t._paymentCharge,this._paymentItems=t._paymentItems,this._receipt=t._receipt;const u=t._id||t.id;this.id=js(u),this._type=t._type||"ReceiptLine",this.additionalData=o.KeyValueObject.initOnlyValidFromArray(t.additionalData),this.amount=this._Amount.init(t.amount),this.paidAmount=this._Amount.init(t.paidAmount),this.paymentGatewayCode=t.paymentGatewayCode,this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptLineCode=t.receiptLineCode,this.receiptLineType="ReceiptLine",this.status=this._Status.init(t.status),this.surcharge=this._Amount.init(t.surcharge)}static dummyData(){return{receiptCode:"receiptCode",tenantCode:"tenantCode"}}static get _classname(){return"ReceiptLine"}static get _superclass(){return"ReceiptLine"}get isCancelled(){return this.status.isCancelled}get isCompleted(){return this.status.isCompleted}get isConfirmed(){return this.status.isConfirmed}get isTerminated(){return this.status.isTerminated}get isValid(){return super.isValid&&!!this.receiptCode}get paymentCharge(){return this._PaymentCharge.init(this._paymentCharge)}get paymentItems(){return this._PaymentItem.initOnlyValidFromArray(this._paymentItems)}get receipt(){return this._Receipt.init(this._receipt)}getAmount(){return this.amount}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setConfirmed(t,e){return this.status.setProcessing(t,e),this.setModified()}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Ns.includes(e)&&(e==="additionalData"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):e==="status"?this[e]=this[e]instanceof this._Status?this[e].update(t[e]):this._Status.init(t[e]):e==="amount"||e==="paidAmount"||e==="surcharge"?this[e]=this[e]instanceof this._Amount?this[e].update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function js(s){return s&&typeof s.toString=="function"?s.toString():s}const Us=["amount","paidAmount","receiptDate","revisionNumber","status","surcharge"];class L extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_ReceiptLine:r,_Status:i}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._ReceiptLine=r&&r._superclass===D._superclass?r:D,this._Status=i&&i._superclass===V._superclass?i:V,this._receiptLines=t._receiptLines;const n=t._id||t.id;this.id=Ks(n),this._type=t._type||"Receipt",this.amount=this._Amount.init(t.amount),this.paidAmount=this._Amount.init(t.paidAmount),this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptNumber=t.receiptNumber,this.receiptType="Receipt",this.revisionNumber=t.revisionNumber||1,this.status=this._Status.init(t.status),this.surcharge=this._Amount.init(t.surcharge)}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"Receipt"}static get _superclass(){return"Receipt"}get isCancelled(){return this.status.isCancelled}get isCompleted(){return this.status.isCompleted}get isConfirmed(){return this.status.isConfirmed}get isTerminated(){return this.status.isTerminated}get receiptLines(){return this._ReceiptLine.initOnlyValidFromArray(this._receiptLines||[])}getAmount(){return this.amount}getFullReceiptNumber(t="."){return`${this.receiptNumber}${t}${this.revisionNumber}`}increaseRevisionNumber(){return this.revisionNumber+=1,this}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setConfirmed(t,e){return this.status.setProcessing(t,e),this.setModified()}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Us.includes(e)&&(e==="status"?this[e]=this.status instanceof this._Status?this.status.update(t[e]):this._Status.init(t[e]):e==="amount"||e==="paidAmount"||e==="surcharge"?this[e]=this[e]instanceof this._Amount?this[e].update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function Ks(s){return s&&typeof s.toString=="function"?s.toString():s}const Hs=["amount"];class W extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_Invoice:r,_InvoiceLine:i,_PaymentGateway:n,_Receipt:a,_ReceiptLine:u}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._Invoice=r&&r._superclass===N._superclass?r:N,this._InvoiceLine=i&&i._superclass===Q._superclass?i:Q,this._PaymentGateway=n&&n._superclass===H._superclass?n:H,this._Receipt=a&&a._superclass===L._superclass?a:L,this._ReceiptLine=u&&u._superclass===D._superclass?u:D,this._invoice=t._invoice,this._invoiceLines=t._invoiceLines,this._paymentGateway=t._paymentGateway,this._receipt=t._receipt,this._receiptLine=t._receiptLine;const c=t._id||t.id;this.id=Ws(c),this._type=t._type||"PaymentItem",this.amount=this._Amount.init(t.amount),this.invoiceCode=t.invoiceCode,this.invoiceDate=t.invoiceDate||new Date().valueOf(),this.invoiceLineCode=t.invoiceLineCode,this.paymentGatewayCode=t.paymentGatewayCode,this.paymentItemCode=t.paymentItemCode,this.paymentItemType="PaymentItem",this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptLineCode=t.receiptLineCode}static dummyData(){return{invoiceCode:"invoiceCode",invoiceLineCode:"invoiceLineCode",paymentGatewayCode:"paymentGatewayCode",receiptCode:"receiptCode",receiptLineCode:"receiptLineCode",tenantCode:"tenantCode"}}static get _classname(){return"PaymentItem"}static get _superclass(){return"PaymentItem"}get invoice(){return this._Invoice.init(this._invoice)}get invoiceLines(){return this._InvoiceLine.initOnlyValidFromArray(this._invoiceLines||[])}get isValid(){return super.isValid&&!!this.invoiceCode&&!!this.invoiceLineCode&&!!this.paymentGatewayCode&&!!this.receiptCode&&!!this.receiptLineCode}get paymentGateway(){return this._PaymentGateway.init(this._paymentGateway)}get receipt(){return this._Receipt.init(this._receipt)}get receiptLines(){return this._ReceiptLine.initOnlyValidFromArray(this._receiptLines||[])}update(t){return Object.keys(t).forEach(e=>{Hs.includes(e)&&(e==="amount"?this[e]=this.amount instanceof this._Amount?this.amount.update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function Ws(s){return s&&typeof s.toString=="function"?s.toString():s}const Qs=["amount","deduction","description","discount","invoiceDate","note","outstanding","purchaseOptions","qty","unitPrice"];class Q extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e,_Invoice:r,_Merchandise:i,_PaymentItem:n,_Status:a}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._Invoice=r&&r._superclass===N._superclass?r:N,this._Merchandise=i&&i._superclass===R._superclass?i:R,this._PaymentItem=n&&n._superclass===W._superclass?n:W,this._Status=a&&a._superclass===O._superclass?a:O,this._invoice=t._invoice,this._merchandise=t._merchandise,this._paymentItems=t._paymentItems;const u=t._id||t.id;this.id=ks(u),this._type=t._type||"InvoiceLine",this.amount=this._Amount.init(t.amount),this.deduction=this._Amount.init(t.deduction),this.description=t.description,this.discount=t.discount||0,this.invoiceCode=t.invoiceCode,this.invoiceDate=t.invoiceDate,this.invoiceLineCode=Gs(t,"invoiceLineCode"),this.invoiceLineType=t.invoiceLineType||"InvoiceLine",this.merchandiseCode=t.merchandiseCode,this.note=t.note,this.outstanding=this._Amount.init(t.outstanding),this.purchaseOptions=o.KeyValueObject.initOnlyValidFromArray(t.purchaseOptions),this.qty=t.qty||1,this.status=this._Status.init(t.status),this.unitPrice=this._Amount.init(t.unitPrice),this.waived=t.waived||0}static dummyData(){return{amount:p.dummyData(),invoiceCode:"invoiceCode",tenantCode:"tenantCode"}}static get _classname(){return"InvoiceLine"}static get _superclass(){return"InvoiceLine"}get isClosed(){return this.status.isClosed}get isOpen(){return this.status.isOpen}get isValid(){return super.isValid&&!!this.amount&&!!this.invoiceCode}get invoice(){return this._Invoice.init(this._invoice)}get merchandise(){return this._Merchandise.init(this._merchandise)}get paymentItems(){return this._PaymentItem.initOnlyValidFromArray(this._paymentItems)}get usedCoupons(){const t=o.KeyValueObject.getValueByKey(this.remarks,"USED_ITEM_COUPONS")||[],e=o.KeyValueObject.getValueByKey(this.remarks,"USED_TOTAL_COUPONS")||[];return[...t,...e]}getPreservedData(){return{created:this.created,invoiceCode:this.invoiceCode,invoiceLineCode:this.invoiceLineCode,qty:this.qty,unitPrice:this.unitPrice,amount:this.amount,deduction:this.deduction,discount:this.discount,invoiceLineType:this.invoiceLineType}}getPurchaseOptionValue(t){const{delimiter:e,key:r,tag:i}=t||{};return Qt({key:r,purchaseOptions:this.purchaseOptions})}setClosed(t,e){return typeof this.status.setClosed!="function"?this:(this.status.setClosed(t,e),this.setModified())}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setOpen(t,e){return this.isOpen||typeof this.status.setOpen!="function"?this:(this.status.setOpen(t,e),this.setModified())}setRevised(t,e){return typeof this.status.setRevised!="function"?this:(this.status.setRevised(t,e),this.setModified())}setVoid(t,e){return typeof this.status.setVoid!="function"?this:(this.status.setVoid(t,e),this.setModified())}update(t){return Object.keys(t).forEach(e=>{Qs.includes(e)&&(e==="amount"||e==="unitPrice"||e==="deduction"||e==="outstanding"?this[e]=this._Amount.init(t[e]):e==="purchaseOptions"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}updateOutstanding({actorCode:t}={}){var n;const e=this.paymentItems;if(e.length===0)return this;if(((n=this.outstanding)==null?void 0:n.value)<=0)return this;const r=e.reduce((a,u)=>{var c;return a+(((c=u==null?void 0:u.amount)==null?void 0:c.value)||0)},0),i=this.amount.value-r;return i<=0&&this.setClosed(Date.now(),t),this.update({outstanding:{currencyCode:this.amount.currencyCode,value:i}})}}function Gs(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function ks(s){return s&&typeof s.toString=="function"?s.toString():s}class vt{constructor(t={}){t=t||{},this.bankAccount=t.bankAccount,this.contactInformation=t.contactInformation,this.name=t.name,this.logo=t.logo}static dummyData(){return{name:"name"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Issuer"}static get _superclass(){return"Issuer"}get isValid(){return!!this.name}updateIssuer(t){return Object.keys(t).forEach(e=>{this[e]=t[e]}),this}}const Ys=["purchaseOptions","qty","status"];class et extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e,_Product:r,_Status:i}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._Product=r&&r._superclass===T._superclass?r:T,this._Status=i&&i._superclass===O._superclass?i:O,this._eventRegistration=t._eventRegistration,this._invoiceLine=t._invoiceLine,this._product=t._product,this._tenant=t._tenant,this._transaction=t._transaction,this._type=t._type||"WalletItem";const n=t._id||t.id;this.id=Js(n),this.invoiceLineCode=t.invoiceLineCode,this.productCode=t.productCode,this.purchaseOptions=o.KeyValueObject.initOnlyValidFromArray(t.purchaseOptions),this.qty=t.qty||1,this.status=this._Status.init(t.status),this.transactionCode=t.transactionCode,this.walletItemCode=zs(t,"walletItemCode")}static dummyData(){return{...super.dummyData(),productCode:"5cd4f5430c2b874ad7ed8cfd",qty:1,status:O.dummyData(),tenantCode:"tenantCode",transactionCode:"transactionCode"}}static get _classname(){return"WalletItem"}static get _superclass(){return"WalletItem"}get isValid(){return super.isValid&&!!this.productCode}get isAssigned(){return this.status.isAssigned}get isAvailable(){return this.isInWallet&&(!this.isUsed||!this.isDelivered)}get isAvailableCoupon(){return this.isCoupon&&!this.isCancelled&&!this.isUsed}get isCancelled(){return this.status.isCancelled}get isCompleted(){return this.status.isCompleted}get isConfirmed(){return this.status.isConfirmed}get isCoupon(){return this.product?this.product.isCoupon:!1}get isDelivered(){return this.status.isDelivered}get isInWallet(){return!this.isCancelled&&!this.isRejected&&!this.isRefunded&&!this.isRefundRequested}get isItemCoupon(){return this.product?this.product.isItemCoupon:!1}get isOnHold(){return this.status.onHold}get isOwned(){return this.isInWallet&&(this.isPaid&&!this.isAssigned&&!this.isConfirmed||this.isWaived&&!this.isAssigned&&!this.isConfirmed||this.isRedeemed&&!this.isAssigned&&!this.isConfirmed||this.isAssigned&&this.isConfirmed)}get isPaid(){return this.status.isPaid}get isPending(){return this.status.isPending}get isRedeemed(){return this.status.redeemed}get isRefunded(){return this.status.isRefunded}get isRefundRequested(){return this.status.isRefundRequested}get isRejected(){return this.status.rejected}get isShared(){return this.status.shared}get isSubmitted(){return this.status.isSubmitted}get isTotalCoupon(){return this.product?this.product.isTotalCoupon:!1}get isUsed(){return this.status.isUsed}get isWaived(){return this.status.isWaived}get couponDetails(){return this.product?this.product.couponDetails:null}get displayPurchaseOptions(){return this.purchaseOptions.length>0?this.purchaseOptions.reduce((t,e)=>{const{value:r}=e;return t+=r.reduce((i,n)=>{const{label:a,value:u}=n;return i+=`<div><span>${a}: </span><span>${u}</span></div>`},"")},""):""}get lastRefundRejectedDetail(){return Array.isArray(this.refundRejectedHistory)&&this.refundRejectedHistory.length>0?this.refundRejectedHistory[this.refundRejectedHistory.length-1]:null}get paid(){if(!this._transaction)return null;const{amount:t,meta:e}=this._transaction;return{created:e.created,currencyCode:t.currencyCode,modified:e.modified,value:t.value}}get product(){return this._Product.init(this._product)}get refundedDetail(){return o.Metadata.getValueByKey(this.metadata,"REFUNDED_DETAIL")||{}}get refundRejectedHistory(){return o.Metadata.getValueByKey(this.metadata,"REFUND_REJECTED_HISTORY")||{}}get refundRequestedDetail(){return o.Metadata.getValueByKey(this.metadata,"REFUND_REQUESTED_DETAIL")||{}}get tenant(){return this._tenant}get usedTimestamp(){return this.status.used}formatFlexcel(){return{...this,...this.status,used:this.isUsed,productName:this.product&&this.product.name?this.product.name:""}}formatOutput({format:t}){switch(t){case"flexcel":return this.formatFlexcel();default:return this}}getCode(){return this.walletItemCode}getPurchaseOptionValue(t){const{delimiter:e,key:r,tag:i}=t||{};return Qt({delimiter:e,key:r,purchaseOptions:this.purchaseOptions,tag:i})}isApplicableCoupon(t){return this.isAvailableCoupon&&(this.product?this.product.isApplicableCoupon(t):!1)}isSameOwner(t){return t&&this.owner?t===this.owner:!1}setAssigned(t){return this.status.setAssigned(t),this}setCancelled(t){return this.status.setCancelled(t),this}setConfirmed(t){return this.status.setConfirmed(t),this}setDelivered(t){return this.status.setDelivered(t),this}setOnHold(){return this.status.setOnHold(),this}setPaid(){return this.status.setPaid(),this}setPaidTimestamp(t){return this.status.setPaid(t),this}setPending(){return this.status.setPending(),this}setRedeemed(){return this.status.setRedeemed(),this}setRejected(){return this.status.setRejected(),this}setRefunded(t){this.status.cancelled||this.setCancelled();const e=this.status.cancelled+1;return this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,"REFUNDED_DETAIL",t),this.status.setRefunded(e),this}setRefundRequested(t){return this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,"REFUND_REQUESTED_DETAIL",t),this.status.setRefundRequested(),this}setRefundRejected(t){const e=this.status.refundRequested;this.unSetRefundRequested();const r=o.Metadata.foundValueByKey(this.metadata,"REFUND_REJECTED_HISTORY")||[];r.push({...t,refundRequested:e,created:new Date().valueOf()}),this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,"REFUND_REJECTED_HISTORY",r)}setShared(){return this.status.setShared(),this}setUsedTimestamp(){return this.status.setUsed(),this}setUsedCouponFor(t){const e=o.KeyValueObject.foundValueByKey(this.metadata,"USED_COUPON_FOR")||[];e.push(t),this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,"USED_COUPON_FOR",e)}setWaived(){return this.status.setWaived(),this}updatePurchaseOptions(t){const{purchaseOptions:e}=this,r=o.Metadata.foundValueByKey(this.metadata,"PURCHASE_OPTION_HISTORY")||[];return r.push({purchaseOptions:B.cloneDeep(e),created:new Date().valueOf()}),this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,"PURCHASE_OPTION_HISTORY",r),e.forEach(i=>{const{key:n,value:a}=i,{value:u}=t.find(c=>c.key===n);a.forEach((c,d)=>{Object.assign(c,u[d])})}),this}unSetAssigned(){return this.status.unSetAssigned(),this}unsetDelivered(){return this.status.unsetDelivered(),this}unSetOnHold(){return this.status.unSetOnHold(),this}unSetRefundRequested(){return this.status.unSetRefundRequested(),this}unsetUsed(){return this.status.unsetUsed(),this}update(t){return Object.keys(t).forEach(e=>{Ys.includes(e)&&(e==="purchaseOptions"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function Js(s){return s&&typeof s.toString=="function"?s.toString():s}function zs(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}const Xs=["amount","couponCodes","status"];class G extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e,_PaymentResultFactory:r,_Status:i,_WalletItem:n}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._PaymentResultFactory=r,this._Status=i&&i._superclass===O._superclass?i:O,this._WalletItem=n&&n._superclass===et._superclass?n:et,this._coupons=t._coupons,this._creditNotes=t._creditNotes,this._invoice=t._invoice,this._paymentGateway=t._paymentGateway,this._paymentResults=t._paymentResults,this._walletItems=t._walletItems;const a=t._id||t.id;this.id=tr(a),this._type=t._type||"Transaction",this.amount=this._Amount.init(t.amount),this.couponCodes=t.couponCodes||[],this.creditNoteCodes=t.creditNoteCodes||[],this.invoiceCode=t.invoiceCode,this.paymentGatewayCode=t.paymentGatewayCode,this.paymentResultRef=t.paymentResultRef,this.status=this._Status.init(t.status),this.transactionCode=Zs(t,"transactionCode")}static dummyData(){return{status:O.dummyData(),tenantCode:"tenantCode"}}static get _classname(){return"Transaction"}static get _superclass(){return"Transaction"}get isValid(){return super.isValid}get billedAmount(){var t;return(t=this.amount)==null?void 0:t.displayAmount()}get isActive(){return this.active===!0}get isAssigned(){return this.status.isAssigned}get isCancelled(){return this.status.isCancelled}get isConfirmed(){return this.status.isConfirmed}get isCompleted(){return this.status.isCompleted}get isExpired(){return this.status.isExpired}get isFailed(){return this.status.isFailed}get isOnHold(){return this.status.isOnHold}get isPaid(){return this.status.isPaid}get isPending(){return this.status.isPending}get isProcessing(){return this.status.isProcessing}get isRedeemed(){return this.status.isRedeemed}get isRefunded(){return this.status.isRefunded}get isShared(){return this.status.isShared}get isSubmitted(){return this.status.isSubmitted}get isWaived(){return this.status.isWaived}get paymentResults(){return this._PaymentResultFactory.initOnlyValidFromArray(this._paymentResults||[])}get paymentResultAmounts(){return this.paymentResults.filter(t=>t.isSuccess()).map(t=>({billedAmount:t.billedAmount,paidTimestamp:t.getPaidTimestamp(),paymentMethod:t.paymentMethod,paymentResultCode:t.paymentResultCode,receivedAmount:t.receivedAmount}))}get successedPaymentResult(){return this.paymentResults.find(t=>t.isSuccess())}get walletItems(){return this._WalletItem.initOnlyValidFromArray(this._walletItems)}getId(){return this.id?this.id.toString():this.id}getLatestStatus(){var t,e;return((e=(t=this.status)==null?void 0:t.statusLast)==null?void 0:e.key)||""}getCode(){return this.transactionCode}isAllowDelete(){return this.active&&!this.deleted&&!this.isCancelled&&!this.isCompleted&&!this.isPaid&&!this.isWaived}isAllowPay(){return this.active&&!this.deleted&&!this.isCancelled&&!this.isCompleted&&!this.isPaid&&!this.isWaived&&!this.isExpired}setAssigned(){return this.status.setAssigned(),this}setCancelled(){return this.status.setCancelled()}setCompleted(){return this.status.setCompleted()}setFailed(){return this.status.setFailed()}setOnHold(){return this.status.setOnHold()}setPaid(){return this.status.setPaid()}setPaymentResultRef(t){return this.paymentResultRef=t,this}setPending(){return this.status.setPending()}setProcessing(){return this.status.setProcessing()}setRedeemed(){return this.status.setRedeemed()}setRefunded(){return this.status.setRefunded()}setSettled(){return this.status.setSettled()}setShared(){return this.status.setShared()}setWaived(){return this.status.setWaived()}updateStatus(t){switch(t){case"cancelled":return this.setCancelled();case"completed":return this.setCompleted();case"failed":return this.setFailed();case"on-hold":return this.setOnHold();case"pending":return this.setPending();case"processing":return this.setProcessing();case"refunded":return this.setRefunded();default:return this}}update(t){return Object.keys(t).forEach(e=>{Xs.includes(e)&&(e==="amount"?this[e]=this._Amount.init(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function Zs(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function tr(s){return s&&typeof s.toString=="function"?s.toString():s}const er=["billToUserCode","checkoutDateTime","description","invoiceDate","issuer","outstanding","revisionNumber","status"];class N extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_BillToUser:r,_Cart:i,_InvoiceLine:n,_Issuer:a,_Status:u,_Transaction:c}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._BillToUser=r,this._Cart=i&&i._superclass===z._superclass?i:z,this._InvoiceLine=n&&n._superclass===Q._superclass?n:Q,this._Issuer=a&&a._superclass===vt._superclass?a:vt,this._Status=u&&u._superclass===O._superclass?u:O,this._Transaction=c&&c._superclass===G._superclass?c:G,this._billToUser=t._billToUser,this._cart=t._cart,this._invoiceLines=t._invoiceLines,this._transactions=t._transactions;const d=t._id||t.id;this.id=rr(d),this._type=t._type||"Invoice",this.amount=this._Amount.init(t.amount),this.billToUserCode=t.billToUserCode,this.cartCode=t.cartCode,this.checkoutDateTime=t.checkoutDateTime||new Date().valueOf(),this.description=t.description,this.invoiceCode=sr(t,"invoiceCode"),this.invoiceDate=t.invoiceDate||new Date().valueOf(),this.invoiceNumber=t.invoiceNumber,this.invoiceType=t.invoiceType||"Invoice",this.issuer=this._Issuer.init(t.issuer),this.outstanding=this._Amount.init(t.outstanding),this.revisionNumber=t.revisionNumber||0,this.status=this._Status.init(t.status)}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"Invoice"}static get _superclass(){return"Invoice"}get isOpen(){return this.status.isOpen}get isValid(){return super.isValid}get isVoid(){return!!this.status.isVoid}get billToUser(){return this._BillToUser&&typeof this._BillToUser.init=="function"?this._BillToUser.init(this._billToUser):this._billToUser}get cart(){return this._Cart.init(this._cart)}get invoiceLines(){return this._InvoiceLine.initOnlyValidFromArray(this._invoiceLines||[])}get merchandises(){return(this.invoiceLines||[]).map(t=>t.merchandise).filter(t=>t)}get merchandisesSummary(){return this.merchandises.reduce((t,e)=>{const r=t.find(i=>i.merchandiseCode===e.merchandiseCode);return r?r.qty+=1:t.push({...e.summary,qty:1}),t},[])}get products(){return(this.merchandises||[]).reduce((t,e)=>(e.products&&(t=t.concat(e.products)),t),[])}get productsSummary(){return this.products.reduce((t,e)=>{const r=t.find(i=>i.productCode===e.productCode);return r?r.qty+=1:t.push({...e.summary,qty:1}),t},[])}get transactions(){return this._Transaction.initOnlyValidFromArray(this._transactions)}get walletItems(){return(this.transactions||[]).reduce((t,e)=>(e.walletItems&&(t=t.concat(e.walletItems)),t),[])}allowCancel(){return this.status.allowCancel()}getAmount(){return this.amount}getCode(){return this.invoiceCode}getCurrencyCode(){return this.amount?this.amount.getCurrencyCode():null}getFullInvoiceNumber(t="."){return`${this.invoiceNumber}${t}${this.revisionNumber}`}getPreservedData(){return{checkoutDateTime:this.checkoutDateTime,created:this.created,invoiceCode:this.invoiceCode,invoiceType:this.invoiceType,invoiceNumber:this.invoiceNumber,invoiceDate:this.invoiceDate,revisionNumber:this.revisionNumber,remarks:this.remarks}}increaseRevisionNumber(){return this.revisionNumber+=1,this}setCancelled(){return this.status.setCancelled()}setClosed(t,e){return typeof this.status.setClosed!="function"?this:(this.status.setClosed(t,e),this.setModified())}setCheckoutDateTime(t){return typeof t=="number"&&(this.checkoutDateTime=t),this}setCompleted(){return this.status.setCompleted(),this.setModified()}setOpen(t,e){return this.isOpen||typeof this.status.setOpen!="function"?this:(this.status.setOpen(t,e),this.setModified())}setRevised(t,e){return typeof this.status.setRevised!="function"?this:(this.status.setRevised(t,e),this.setModified())}setVoid(t,e){return typeof this.status.setVoid!="function"?this:(this.status.setVoid(t,e),this.setModified())}setWaived(){return this.status.setWaived(),this.setModified()}update(t){return Object.keys(t).forEach(e=>{er.includes(e)&&(e==="amount"||e==="outstanding"?this[e]=this._Amount.init(t[e]):e==="issuer"?this[e]=this._Issuer.init(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}updateOutstanding({actorCode:t}={}){var i;const e=this.invoiceLines;if(e.length===0)return this;if(((i=this.outstanding)==null?void 0:i.value)<=0)return this;const r=e.reduce((n,a)=>{var u;return a.updateOutstanding({actorCode:t}),n+((u=a==null?void 0:a.outstanding)==null?void 0:u.value)},0);return r<=0&&this.setClosed(Date.now(),t),this._invoiceLines=e,this.update({outstanding:{currencyCode:this.getCurrencyCode(),value:r}})}}function sr(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function rr(s){return s&&typeof s.toString=="function"?s.toString():s}let ot=null,Yt=null,$={},q=null;function ir(s,t,e){const r=[],{status:i}=s;return!(i instanceof O)||i.isCancelled||((i.isCompleted||s.amount&&s.amount.value===0)&&(r.push({css:{element:"__button"},icon:"fa fa-download",label:$.DOWNLOAD,onClick:q.onOrderListAction("downloadInvoice")}),r.push({css:{element:"__button"},icon:"fa fa-paper-plane",label:$.SENDEMAIL,onClick:q.onOrderListAction("sendInvoice")})),i.isPending&&(Yt?(r.push({css:{element:"__button"},icon:"fa fa-edit",label:$.ADMIN_SETTLE,onClick:q.onOrderListAction("adminSettle")}),ot&&ot.allowWaived&&r.push({css:{element:"__button"},icon:"fa fa-edit",label:$.WAIVED,onClick:q.onOrderListAction("waived")})):r.push({css:{element:"__button"},icon:"fa fa-money",label:$.PAY,onClick:q.onOrderListAction("payOnline")}),r.push({css:{element:"__button"},icon:"fa fa-trash",label:$.CANCEL,onClick:q.onOrderListAction("cancel")}))),r}function nr(s,t){return N.initFromArray(t).map(r=>{const i=o.convertTimestampToString(r.invoiceDate,"YYYY-MM-DD HH:mm"),{amount:n,itemNames:a,qty:u}=r.invoiceLines.reduce((l,h)=>{const m=s.find(f=>f.merchandiseCode===h.merchandiseCode);return m&&(l.itemNames.push(m.name),l.qty.push(h.qty)),{...l,amount:r.amount&&r.amount.value?r.amount:{value:l.amount.value+h.amount.value*h.qty,currencyCode:h.amount.currencyCode,default:l.amount.default&&h.amount.default}}},{amount:{value:0,currencyCode:"",default:!0},itemNames:[],qty:[]}),c=a.reduce((l,h,m)=>(l.push(`<div>${h} x ${u[m]}</div>`),l),[]),d=r.revisionNumber>1?`R${r.revisionNumber}`:"";return{...r,_invoiceDate:i,_amountValue:`${n.currencyCode} ${(n.value/100).toFixed(2)}`,_amountCurrency:n.currencyCode,_status:ar(r.status),_itemNames:c.join(`
|
|
2
|
-
`),_invoiceNumber:`${r.invoiceNumber} ${d}`}})}function ar(s){let t="";if(!(s instanceof O))return t;if(s.isCancelled)return t="cancelled",t;if(s.isCompleted)return t="completed",t;let e=0;return t=Object.keys(s).reduce((r,i)=>(s[i]>e&&(e=s[i],r=i),r),""),t}function ur(s){return[...s,{label:"Actions",customComponentName:"q-list-body-row-cell-action",actionBuilder:ir,css:{element:"__action"},labelButton:{DOWNLOAD:"Download",CANCEL:"Cancel",SETTLE:"Settle",PAY:"Pay"}}]}function Jt({component:s,config:t,merchandises:e,invoices:r,defaultHeaders:i,isAdmin:n,label:a={}}){q=s,ot=t,Yt=n,$=a.button||{};const c=nr(e,r).sort((l,h)=>l.invoiceDate<h.invoiceDate?1:-1),d=ur(i);return{rows:c,headers:d}}function zt(s,t){if(!t)return s;let e=null;switch(typeof t){case"function":return s.forEach(r=>{e=t(r)}),e.length===0||s.sort((r,i)=>r[e]<i[e]?1:-1),s;case"string":return e=t,s.sort((r,i)=>r[e]<i[e]?1:-1),s;default:return s}}function Xt({arr:s=[],key:t}){const[e]=s,r=e[t];return s.every(i=>i[t]===r)}function Zt({arr:s=[],key:t}){const e=s.length-1,r=s[0][t],i=s[e][t];return r<i}const cr=Object.freeze(Object.defineProperty({__proto__:null,Chain:I,ChainManager:lt,ChainTarget:ht,ComplimentaryItemManager:Ft,CouponManager:$t,adminSettle:Dt,calculateAmount:Lt,calculateByCoupon:mt,calculator:j,checkDuplicate:yt,defaultComparator:gt,defaultSort:zt,eleInArrayComparator:qt,firstLetterToLower:ft,getFakeClass:Mt,getSubClass:xt,handlerOrderList:Jt,isAllEqual:Xt,isDescendingOrder:Zt,makeResponseHelper:Ut,objectAllInArrayComparator:Nt,objectComparator:Bt,objectOrderInArrayComparator:jt,setQuery:Kt,stringHelper:A},Symbol.toStringTag,{value:"Module"})),dr=["name"];class te extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const e=t._id||t.id;this.id=or(e),this._type=t._type||"BillingAccount",this.billingAccountCode=t.billingAccountCode,this.name=t.name}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"BillingAccount"}static get _superclass(){return"BillingAccount"}update(t){return Object.keys(t).forEach(e=>{dr.includes(e)&&(this[e]=t[e])}),super.update(t)}}function or(s){return s&&typeof s.toString=="function"?s.toString():s}const lr=["name"];class ee extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const e=t._id||t.id;this.id=hr(e),this._type=t._type||"BillingProject",this.billingProjectCode=t.billingProjectCode,this.name=t.name}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"BillingProject"}static get _superclass(){return"BillingProject"}update(t){return Object.keys(t).forEach(e=>{lr.includes(e)&&(this[e]=t[e])}),super.update(t)}}function hr(s){return s&&typeof s.toString=="function"?s.toString():s}const mr=["codes","description","max","min","name","priority","productCodes"];class se extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Product:e}=t._constructor||{};this._Product=e&&e._superclass===T._superclass?e:T,this._products=t._products,this._type=t._type||"Category";const r=t._id||t.id;this.id=fr(r),this.categoryCode=pr(t,"categoryCode"),this.codes=t.codes||[],this.description=t.description,this.max=t.max||1,this.min=t.min||0,this.name=t.name,this.priority=t.priority||10,this.productCodes=t.productCodes||[]}static dummyData(){return{name:"category",tenantCode:"tenantCode"}}static get _classname(){return"Category"}static get _superclass(){return"Category"}get isValid(){return super.isValid&&!!this.name&&this.max>this.min}get products(){return this._Product.initOnlyValidFromArray(this._products)}update(t){return Object.keys(t).forEach(e=>{mr.includes(e)&&(this[e]=t[e])}),super.update(t)}}function pr(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function fr(s){return s&&typeof s.toString=="function"?s.toString():s}const yr=["amount","description","qty"];class st extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._creditNote=t._creditNote,this._type=t._type||"CreditNoteLine";const r=t._id||t.id;this.id=Cr(r),this.amount=this._Amount.init(t.amount),this.creditNoteCode=t.creditNoteCode,this.creditNoteLineCode=gr(t,"creditNoteLineCode"),this.description=t.description,this.handlingCharge=this._Amount.init(t.handlingCharge),this.qty=t.qty||1}static dummyData(){return{creditNoteCode:"creditNoteCode",tenantCode:"tenantCode"}}static get _classname(){return"CreditNoteLine"}static get _superclass(){return"CreditNoteLine"}get isValid(){return super.isValid&&!!this.creditNoteCode}setAmount(t){const e=this._Amount.init(t);return e&&(this.amount=e),this}update(t){return Object.keys(t).forEach(e=>{yr.includes(e)&&(e==="amount"||e==="unitPrice"||e==="deduction"?this[e]=this._Amount.init(t[e]):e==="purchaseOptions"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}function gr(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Cr(s){return s&&typeof s.toString=="function"?s.toString():s}const _r=["description","status"];class rt extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e,_CreditNoteLine:r,_Status:i}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._CreditNoteLine=r&&r._superclass===st._superclass?r:st,this._Status=i&&i._superclass===O._superclass?i:O,this._type=t._type||"CreditNote";const n=t._id||t.id;this.id=Ar(n),this.amount=this._Amount.init(t.amount),this.creditNoteCode=Or(t,"creditNoteCode"),this.creditNoteLines=this._CreditNoteLine.initOnlyValidFromArray(t.creditNoteLines),this.description=t.description,this.invoiceCode=t.invoiceCode,this.handlingCharge=this._Amount.init(t.handlingCharge),this.status=this._Status.init(t.status)}static dummyData(){return{invoiceCode:"invoiceCode",tenantCode:"tenantCode"}}static get _classname(){return"CreditNote"}static get _superclass(){return"CreditNote"}get isActive(){return!!this.active}get isPending(){return this.status.isPending}get isValid(){return super.isValid&&!!this.invoiceCode}get displayCreated(){return o.formatDate(this.meta.created,"YYYY/MM/DD hh:mm")}get displayRefundedDate(){return o.formatDate(this.meta.created,"YYYY/MM/DD hh:mm")}get refundedDetail(){return o.KeyValueObject.foundValueByKey(this.metadata,"REFUNDED_DETAIL")||{}}getCode(){return this.creditNoteCode}setAmount(t){const e=this_Amount.init(t);return this.isPending&&e&&(this.amount=e),this}setCompleted(){return this.status.setCompleted(),this.setModified()}setPaid(t){return this.status.setPaid(t),this.setModified()}update(t){return Object.keys(t).forEach(e=>{_r.includes(e)&&(e==="amount"?this[e]=this._Amount.init(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function Or(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Ar(s){return s&&typeof s.toString=="function"?s.toString():s}class re extends o.Repo{constructor(t={}){t=t||{},super(t);const{_CreditNote:e}=t._constructor||{};this._CreditNote=e&&e._superclass===rt._superclass?e:rt}static get _classname(){return"CreditNoteRepo"}init(t){return this._CreditNote.init(t)}}const vr=["description","name","symbol"];class ie extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const e=t._id||t.id;this.id=wr(e),this._type=t._type||"Currency",this.code=t.code,this.currencyCode=br(t,"currencyCode"),this.description=t.description,this.factor=t.factor||1,this.name=t.name,this.symbol=t.symbol||null,this.unit=t.unit}static dummyData(){return{code:"USD",factor:100,name:"US dollar",tenantCode:"platform",unit:"Cent"}}static get _classname(){return"Currency"}static get _superclass(){return"Currency"}get isValid(){return super.isValid&&!!this.code&&typeof this.factor=="number"&&!!this.name&&!!this.unit}fromCurrencyValue(t){return t/this.factor}getCode(){return this.currencyCode}update(t){return Object.keys(t).forEach(e=>{vr.includes(e)&&(this[e]=t[e])}),super.update(t)}}function br(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function wr(s){return s&&typeof s.toString=="function"?s.toString():s}const Ir=["amount","deduction","discount","note","unitPrice","status","waived","qty"];class it extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_Merchandise:r,_Order:i,_OrderService:n,_Status:a}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._Merchandise=r&&r._superclass===R._superclass?r:R,this._Order=i&&i._superclass===nt._superclass?i:nt,this._Status=a&&a._superclass===Z._superclass?a:Z,this._merchandise=t._merchandise,this._order=t._order;const u=t._id||t.id;this.id=Pr(u),this._type=t._type||"OrderLine",this.amount=this._Amount.init(t.amount),this.deduction=this._Amount.init(t.deduction),this.discount=t.discount||0,this.note=t.note,this.unitPrice=this._Amount.init(t.unitPrice),this.status=this._Status.init(t.status),this.orderCode=t.orderCode,this.orderLineCode=t.orderLineCode,this.orderLineType="OrderLine",this.merchandiseCode=t.merchandiseCode,this.waived=t.waived||0,this.qty=t.qty||1}static dummyData(){return{amount:p.dummyData(),orderCode:"orderCode",tenantCode:"tenantCode"}}static get _classname(){return"OrderLine"}static get _superclass(){return"OrderLine"}get currentStatus(){return this.isClosed?"closed":this.isBillable?"billable":this.isCancelled?"cancelled":this.isInvalid?"invalid":this.isExpired?"expired":"open"}get isActive(){return!this.isClosed&&!this.isCancelled&&!this.isExpired&&!this.isInvalid}get isBillable(){return this.isFulfilled&&!this.isClosed&&!this.isCancelled}get isOpen(){return!this.isClosed&&!this.isCancelled&&!this.isExpired&&!this.isInvalid&&!this.isFulfilled}get isClosed(){return!!this.status.isClosed||!!this.status.isPosted}get isCancelled(){return this.status.isCancelled}get isExpired(){return!this.isClosed&&!this.isCancelled&&this.status.isExpired}get isFulfilled(){return this.status.isFulfilled}get isInvalid(){return!this.isClosed&&!this.isCancelled&&this.status.isInvalid}get isValid(){return super.isValid&&!!this.merchandiseCode}get order(){return this._Order.init(this._order)}get merchandise(){return this._Merchandise.init(this._merchandise)}allowCancel(){return this.status.allowCancel()}createInvoiceLine(){return{invoiceLineType:"InvoiceLine",amount:this.amount,unitPrice:this.unitPrice,deduction:this.deduction,discount:this.discount,outstanding:this.amount,qty:this.qty,merchandiseCode:this.merchandiseCode,metadata:this.metadata,note:this.note,purchaseOptions:this.purchaseOptions,remarks:this.remarks,waived:this.waived,owner:this.owner,tenantCode:this.tenantCode}}getAmount(){return this.amount}getPreservedData(){return{created:this.created,orderCode:this.orderCode,orderLineCode:this.orderLineCode,orderLineType:this.orderLineType}}toCaculateAmountItem(){return{merchandiseCode:this.merchandiseCode,qty:this.qty,price:this.unitPrice,discount:this.discount,subTotal:this.amount,priceStrategy:null,purchaseOptions:this.purchaseOptions||[],remarks:this.remarks,waived:this.waived}}getCurrencyCode(){return this.amount?this.amount.getCurrencyCode():null}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setClosed(t,e){return this.status.setClosed(t,e),this.setModified()}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setFulfilled(t,e){return this.status.setFulfilled(t,e),this.setModified()}setInvalid(t,e){return this.status.setInvalid(t,e),this.setModified()}setOpen(t,e){return this.status.setOpen(t,e),this.setModified()}setQty(t){return typeof t=="number"&&t>0&&(this.qty=t,this.setModified()),this.qty}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Ir.includes(e)&&(e==="purchaseOptions"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):e==="amount"||e==="deduction"||e==="unitPrice"?this[e]=this[e]instanceof this._Amount?this[e].update(t[e]):this._Amount.init(t[e]):e==="status"?this[e]=this[e]instanceof this._Status?this[e].update(t[e]):this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function Pr(s){return s&&typeof s.toString=="function"?s.toString():s}const Sr=["amount","status","name"];class nt extends o.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_OrderLine:r,_Status:i}=t._constructor||{};this._Amount=e&&e._superclass===p._superclass?e:p,this._OrderLine=r&&r._superclass===it._superclass?r:it,this._Status=i&&i._superclass===X._superclass?i:X,this._orderLines=t._orderLines;const n=t._id||t.id;this.id=Rr(n),this._type=t._type||"Order",this.amount=this._Amount.init(t.amount),this.orderCode=t.orderCode,this.orderType="Order",this.status=this._Status.init(t.status),this.name=t.name}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"Order"}static get _superclass(){return"Order"}get isCompleted(){return this.status.isCompleted}get isClosed(){return this.status.isClosed}get isExpired(){return this.status.isExpired}get isInvalid(){return this.status.isInvalid}get isOpen(){return this.status.isOpen}get isTerminated(){return this.status.isTerminated}get orderLines(){return this._OrderLine.initOnlyValidFromArray(this._orderLines||[])}getAmount(){return this.amount}getCurrencyCode(){return this.amount?this.amount.getCurrencyCode():null}getFullOrderNumber(t="."){return`${this.orderNumber}${t}${this.revisionNumber}`}increaseRevisionNumber(){return this.revisionNumber+=1,this}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setClosed(t,e){return this.status.setClosed(t,e),this.setModified()}setExpired(t,e){return this.status.setExpired(t,e),this.setModified()}setInvalid(t,e){return this.status.setInvalid(t,e),this.setModified()}setOpen(t,e){return this.status.setOpen(t,e),this.setModified()}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Sr.includes(e)&&(e==="amount"?this[e]=this.amount instanceof this._Amount?this.amount.update(t[e]):this._Amount.init(t[e]):e==="status"?this[e]=this.status instanceof this._Status?this.status.update(t[e]):this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}updateAmount(){const t=this.orderLines;if(t.length===0)return this;const e=t.reduce((r,i)=>{var n;return r+((n=i==null?void 0:i.amount)==null?void 0:n.value)||0},0);return this.update({amount:{value:e}})}}function Rr(s){return s&&typeof s.toString=="function"?s.toString():s}const Vr=["active","deleted","remarks","result"];class ne extends o.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Transaction:e}=t._constructor||{};this._Transaction=e&&e._superclass===G._superclass?e:G,this._transaction=t._transaction,this._type=t._type||"PaymentResult";const r=t._id||t.id;this.id=Tr(r),this.paymentResultCode=Er(t,"paymentResultCode"),this.paymentResultType=t.paymentResultType||"PaymentResult",this.result=t.result,this.resultRef=t.resultRef,this.resultType=t.resultType,this.transactionCode=t.transactionCode}static dummyData(){return{paymentResultType:"PaymentResult",result:{id:"resultId"},resultType:"resultType",tenantCode:"tenantCode",transactionCode:"transactionCode"}}static get _classname(){return"PaymentResult"}static get _superclass(){return"PaymentResult"}get isValid(){return super.isValid&&!!this.resultType&&!!this.transactionCode}get amount(){throw new Error(`${this._classname} subclass should implement get amount`)}get billedAmount(){throw new Error(`${this._classname} subclass should implement get billedAmount`)}get paymentMethod(){throw new Error(`${this._classname} subclass should implement get paymentMethod`)}get receivedAmount(){throw new Error(`${this._classname} subclass should implement get receivedAmount`)}get resultStatus(){throw new Error(`${this._classname} subclass should implement get resultStatus`)}get transaction(){return this._Transaction.init(this._transaction)}addMetadata(t,e){return this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,t,e),this}addRemark(t,e){return this.remarks=o.KeyValueObject.insertOrUpdateRecord(this.remarks,t,e),this}compareStatus(t){throw new Error(`${this.paymentResultType} subclass should implement compareStatus`)}getCode(){return this.paymentResultCode}getPaidAmount(){throw new Error(`${this.paymentResultType} subclass should implement getPaidAmount`)}getPaidTimestamp(){throw new Error(`${this.paymentResultType} subclass should implement getPaidTimestamp in milliseconds`)}getPaymentCode(){throw new Error(`${this.paymentResultType} subclass should implement getPaymentCode`)}getTransactionStatus(){throw new Error(`${this.paymentResultType} subclass should implement getTransactionStatus`)}handlePayment(t){if(!this.isForThisPayment(t))return{payment:t,err:new Error("the payment result is not for this payment")};if(!this.isSameAmount(t))return{payment:t,err:new Error("the amount was not matched")};try{return t.settled(),t.setPaidAmount(this.getPaidAmount()).setPaidTimestamp(this.getPaidTimestamp()).setPaymentResultCode(this.paymentResultCode),{payment:t,err:null}}catch(e){return{payment:t,err:e}}}isForThisPayment(t){return this.getPaymentCode()===t.paymentCode}isSameAmount(t){return this.getPaidAmount()===t.getAmount()}isSuccess(){throw new Error(`${this.paymentResultType} subclass should implement isSuccess`)}setupMetadata(){const t=this.amount,e=this.paymentMethod;return this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,"AMOUNT",t),this.metadata=o.Metadata.insertOrUpdateRecord(this.metadata,"PAYMENT_METHOD",e),this.remarks=o.KeyValueObject.insertOrUpdateRecord(this.remarks,"amount",t),this.remarks=o.KeyValueObject.insertOrUpdateRecord(this.remarks,"paymentMethod",e),this}setupRemarks(){return this.setupMetadata()}update(t){return Object.keys(t).forEach(e=>{Vr.includes(e)&&(this[e]=t[e])}),super.update(t)}}function Er(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Tr(s){return s&&typeof s.toString=="function"?s.toString():s}const Dr=["active","deleted","description","intangible","limitPercentage","lineOptions","maxPerWallet","name","originalStock","owner","productOptions","remarks","requiredStoreItemCode","stock"];class ae{constructor(t={}){t=t||{};const{_ItemOption:e}=t._constructor||{};this._ItemOption=e&&e._superclass===E?e:E;const r=t._id||t.id;this.id=Lr(r),this._type=t._type||"StoreItem",this.active=typeof t.active<"u"?!!t.active:!0,this.created=t.created||new Date().valueOf(),this.creator=t.creator,this.deleted=t.deleted||!1,this.description=t.description||"",this.intangible=t.intangible||!1,this.limitPercentage=t.limitPercentage||100,this.lineOptions=this._ItemOption.initOnlyValidFromArray(t.lineOptions),this.maxPerWallet=t.maxPerWallet||1,this.metadata=o.Metadata.initOnlyValidFromArray(t.metadata),this.modified=t.modified||new Date().valueOf(),this.name=t.name||"",this.originalStock=t.originalStock||0,this.owner=t.owner,this.productCode=xr(t,"productCode"),this.productOptions=this._ItemOption.initOnlyValidFromArray(t.productOptions),this.requiredStoreItemCode=t.requiredStoreItemCode,this.remarks=o.KeyValueObject.initOnlyValidFromArray(t.remarks),this.stock=t.stock||0,this.storeItemType=t.storeItemType||"StoreItem",this.tenantCode=t.tenantCode}static dummyData(){return{name:"badge",tenantCode:"tenantCode"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"StoreItem"}static get _superclass(){return"StoreItem"}get isValid(){return!!this.tenantCode&&!!this.name}get isReachedLimitPercentage(){return this.soldPercentage>=this.limitPercentage}get soldPercentage(){return(this.originalStock-this.stock)/this.originalStock*100}get summary(){return{product:this,productCode:this.productCode,name:this.name}}ableToHave(t){return this.maxPerWallet>=t}checkStoreItemItemOptions(t=[]){return K.getItemOptionFillInsByTarget({itemOptionFillIns:t,target:"StoreItem",targetCode:this.productCode}).reduce((r,i)=>{const n=i.getKey(),a=this.getStoreItemOptionByKey(n);return a?(a.isValidFillInValue(i.getValue())||r.errMsgs.push(`the product(${this.productCode}) option's(${n}) fillInValue is invalid`),r):(r.errMsgs.push(`options of the product(${this.productCode}) does not contain key: "${n}"`),r)},{errMsgs:[]})}getCode(){return this.productCode}getMetadataValueByKey(t){return o.Metadata.getValueByKey(this.metadata||[],t)}getStoreItemOptionByKey(t){const e=this._ItemOption.getByKey(this.productOptions,t);return e.length===1?e[0]:null}hasStock(t){return this.stock>=t}isQualified(t){const e=this.getMetadataValueByKey("RULES")||[];return e.length===0?!0:e.reduce((r,i)=>r||o.getValidation(i,t,Mr,o.KeyValueObject),!1)}isTicket(){return!1}setModified(){return this.modified=new Date().valueOf(),this}update(t){return Object.keys(t).forEach(e=>{Dr.includes(e)&&(e==="metadata"?this[e]=o.Metadata.initOnlyValidFromArray(t[e]):e==="productOptions"?this[e]=this._ItemOption.initOnlyValidFromArray(t[e]):e==="remarks"?this[e]=o.KeyValueObject.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this.setModified()}}function Lr(s){return s&&typeof s.toString=="function"?s.toString():s}function xr(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Mr(s,t){return o.getValueByKeys(s.split("."),t)}const Fr=Object.freeze(Object.defineProperty({__proto__:null,Amount:p,BillingAccount:te,BillingProject:ee,Cart:z,CartItem:Y,Category:se,CreditNote:rt,CreditNoteLine:st,CreditNoteRepo:re,Currency:ie,Invoice:N,InvoiceLine:Q,ItemOption:E,ItemOptionLocale:J,KeyValueObject:o.KeyValueObject,Merchandise:R,Order:nt,OrderLine:it,PaymentCharge:tt,PaymentGateway:H,PaymentItem:W,PaymentResult:ne,Price:P,PriceStrategy:k,Product:T,Receipt:L,ReceiptLine:D,Status:O,StatusQStore:V,StatusQStoreInvoice:Gt,StatusQStoreInvoiceLine:kt,StatusQStoreOrder:X,StatusQStoreOrderLine:Z,StoreItem:ae,Transaction:G,WalletItem:et},Symbol.toStringTag,{value:"Module"})),$r={...Qe,...cr,...Fr};Object.defineProperty(exports,"KeyValueObject",{enumerable:!0,get:()=>o.KeyValueObject});exports.Amount=p;exports.BillingAccount=te;exports.BillingProject=ee;exports.Cart=z;exports.CartItem=Y;exports.Category=se;exports.Chain=I;exports.ChainManager=lt;exports.ChainManagerFactory=pt;exports.ChainTarget=ht;exports.ComplimentaryItemManager=Ft;exports.CouponManager=$t;exports.CreditNote=rt;exports.CreditNoteLine=st;exports.CreditNoteRepo=re;exports.Currency=ie;exports.Invoice=N;exports.InvoiceLine=Q;exports.ItemOption=E;exports.ItemOptionLocale=J;exports.Merchandise=R;exports.Order=nt;exports.OrderLine=it;exports.PaymentCharge=tt;exports.PaymentGateway=H;exports.PaymentItem=W;exports.PaymentResult=ne;exports.Price=P;exports.PriceStrategy=k;exports.Product=T;exports.Receipt=L;exports.ReceiptLine=D;exports.Status=O;exports.StatusQStore=V;exports.StatusQStoreInvoice=Gt;exports.StatusQStoreInvoiceLine=kt;exports.StatusQStoreOrder=X;exports.StatusQStoreOrderLine=Z;exports.StoreItem=ae;exports.Transaction=G;exports.WalletItem=et;exports.adminSettle=Dt;exports.calculateAmount=Lt;exports.calculateByCoupon=mt;exports.calculator=j;exports.checkDuplicate=yt;exports.default=$r;exports.defaultComparator=gt;exports.defaultSort=zt;exports.eleInArrayComparator=qt;exports.firstLetterToLower=ft;exports.getFakeClass=Mt;exports.getSubClass=xt;exports.handlerOrderList=Jt;exports.isAllEqual=Xt;exports.isDescendingOrder=Zt;exports.makeResponseHelper=Ut;exports.objectAllInArrayComparator=Nt;exports.objectComparator=Bt;exports.objectOrderInArrayComparator=jt;exports.setQuery=Kt;exports.stringHelper=A;
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("@questwork/q-utilities"),N=require("lodash");class m{constructor(t={}){t=t||{},this.currencyCode=t.currencyCode||t.currency,this.value=t.value,this.default=t.default||0}static dummyData(){return{currencyCode:"USD",value:100}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Amount"}static get _superclass(){return"Amount"}static getAmountsByCurrency(t,e){return t.filter(i=>i.currencyCode===e)}static getAmountsByCurrencyCode(t,e){return t.filter(i=>i.currencyCode===e)}get isValid(){return typeof this.currencyCode=="string"&&!!this.currencyCode&&typeof this.value=="number"}displayAmount(t){return!this.value===0?t||"":`${this.currencyCode}${this.value}`}getCurrencyCode(){return this.currencyCode}update(t){return Object.keys(t).forEach(e=>{this[e]=t[e]}),this}}function G(s,t){return Ce(t).map(r=>r.reduce((n,a)=>{if(n.qty===0)return n;let u;a.recursing?u=Vt:u=ye;const c=u(a,s);return n.value+=c.value,n.qty=c.qty,n.priceStrategy=c.priceStrategy,n},{priceStrategy:null,value:0,qty:s}))}function ye(s,t){const e=s;if(t<e.min)return{value:0,qty:t};const i=s.max===null?t:Math.min(s.max,t);return{priceStrategy:e.priceStrategy,value:Et(s,i),qty:s.max===null||s.max>=t?0:t-s.max}}function Vt(s,t,e=0,i=0){const r=s;if(t<r.min)return{amount:0,qty:t};const n=Et(s,s.min),a=t-s.min;return a===0||s.max!==null&&s.max-a<s.min?{priceStrategy:r.priceStrategy,value:i+i,qty:a}:Vt(s,a,e+s.min,i+n)}function Et(s,t){const e=s.value*t*(1-s.discount)-s.deduction;return e<0?0:e}function Ce(s=[]){const t=[],e=[];function i(r){let n,a;for(n=0;n<r.length;n++)a=r.splice(n,1)[0],e.push(a),r.length===0&&t.push(e.slice()),i(r),r.splice(n,0,a),e.pop();return t}return i(s)}class w{constructor(t={}){t=t||{},this.options=t}addException(t,e){return this.chainManager.addException(t,e),this}exitChain(t){}async handleRequest(t){throw new Error("should implement by subclass")}hasException(){return this.chainManager.hasException()}async next(t){return this.chainManager.exitOnErr&&t.hasException()?this.exitChain(t):(this.successor&&await this.successor.handleRequest(t),this.exitChain(t))}setChainManager(t){return this.chainManager=t,this}setSuccessor(t){return this.successor=t,this}}class ft{constructor(t){t=t||{},this.exitOnErr=t.exitOnErr||!1,this.runAllChains=typeof t.runAllChains<"u"?!!t.runAllChains:!0,this.chains=t.chains||[],this.chainTarget=t.chainTarget}appendChains(t){return t.forEach(e=>{e.setChainManager(this);const i=this.chains.length;i>0&&t[i-1].setSuccessor(e),this.chains.push(e)}),this}addException(t,e){if(typeof e>"u")return this.exceptionHandler.setProp(t),this;const i=this.exceptionHandler.getResult(t);return Array.isArray(i)?this.exceptionHandler.setProp({[t]:i.concat(e)}):this.exceptionHandler.setProp({[t]:Array.isArray(e)?e:[e]}),this}createChains({chains:t=[]}={}){if(t.find(e=>!(e instanceof w)))throw new Error("every chain must be an instance of Chain");return this.appendChains(t)}getResult(){const t={data:this.chainTarget.getResult()};return this.chainTarget.hasException()&&(t.err=this.chainTarget.getException()),t}async handleRequest(){await this.chains[0].handleRequest(this.chainTarget)}hasException(){return this.exceptionHandler.isNotEmpty()}resetHandlers(){return this.exceptionHandler.clear(),this.resultHandler.clear(),this}}class _e{constructor(){this.result={}}getResult(t){return t?this.result[t]:this.result}isNotEmpty(){return Object.keys(this.result).length>0}reset(){return this.result={},this}setProp(t){return this.result=Object.assign(this.result,t),this}unsetProp(t){return typeof this.result[t]<"u"&&delete this.result[t],this}}class yt{constructor(t){t=t||{},this.exceptionHandler=t.exceptionHandler||new _e}addException(t,e){if(typeof e>"u")return this.exceptionHandler.setProp(t),this;const i=this.exceptionHandler.getResult(t),r=e instanceof Error?e.message:e;return Array.isArray(i)?this.exceptionHandler.setProp({[t]:i.concat(r)}):this.exceptionHandler.setProp({[t]:Array.isArray(r)?r:[r]}),this}getException(){return this.exceptionHandler.getResult()}getResult(){throw new Error("should implement by subclass")}hasException(){return this.exceptionHandler.isNotEmpty()}reset(){return this.exceptionHandler.reset(),this}setProp(t){return Object.assign(this,t),this}unsetProp(t){return t!=="exceptionHandler"&&typeof this[t]<"u"&&delete this[t],this}}function Ct({coupon:s,price:t,currencyCode:e}){const{couponDetails:i}=s;if(!i)return 0;const{type:r,item:n}=i;if(n)switch(r){case"Deduction":return Ae({price:t,couponDetails:i,currencyCode:e});case"Percentage":return Oe({price:t,couponDetails:i});default:return 0}}function Ae({price:s,couponDetails:t,currencyCode:e}){const{value:i}=t;return l.KeyValueObject.foundValueByKey(i,e)}function Oe({price:s,couponDetails:t}){const{value:e}=t;return s.value*(e/100)}class ve extends w{constructor(t={}){super(t),this.groupCategory=t.groupCategory,this.categories=t.categories,this.walletItems=t.walletItems}async handleRequest(t){try{const{lines:e,users:i}=t,r=be(this.categories,this.walletItems);e.forEach(n=>{Pe(n,r)}),await this.next(t)}catch(e){t.addException("calculate categories limit fail",e.message),this.exitChain()}}}function be(s=[],t=[]){return s.reduce((e,i)=>{const{categoryCode:r,codes:n,name:a,max:u,min:c,productCodes:o=[]}=i,d=t.filter(h=>Ie(h)&&o.includes(h.productCode));return e.push({categoryCode:r,codes:n,max:u,min:c,name:a,owned:d.length,productCodes:o,used:0}),e},[])}function Pe(s,t){const{productsQty:e,updatedItem:i}=s;Object.keys(e).forEach(r=>{const n=t.find(a=>a.productCodes.includes(r)&&a.codes.includes(i.merchandiseCode));if(n){const a=n.max-(n.used+n.owned);if(a===0)i.qty=0,s.disabled=!0;else{e[r]*i.qty>a&&(i.qty=0,s.errors.push(`You have exceeded the maximum number of category "${n.name}".`));const c=we(i,a,e[r]);n.used+=c}}})}function we(s,t,e){let i;const r=e*s.qty;return t-r>=0?i=r:(s.qty=t,i=t),i}function Ie(s){if(!s)return!1;if(typeof s.isInWallet<"u")return s.isInWallet;const t=s.status||{};return!t.cancelled&&!t.rejected&&!t.refunded&&!t.refundRequested}class Se extends w{constructor(t={}){super(t),this.currency=t.currency,this.dateTime=t.dateTime,this.entitlements=t.entitlements||[],this.merchandises=t.merchandises}async handleRequest(t){try{const{lines:e,registration:i,user:r}=t,n=N.cloneDeep(this.entitlements);e.forEach(a=>{const u=Te(a,this.dateTime),c=Fe(u,a,{registration:i,user:r}),o=Ve(this.currency.code,c,a),d=Ee(o,this.currency.code,a);Object.assign(a.updatedItem,d||{})}),Re(e,n,this.currency.code),await this.next(t)}catch(e){t.addException("get price fail",e.message),this.exitChain()}}}function Re(s,t=[],e){Array.from(s).sort((r,n)=>n.updatedItem.price&&r.updatedItem.price?n.updatedItem.price.value-r.updatedItem.price.value:1).forEach(r=>{const{merchandise:n,updatedItem:a}=r,{priceStrategies:u=[],qty:c}=a,{merchandiseCode:o,productCodes:d}=n,{waived:h,entitlementsRemarkValue:g}=De(t,d,c),p=u.map(x=>x.toCalculatorRule({currencyCode:e})),f=c-h;let y=G(f,p);y.length===0&&(a.qty=0,r.disabled=!0,r.errors.push("No available price.")),y=(y||[]).sort((x,mt)=>x.value-mt.value);const[C={}]=y;C.qty>0&&r.errors.push("Exceed maximum quantity per transaction."),C.qty<0&&r.errors.push("No available price.");const{priceStrategy:_,value:v}=C,b=_||u[0],P=m.init(b?b.getAmountByCurrencyCode(e):null),K=m.init({value:v,currencyCode:e}),lt=(P?P.value:0)*f-(K?K.value:0)+(P?P.value:0)*h,dt=m.init({value:lt,currencyCode:e});let L=l.KeyValueObject.initOnlyValidFromArray([...a.remarks||[]]);L=l.KeyValueObject.updateOrInsertRecord(L,"entitlements",g);let M=l.Metadata.initOnlyValidFromArray([...a.metadata||[]]);M=l.Metadata.updateOrInsertRecord(M,"entitlements",g);const ht={merchandiseCode:o,price:P,discount:dt,subTotal:K,qty:c,waived:h,remarks:L,metadata:M,priceStrategies:u,priceStrategy:b};Object.assign(r.updatedItem,ht)})}function Ve(s,t,e){if(t.length===0)return[];const{updatedItem:i}=e,r=t.filter(n=>n.hasCurrencyCode(s));return r.length===0&&(i.qty=0,e.disabled=!0,e.errors.push(`Not support currency "${s}".`)),r}function Ee(s,t,e){if(s.length===0)return null;const{merchandise:i,updatedItem:r}=e,{qty:n}=r,{merchandiseCode:a}=i,u=s.map(_=>_.toCalculatorRule({currencyCode:t}));let c=G(n,u);if(c.length===0)return r.qty=0,e.disabled=!0,e.errors.push("No available price."),null;c=c.sort((_,v)=>_.value-v.value);const[o={}]=c;if(o.qty>0)return e.errors.push("Exceed maximum quantity per transaction."),null;if(o.qty<0)return e.errors.push("No available price."),null;const{priceStrategy:d,value:h}=o,g=d||s[0],p=m.init(g.getAmountByCurrencyCode(t)),f=m.init({value:h,currencyCode:t}),y=p.value*n-f.value,C=m.init({value:y,currencyCode:t});return{merchandiseCode:a,price:p,discount:C,subTotal:f,qty:n,priceStrategies:s,priceStrategy:g}}function De(s,t,e){if(s.length===0)return{waived:0,entitlementsRemarkValue:[]};const i=Array.from({length:e}).map(()=>[...t]),{waived:r,entitlementsRemarkValue:n}=i.reduce((a,u)=>{if(a.continue===!1)return a;const{entitlementKeyValues:c}=u.reduce((o,d)=>{const h=s.findIndex(g=>(g.value||[]).includes(d));if(h!==-1){const[g]=s.splice(h,1);o.cutEntitlements.push(g),o.entitlementKeyValues.push({key:d,value:g.key})}return o},{cutEntitlements:[],entitlementKeyValues:[]});return u.length!==c.length?a.continue=!1:(a.waived+=1,a.entitlementsRemarkValue.push(...c)),a},{continue:!0,waived:0,entitlementsRemarkValue:[]});return{waived:r,entitlementsRemarkValue:n}}function Te(s,t){const{merchandise:e,updatedItem:i}=s,r=e.getPricesByTime(t);return r.length===0&&(i.qty=0,s.disabled=!0,s.errors.push("Currently not available for sale.")),r.sort((n,a)=>n.dateBegin-a.dateBegin)}function Fe(s,t,e){const{updatedItem:i}=t;let r=[];return s.length!==0&&(r=s.reduce((n,a)=>{const u=a.getStrategiesByRestrictions(e);return n.concat(u)},[])),r.length===0&&(i.qty=0,t.available=!1,t.errors.push("You are not entitled to this item.")),r}class Le extends w{constructor(t={}){super(t),this.currency=t.currency,this.dateTime=t.dateTime,this.entitlements=t.entitlements||[],this.merchandises=t.merchandises}async handleRequest(t){try{const{lines:e}=t,i=N.cloneDeep(this.entitlements);e.forEach(r=>{const n=je(r,this.dateTime),a=qe(n),u=xe(this.currency.code,a,r),c=Be(u,this.currency.code,r);Object.assign(r.updatedItem,c||{})}),Me(e,i,this.currency.code),await this.next(t)}catch(e){t.addException("get price fail",e.message),this.exitChain()}}}function Me(s,t=[],e){Array.from(s).sort((r,n)=>n.updatedItem.price.value-r.updatedItem.price.value).forEach(r=>{const{merchandise:n,updatedItem:a}=r,{priceStrategies:u,qty:c}=a,{merchandiseCode:o,productCodes:d}=n,{waived:h,entitlementsRemarkValue:g}=$e(t,d,c),p=u.map(x=>x.toCalculatorRule({currencyCode:e}));Dt({rules:p,max:9999});const f=c-h;let y=G(f,p);y.length===0&&(a.qty=0,r.disabled=!0,r.errors.push("No available price.")),y=y.sort((x,mt)=>x.value-mt.value);const[C={}]=y;C.qty>0&&r.errors.push("Exceed maximum quantity per transaction."),C.qty<0&&r.errors.push("No available price.");const{priceStrategy:_,value:v}=C,b=_||u[0],P=m.init(b.getAmountByCurrencyCode(e)),K=m.init({value:v,currencyCode:e}),lt=P.value*f-K.value+P.value*h,dt=m.init({value:lt,currencyCode:e});let L=l.KeyValueObject.initOnlyValidFromArray([...a.remarks||[]]);L=l.KeyValueObject.updateOrInsertRecord(L,"entitlements",g);let M=l.Metadata.initOnlyValidFromArray([...a.metadata||[]]);M=l.Metadata.updateOrInsertRecord(M,"entitlements",g);const ht={merchandiseCode:o,price:P,discount:dt,subTotal:K,qty:c,waived:h,remarks:L,metadata:M,priceStrategies:u,priceStrategy:b};Object.assign(r.updatedItem,ht)})}function xe(s,t,e){if(t.length===0)return[];const{updatedItem:i}=e,r=t.filter(n=>n.hasCurrencyCode(s));return r.length===0&&(i.qty=0,e.disabled=!0,e.errors.push(`Not support currency "${s}".`)),r}function Be(s,t,e){if(s.length===0)return null;const{merchandise:i,updatedItem:r}=e,{qty:n}=r,{merchandiseCode:a}=i,u=s.map(_=>_.toCalculatorRule({currencyCode:t}));Dt({rules:u,max:9999});let c=G(n,u);if(c.length===0)return r.qty=0,e.disabled=!0,e.errors.push("No available price."),null;c=c.sort((_,v)=>_.value-v.value);const[o={}]=c;if(o.qty>0)return e.errors.push("Exceed maximum quantity per transaction."),null;if(o.qty<0)return e.errors.push("No available price."),null;const{priceStrategy:d,value:h}=o,g=d||s[0],p=m.init(g.getAmountByCurrencyCode(t)),f=m.init({value:h,currencyCode:t}),y=p.value*n-f.value,C=m.init({value:y,currencyCode:t});return{merchandiseCode:a,price:p,discount:C,subTotal:f,qty:n,priceStrategies:s,priceStrategy:g}}function $e(s,t,e){if(s.length===0)return{waived:0,entitlementsRemarkValue:[]};const i=Array.from({length:e}).map(()=>[...t]),{waived:r,entitlementsRemarkValue:n}=i.reduce((a,u)=>{if(a.continue===!1)return a;const{entitlementKeyValues:c}=u.reduce((o,d)=>{const h=s.findIndex(g=>(g.value||[]).includes(d));if(h!==-1){const[g]=s.splice(h,1);o.cutEntitlements.push(g),o.entitlementKeyValues.push({key:d,value:g.key})}return o},{cutEntitlements:[],entitlementKeyValues:[]});return u.length!==c.length?a.continue=!1:(a.waived+=1,a.entitlementsRemarkValue.push(...c)),a},{continue:!0,waived:0,entitlementsRemarkValue:[]});return{waived:r,entitlementsRemarkValue:n}}function je(s,t){const{merchandise:e,updatedItem:i}=s,r=e.getPricesByTime(t);return r.length===0&&(i.qty=0,s.disabled=!0,s.errors.push("Currently not available for sale.")),r.sort((n,a)=>n.dateBegin-a.dateBegin)}function qe(s){return s.length===0?[]:s.reduce((e,i)=>{const r=i.priceStrategies;return e.concat(r)},[])}function Dt({rules:s,max:t}){return s.forEach(e=>{const i=e;i.max=t}),s}class Tt extends w{constructor(t={}){super(t)}async handleRequest(t){try{const{lines:e}=t;e.forEach(i=>{const{item:r={}}=i;i.updatedItem={...r,waived:0,remarks:l.KeyValueObject.initOnlyValidFromArray(r.remarks),metadata:l.Metadata.initOnlyValidFromArray(r.metadata),price:m.init(r.price),discount:m.init(r.discount),subTotal:m.init(r.subTotal),priceStrategy:null},i.available=!0,i.disabled=!1,i.errors=[],i.messages=[],i.validated=!0}),await this.next(t)}catch(e){t.addException("init lines fail",e.message),this.exitChain()}}}class Ft extends w{constructor(t={}){super(t)}async handleRequest(t){try{const{lines:e,users:i}=t;e.forEach(r=>{const{updatedItem:n,merchandise:a}=r,u=a.getStock();if(u===0)r.disabled=!0,r.errors.push("Full.");else{const{qty:c}=n;n.qty=c>u?u:c}}),await this.next(t)}catch(e){t.addException("calculate merchansises limit fail",e.message),this.exitChain()}}}class Ne extends w{constructor(t={}){super(t),this.currency=t.currency}async handleRequest(t){try{const{lines:e}=t;e.forEach(i=>{Ue({line:i,currency:this.currency})}),await this.next(t)}catch(e){t.addException("handle related coupons fail",e.message),this.exitChain()}}}function Ue({line:s,currency:t}){const{updatedItem:e}=s,{price:i,qty:r,discount:n,purchaseOptions:a,remarks:u,subTotal:c}=e;if(a.length===0||e.qty===0)return;const o=Ge(a);if(!o)return;const d=c.value+o*(t.factor||1),h={subTotal:m.init({value:d,currencyCode:t.code})};Object.assign(e,h)}function Ge(s){var t;for(const e of s){const i=(t=e.value)==null?void 0:t.find(r=>r.key==="priceAdjustment");if(i)return Number(i.value)}return null}class Lt extends w{constructor(t={}){super(t),this.products=t.products||[]}async handleRequest(t){try{const{lines:e,users:i}=t,r=Ke(this.products);e.forEach(n=>{const{merchandise:a,productsQty:u,updatedItem:c}=n,{qty:o}=c;Object.keys(u).forEach(d=>{const h=u[d],g=r[d];if(!g)throw new Error(`Invalid merchandise "${a.name}": no productCode "${d}"`);const{name:p,stock:f,used:y}=g,C=f-y;if(C===0)c.qty=0;else{const _=h*o;if(C-_>0)g.used+=_;else{const b=Math.floor(C/h);b===0?(c.qty=0,n.disabled=!0,n.errors.push(`"${p}" does not have enough stock`)):(g.used+=b*h,c.qty=Math.min(c.qty,b))}}})}),await this.next(t)}catch(e){t.addException("calculate products limit fail",e.message),this.exitChain()}}}function Ke(s){return s.reduce((t,e)=>{const{productCode:i,name:r,stock:n}=e;return t[i]={name:r,stock:n,used:0},t},{})}class He extends w{constructor(t={}){super(t),this.products=t.products||[],this.walletItems=t.walletItems||[]}async handleRequest(t){try{const{lines:e,users:i}=t,r=this.walletItems.filter(We).map(u=>u.productCode),n=e.reduce((u,c)=>{const{merchandise:o,updatedItem:d}=c;return d.qty>0?u.concat(o.productCodes):u},[]),a=[...new Set(n.concat(r))];e.forEach(u=>{const{item:c,updatedItem:o,merchandise:d}=u,{productCodes:h}=d;this.products.filter(p=>h.includes(p.productCode)).forEach(p=>{const f=r.reduce((v,b)=>b===p.productCode?v+1:v,0);p.maxPerWallet>f||(u.disabled=!0);const[y=[]]=l.KeyValueObject.getValuesByKey(p.remarks,"restrictions"),[C=[]]=l.KeyValueObject.getValuesByKey(y,"requiredProductCodes");if(C.length===0)return;C.some(v=>a.includes(v))||(u.disabled=!0,o.qty=0)})}),await this.next(t)}catch(e){t.addException("check product restriction fail",e.message),this.exitChain()}}}function We(s){if(!s)return!1;if(typeof s.isInWallet<"u")return s.isInWallet;const t=s.status||{};return!t.cancelled&&!t.rejected&&!t.refunded&&!t.refundRequested}class Qe extends w{constructor(t={}){super(t)}async handleRequest(t){try{const{lines:e,users:i}=t;e.forEach(r=>{const{updatedItem:n}=r,{purchaseOptions:a=[]}=n;if(a.length===0||n.qty===0)return;let u=!1,c=!1;a.forEach(o=>{(o.value||[]).forEach(d=>{const{required:h,validated:g,value:p}=d;h&&!p&&!u&&(u=!0,r.validated=!1,r.errors.push("Please fill in the option(s).")),g&&!c&&(c=!0,r.errors.push("Invalid option(s)."))})})}),await this.next(t)}catch(e){t.addException("Check product restriction failed.",e.message),this.exitChain()}}}class Ye extends w{constructor(t={}){super(t),this.autoUseCoupon=t.autoUseCoupon||!1,this.currency=t.currency,this.walletItems=t.walletItems}async handleRequest(t){try{const{lines:e,relatedTotalCoupons:i=[],users:r}=t,n=this.walletItems.filter(a=>a.isCoupon);e.forEach(a=>{ze({line:a,currencyCode:this.currency.code}),ts(a,n,this.autoUseCoupon,this.currency.code)}),e.forEach(a=>{Xe(a)}),Je({lines:e,currencyCode:this.currency.code,relatedTotalCoupons:i}),ke({lines:e,autoUseCoupon:this.autoUseCoupon,currencyCode:this.currency.code,relatedTotalCoupons:i}),await this.next(t)}catch(e){t.addException("handle related coupons fail",e.message),this.exitChain()}}}function ke({lines:s,autoUseCoupon:t,currencyCode:e,relatedTotalCoupons:i}){t&&i.forEach(r=>{const n=Mt(r,s,e);Object.assign(r,n)})}function Mt(s,t,e){const{availableCoupons:i,usedCoupons:r,product:n}=s;if(i.length>0&&t.filter(c=>n.isApplicableCoupon(c.merchandise)).reduce((c,o)=>{const{updatedItem:d={}}=o,{subTotal:h={}}=d;return h&&h.value&&(c+=h.value),c},0)>0){const[c]=i.splice(0,1);return c.setOnHold(),r.push(c),xt({lines:t,currencyCode:e,coupon:c}),Mt(s,t,e)}return s}function ze({line:s,currencyCode:t}){const{usedCoupons:e={},updatedItem:i}=s;Object.keys(e).forEach(r=>{_t(e[r]).forEach(n=>{const a=Bt({updatedItem:i,coupon:n,currencyCode:t});Object.assign(i,a)})})}function Je({lines:s,currencyCode:t,relatedTotalCoupons:e}){e.forEach(i=>{const{usedCoupons:r}=i;_t(r).forEach(n=>{xt({lines:s,currencyCode:t,coupon:n})})})}function xt({lines:s,currencyCode:t,coupon:e}){const i=s.filter(u=>e.isApplicableCoupon(u.merchandise)),r=i.reduce((u,c)=>{const{price:o={},qty:d}=c.updatedItem||{};return u+=o.value*d},0),{couponDetails:n,walletItemCode:a}=e;if(n){const{type:u,total:c}=n,{value:o}=n;switch(u){case"Deduction":{const d=l.KeyValueObject.foundValueByKey(o,t);i.forEach(h=>{const{updatedItem:g}=h,{price:p,qty:f,discount:y,remarks:C,subTotal:_}=g,v=d*(p.value*f/r)+y.value,b=_.value>d?_.value-d:0,P={discount:m.init({value:v,currencyCode:t}),remarks:gt(C,"USED_TOTAL_COUPONS",a),subTotal:m.init({value:b,currencyCode:t})};Object.assign(g,P)});break}case"Percentage":{i.forEach(d=>{const{updatedItem:h}=d,{price:g,qty:p,discount:f,remarks:y,subTotal:C}=h,_=g.value*(o/100)*p,v=_+f.value,b=C.value>_?C.value-_:0,P={discount:m.init({value:v,currencyCode:t}),remarks:gt(y,"USED_TOTAL_COUPONS",a),subTotal:m.init({value:b,currencyCode:t})};Object.assign(h,P)});break}}}}function Bt({updatedItem:s,coupon:t,currencyCode:e}){const{couponDetails:i,walletItemCode:r}=t;if(!i)return s;const{price:n,qty:a,discount:u,remarks:c,subTotal:o}=s,d=Ct({coupon:t,price:n,currencyCode:e}),h=d+u.value,g=o.value>d?o.value-d:0;return{...s,discount:m.init({value:h,currencyCode:e}),remarks:gt(c,"USED_ITEM_COUPONS",r),subTotal:m.init({value:g,currencyCode:e})}}function _t(s=[]){const t=[];return s.filter(e=>{const{walletItemCode:i}=e||{};return!i||t.includes(i)?!1:(t.push(i),!0)})}function gt(s,t,e){const i=l.KeyValueObject.foundValueByKey(s,t)||[],r=[...new Set([...i,e])];return l.KeyValueObject.insertOrUpdateRecord(s,t,r)}function Xe(s){const{relatedCoupons:t=[]}=s;s.relatedCoupons=t.map(e=>({...e,availableCoupons:e.coupons.filter(i=>!i.isOnHold)}))}function Ze(s,t,e,i){const{merchandise:r,usedCoupons:n={},updatedItem:a={}}=s;return t.filter(c=>c.isApplicableCoupon(r)&&c.isItemCoupon).reduce((c,o)=>{const d=o.product.productCode;let h=c.find(y=>y.productCode===d);const g=o.isOnHold;h||(h={coupons:[],product:o.product,productCode:d,usedQty:_t(n[d]).length},c.push(h)),h.coupons.push(o);const{qty:p,subTotal:f}=a;if(e&&!g&&h.usedQty<p&&f.value>0){o.setOnHold(),n[d]=[...n[d]||[],o];const y=Bt({updatedItem:a,currencyCode:i,coupon:o});Object.assign(a,y),h.usedQty=n[d].length}return c},[])}function ts(s,t,e,i){t.length>0&&(s.relatedCoupons=Ze(s,t,e,i))}class es extends yt{constructor(t={}){super(t),this.lines=t.lines,this.relatedTotalCoupons=t.relatedTotalCoupons,this.registration=t.registration,this.user=t.user}getResult(){return{lines:this.lines,relatedTotalCoupons:this.relatedTotalCoupons}}}class At{static getChainManager({payload:t={},serviceAppName:e,type:i}={}){let r=[];switch(i){case"CALCULATE_AMOUNT":return r=ss(t),this.calculateAmount({chains:r,payload:t,serviceAppName:e});case"CALCULATE_AMOUNT_FOR_GROUP":return r=is(t),this.calculateAmount({chains:r,payload:t,serviceAppName:e});default:throw new Error("invalid type")}}static calculateAmount({chains:t=[],payload:e={},serviceAppName:i}){const{lines:r,registration:n,relatedTotalCoupons:a,user:u}=e,c=new es({lines:r,registration:n||u,relatedTotalCoupons:a,user:u||{}}),o=new ft({chainTarget:c});return o.createChains({chains:t}),o}}function ss(s){const{autoUseCoupon:t,categories:e,currency:i,dateTime:r,entitlements:n,merchandises:a,products:u,walletItems:c}=s;return[new Tt,new ve({categories:e,walletItems:c}),new He({products:u,walletItems:c}),new Qe,new Ft,new Lt({products:u}),new Se({currency:i,dateTime:r,entitlements:n,merchandises:a}),new Ye({currency:i,autoUseCoupon:t,walletItems:c}),new Ne({currency:i})]}function is(s){const{currency:t,dateTime:e,entitlements:i,merchandises:r,products:n}=s;return[new Tt,new Ft,new Lt({products:n}),new Le({currency:t,dateTime:e,entitlements:i,merchandises:r})]}const rs=Object.freeze(Object.defineProperty({__proto__:null,ChainManagerFactory:At},Symbol.toStringTag,{value:"Module"}));function $t({adminSettleFormData:s={},component:t,eventRegistration:e,invoice:i,payeeName:r,payeeAddress:n,payeeCountry:a,cb:u}){const c=e||t.registration;t.invoice=i,t.adminSettleFormData={...i,...s,email:c&&c.getEmail()||"",payeeName:r,payeeAddress:n,payeeCountry:a,paidDate:new Date().valueOf(),totalAmount:ns(i)},u()}function ns(s){if(!s.amount)return"";const{amount:t}=s;return`${t.currencyCode} ${(t.value/100).toFixed(2)}`}async function jt(s){const{currency:t,merchandises:e=[],lines:i,products:r,user:n}=s,a={lines:i,merchandises:e,products:r,currency:t,dateTime:Date.now(),categories:[],entitlements:[],walletItems:[],user:{}},u=At.getChainManager({payload:a,type:"CALCULATE_AMOUNT"});await u.handleRequest();const{data:c={},err:o}=u.getResult();if(o)throw o;if((c.lines||[]).find(g=>Array.isArray(g.errors)&&g.errors.length>0))throw new Error("has invalid line");return{data:c,err:o}}function Ot(s){return s.charAt(0).toLowerCase()+s.slice(1)}function qt(s){const t=s.name,e=`${Ot(t)}Type`;class i extends s{constructor(n){const a=n||{};super(a),this[e]=a[e]||`${t}Event`}get isValid(){return super.isValid}static init(n){const a=new i(n);return a.isValid?a:null}static dummyData(){return{...super.dummyData(),[e]:`${t}Event`}}}return i}function Nt(){class s{constructor(e){const i=e||{};this._type="Fake",this.fakeCode=i.fakeCode,this.fakeType=i.fakeType||"Fake"}static dummyData(){return{fakeCode:"fakeCode"}}static init(e){const i=new s(e);return i.isValid?i:null}get isValid(){return!!this.fakeCode}}return s}class as{constructor(t={}){var e,i;this.mapping=(e=t.rule)==null?void 0:e.mapping,this.makeWalletItemHandler=t.makeWalletItemHandler,this.tiers=(i=t.rule)==null?void 0:i.tiers}get complimentaryCategories(){return this.mapping.map(t=>t.key)}get countableCategories(){const t=this.mapping.reduce((e,i)=>{const{value:r}=i;return Array.isArray(r)&&r.forEach(n=>e.add(n)),e},new Set);return Array.from(t)}process({walletItems:t}){const{complimentaryWalletItems:e,countableWalletItems:i}=os({complimentaryCategories:this.complimentaryCategories,countableCategories:this.countableCategories,walletItems:t}),r=cs({tiers:this.tiers,total:i.length}),{toBeAssignedItems:n,entitlements:a}=us({complimentaryWalletItems:e,tier:r,countableWalletItems:i,mapping:this.mapping});return{walletItems:this.makeWalletItemHandler(n),entitlements:a,tier:r}}}function us({complimentaryWalletItems:s,tier:t,countableWalletItems:e,mapping:i}){const{numOfComplimentaryItem:r}=t,n=r-s.length,a=e.map(o=>o.productCode),u=s.reduce((o,d)=>{const{productCode:h}=d,g=o.get(h)||0;return o.set(h,g+1),o},new Map),c=[];if(n>0){const d=i.find(g=>{const{value:p}=g;return p.find(f=>a.includes(f))}).key,h=u.get(d)||0;u.set(d,h+n),c.push({productCode:d,qty:n})}return{toBeAssignedItems:c,entitlements:Array.from(u,([o,d])=>({productCode:o,qty:d}))}}function cs({tiers:s,total:t}){const e=[...s].sort((r,n)=>r.gte-n.gte);let i=e[0];return e.forEach(r=>{t>=r.gte&&(i=r)}),i}function os({complimentaryCategories:s,countableCategories:t,walletItems:e}){return e.reduce((i,r)=>{const{productCode:n}=r;return s.includes(n)&&i.complimentaryWalletItems.push(r),t.includes(n)&&i.countableWalletItems.push(r),i},{complimentaryWalletItems:[],countableWalletItems:[]})}class Ut{constructor(t){this.makeWalletItemHandler=t.makeWalletItemHandler,this.rule=t.rule,this.type=t.type,this.handler=this.getHandler()}getHandler(){switch(this.type){case"TIER_MAPPING":return new as({rule:this.rule,makeWalletItemHandler:this.makeWalletItemHandler})}}process({walletItems:t}){return this.handler.process({walletItems:t})}}function ls({newRoles:s,originalRoles:t}){const e=Pt(s),i=Pt(t),r=new Set([...Object.keys(e),...Object.keys(i)]);return Array.from(r).reduce((n,a)=>{const u=e[a]||0,c=i[a]||0,o=u-c;return o!==0&&n.push({key:a,value:{delta:o,newValue:u,originalValue:c}}),n},[])}function Pt(s){return s.reduce((t,e)=>(e.getCouponCodes().forEach(r=>{const{key:n,value:a}=r;t[n]=t[n]?t[n]+a:a}),t),{})}class Gt{constructor(t){this.products=t.products||[],this.walletItems=t.walletItems||[],this.originalRoles=t.originalRoles||[],this.newRoles=t.newRoles||[]}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}get isValid(){return!!this}get couponProducts(){return this.products.filter(t=>t.isCoupon)}get couponWalletItems(){return this.walletItems.filter(t=>t.isCoupon)}get roleRelatedCoupons(){return ls({newRoles:this.newRoles,originalRoles:this.originalRoles})}get couponItemList(){return this.couponProducts.map(t=>{const e=this.walletItems.filter(o=>o.productCode===t.productCode),i=e.filter(o=>o.isUsed);i.forEach(o=>{o.useForWalletItems=this.walletItems.filter(d=>(o.useFor||[]).includes(d.walletItemCode))});const r=e.filter(o=>!o.isAvailableCoupon),n=l.KeyValueObject.foundValueByKey(this.roleRelatedCoupons,t.productCode)||{},a=t.maxPerWallet-(i.length+r.length),{qty:u,remarks:c}=ds({product:t,availableCoupons:r,roleBase:n,remainingQuota:a});return{product:t,usedCoupons:i,availableCoupons:r,alreadyHave:i.length+r.length,maxLimit:t.maxPerWallet,remainingQuota:a,qty:u,roleBase:n,remarks:c}})}setNewRoles(t){this.newRoles=t}}function ds({product:s,remainingQuota:t,availableCoupons:e,roleBase:i}){const{delta:r=0}=i,{maxPerWallet:n}=s;let a=r;const u=[];return r>0&&n&&r>t&&(a=0,u.push(`max ${n}`)),r<0&&n&&e.length<r&&(a=e.length,u.push(`only ${e.length} could be cancelled`)),{qty:a,remarks:u}}const hs=["value"];class W{constructor(t={}){t=t||{},this.target=t.target,this.targetCode=t.targetCode,this.key=t.key,this.value=t.value||[]}static dummyData(){return{target:"Merchandise",targetCode:"code",key:"color"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"ItemOptionFillIn"}static get _superclass(){return"ItemOptionFillIn"}static getItemOptionFillInsByTarget({itemOptionFillIns:t=[],target:e,targetCode:i}){if(!e)throw new Error("no target");return i?t.filter(r=>r.target===e&&r.targetCode===i):t.filter(r=>r.target===e)}get isValid(){return!!this.target&&!!this.targetCode&&!!this.key}getKey(){return this.key}getValue(){return this.value}update(t){return Object.keys(t).forEach(e=>{hs.includes(e)&&(this[e]=t[e])}),this}}function vt(s,t,e){e=e||{};let i;if(e.operation&&e.props&&(i=e.props.reduce((r,n)=>{const{prop:a,compareFn:u}=n,c=typeof u=="function"?u(s,t,a):bt(s,t,a);return r===null?c:wt(c,r,e.operation)},null),e.subOperation&&e.subOperation.operation)){const r=vt(s,t,e.subOperation);i=wt(r,i,e.operation)}return i}function bt(s,t,e){return s[e]===null||s[e]===void 0?!1:s[e]===t[e]}function Kt(s,t,e){if(s[e]===null||s[e]===void 0)return!1;if(!Array.isArray(s[e])&&!Array.isArray(t[e]))throw new TypeError("This function can only compare array.");return ms(s[e],t[e])>0}function Ht(s,t,e){return s[e]===null||s[e]===void 0?!1:s[e].isSame(t[e])}function Wt(s,t,e){if(s[e]===null||s[e]===void 0)return!1;if(!Array.isArray(s[e])&&!Array.isArray(t[e]))throw new TypeError("This function can only compare array.");return s[e].reduce((i,r)=>{const n=r.isSameIn(t[e]);return i===null?n:n&&i},null)}function Qt(s,t,e){if(s[e]===null||s[e]===void 0)return!1;if(!Array.isArray(s[e])&&!Array.isArray(t[e]))throw new TypeError("This function can only compare array.");return s[e].length!==t[e].length?!1:s[e].reduce((i,r,n)=>{const a=r.isSame(t[e][n]);return i===null?a:a&&i},null)}function wt(s,t,e){if(e.toLowerCase()==="or")return s||t;if(e.toLowerCase()==="and")return s&&t;throw new Error("The operation does not conform to the specification.")}function ms(s,t){const e=new Set(t);return s.filter(i=>e.has(i))}const gs="20200130",ps=[{data:[],err:null,isNew:null,message:null,total:0,version:"20200130"}];class fs{constructor(t={}){this.standardResponseObj=ys(t.responseVer)}get isValid(){return!!this.standardResponseObj}standardizeResponse(t={}){let e,i;return t.message&&(e=t.message),t.err&&(i={hasError:!0,message:t.err.message||t.err}),{...this.standardResponseObj,...t,err:i,message:e}}}function ys(s=gs){return s?ps.find(t=>t.version===s):null}function Yt(s){const t=new fs(s);if(!t.isValid)throw new TypeError("Invalid options for responseHelper");return t}function kt({ctx:s,ids:t}){const{clientApp:e}=s.state,{query:i}=s.request,{id:r}=s.params;if(s.isAuthenticated()&&!e)return{id:r,ids:t,...i};const n=e?e.name:null;return!n||n==="com.questwork.questwork-admin"?{id:r,ids:t,...i}:{id:r,ids:t,...i,clientAppName:n}}function Cs(s,t=34){const e=As(t);return _s(s,e)}function _s(s,t){const e=t.byCode;if(s===0)return e[0];let i="";const r=t.length;for(;s>0;)i=e[s%r]+i,s=Math.floor(s/r);return i}function As(s){let t="9876543210ABCDEFGHJKLMNPQRSTUVWXYZ";return s===58&&(t="9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz"),Os(t)}function Os(s){const t={},e={},i=s.length;let r,n;for(r=0;r<i;r++)n=s[r],t[r]=n,e[n]=r;return{byCode:t,byChar:e,length:i}}function vs({len:s=16,pattern:t="a1"}={}){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i="abcdefghijklmnopqrstuvwxyz",r="1234567890",n="~!@#$%^&*_+-=";let a="";t.includes("A")&&(a+=e),t.includes("a")&&(a+=i),t.includes("1")&&(a+=r),t.includes("#")&&(a+=n);const u=[...a];return[...new Array(s)].map(c=>u[Math.random()*u.length|0]).join``}function bs(s){return typeof s!="string"&&(s=s.toString()),s.split("").reverse().join("")}function Ps(s=34){const t=new Date().valueOf(),e=vs({len:8,pattern:"1"}),i=bs(`${t}${e}`);return Cs(i,s)}const A={setCode:Ps},ws=["label","locale","value"];class X{constructor(t={}){t=t||{},this.locale=t.locale,this.label=t.label,this.value=t.value||""}static dummyData(){return{}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"ItemOptionLocale"}static get _superclass(){return"ItemOptionLocale"}get isValid(){return!!this}update(t){return Object.keys(t).forEach(e=>{ws.includes(e)&&(this[e]=t[e])}),this}}const Is=["description","key","label","type","value","locales"];class E{constructor(t={}){t=t||{};const{_ItemOptionLocale:e}=t._constructor||{};this._ItemOptionLocale=e&&e._superclass===X._superclass?e:X,this.approved=t.approved||!1,this.description=t.description,this.itemOptionCode=Ss(t,"itemOptionCode"),this.itemOptionType=t.itemOptionType||"ItemOption",this.key=t.key,this.label=t.label,this.layout=t.layout,this.required=t.required||!1,this.type=t.type,this.value=t.value||"",this.locales=this._ItemOptionLocale.initOnlyValidFromArray(t.locales)}static dummyData(){return{key:"firstName"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"ItemOption"}static get _superclass(){return"ItemOption"}get isRequired(){return this.required}get isValid(){return!!this.key}isValidFillInValue(t){if(!Array.isArray(t))return!1;if(t.length===0)return!this.isRequired;if(t.length===1){const e=typeof t[0]=="string";return this.isRequired?e&&!!t[0]:e}return!1}update(t){return Object.keys(t).forEach(e=>{Is.includes(e)&&(e==="locales"?this[e]=this._ItemOptionLocale.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this}}function Ss(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}class H{constructor(t={}){t=t||{},this.description=t.description,this.header=t.header,this.key=t.key,this.type=t.type}static dummyData(){return{header:"First Name",key:"firstName",type:"TextInput"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"MerchandiseOption"}static get _superclass(){return"MerchandiseOption"}static convertToFormData(t=[]){const e={};return t.map(i=>{let r=!1;i.values.map(n=>{n.default&&(e[i.key]=n.value,r=!0)}),r||(e[i.key]="")}),e}static convertToInputs(t=[]){return t.map(e=>({type:e.type,label:e.header,name:e.key,values:e.values}))}static convertToPurchaseOptions(t=[]){const e=[];return t.map(i=>{let r=!1;i.values.map(n=>{n.default&&(e.push({key:i.key,value:n.value}),r=!0)}),r||e.push({key:i.key,value:""})}),e}get isValid(){return!!this.key}updateMerchandiseOption(t){Object.keys(t).forEach(e=>{this[e]=t[e]})}}const Rs=["allocatedAmount","productCode"];class j{constructor(t={}){t=t||{};const{_Amount:e}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this.allocatedAmount=this._Amount.init(t.allocatedAmount),this.productCode=t.productCode}static dummyData(){return{allocatedAmount:m.dummyData(),productCode:"productCode"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"AccountAllocation"}static get _superclass(){return"AccountAllocation"}get isValid(){return!!this.productCode&&!!this.allocatedAmount&&!!this.allocatedAmount.currencyCode&&typeof this.allocatedAmount.value=="number"}update(t){return Object.keys(t).forEach(e=>{Rs.includes(e)&&(e==="allocatedAmount"?this[e]=this._Amount.init(t[e]):this[e]=t[e])}),this}}const Vs=["accountAllocations","currencyCode"];class Z{constructor(t={}){t=t||{};const{_AccountAllocation:e}=t._constructor||{};this._AccountAllocation=e&&e._superclass===j._superclass?e:j,this.accountAllocations=this._AccountAllocation.initOnlyValidFromArray(t.accountAllocations),this.currencyCode=t.currencyCode}static dummyData(){return{accountAllocations:[j.dummyData()],currencyCode:"USD"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"AccountAllocationGroup"}static get _superclass(){return"AccountAllocationGroup"}get isValid(){return!!this.currencyCode&&this.accountAllocations.length>0&&this.accountAllocations.every(t=>{var e;return((e=t.allocatedAmount)==null?void 0:e.currencyCode)===this.currencyCode})}update(t){return Object.keys(t).forEach(e=>{Vs.includes(e)&&(e==="accountAllocations"?this[e]=this._AccountAllocation.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this}}const Es=["min","max"];class It{constructor(t={}){t=t||{},this.max=t.max===null||t.max>0?t.max:1,this.min=t.min===null||t.min>=0?t.min:0}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"QtyPerTransaction"}static get _superclass(){return"QtyPerTransaction"}get isValid(){return typeof this.min=="number"&&(this.max===null||typeof this.max=="number"&&this.max>=this.min)}update(t){return Object.keys(t).forEach(e=>{Es.includes(e)&&(this[e]=t[e])}),this}}const Ds=["productCode","unitAllocatedAmount"];class q{constructor(t={}){t=t||{};const{_Amount:e}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this.productCode=t.productCode,this.unitAllocatedAmount=this._Amount.init(t.unitAllocatedAmount)}static dummyData(){return{productCode:"productCode",unitAllocatedAmount:m.dummyData()}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"RefundAccountAllocation"}static get _superclass(){return"RefundAccountAllocation"}get isValid(){return!!this.productCode&&!!this.unitAllocatedAmount&&!!this.unitAllocatedAmount.currencyCode&&typeof this.unitAllocatedAmount.value=="number"}update(t){return Object.keys(t).forEach(e=>{Ds.includes(e)&&(e==="unitAllocatedAmount"?this[e]=this._Amount.init(t[e]):this[e]=t[e])}),this}}const Ts=["currencyCode","refundAccountAllocations"];class tt{constructor(t={}){t=t||{};const{_RefundAccountAllocation:e}=t._constructor||{};this._RefundAccountAllocation=e&&e._superclass===q._superclass?e:q,this.currencyCode=t.currencyCode,this.refundAccountAllocations=this._RefundAccountAllocation.initOnlyValidFromArray(t.refundAccountAllocations)}static dummyData(){return{currencyCode:"USD",refundAccountAllocations:[q.dummyData()]}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"RefundAccountAllocationGroup"}static get _superclass(){return"RefundAccountAllocationGroup"}get isValid(){return!!this.currencyCode&&this.refundAccountAllocations.length>0&&this.refundAccountAllocations.every(t=>{var e;return((e=t.unitAllocatedAmount)==null?void 0:e.currencyCode)===this.currencyCode})}update(t){return Object.keys(t).forEach(e=>{Ts.includes(e)&&(e==="refundAccountAllocations"?this[e]=this._RefundAccountAllocation.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this}}const Fs=["accountAllocationGroups","active","amounts","deductions","discount","metadata","name","qtyPerTransaction","refundAccountAllocationGroups","remarks"];class z{constructor(t={}){t=t||{};const{_AccountAllocationGroup:e,_Amount:i,_QtyPerTransaction:r,_RefundAccountAllocationGroup:n}=t._constructor||{};this._AccountAllocationGroup=e&&e._superclass===Z._superclass?e:Z,this._Amount=i&&i._superclass===m._superclass?i:m,this._QtyPerTransaction=r&&r._superclass===It._superclass?r:It,this._RefundAccountAllocationGroup=n&&n._superclass===tt._superclass?n:tt,this.accountAllocationGroups=this._AccountAllocationGroup.initOnlyValidFromArray(t.accountAllocationGroups),this.active=typeof t.active<"u"?!!t.active:!0,this.amounts=this._Amount.initOnlyValidFromArray(t.amounts),this.deductions=this._Amount.initOnlyValidFromArray(t.deductions),this.discount=t.discount||0,this.metadata=l.Metadata.initOnlyValidFromArray(t.metadata),this.name=t.name,this.qtyPerTransaction=this._QtyPerTransaction.init(t.qtyPerTransaction),this.priceStrategyType=t.priceStrategyType||"PriceStrategy",this.refundAccountAllocationGroups=this._RefundAccountAllocationGroup.initOnlyValidFromArray(t.refundAccountAllocationGroups),this.remarks=l.KeyValueObject.initOnlyValidFromArray(t.remarks)}static dummyData(){return{amounts:[m.dummyData()],name:"name"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"PriceStrategy"}static get _superclass(){return"PriceStrategy"}get isValid(){return this.amounts.length>0&&typeof this.discount=="number"&&this.discount>=0&&this.discount<=100}get defaultAmount(){return this.amounts&&this.amounts.length===1?this.amounts[0]:null}get restrictions(){let t=[];return t=l.Metadata.getValuesByKey(this.metadata,"RESTRICTIONS"),t.length===0&&(t=l.KeyValueObject.getValuesByKey(this.remarks,"restrictions")),t[0]||[]}getAmount({currencyCode:t,qty:e}){const i=this.getAmountByCurrencyCode(t);if(i){const{value:r}=i;return r*e}return null}getAmountByCurrencyCode(t){const e=this._Amount.getAmountsByCurrencyCode(this.amounts,t);return e.length===0?null:e[0]}getDeductionByCurrencyCode(t){const e=this._Amount.getAmountsByCurrencyCode(this.deductions,t);return e.length===0?null:e[0]}getRemarks(){return this.remarks?this.remarks:[]}deductionHasCurrencyCode(t){return this.deductions.length===0?!0:this.getDeductionByCurrencyCode(t)!==null}hasCurrencyCode(t){return this._Amount.getAmountsByCurrencyCode(this.amounts,t).length!==0}hasCurrencyCodeWithQty(t,e){return!(this.qtyPerTransaction.min>e||this._Amount.getAmountsByCurrencyCode(this.amounts,t).length===0)}isMatchedRestrictions(t={}){return this.restrictions.length===0?!0:this.restrictions.reduce((i,r)=>{const{key:n,value:a={}}=r;return i=i||Ls(n,a,t),i},!1)||!1}isQtyValid(t){return!(this.qtyPerTransaction.min>t)}setRemarks(t){return Array.isArray(t)&&(this.remarks=l.KeyValueObject.initFromArray(t)),this}toCalculatorRule({currencyCode:t}){const e=this.getAmountByCurrencyCode(t);return{deduction:0,discount:0,min:this.qtyPerTransaction.min,max:this.qtyPerTransaction.max,value:e.value||e.default,recursing:!1,recursingStartQty:null,priceStrategy:this}}update(t){return Object.keys(t).forEach(e=>{Fs.includes(e)&&(e==="amounts"||e==="deductions"?this[e]=this._Amount.initOnlyValidFromArray(t[e]):e==="qtyPerTransaction"?this[e]=this._QtyPerTransaction.init(t[e]):e==="accountAllocationGroups"?this[e]=this._AccountAllocationGroup.initOnlyValidFromArray(t[e]):e==="refundAccountAllocationGroups"?this[e]=this._RefundAccountAllocationGroup.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this}}function Ls(s,t,e){return Object.keys(t).reduce((i,r)=>{const n=N.get(e[s],r),a=Object.keys(t[r]);return i=i&&zt(n,t[r],a,!0),i},!0)}function zt(s,t={},e=[],i=!0){if(!i||e.length===0)return i;const r=e.shift(),n=t[r];return i=Ms({action:r,formulaValue:n,val:s}),zt(s,t,e,i)}function Ms({action:s,formulaValue:t,val:e}){switch(s){case"elemMatch":case"$elemMatch":return(e||[]).some(i=>Object.keys(t).filter(r=>Object.prototype.hasOwnProperty.call(i,r)&&i[r]===t[r]).length>0);case"eq":case"$eq":return N.isEqual(e,t);case"gt":case"$gt":return e>t;case"gte":case"$gte":return e>=t;case"$in":return Array.isArray(e)?!!e.find(i=>t.includes(i)):typeof e!="object"?!!t.includes(e):!1;case"$nin":return Array.isArray(e)?!e.some(i=>t.includes(i)):typeof e!="object"?!t.includes(e):!0;case"$includes":return e&&e.includes(t);case"$keyValue":return Array.isArray(e)?e.find(i=>t.key===i.key&&t.values.includes(i.value))!==void 0:e.key?t.key===e.key&&t.values.includes(e.value):!1;case"lt":case"$lt":return e<t;case"lte":case"$lte":return e<=t;case"ne":case"$ne":return e!==t;default:return!0}}const xs=["dateBegin","dateEnd","name","priceStrategies"];class S{constructor(t){t=t||{};const{_PriceStrategy:e}=t._constructor||{};this._PriceStrategy=e&&e._superclass===z._superclass?e:z,this.created=t.created||new Date().valueOf(),this.dateBegin=t.dateBegin||new Date().valueOf(),this.dateEnd=t.dateEnd||null,this.modified=t.modified||new Date().valueOf(),this.name=t.name||"",this.priceStrategies=this._PriceStrategy.initOnlyValidFromArray(t.priceStrategies),this.remarks=l.KeyValueObject.initOnlyValidFromArray(t.remarks)}static dummyData(){return{name:"Standard",dateBegin:new Date().valueOf(),dateEnd:new Date().valueOf()+1,priceStrategies:[z.dummyData()]}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Price"}static get _superclass(){return"Price"}static getPricesByTime(t=[],e){return t.filter(r=>r.isAvailableByDate(e))}get isValid(){return this.priceStrategies.length>0}get defaultAmount(){return this.defaultStrategy?this.defaultStrategy.defaultAmount:null}get defaultStrategy(){return this.getStrategies().length===1?this.priceStrategies[0]:null}getStrategies(){return this.priceStrategies?this.priceStrategies:[]}getStrategiesByRestrictions(t){return this.priceStrategies.filter(e=>e.isMatchedRestrictions(t))}getStrategiesByCurrencyAndQty(t,e){let i=this.getStrategiesByCurrencyCode(t,this.priceStrategies);return i=this.getStrategiesByQty(e,i),i}getStrategiesByCurrencyCode(t,e){return(e||this.priceStrategies).reduce((r,n)=>(n.hasCurrencyCode(t)&&n.deductionHasCurrencyCode(t)&&r.push(n),r),[])}getStrategiesByQty(t,e){return(e||this.priceStrategies).reduce((r,n)=>(n.isQtyValid(t)&&r.push(n),r),[])}isAvailableByDate(t){const e=t||new Date().valueOf();return e>=this.dateBegin&&(e<this.dateEnd||this.dateEnd===null)}hasCurrencyCodeWithQty(t,e){return this.priceStrategies.reduce((i,r)=>(i=r.hasCurrencyCodeWithQty(t,e)?!0:i,i),!1)}setModified(){return this.modified=new Date().valueOf(),this}setStrategies(t){return Array.isArray(t)&&(this.priceStrategies=this._PriceStrategy.initOnlyValidFromArray(t)),this.setModified()}update(t){return Object.keys(t).forEach(e=>{xs.includes(e)&&(e==="remarks"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):e==="priceStrategies"?this[e]=this._PriceStrategy.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this.setModified()}}const Bs=["couponDetails","description","entitlements","intangible","limitPercentage","lineOptions","maxPerWallet","name","originalStock","printable","printLayoutCodes","printLayoutMappingCodes","productCategories","productGroupName","productOptions","requiredProductCode","stock"];class R extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_ItemOption:e}=t._constructor||{};this._ItemOption=e&&e._superclass===E?e:E;const i=t._id||t.id;this.id=$s(i),this._type=t._type||"Product",this.couponDetails=t.couponDetails,this.description=t.description||"",this.entitlements=t.entitlements,this.intangible=t.intangible||!1,this.limitPercentage=t.limitPercentage||100,this.lineOptions=this._ItemOption.initOnlyValidFromArray(t.lineOptions),this.maxPerWallet=t.maxPerWallet||1,this.name=t.name||"",this.originalStock=t.originalStock||0,this.printable=t.printable||!1,this.printLayoutCodes=t.printLayoutCodes||[],this.printLayoutMappingCodes=t.printLayoutMappingCodes||[],this.productCategories=t.productCategories||[],this.productCode=js(t,"productCode"),this.productGroupName=typeof t.productGroupName<"u"?t.productGroupName.toUpperCase():t.productGroupName||"DEFAULT",this.productOptions=this._ItemOption.initOnlyValidFromArray(t.productOptions),this.productType=t.productType||"Product",this.requiredProductCode=t.requiredProductCode,this.stock=t.stock||0}static dummyData(){return{name:"badge",tenantCode:"tenantCode"}}static get _classname(){return"Product"}static get _superclass(){return"Product"}get isValid(){return super.isValid&&!!this.name}get isBadge(){return this.productGroupName==="BADGE"}get isCoupon(){return this.productGroupName==="COUPON"}get isItemCoupon(){return this.couponDetails?this.couponDetails.item:!1}get isPrintable(){return this.printLayoutMappingCodes.length>0}get isReachedLimitPercentage(){return this.soldPercentage>=this.limitPercentage}get isTotalCoupon(){return this.couponDetails?this.couponDetails.total:!1}get soldPercentage(){return(this.originalStock-this.stock)/this.originalStock*100}get summary(){return{product:this,productCode:this.productCode,name:this.name}}ableToHave(t){return this.maxPerWallet>=t}checkProductItemOptions(t=[]){return W.getItemOptionFillInsByTarget({itemOptionFillIns:t,target:"Product",targetCode:this.productCode}).reduce((i,r)=>{const n=r.getKey(),a=this.getProductOptionByKey(n);return a?(a.isValidFillInValue(r.getValue())||i.errMsgs.push(`the product(${this.productCode}) option's(${n}) fillInValue is invalid`),i):(i.errMsgs.push(`options of the product(${this.productCode}) does not contain key: "${n}"`),i)},{errMsgs:[]})}getCode(){return this.productCode}getPreservedData(){return{metadata:this.metadata,name:this.name,productCode:this.productCode,productGroupName:this.productGroupName,productType:this.productType,tenantCode:this.tenantCode}}getMetadataValueByKey(t){return l.Metadata.getValueByKey(this.metadata||[],t)}getProductOptionByKey(t){const e=this._ItemOption.getByKey(this.productOptions,t);return e.length===1?e[0]:null}hasStock(t){return this.stock>=t}isApplicableCoupon(t){if(!this.couponDetails)return!1;const{merchandiseCodes:e=[]}=this.couponDetails;return e.length>0?e.includes(t.merchandiseCode):!0}isQualified(t){const e=this.getMetadataValueByKey("RULES")||[];return e.length===0?!0:e.reduce((i,r)=>i||l.getValidation(r,t,qs,l.KeyValueObject),!1)}isTicket(){return!1}update(t){return Object.keys(t).forEach(e=>{Bs.includes(e)&&(e==="productOptions"||e==="lineOptions"?this[e]=this._ItemOption.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}function $s(s){return s&&typeof s.toString=="function"?s.toString():s}function js(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function qs(s,t){return l.getValueByKeys(s.split("."),t)}const Ns=["billingAccountCode","billingProjectCode"];class Jt extends R{constructor(t={}){t=t||{},super(t),this.billingAccountCode=t.billingAccountCode,this.billingProjectCode=t.billingProjectCode,this.productType="ProductBilling"}static dummyData(){return{...R.dummyData(),billingAccountCode:"billingAccountCode",billingProjectCode:"billingProjectCode",productType:"ProductBilling"}}static get _classname(){return"ProductBilling"}get isValid(){return super.isValid&&!!this.billingAccountCode&&!!this.billingProjectCode}getPreservedData(){return{...super.getPreservedData(),billingAccountCode:this.billingAccountCode,billingProjectCode:this.billingProjectCode}}update(t){return Object.keys(t).forEach(e=>{Ns.includes(e)&&(this[e]=t[e])}),super.update(t)}}const Us=["allowEditQty","allowEditUnitPrice","defaultCurrency","description","eventSessionCode","intangible","locales","max","merchandiseCategoryCodes","merchandiseOptions","name","onlyFor","prices","priority","productCodes","sku","stock","visibleBy"];class I extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_ItemOption:e,_ItemOptionFillIn:i,_MerchandiseOption:r,_Price:n,_Product:a}=t._constructor||{};this._ItemOption=e&&e._superclass===E._superclass?e:E,this._ItemOptionFillIn=i&&i._superclass===W._superclass?i:W,this._MerchandiseOption=r&&r._superclass===H._superclass?r:H,this._Price=n&&n._superclass===S._superclass?n:S,this._Product=a&&a._superclass===R._superclass?a:R,this._products=t._products||[],this._type=t._type||"Merchandise";const u=t._id||t.id;this.id=Hs(u),this.allowEditQty=t.allowEditQty||!1,this.allowEditUnitPrice=t.allowEditUnitPrice||!1,this.defaultCurrency=t.defaultCurrency||"HKD",this.description=t.description,this.free=t.free||!1,this.intangible=t.intangible||!1,this.max=t.max||1,this.merchandiseCategoryCodes=t.merchandiseCategoryCodes||[],this.merchandiseCode=Ks(t,"merchandiseCode"),this.merchandiseOptions=Gs(this,t),this.merchandiseType=t.merchandiseType||"Merchandise",this.name=t.name||"",this.prices=this._Price.initOnlyValidFromArray(t.prices),this.productCodes=t.productCodes||[],this.priority=t.priority||100,this.sku=t.sku||"",this.stock=t.stock||0,this.targets=t.targets||[]}static dummyData(){return{name:"delegate badge",sku:"20190430",productCodes:["123456"],merchandiseOptions:[E.init({itemOptionType:"ItemOptionText",type:"TextInput",key:"firstName",label:"First Name"})],prices:[S.dummyData()],stock:100,tenantCode:"85223977000"}}static get _classname(){return"Merchandise"}static get _superclass(){return"Merchandise"}get afterEnd(){return this.getBeginAndEndDates().dateEnd>Date.now()}get beforeBegin(){return this.getBeginAndEndDates().dateBegin<=Date.now()}get currentPrice(){if(this.free)return null;const t=Date.now(),e=this.prices.filter(i=>i.isAvailableByDate(t));if(e.length===1)return e[0];if(e.length===0)return null;if(e.length>1)throw new Error("Incorrect price settings for merchandise")}get hasStock(){return this.stock>0||!!this.intangible}get isActive(){return this.active===!0}get isDeleted(){return this.deleted===!0}get isAvailable(){return this.isActive&&!this.isDeleted&&this.hasStock&&(this.free||this.currentPrice)}get isAvailableByDate(){return!this.afterEnd&&!this.beforeBegin}get isForPersonal(){return!Array.isArray(this.targets)||this.targets.length===0}get isForGroup(){return Array.isArray(this.targets)&&this.targets.includes("GROUP")}get isPrintable(){return this.printOut.isPrintable}get isValid(){return super.isValid&&!!this.name&&!!this.productCodes&&this.productCodes.length>0}get products(){return this._Product.initOnlyValidFromArray(this._products||[])}get summary(){return{currentPrice:this.currentPrice,free:this.free,max:this.max,merchandise:this,merchandiseCode:this.merchandiseCode,name:this.name,stock:this.stock}}checkHasStock(t){return this.stock>=t}checkMerchandiseItemOptions(t=[]){return this._ItemOptionFillIn.getItemOptionFillInsByTarget({itemOptionFillIns:t,target:"Merchandise",targetCode:this.merchandiseCode}).reduce((i,r)=>{const n=r.getKey(),a=this.getMerchandiseOptionByKey(n);return a?(a.isValidFillInValue(r.getValue())||i.errMsgs.push(`the merchandise(${this.merchandiseCode}) option's(${n}) fillInValue is invalid`),i):(i.errMsgs.push(`options of the merchandise(${this.merchandiseCode}) does not contain key: "${n}"`),i)},{errMsgs:[]})}checkProductsItemOptions(t=[]){return this.getProducts().reduce((e,i)=>{const{errMsgs:r}=i.checkProductItemOptions(t);return e.errMsgs.push(...r),e},{errMsgs:[]})}convertMerchandiseOptionsToFormData(){return H.convertToFormData(this.merchandiseOptions)}convertMerchandiseOptionsToInputs(){return H.convertToInputs(this.merchandiseOptions)}convertMerchandiseOptionsToPurchaseOptions(){return H.convertToPurchaseOptions(this.merchandiseOptions)}getAmountFromPrice({cartItems:t,currency:e,dateTimestamp:i=Date.now(),qty:r,roleCodes:n}){const a={cartItems:t,errorMessages:[],merchandise:this,price:null,qty:r,value:null},u=e||this.defaultCurrency,c=this.getPriceByTimeAndRoleCodes(i,n);if(!c)return a.errorMessages.push("Can't get available price for you."),a;a.price=c;const o=c.getStrategiesByCurrencyAndQty(u,r);if(o.length===0)return a.errorMessages.push("Can't get available strategies from price."),a;const{convertedPriceStrategies:d,maxQty:h}=o.reduce((f,y)=>{const C=y.toCalculatorRule({currency:u,qty:r});return f.convertedPriceStrategies.push(C),C.max===null&&(f.maxQty=null),C.max!==null&&f.maxQty!==null&&(f.maxQty+=C.max),f},{convertedPriceStrategies:[],maxQty:0});if(h!==null&&h<r)return a.errorMessages.push(`Currently you can only purchase a maximum of ${h} pieces of this merchandise.`),a;let g=G(r,d);if(g.length===0)return a.errorMessages.push("No amount"),a;g=g.sort((f,y)=>f.value-y.value);const[p]=g;return p.qty>0?(a.errorMessages.push("Exceed maximum quantity per transaction."),a):p.qty<0?(a.errorMessages.push("No amount."),a):(a.value=p.value,a)}getAvailableInfo({cartItems:t,currency:e,dateTimestamp:i=Date.now(),roleCodes:r}={}){const n={available:!1,unavailableMessages:[],merchandise:this,cartItemInfos:[],cartItems:t,qty:t.reduce((d,h)=>d+h.getQty(),0)};this.stock<n.qty&&n.unavailableMessages.push(`The quantity(${n.qty}) you selected is less than the stock(${this.stock}).`),this.isActive||n.unavailableMessages.push("Inactive."),this.isDeleted&&n.unavailableMessages.push("Deleted.");const a=this.getPriceByTimeAndRoleCodes(i,r);a||n.unavailableMessages.push("No available price for you in this time."),n.price=a;const u=e||this.defaultCurrency;a.getStrategiesByCurrencyAndQty(u,n.qty).length===0&&n.unavailableMessages.push(`The price not support currency '${u}'.`);const{cartItemInfos:c,hasProblem:o}=this.getItemOptionInfos(t);return n.cartItemInfos=c,o&&n.unavailableMessages.push("Cart item has problem, please check."),n.unavailableMessages.length===0&&(n.available=!0),n}getBeginAndEndDates(){const t={dateBegin:null,dateEnd:null};return this.prices.reduce((e,i)=>((!e.dateBegin||i.dateBegin>e.dateBegin)&&(e.dateBegin=i.dateBegin),(!e.dateEnd||i.dateEnd<=e.dateEnd)&&(e.dateEnd=i.dateEnd),e),t)}getCode(){return this.merchandiseCode}getCurrentAmount({currencyCode:t,payload:e,ignoreRestriction:i=!1}){if(!this.currentPrice)return null;let r=i?this.currentPrice.priceStrategies:this.currentPrice.getStrategiesByRestrictions(e);return r=this.currentPrice.getStrategiesByCurrencyCode(t,r),r.length===0?null:r[0].getAmountByCurrencyCode(t)}getCurrentPrice(t){const e=t||Date.now(),i=this.getPricesByTime(e);return i.length===1?i[0]:null}getCurrentPriceByRoleCodes(t){const e=Date.now();let i=this.getPricesByTime(e);return i=S.getPricesByRoleCodes(i,t),i.length===1?i[0]:null}getItemOptionInfos(t=[]){return t.reduce((e,i)=>{const r=i.getItemOptionFillIns(),n={available:!0,cartItem:i,unavailableMessages:[]},a=this.checkMerchandiseItemOptions(r),{errMsgs:u}=this.checkProductsItemOptions(r);return n.unavailableMessages.push(...a.errMsgs),n.unavailableMessages.push(...u),n.available=!(n.unavailableMessages.length>0),e.hasProblem=n.available?e.hasProblem:!0,e.cartItemInfos.push(n),e},{cartItemInfos:[],hasProblem:!1})}getMerchandiseOptionByKey(t){const e=this._ItemOption.getByKey(this.merchandiseOptions,t);return e.length===1?e[0]:null}getPreservedData(){return{allowEditQty:this.allowEditQty,allowEditUnitPrice:this.allowEditUnitPrice,defaultCurrency:this.defaultCurrency,description:this.description,merchandiseCategoryCodes:this.merchandiseCategoryCodes,merchandiseCode:this.merchandiseCode,merchandiseOptions:this.merchandiseOptions,merchandiseType:this.merchandiseType,metadata:this.metadata,name:this.name,priority:this.priority,productCodes:this.productCodes,sku:this.sku,stock:this.stock,tenantCode:this.tenantCode}}getPrices(){return this.prices?this.prices:[]}getPricesByTime(t){const e=t||Date.now();return S.getPricesByTime(this.prices,e)}getPriceByTimeAndRoleCodes(t,e){let i=this.getPricesByTime(t);return i=S.getPricesByRoleCodes(i,e),i.length===1?i[0]:null}getProducts(){return this.products||[]}getProductsMetadataValuesByKey(t){return this.products.map(e=>e.getMetadataValueByKey(t)).filter(e=>e)}getProductsQty(t=1){return this.productCodes.reduce((e,i)=>(e[i]?e[i]+=1*t:e[i]=1*t,e),{})}getRemarksByKey(t){return l.KeyValueObject.getValuesByKey(this.remarks,t)}getStock(){return this.stock||0}getSummary(t){const e=this.getCurrentAmount(t);return e?{...this.summary,currentAmount:e}:null}reachLimit(t){return this.max<t}setPrices(t){return Array.isArray(t)&&(this.prices=this._Price.initOnlyValidFromArray(t)),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Us.includes(e)&&(e==="merchandiseOptions"&&this.tenantCode?this[e]=this._ItemOption.initOnlyValidFromArray(t[e]):e==="merchandiseOptions"&&this.tenantCode?this[e]=H.initOnlyValidFromArray(t[e]):e==="prices"?this[e]=this._Price.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}function Gs(s,t){return t.tenantCode?s._ItemOption.initOnlyValidFromArray(t.merchandiseOptions):s._MerchandiseOption.initOnlyValidFromArray(t.merchandiseOptions)}function Ks(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Hs(s){return s&&typeof s.toString=="function"?s.toString():s}const Ws=["billingAccountCode","billingProjectCode","bussinessUnits","orderExpiryMs","orderInvalidMs","unsupportedPaymentGatewayCodes"];class Xt extends I{constructor(t={}){t=t||{},super(t);const{_BillingAccount:e,_BillingProject:i}=t._constructor||{};this._BillingAccount=e,this._BillingProject=i,this._billingAccount=t._billingAccount,this._billingProject=t._billingProject,this.billingAccountCode=t.billingAccountCode,this.billingProjectCode=t.billingProjectCode,this.bussinessUnits=t.bussinessUnits||[],this.merchandiseType="MerchandiseBilling",this.orderExpiryMs=t.orderExpiryMs||null,this.orderInvalidMs=t.orderInvalidMs||null,this.unsupportedPaymentGatewayCodes=t.unsupportedPaymentGatewayCodes||[]}static get _classname(){return"MerchandiseBilling"}get billingAccount(){return this._BillingAccount&&typeof this._BillingAccount.init=="function"?this._BillingAccount.init(this._billingAccount):this._billingAccount}get billingProject(){return this._BillingProject&&typeof this._BillingProject.init=="function"?this._BillingProject.init(this._billingProject):this._billingProject}get isValid(){return super.isValid&&!!this.billingProjectCode&&this.hasValidBillingProducts&&this.hasValidAccountAllocations&&this.hasValidRefundAccountAllocations}get hasValidBillingProducts(){return this.products.length===0?!0:this.products.every(t=>!!t.billingAccountCode&&!!t.billingProjectCode)}get hasValidAccountAllocations(){return this.prices.length===0?!1:this.prices.every(t=>t.priceStrategies.every(e=>this.hasValidAccountAllocationsByStrategy(e)))}get hasValidRefundAccountAllocations(){return this.prices.every(t=>t.priceStrategies.every(e=>this.hasValidRefundAccountAllocationsByStrategy(e)))}getPreservedData(){return{...super.getPreservedData(),billingAccountCode:this.billingAccountCode,billingProjectCode:this.billingProjectCode,bussinessUnits:this.bussinessUnits,orderExpiryMs:this.orderExpiryMs,orderInvalidMs:this.orderInvalidMs,unsupportedPaymentGatewayCodes:this.unsupportedPaymentGatewayCodes}}hasValidAccountAllocationsByStrategy(t){const{accountAllocationGroups:e=[],amounts:i=[]}=t,r=i.map(n=>n.currencyCode);return e.length===0||this.hasDuplicateCurrencies(e)||!e.every(n=>r.includes(n.currencyCode))?!1:i.every(n=>{const{currencyCode:a,value:u}=n,c=e.find(d=>d.currencyCode===a);return c?c.accountAllocations.reduce((d,h)=>!h||!this.productCodes.includes(h.productCode)?Number.NaN:d+h.allocatedAmount.value,0)===u:!1})}hasValidRefundAccountAllocationsByStrategy(t){const{amounts:e=[],refundAccountAllocationGroups:i=[]}=t;if(i.length===0)return!0;if(this.hasDuplicateCurrencies(i))return!1;const r=e.map(n=>n.currencyCode);return i.every(n=>!!n&&r.includes(n.currencyCode)&&n.refundAccountAllocations.every(a=>{var u,c;return!!a&&this.productCodes.includes(a.productCode)&&((u=a.unitAllocatedAmount)==null?void 0:u.currencyCode)===n.currencyCode&&typeof((c=a.unitAllocatedAmount)==null?void 0:c.value)=="number"}))}hasDuplicateCurrencies(t=[]){const e=t.map(i=>i.currencyCode);return new Set(e).size!==e.length}update(t){return Object.keys(t).forEach(e=>{Ws.includes(e)&&(this[e]=t[e])}),super.update(t)}}const Qs=["paidAmount","purchaseOptions","qty","itemOptionFillIns","remarks"];class J{constructor(t={}){t=t||{};const{_Amount:e,_ItemOptionFillIn:i,_Merchandise:r}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._ItemOptionFillIn=i&&i._superclass===W._superclass?i:W,this._Merchandise=r&&r._superclass===I._superclass?r:I,this._merchandise=t._merchandise,this.cartItemCode=Ys(t,"cartItemCode"),this.created=t.created||new Date().valueOf(),this.discount=this._Amount.init(t.discount),this.itemOptionFillIns=this._ItemOptionFillIn.initOnlyValidFromArray(t.itemOptionFillIns),this.merchandiseCode=t.merchandiseCode,this.metadata=l.Metadata.initOnlyValidFromArray(t.metadata),this.price=this._Amount.init(t.price),this.purchaseOptions=l.KeyValueObject.initOnlyValidFromArray(t.purchaseOptions),this.qty=t.qty,this.remarks=l.KeyValueObject.initOnlyValidFromArray(t.remarks),this.subTotal=this._Amount.init(t.subTotal),this.waived=t.waived||0}static dummyData(){return{merchandiseCode:"merchandiseCode",qty:1}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"CartItem"}static get _superclass(){return"CartItem"}static getByMerchandiseCode(t=[],e){return t.filter(i=>i.merchandiseCode===e)}static mergeDuplicateCartItems(t){return Zt(t)}get isValid(){return!!this.merchandiseCode&&this.qty>0}get merchandise(){return this._Merchandise.init(this._merchandise)}createInvoiceLine(){return{amount:this.subTotal,unitPrice:this.price,deduction:this.discount,qty:this.qty,merchandiseCode:this.merchandiseCode,metadata:this.metadata,purchaseOptions:this.purchaseOptions,remarks:this.remarks,waived:this.waived}}getCurrencyCode(){return this.price?this.price.getCurrencyCode():null}getItemOptionFillIns(){return this.itemOptionFillIns}getMerchandiseCode(){return this.merchandiseCode}getQty(){return this.qty}toCaculateAmountItem(){return{merchandiseCode:this.getMerchandiseCode(),qty:this.qty,price:this.price,discount:this.discount,subTotal:this.subTotal,priceStrategy:null,purchaseOptions:this.purchaseOptions,remarks:this.remarks,waived:this.waived}}update(t){return Object.keys(t).forEach(e=>{Qs.includes(e)&&(e==="discount"||e==="price"||e==="subTotal"?this[e]=this._Amount.init(t[e]):e==="itemOptionFillIns"?this[e]=this._ItemOptionFillIn.initOnlyValidFromArray(t[e]):e==="metadata"?this[e]=l.Metadata.initOnlyValidFromArray(t[e]):e==="purchaseOptions"||e==="remarks"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this}}function Zt(s,t=[]){const e=s.shift(),{matched:i}=s.reduce((r,n)=>{if(r.matched)return r;if(e.merchandiseCode===n.merchandiseCode&&e.itemOptionFillIns.length===n.itemOptionFillIns.length){const{itemOptionFillIns:a}=n;N.intersectionWith(a,e.itemOptionFillIns,(c,o)=>c.target===o.target&&c.targetCode===o.targetCode&&c.key===o.key&&N.intersection(c.value,o.value).length===c.value.length).length===a.length&&(r.matched=n)}return r},{matched:null});return i?i.qty+=e.qty:t.push(e),s.length===0?t:Zt(s,t)}function Ys(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}const ks=["created"];class O{constructor(t){t=t||{},this.absent=t.absent||null,this.assigned=t.assigned||null,this.cancelled=t.cancelled||null,this.completed=t.completed||null,this.confirmed=t.confirmed||null,this.created=t.created||new Date().valueOf(),this.delivered=t.delivered||null,this.expired=t.expired||null,this.failed=t.failed||null,this.onHold=t.onHold||null,this.processing=t.processing||null,this.paid=t.paid||null,this.payLater=t.payLater||null,this.pending=t.pending,this.redeemed=t.redeemed||null,this.refunded=t.refunded||null,this.refundRequested=t.refundRequested||null,this.rejected=t.rejected||null,this.shared=t.shared||null,this.submitted=t.submitted||null,this.terminated=t.terminated||null,this.used=t.used||null,this.waived=t.waived||null}static dummyData(){return{created:new Date().valueOf(),modified:new Date().valueOf()}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Status"}static get _superclass(){return"Status"}get isValid(){return this}get isAbsent(){return this.absent!==null}get isAssigned(){return this.assigned!==null}get isCancelled(){return this.cancelled!==null}get isCompleted(){return this.completed!==null}get isConfirmed(){return this.confirmed!==null}get isDelivered(){return this.delivered!==null}get isExpired(){return this.expired!==null}get isFailed(){return this.failed!==null}get isOnHold(){return this.onHold!==null}get isProcessing(){return this.processing!==null}get isPaid(){return this.paid!==null}get isPayLater(){return this.payLater!==null}get isPending(){return!this.isSettled&&!this.isCancelled&&!this.isRefundRequested}get isRedeemed(){return this.redeemed!==null}get isRefunded(){return this.refunded!==null}get isRefundRequested(){return this.refundRequested!==null}get isRejected(){return this.rejected!==null}get isSettled(){return this.isPaid||this.isWaived||this.isRedeemed}get isShared(){return this.shared!==null}get isSubmitted(){return this.submitted!==null}get isTerminated(){return this.terminated!==null}get isUsed(){return this.used!==null}get isWaived(){return this.waived!==null}get lastStatus(){return this.modified}get modified(){return this.statusLast?this.statusLast.value:""}get statusLast(){return this.statusList.length===0?null:this.statusList[this.statusList.length-1]}get statusList(){return Object.keys(this).reduce((e,i)=>(this[i]&&e.push({key:i,value:this[i]}),e),[]).sort((e,i)=>e.value>i.value?1:-1)}allowCancel(){return this.isPending||this.isWaived}allowRefundRequest(){return this.isPaid&&!this.isCancelled}setAbsent(t){return this.absent=t||new Date().valueOf(),this}setAssigned(t){return this.assigned=t||new Date().valueOf(),this}setCancelled(t){return this.cancelled=t||new Date().valueOf(),this}setCompleted(t){return this.completed=t||new Date().valueOf(),this}setConfirmed(t){return this.confirmed=t||new Date().valueOf(),this}setDelivered(t){return this.delivered=t||new Date().valueOf(),this}setExpired(t){return this.expired=t||new Date().valueOf(),this}setFailed(t){return this.failed=t||new Date().valueOf(),this}setOnHold(){return this.onHold=new Date().valueOf(),this}setProcessing(){return this.processing=new Date().valueOf(),this}setPaid(t){return this.paid=t||new Date().valueOf(),this.waived=null,this}setPayLater(t){return this.payLater=t||new Date().valueOf(),this}setPending(t){return this.pending=t||new Date().valueOf(),this}setRedeemed(t){return this.redeemed=t||new Date().valueOf(),this}setRefunded(t){return this.refunded=t||new Date().valueOf(),this}setRefundRequested(t){return this.refundRequested=t||new Date().valueOf(),this}setRejected(t){return this.rejected=t||new Date().valueOf(),this}setShared(t){return this.shared=t||new Date().valueOf(),this}setSubmitted(t){return this.submitted=t||new Date().valueOf(),this}setTerminated(t){return this.terminated=t||new Date().valueOf(),this}setUsed(t){return this.used=t||new Date().valueOf(),this.delivered=this.delivered||this.used,this}setWaived(t){return this.waived=t||new Date().valueOf(),this.paid=null,this}unSetAssigned(){this.assigned=null}unsetDelivered(){this.delivered=null}unSetOnHold(){this.onHold=null}unSetRefundRequested(){this.refundRequested=null}unsetUsed(){this.used=null}update(t){return Object.keys(t).forEach(e=>{ks.includes(e)||(this[e]=t[e])}),this}}const zs=[];class et extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_CartItem:e,_Merchandise:i,_Status:r}=t._constructor||{};this._CartItem=e&&e._superclass===J._superclass?e:J,this._Merchandise=i&&i._superclass===I._superclass?i:I,this._Status=r&&r._superclass===O._superclass?r:O;const n=t._id||t.id;this.id=Xs(n),this._merchandises=t._merchandises,this._type=t._type||"Cart",this.cartCode=Js(t,"cartCode"),this.cartItems=this._CartItem.initOnlyValidFromArray(t.cartItems),this.status=this._Status.init(t.status)}static dummyData(){return{cartItems:[J.dummyData()],tenantCode:"tenantCode"}}static get _classname(){return"Cart"}static get _superclass(){return"Cart"}get isValid(){return super.isValid}get isActive(){return!!this.active}get merchandises(){return this._Merchandise.initOnlyValidFromArray(this._merchandises||[])}get merchandisesSummary(){return this.merchandises.reduce((t,e)=>{const i=t.find(r=>r.merchandiseCode===e.merchandiseCode);return i?i.qty+=1:t.push({...e.summary,qty:1}),t},[])}checkoutAvailable({ownedWalletItems:t,selectCartItems:e,isCoordinator:i=!1}){try{return i?this.checkHasStock({selectCartItems:e}):this.checkHasStock({selectCartItems:e})&&!this.checkWalletItemReachLimit({ownedWalletItems:t,selectCartItems:e})&&!this.checkMerchandiseReachLimit({selectCartItems:e})}catch(r){throw r}}checkHasStock({selectCartItems:t}){try{return t.forEach(e=>{const{qty:i}=e;if(this.merchandises&&this.merchandises.length===0)throw new Error("not have merchandises array object");const[r]=this.merchandises.filter(a=>a.merchandiseCode===e.merchandiseCode),{products:n}=r;if(n&&n.length===0)throw new Error("merchandise not have products array object");if(!r.checkHasStock(i))throw new Error("merchandise not enough stock");n.forEach(a=>{if(!a.hasStock(i))throw new Error("product not enough stock")})}),!0}catch(e){throw e}}checkWalletItemReachLimit({ownedWalletItems:t,selectCartItems:e}){try{return e.forEach(i=>{const{qty:r}=i,[n]=this.merchandises.filter(u=>u.merchandiseCode===i.merchandiseCode),{products:a}=n;if(a&&a.length===0)throw new Error("merchandise not have products array object");a.forEach(u=>{const o=t.filter(d=>d.productCode===u.productCode).length||0;if(!u.ableToHave(o+r))throw new Error("walletItem reach limit")})}),!1}catch(i){throw i}}checkMerchandiseReachLimit({selectCartItems:t}){try{return t.forEach(e=>{const{qty:i}=e,[r]=this.merchandises.filter(n=>n.merchandiseCode===e.merchandiseCode);if(i>r.max)throw new Error("merchandise reach limit")}),!1}catch(e){throw e}}clearCartItems(){return this.cartItems=[],this}createInvoiceLines(){return this.cartItems.map(t=>Object.assign(t.createInvoiceLine(),{cartCode:this.cartCode,tenantCode:this.tenantCode}))}getCartItems(){return this.cartItems}getCartItemCodes(){return this.cartItems.map(t=>t.cartItemCode)}getCode(){return this.cartCode}getCurrencyCode(){return this.cartItems.length>0?this.cartItems[0].getCurrencyCode():null}getMerchandiseAvailableInfos({cartItems:t,currency:e,roleCodes:i}){if(this.cartItems.length>0&&this.merchandises.length===0)throw new Error("No merchandises");const r=this;if(t=t||r.cartItems,t=this._CartItem.initOnlyValidFromArray(t),t.length===0)throw new Error("No cartItems");return r.merchandises.reduce((n,a)=>{const u=this._CartItem.getByMerchandiseCode(t,a.merchandiseCode),c=a.getAvailableInfo({cartItems:u,currency:e,roleCodes:i});return n.push(c),n},[])}getRelatedRegistrationGroupCode(){return l.KeyValueObject.getValueByKey(this.remarks||[],"registrationGroupCode")}setCartItems(t){return this.cartItems=this._CartItem.initOnlyValidFromArray(t),this}setCompleted(){return this.status.setCompleted(),this.setModified()}updateAvailable({isCoordinator:t,selectCartItems:e}){try{return t?this.checkHasStock({selectCartItems:e}):this.checkHasStock({selectCartItems:e})&&!this.checkMerchandiseReachLimit({selectCartItems:e})}catch(i){throw i}}update(t){return Object.keys(t).forEach(e=>{zs.includes(e)&&(this[e]=t[e])}),super.update(t)}updateStock(){if(this.cartItems.length===0)throw new Error("No cartItems");let t=[],e=[];return this.cartItems.forEach(i=>{const{merchandiseCode:r,qty:n}=i,[a]=this.merchandises.filter(o=>o.merchandiseCode===r),u=a.stock-n,{products:c}=a;c.forEach(o=>{const d=o.stock-i.qty;o.updateProduct({stock:d})}),t=t.concat(c),a.update({stock:u}),e=e.concat(a)}),{newProducts:t,newMerchandises:e}}}function Js(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Xs(s){return s&&typeof s.toString=="function"?s.toString():s}function te(s){const{delimiter:t=": ",key:e,purchaseOptions:i,tag:r="div"}=s||{};if(!e)return i.reduce((a,u)=>{const c=St({delimiter:t,purchaseOption:u,tag:r});return r?a.push(`<${r}>${c.join("")}</${r}>`):a.push(`${c.join("; ")}`),a},[]);const n=(i||[]).find(a=>!!e&&a.key===e);return n?St({delimiter:t,purchaseOption:n,tag:r}):[]}function St({delimiter:s=": ",purchaseOption:t,tag:e="div"}){return(t.value||[]).reduce((i,r)=>{const{label:n,value:a={}}=r||{},u=n??"";return Array.isArray(a)?e?i.push(`<${e}>${u}${s}${a.join(s)}</${e}>`):i.push(`${u}${s}${a.join(s)}`):typeof a=="object"?Object.keys(a).map(c=>{e?i.push(`<${e}>${c}${s}${a[c]}</${e}>`):i.push(`${c}${s}${a[c]}`)}):e?i.push(`<${e}>${u}${s}${a}</${e}>`):i.push(`${u}${s}${a}`),i},[])}const Zs=["label","logoUrl","name","sandbox","setting"];class D extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const e=t._id||t.id;this.id=ei(e),this._type=t._type||"PaymentGateway",this.hasWebhook=t.hasWebhook||!1,this.label=t.label,this.logoUrl=t.logoUrl,this.name=t.name||"",this.paymentGatewayCode=ti(t,"paymentGatewayCode"),this.paymentGatewayType=t.paymentGatewayType||"PaymentGateway",this.paymentResultType=t.paymentResultType||"PaymentResult",this.sandbox=t.sandbox||!1,this.setting=t.setting||null}static dummyData(){return{name:"name",tenantCode:"tenantCode"}}static get _classname(){return"PaymentGateway"}static get _superclass(){return"PaymentGateway"}get isValid(){return super.isValid&&!!this.name}async createPayment(){throw new Error(`${this._classname} subclass should implement createPayment`)}async getAppPayParams(){throw new Error(`${this._classname} subclass should implement getAppPayParams`)}getCode(){return this.paymentGatewayCode}async updatePayment(){throw new Error(`${this._classname} subclass should implement updatePayment`)}async query(){throw new Error(`${this._classname} subclass should implement query`)}async submit(){throw new Error(`${this._classname} subclass should implement submit`)}setCompletedRelatedStatus(t){throw new Error(`${this.name} subclass should implement setCompletedRelatedStatus`)}update(t){return Object.keys(t).forEach(e=>{Zs.includes(e)&&(this[e]=t[e])}),super.update(t)}}function ti(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function ei(s){return s&&typeof s.toString=="function"?s.toString():s}const si=["clearingBillingAccountCode","settlementDebitBillingAccountCode","settlementFeeBillingAccountCode","settlementFeeBillingProjectCode","settlementFeeRate","surchargeBillingAccountCode","surchargeBillingProjectCode","surchargeClearingBillingAccountCode","surcharges"];class ee extends D{constructor(t={}){t=t||{},super(t);const{_Price:e}=t._constructor||{};this._Price=e&&e._superclass===S._superclass?e:S,this.paymentGatewayType="PaymentGatewayBilling",this.clearingBillingAccountCode=t.clearingBillingAccountCode,this.surchargeClearingBillingAccountCode=t.surchargeClearingBillingAccountCode,this.settlementDebitBillingAccountCode=t.settlementDebitBillingAccountCode,this.settlementFeeRate=t.settlementFeeRate||0,this.settlementFeeBillingAccountCode=t.settlementFeeBillingAccountCode,this.settlementFeeBillingProjectCode=t.settlementFeeBillingProjectCode,this.surchargeBillingAccountCode=t.surchargeBillingAccountCode,this.surchargeBillingProjectCode=t.surchargeBillingProjectCode,this.surcharges=this._Price.initOnlyValidFromArray(t.surcharges)}static dummyData(){return{...D.dummyData(),paymentGatewayType:"PaymentGatewayBilling",settlementDebitBillingAccountCode:"settlementDebitBillingAccountCode"}}static get _classname(){return"PaymentGatewayBilling"}get hasSurcharge(){return this.surcharges.length>0}get isDeferred(){return!!this.clearingBillingAccountCode}get isValid(){return super.isValid&&!!this.settlementDebitBillingAccountCode&&(!this.hasSurcharge||!!this.surchargeBillingAccountCode&&!!this.surchargeBillingProjectCode)}update(t={}){return Object.keys(t).forEach(e=>{si.includes(e)&&(e==="surcharges"?this[e]=this._Price.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}class V extends l.Status{constructor(t){t=t||{},super(t),this.cancelled=this._ActionRecord.init(t.cancelled),this.completed=this._ActionRecord.init(t.completed),this.confirmed=this._ActionRecord.init(t.confirmed),this.deleted=this._ActionRecord.init(t.deleted),this.terminated=this._ActionRecord.init(t.terminated)}static get _classname(){return"StatusQStore"}get _classname(){return"StatusQStore"}get isCancelled(){var t;return((t=this.cancelled)==null?void 0:t.timestamp)>0}get isCompleted(){var t;return((t=this.completed)==null?void 0:t.timestamp)>0}get isConfirmed(){var t;return((t=this.confirmed)==null?void 0:t.timestamp)>0}get isDeleted(){var t;return((t=this.deleted)==null?void 0:t.timestamp)>0}get isTerminated(){var t;return((t=this.terminated)==null?void 0:t.timestamp)>0}get isValid(){return super.isValid}setCancelled(t,e){return this.setValue(t,e,"cancelled")}setCompleted(t,e){return this.setValue(t,e,"completed")}setConfirmed(t,e){return this.setValue(t,e,"confirmed")}setDeleted(t,e){return this.setValue(t,e,"deleted")}setTerminated(t,e){return this.setValue(t,e,"terminated")}}class se extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.open=this._ActionRecord.init(t.open),this.revised=this._ActionRecord.init(t.revised),this.void=this._ActionRecord.init(t.void)}static get _classname(){return"StatusQStoreInvoice"}get _classname(){return"StatusQStoreInvoice"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}get isRevised(){var t;return((t=this.revised)==null?void 0:t.timestamp)>0}get isValid(){return super.isValid}get isVoid(){var t;return((t=this.void)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setOpen(t,e){return this.setValue(t,e,"open")}setRevised(t,e){return this.setValue(t,e,"revised")}setVoid(t,e){return this.setValue(t,e,"void")}}class ie extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.open=this._ActionRecord.init(t.open),this.revised=this._ActionRecord.init(t.revised),this.void=this._ActionRecord.init(t.void)}static get _classname(){return"StatusQStoreInvoiceLine"}get _classname(){return"StatusQStoreInvoiceLine"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}get isRevised(){var t;return((t=this.revised)==null?void 0:t.timestamp)>0}get isValid(){return super.isValid}get isVoid(){var t;return((t=this.void)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setOpen(t,e){return this.setValue(t,e,"open")}setRevised(t,e){return this.setValue(t,e,"revised")}setVoid(t,e){return this.setValue(t,e,"void")}}class st extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.expired=this._ActionRecord.init(t.expired),this.invalid=this._ActionRecord.init(t.invalid),this.open=this._ActionRecord.init(t.open)}static get _classname(){return"StatusQStoreOrder"}get _classname(){return"StatusQStoreOrder"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isExpired(){var t;return((t=this.expired)==null?void 0:t.timestamp)<Date.now()}get isInvalid(){var t;return((t=this.invalid)==null?void 0:t.timestamp)<Date.now()}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setExpired(t,e){return this.setValue(t,e,"expired")}setInvalid(t,e){return this.setValue(t,e,"invalid")}setOpen(t,e){return this.setValue(t,e,"open")}}class it extends V{constructor(t){t=t||{},super(t),this.closed=this._ActionRecord.init(t.closed),this.expired=this._ActionRecord.init(t.expired),this.fulfilled=this._ActionRecord.init(t.fulfilled),this.invalid=this._ActionRecord.init(t.invalid),this.open=this._ActionRecord.init(t.open)}static get _classname(){return"StatusQStoreOrderLine"}get _classname(){return"StatusQStoreOrderLine"}get isClosed(){var t;return((t=this.closed)==null?void 0:t.timestamp)>0}get isExpired(){var t;return((t=this.expired)==null?void 0:t.timestamp)<Date.now()}get isFulfilled(){var t;return((t=this.fulfilled)==null?void 0:t.timestamp)>0}get isInvalid(){var t;return((t=this.invalid)==null?void 0:t.timestamp)<Date.now()}get isOpen(){var t;return((t=this.open)==null?void 0:t.timestamp)>0}setClosed(t,e){return this.setValue(t,e,"closed")}setExpired(t,e){return this.setValue(t,e,"expired")}setFulfilled(t,e){return this.setValue(t,e,"fulfilled")}setInvalid(t,e){return this.setValue(t,e,"invalid")}setOpen(t,e){return this.setValue(t,e,"open")}}const ii=["amount"];class rt extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_PaymentGateway:i,_Receipt:r,_ReceiptLine:n}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._PaymentGateway=i&&i._superclass===D._superclass?i:D,this._Receipt=r&&r._superclass===F._superclass?r:F,this._ReceiptLine=n&&n._superclass===T._superclass?n:T,this._paymentGateway=t._paymentGateway,this._receipt=t._receipt,this._receiptLine=t._receiptLine;const a=t._id||t.id;this.id=ri(a),this._type=t._type||"PaymentCharge",this.amount=this._Amount.init(t.amount),this.billingAccountCode=t.billingAccountCode,this.billingProjectCode=t.billingProjectCode,this.paymentGatewayCode=t.paymentGatewayCode,this.paymentChargeCode=t.paymentChargeCode,this.paymentChargeType="PaymentCharge",this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptLineCode=t.receiptLineCode}static dummyData(){return{billingAccountCode:"billingAccountCode",paymentGatewayCode:"paymentGatewayCode",receiptCode:"receiptCode",receiptLineCode:"receiptLineCode",tenantCode:"tenantCode"}}static get _classname(){return"PaymentCharge"}static get _superclass(){return"PaymentCharge"}get isValid(){return super.isValid&&!!this.billingAccountCode&&!!this.paymentGatewayCode&&!!this.receiptCode&&!!this.receiptLineCode}get paymentGateway(){return this._PaymentGateway.init(this._paymentGateway)}get receipt(){return this._Receipt.init(this._receipt)}get receiptLines(){return this._ReceiptLine.initOnlyValidFromArray(this._receiptLines||[])}update(t){return Object.keys(t).forEach(e=>{ii.includes(e)&&(e==="amount"?this[e]=this.amount instanceof this._Amount?this.amount.update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function ri(s){return s&&typeof s.toString=="function"?s.toString():s}const ni=["additionalData","amount","paidAmount","paymentGatewayCode","receiptDate","status","surcharge"];class T extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_PaymentCharge:i,_PaymentItem:r,_Receipt:n,_Status:a}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._PaymentCharge=i&&i._superclass===rt._superclass?i:rt,this._PaymentItem=r&&r._superclass===Q._superclass?r:Q,this._Receipt=n&&n._superclass===F._superclass?n:F,this._Status=a&&a._superclass===V._superclass?a:V,this._paymentCharge=t._paymentCharge,this._paymentItems=t._paymentItems,this._receipt=t._receipt;const u=t._id||t.id;this.id=ai(u),this._type=t._type||"ReceiptLine",this.additionalData=l.KeyValueObject.initOnlyValidFromArray(t.additionalData),this.amount=this._Amount.init(t.amount),this.paidAmount=this._Amount.init(t.paidAmount),this.paymentGatewayCode=t.paymentGatewayCode,this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptLineCode=t.receiptLineCode,this.receiptLineType="ReceiptLine",this.status=this._Status.init(t.status),this.surcharge=this._Amount.init(t.surcharge)}static dummyData(){return{receiptCode:"receiptCode",tenantCode:"tenantCode"}}static get _classname(){return"ReceiptLine"}static get _superclass(){return"ReceiptLine"}get isCancelled(){return this.status.isCancelled}get isCompleted(){return this.status.isCompleted}get isConfirmed(){return this.status.isConfirmed}get isTerminated(){return this.status.isTerminated}get isValid(){return super.isValid&&!!this.receiptCode}get paymentCharge(){return this._PaymentCharge.init(this._paymentCharge)}get paymentItems(){return this._PaymentItem.initOnlyValidFromArray(this._paymentItems)}get receipt(){return this._Receipt.init(this._receipt)}getAmount(){return this.amount}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setConfirmed(t,e){return this.status.setProcessing(t,e),this.setModified()}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{ni.includes(e)&&(e==="additionalData"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):e==="status"?this[e]=this[e]instanceof this._Status?this[e].update(t[e]):this._Status.init(t[e]):e==="amount"||e==="paidAmount"||e==="surcharge"?this[e]=this[e]instanceof this._Amount?this[e].update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function ai(s){return s&&typeof s.toString=="function"?s.toString():s}const ui=["amount","paidAmount","receiptDate","revisionNumber","status","surcharge"];class F extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_ReceiptLine:i,_Status:r}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._ReceiptLine=i&&i._superclass===T._superclass?i:T,this._Status=r&&r._superclass===V._superclass?r:V,this._receiptLines=t._receiptLines;const n=t._id||t.id;this.id=ci(n),this._type=t._type||"Receipt",this.amount=this._Amount.init(t.amount),this.paidAmount=this._Amount.init(t.paidAmount),this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptNumber=t.receiptNumber,this.receiptType="Receipt",this.revisionNumber=t.revisionNumber||1,this.status=this._Status.init(t.status),this.surcharge=this._Amount.init(t.surcharge)}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"Receipt"}static get _superclass(){return"Receipt"}get isCancelled(){return this.status.isCancelled}get isCompleted(){return this.status.isCompleted}get isConfirmed(){return this.status.isConfirmed}get isTerminated(){return this.status.isTerminated}get receiptLines(){return this._ReceiptLine.initOnlyValidFromArray(this._receiptLines||[])}getAmount(){return this.amount}getFullReceiptNumber(t="."){return`${this.receiptNumber}${t}${this.revisionNumber}`}increaseRevisionNumber(){return this.revisionNumber+=1,this}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setConfirmed(t,e){return this.status.setProcessing(t,e),this.setModified()}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{ui.includes(e)&&(e==="status"?this[e]=this.status instanceof this._Status?this.status.update(t[e]):this._Status.init(t[e]):e==="amount"||e==="paidAmount"||e==="surcharge"?this[e]=this[e]instanceof this._Amount?this[e].update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function ci(s){return s&&typeof s.toString=="function"?s.toString():s}const oi=["amount"];class Q extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_Invoice:i,_InvoiceLine:r,_PaymentGateway:n,_Receipt:a,_ReceiptLine:u}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._Invoice=i&&i._superclass===U._superclass?i:U,this._InvoiceLine=r&&r._superclass===Y._superclass?r:Y,this._PaymentGateway=n&&n._superclass===D._superclass?n:D,this._Receipt=a&&a._superclass===F._superclass?a:F,this._ReceiptLine=u&&u._superclass===T._superclass?u:T,this._invoice=t._invoice,this._invoiceLines=t._invoiceLines,this._paymentGateway=t._paymentGateway,this._receipt=t._receipt,this._receiptLine=t._receiptLine;const c=t._id||t.id;this.id=li(c),this._type=t._type||"PaymentItem",this.amount=this._Amount.init(t.amount),this.invoiceCode=t.invoiceCode,this.invoiceDate=t.invoiceDate||new Date().valueOf(),this.invoiceLineCode=t.invoiceLineCode,this.paymentGatewayCode=t.paymentGatewayCode,this.paymentItemCode=t.paymentItemCode,this.paymentItemType="PaymentItem",this.receiptCode=t.receiptCode,this.receiptDate=t.receiptDate||new Date().valueOf(),this.receiptLineCode=t.receiptLineCode}static dummyData(){return{invoiceCode:"invoiceCode",invoiceLineCode:"invoiceLineCode",paymentGatewayCode:"paymentGatewayCode",receiptCode:"receiptCode",receiptLineCode:"receiptLineCode",tenantCode:"tenantCode"}}static get _classname(){return"PaymentItem"}static get _superclass(){return"PaymentItem"}get invoice(){return this._Invoice.init(this._invoice)}get invoiceLines(){return this._InvoiceLine.initOnlyValidFromArray(this._invoiceLines||[])}get isValid(){return super.isValid&&!!this.invoiceCode&&!!this.invoiceLineCode&&!!this.paymentGatewayCode&&!!this.receiptCode&&!!this.receiptLineCode}get paymentGateway(){return this._PaymentGateway.init(this._paymentGateway)}get receipt(){return this._Receipt.init(this._receipt)}get receiptLines(){return this._ReceiptLine.initOnlyValidFromArray(this._receiptLines||[])}update(t){return Object.keys(t).forEach(e=>{oi.includes(e)&&(e==="amount"?this[e]=this.amount instanceof this._Amount?this.amount.update(t[e]):this._Amount.init(t[e]):this[e]=t[e])}),super.update(t)}}function li(s){return s&&typeof s.toString=="function"?s.toString():s}const di=["accountAllocations","amount","deduction","description","discount","invoiceDate","note","outstanding","purchaseOptions","qty","refundAccountAllocations","unitPrice"];class Y extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_AccountAllocation:e,_Amount:i,_Invoice:r,_Merchandise:n,_PaymentItem:a,_RefundAccountAllocation:u,_Status:c}=t._constructor||{};this._AccountAllocation=e&&e._superclass===j._superclass?e:j,this._Amount=i&&i._superclass===m._superclass?i:m,this._Invoice=r&&r._superclass===U._superclass?r:U,this._Merchandise=n&&n._superclass===I._superclass?n:I,this._PaymentItem=a&&a._superclass===Q._superclass?a:Q,this._RefundAccountAllocation=u&&u._superclass===q._superclass?u:q,this._Status=c&&c._superclass===O._superclass?c:O,this._invoice=t._invoice,this._merchandise=t._merchandise,this._paymentItems=t._paymentItems;const o=t._id||t.id;this.id=mi(o),this._type=t._type||"InvoiceLine",this.accountAllocations=this._AccountAllocation.initOnlyValidFromArray(t.accountAllocations),this.amount=this._Amount.init(t.amount),this.deduction=this._Amount.init(t.deduction),this.description=t.description,this.discount=t.discount||0,this.invoiceCode=t.invoiceCode,this.invoiceDate=t.invoiceDate,this.invoiceLineCode=hi(t,"invoiceLineCode"),this.invoiceLineType=t.invoiceLineType||"InvoiceLine",this.merchandiseCode=t.merchandiseCode,this.note=t.note,this.outstanding=this._Amount.init(t.outstanding),this.purchaseOptions=l.KeyValueObject.initOnlyValidFromArray(t.purchaseOptions),this.qty=t.qty||1,this.refundAccountAllocations=this._RefundAccountAllocation.initOnlyValidFromArray(t.refundAccountAllocations),this.status=this._Status.init(t.status),this.unitPrice=this._Amount.init(t.unitPrice),this.waived=t.waived||0}static dummyData(){return{amount:m.dummyData(),invoiceCode:"invoiceCode",tenantCode:"tenantCode"}}static get _classname(){return"InvoiceLine"}static get _superclass(){return"InvoiceLine"}get isClosed(){return this.status.isClosed}get isOpen(){return this.status.isOpen}get isValid(){return super.isValid&&!!this.amount&&!!this.invoiceCode}get invoice(){return this._Invoice.init(this._invoice)}get merchandise(){return this._Merchandise.init(this._merchandise)}get paymentItems(){return this._PaymentItem.initOnlyValidFromArray(this._paymentItems)}get usedCoupons(){const t=l.KeyValueObject.getValueByKey(this.remarks,"USED_ITEM_COUPONS")||[],e=l.KeyValueObject.getValueByKey(this.remarks,"USED_TOTAL_COUPONS")||[];return[...t,...e]}getPreservedData(){return{created:this.created,invoiceCode:this.invoiceCode,invoiceLineCode:this.invoiceLineCode,qty:this.qty,unitPrice:this.unitPrice,amount:this.amount,deduction:this.deduction,discount:this.discount,invoiceLineType:this.invoiceLineType}}getPurchaseOptionValue(t){const{key:e}=t||{};return te({key:e,purchaseOptions:this.purchaseOptions})}setClosed(t,e){return typeof this.status.setClosed!="function"?this:(this.status.setClosed(t,e),this.setModified())}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setOpen(t,e){return this.isOpen||typeof this.status.setOpen!="function"?this:(this.status.setOpen(t,e),this.setModified())}setRevised(t,e){return typeof this.status.setRevised!="function"?this:(this.status.setRevised(t,e),this.setModified())}setVoid(t,e){return typeof this.status.setVoid!="function"?this:(this.status.setVoid(t,e),this.setModified())}update(t){return Object.keys(t).forEach(e=>{di.includes(e)&&(e==="amount"||e==="unitPrice"||e==="deduction"||e==="outstanding"?this[e]=this._Amount.init(t[e]):e==="accountAllocations"?this[e]=this._AccountAllocation.initOnlyValidFromArray(t[e]):e==="purchaseOptions"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):e==="refundAccountAllocations"?this[e]=this._RefundAccountAllocation.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}updateOutstanding({actorCode:t}={}){var n;const e=this.paymentItems;if(e.length===0)return this;if(((n=this.outstanding)==null?void 0:n.value)<=0)return this;const i=e.reduce((a,u)=>{var c;return a+(((c=u==null?void 0:u.amount)==null?void 0:c.value)||0)},0),r=this.amount.value-i;return r<=0&&this.setClosed(Date.now(),t),this.update({outstanding:{currencyCode:this.amount.currencyCode,value:r}})}}function hi(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function mi(s){return s&&typeof s.toString=="function"?s.toString():s}class Rt{constructor(t={}){t=t||{},this.bankAccount=t.bankAccount,this.contactInformation=t.contactInformation,this.name=t.name,this.logo=t.logo}static dummyData(){return{name:"name"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"Issuer"}static get _superclass(){return"Issuer"}get isValid(){return!!this.name}updateIssuer(t){return Object.keys(t).forEach(e=>{this[e]=t[e]}),this}}const gi=["purchaseOptions","qty","status"];class nt extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e,_Product:i,_Status:r}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._Product=i&&i._superclass===R._superclass?i:R,this._Status=r&&r._superclass===O._superclass?r:O,this._eventRegistration=t._eventRegistration,this._invoiceLine=t._invoiceLine,this._product=t._product,this._tenant=t._tenant,this._transaction=t._transaction,this._type=t._type||"WalletItem";const n=t._id||t.id;this.id=pi(n),this.invoiceLineCode=t.invoiceLineCode,this.productCode=t.productCode,this.purchaseOptions=l.KeyValueObject.initOnlyValidFromArray(t.purchaseOptions),this.qty=t.qty||1,this.status=this._Status.init(t.status),this.transactionCode=t.transactionCode,this.walletItemCode=fi(t,"walletItemCode")}static dummyData(){return{...super.dummyData(),productCode:"5cd4f5430c2b874ad7ed8cfd",qty:1,status:O.dummyData(),tenantCode:"tenantCode",transactionCode:"transactionCode"}}static get _classname(){return"WalletItem"}static get _superclass(){return"WalletItem"}get isValid(){return super.isValid&&!!this.productCode}get isAssigned(){return this.status.isAssigned}get isAvailable(){return this.isInWallet&&(!this.isUsed||!this.isDelivered)}get isAvailableCoupon(){return this.isCoupon&&!this.isCancelled&&!this.isUsed}get isCancelled(){return this.status.isCancelled}get isCompleted(){return this.status.isCompleted}get isConfirmed(){return this.status.isConfirmed}get isCoupon(){return this.product?this.product.isCoupon:!1}get isDelivered(){return this.status.isDelivered}get isInWallet(){return!this.isCancelled&&!this.isRejected&&!this.isRefunded&&!this.isRefundRequested}get isItemCoupon(){return this.product?this.product.isItemCoupon:!1}get isOnHold(){return this.status.onHold}get isOwned(){return this.isInWallet&&(this.isPaid&&!this.isAssigned&&!this.isConfirmed||this.isWaived&&!this.isAssigned&&!this.isConfirmed||this.isRedeemed&&!this.isAssigned&&!this.isConfirmed||this.isAssigned&&this.isConfirmed)}get isPaid(){return this.status.isPaid}get isPending(){return this.status.isPending}get isRedeemed(){return this.status.redeemed}get isRefunded(){return this.status.isRefunded}get isRefundRequested(){return this.status.isRefundRequested}get isRejected(){return this.status.rejected}get isShared(){return this.status.shared}get isSubmitted(){return this.status.isSubmitted}get isTotalCoupon(){return this.product?this.product.isTotalCoupon:!1}get isUsed(){return this.status.isUsed}get isWaived(){return this.status.isWaived}get couponDetails(){return this.product?this.product.couponDetails:null}get displayPurchaseOptions(){return this.purchaseOptions.length>0?this.purchaseOptions.reduce((t,e)=>{const{value:i}=e;return t+=i.reduce((r,n)=>{const{label:a,value:u}=n;return r+=`<div><span>${a}: </span><span>${u}</span></div>`},"")},""):""}get lastRefundRejectedDetail(){return Array.isArray(this.refundRejectedHistory)&&this.refundRejectedHistory.length>0?this.refundRejectedHistory[this.refundRejectedHistory.length-1]:null}get paid(){if(!this._transaction)return null;const{amount:t,meta:e}=this._transaction;return{created:e.created,currencyCode:t.currencyCode,modified:e.modified,value:t.value}}get product(){return this._Product.init(this._product)}get refundedDetail(){return l.Metadata.getValueByKey(this.metadata,"REFUNDED_DETAIL")||{}}get refundRejectedHistory(){return l.Metadata.getValueByKey(this.metadata,"REFUND_REJECTED_HISTORY")||{}}get refundRequestedDetail(){return l.Metadata.getValueByKey(this.metadata,"REFUND_REQUESTED_DETAIL")||{}}get tenant(){return this._tenant}get usedTimestamp(){return this.status.used}formatFlexcel(){return{...this,...this.status,used:this.isUsed,productName:this.product&&this.product.name?this.product.name:""}}formatOutput({format:t}){switch(t){case"flexcel":return this.formatFlexcel();default:return this}}getCode(){return this.walletItemCode}getPurchaseOptionValue(t){const{delimiter:e,key:i,tag:r}=t||{};return te({delimiter:e,key:i,purchaseOptions:this.purchaseOptions,tag:r})}isApplicableCoupon(t){return this.isAvailableCoupon&&(this.product?this.product.isApplicableCoupon(t):!1)}isSameOwner(t){return t&&this.owner?t===this.owner:!1}setAssigned(t){return this.status.setAssigned(t),this}setCancelled(t){return this.status.setCancelled(t),this}setConfirmed(t){return this.status.setConfirmed(t),this}setDelivered(t){return this.status.setDelivered(t),this}setOnHold(){return this.status.setOnHold(),this}setPaid(){return this.status.setPaid(),this}setPaidTimestamp(t){return this.status.setPaid(t),this}setPending(){return this.status.setPending(),this}setRedeemed(){return this.status.setRedeemed(),this}setRejected(){return this.status.setRejected(),this}setRefunded(t){this.status.cancelled||this.setCancelled();const e=this.status.cancelled+1;return this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,"REFUNDED_DETAIL",t),this.status.setRefunded(e),this}setRefundRequested(t){return this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,"REFUND_REQUESTED_DETAIL",t),this.status.setRefundRequested(),this}setRefundRejected(t){const e=this.status.refundRequested;this.unSetRefundRequested();const i=l.Metadata.foundValueByKey(this.metadata,"REFUND_REJECTED_HISTORY")||[];i.push({...t,refundRequested:e,created:new Date().valueOf()}),this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,"REFUND_REJECTED_HISTORY",i)}setShared(){return this.status.setShared(),this}setUsedTimestamp(){return this.status.setUsed(),this}setUsedCouponFor(t){const e=l.KeyValueObject.foundValueByKey(this.metadata,"USED_COUPON_FOR")||[];e.push(t),this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,"USED_COUPON_FOR",e)}setWaived(){return this.status.setWaived(),this}updatePurchaseOptions(t){const{purchaseOptions:e}=this,i=l.Metadata.foundValueByKey(this.metadata,"PURCHASE_OPTION_HISTORY")||[];return i.push({purchaseOptions:N.cloneDeep(e),created:new Date().valueOf()}),this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,"PURCHASE_OPTION_HISTORY",i),e.forEach(r=>{const{key:n,value:a}=r,{value:u}=t.find(c=>c.key===n);a.forEach((c,o)=>{Object.assign(c,u[o])})}),this}unSetAssigned(){return this.status.unSetAssigned(),this}unsetDelivered(){return this.status.unsetDelivered(),this}unSetOnHold(){return this.status.unSetOnHold(),this}unSetRefundRequested(){return this.status.unSetRefundRequested(),this}unsetUsed(){return this.status.unsetUsed(),this}update(t){return Object.keys(t).forEach(e=>{gi.includes(e)&&(e==="purchaseOptions"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function pi(s){return s&&typeof s.toString=="function"?s.toString():s}function fi(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}const yi=["amount","couponCodes","status"];class k extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e,_PaymentResultFactory:i,_Status:r,_WalletItem:n}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._PaymentResultFactory=i,this._Status=r&&r._superclass===O._superclass?r:O,this._WalletItem=n&&n._superclass===nt._superclass?n:nt,this._coupons=t._coupons,this._creditNotes=t._creditNotes,this._invoice=t._invoice,this._paymentGateway=t._paymentGateway,this._paymentResults=t._paymentResults,this._walletItems=t._walletItems;const a=t._id||t.id;this.id=_i(a),this._type=t._type||"Transaction",this.amount=this._Amount.init(t.amount),this.couponCodes=t.couponCodes||[],this.creditNoteCodes=t.creditNoteCodes||[],this.invoiceCode=t.invoiceCode,this.paymentGatewayCode=t.paymentGatewayCode,this.paymentResultRef=t.paymentResultRef,this.status=this._Status.init(t.status),this.transactionCode=Ci(t,"transactionCode")}static dummyData(){return{status:O.dummyData(),tenantCode:"tenantCode"}}static get _classname(){return"Transaction"}static get _superclass(){return"Transaction"}get isValid(){return super.isValid}get billedAmount(){var t;return(t=this.amount)==null?void 0:t.displayAmount()}get isActive(){return this.active===!0}get isAssigned(){return this.status.isAssigned}get isCancelled(){return this.status.isCancelled}get isConfirmed(){return this.status.isConfirmed}get isCompleted(){return this.status.isCompleted}get isExpired(){return this.status.isExpired}get isFailed(){return this.status.isFailed}get isOnHold(){return this.status.isOnHold}get isPaid(){return this.status.isPaid}get isPending(){return this.status.isPending}get isProcessing(){return this.status.isProcessing}get isRedeemed(){return this.status.isRedeemed}get isRefunded(){return this.status.isRefunded}get isShared(){return this.status.isShared}get isSubmitted(){return this.status.isSubmitted}get isWaived(){return this.status.isWaived}get paymentResults(){return this._PaymentResultFactory.initOnlyValidFromArray(this._paymentResults||[])}get paymentResultAmounts(){return this.paymentResults.filter(t=>t.isSuccess()).map(t=>({billedAmount:t.billedAmount,paidTimestamp:t.getPaidTimestamp(),paymentMethod:t.paymentMethod,paymentResultCode:t.paymentResultCode,receivedAmount:t.receivedAmount}))}get successedPaymentResult(){return this.paymentResults.find(t=>t.isSuccess())}get walletItems(){return this._WalletItem.initOnlyValidFromArray(this._walletItems)}getId(){return this.id?this.id.toString():this.id}getLatestStatus(){var t,e;return((e=(t=this.status)==null?void 0:t.statusLast)==null?void 0:e.key)||""}getCode(){return this.transactionCode}isAllowDelete(){return this.active&&!this.deleted&&!this.isCancelled&&!this.isCompleted&&!this.isPaid&&!this.isWaived}isAllowPay(){return this.active&&!this.deleted&&!this.isCancelled&&!this.isCompleted&&!this.isPaid&&!this.isWaived&&!this.isExpired}setAssigned(){return this.status.setAssigned(),this}setCancelled(){return this.status.setCancelled()}setCompleted(){return this.status.setCompleted()}setFailed(){return this.status.setFailed()}setOnHold(){return this.status.setOnHold()}setPaid(){return this.status.setPaid()}setPaymentResultRef(t){return this.paymentResultRef=t,this}setPending(){return this.status.setPending()}setProcessing(){return this.status.setProcessing()}setRedeemed(){return this.status.setRedeemed()}setRefunded(){return this.status.setRefunded()}setSettled(){return this.status.setSettled()}setShared(){return this.status.setShared()}setWaived(){return this.status.setWaived()}updateStatus(t){switch(t){case"cancelled":return this.setCancelled();case"completed":return this.setCompleted();case"failed":return this.setFailed();case"on-hold":return this.setOnHold();case"pending":return this.setPending();case"processing":return this.setProcessing();case"refunded":return this.setRefunded();default:return this}}update(t){return Object.keys(t).forEach(e=>{yi.includes(e)&&(e==="amount"?this[e]=this._Amount.init(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function Ci(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function _i(s){return s&&typeof s.toString=="function"?s.toString():s}const Ai=["billToUserCode","checkoutDateTime","description","invoiceDate","issuer","outstanding","revisionNumber","status"];class U extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_BillToUser:i,_Cart:r,_InvoiceLine:n,_Issuer:a,_Status:u,_Transaction:c}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._BillToUser=i,this._Cart=r&&r._superclass===et._superclass?r:et,this._InvoiceLine=n&&n._superclass===Y._superclass?n:Y,this._Issuer=a&&a._superclass===Rt._superclass?a:Rt,this._Status=u&&u._superclass===O._superclass?u:O,this._Transaction=c&&c._superclass===k._superclass?c:k,this._billToUser=t._billToUser,this._cart=t._cart,this._invoiceLines=t._invoiceLines,this._transactions=t._transactions;const o=t._id||t.id;this.id=vi(o),this._type=t._type||"Invoice",this.amount=this._Amount.init(t.amount),this.billToUserCode=t.billToUserCode,this.cartCode=t.cartCode,this.checkoutDateTime=t.checkoutDateTime||new Date().valueOf(),this.description=t.description,this.invoiceCode=Oi(t,"invoiceCode"),this.invoiceDate=t.invoiceDate||new Date().valueOf(),this.invoiceNumber=t.invoiceNumber,this.invoiceType=t.invoiceType||"Invoice",this.issuer=this._Issuer.init(t.issuer),this.outstanding=this._Amount.init(t.outstanding),this.revisionNumber=t.revisionNumber||0,this.status=this._Status.init(t.status)}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"Invoice"}static get _superclass(){return"Invoice"}get isOpen(){return this.status.isOpen}get isValid(){return super.isValid}get isVoid(){return!!this.status.isVoid}get billToUser(){return this._BillToUser&&typeof this._BillToUser.init=="function"?this._BillToUser.init(this._billToUser):this._billToUser}get cart(){return this._Cart.init(this._cart)}get invoiceLines(){return this._InvoiceLine.initOnlyValidFromArray(this._invoiceLines||[])}get merchandises(){return(this.invoiceLines||[]).map(t=>t.merchandise).filter(t=>t)}get merchandisesSummary(){return this.merchandises.reduce((t,e)=>{const i=t.find(r=>r.merchandiseCode===e.merchandiseCode);return i?i.qty+=1:t.push({...e.summary,qty:1}),t},[])}get products(){return(this.merchandises||[]).reduce((t,e)=>(e.products&&(t=t.concat(e.products)),t),[])}get productsSummary(){return this.products.reduce((t,e)=>{const i=t.find(r=>r.productCode===e.productCode);return i?i.qty+=1:t.push({...e.summary,qty:1}),t},[])}get transactions(){return this._Transaction.initOnlyValidFromArray(this._transactions)}get walletItems(){return(this.transactions||[]).reduce((t,e)=>(e.walletItems&&(t=t.concat(e.walletItems)),t),[])}allowCancel(){return this.status.allowCancel()}getAmount(){return this.amount}getCode(){return this.invoiceCode}getCurrencyCode(){return this.amount?this.amount.getCurrencyCode():null}getFullInvoiceNumber(t="."){return`${this.invoiceNumber}${t}${this.revisionNumber}`}getPreservedData(){return{checkoutDateTime:this.checkoutDateTime,created:this.created,invoiceCode:this.invoiceCode,invoiceType:this.invoiceType,invoiceNumber:this.invoiceNumber,invoiceDate:this.invoiceDate,revisionNumber:this.revisionNumber,remarks:this.remarks}}increaseRevisionNumber(){return this.revisionNumber+=1,this}setCancelled(){return this.status.setCancelled()}setClosed(t,e){return typeof this.status.setClosed!="function"?this:(this.status.setClosed(t,e),this.setModified())}setCheckoutDateTime(t){return typeof t=="number"&&(this.checkoutDateTime=t),this}setCompleted(){return this.status.setCompleted(),this.setModified()}setOpen(t,e){return this.isOpen||typeof this.status.setOpen!="function"?this:(this.status.setOpen(t,e),this.setModified())}setRevised(t,e){return typeof this.status.setRevised!="function"?this:(this.status.setRevised(t,e),this.setModified())}setVoid(t,e){return typeof this.status.setVoid!="function"?this:(this.status.setVoid(t,e),this.setModified())}setWaived(){return this.status.setWaived(),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Ai.includes(e)&&(e==="amount"||e==="outstanding"?this[e]=this._Amount.init(t[e]):e==="issuer"?this[e]=this._Issuer.init(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}updateOutstanding({actorCode:t}={}){var r;const e=this.invoiceLines;if(e.length===0)return this;if(((r=this.outstanding)==null?void 0:r.value)<=0)return this;const i=e.reduce((n,a)=>{var u;return a.updateOutstanding({actorCode:t}),n+((u=a==null?void 0:a.outstanding)==null?void 0:u.value)},0);return i<=0&&this.setClosed(Date.now(),t),this._invoiceLines=e,this.update({outstanding:{currencyCode:this.getCurrencyCode(),value:i}})}}function Oi(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function vi(s){return s&&typeof s.toString=="function"?s.toString():s}let pt=null,re=null,B={},$=null;function bi(s,t,e){const i=[],{status:r}=s;return!(r instanceof O)||r.isCancelled||((r.isCompleted||s.amount&&s.amount.value===0)&&(i.push({css:{element:"__button"},icon:"fa fa-download",label:B.DOWNLOAD,onClick:$.onOrderListAction("downloadInvoice")}),i.push({css:{element:"__button"},icon:"fa fa-paper-plane",label:B.SENDEMAIL,onClick:$.onOrderListAction("sendInvoice")})),r.isPending&&(re?(i.push({css:{element:"__button"},icon:"fa fa-edit",label:B.ADMIN_SETTLE,onClick:$.onOrderListAction("adminSettle")}),pt&&pt.allowWaived&&i.push({css:{element:"__button"},icon:"fa fa-edit",label:B.WAIVED,onClick:$.onOrderListAction("waived")})):i.push({css:{element:"__button"},icon:"fa fa-money",label:B.PAY,onClick:$.onOrderListAction("payOnline")}),i.push({css:{element:"__button"},icon:"fa fa-trash",label:B.CANCEL,onClick:$.onOrderListAction("cancel")}))),i}function Pi(s,t){return U.initFromArray(t).map(i=>{const r=l.convertTimestampToString(i.invoiceDate,"YYYY-MM-DD HH:mm"),{amount:n,itemNames:a,qty:u}=i.invoiceLines.reduce((d,h)=>{const g=s.find(p=>p.merchandiseCode===h.merchandiseCode);return g&&(d.itemNames.push(g.name),d.qty.push(h.qty)),{...d,amount:i.amount&&i.amount.value?i.amount:{value:d.amount.value+h.amount.value*h.qty,currencyCode:h.amount.currencyCode,default:d.amount.default&&h.amount.default}}},{amount:{value:0,currencyCode:"",default:!0},itemNames:[],qty:[]}),c=a.reduce((d,h,g)=>(d.push(`<div>${h} x ${u[g]}</div>`),d),[]),o=i.revisionNumber>1?`R${i.revisionNumber}`:"";return{...i,_invoiceDate:r,_amountValue:`${n.currencyCode} ${(n.value/100).toFixed(2)}`,_amountCurrency:n.currencyCode,_status:wi(i.status),_itemNames:c.join(`
|
|
2
|
+
`),_invoiceNumber:`${i.invoiceNumber} ${o}`}})}function wi(s){let t="";if(!(s instanceof O))return t;if(s.isCancelled)return t="cancelled",t;if(s.isCompleted)return t="completed",t;let e=0;return t=Object.keys(s).reduce((i,r)=>(s[r]>e&&(e=s[r],i=r),i),""),t}function Ii(s){return[...s,{label:"Actions",customComponentName:"q-list-body-row-cell-action",actionBuilder:bi,css:{element:"__action"},labelButton:{DOWNLOAD:"Download",CANCEL:"Cancel",SETTLE:"Settle",PAY:"Pay"}}]}function ne({component:s,config:t,merchandises:e,invoices:i,defaultHeaders:r,isAdmin:n,label:a={}}){$=s,pt=t,re=n,B=a.button||{};const c=Pi(e,i).sort((d,h)=>d.invoiceDate<h.invoiceDate?1:-1),o=Ii(r);return{rows:c,headers:o}}function ae(s,t){if(!t)return s;let e=null;switch(typeof t){case"function":return s.forEach(i=>{e=t(i)}),e.length===0||s.sort((i,r)=>i[e]<r[e]?1:-1),s;case"string":return e=t,s.sort((i,r)=>i[e]<r[e]?1:-1),s;default:return s}}function ue({arr:s=[],key:t}){const[e]=s,i=e[t];return s.every(r=>r[t]===i)}function ce({arr:s=[],key:t}){const e=s.length-1,i=s[0][t],r=s[e][t];return i<r}const Si=Object.freeze(Object.defineProperty({__proto__:null,Chain:w,ChainManager:ft,ChainTarget:yt,ComplimentaryItemManager:Ut,CouponManager:Gt,adminSettle:$t,calculateAmount:jt,calculateByCoupon:Ct,calculator:G,checkDuplicate:vt,defaultComparator:bt,defaultSort:ae,eleInArrayComparator:Kt,firstLetterToLower:Ot,getFakeClass:Nt,getSubClass:qt,handlerOrderList:ne,isAllEqual:ue,isDescendingOrder:ce,makeResponseHelper:Yt,objectAllInArrayComparator:Wt,objectComparator:Ht,objectOrderInArrayComparator:Qt,setQuery:kt,stringHelper:A},Symbol.toStringTag,{value:"Module"})),Ri=["default","name","segment"];class oe extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const e=t._id||t.id;this.id=Vi(e),this._type=t._type||"BillingAccount",this.billingAccountCode=t.billingAccountCode,this.default=!!t.default,this.name=t.name,this.segment=t.segment}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"BillingAccount"}static get _superclass(){return"BillingAccount"}update(t){return Object.keys(t).forEach(e=>{Ri.includes(e)&&(this[e]=t[e])}),super.update(t)}}function Vi(s){return s&&typeof s.toString=="function"?s.toString():s}const Ei=["description"];class le extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m;const i=t._id||t.id;this.id=Ti(i),this._type=t._type||"BillingLedgerEntry",this.billingAccountCode=t.billingAccountCode,this.billingLedgerEntryCode=Di(t,"billingLedgerEntryCode"),this.billingProjectCode=t.billingProjectCode,this.creditAmount=this._Amount.init(t.creditAmount),this.currencyCode=t.currencyCode,this.debitAmount=this._Amount.init(t.debitAmount),this.description=t.description,this.postingDate=t.postingDate,this.sourceDocumentCode=t.sourceDocumentCode,this.sourceDocumentType=t.sourceDocumentType,this.sourceLineCode=t.sourceLineCode}static dummyData(){return{billingAccountCode:"billingAccountCode",billingProjectCode:"billingProjectCode",creditAmount:m.dummyData(),currencyCode:"USD",postingDate:Date.now(),sourceDocumentCode:"sourceDocumentCode",sourceDocumentType:"Invoice",tenantCode:"tenantCode"}}static get _classname(){return"BillingLedgerEntry"}static get _superclass(){return"BillingLedgerEntry"}get hasOneSideAmount(){return!!this.debitAmount&&!this.creditAmount||!this.debitAmount&&!!this.creditAmount}get isValid(){return super.isValid&&!!this.billingAccountCode&&!!this.billingProjectCode&&!!this.currencyCode&&this.hasOneSideAmount&&!!this.postingDate&&!!this.sourceDocumentCode&&!!this.sourceDocumentType}update(t){return Object.keys(t).forEach(e=>{Ei.includes(e)&&(this[e]=t[e])}),super.update(t)}}function Di(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Ti(s){return s&&typeof s.toString=="function"?s.toString():s}const Fi=["name","receivableBillingAccountCode"];class de extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const e=t._id||t.id;this.id=Li(e),this._type=t._type||"BillingProject",this.billingProjectCode=t.billingProjectCode,this.name=t.name,this.receivableBillingAccountCode=t.receivableBillingAccountCode}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"BillingProject"}static get _superclass(){return"BillingProject"}update(t){return Object.keys(t).forEach(e=>{Fi.includes(e)&&(this[e]=t[e])}),super.update(t)}}function Li(s){return s&&typeof s.toString=="function"?s.toString():s}const Mi=["codes","description","max","min","name","priority","productCodes"];class he extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Product:e}=t._constructor||{};this._Product=e&&e._superclass===R._superclass?e:R,this._products=t._products,this._type=t._type||"Category";const i=t._id||t.id;this.id=Bi(i),this.categoryCode=xi(t,"categoryCode"),this.codes=t.codes||[],this.description=t.description,this.max=t.max||1,this.min=t.min||0,this.name=t.name,this.priority=t.priority||10,this.productCodes=t.productCodes||[]}static dummyData(){return{name:"category",tenantCode:"tenantCode"}}static get _classname(){return"Category"}static get _superclass(){return"Category"}get isValid(){return super.isValid&&!!this.name&&this.max>this.min}get products(){return this._Product.initOnlyValidFromArray(this._products)}update(t){return Object.keys(t).forEach(e=>{Mi.includes(e)&&(this[e]=t[e])}),super.update(t)}}function xi(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Bi(s){return s&&typeof s.toString=="function"?s.toString():s}const $i=["amount","description","qty"];class at extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._creditNote=t._creditNote,this._type=t._type||"CreditNoteLine";const i=t._id||t.id;this.id=qi(i),this.amount=this._Amount.init(t.amount),this.creditNoteCode=t.creditNoteCode,this.creditNoteLineCode=ji(t,"creditNoteLineCode"),this.description=t.description,this.handlingCharge=this._Amount.init(t.handlingCharge),this.qty=t.qty||1}static dummyData(){return{creditNoteCode:"creditNoteCode",tenantCode:"tenantCode"}}static get _classname(){return"CreditNoteLine"}static get _superclass(){return"CreditNoteLine"}get isValid(){return super.isValid&&!!this.creditNoteCode}setAmount(t){const e=this._Amount.init(t);return e&&(this.amount=e),this}update(t){return Object.keys(t).forEach(e=>{$i.includes(e)&&(e==="amount"||e==="unitPrice"||e==="deduction"?this[e]=this._Amount.init(t[e]):e==="purchaseOptions"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):this[e]=t[e])}),super.update(t)}}function ji(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function qi(s){return s&&typeof s.toString=="function"?s.toString():s}const Ni=["description","status"];class ut extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Amount:e,_CreditNoteLine:i,_Status:r}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._CreditNoteLine=i&&i._superclass===at._superclass?i:at,this._Status=r&&r._superclass===O._superclass?r:O,this._type=t._type||"CreditNote";const n=t._id||t.id;this.id=Gi(n),this.amount=this._Amount.init(t.amount),this.creditNoteCode=Ui(t,"creditNoteCode"),this.creditNoteLines=this._CreditNoteLine.initOnlyValidFromArray(t.creditNoteLines),this.description=t.description,this.invoiceCode=t.invoiceCode,this.handlingCharge=this._Amount.init(t.handlingCharge),this.status=this._Status.init(t.status)}static dummyData(){return{invoiceCode:"invoiceCode",tenantCode:"tenantCode"}}static get _classname(){return"CreditNote"}static get _superclass(){return"CreditNote"}get isActive(){return!!this.active}get isPending(){return this.status.isPending}get isValid(){return super.isValid&&!!this.invoiceCode}get displayCreated(){return l.formatDate(this.meta.created,"YYYY/MM/DD hh:mm")}get displayRefundedDate(){return l.formatDate(this.meta.created,"YYYY/MM/DD hh:mm")}get refundedDetail(){return l.KeyValueObject.foundValueByKey(this.metadata,"REFUNDED_DETAIL")||{}}getCode(){return this.creditNoteCode}setAmount(t){const e=this_Amount.init(t);return this.isPending&&e&&(this.amount=e),this}setCompleted(){return this.status.setCompleted(),this.setModified()}setPaid(t){return this.status.setPaid(t),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Ni.includes(e)&&(e==="amount"?this[e]=this._Amount.init(t[e]):e==="status"?this[e]=this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function Ui(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Gi(s){return s&&typeof s.toString=="function"?s.toString():s}class me extends l.Repo{constructor(t={}){t=t||{},super(t);const{_CreditNote:e}=t._constructor||{};this._CreditNote=e&&e._superclass===ut._superclass?e:ut}static get _classname(){return"CreditNoteRepo"}init(t){return this._CreditNote.init(t)}}const Ki=["description","name","symbol"];class ge extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const e=t._id||t.id;this.id=Wi(e),this._type=t._type||"Currency",this.code=t.code,this.currencyCode=Hi(t,"currencyCode"),this.description=t.description,this.factor=t.factor||1,this.name=t.name,this.symbol=t.symbol||null,this.unit=t.unit}static dummyData(){return{code:"USD",factor:100,name:"US dollar",tenantCode:"platform",unit:"Cent"}}static get _classname(){return"Currency"}static get _superclass(){return"Currency"}get isValid(){return super.isValid&&!!this.code&&typeof this.factor=="number"&&!!this.name&&!!this.unit}fromCurrencyValue(t){return t/this.factor}getCode(){return this.currencyCode}update(t){return Object.keys(t).forEach(e=>{Ki.includes(e)&&(this[e]=t[e])}),super.update(t)}}function Hi(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Wi(s){return s&&typeof s.toString=="function"?s.toString():s}const Qi=["amount","deduction","discount","note","unitPrice","status","waived","qty"];class ct extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_Merchandise:i,_Order:r,_OrderService:n,_Status:a}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._Merchandise=i&&i._superclass===I._superclass?i:I,this._Order=r&&r._superclass===ot._superclass?r:ot,this._Status=a&&a._superclass===it._superclass?a:it,this._merchandise=t._merchandise,this._order=t._order;const u=t._id||t.id;this.id=Yi(u),this._type=t._type||"OrderLine",this.amount=this._Amount.init(t.amount),this.deduction=this._Amount.init(t.deduction),this.discount=t.discount||0,this.note=t.note,this.unitPrice=this._Amount.init(t.unitPrice),this.status=this._Status.init(t.status),this.orderCode=t.orderCode,this.orderLineCode=t.orderLineCode,this.orderLineType="OrderLine",this.merchandiseCode=t.merchandiseCode,this.waived=t.waived||0,this.qty=t.qty||1}static dummyData(){return{amount:m.dummyData(),orderCode:"orderCode",tenantCode:"tenantCode"}}static get _classname(){return"OrderLine"}static get _superclass(){return"OrderLine"}get currentStatus(){return this.isClosed?"closed":this.isBillable?"billable":this.isCancelled?"cancelled":this.isInvalid?"invalid":this.isExpired?"expired":"open"}get isActive(){return!this.isClosed&&!this.isCancelled&&!this.isExpired&&!this.isInvalid}get isBillable(){return this.isFulfilled&&!this.isClosed&&!this.isCancelled}get isOpen(){return!this.isClosed&&!this.isCancelled&&!this.isExpired&&!this.isInvalid&&!this.isFulfilled}get isClosed(){return!!this.status.isClosed||!!this.status.isPosted}get isCancelled(){return this.status.isCancelled}get isExpired(){return!this.isClosed&&!this.isCancelled&&this.status.isExpired}get isFulfilled(){return this.status.isFulfilled}get isInvalid(){return!this.isClosed&&!this.isCancelled&&this.status.isInvalid}get isValid(){return super.isValid&&!!this.merchandiseCode}get order(){return this._Order.init(this._order)}get merchandise(){return this._Merchandise.init(this._merchandise)}allowCancel(){return this.status.allowCancel()}createInvoiceLine(){return{invoiceLineType:"InvoiceLine",amount:this.amount,unitPrice:this.unitPrice,deduction:this.deduction,discount:this.discount,outstanding:this.amount,qty:this.qty,merchandiseCode:this.merchandiseCode,metadata:this.metadata,note:this.note,purchaseOptions:this.purchaseOptions,remarks:this.remarks,waived:this.waived,owner:this.owner,tenantCode:this.tenantCode}}getAmount(){return this.amount}getPreservedData(){return{created:this.created,orderCode:this.orderCode,orderLineCode:this.orderLineCode,orderLineType:this.orderLineType}}toCaculateAmountItem(){return{merchandiseCode:this.merchandiseCode,qty:this.qty,price:this.unitPrice,discount:this.discount,subTotal:this.amount,priceStrategy:null,purchaseOptions:this.purchaseOptions||[],remarks:this.remarks,waived:this.waived}}getCurrencyCode(){return this.amount?this.amount.getCurrencyCode():null}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setClosed(t,e){return this.status.setClosed(t,e),this.setModified()}setCompleted(t,e){return this.status.setCompleted(t,e),this.setModified()}setFulfilled(t,e){return this.status.setFulfilled(t,e),this.setModified()}setInvalid(t,e){return this.status.setInvalid(t,e),this.setModified()}setOpen(t,e){return this.status.setOpen(t,e),this.setModified()}setQty(t){return typeof t=="number"&&t>0&&(this.qty=t,this.setModified()),this.qty}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{Qi.includes(e)&&(e==="purchaseOptions"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):e==="amount"||e==="deduction"||e==="unitPrice"?this[e]=this[e]instanceof this._Amount?this[e].update(t[e]):this._Amount.init(t[e]):e==="status"?this[e]=this[e]instanceof this._Status?this[e].update(t[e]):this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}}function Yi(s){return s&&typeof s.toString=="function"?s.toString():s}const ki=["amount","status","name"];class ot extends l.TenantAwareEntity{constructor(t){t=t||{},super(t);const{_Amount:e,_OrderLine:i,_Status:r}=t._constructor||{};this._Amount=e&&e._superclass===m._superclass?e:m,this._OrderLine=i&&i._superclass===ct._superclass?i:ct,this._Status=r&&r._superclass===st._superclass?r:st,this._orderLines=t._orderLines;const n=t._id||t.id;this.id=zi(n),this._type=t._type||"Order",this.amount=this._Amount.init(t.amount),this.orderCode=t.orderCode,this.orderType="Order",this.status=this._Status.init(t.status),this.name=t.name}static dummyData(){return{tenantCode:"tenantCode"}}static get _classname(){return"Order"}static get _superclass(){return"Order"}get isCompleted(){return this.status.isCompleted}get isClosed(){return this.status.isClosed}get isExpired(){return this.status.isExpired}get isInvalid(){return this.status.isInvalid}get isOpen(){return this.status.isOpen}get isTerminated(){return this.status.isTerminated}get orderLines(){return this._OrderLine.initOnlyValidFromArray(this._orderLines||[])}getAmount(){return this.amount}getCurrencyCode(){return this.amount?this.amount.getCurrencyCode():null}getFullOrderNumber(t="."){return`${this.orderNumber}${t}${this.revisionNumber}`}increaseRevisionNumber(){return this.revisionNumber+=1,this}setCancelled(t,e){return this.status.setCancelled(t,e),this.setModified()}setClosed(t,e){return this.status.setClosed(t,e),this.setModified()}setExpired(t,e){return this.status.setExpired(t,e),this.setModified()}setInvalid(t,e){return this.status.setInvalid(t,e),this.setModified()}setOpen(t,e){return this.status.setOpen(t,e),this.setModified()}setTerminated(t,e){return this.status.setTerminated(t,e),this.setModified()}update(t){return Object.keys(t).forEach(e=>{ki.includes(e)&&(e==="amount"?this[e]=this.amount instanceof this._Amount?this.amount.update(t[e]):this._Amount.init(t[e]):e==="status"?this[e]=this.status instanceof this._Status?this.status.update(t[e]):this._Status.init(t[e]):this[e]=t[e])}),super.update(t)}updateAmount(){const t=this.orderLines;if(t.length===0)return this;const e=t.reduce((i,r)=>{var n;return i+((n=r==null?void 0:r.amount)==null?void 0:n.value)||0},0);return this.update({amount:{value:e}})}}function zi(s){return s&&typeof s.toString=="function"?s.toString():s}const Ji=["active","deleted","remarks","result"];class pe extends l.TenantAwareEntity{constructor(t={}){t=t||{},super(t);const{_Transaction:e}=t._constructor||{};this._Transaction=e&&e._superclass===k._superclass?e:k,this._transaction=t._transaction,this._type=t._type||"PaymentResult";const i=t._id||t.id;this.id=Zi(i),this.paymentResultCode=Xi(t,"paymentResultCode"),this.paymentResultType=t.paymentResultType||"PaymentResult",this.result=t.result,this.resultRef=t.resultRef,this.resultType=t.resultType,this.transactionCode=t.transactionCode}static dummyData(){return{paymentResultType:"PaymentResult",result:{id:"resultId"},resultType:"resultType",tenantCode:"tenantCode",transactionCode:"transactionCode"}}static get _classname(){return"PaymentResult"}static get _superclass(){return"PaymentResult"}get isValid(){return super.isValid&&!!this.resultType&&!!this.transactionCode}get amount(){throw new Error(`${this._classname} subclass should implement get amount`)}get billedAmount(){throw new Error(`${this._classname} subclass should implement get billedAmount`)}get paymentMethod(){throw new Error(`${this._classname} subclass should implement get paymentMethod`)}get receivedAmount(){throw new Error(`${this._classname} subclass should implement get receivedAmount`)}get resultStatus(){throw new Error(`${this._classname} subclass should implement get resultStatus`)}get transaction(){return this._Transaction.init(this._transaction)}addMetadata(t,e){return this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,t,e),this}addRemark(t,e){return this.remarks=l.KeyValueObject.insertOrUpdateRecord(this.remarks,t,e),this}compareStatus(t){throw new Error(`${this.paymentResultType} subclass should implement compareStatus`)}getCode(){return this.paymentResultCode}getPaidAmount(){throw new Error(`${this.paymentResultType} subclass should implement getPaidAmount`)}getPaidTimestamp(){throw new Error(`${this.paymentResultType} subclass should implement getPaidTimestamp in milliseconds`)}getPaymentCode(){throw new Error(`${this.paymentResultType} subclass should implement getPaymentCode`)}getTransactionStatus(){throw new Error(`${this.paymentResultType} subclass should implement getTransactionStatus`)}handlePayment(t){if(!this.isForThisPayment(t))return{payment:t,err:new Error("the payment result is not for this payment")};if(!this.isSameAmount(t))return{payment:t,err:new Error("the amount was not matched")};try{return t.settled(),t.setPaidAmount(this.getPaidAmount()).setPaidTimestamp(this.getPaidTimestamp()).setPaymentResultCode(this.paymentResultCode),{payment:t,err:null}}catch(e){return{payment:t,err:e}}}isForThisPayment(t){return this.getPaymentCode()===t.paymentCode}isSameAmount(t){return this.getPaidAmount()===t.getAmount()}isSuccess(){throw new Error(`${this.paymentResultType} subclass should implement isSuccess`)}setupMetadata(){const t=this.amount,e=this.paymentMethod;return this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,"AMOUNT",t),this.metadata=l.Metadata.insertOrUpdateRecord(this.metadata,"PAYMENT_METHOD",e),this.remarks=l.KeyValueObject.insertOrUpdateRecord(this.remarks,"amount",t),this.remarks=l.KeyValueObject.insertOrUpdateRecord(this.remarks,"paymentMethod",e),this}setupRemarks(){return this.setupMetadata()}update(t){return Object.keys(t).forEach(e=>{Ji.includes(e)&&(this[e]=t[e])}),super.update(t)}}function Xi(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function Zi(s){return s&&typeof s.toString=="function"?s.toString():s}const tr=["active","deleted","description","intangible","limitPercentage","lineOptions","maxPerWallet","name","originalStock","owner","productOptions","remarks","requiredStoreItemCode","stock"];class fe{constructor(t={}){t=t||{};const{_ItemOption:e}=t._constructor||{};this._ItemOption=e&&e._superclass===E?e:E;const i=t._id||t.id;this.id=er(i),this._type=t._type||"StoreItem",this.active=typeof t.active<"u"?!!t.active:!0,this.created=t.created||new Date().valueOf(),this.creator=t.creator,this.deleted=t.deleted||!1,this.description=t.description||"",this.intangible=t.intangible||!1,this.limitPercentage=t.limitPercentage||100,this.lineOptions=this._ItemOption.initOnlyValidFromArray(t.lineOptions),this.maxPerWallet=t.maxPerWallet||1,this.metadata=l.Metadata.initOnlyValidFromArray(t.metadata),this.modified=t.modified||new Date().valueOf(),this.name=t.name||"",this.originalStock=t.originalStock||0,this.owner=t.owner,this.productCode=sr(t,"productCode"),this.productOptions=this._ItemOption.initOnlyValidFromArray(t.productOptions),this.requiredStoreItemCode=t.requiredStoreItemCode,this.remarks=l.KeyValueObject.initOnlyValidFromArray(t.remarks),this.stock=t.stock||0,this.storeItemType=t.storeItemType||"StoreItem",this.tenantCode=t.tenantCode}static dummyData(){return{name:"badge",tenantCode:"tenantCode"}}static init(t={}){if(t instanceof this)return t;const e=new this(t);return e.isValid?e:null}static initFromArray(t=[]){return Array.isArray(t)?t.map(e=>this.init(e)):[]}static initOnlyValidFromArray(t=[]){return this.initFromArray(t).filter(e=>e)}static get _classname(){return"StoreItem"}static get _superclass(){return"StoreItem"}get isValid(){return!!this.tenantCode&&!!this.name}get isReachedLimitPercentage(){return this.soldPercentage>=this.limitPercentage}get soldPercentage(){return(this.originalStock-this.stock)/this.originalStock*100}get summary(){return{product:this,productCode:this.productCode,name:this.name}}ableToHave(t){return this.maxPerWallet>=t}checkStoreItemItemOptions(t=[]){return W.getItemOptionFillInsByTarget({itemOptionFillIns:t,target:"StoreItem",targetCode:this.productCode}).reduce((i,r)=>{const n=r.getKey(),a=this.getStoreItemOptionByKey(n);return a?(a.isValidFillInValue(r.getValue())||i.errMsgs.push(`the product(${this.productCode}) option's(${n}) fillInValue is invalid`),i):(i.errMsgs.push(`options of the product(${this.productCode}) does not contain key: "${n}"`),i)},{errMsgs:[]})}getCode(){return this.productCode}getMetadataValueByKey(t){return l.Metadata.getValueByKey(this.metadata||[],t)}getStoreItemOptionByKey(t){const e=this._ItemOption.getByKey(this.productOptions,t);return e.length===1?e[0]:null}hasStock(t){return this.stock>=t}isQualified(t){const e=this.getMetadataValueByKey("RULES")||[];return e.length===0?!0:e.reduce((i,r)=>i||l.getValidation(r,t,ir,l.KeyValueObject),!1)}isTicket(){return!1}setModified(){return this.modified=new Date().valueOf(),this}update(t){return Object.keys(t).forEach(e=>{tr.includes(e)&&(e==="metadata"?this[e]=l.Metadata.initOnlyValidFromArray(t[e]):e==="productOptions"?this[e]=this._ItemOption.initOnlyValidFromArray(t[e]):e==="remarks"?this[e]=l.KeyValueObject.initOnlyValidFromArray(t[e]):this[e]=t[e])}),this.setModified()}}function er(s){return s&&typeof s.toString=="function"?s.toString():s}function sr(s,t){const e=s||{};return e[t]?e[t]:A.setCode()}function ir(s,t){return l.getValueByKeys(s.split("."),t)}const rr=Object.freeze(Object.defineProperty({__proto__:null,AccountAllocation:j,AccountAllocationGroup:Z,Amount:m,BillingAccount:oe,BillingLedgerEntry:le,BillingProject:de,Cart:et,CartItem:J,Category:he,CreditNote:ut,CreditNoteLine:at,CreditNoteRepo:me,Currency:ge,Invoice:U,InvoiceLine:Y,ItemOption:E,ItemOptionLocale:X,KeyValueObject:l.KeyValueObject,Merchandise:I,MerchandiseBilling:Xt,Order:ot,OrderLine:ct,PaymentCharge:rt,PaymentGateway:D,PaymentGatewayBilling:ee,PaymentItem:Q,PaymentResult:pe,Price:S,PriceStrategy:z,Product:R,ProductBilling:Jt,Receipt:F,ReceiptLine:T,RefundAccountAllocation:q,RefundAccountAllocationGroup:tt,Status:O,StatusQStore:V,StatusQStoreInvoice:se,StatusQStoreInvoiceLine:ie,StatusQStoreOrder:st,StatusQStoreOrderLine:it,StoreItem:fe,Transaction:k,WalletItem:nt},Symbol.toStringTag,{value:"Module"})),nr={...rs,...Si,...rr};Object.defineProperty(exports,"KeyValueObject",{enumerable:!0,get:()=>l.KeyValueObject});exports.AccountAllocation=j;exports.AccountAllocationGroup=Z;exports.Amount=m;exports.BillingAccount=oe;exports.BillingLedgerEntry=le;exports.BillingProject=de;exports.Cart=et;exports.CartItem=J;exports.Category=he;exports.Chain=w;exports.ChainManager=ft;exports.ChainManagerFactory=At;exports.ChainTarget=yt;exports.ComplimentaryItemManager=Ut;exports.CouponManager=Gt;exports.CreditNote=ut;exports.CreditNoteLine=at;exports.CreditNoteRepo=me;exports.Currency=ge;exports.Invoice=U;exports.InvoiceLine=Y;exports.ItemOption=E;exports.ItemOptionLocale=X;exports.Merchandise=I;exports.MerchandiseBilling=Xt;exports.Order=ot;exports.OrderLine=ct;exports.PaymentCharge=rt;exports.PaymentGateway=D;exports.PaymentGatewayBilling=ee;exports.PaymentItem=Q;exports.PaymentResult=pe;exports.Price=S;exports.PriceStrategy=z;exports.Product=R;exports.ProductBilling=Jt;exports.Receipt=F;exports.ReceiptLine=T;exports.RefundAccountAllocation=q;exports.RefundAccountAllocationGroup=tt;exports.Status=O;exports.StatusQStore=V;exports.StatusQStoreInvoice=se;exports.StatusQStoreInvoiceLine=ie;exports.StatusQStoreOrder=st;exports.StatusQStoreOrderLine=it;exports.StoreItem=fe;exports.Transaction=k;exports.WalletItem=nt;exports.adminSettle=$t;exports.calculateAmount=jt;exports.calculateByCoupon=Ct;exports.calculator=G;exports.checkDuplicate=vt;exports.default=nr;exports.defaultComparator=bt;exports.defaultSort=ae;exports.eleInArrayComparator=Kt;exports.firstLetterToLower=Ot;exports.getFakeClass=Nt;exports.getSubClass=qt;exports.handlerOrderList=ne;exports.isAllEqual=ue;exports.isDescendingOrder=ce;exports.makeResponseHelper=Yt;exports.objectAllInArrayComparator=Wt;exports.objectComparator=Ht;exports.objectOrderInArrayComparator=Qt;exports.setQuery=kt;exports.stringHelper=A;
|
|
3
3
|
//# sourceMappingURL=q-store-model.cjs.map
|