b23-lib 1.8.6 → 1.8.8
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/Classes/Cart.d.mts +1 -0
- package/dist/Classes/Cart.d.ts +1 -0
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/LineItem.d.mts +16 -0
- package/dist/Classes/LineItem.d.ts +16 -0
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.d.mts +1 -0
- package/dist/Classes/Order.d.ts +1 -0
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/ShoppingContainer.d.mts +1 -0
- package/dist/Classes/ShoppingContainer.d.ts +1 -0
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/{chunk-AU6EJ42U.mjs → chunk-2NO3E4TI.mjs} +2 -2
- package/dist/{chunk-AU6EJ42U.mjs.map → chunk-2NO3E4TI.mjs.map} +1 -1
- package/dist/{chunk-UBZ7FGYE.mjs → chunk-MPZ4IPRM.mjs} +2 -2
- package/dist/{chunk-UBZ7FGYE.mjs.map → chunk-MPZ4IPRM.mjs.map} +1 -1
- package/dist/chunk-STQZVQ7K.mjs +2 -0
- package/dist/chunk-STQZVQ7K.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-WU6FFDBS.mjs +0 -2
- package/dist/chunk-WU6FFDBS.mjs.map +0 -1
package/dist/Classes/LineItem.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var s=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
|
|
1
|
+
'use strict';var s=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 o=class{id;productKey;variantId;name;attributes;specifications;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.specifications={...t.specifications},this.primaryImage=new s(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}}getSpecifications(t){return t?this.specifications[t]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}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((a,c)=>c.minQuantity-a.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(),specifications:this.getSpecifications(),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(a=>a.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 s({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};module.exports=o;//# sourceMappingURL=LineItem.js.map
|
|
2
2
|
//# sourceMappingURL=LineItem.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/ImageInfo.ts","../../src/Classes/LineItem.ts"],"names":["ImageInfoModel","data","resolutionKey","altText","order","label","url","LineItemModel","item","tier","locale","sum","quantity","unitPrice","applicableTier","b","subItems","addQuantity","subItem","existingSubItem","sub"],"mappings":"aAoBA,IAAqBA,CAArB,CAAA,KAAoC,CACxB,OAAA,CACA,GACA,C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A,GACL,IAAK,CAAA,qBAAA,GACP,CAOA,aAAsB,EAAA,CACpB,IAAK,CAAA,EAAA,CAAK,GACV,IAAK,CAAA,UAAA,CAAa,EAClB,CAAA,IAAA,CAAK,SAAY,CAAA,EAAA,CACjB,IAAK,CAAA,IAAA,CAAO,CAAE,EAAI,CAAA,EAAG,CACrB,CAAA,IAAA,CAAK,UAAa,CAAA,CAAE,KAAO,CAAA,CAAE,KAAM,EAAI,CAAA,GAAA,CAAK,EAAG,CAAE,CACjD,CAAA,IAAA,CAAK,YAAe,CAAA,IAAIpB,EAAe,CAAE,OAAA,CAAS,CAAE,QAAA,CAAU,EAAG,CAAE,CAAC,CAAA,CACpE,KAAK,QAAW,CAAA,EAChB,CAAA,IAAA,CAAK,wBAAyB,EAAA,CAC9B,IAAK,CAAA,qBAAA,GACP,CACF","file":"LineItem.js","sourcesContent":["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 { BasePrice, Color, LocaleCode, LocalizedString, PriceTier } from \"./Common\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\n\r\nexport type SubItem = {\r\n size: string;\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemAttributes = {\r\n id: string;\r\n productKey: string;\r\n variantId: string;\r\n name: LocalizedString;\r\n attributes: {\r\n color: Color;\r\n };\r\n primaryImage: ImageInfoData;\r\n subItems: SubItem[];\r\n basePrice: BasePrice;\r\n priceTiers: PriceTier[];\r\n}\r\n\r\nexport type LineItemData = LineItemAttributes & {\r\n totalQuantity: number;\r\n priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n}\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected variantId: string;\r\n protected name: LocalizedString;\r\n protected attributes: {\r\n color: Color;\r\n };\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected totalQuantity: number;\r\n protected basePrice: BasePrice;\r\n protected priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n protected priceTiers: PriceTier[];\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.variantId = data.variantId;\r\n\r\n this.name = { ...data.name };\r\n this.attributes = { ...data.attributes };\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = data.subItems.map(item => ({ ...item }));\r\n this.basePrice = { ...data.basePrice };\r\n this.priceTiers = data.priceTiers.map(tier => ({ ...tier }));\r\n\r\n this.totalQuantity = 0;\r\n this.priceTotals = {\r\n subtotal: 0,\r\n mrpTotal: 0\r\n };\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /** Gets the unique identifier of the line item. */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /** Gets the product key associated with this line item. */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /** Gets the product variant ID associated with this line item. */\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 variant attributes. */\r\n getAttributes(): { color: Color } {\r\n return { ...this.attributes };\r\n }\r\n\r\n /** Gets the image information model for this line item. */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /** Gets the sub-items (size/quantity breakdown). */\r\n getSubItems(): SubItem[] {\r\n return this.subItems.map(item => ({ ...item }));\r\n }\r\n\r\n /** Gets the total quantity for this line item across all sub-items. */\r\n getTotalQuantity(): number {\r\n return this.totalQuantity;\r\n }\r\n\r\n /** Gets the base price for a single unit. */\r\n getBasePrice(): BasePrice {\r\n return { ...this.basePrice };\r\n }\r\n\r\n /** Gets the calculated price details (subtotal, mrpTotal) for this line item. */\r\n getPriceTotals(): { subtotal: number; mrpTotal: number } {\r\n return { ...this.priceTotals };\r\n }\r\n\r\n /** Gets the applicable price tiers for this product variant. */\r\n getPriceTiers(): PriceTier[] {\r\n return this.priceTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Recalculates the total quantity based on the quantities in subItems.\r\n */\r\n protected recalculateTotalQuantity(): void {\r\n this.totalQuantity = this.subItems.reduce((sum, item) => sum + item.quantity, 0);\r\n }\r\n\r\n /**\r\n * Recalculates the line item's price (subtotal and mrpTotal)\r\n * based on total quantity, base price, and applicable price tiers.\r\n */\r\n protected recalculatePriceTotal(): void {\r\n const quantity = this.totalQuantity;\r\n let unitPrice = this.basePrice.unitPrice;\r\n\r\n let applicableTier = null;\r\n for (const tier of this.priceTiers.sort((a, b) => b.minQuantity - a.minQuantity)) { \r\n if (quantity >= tier.minQuantity) {\r\n applicableTier = tier;\r\n break;\r\n }\r\n }\r\n\r\n if (applicableTier) {\r\n unitPrice = applicableTier.unitPrice;\r\n }\r\n\r\n // Calculate totals\r\n this.priceTotals.mrpTotal = this.basePrice.unitPrice * quantity;\r\n this.priceTotals.subtotal = unitPrice * quantity;\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n attributes: this.getAttributes(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n totalQuantity: this.getTotalQuantity(),\r\n basePrice: this.getBasePrice(),\r\n priceTotals: this.getPriceTotals(),\r\n priceTiers: this.getPriceTiers(),\r\n };\r\n }\r\n \r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * Recalculates total quantity and price totals afterwards.\r\n *\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity);\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price totals afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n this.id = '';\r\n this.productKey = '';\r\n this.variantId = '';\r\n this.name = { en: '' };\r\n this.attributes = { color: { name: '', hex: '' } };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/ImageInfo.ts","../../src/Classes/LineItem.ts"],"names":["ImageInfoModel","data","resolutionKey","altText","order","label","url","LineItemModel","item","tier","locale","sum","quantity","unitPrice","applicableTier","b","subItems","addQuantity","subItem","existingSubItem","sub"],"mappings":"aAoBA,IAAqBA,CAArB,CAAA,KAAoC,CACxB,OAAA,CACA,IACA,KACA,CAAA,KAAA,CAMV,WAAYC,CAAAA,CAAAA,CAA0B,CAMpC,GALA,IAAK,CAAA,OAAA,CAAU,CAAE,GAAGA,CAAAA,CAAK,OAAQ,CAAA,CACjC,IAAK,CAAA,GAAA,CAAMA,CAAK,CAAA,GAAA,CAChB,KAAK,KAAQA,CAAAA,CAAAA,CAAK,KAClB,CAAA,IAAA,CAAK,MAAQA,CAAK,CAAA,KAAA,CAEd,CAAC,IAAA,CAAK,QAAQ,QACd,CAAA,MAAO,oEAEb,CAMA,UAAa,EAAA,CACX,OAAO,CAAE,GAAG,IAAK,CAAA,OAAQ,CAC3B,CAOA,UAAUC,CAAuC,CAAA,CAC/C,OAAO,IAAA,CAAK,QAAQA,CAAa,CAAA,EAAK,IAAK,CAAA,OAAA,CAAQ,QACrD,CAKA,MAA6B,EAAA,CAC3B,OAAO,IAAK,CAAA,GACd,CAKA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IAAIpB,CAAe,CAAA,CAAE,OAAS,CAAA,CAAE,QAAU,CAAA,EAAG,CAAE,CAAC,EACpE,IAAK,CAAA,QAAA,CAAW,EAAC,CACjB,KAAK,wBAAyB,EAAA,CAC9B,IAAK,CAAA,qBAAA,GACP,CACF","file":"LineItem.js","sourcesContent":["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 { BasePrice, Color, LocaleCode, LocalizedString, PriceTier } from \"./Common\";\r\nimport ImageInfoModel, { ImageInfoData } from \"./ImageInfo\";\r\nimport { LocalizedProductSpecification, ProductSpecification } from \"./Product\";\r\n\r\nexport type SubItem = {\r\n size: string;\r\n quantity: number;\r\n};\r\n\r\nexport type LineItemAttributes = {\r\n id: string;\r\n productKey: string;\r\n variantId: string;\r\n name: LocalizedString;\r\n attributes: {\r\n color: Color;\r\n };\r\n specifications: LocalizedProductSpecification;\r\n primaryImage: ImageInfoData;\r\n subItems: SubItem[];\r\n basePrice: BasePrice;\r\n priceTiers: PriceTier[];\r\n}\r\n\r\nexport type LineItemData = LineItemAttributes & {\r\n totalQuantity: number;\r\n priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n}\r\n\r\n/**\r\n * Represents a line item within a shopping cart.\r\n */\r\nexport default class LineItemModel {\r\n protected id: string;\r\n protected productKey: string;\r\n protected variantId: string;\r\n protected name: LocalizedString;\r\n protected attributes: {\r\n color: Color;\r\n };\r\n protected specifications: LocalizedProductSpecification;\r\n protected primaryImage: ImageInfoModel;\r\n protected subItems: SubItem[];\r\n protected totalQuantity: number;\r\n protected basePrice: BasePrice;\r\n protected priceTotals: {\r\n subtotal: number;\r\n mrpTotal: number;\r\n };\r\n protected priceTiers: PriceTier[];\r\n\r\n /**\r\n * Creates an instance of LineItemModel.\r\n * @param data - The initial line item attributes.\r\n */\r\n constructor(data: LineItemAttributes) {\r\n this.id = data.id;\r\n this.productKey = data.productKey;\r\n this.variantId = data.variantId;\r\n\r\n this.name = { ...data.name };\r\n this.attributes = { ...data.attributes };\r\n this.specifications = {...data.specifications };\r\n this.primaryImage = new ImageInfoModel(data.primaryImage);\r\n this.subItems = data.subItems.map(item => ({ ...item }));\r\n this.basePrice = { ...data.basePrice };\r\n this.priceTiers = data.priceTiers.map(tier => ({ ...tier }));\r\n\r\n this.totalQuantity = 0;\r\n this.priceTotals = {\r\n subtotal: 0,\r\n mrpTotal: 0\r\n };\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /** Gets the unique identifier of the line item. */\r\n getId(): string {\r\n return this.id;\r\n }\r\n\r\n /** Gets the product key associated with this line item. */\r\n getProductKey(): string {\r\n return this.productKey;\r\n }\r\n\r\n /** Gets the product variant ID associated with this line item. */\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 variant attributes. */\r\n getAttributes(): { color: Color } {\r\n return { ...this.attributes };\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 /** Gets the image information model for this line item. */\r\n getImage(): ImageInfoModel {\r\n return this.primaryImage;\r\n }\r\n\r\n /** Gets the sub-items (size/quantity breakdown). */\r\n getSubItems(): SubItem[] {\r\n return this.subItems.map(item => ({ ...item }));\r\n }\r\n\r\n /** Gets the total quantity for this line item across all sub-items. */\r\n getTotalQuantity(): number {\r\n return this.totalQuantity;\r\n }\r\n\r\n /** Gets the base price for a single unit. */\r\n getBasePrice(): BasePrice {\r\n return { ...this.basePrice };\r\n }\r\n\r\n /** Gets the calculated price details (subtotal, mrpTotal) for this line item. */\r\n getPriceTotals(): { subtotal: number; mrpTotal: number } {\r\n return { ...this.priceTotals };\r\n }\r\n\r\n /** Gets the applicable price tiers for this product variant. */\r\n getPriceTiers(): PriceTier[] {\r\n return this.priceTiers.map(tier => ({ ...tier }));\r\n }\r\n\r\n /**\r\n * Recalculates the total quantity based on the quantities in subItems.\r\n */\r\n protected recalculateTotalQuantity(): void {\r\n this.totalQuantity = this.subItems.reduce((sum, item) => sum + item.quantity, 0);\r\n }\r\n\r\n /**\r\n * Recalculates the line item's price (subtotal and mrpTotal)\r\n * based on total quantity, base price, and applicable price tiers.\r\n */\r\n protected recalculatePriceTotal(): void {\r\n const quantity = this.totalQuantity;\r\n let unitPrice = this.basePrice.unitPrice;\r\n\r\n let applicableTier = null;\r\n for (const tier of this.priceTiers.sort((a, b) => b.minQuantity - a.minQuantity)) { \r\n if (quantity >= tier.minQuantity) {\r\n applicableTier = tier;\r\n break;\r\n }\r\n }\r\n\r\n if (applicableTier) {\r\n unitPrice = applicableTier.unitPrice;\r\n }\r\n\r\n // Calculate totals\r\n this.priceTotals.mrpTotal = this.basePrice.unitPrice * quantity;\r\n this.priceTotals.subtotal = unitPrice * quantity;\r\n }\r\n\r\n\r\n /**\r\n * Gets a plain data object representing the line item's details.\r\n * @returns LineItemData.\r\n */\r\n getDetails(): LineItemData {\r\n return {\r\n id: this.getId(),\r\n productKey: this.getProductKey(),\r\n variantId: this.getVariantId(),\r\n name: this.getName(),\r\n attributes: this.getAttributes(),\r\n specifications: this.getSpecifications(),\r\n primaryImage: this.getImage().getDetails(),\r\n subItems: this.getSubItems(),\r\n totalQuantity: this.getTotalQuantity(),\r\n basePrice: this.getBasePrice(),\r\n priceTotals: this.getPriceTotals(),\r\n priceTiers: this.getPriceTiers(),\r\n };\r\n }\r\n \r\n /**\r\n * Adds or updates sub-items (e.g., sizes with quantities) to the line item.\r\n * If a sub-item with the same size already exists, its quantity is either\r\n * updated by adding the new quantity or replaced entirely, based on the `addQuantity` flag.\r\n * Sub-items with a resulting quantity of 0 are removed.\r\n * Recalculates total quantity and price totals afterwards.\r\n *\r\n * @param subItems - An array of `SubItem` objects to add or update.\r\n * @param addQuantity - If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n */\r\n addSubItems(subItems: SubItem[], addQuantity: boolean): void {\r\n subItems.forEach(subItem => {\r\n const existingSubItem = this.subItems.find(item => item.size === subItem.size);\r\n if (existingSubItem) {\r\n existingSubItem.quantity = addQuantity ? existingSubItem.quantity + subItem.quantity : subItem.quantity;\r\n } else {\r\n this.subItems.push(subItem);\r\n }\r\n })\r\n this.subItems = this.subItems.filter(sub => sub.quantity);\r\n\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n\r\n /**\r\n * Resets the line item's properties to their default empty or initial state.\r\n * Useful for clearing out line item data without creating a new instance.\r\n * Recalculates total quantity and price totals afterwards (which will be zero).\r\n */\r\n clearLineItem(): void {\r\n this.id = '';\r\n this.productKey = '';\r\n this.variantId = '';\r\n this.name = { en: '' };\r\n this.attributes = { color: { name: '', hex: '' } };\r\n this.primaryImage = new ImageInfoModel({ sources: { original: '' } });\r\n this.subItems = [];\r\n this.recalculateTotalQuantity();\r\n this.recalculatePriceTotal();\r\n }\r\n}"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as default}from'../chunk-
|
|
1
|
+
export{a as default}from'../chunk-STQZVQ7K.mjs';import'../chunk-DKI6BDWK.mjs';//# sourceMappingURL=LineItem.mjs.map
|
|
2
2
|
//# sourceMappingURL=LineItem.mjs.map
|
package/dist/Classes/Order.d.mts
CHANGED
package/dist/Classes/Order.d.ts
CHANGED
package/dist/Classes/Order.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var l=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,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var p=class extends l{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 g=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 m=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 g(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,o)=>o.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 g({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var C={IN:"INR"},D={INR:"\u20B9"};var u=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){return n.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,o=C[e];if(o===void 0)throw new Error("Currency mapping not found for CountryCode");let c=t,b=s?0:n.getDecimalPlaces(o),a={style:r.style??"currency",currency:o,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:b,maximumFractionDigits:b};s&&(c=Math.round(c));try{return new Intl.NumberFormat(i,a).format(c)}catch(S){return console.error(`Error formatting price for country "${e}" and currency "${o}":`,S),`${D[o]??o} ${n.addThousandSeparators(c.toFixed(b))}`}}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=C[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 C[t]}};var h=class extends l{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 I=class extends l{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 m(i)),this.billingAddress=t.billingAddress?new p(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new p(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new h(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=u.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=u.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 m(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new p(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new p(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new h(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(),o=0,c=r==="SHIPPING"?this.total.shipping:this.total.subtotal;if(c<=0)return 0;switch(s){case"flat":let a=i?.price??0;o=Math.min(c,a);break;case"percentage":o=c*(t.getPercentageValue()/100);break;default:return 0}let b=Math.min(o,i.price);return u.getRoundedPrice(Math.max(0,b),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);}),u.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=u.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=u.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=u.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=u.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=u.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()}}};var y=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}};var f=(a=>(a.PLACED="PLACED",a.PENDING_PAYMENT="PENDING_PAYMENT",a.PROCESSING="PROCESSING",a.SHIPPED="SHIPPED",a.DELIVERED="DELIVERED",a.CANCELLED="CANCELLED",a.RETURNED="RETURNED",a.REFUNDED="REFUNDED",a.COMPLETED="COMPLETED",a))(f||{}),T=(s=>(s.INITIAL="INITIAL",s.PROCESSING="PROCESSING",s.SHIPPED="SHIPPED",s.DELIVERED="DELIVERED",s.CANCELLED="CANCELLED",s))(T||{}),A=class extends I{orderNumber;cartId;paymentStatus;holdReason;state;lineItemStateMap;constructor(t,e=new Date){super(t,e),this.orderNumber=t.orderNumber,this.cartId=t.cartId,this.paymentStatus=t.paymentStatus,this.holdReason=t.holdReason||"",this.state=t.state,this.lineItemStateMap={},t.lineItems.forEach(i=>{let r=this.lineItemStateMap[i.id];this.lineItemStateMap[i.id]={state:r?.state||"INITIAL",reason:r?.reason||"",transitionAt:r?.transitionAt||this.createdAt};});}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getShippingAddress(){return this.shippingAddress}getBillingAddress(){return this.billingAddress}getOrderNumber(){return this.orderNumber}getCartId(){return this.cartId}getPaymentStatus(){return this.paymentStatus}getHoldReason(){return this.holdReason}getState(){return this.state}getLineItemsStateMap(){return {...this.lineItemStateMap}}getLineItemState(t){if(!this.lineItemStateMap[t])throw new y(t);return this.lineItemStateMap[t].state}getDetails(){return {...super.getDetails(),orderNumber:this.getOrderNumber(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),shippingAddress:this.getShippingAddress().getDetails(),billingAddress:this.getBillingAddress().getDetails(),cartId:this.getCartId(),paymentStatus:this.getPaymentStatus(),holdReason:this.getHoldReason(),state:this.getState(),lineItemStateMap:this.getLineItemsStateMap()}}};exports.OrderLineItemState=T;exports.OrderState=f;exports.default=A;//# sourceMappingURL=Order.js.map
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var l=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,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var p=class extends l{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 g=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 h=class{id;productKey;variantId;name;attributes;specifications;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.specifications={...t.specifications},this.primaryImage=new g(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}}getSpecifications(t){return t?this.specifications[t]??this.specifications.en:JSON.parse(JSON.stringify(this.specifications))}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,o)=>o.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(),specifications:this.getSpecifications(),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 g({sources:{original:""}}),this.subItems=[],this.recalculateTotalQuantity(),this.recalculatePriceTotal();}};var C={IN:"INR"},f={INR:"\u20B9"};var u=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){return n.getFormattedString(this.price,this.country,t)}static getFormattedString(t,e,i,r={}){let s=r.displayAsInteger??!1,o=C[e];if(o===void 0)throw new Error("Currency mapping not found for CountryCode");let d=t,b=s?0:n.getDecimalPlaces(o),a={style:r.style??"currency",currency:o,signDisplay:"never",currencyDisplay:r.currencyDisplay,minimumFractionDigits:b,maximumFractionDigits:b};s&&(d=Math.round(d));try{return new Intl.NumberFormat(i,a).format(d)}catch(D){return console.error(`Error formatting price for country "${e}" and currency "${o}":`,D),`${f[o]??o} ${n.addThousandSeparators(d.toFixed(b))}`}}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=C[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 C[t]}};var m=class extends l{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 I=class extends l{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 h(i)),this.billingAddress=t.billingAddress?new p(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new p(t.shippingAddress,e):null,this.coupons=(t.coupons||[]).map(i=>new m(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=u.getRoundedPrice(this.lineItems.reduce((t,e)=>t+e.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=u.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 h(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new p(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new p(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons.map(t=>new m(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(),o=0,d=r==="SHIPPING"?this.total.shipping:this.total.subtotal;if(d<=0)return 0;switch(s){case"flat":let a=i?.price??0;o=Math.min(d,a);break;case"percentage":o=d*(t.getPercentageValue()/100);break;default:return 0}let b=Math.min(o,i.price);return u.getRoundedPrice(Math.max(0,b),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);}),u.getRoundedPrice(t,this.country)}updateCartTotals(){this.total.subtotal=u.getRoundedPrice(this.lineItems.reduce((r,s)=>r+s.getPriceTotals().subtotal,0),this.country),this.total.mrpTotal=u.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=u.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=u.getRoundedPrice(Math.max(0,i-e),this.country);}setShippingDetails(t){this.shippingDetails=t?{...t}:null,this.total.shipping=u.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()}}};var y=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}};var S=(a=>(a.PLACED="PLACED",a.PENDING_PAYMENT="PENDING_PAYMENT",a.PROCESSING="PROCESSING",a.SHIPPED="SHIPPED",a.DELIVERED="DELIVERED",a.CANCELLED="CANCELLED",a.RETURNED="RETURNED",a.REFUNDED="REFUNDED",a.COMPLETED="COMPLETED",a))(S||{}),T=(s=>(s.INITIAL="INITIAL",s.PROCESSING="PROCESSING",s.SHIPPED="SHIPPED",s.DELIVERED="DELIVERED",s.CANCELLED="CANCELLED",s))(T||{}),A=class extends I{orderNumber;cartId;paymentStatus;holdReason;state;lineItemStateMap;constructor(t,e=new Date){super(t,e),this.orderNumber=t.orderNumber,this.cartId=t.cartId,this.paymentStatus=t.paymentStatus,this.holdReason=t.holdReason||"",this.state=t.state,this.lineItemStateMap={},t.lineItems.forEach(i=>{let r=this.lineItemStateMap[i.id];this.lineItemStateMap[i.id]={state:r?.state||"INITIAL",reason:r?.reason||"",transitionAt:r?.transitionAt||this.createdAt};});}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getShippingAddress(){return this.shippingAddress}getBillingAddress(){return this.billingAddress}getOrderNumber(){return this.orderNumber}getCartId(){return this.cartId}getPaymentStatus(){return this.paymentStatus}getHoldReason(){return this.holdReason}getState(){return this.state}getLineItemsStateMap(){return {...this.lineItemStateMap}}getLineItemState(t){if(!this.lineItemStateMap[t])throw new y(t);return this.lineItemStateMap[t].state}getDetails(){return {...super.getDetails(),orderNumber:this.getOrderNumber(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),shippingAddress:this.getShippingAddress().getDetails(),billingAddress:this.getBillingAddress().getDetails(),cartId:this.getCartId(),paymentStatus:this.getPaymentStatus(),holdReason:this.getHoldReason(),state:this.getState(),lineItemStateMap:this.getLineItemsStateMap()}}};exports.OrderLineItemState=T;exports.OrderState=S;exports.default=A;//# sourceMappingURL=Order.js.map
|
|
2
2
|
//# sourceMappingURL=Order.js.map
|