b23-lib 1.7.1 → 1.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +2 -0
- package/dist/Auth/index.mjs.map +1 -0
- package/dist/Classes/{Address.d.cts → Address.d.mts} +3 -3
- package/dist/Classes/Address.js +1 -1
- package/dist/Classes/Address.js.map +1 -1
- package/dist/Classes/Address.mjs +2 -0
- package/dist/Classes/Address.mjs.map +1 -0
- package/dist/Classes/{Base.d.cts → Base.d.mts} +2 -2
- package/dist/Classes/Base.js +1 -1
- package/dist/Classes/Base.js.map +1 -1
- package/dist/Classes/Base.mjs +2 -0
- package/dist/Classes/Base.mjs.map +1 -0
- package/dist/Classes/{Cart.d.cts → Cart.d.mts} +8 -8
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +2 -0
- package/dist/Classes/Cart.mjs.map +1 -0
- package/dist/Classes/{Common.d.cts → Common.d.mts} +1 -1
- package/dist/Classes/Common.js +1 -1
- package/dist/Classes/Common.mjs +2 -0
- package/dist/Classes/{Common.cjs.map → Common.mjs.map} +1 -1
- package/dist/Classes/{Coupon.d.cts → Coupon.d.mts} +3 -3
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +2 -0
- package/dist/Classes/Coupon.mjs.map +1 -0
- package/dist/Classes/{Customer.d.cts → Customer.d.mts} +3 -3
- package/dist/Classes/Customer.js +1 -1
- package/dist/Classes/Customer.js.map +1 -1
- package/dist/Classes/Customer.mjs +2 -0
- package/dist/Classes/Customer.mjs.map +1 -0
- package/dist/Classes/{CustomerAddress.d.cts → CustomerAddress.d.mts} +14 -10
- package/dist/Classes/CustomerAddress.d.ts +10 -6
- package/dist/Classes/CustomerAddress.js +1 -1
- package/dist/Classes/CustomerAddress.js.map +1 -1
- package/dist/Classes/CustomerAddress.mjs +2 -0
- package/dist/Classes/CustomerAddress.mjs.map +1 -0
- package/dist/Classes/Enum.js +1 -1
- package/dist/Classes/Enum.js.map +1 -1
- package/dist/Classes/Enum.mjs +2 -0
- package/dist/Classes/Enum.mjs.map +1 -0
- package/dist/Classes/ImageInfo.js +1 -1
- package/dist/Classes/ImageInfo.js.map +1 -1
- package/dist/Classes/ImageInfo.mjs +2 -0
- package/dist/Classes/ImageInfo.mjs.map +1 -0
- package/dist/Classes/{LineItem.d.cts → LineItem.d.mts} +3 -3
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +2 -0
- package/dist/Classes/LineItem.mjs.map +1 -0
- package/dist/Classes/{Order.d.cts → Order.d.mts} +9 -9
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +2 -0
- package/dist/Classes/Order.mjs.map +1 -0
- package/dist/Classes/{Payment.d.cts → Payment.d.mts} +3 -3
- package/dist/Classes/Payment.js +1 -1
- package/dist/Classes/Payment.js.map +1 -1
- package/dist/Classes/Payment.mjs +2 -0
- package/dist/Classes/Payment.mjs.map +1 -0
- package/dist/Classes/{Price.d.cts → Price.d.mts} +2 -2
- package/dist/Classes/Price.js +1 -1
- package/dist/Classes/Price.js.map +1 -1
- package/dist/Classes/Price.mjs +2 -0
- package/dist/Classes/Price.mjs.map +1 -0
- package/dist/Classes/{Product.d.cts → Product.d.mts} +4 -4
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +2 -0
- package/dist/Classes/Product.mjs.map +1 -0
- package/dist/Classes/{ShoppingContainer.d.cts → ShoppingContainer.d.mts} +7 -7
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +2 -0
- package/dist/Classes/ShoppingContainer.mjs.map +1 -0
- package/dist/Dynamodb/index.js +1 -1
- package/dist/Dynamodb/index.js.map +1 -1
- package/dist/Dynamodb/index.mjs +2 -0
- package/dist/Dynamodb/index.mjs.map +1 -0
- package/dist/chunk-4H4LJ3UL.mjs +2 -0
- package/dist/chunk-4H4LJ3UL.mjs.map +1 -0
- package/dist/{chunk-7UEGCYYY.js → chunk-65X54TKF.mjs} +2 -2
- package/dist/chunk-65X54TKF.mjs.map +1 -0
- package/dist/chunk-763MN5XV.mjs +2 -0
- package/dist/chunk-763MN5XV.mjs.map +1 -0
- package/dist/chunk-CWKGR4AF.mjs +2 -0
- package/dist/chunk-CWKGR4AF.mjs.map +1 -0
- package/dist/{chunk-IYDPJQAK.js → chunk-DKI6BDWK.mjs} +2 -2
- package/dist/chunk-DKI6BDWK.mjs.map +1 -0
- package/dist/{chunk-Q2WQECY6.js → chunk-SPLTJRHG.mjs} +2 -2
- package/dist/chunk-SPLTJRHG.mjs.map +1 -0
- package/dist/chunk-T6IVHYQQ.mjs +2 -0
- package/dist/chunk-T6IVHYQQ.mjs.map +1 -0
- package/dist/{chunk-42S4IPCA.js → chunk-T6YCHB3K.mjs} +2 -2
- package/dist/chunk-T6YCHB3K.mjs.map +1 -0
- package/dist/chunk-WU6FFDBS.mjs +2 -0
- package/dist/chunk-WU6FFDBS.mjs.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +1 -2
- package/dist/Auth/index.cjs +0 -2
- package/dist/Auth/index.cjs.map +0 -1
- package/dist/Classes/Address.cjs +0 -2
- package/dist/Classes/Address.cjs.map +0 -1
- package/dist/Classes/Base.cjs +0 -2
- package/dist/Classes/Base.cjs.map +0 -1
- package/dist/Classes/Cart.cjs +0 -2
- package/dist/Classes/Cart.cjs.map +0 -1
- package/dist/Classes/Common.cjs +0 -2
- package/dist/Classes/Coupon.cjs +0 -2
- package/dist/Classes/Coupon.cjs.map +0 -1
- package/dist/Classes/Customer.cjs +0 -2
- package/dist/Classes/Customer.cjs.map +0 -1
- package/dist/Classes/CustomerAddress.cjs +0 -2
- package/dist/Classes/CustomerAddress.cjs.map +0 -1
- package/dist/Classes/Enum.cjs +0 -2
- package/dist/Classes/Enum.cjs.map +0 -1
- package/dist/Classes/ImageInfo.cjs +0 -2
- package/dist/Classes/ImageInfo.cjs.map +0 -1
- package/dist/Classes/LineItem.cjs +0 -2
- package/dist/Classes/LineItem.cjs.map +0 -1
- package/dist/Classes/Order.cjs +0 -2
- package/dist/Classes/Order.cjs.map +0 -1
- package/dist/Classes/Payment.cjs +0 -2
- package/dist/Classes/Payment.cjs.map +0 -1
- package/dist/Classes/Price.cjs +0 -2
- package/dist/Classes/Price.cjs.map +0 -1
- package/dist/Classes/Product.cjs +0 -2
- package/dist/Classes/Product.cjs.map +0 -1
- package/dist/Classes/ShoppingContainer.cjs +0 -2
- package/dist/Classes/ShoppingContainer.cjs.map +0 -1
- package/dist/Dynamodb/index.cjs +0 -2
- package/dist/Dynamodb/index.cjs.map +0 -1
- package/dist/chunk-2ESSIPYR.js +0 -2
- package/dist/chunk-2ESSIPYR.js.map +0 -1
- package/dist/chunk-2IVRLXCO.js +0 -2
- package/dist/chunk-2IVRLXCO.js.map +0 -1
- package/dist/chunk-42S4IPCA.js.map +0 -1
- package/dist/chunk-7UEGCYYY.js.map +0 -1
- package/dist/chunk-IYDPJQAK.js.map +0 -1
- package/dist/chunk-P5BGQ3PJ.js +0 -2
- package/dist/chunk-P5BGQ3PJ.js.map +0 -1
- package/dist/chunk-PD6TDU7F.js +0 -2
- package/dist/chunk-PD6TDU7F.js.map +0 -1
- package/dist/chunk-Q2WQECY6.js.map +0 -1
- package/dist/chunk-XL3K64E6.js +0 -2
- package/dist/chunk-XL3K64E6.js.map +0 -1
- package/dist/index.cjs +0 -3
- package/dist/index.cjs.map +0 -1
- /package/dist/Auth/{index.d.cts → index.d.mts} +0 -0
- /package/dist/Classes/{Enum.d.cts → Enum.d.mts} +0 -0
- /package/dist/Classes/{ImageInfo.d.cts → ImageInfo.d.mts} +0 -0
- /package/dist/Dynamodb/{index.d.cts → index.d.mts} +0 -0
- /package/dist/{index.d.cts → index.d.mts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Payment.ts"],"names":["PaymentStatus","PaymentMode","PaymentModel","BaseModel","data","date"],"mappings":"qCAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,OAAU,CAAA,SAAA,CACVA,EAAA,UAAa,CAAA,YAAA,CACbA,CAAA,CAAA,QAAA,CAAW,WACXA,CAAA,CAAA,MAAA,CAAS,QACTA,CAAAA,CAAAA,CAAA,SAAW,UACXA,CAAAA,CAAAA,CAAA,kBAAqB,CAAA,oBAAA,CANXA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CASAC,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,UAAY,WACZA,CAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CACPA,EAAA,IAAO,CAAA,MAAA,CACPA,CAAA,CAAA,WAAA,CAAc,cACdA,CAAA,CAAA,MAAA,CAAS,QACTA,CAAAA,CAAAA,CAAA,GAAM,CAAA,KAAA,CACNA,CAAA,CAAA,OAAA,CAAU,UAPAA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAyCSC,CAArB,CAAA,cAA0CC,CAAU,CACxC,KAAA,CACA,UACA,CAAA,WAAA,CACA,WACA,MACA,CAAA,SAAA,CACA,MACA,CAAA,QAAA,CACA,WACA,CAAA,eAAA,CACA,gBACA,CAAA,mBAAA,CACA,eACA,SACA,CAAA,SAAA,CACA,aAOV,CAAA,WAAA,CAAYC,EAAyBC,CAAa,CAAA,IAAI,IAAQ,CAAA,CAC5D,MAAMD,CAAMC,CAAAA,CAAI,CAGhB,CAAA,IAAA,CAAK,KAAQD,CAAAA,CAAAA,C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EAAA,CAAE,OAAO,IAAA,CAAK,gBAAkB,CAM1E,sBAAA,EAA6C,CAAE,OAAO,IAAK,CAAA,mBAAqB,CAMhF,iBAAA,EAA4B,CAAE,OAAO,IAAA,CAAK,cAAgB,CAM1D,cAAmC,CAAE,OAAO,IAAK,CAAA,SAAW,CAM5D,YAAmC,EAAA,CAAE,OAAO,IAAA,CAAK,SAAW,CAM5D,gBAAgC,EAAA,CAAE,OAAO,IAAK,CAAA,aAAe,CAOpE,UAAA,EAA0B,CAExB,OAAO,CACL,GAFkB,KAAA,CAAM,YAGxB,CAAA,KAAA,CAAO,IAAK,CAAA,QAAA,EACZ,CAAA,UAAA,CAAY,IAAK,CAAA,aAAA,GACjB,WAAa,CAAA,IAAA,CAAK,cAAe,EAAA,CACjC,WAAY,IAAK,CAAA,aAAA,EACjB,CAAA,MAAA,CAAQ,KAAK,SAAU,EAAA,CACvB,SAAW,CAAA,IAAA,CAAK,YAAa,EAAA,CAC7B,MAAQ,CAAA,IAAA,CAAK,WACb,CAAA,QAAA,CAAU,IAAK,CAAA,WAAA,GACf,WAAa,CAAA,IAAA,CAAK,cAAe,EAAA,CACjC,iBAAkB,IAAK,CAAA,mBAAA,EACvB,CAAA,cAAA,CAAgB,KAAK,iBAAkB,EAAA,CACvC,SAAW,CAAA,IAAA,CAAK,cAChB,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,GAChB,aAAe,CAAA,IAAA,CAAK,gBAAiB,EACvC,CACF,CACF","file":"Payment.js","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport { CurrencyCode, ISODateTime } from \"./Common\";\r\n\r\nexport enum PaymentStatus {\r\n PENDING = \"PENDING\",\r\n AUTHORIZED = \"AUTHORIZED\",\r\n CAPTURED = \"CAPTURED\",\r\n FAILED = \"FAILED\",\r\n REFUNDED = \"REFUNDED\",\r\n PARTIALLY_REFUNDED = \"PARTIALLY_REFUNDED\",\r\n}\r\n\r\nexport enum PaymentMode {\r\n PAY_LATER = \"PAY_LATER\",\r\n CARD = \"CARD\",\r\n CASH = \"CASH\",\r\n NET_BANKING = \"NET_BANKING\",\r\n WALLET = \"WALLET\",\r\n COD = \"COD\",\r\n UNKNOWN = \"UNKNOWN\",\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a PaymentModel.\r\n */\r\nexport type PaymentAttributes = BaseAttributes & {\r\n txnId: string;\r\n externalId?: string;\r\n orderNumber: string;\r\n customerId: string;\r\n status: PaymentStatus;\r\n subStatus?: string;\r\n amount: number;\r\n currency: CurrencyCode;\r\n paymentMode: PaymentMode;\r\n gatewayResponse?: string;\r\n gatewayErrorCode?: string;\r\n gatewayErrorMessage?: string;\r\n amountRefunded?: number;\r\n cardLast4?: string;\r\n cardBrand?: string;\r\n transactionAt: ISODateTime;\r\n};\r\n\r\n/**\r\n * Output data structure for a PaymentModel.\r\n * Excludes potentially large or sensitive fields by default.\r\n */\r\nexport type PaymentData = Omit<PaymentAttributes, 'gatewayResponse' | 'gatewayErrorMessage'> & BaseData\r\n\r\n/**\r\n * Represents a payment transaction, attempt, or record associated with an order.\r\n */\r\nexport default class PaymentModel extends BaseModel {\r\n protected txnId: string;\r\n protected externalId?: string;\r\n protected orderNumber: string;\r\n protected customerId: string;\r\n protected status: PaymentStatus;\r\n protected subStatus?: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n protected paymentMode: PaymentMode;\r\n protected gatewayResponse?: string;\r\n protected gatewayErrorCode?: string;\r\n protected gatewayErrorMessage?: string;\r\n protected amountRefunded: number;\r\n protected cardLast4?: string;\r\n protected cardBrand?: string;\r\n protected transactionAt: ISODateTime;\r\n\r\n /**\r\n * Creates an instance of PaymentModel.\r\n * @param data - The initial payment attributes.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: PaymentAttributes, date: Date = new Date()) {\r\n super(data, date); // Pass BaseAttributes to parent\r\n\r\n // Assign properties\r\n this.txnId = data.txnId;\r\n this.externalId = data.externalId;\r\n this.orderNumber = data.orderNumber;\r\n this.customerId = data.customerId;\r\n this.status = data.status;\r\n this.subStatus = data.subStatus;\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n this.paymentMode = data.paymentMode;\r\n this.gatewayResponse = data.gatewayResponse;\r\n this.gatewayErrorCode = data.gatewayErrorCode;\r\n this.gatewayErrorMessage = data.gatewayErrorMessage;\r\n this.amountRefunded = data.amountRefunded || 0; // Default to 0 if undefined\r\n this.cardLast4 = data.cardLast4;\r\n this.cardBrand = data.cardBrand;\r\n this.transactionAt = data.transactionAt;\r\n }\r\n\r\n /**\r\n * Gets the primary transaction identifier.\r\n * @returns The transaction ID string.\r\n */\r\n public getTxnId(): string { return this.txnId; }\r\n\r\n /**\r\n * Gets the external identifier, often from a payment gateway.\r\n * @returns The external ID string, or undefined if not set.\r\n */\r\n public getExternalId(): string | undefined { return this.externalId; }\r\n\r\n /**\r\n * Gets the order number associated with this payment.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string { return this.orderNumber; }\r\n\r\n /**\r\n * Gets the customer ID associated with this payment.\r\n * @returns The customer ID string.\r\n */\r\n public getCustomerId(): string { return this.customerId; }\r\n\r\n /**\r\n * Gets the current status of the payment (e.g., PENDING, CAPTURED).\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getStatus(): PaymentStatus { return this.status; }\r\n\r\n /**\r\n * Gets the detailed sub-status, often provided by the payment gateway.\r\n * @returns The sub-status string, or undefined if not set.\r\n */\r\n public getSubStatus(): string | undefined { return this.subStatus; }\r\n\r\n /**\r\n * Gets the amount of the payment transaction.\r\n * @returns The payment amount number.\r\n */\r\n public getAmount(): number { return this.amount; }\r\n\r\n /**\r\n * Gets the currency code for the payment amount.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode { return this.currency; }\r\n\r\n /**\r\n * Gets the mode or method used for the payment (e.g., CARD, COD).\r\n * @returns The PaymentMode enum value.\r\n */\r\n public getPaymentMode(): PaymentMode { return this.paymentMode; }\r\n\r\n /**\r\n * Gets the raw response data from the payment gateway (potentially large).\r\n * @returns The gateway response string, or undefined if not set.\r\n */\r\n public getGatewayResponse(): string | undefined { return this.gatewayResponse; }\r\n\r\n /**\r\n * Gets the error code returned by the payment gateway, if any.\r\n * @returns The gateway error code string, or undefined if no error occurred or wasn't recorded.\r\n */\r\n public getGatewayErrorCode(): string | undefined { return this.gatewayErrorCode; }\r\n\r\n /**\r\n * Gets the error message returned by the payment gateway, if any.\r\n * @returns The gateway error message string, or undefined if no error occurred or wasn't recorded.\r\n */\r\n public getGatewayErrorMessage(): string | undefined { return this.gatewayErrorMessage; }\r\n\r\n /**\r\n * Gets the total amount that has been refunded for this transaction.\r\n * @returns The refunded amount number (defaults to 0).\r\n */\r\n public getAmountRefunded(): number { return this.amountRefunded; }\r\n\r\n /**\r\n * Gets the last 4 digits of the card used, if applicable.\r\n * @returns The card's last 4 digits string, or undefined.\r\n */\r\n public getCardLast4(): string | undefined { return this.cardLast4; }\r\n\r\n /**\r\n * Gets the brand of the card used (e.g., Visa, Mastercard), if applicable.\r\n * @returns The card brand string, or undefined.\r\n */\r\n public getCardBrand(): string | undefined { return this.cardBrand; }\r\n\r\n /**\r\n * Gets the timestamp when the transaction occurred or was recorded.\r\n * @returns The transaction timestamp as an ISO 8601 string.\r\n */\r\n public getTransactionAt(): ISODateTime { return this.transactionAt; }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the payment's current state.\r\n * @returns PaymentData object suitable for serialization or API responses.\r\n */\r\n getDetails(): PaymentData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n ...baseDetails,\r\n txnId: this.getTxnId(),\r\n externalId: this.getExternalId(),\r\n orderNumber: this.getOrderNumber(),\r\n customerId: this.getCustomerId(),\r\n status: this.getStatus(),\r\n subStatus: this.getSubStatus(),\r\n amount: this.getAmount(),\r\n currency: this.getCurrency(),\r\n paymentMode: this.getPaymentMode(),\r\n gatewayErrorCode: this.getGatewayErrorCode(),\r\n amountRefunded: this.getAmountRefunded(),\r\n cardLast4: this.getCardLast4(),\r\n cardBrand: this.getCardBrand(),\r\n transactionAt: this.getTransactionAt(),\r\n };\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/Payment.ts"],"names":["BaseModel","data","date","modifiedBy","fieldName","value","PaymentStatus","PaymentMode","PaymentModel"],"mappings":"sEA0BA,IAAqBA,CAAAA,CAArB,KAA+B,CACnB,YACA,CAAA,OAAA,CACA,SACA,CAAA,UAAA,CACA,UAQV,CAAA,WAAA,CAAYC,CAAsBC,CAAAA,CAAAA,CAAa,IAAI,IAAA,CAAQ,CACzD,IAAK,CAAA,YAAA,CAAe,CAAE,GAAGD,CAAK,CAAA,YAAa,CAC3C,CAAA,IAAA,CAAK,OAAUA,CAAAA,CAAAA,CAAK,OAAW,EAAA,CAAA,CAC/B,IAAK,CAAA,SAAA,CAAYA,EAAK,SAAa,EAAA,CAAC,KAAM,CAAA,IAAA,CAAK,KAAMA,CAAAA,CAAAA,CAAK,SAAS,CAAC,CAElE,CAAA,IAAI,IAAKA,CAAAA,CAAAA,CAAK,SAAS,CAAA,CAAE,WAAY,EAAA,CAErCC,CAAK,CAAA,WAAA,EACP,CAAA,IAAA,CAAK,UAAaD,CAAAA,CAAAA,CAAK,UAAc,EAAA,CAAC,KAAM,CAAA,IAAA,CAAK,KAAMA,CAAAA,CAAAA,CAAK,UAAU,CAAC,EACnE,IAAI,IAAA,CAAKA,CAAK,CAAA,UAAU,CAAE,CAAA,WAAA,EAC1BC,CAAAA,CAAAA,CAAK,WAAY,EAAA,CAErB,IAAK,CAAA,UAAA,CAAaD,CAAK,CAAA,UAAA,EAAc,GACvC,CAMA,UAAuB,EAAA,CACrB,OAAO,CACL,YAAc,CAAA,IAAA,CAAK,kBAAmB,EAAA,CACtC,OAAS,CAAA,IAAA,CAAK,UAAW,EAAA,CACzB,SAAW,CAAA,IAAA,CAAK,cAChB,CAAA,UAAA,CAAY,IAAK,CAAA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A,IAAA,CAAK,YAAa,EAAA,CAC7B,MAAQ,CAAA,IAAA,CAAK,SAAU,EAAA,CACvB,SAAU,IAAK,CAAA,WAAA,EACf,CAAA,WAAA,CAAa,IAAK,CAAA,cAAA,EAClB,CAAA,gBAAA,CAAkB,IAAK,CAAA,mBAAA,EACvB,CAAA,cAAA,CAAgB,IAAK,CAAA,iBAAA,EACrB,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,EAChB,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,EAChB,CAAA,aAAA,CAAe,IAAK,CAAA,gBAAA,EACtB,CACF,CACF","file":"Payment.js","sourcesContent":["import { ISODateTime } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTime;\r\n modifiedAt?: ISODateTime;\r\n modifiedBy?: string;\r\n};\r\n\r\nexport type BaseData = {\r\n customFields: CustomFields;\r\n version: number;\r\n createdAt: ISODateTime;\r\n modifiedAt: ISODateTime;\r\n modifiedBy: string;\r\n};\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTime;\r\n protected modifiedAt: ISODateTime;\r\n protected modifiedBy: string;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = data.modifiedBy ?? '';\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns The modifier identifier string.\r\n */\r\n getModifiedBy(): string {\r\n return this.modifiedBy;\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(modifiedBy: string): void {\r\n this.modifiedBy = modifiedBy;\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n","import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport { CurrencyCode, ISODateTime } from \"./Common\";\r\n\r\nexport enum PaymentStatus {\r\n PENDING = \"PENDING\",\r\n AUTHORIZED = \"AUTHORIZED\",\r\n CAPTURED = \"CAPTURED\",\r\n FAILED = \"FAILED\",\r\n REFUNDED = \"REFUNDED\",\r\n PARTIALLY_REFUNDED = \"PARTIALLY_REFUNDED\",\r\n}\r\n\r\nexport enum PaymentMode {\r\n PAY_LATER = \"PAY_LATER\",\r\n CARD = \"CARD\",\r\n CASH = \"CASH\",\r\n NET_BANKING = \"NET_BANKING\",\r\n WALLET = \"WALLET\",\r\n COD = \"COD\",\r\n UNKNOWN = \"UNKNOWN\",\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a PaymentModel.\r\n */\r\nexport type PaymentAttributes = BaseAttributes & {\r\n txnId: string;\r\n externalId?: string;\r\n orderNumber: string;\r\n customerId: string;\r\n status: PaymentStatus;\r\n subStatus?: string;\r\n amount: number;\r\n currency: CurrencyCode;\r\n paymentMode: PaymentMode;\r\n gatewayResponse?: string;\r\n gatewayErrorCode?: string;\r\n gatewayErrorMessage?: string;\r\n amountRefunded?: number;\r\n cardLast4?: string;\r\n cardBrand?: string;\r\n transactionAt: ISODateTime;\r\n};\r\n\r\n/**\r\n * Output data structure for a PaymentModel.\r\n * Excludes potentially large or sensitive fields by default.\r\n */\r\nexport type PaymentData = Omit<PaymentAttributes, 'gatewayResponse' | 'gatewayErrorMessage'> & BaseData\r\n\r\n/**\r\n * Represents a payment transaction, attempt, or record associated with an order.\r\n */\r\nexport default class PaymentModel extends BaseModel {\r\n protected txnId: string;\r\n protected externalId?: string;\r\n protected orderNumber: string;\r\n protected customerId: string;\r\n protected status: PaymentStatus;\r\n protected subStatus?: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n protected paymentMode: PaymentMode;\r\n protected gatewayResponse?: string;\r\n protected gatewayErrorCode?: string;\r\n protected gatewayErrorMessage?: string;\r\n protected amountRefunded: number;\r\n protected cardLast4?: string;\r\n protected cardBrand?: string;\r\n protected transactionAt: ISODateTime;\r\n\r\n /**\r\n * Creates an instance of PaymentModel.\r\n * @param data - The initial payment attributes.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: PaymentAttributes, date: Date = new Date()) {\r\n super(data, date); // Pass BaseAttributes to parent\r\n\r\n // Assign properties\r\n this.txnId = data.txnId;\r\n this.externalId = data.externalId;\r\n this.orderNumber = data.orderNumber;\r\n this.customerId = data.customerId;\r\n this.status = data.status;\r\n this.subStatus = data.subStatus;\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n this.paymentMode = data.paymentMode;\r\n this.gatewayResponse = data.gatewayResponse;\r\n this.gatewayErrorCode = data.gatewayErrorCode;\r\n this.gatewayErrorMessage = data.gatewayErrorMessage;\r\n this.amountRefunded = data.amountRefunded || 0; // Default to 0 if undefined\r\n this.cardLast4 = data.cardLast4;\r\n this.cardBrand = data.cardBrand;\r\n this.transactionAt = data.transactionAt;\r\n }\r\n\r\n /**\r\n * Gets the primary transaction identifier.\r\n * @returns The transaction ID string.\r\n */\r\n public getTxnId(): string { return this.txnId; }\r\n\r\n /**\r\n * Gets the external identifier, often from a payment gateway.\r\n * @returns The external ID string, or undefined if not set.\r\n */\r\n public getExternalId(): string | undefined { return this.externalId; }\r\n\r\n /**\r\n * Gets the order number associated with this payment.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string { return this.orderNumber; }\r\n\r\n /**\r\n * Gets the customer ID associated with this payment.\r\n * @returns The customer ID string.\r\n */\r\n public getCustomerId(): string { return this.customerId; }\r\n\r\n /**\r\n * Gets the current status of the payment (e.g., PENDING, CAPTURED).\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getStatus(): PaymentStatus { return this.status; }\r\n\r\n /**\r\n * Gets the detailed sub-status, often provided by the payment gateway.\r\n * @returns The sub-status string, or undefined if not set.\r\n */\r\n public getSubStatus(): string | undefined { return this.subStatus; }\r\n\r\n /**\r\n * Gets the amount of the payment transaction.\r\n * @returns The payment amount number.\r\n */\r\n public getAmount(): number { return this.amount; }\r\n\r\n /**\r\n * Gets the currency code for the payment amount.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode { return this.currency; }\r\n\r\n /**\r\n * Gets the mode or method used for the payment (e.g., CARD, COD).\r\n * @returns The PaymentMode enum value.\r\n */\r\n public getPaymentMode(): PaymentMode { return this.paymentMode; }\r\n\r\n /**\r\n * Gets the raw response data from the payment gateway (potentially large).\r\n * @returns The gateway response string, or undefined if not set.\r\n */\r\n public getGatewayResponse(): string | undefined { return this.gatewayResponse; }\r\n\r\n /**\r\n * Gets the error code returned by the payment gateway, if any.\r\n * @returns The gateway error code string, or undefined if no error occurred or wasn't recorded.\r\n */\r\n public getGatewayErrorCode(): string | undefined { return this.gatewayErrorCode; }\r\n\r\n /**\r\n * Gets the error message returned by the payment gateway, if any.\r\n * @returns The gateway error message string, or undefined if no error occurred or wasn't recorded.\r\n */\r\n public getGatewayErrorMessage(): string | undefined { return this.gatewayErrorMessage; }\r\n\r\n /**\r\n * Gets the total amount that has been refunded for this transaction.\r\n * @returns The refunded amount number (defaults to 0).\r\n */\r\n public getAmountRefunded(): number { return this.amountRefunded; }\r\n\r\n /**\r\n * Gets the last 4 digits of the card used, if applicable.\r\n * @returns The card's last 4 digits string, or undefined.\r\n */\r\n public getCardLast4(): string | undefined { return this.cardLast4; }\r\n\r\n /**\r\n * Gets the brand of the card used (e.g., Visa, Mastercard), if applicable.\r\n * @returns The card brand string, or undefined.\r\n */\r\n public getCardBrand(): string | undefined { return this.cardBrand; }\r\n\r\n /**\r\n * Gets the timestamp when the transaction occurred or was recorded.\r\n * @returns The transaction timestamp as an ISO 8601 string.\r\n */\r\n public getTransactionAt(): ISODateTime { return this.transactionAt; }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the payment's current state.\r\n * @returns PaymentData object suitable for serialization or API responses.\r\n */\r\n getDetails(): PaymentData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n ...baseDetails,\r\n txnId: this.getTxnId(),\r\n externalId: this.getExternalId(),\r\n orderNumber: this.getOrderNumber(),\r\n customerId: this.getCustomerId(),\r\n status: this.getStatus(),\r\n subStatus: this.getSubStatus(),\r\n amount: this.getAmount(),\r\n currency: this.getCurrency(),\r\n paymentMode: this.getPaymentMode(),\r\n gatewayErrorCode: this.getGatewayErrorCode(),\r\n amountRefunded: this.getAmountRefunded(),\r\n cardLast4: this.getCardLast4(),\r\n cardBrand: this.getCardBrand(),\r\n transactionAt: this.getTransactionAt(),\r\n };\r\n }\r\n}\r\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'../chunk-SPLTJRHG.mjs';var u=(r=>(r.PENDING="PENDING",r.AUTHORIZED="AUTHORIZED",r.CAPTURED="CAPTURED",r.FAILED="FAILED",r.REFUNDED="REFUNDED",r.PARTIALLY_REFUNDED="PARTIALLY_REFUNDED",r))(u||{}),i=(e=>(e.PAY_LATER="PAY_LATER",e.CARD="CARD",e.CASH="CASH",e.NET_BANKING="NET_BANKING",e.WALLET="WALLET",e.COD="COD",e.UNKNOWN="UNKNOWN",e))(i||{}),s=class extends a{txnId;externalId;orderNumber;customerId;status;subStatus;amount;currency;paymentMode;gatewayResponse;gatewayErrorCode;gatewayErrorMessage;amountRefunded;cardLast4;cardBrand;transactionAt;constructor(t,a=new Date){super(t,a),this.txnId=t.txnId,this.externalId=t.externalId,this.orderNumber=t.orderNumber,this.customerId=t.customerId,this.status=t.status,this.subStatus=t.subStatus,this.amount=t.amount,this.currency=t.currency,this.paymentMode=t.paymentMode,this.gatewayResponse=t.gatewayResponse,this.gatewayErrorCode=t.gatewayErrorCode,this.gatewayErrorMessage=t.gatewayErrorMessage,this.amountRefunded=t.amountRefunded||0,this.cardLast4=t.cardLast4,this.cardBrand=t.cardBrand,this.transactionAt=t.transactionAt;}getTxnId(){return this.txnId}getExternalId(){return this.externalId}getOrderNumber(){return this.orderNumber}getCustomerId(){return this.customerId}getStatus(){return this.status}getSubStatus(){return this.subStatus}getAmount(){return this.amount}getCurrency(){return this.currency}getPaymentMode(){return this.paymentMode}getGatewayResponse(){return this.gatewayResponse}getGatewayErrorCode(){return this.gatewayErrorCode}getGatewayErrorMessage(){return this.gatewayErrorMessage}getAmountRefunded(){return this.amountRefunded}getCardLast4(){return this.cardLast4}getCardBrand(){return this.cardBrand}getTransactionAt(){return this.transactionAt}getDetails(){return {...super.getDetails(),txnId:this.getTxnId(),externalId:this.getExternalId(),orderNumber:this.getOrderNumber(),customerId:this.getCustomerId(),status:this.getStatus(),subStatus:this.getSubStatus(),amount:this.getAmount(),currency:this.getCurrency(),paymentMode:this.getPaymentMode(),gatewayErrorCode:this.getGatewayErrorCode(),amountRefunded:this.getAmountRefunded(),cardLast4:this.getCardLast4(),cardBrand:this.getCardBrand(),transactionAt:this.getTransactionAt()}}};export{i as PaymentMode,u as PaymentStatus,s as default};//# sourceMappingURL=Payment.mjs.map
|
|
2
|
+
//# sourceMappingURL=Payment.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Payment.ts"],"names":["PaymentStatus","PaymentMode","PaymentModel","BaseModel","data","date"],"mappings":"sCAGO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA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L,GAFkB,KAAA,CAAM,YAGxB,CAAA,KAAA,CAAO,IAAK,CAAA,QAAA,EACZ,CAAA,UAAA,CAAY,IAAK,CAAA,aAAA,GACjB,WAAa,CAAA,IAAA,CAAK,cAAe,EAAA,CACjC,WAAY,IAAK,CAAA,aAAA,EACjB,CAAA,MAAA,CAAQ,KAAK,SAAU,EAAA,CACvB,SAAW,CAAA,IAAA,CAAK,YAAa,EAAA,CAC7B,MAAQ,CAAA,IAAA,CAAK,WACb,CAAA,QAAA,CAAU,IAAK,CAAA,WAAA,GACf,WAAa,CAAA,IAAA,CAAK,cAAe,EAAA,CACjC,iBAAkB,IAAK,CAAA,mBAAA,EACvB,CAAA,cAAA,CAAgB,KAAK,iBAAkB,EAAA,CACvC,SAAW,CAAA,IAAA,CAAK,cAChB,CAAA,SAAA,CAAW,IAAK,CAAA,YAAA,GAChB,aAAe,CAAA,IAAA,CAAK,gBAAiB,EACvC,CACF,CACF","file":"Payment.mjs","sourcesContent":["import BaseModel, { BaseAttributes, BaseData } from \"./Base\";\r\nimport { CurrencyCode, ISODateTime } from \"./Common\";\r\n\r\nexport enum PaymentStatus {\r\n PENDING = \"PENDING\",\r\n AUTHORIZED = \"AUTHORIZED\",\r\n CAPTURED = \"CAPTURED\",\r\n FAILED = \"FAILED\",\r\n REFUNDED = \"REFUNDED\",\r\n PARTIALLY_REFUNDED = \"PARTIALLY_REFUNDED\",\r\n}\r\n\r\nexport enum PaymentMode {\r\n PAY_LATER = \"PAY_LATER\",\r\n CARD = \"CARD\",\r\n CASH = \"CASH\",\r\n NET_BANKING = \"NET_BANKING\",\r\n WALLET = \"WALLET\",\r\n COD = \"COD\",\r\n UNKNOWN = \"UNKNOWN\",\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a PaymentModel.\r\n */\r\nexport type PaymentAttributes = BaseAttributes & {\r\n txnId: string;\r\n externalId?: string;\r\n orderNumber: string;\r\n customerId: string;\r\n status: PaymentStatus;\r\n subStatus?: string;\r\n amount: number;\r\n currency: CurrencyCode;\r\n paymentMode: PaymentMode;\r\n gatewayResponse?: string;\r\n gatewayErrorCode?: string;\r\n gatewayErrorMessage?: string;\r\n amountRefunded?: number;\r\n cardLast4?: string;\r\n cardBrand?: string;\r\n transactionAt: ISODateTime;\r\n};\r\n\r\n/**\r\n * Output data structure for a PaymentModel.\r\n * Excludes potentially large or sensitive fields by default.\r\n */\r\nexport type PaymentData = Omit<PaymentAttributes, 'gatewayResponse' | 'gatewayErrorMessage'> & BaseData\r\n\r\n/**\r\n * Represents a payment transaction, attempt, or record associated with an order.\r\n */\r\nexport default class PaymentModel extends BaseModel {\r\n protected txnId: string;\r\n protected externalId?: string;\r\n protected orderNumber: string;\r\n protected customerId: string;\r\n protected status: PaymentStatus;\r\n protected subStatus?: string;\r\n protected amount: number;\r\n protected currency: CurrencyCode;\r\n protected paymentMode: PaymentMode;\r\n protected gatewayResponse?: string;\r\n protected gatewayErrorCode?: string;\r\n protected gatewayErrorMessage?: string;\r\n protected amountRefunded: number;\r\n protected cardLast4?: string;\r\n protected cardBrand?: string;\r\n protected transactionAt: ISODateTime;\r\n\r\n /**\r\n * Creates an instance of PaymentModel.\r\n * @param data - The initial payment attributes.\r\n * @param date - Optional date object for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: PaymentAttributes, date: Date = new Date()) {\r\n super(data, date); // Pass BaseAttributes to parent\r\n\r\n // Assign properties\r\n this.txnId = data.txnId;\r\n this.externalId = data.externalId;\r\n this.orderNumber = data.orderNumber;\r\n this.customerId = data.customerId;\r\n this.status = data.status;\r\n this.subStatus = data.subStatus;\r\n this.amount = data.amount;\r\n this.currency = data.currency;\r\n this.paymentMode = data.paymentMode;\r\n this.gatewayResponse = data.gatewayResponse;\r\n this.gatewayErrorCode = data.gatewayErrorCode;\r\n this.gatewayErrorMessage = data.gatewayErrorMessage;\r\n this.amountRefunded = data.amountRefunded || 0; // Default to 0 if undefined\r\n this.cardLast4 = data.cardLast4;\r\n this.cardBrand = data.cardBrand;\r\n this.transactionAt = data.transactionAt;\r\n }\r\n\r\n /**\r\n * Gets the primary transaction identifier.\r\n * @returns The transaction ID string.\r\n */\r\n public getTxnId(): string { return this.txnId; }\r\n\r\n /**\r\n * Gets the external identifier, often from a payment gateway.\r\n * @returns The external ID string, or undefined if not set.\r\n */\r\n public getExternalId(): string | undefined { return this.externalId; }\r\n\r\n /**\r\n * Gets the order number associated with this payment.\r\n * @returns The order number string.\r\n */\r\n public getOrderNumber(): string { return this.orderNumber; }\r\n\r\n /**\r\n * Gets the customer ID associated with this payment.\r\n * @returns The customer ID string.\r\n */\r\n public getCustomerId(): string { return this.customerId; }\r\n\r\n /**\r\n * Gets the current status of the payment (e.g., PENDING, CAPTURED).\r\n * @returns The PaymentStatus enum value.\r\n */\r\n public getStatus(): PaymentStatus { return this.status; }\r\n\r\n /**\r\n * Gets the detailed sub-status, often provided by the payment gateway.\r\n * @returns The sub-status string, or undefined if not set.\r\n */\r\n public getSubStatus(): string | undefined { return this.subStatus; }\r\n\r\n /**\r\n * Gets the amount of the payment transaction.\r\n * @returns The payment amount number.\r\n */\r\n public getAmount(): number { return this.amount; }\r\n\r\n /**\r\n * Gets the currency code for the payment amount.\r\n * @returns The CurrencyCode enum value.\r\n */\r\n public getCurrency(): CurrencyCode { return this.currency; }\r\n\r\n /**\r\n * Gets the mode or method used for the payment (e.g., CARD, COD).\r\n * @returns The PaymentMode enum value.\r\n */\r\n public getPaymentMode(): PaymentMode { return this.paymentMode; }\r\n\r\n /**\r\n * Gets the raw response data from the payment gateway (potentially large).\r\n * @returns The gateway response string, or undefined if not set.\r\n */\r\n public getGatewayResponse(): string | undefined { return this.gatewayResponse; }\r\n\r\n /**\r\n * Gets the error code returned by the payment gateway, if any.\r\n * @returns The gateway error code string, or undefined if no error occurred or wasn't recorded.\r\n */\r\n public getGatewayErrorCode(): string | undefined { return this.gatewayErrorCode; }\r\n\r\n /**\r\n * Gets the error message returned by the payment gateway, if any.\r\n * @returns The gateway error message string, or undefined if no error occurred or wasn't recorded.\r\n */\r\n public getGatewayErrorMessage(): string | undefined { return this.gatewayErrorMessage; }\r\n\r\n /**\r\n * Gets the total amount that has been refunded for this transaction.\r\n * @returns The refunded amount number (defaults to 0).\r\n */\r\n public getAmountRefunded(): number { return this.amountRefunded; }\r\n\r\n /**\r\n * Gets the last 4 digits of the card used, if applicable.\r\n * @returns The card's last 4 digits string, or undefined.\r\n */\r\n public getCardLast4(): string | undefined { return this.cardLast4; }\r\n\r\n /**\r\n * Gets the brand of the card used (e.g., Visa, Mastercard), if applicable.\r\n * @returns The card brand string, or undefined.\r\n */\r\n public getCardBrand(): string | undefined { return this.cardBrand; }\r\n\r\n /**\r\n * Gets the timestamp when the transaction occurred or was recorded.\r\n * @returns The transaction timestamp as an ISO 8601 string.\r\n */\r\n public getTransactionAt(): ISODateTime { return this.transactionAt; }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the payment's current state.\r\n * @returns PaymentData object suitable for serialization or API responses.\r\n */\r\n getDetails(): PaymentData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n ...baseDetails,\r\n txnId: this.getTxnId(),\r\n externalId: this.getExternalId(),\r\n orderNumber: this.getOrderNumber(),\r\n customerId: this.getCustomerId(),\r\n status: this.getStatus(),\r\n subStatus: this.getSubStatus(),\r\n amount: this.getAmount(),\r\n currency: this.getCurrency(),\r\n paymentMode: this.getPaymentMode(),\r\n gatewayErrorCode: this.getGatewayErrorCode(),\r\n amountRefunded: this.getAmountRefunded(),\r\n cardLast4: this.getCardLast4(),\r\n cardBrand: this.getCardBrand(),\r\n transactionAt: this.getTransactionAt(),\r\n };\r\n }\r\n}\r\n"]}
|
package/dist/Classes/Price.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';var i={IN:"INR"},s={INR:"\u20B9"};var a=class c{price;country;constructor(r,e){if(this.country=e,r<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=r;}getCountry(){return this.country}getRoundedPrice(){return c.getRoundedPrice(this.price,this.country)}getFormattedString(r,e={}){let o=e.displayAsInteger??!1,t=i[this.country];if(t===void 0)throw new Error("Currency mapping not found for CountryCode");let n=this.price,u=o?0:c.getDecimalPlaces(t),d={style:"currency",currency:t,signDisplay:"never",currencyDisplay:e.currencyDisplay,minimumFractionDigits:u,maximumFractionDigits:u};o&&(n=Math.round(n));try{return new Intl.NumberFormat(r,d).format(n)}catch(l){return console.error(`Error formatting price for locale "${r}" and currency "${t}":`,l),`${s[t]??t} ${c.addThousandSeparators(n.toFixed(u))}`}}static getDecimalPlaces(r){switch(r){case"INR":default:return 2}}static addThousandSeparators(r){let e=r.split("."),o=e[0],t=e.length>1?"."+e[1]:"";return o.replace(/\B(?=(\d{3})+(?!\d))/g,",")+t}static getRoundedPrice(r,e){if(r<0)throw new Error("Price cannot be negative for rounding.");let o=i[e];if(o===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let t=c.getDecimalPlaces(o),n=Math.pow(10,t);return Math.round(r*n)/n}static getCurrency(r){return i[r]}};a.getRoundedPrice(-1,"IN");module.exports=a;//# sourceMappingURL=Price.js.map
|
|
2
2
|
//# sourceMappingURL=Price.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"Price.js"}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Enum.ts","../../src/Classes/Price.ts"],"names":["CountryCurrencyMap","CurrencySymbolMap","PriceModel","_PriceModel","price","country","locale","options","displayAsInteger","currency","valueToFormat","fractionDigits","formattingOptions","error","numStr","parts","integerPart","decimalPart","decimalPlaces","multiplier"],"mappings":"aAkBO,IAAMA,CAAqB,CAAA,CAClB,EAAwB,CAAA,KACxC,CAEaC,CAAAA,CAAAA,CAAoB,CAC9B,GAAA,CAAiC,QACpC,CAAA,CCrBqBC,IAAAA,CAAAA,CAArB,MAAqBC,CAAW,CACpB,KAAA,CACA,OAQV,CAAA,WAAA,CAAYC,CAAeC,CAAAA,CAAAA,CAAs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CAAAA,CAAmBK,CAAO,CACnC,CAEF,EAEAH,CAAW,CAAA,eAAA,CAAgB,GAAI,IAAI,CAAA","file":"Price.js","sourcesContent":["/**\r\n * Represents the countries where the application operates or products are available.\r\n */\r\nexport enum OperationalCountry {\r\n /** India */ IN = 'IN',\r\n}\r\n \r\nexport enum OperationalCountryCurrency {\r\n /** India */ INR = 'INR',\r\n}\r\n\r\nexport enum OperationalLocale {\r\n /** India */ 'en-IN' = 'en-IN',\r\n}\r\n\r\n/**\r\n * Defines the supported ISO 4217 currency codes as an enumeration.\r\n */\r\nexport const CountryCurrencyMap = {\r\n /** India */ [OperationalCountry.IN]: OperationalCountryCurrency.INR,\r\n};\r\n\r\nexport const CurrencySymbolMap = {\r\n [OperationalCountryCurrency.INR]: '₹',\r\n}\r\n\r\n/**\r\n * Defines standard gender categories for product targeting.\r\n */\r\nexport enum GenderCategory {\r\n MALE = 'Male',\r\n FEMALE = 'Female',\r\n UNISEX = 'Unisex',\r\n KIDS = 'Kids',\r\n BOY = 'Boy',\r\n GIRL = 'Girl',\r\n}","import { CountryCode, CurrencyCode, LocaleCode } from \"./Common\"; // Assuming these are in Common.ts\r\nimport { CountryCurrencyMap, CurrencySymbolMap } from \"./Enum\"; // Ensure these maps exist\r\n\r\nexport default class PriceModel {\r\n protected price: number;\r\n protected country: CountryCode;\r\n\r\n /**\r\n * Creates an instance of PriceModel, storing the currency-correct rounded price.\r\n * @param price - The initial price value.\r\n * @param country - The country code used for rounding and determining the currency symbol.\r\n * @throws {Error} If price is negative or country/currency mapping is missing.\r\n */\r\n constructor(price: number, country: CountryCode) {\r\n this.country = country;\r\n\r\n if(price < 0) {\r\n throw new Error(\"InvalidPrice: Price cannot be negative.\");\r\n }\r\n\r\n this.price = price\r\n }\r\n\r\n /**\r\n * Gets the country code associated with this price instance.\r\n * The country code is used for determining currency and formatting rules.\r\n * @returns The CountryCode enum value.\r\n */\r\n public getCountry(): CountryCode {\r\n return this.country;\r\n }\r\n\r\n /**\r\n * Gets the rounded price value based on standard currency rules.\r\n * @returns The numeric price, rounded according to its currency's typical decimal places.\r\n */\r\n public getRoundedPrice(): number {\r\n return PriceModel.getRoundedPrice(this.price, this.country);\r\n }\r\n\r\n /**\r\n * Gets a locale-aware formatted display string for the price.\r\n * Uses Intl.NumberFormat for accurate formatting based on locale and currency.\r\n * @param locale - The locale code (e.g., 'en-US', 'de-DE', 'en-IN') to use for formatting rules.\r\n * @param options - Configuration options for formatting.\r\n * @param options.displayAsInteger - If true, the formatted string will show the price rounded to the nearest integer (no decimals). Defaults to false.\r\n * @returns The formatted price string according to locale rules.\r\n */\r\n public getFormattedString(locale: LocaleCode, options: { displayAsInteger?: boolean, currencyDisplay?: 'symbol' | 'narrowSymbol' | 'code' | 'name' } = {}): string {\r\n const displayAsInteger = options.displayAsInteger ?? false;\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[this.country];\r\n\r\n if (currency === undefined) {\r\n throw new Error('Currency mapping not found for CountryCode');\r\n }\r\n\r\n let valueToFormat = this.price;\r\n const fractionDigits = displayAsInteger ? 0 : PriceModel.getDecimalPlaces(currency);\r\n\r\n let formattingOptions: Intl.NumberFormatOptions = {\r\n style: 'currency',\r\n currency: currency,\r\n signDisplay: 'never',\r\n currencyDisplay: options.currencyDisplay,\r\n minimumFractionDigits: fractionDigits,\r\n maximumFractionDigits: fractionDigits,\r\n };\r\n\r\n if (displayAsInteger) {\r\n valueToFormat = Math.round(valueToFormat);\r\n }\r\n\r\n try {\r\n return new Intl.NumberFormat(locale, formattingOptions).format(valueToFormat);\r\n } catch (error) {\r\n console.error(`Error formatting price for locale \"${locale}\" and currency \"${currency}\":`, error);\r\n // Basic fallback without symbol if Intl fails completely\r\n return `${CurrencySymbolMap[currency] ?? currency} ${PriceModel.addThousandSeparators(valueToFormat.toFixed(fractionDigits))}`;\r\n }\r\n }\r\n\r\n /**\r\n * Helper method to determine standard decimal places for a currency.\r\n * @param currency - The currency code.\r\n * @returns The number of decimal places (0, 2, or 3 based on common rules).\r\n */\r\n private static getDecimalPlaces(currency: CurrencyCode): number {\r\n switch (currency) {\r\n case 'INR':\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n /**\r\n * Adds basic thousand separators (commas) to a number string.\r\n * Does not handle different locale separators (e.g., periods, spaces).\r\n * @param numStr - The number string (potentially with decimals).\r\n * @returns The number string with commas added.\r\n */\r\n private static addThousandSeparators(numStr: string): string {\r\n const parts = numStr.split('.');\r\n const integerPart = parts[0];\r\n const decimalPart = parts.length > 1 ? '.' + parts[1] : '';\r\n\r\n const formattedInteger = integerPart.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\r\n return formattedInteger + decimalPart;\r\n }\r\n\r\n /**\r\n * Rounds a price value according to the standard decimal places\r\n * for the currency associated with the given country.\r\n *\r\n * @param price - The price value to round. Must be a non-negative number.\r\n * @param country - The country code to determine the currency and rounding rules.\r\n * @returns The rounded price as a number.\r\n * @throws {Error} If the country code is not found in the CountryCurrencyMap or price is negative.\r\n */\r\n static getRoundedPrice(price: number, country: CountryCode): number {\r\n if (price < 0) {\r\n throw new Error(\"Price cannot be negative for rounding.\");\r\n }\r\n\r\n const currency: CurrencyCode | undefined = CountryCurrencyMap[country];\r\n if (currency === undefined) {\r\n throw new Error(`Currency mapping not found for CountryCode: ${country}`);\r\n }\r\n\r\n const decimalPlaces = PriceModel.getDecimalPlaces(currency);\r\n const multiplier = Math.pow(10, decimalPlaces);\r\n const roundedValue = Math.round(price * multiplier) / multiplier;\r\n\r\n return roundedValue;\r\n }\r\n\r\n /**\r\n * Static method to retrieve the currency code associated with a given country code.\r\n * Uses the `CountryCurrencyMap` to find the corresponding currency.\r\n *\r\n * @param country - The country code (e.g., 'IN') for which to find the currency.\r\n * @returns The currency code (e.g., 'INR') as a string, or undefined if the mapping doesn't exist.\r\n */\r\n static getCurrency(country: CountryCode): string {\r\n return CountryCurrencyMap[country];\r\n }\r\n\r\n}\r\n\r\nPriceModel.getRoundedPrice(-1, 'IN')"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"Price.mjs"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import BaseModel, { BaseAttributes } from './Base.
|
|
2
|
-
import { LocalizedString, BasePriceList, PriceTierList, Color, LocaleCode, CountryCode } from './Common.
|
|
3
|
-
import { GenderCategory } from './Enum.
|
|
4
|
-
import ImageInfoModel, { ImageInfoData } from './ImageInfo.
|
|
1
|
+
import BaseModel, { BaseAttributes } from './Base.mjs';
|
|
2
|
+
import { LocalizedString, BasePriceList, PriceTierList, Color, LocaleCode, CountryCode } from './Common.mjs';
|
|
3
|
+
import { GenderCategory } from './Enum.mjs';
|
|
4
|
+
import ImageInfoModel, { ImageInfoData } from './ImageInfo.mjs';
|
|
5
5
|
|
|
6
6
|
type ProductVariantIdentifier = {
|
|
7
7
|
key: string;
|
package/dist/Classes/Product.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';var n=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){this.customFields={...e.customFields},this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy=e.modifiedBy??"";}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return this.modifiedBy}setModifiedBy(e){this.modifiedBy=e;}getCustomField(e){return this.customFields[e]??null}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return {...this.customFields}}};var r=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw "Cannot remove the 'original' image source.";delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var o=class extends n{id;key;variantId;name;description;slug;brand;basePrices;priceTiers;attributes;primaryImage;additionalImages;isActive;targetGender;categories;specifications;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static variantIdRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.variantId=e.variantId,this.name=e.name,this.description=e.description,this.slug=e.slug,this.brand=e.brand,this.basePrices=e.basePrices.map(i=>({...i})),this.priceTiers=e.priceTiers?e.priceTiers.map(i=>({...i})):e.basePrices.map(i=>({...i})),this.attributes={...e.attributes,sizes:[...e.attributes.sizes]},this.primaryImage=new r(e.primaryImage),this.additionalImages=(e.additionalImages||[]).map(i=>new r(i)),this.isActive=e.isActive,this.targetGender=e.targetGender,this.categories=[...e.categories],this.specifications=JSON.parse(JSON.stringify({...e.specifications})),this.searchTags=e.searchTags?[...e.searchTags]:[];}getId(){return this.id}getKey(){return this.key}getVariantId(){return this.variantId}getName(e){return e?this.name[e]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description.en:{...this.description}}getSlug(e){return e?this.slug[e]??this.slug.en:{...this.slug}}getBrand(){return this.brand}getBasePrices(e){return (e?this.basePrices.filter(i=>i.country===e):this.basePrices).map(i=>({...i}))}getPriceTiers(e){return (e?this.priceTiers.filter(i=>i.country===e):this.priceTiers).map(i=>({...i}))}getAttributes(){return {...this.attributes,color:{...this.attributes.color},sizes:[...this.attributes.sizes]}}getPrimaryImage(){return this.primaryImage}getAdditionalImages(){return this.additionalImages}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return [...this.categories]}getSpecifications(e){return e?this.specifications[e]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getSearchTags(){return [...this.searchTags]}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),variantId:this.getVariantId(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),basePrices:this.getBasePrices(),priceTiers:this.getPriceTiers(),attributes:this.getAttributes(),primaryImage:this.getPrimaryImage().getDetails(),additionalImages:this.getAdditionalImages().map(t=>t.getDetails()),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}getMaxDiscountPercent(e){let t=this.basePrices.find(s=>s.country===e),i=this.priceTiers?.filter(s=>s.country===e).sort((s,d)=>s.unitPrice-d.unitPrice)[0]?.unitPrice;return !t||t.unitPrice<=0||i===void 0?0:Math.max(0,t.unitPrice-i)/t.unitPrice*100}};module.exports=o;//# sourceMappingURL=Product.js.map
|
|
2
2
|
//# sourceMappingURL=Product.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Product.ts"],"names":["ProductModel","BaseModel","data","date","price","tier","ImageInfoModel","image","locale","country","baseDetails","basePrice","lowestTierPrice","a","b"],"mappings":"0EAsDA,IAAqBA,CAArB,CAAA,cAA0CC,CAAU,CACtC,EACA,CAAA,GAAA,CACA,SAEA,CAAA,IAAA,CACA,WACA,CAAA,IAAA,CACA,KAEA,CAAA,UAAA,CACA,UAEA,CAAA,UAAA,CAKA,YACA,CAAA,gBAAA,CAEA,QACA,CAAA,YAAA,CACA,UACA,CAAA,cAAA,CACA,UAEV,CAAA,OAAO,eAAk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EAAKC,CAAoB,GAAA,KAAA,CAAA,CACvD,CAIM,CAAA,IAAA,CAAK,GAAI,CAAA,CAAA,CAAGD,CAAU,CAAA,SAAA,CAAYC,CAAe,CAAA,CAG/CD,CAAU,CAAA,SAAA,CAAa,GAC5C,CACF","file":"Product.js","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { BasePriceList, PriceTierList, Color, LocalizedString, CountryCode, LocaleCode } from './Common';\r\nimport { GenderCategory } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type ProductVariantIdentifier = {\r\n key: string;\r\n variantId: string;\r\n};\r\n\r\nexport type ProductHashKey = {\r\n id: string;\r\n variantId: string;\r\n}\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n variantId: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n basePrices: BasePriceList;\r\n priceTiers: PriceTierList;\r\n\r\n attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n primaryImage: ImageInfoData;\r\n additionalImages?: ImageInfoData[];\r\n\r\n // Metadata & Categorization\r\n isActive: boolean;\r\n targetGender: GenderCategory;\r\n categories: string[];\r\n specifications: { [locale: string]: { [key: string]: string | string[] } };\r\n searchTags?: string[];\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type LocalizedProductSpecification = {\r\n en: ProductSpecification\r\n} & {\r\n [locale in LocaleCode]?: ProductSpecification\r\n}\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected variantId: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected basePrices: BasePriceList;\r\n protected priceTiers: PriceTierList;\r\n\r\n protected attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n protected primaryImage: ImageInfoModel;\r\n protected additionalImages: ImageInfoModel[];\r\n\r\n protected isActive: boolean;\r\n protected targetGender: GenderCategory;\r\n protected categories: string[];\r\n protected specifications: LocalizedProductSpecification;\r\n protected searchTags: string[];\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static variantIdRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.variantId = data.variantId;\r\n this.name = data.name;\r\n this.description = data.description;\r\n this.slug = data.slug;\r\n this.brand = data.brand;\r\n\r\n this.basePrices = data.basePrices.map(price => ({ ...price }));\r\n this.priceTiers = data.priceTiers ? \r\n data.priceTiers.map(tier => ({ ...tier })) \r\n : \r\n data.basePrices.map(price => ({ ...price }));;\r\n\r\n this.attributes = {\r\n ...data.attributes,\r\n sizes: [...data.attributes.sizes]\r\n };\r\n\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.additionalImages = (data.additionalImages || []).map(image => new ImageInfoModel(image));\r\n this.isActive = data.isActive;\r\n this.targetGender = data.targetGender;\r\n this.categories = [...data.categories];\r\n this.specifications = JSON.parse(JSON.stringify({ ...data.specifications }));\r\n this.searchTags = data.searchTags ? [...data.searchTags] : [];\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the specific Variant ID.\r\n * @returns Variant ID.\r\n */\r\n getVariantId(): string {\r\n return this.variantId;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if(locale) {\r\n return this.name[locale] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if(locale){\r\n return this.description[locale] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug.en;\r\n } else {\r\n return { ...this.slug };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the list of base prices. Returns copies of the price objects.\r\n * Optionally filters by country.\r\n * @param country - Optional country code to filter prices for.\r\n * @returns A list of base prices (or an empty list if none match).\r\n */\r\n getBasePrices(country?: CountryCode): BasePriceList {\r\n const filteredPrices = country ? this.basePrices.filter(price => price.country === country) : this.basePrices;\r\n return filteredPrices.map(price => ({ ...price }));\r\n }\r\n\r\n /**\r\n * Gets the list of quantity-based price tiers. Returns copies of the tier objects.\r\n * Optionally filters by country.\r\n * @param country - Optional country code to filter tiers for.\r\n * @returns A list of price tiers (or an empty list if none match or none exist).\r\n */\r\n getPriceTiers(country?: CountryCode): PriceTierList {\r\n const filteredTiers = country ? this.priceTiers.filter(tier => tier.country === country) : this.priceTiers;\r\n return filteredTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): { color: Color; sizes: string[] } {\r\n return {\r\n ...this.attributes,\r\n color: { ...this.attributes.color }, // Copy color object\r\n sizes: [...this.attributes.sizes]\r\n };\r\n }\r\n\r\n /**\r\n * Gets details of product's primary image.\r\n * @returns The ImageInfoModel instance for the primary image.\r\n */\r\n getPrimaryImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the list of additional product images.\r\n * @returns An array of ImageInfoModel instances.\r\n */\r\n getAdditionalImages(): ImageInfoModel[] {\r\n return this.additionalImages;\r\n }\r\n\r\n /**\r\n * Checks if the product variant is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return [...this.categories];\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedProductSpecification\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedProductSpecification | ProductSpecification | undefined {\r\n if(locale){\r\n return this.specifications[locale] ?? this.specifications.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /**\r\n * Gets the list of search tags. Returns a copy.\r\n * @returns An array of search tags.\r\n */\r\n getSearchTags(): string[] {\r\n return [...this.searchTags];\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n basePrices: this.getBasePrices(),\r\n priceTiers: this.getPriceTiers(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getPrimaryImage().getDetails(),\r\n additionalImages: this.getAdditionalImages().map(image => image.getDetails()),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n }; \r\n }\r\n\r\n /**\r\n * Calculates the maximum potential discount percentage for a given country\r\n * based on the lowest price tier compared to the base price.\r\n * @param country - The country code to calculate the discount for.\r\n * @returns The maximum discount percentage (0-100), or 0 if calculation is not possible.\r\n */\r\n getMaxDiscountPercent(country: CountryCode): number {\r\n // Find base price for the country (should be unique per country)\r\n const basePrice = this.basePrices.find(price => price.country === country);\r\n\r\n // Find the lowest unit price among tiers for the country\r\n const lowestTierPrice = this.priceTiers\r\n ?.filter(tier => tier.country === country) // Filter tiers for the country first\r\n .sort((a, b) => a.unitPrice - b.unitPrice)[0]?.unitPrice; // Then sort and get lowest\r\n\r\n // Validate prices before calculation\r\n if (!basePrice || basePrice.unitPrice <= 0 || lowestTierPrice === undefined) {\r\n return 0; // Cannot calculate discount\r\n }\r\n\r\n // Calculate discount, ensuring it's not negative\r\n const discount = Math.max(0, basePrice.unitPrice - lowestTierPrice);\r\n\r\n // Calculate percentage\r\n return (discount / basePrice.unitPrice) * 100;\r\n }\r\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Base.ts","../../src/Classes/ImageInfo.ts","../../src/Classes/Product.ts"],"names":["BaseModel","data","date","modifiedBy","fieldName","value","ImageInfoModel","resolutionKey","altText","order","label","url","ProductModel","price","tier","image","locale","country","baseDetails","basePrice","lowestTierPrice","a","b"],"mappings":"aA0BA,IAAqBA,CAAAA,CAArB,KAA+B,CACnB,YAAA,CACA,QACA,SACA,CAAA,UAAA,CACA,UAQV,CAAA,WAAA,CAAYC,CAAsBC,CAAAA,CAAAA,CAAa,IAAI,IAAQ,CAAA,CACzD,KAAK,YAAe,CAAA,CAAE,GAAGD,CAAK,CAAA,YAAa,CAC3C,CAAA,IAAA,CAAK,OAAUA,CAAAA,CAAAA,CAAK,SAAW,CAC/B,CAAA,IAAA,CAAK,UAAYA,CAAK,CAAA,SAAA,EAAa,CAAC,KAAM,CAAA,IAAA,CAAK,KAAMA,CAAAA,CAAAA,CAAK,SAAS,CAAC,EAElE,IAAI,IAAA,CAAKA,CAAK,CAAA,SAAS,CAAE,CAAA,WAAA,GAEzBC,CAAK,CAAA,WAAA,EACP,CAAA,IAAA,CAAK,UAAaD,CAAAA,CAAAA,CAAK,YAAc,CAAC,KAAA,CAAM,KAAK,KAAMA,CAAAA,CAAAA,CAAK,UAAU,CAAC,CAAA,CACnE,IAAI,IAAA,CAAKA,CAAK,CAAA,UAAU,EAAE,WAAY,EAAA,CACtCC,CAAK,CAAA,WAAA,EAET,CAAA,IAAA,CAAK,WAAaD,CAAK,CAAA,UAAA,EAAc,GACvC,CAMA,UAAuB,EAAA,CACrB,OAAO,CACL,YAAA,CAAc,KAAK,kBAAmB,EAAA,CACtC,QAAS,IAAK,CAAA,UAAA,EACd,CAAA,SAAA,CAAW,IAAK,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,EAAkB,CAAA,UAAA,EACrC,CAAA,gBAAA,CAAkB,KAAK,mBAAoB,EAAA,CAAE,GAAIH,CAAAA,CAAAA,EAASA,CAAM,CAAA,UAAA,EAAY,CAC5E,CAAA,QAAA,CAAU,KAAK,WAAY,EAAA,CAC3B,aAAc,IAAK,CAAA,eAAA,EACnB,CAAA,UAAA,CAAY,IAAK,CAAA,aAAA,GACjB,cAAgB,CAAA,IAAA,CAAK,iBAAkB,EAAA,CACvC,UAAY,CAAA,IAAA,CAAK,eACjB,CAAA,GAAGG,CACP,CACJ,CAQA,qBAAA,CAAsBD,EAA8B,CAElD,IAAME,EAAY,IAAK,CAAA,UAAA,CAAW,KAAKN,CAASA,EAAAA,CAAAA,CAAM,OAAYI,GAAAA,CAAO,CAGnEG,CAAAA,CAAAA,CAAkB,KAAK,UACC,EAAA,MAAA,CAAON,CAAQA,EAAAA,CAAAA,CAAK,OAAYG,GAAAA,CAAO,EACxC,IAAK,CAAA,CAACI,CAAGC,CAAAA,CAAAA,GAAMD,CAAE,CAAA,SAAA,CAAYC,EAAE,SAAS,CAAA,CAAE,CAAC,CAAG,EAAA,SAAA,CAG3E,OAAI,CAACH,CAAAA,EAAaA,CAAU,CAAA,SAAA,EAAa,CAAKC,EAAAA,CAAAA,GAAoB,OACvD,CAIM,CAAA,IAAA,CAAK,GAAI,CAAA,CAAA,CAAGD,CAAU,CAAA,SAAA,CAAYC,CAAe,CAG/CD,CAAAA,CAAAA,CAAU,SAAa,CAAA,GAC5C,CACF","file":"Product.js","sourcesContent":["import { ISODateTime } from \"./Common\";\r\n\r\nexport interface CustomFields {\r\n [key: string]: any;\r\n}\r\n\r\nexport type BaseAttributes = {\r\n customFields?: CustomFields;\r\n version?: number;\r\n createdAt?: ISODateTime;\r\n modifiedAt?: ISODateTime;\r\n modifiedBy?: string;\r\n};\r\n\r\nexport type BaseData = {\r\n customFields: CustomFields;\r\n version: number;\r\n createdAt: ISODateTime;\r\n modifiedAt: ISODateTime;\r\n modifiedBy: string;\r\n};\r\n\r\n/**\r\n * Provides common foundational properties and methods for other data models.\r\n * Handles tracking of custom fields, versioning, and timestamps.\r\n */\r\nexport default class BaseModel {\r\n protected customFields: CustomFields;\r\n protected version: number;\r\n protected createdAt: ISODateTime;\r\n protected modifiedAt: ISODateTime;\r\n protected modifiedBy: string;\r\n\r\n /**\r\n * Creates an instance of BaseModel.\r\n * Initializes common properties like timestamps, version, and custom fields.\r\n * @param data - Optional initial attributes for the base model.\r\n * @param date - Optional date object to use for default timestamps (defaults to current time).\r\n */\r\n constructor(data: BaseAttributes, date: Date = new Date()) {\r\n this.customFields = { ...data.customFields };\r\n this.version = data.version ?? 1;\r\n this.createdAt = data.createdAt && !isNaN(Date.parse(data.createdAt))\r\n ?\r\n new Date(data.createdAt).toISOString()\r\n :\r\n date.toISOString();\r\n this.modifiedAt = data.modifiedAt && !isNaN(Date.parse(data.modifiedAt))\r\n ? new Date(data.modifiedAt).toISOString()\r\n : date.toISOString();\r\n\r\n this.modifiedBy = data.modifiedBy ?? '';\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the base model's current state.\r\n * @returns BaseData object containing common properties.\r\n */\r\n getDetails(): BaseData {\r\n return {\r\n customFields: this.getAllCustomFields(), // Use getter to return a copy\r\n version: this.getVersion(),\r\n createdAt: this.getCreatedAt(),\r\n modifiedAt: this.getModifiedAt(),\r\n modifiedBy: this.getModifiedBy(),\r\n }\r\n }\r\n\r\n /**\r\n * Gets the current version number of the model instance.\r\n * @returns The version number.\r\n */\r\n getVersion(): number {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as an ISO 8601 string.\r\n * @returns The creation timestamp string.\r\n */\r\n getCreatedAt(): string {\r\n return this.createdAt;\r\n }\r\n\r\n /**\r\n * Gets the creation timestamp as a Unix epoch time (milliseconds).\r\n * @returns The creation time in milliseconds since the epoch.\r\n */\r\n getCreatedAtTime(): number {\r\n return new Date(this.createdAt).getTime();\r\n }\r\n\r\n\r\n /**\r\n * Gets the last modification timestamp as an ISO 8601 string.\r\n * @returns The last modification timestamp string.\r\n */\r\n getModifiedAt(): string {\r\n return this.modifiedAt;\r\n }\r\n\r\n /**\r\n * Gets the last modification timestamp as a Unix epoch time (milliseconds).\r\n * @returns The last modification time in milliseconds since the epoch.\r\n */\r\n getModifiedAtTime(): number {\r\n return new Date(this.modifiedAt).getTime();\r\n }\r\n\r\n /**\r\n * Gets the identifier of the user or process that last modified the instance.\r\n * @returns The modifier identifier string.\r\n */\r\n getModifiedBy(): string {\r\n return this.modifiedBy;\r\n }\r\n\r\n /**\r\n * Sets the identifier of the user or process that last modified the instance.\r\n * @param modifiedBy - The identifier string.\r\n */\r\n setModifiedBy(modifiedBy: string): void {\r\n this.modifiedBy = modifiedBy;\r\n }\r\n\r\n /**\r\n * Retrieves the value of a specific custom field.\r\n * @param fieldName - The name (key) of the custom field to retrieve.\r\n * @returns The value of the custom field, or null if the field does not exist.\r\n */\r\n getCustomField(fieldName: string): any {\r\n return this.customFields[fieldName] ?? null;\r\n }\r\n\r\n /**\r\n * Sets the value of a specific custom field.\r\n * Also updates the modification timestamp and increments the version.\r\n * @param fieldName - The name (key) of the custom field to set.\r\n * @param value - The value to assign to the custom field.\r\n */\r\n setCustomField(fieldName: string, value: any): void {\r\n this.customFields[fieldName] = value;\r\n }\r\n\r\n /**\r\n * Retrieves a shallow copy of all custom fields associated with the instance.\r\n * @returns An object containing all custom fields.\r\n */\r\n getAllCustomFields(): CustomFields {\r\n return { ...this.customFields };\r\n }\r\n}\r\n","export enum ImageResolution {\r\n THUMBNAIL = 'thumbnail',\r\n SMALL = 'small',\r\n MEDIUM = 'medium',\r\n LARGE = 'large',\r\n ORIGINAL = 'original',\r\n}\r\n\r\nexport type ImageInfoAttribute = {\r\n sources: { [key in ImageResolution]?: string } & { original: string };\r\n alt?: string;\r\n order?: number;\r\n label?: string;\r\n};\r\n\r\nexport type ImageInfoData = ImageInfoAttribute;\r\n\r\n/**\r\n * Represents and manages structured image data, including multiple resolutions.\r\n */\r\nexport default class ImageInfoModel {\r\n protected sources: { [key in ImageResolution]?: string } & { original: string };\r\n protected alt?: string;\r\n protected order?: number;\r\n protected label?: string;\r\n\r\n /**\r\n * Creates an instance of ImageInfoModel.\r\n * @param data - The initial image data.\r\n */\r\n constructor(data: ImageInfoAttribute) {\r\n this.sources = { ...data.sources };\r\n this.alt = data.alt;\r\n this.order = data.order;\r\n this.label = data.label;\r\n\r\n if (!this.sources.original) {\r\n throw (\"ImageInfoModel cannot be created without an 'original' source URL.\");\r\n }\r\n }\r\n\r\n /**\r\n * Gets the sources object containing URLs for different resolutions.\r\n * Returns a copy to prevent external modification.\r\n */\r\n getSources() {\r\n return { ...this.sources };\r\n }\r\n\r\n /**\r\n * Gets the URL for a specific resolution key.\r\n * @param resolutionKey - The key of the desired resolution (e.g., 'thumbnail', 'medium').\r\n * @returns The URL string if the key doesn't exist, otherwise original image URL will be returned.\r\n */\r\n getSource(resolutionKey: ImageResolution): string{\r\n return this.sources[resolutionKey] || this.sources.original;\r\n }\r\n\r\n /**\r\n * Gets the alternative text for the image.\r\n */\r\n getAlt(): string | undefined {\r\n return this.alt;\r\n }\r\n\r\n /**\r\n * Gets the display order number for the image.\r\n */\r\n getOrder(): number | undefined {\r\n return this.order;\r\n }\r\n\r\n /**\r\n * Gets the display label or caption for the image.\r\n */\r\n getLabel(): string | undefined {\r\n return this.label;\r\n }\r\n\r\n /**\r\n * Sets the alternative text for the image.\r\n * @param altText - The new alt text.\r\n */\r\n setAlt(altText: string | undefined): void {\r\n this.alt = altText;\r\n // Potentially add logic here to trigger updates if needed\r\n }\r\n\r\n /**\r\n * Sets the display order for the image.\r\n * @param order - The new order number.\r\n */\r\n setOrder(order: number | undefined): void {\r\n this.order = order;\r\n }\r\n\r\n /**\r\n * Sets the display label for the image.\r\n * @param label - The new label text.\r\n */\r\n setLabel(label: string | undefined): void {\r\n this.label = label;\r\n }\r\n\r\n /**\r\n * Updates or adds a URL for a specific resolution.\r\n * @param resolutionKey - The key of the resolution to update/add.\r\n * @param url - The URL for the resolution. Set to undefined to remove.\r\n */\r\n setSource(resolutionKey: ImageResolution, url: string | undefined): void {\r\n if (url === undefined) {\r\n // Prevent deleting the 'original' key if it's required\r\n if (resolutionKey === 'original') {\r\n throw (\"Cannot remove the 'original' image source.\");\r\n return;\r\n }\r\n delete this.sources[resolutionKey];\r\n } else {\r\n this.sources[resolutionKey] = url;\r\n }\r\n }\r\n\r\n /**\r\n * Returns a plain JavaScript object representation of the image info.\r\n */\r\n getDetails(): ImageInfoData {\r\n return {\r\n sources: this.getSources(),\r\n alt: this.getAlt(),\r\n order: this.getOrder(),\r\n label: this.getLabel(),\r\n };\r\n }\r\n}","import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { BasePriceList, PriceTierList, Color, LocalizedString, CountryCode, LocaleCode } from './Common';\r\nimport { GenderCategory } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type ProductVariantIdentifier = {\r\n key: string;\r\n variantId: string;\r\n};\r\n\r\nexport type ProductHashKey = {\r\n id: string;\r\n variantId: string;\r\n}\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n variantId: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n basePrices: BasePriceList;\r\n priceTiers: PriceTierList;\r\n\r\n attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n primaryImage: ImageInfoData;\r\n additionalImages?: ImageInfoData[];\r\n\r\n // Metadata & Categorization\r\n isActive: boolean;\r\n targetGender: GenderCategory;\r\n categories: string[];\r\n specifications: { [locale: string]: { [key: string]: string | string[] } };\r\n searchTags?: string[];\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type LocalizedProductSpecification = {\r\n en: ProductSpecification\r\n} & {\r\n [locale in LocaleCode]?: ProductSpecification\r\n}\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected variantId: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected basePrices: BasePriceList;\r\n protected priceTiers: PriceTierList;\r\n\r\n protected attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n protected primaryImage: ImageInfoModel;\r\n protected additionalImages: ImageInfoModel[];\r\n\r\n protected isActive: boolean;\r\n protected targetGender: GenderCategory;\r\n protected categories: string[];\r\n protected specifications: LocalizedProductSpecification;\r\n protected searchTags: string[];\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static variantIdRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.variantId = data.variantId;\r\n this.name = data.name;\r\n this.description = data.description;\r\n this.slug = data.slug;\r\n this.brand = data.brand;\r\n\r\n this.basePrices = data.basePrices.map(price => ({ ...price }));\r\n this.priceTiers = data.priceTiers ? \r\n data.priceTiers.map(tier => ({ ...tier })) \r\n : \r\n data.basePrices.map(price => ({ ...price }));;\r\n\r\n this.attributes = {\r\n ...data.attributes,\r\n sizes: [...data.attributes.sizes]\r\n };\r\n\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.additionalImages = (data.additionalImages || []).map(image => new ImageInfoModel(image));\r\n this.isActive = data.isActive;\r\n this.targetGender = data.targetGender;\r\n this.categories = [...data.categories];\r\n this.specifications = JSON.parse(JSON.stringify({ ...data.specifications }));\r\n this.searchTags = data.searchTags ? [...data.searchTags] : [];\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the specific Variant ID.\r\n * @returns Variant ID.\r\n */\r\n getVariantId(): string {\r\n return this.variantId;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if(locale) {\r\n return this.name[locale] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if(locale){\r\n return this.description[locale] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug.en;\r\n } else {\r\n return { ...this.slug };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the list of base prices. Returns copies of the price objects.\r\n * Optionally filters by country.\r\n * @param country - Optional country code to filter prices for.\r\n * @returns A list of base prices (or an empty list if none match).\r\n */\r\n getBasePrices(country?: CountryCode): BasePriceList {\r\n const filteredPrices = country ? this.basePrices.filter(price => price.country === country) : this.basePrices;\r\n return filteredPrices.map(price => ({ ...price }));\r\n }\r\n\r\n /**\r\n * Gets the list of quantity-based price tiers. Returns copies of the tier objects.\r\n * Optionally filters by country.\r\n * @param country - Optional country code to filter tiers for.\r\n * @returns A list of price tiers (or an empty list if none match or none exist).\r\n */\r\n getPriceTiers(country?: CountryCode): PriceTierList {\r\n const filteredTiers = country ? this.priceTiers.filter(tier => tier.country === country) : this.priceTiers;\r\n return filteredTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): { color: Color; sizes: string[] } {\r\n return {\r\n ...this.attributes,\r\n color: { ...this.attributes.color }, // Copy color object\r\n sizes: [...this.attributes.sizes]\r\n };\r\n }\r\n\r\n /**\r\n * Gets details of product's primary image.\r\n * @returns The ImageInfoModel instance for the primary image.\r\n */\r\n getPrimaryImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the list of additional product images.\r\n * @returns An array of ImageInfoModel instances.\r\n */\r\n getAdditionalImages(): ImageInfoModel[] {\r\n return this.additionalImages;\r\n }\r\n\r\n /**\r\n * Checks if the product variant is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return [...this.categories];\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedProductSpecification\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedProductSpecification | ProductSpecification | undefined {\r\n if(locale){\r\n return this.specifications[locale] ?? this.specifications.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /**\r\n * Gets the list of search tags. Returns a copy.\r\n * @returns An array of search tags.\r\n */\r\n getSearchTags(): string[] {\r\n return [...this.searchTags];\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n basePrices: this.getBasePrices(),\r\n priceTiers: this.getPriceTiers(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getPrimaryImage().getDetails(),\r\n additionalImages: this.getAdditionalImages().map(image => image.getDetails()),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n }; \r\n }\r\n\r\n /**\r\n * Calculates the maximum potential discount percentage for a given country\r\n * based on the lowest price tier compared to the base price.\r\n * @param country - The country code to calculate the discount for.\r\n * @returns The maximum discount percentage (0-100), or 0 if calculation is not possible.\r\n */\r\n getMaxDiscountPercent(country: CountryCode): number {\r\n // Find base price for the country (should be unique per country)\r\n const basePrice = this.basePrices.find(price => price.country === country);\r\n\r\n // Find the lowest unit price among tiers for the country\r\n const lowestTierPrice = this.priceTiers\r\n ?.filter(tier => tier.country === country) // Filter tiers for the country first\r\n .sort((a, b) => a.unitPrice - b.unitPrice)[0]?.unitPrice; // Then sort and get lowest\r\n\r\n // Validate prices before calculation\r\n if (!basePrice || basePrice.unitPrice <= 0 || lowestTierPrice === undefined) {\r\n return 0; // Cannot calculate discount\r\n }\r\n\r\n // Calculate discount, ensuring it's not negative\r\n const discount = Math.max(0, basePrice.unitPrice - lowestTierPrice);\r\n\r\n // Calculate percentage\r\n return (discount / basePrice.unitPrice) * 100;\r\n }\r\n}"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'../chunk-DKI6BDWK.mjs';import {a}from'../chunk-SPLTJRHG.mjs';var n=class extends a{id;key;variantId;name;description;slug;brand;basePrices;priceTiers;attributes;primaryImage;additionalImages;isActive;targetGender;categories;specifications;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static variantIdRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;constructor(e,i=new Date){super(e,i),this.id=e.id,this.key=e.key,this.variantId=e.variantId,this.name=e.name,this.description=e.description,this.slug=e.slug,this.brand=e.brand,this.basePrices=e.basePrices.map(t=>({...t})),this.priceTiers=e.priceTiers?e.priceTiers.map(t=>({...t})):e.basePrices.map(t=>({...t})),this.attributes={...e.attributes,sizes:[...e.attributes.sizes]},this.primaryImage=new b(e.primaryImage),this.additionalImages=(e.additionalImages||[]).map(t=>new b(t)),this.isActive=e.isActive,this.targetGender=e.targetGender,this.categories=[...e.categories],this.specifications=JSON.parse(JSON.stringify({...e.specifications})),this.searchTags=e.searchTags?[...e.searchTags]:[];}getId(){return this.id}getKey(){return this.key}getVariantId(){return this.variantId}getName(e){return e?this.name[e]??this.name.en:{...this.name}}getDescription(e){return e?this.description[e]??this.description.en:{...this.description}}getSlug(e){return e?this.slug[e]??this.slug.en:{...this.slug}}getBrand(){return this.brand}getBasePrices(e){return (e?this.basePrices.filter(t=>t.country===e):this.basePrices).map(t=>({...t}))}getPriceTiers(e){return (e?this.priceTiers.filter(t=>t.country===e):this.priceTiers).map(t=>({...t}))}getAttributes(){return {...this.attributes,color:{...this.attributes.color},sizes:[...this.attributes.sizes]}}getPrimaryImage(){return this.primaryImage}getAdditionalImages(){return this.additionalImages}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return [...this.categories]}getSpecifications(e){return e?this.specifications[e]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}getSearchTags(){return [...this.searchTags]}getDetails(){let e=super.getDetails();return {id:this.getId(),key:this.getKey(),variantId:this.getVariantId(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),basePrices:this.getBasePrices(),priceTiers:this.getPriceTiers(),attributes:this.getAttributes(),primaryImage:this.getPrimaryImage().getDetails(),additionalImages:this.getAdditionalImages().map(i=>i.getDetails()),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}getMaxDiscountPercent(e){let i=this.basePrices.find(r=>r.country===e),t=this.priceTiers?.filter(r=>r.country===e).sort((r,c)=>r.unitPrice-c.unitPrice)[0]?.unitPrice;return !i||i.unitPrice<=0||t===void 0?0:Math.max(0,i.unitPrice-t)/i.unitPrice*100}};export{n as default};//# sourceMappingURL=Product.mjs.map
|
|
2
|
+
//# sourceMappingURL=Product.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Product.ts"],"names":["ProductModel","BaseModel","data","date","price","tier","ImageInfoModel","image","locale","country","baseDetails","basePrice","lowestTierPrice","a","b"],"mappings":"4EAsDA,IAAqBA,CAArB,CAAA,cAA0CC,CAAU,CACtC,EACA,CAAA,GAAA,CACA,SAEA,CAAA,IAAA,CACA,WACA,CAAA,IAAA,CACA,KAEA,CAAA,UAAA,CACA,UAEA,CAAA,UAA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AE,CAAA,CAAC,CAAG,EAAA,SAAA,CAG3E,OAAI,CAACH,CAAaA,EAAAA,CAAAA,CAAU,SAAa,EAAA,CAAA,EAAKC,CAAoB,GAAA,KAAA,CAAA,CACvD,CAIM,CAAA,IAAA,CAAK,GAAI,CAAA,CAAA,CAAGD,CAAU,CAAA,SAAA,CAAYC,CAAe,CAAA,CAG/CD,CAAU,CAAA,SAAA,CAAa,GAC5C,CACF","file":"Product.mjs","sourcesContent":["import BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { BasePriceList, PriceTierList, Color, LocalizedString, CountryCode, LocaleCode } from './Common';\r\nimport { GenderCategory } from \"./Enum\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type ProductVariantIdentifier = {\r\n key: string;\r\n variantId: string;\r\n};\r\n\r\nexport type ProductHashKey = {\r\n id: string;\r\n variantId: string;\r\n}\r\n\r\nexport type ProductAttributes = BaseAttributes & {\r\n id: string;\r\n key: string;\r\n variantId: string;\r\n\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n slug: LocalizedString;\r\n brand: string;\r\n\r\n basePrices: BasePriceList;\r\n priceTiers: PriceTierList;\r\n\r\n attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n primaryImage: ImageInfoData;\r\n additionalImages?: ImageInfoData[];\r\n\r\n // Metadata & Categorization\r\n isActive: boolean;\r\n targetGender: GenderCategory;\r\n categories: string[];\r\n specifications: { [locale: string]: { [key: string]: string | string[] } };\r\n searchTags?: string[];\r\n};\r\n\r\nexport type ProductData = Required<ProductAttributes>\r\n\r\nexport type ProductSpecification = { [key: string]: string | string[] };\r\n\r\nexport type LocalizedProductSpecification = {\r\n en: ProductSpecification\r\n} & {\r\n [locale in LocaleCode]?: ProductSpecification\r\n}\r\n\r\nexport default class ProductModel extends BaseModel {\r\n protected id: string;\r\n protected key: string;\r\n protected variantId: string;\r\n\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected slug: LocalizedString;\r\n protected brand: string;\r\n\r\n protected basePrices: BasePriceList;\r\n protected priceTiers: PriceTierList;\r\n\r\n protected attributes: {\r\n color: Color;\r\n sizes: string[];\r\n };\r\n\r\n protected primaryImage: ImageInfoModel;\r\n protected additionalImages: ImageInfoModel[];\r\n\r\n protected isActive: boolean;\r\n protected targetGender: GenderCategory;\r\n protected categories: string[];\r\n protected specifications: LocalizedProductSpecification;\r\n protected searchTags: string[];\r\n\r\n static productKeyRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n static variantIdRegex = /^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$/;\r\n\r\n /**\r\n * Creates an instance of ProductModel.\r\n * Initializes properties based on the provided data, creating copies where necessary.\r\n * @param data - The initial product attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: ProductAttributes, date: Date = new Date()) {\r\n super(data, date);\r\n this.id = data.id;\r\n this.key = data.key;\r\n this.variantId = data.variantId;\r\n this.name = data.name;\r\n this.description = data.description;\r\n this.slug = data.slug;\r\n this.brand = data.brand;\r\n\r\n this.basePrices = data.basePrices.map(price => ({ ...price }));\r\n this.priceTiers = data.priceTiers ? \r\n data.priceTiers.map(tier => ({ ...tier })) \r\n : \r\n data.basePrices.map(price => ({ ...price }));;\r\n\r\n this.attributes = {\r\n ...data.attributes,\r\n sizes: [...data.attributes.sizes]\r\n };\r\n\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.additionalImages = (data.additionalImages || []).map(image => new ImageInfoModel(image));\r\n this.isActive = data.isActive;\r\n this.targetGender = data.targetGender;\r\n this.categories = [...data.categories];\r\n this.specifications = JSON.parse(JSON.stringify({ ...data.specifications }));\r\n this.searchTags = data.searchTags ? [...data.searchTags] : [];\r\n }\r\n\r\n /**\r\n * Gets the base Product ID.\r\n * @returns Product ID.\r\n */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /**\r\n * Gets the user-friendly product key.\r\n * @returns Product Key.\r\n */\r\n getKey(): string {\r\n return this.key;\r\n }\r\n\r\n /**\r\n * Gets the specific Variant ID.\r\n * @returns Variant ID.\r\n */\r\n getVariantId(): string {\r\n return this.variantId;\r\n }\r\n\r\n /**\r\n * Gets the full localized product name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the product name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if(locale) {\r\n return this.name[locale] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product description object.\r\n * @returns A copy of the LocalizedString object for the description.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the product description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if(locale){\r\n return this.description[locale] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized product slug object.\r\n * @returns A copy of the LocalizedString object for the slug.\r\n */\r\n getSlug(): LocalizedString\r\n /**\r\n * Gets the product slug for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The slug string for the specified locale.\r\n */\r\n getSlug(locale: LocaleCode): string\r\n getSlug(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.slug[locale] ?? this.slug.en;\r\n } else {\r\n return { ...this.slug };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the brand associated with the product.\r\n * @returns The brand name string.\r\n */\r\n getBrand(): string {\r\n return this.brand;\r\n }\r\n\r\n /**\r\n * Gets the list of base prices. Returns copies of the price objects.\r\n * Optionally filters by country.\r\n * @param country - Optional country code to filter prices for.\r\n * @returns A list of base prices (or an empty list if none match).\r\n */\r\n getBasePrices(country?: CountryCode): BasePriceList {\r\n const filteredPrices = country ? this.basePrices.filter(price => price.country === country) : this.basePrices;\r\n return filteredPrices.map(price => ({ ...price }));\r\n }\r\n\r\n /**\r\n * Gets the list of quantity-based price tiers. Returns copies of the tier objects.\r\n * Optionally filters by country.\r\n * @param country - Optional country code to filter tiers for.\r\n * @returns A list of price tiers (or an empty list if none match or none exist).\r\n */\r\n getPriceTiers(country?: CountryCode): PriceTierList {\r\n const filteredTiers = country ? this.priceTiers.filter(tier => tier.country === country) : this.priceTiers;\r\n return filteredTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Gets the variant-specific attributes (color, sizes). Returns copies.\r\n * @returns Product Attributes.\r\n */\r\n getAttributes(): { color: Color; sizes: string[] } {\r\n return {\r\n ...this.attributes,\r\n color: { ...this.attributes.color }, // Copy color object\r\n sizes: [...this.attributes.sizes]\r\n };\r\n }\r\n\r\n /**\r\n * Gets details of product's primary image.\r\n * @returns The ImageInfoModel instance for the primary image.\r\n */\r\n getPrimaryImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /**\r\n * Gets the list of additional product images.\r\n * @returns An array of ImageInfoModel instances.\r\n */\r\n getAdditionalImages(): ImageInfoModel[] {\r\n return this.additionalImages;\r\n }\r\n\r\n /**\r\n * Checks if the product variant is active.\r\n * @returns True if the product is active, false otherwise.\r\n */\r\n getIsActive(): boolean {\r\n return this.isActive;\r\n }\r\n\r\n /**\r\n * Gets the target gender category for the product.\r\n * @returns The GenderCategory enum value.\r\n */\r\n getTargetGender(): GenderCategory {\r\n return this.targetGender;\r\n }\r\n\r\n /**\r\n * Gets the list of categories the product belongs to. Returns a copy.\r\n * @returns An array of category.\r\n */\r\n getCategories(): string[] {\r\n return [...this.categories];\r\n }\r\n\r\n /**\r\n * Gets the full localized product specifications object.\r\n * @returns Product Specifications\r\n */\r\n getSpecifications(): LocalizedProductSpecification\r\n /**\r\n * Gets the product specifications for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The ProductSpecification object for the specified locale, or undefined if not found.\r\n */\r\n getSpecifications(locale: LocaleCode): ProductSpecification | undefined\r\n getSpecifications(locale?: LocaleCode): LocalizedProductSpecification | ProductSpecification | undefined {\r\n if(locale){\r\n return this.specifications[locale] ?? this.specifications.en;\r\n } else {\r\n return JSON.parse(JSON.stringify(this.specifications));\r\n }\r\n }\r\n\r\n /**\r\n * Gets the list of search tags. Returns a copy.\r\n * @returns An array of search tags.\r\n */\r\n getSearchTags(): string[] {\r\n return [...this.searchTags];\r\n }\r\n\r\n /**\r\n *\r\n * @returns ProductData\r\n */\r\n getDetails(): ProductData {\r\n const baseDetails = super.getDetails();\r\n return {\r\n id: this.getId(),\r\n key: this.getKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n slug: this.getSlug(),\r\n brand: this.getBrand(),\r\n basePrices: this.getBasePrices(),\r\n priceTiers: this.getPriceTiers(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getPrimaryImage().getDetails(),\r\n additionalImages: this.getAdditionalImages().map(image => image.getDetails()),\r\n isActive: this.getIsActive(),\r\n targetGender: this.getTargetGender(),\r\n categories: this.getCategories(),\r\n specifications: this.getSpecifications(),\r\n searchTags: this.getSearchTags(),\r\n ...baseDetails\r\n }; \r\n }\r\n\r\n /**\r\n * Calculates the maximum potential discount percentage for a given country\r\n * based on the lowest price tier compared to the base price.\r\n * @param country - The country code to calculate the discount for.\r\n * @returns The maximum discount percentage (0-100), or 0 if calculation is not possible.\r\n */\r\n getMaxDiscountPercent(country: CountryCode): number {\r\n // Find base price for the country (should be unique per country)\r\n const basePrice = this.basePrices.find(price => price.country === country);\r\n\r\n // Find the lowest unit price among tiers for the country\r\n const lowestTierPrice = this.priceTiers\r\n ?.filter(tier => tier.country === country) // Filter tiers for the country first\r\n .sort((a, b) => a.unitPrice - b.unitPrice)[0]?.unitPrice; // Then sort and get lowest\r\n\r\n // Validate prices before calculation\r\n if (!basePrice || basePrice.unitPrice <= 0 || lowestTierPrice === undefined) {\r\n return 0; // Cannot calculate discount\r\n }\r\n\r\n // Calculate discount, ensuring it's not negative\r\n const discount = Math.max(0, basePrice.unitPrice - lowestTierPrice);\r\n\r\n // Calculate percentage\r\n return (discount / basePrice.unitPrice) * 100;\r\n }\r\n}"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import BaseModel, { BaseAttributes, BaseData } from './Base.
|
|
2
|
-
import AddressModel, { AddressData } from './Address.
|
|
3
|
-
import LineItemModel, { LineItemData } from './LineItem.
|
|
4
|
-
import { ShippingDetails, CountryCode, CurrencyCode, LocaleCode } from './Common.
|
|
5
|
-
import CouponModel, { CouponData } from './Coupon.
|
|
6
|
-
import './ImageInfo.
|
|
7
|
-
import './Enum.
|
|
1
|
+
import BaseModel, { BaseAttributes, BaseData } from './Base.mjs';
|
|
2
|
+
import AddressModel, { AddressData } from './Address.mjs';
|
|
3
|
+
import LineItemModel, { LineItemData } from './LineItem.mjs';
|
|
4
|
+
import { ShippingDetails, CountryCode, CurrencyCode, LocaleCode } from './Common.mjs';
|
|
5
|
+
import CouponModel, { CouponData } from './Coupon.mjs';
|
|
6
|
+
import './ImageInfo.mjs';
|
|
7
|
+
import './Enum.mjs';
|
|
8
8
|
|
|
9
9
|
type BaseShoppingContainerAttributes = BaseAttributes & {
|
|
10
10
|
id: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as default}from'../chunk-2ESSIPYR.js';import'../chunk-P5BGQ3PJ.js';import'../chunk-IYDPJQAK.js';import'../chunk-XL3K64E6.js';import'../chunk-7UEGCYYY.js';import'../chunk-PD6TDU7F.js';import'../chunk-2IVRLXCO.js';import'../chunk-Q2WQECY6.js';//# sourceMappingURL=ShoppingContainer.js.map
|
|
1
|
+
'use strict';var u=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy=t.modifiedBy??"";}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return this.modifiedBy}setModifiedBy(t){this.modifiedBy=t;}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var l=class extends u{id;firstName;lastName;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName,this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var d=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw "ImageInfoModel cannot be created without an 'original' source URL."}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw "Cannot remove the 'original' image source.";delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var p=class{id;productKey;variantId;name;attributes;primaryImage;subItems;totalQuantity;basePrice;priceTotals;priceTiers;constructor(t){this.id=t.id,this.productKey=t.productKey,this.variantId=t.variantId,this.name={...t.name},this.attributes={...t.attributes},this.primaryImage=new d(t.primaryImage),this.subItems=t.subItems.map(e=>({...e})),this.basePrice={...t.basePrice},this.priceTiers=t.priceTiers.map(e=>({...e})),this.totalQuantity=0,this.priceTotals={subtotal:0,mrpTotal:0},this.recalculateTotalQuantity(),this.recalculatePriceTotal();}getId(){return this.id}getProductKey(){return this.productKey}getVariantId(){return this.variantId}getName(t){return t?this.name[t]??this.name.en:{...this.name}}getAttributes(){return {...this.attributes}}getImage(){return this.primaryImage}getSubItems(){return this.subItems.map(t=>({...t}))}getTotalQuantity(){return this.totalQuantity}getBasePrice(){return {...this.basePrice}}getPriceTotals(){return {...this.priceTotals}}getPriceTiers(){return this.priceTiers.map(t=>({...t}))}recalculateTotalQuantity(){this.totalQuantity=this.subItems.reduce((t,e)=>t+e.quantity,0);}recalculatePriceTotal(){let t=this.totalQuantity,e=this.basePrice.unitPrice,i=null;for(let r of this.priceTiers.sort((s,a)=>a.minQuantity-s.minQuantity))if(t>=r.minQuantity){i=r;break}i&&(e=i.unitPrice),this.priceTotals.mrpTotal=this.basePrice.unitPrice*t,this.priceTotals.subtotal=e*t;}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),variantId:this.getVariantId(),name:this.getName(),attributes:this.getAttributes(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),totalQuantity:this.getTotalQuantity(),basePrice:this.getBasePrice(),priceTotals:this.getPriceTotals(),priceTiers:this.getPriceTiers()}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(s=>s.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity),this.recalculateTotalQuantity(),this.recalculatePriceTotal();}clearLineItem(){this.id="",this.productKey="",this.variantId="",this.name={en:""},this.attributes={color:{name:"",hex:""}},this.primaryImage=new d({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var h={IN:"INR"},I={INR:"\u20B9"};var o=class n{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t;}getCountry(){return this.country}getRoundedPrice(){return n.getRoundedPrice(this.price,this.country)}getFormattedString(t,e={}){let i=e.displayAsInteger??!1,r=h[this.country];if(r===void 0)throw new Error("Currency mapping not found for CountryCode");let s=this.price,a=i?0:n.getDecimalPlaces(r),m={style:"currency",currency:r,signDisplay:"never",currencyDisplay:e.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};i&&(s=Math.round(s));try{return new Intl.NumberFormat(t,m).format(s)}catch(y){return console.error(`Error formatting price for locale "${t}" and currency "${r}":`,y),`${I[r]??r} ${n.addThousandSeparators(s.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let i=h[e];if(i===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let r=n.getDecimalPlaces(i),s=Math.pow(10,r);return Math.round(t*s)/s}static getCurrency(t){return h[t]}};o.getRoundedPrice(-1,"IN");var g=class extends u{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){super(t,e),this.couponCode=t.couponCode,this.name={...t.name},this.description={...t.description},this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=t.minCartValue.map(i=>({...i})),this.maxCartDiscount=t.maxCartDiscount.map(i=>({...i})),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue.find(e=>e.country===t):this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount.find(e=>e.country===t):this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:this.getMinCartValue(),maxCartDiscount:this.getMaxCartDiscount(),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}};var b=class extends u{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new p(i)),this.billingAddress=t.billingAddress?new l(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new l(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new g(i)),this.shippingDetails=t.shippingDetails?{...t.shippingDetails}:null,this.total={shipping:t.total?.shipping||0,effectiveShipping:t.total?.effectiveShipping||t.total?.shipping||0,subtotal:0,mrpTotal:0,couponTotal:t.total?.couponTotal||{},grandTotal:t.total?.grandTotal||0},this.recalculateBaseTotals();}recalculateBaseTotals(){this.total.subtotal=o.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=o.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().mrpTotal,0),this.country);}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new p(t.getDetails()))}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new l(this.shippingAddress.getDetails()):null}getBillingAddress(){return this.billingAddress?new l(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new g(t.getDetails()))}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return {...this.total,couponTotal:{...this.total.couponTotal}}}calculateApplicableCouponDiscount(t){if(!t.isActive())return 0;let e=t.getMinCartValue(this.country),i=t.getMaxCartDiscount(this.country);if(!e||this.total.subtotal<e.price||!i||i.price<0)return 0;let r=t.getCategory(),s=t.getDiscountMethod(),a=0,m=r==="SHIPPING"?this.total.shipping:this.total.subtotal;if(m<=0)return 0;switch(s){case"flat":let C=i?.price??0;a=Math.min(m,C);break;case"percentage":a=m*(t.getPercentageValue()/100);break;default:return 0}let y=Math.min(a,i.price);return o.getRoundedPrice(Math.max(0,y),this.country)}recalculateCouponTotals(){this.total.couponTotal={};let t=0;return this.coupons.forEach(e=>{let i=this.calculateApplicableCouponDiscount(e);i>0&&(this.total.couponTotal[e.getCode()]=i,t+=i);}),o.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=o.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=o.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().mrpTotal,0),this.country),this.recalculateCouponTotals();let t=this.coupons.filter(r=>r.getCategory()==="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0);this.total.effectiveShipping=o.getRoundedPrice(Math.max(0,this.total.shipping-t),this.country);let e=this.coupons.filter(r=>r.getCategory()!=="SHIPPING").reduce((r,s)=>r+(this.total.couponTotal[s.getCode()]??0),0),i=this.total.subtotal+this.total.effectiveShipping;this.total.grandTotal=o.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=o.getRoundedPrice(this.shippingDetails?.estimatedCost??0,this.country),this.updateCartTotals();}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:this.getTotal(),country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}};module.exports=b;//# sourceMappingURL=ShoppingContainer.js.map
|
|
2
2
|
//# sourceMappingURL=ShoppingContainer.js.map
|