feeef 0.4.14 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,7 @@ A TypeScript service for managing shopping carts in e-commerce platforms. It all
13
13
  - **Cart management**: Add, remove, toggle cart items.
14
14
  - **Shipping management**: Set shipping method and address.
15
15
  - **Subtotal and total calculation**: Calculate total prices with or without shipping.
16
+ - **Product offers**: Support for product-specific offers with quantity constraints.
16
17
  - **Reactive updates**: Use listeners to react to cart changes, useful in React or other reactive UI frameworks.
17
18
  - **Customization**: Flexible enough to handle product variants and shipping policies.
18
19
 
@@ -47,11 +48,20 @@ const cart = new CartService()
47
48
  cart.setCurrentItem({ product, quantity: 2 })
48
49
  cart.addCurrentItemToCart()
49
50
 
51
+ // Apply an offer to the cart item
52
+ cart.updateCurrentItemOffer({
53
+ code: "SUMMER2024",
54
+ title: "Summer Sale",
55
+ price: 899.99,
56
+ minQuantity: 2, // Must buy at least 2
57
+ maxQuantity: 5 // Cannot buy more than 5 with this offer
58
+ })
59
+
50
60
  // Set shipping method (from store)
51
61
  cart.setShippingMethod(store)
52
62
 
53
63
  // Calculate totals
54
- console.log('Subtotal:', cart.getSubtotal()) // 2000
64
+ console.log('Subtotal:', cart.getSubtotal()) // 1799.98 (2 * 899.99)
55
65
  console.log('Total with shipping:', cart.getTotal()) // Includes shipping if set
56
66
 
57
67
  // Example listener to track cart changes
@@ -156,6 +166,12 @@ cart.removeListener(listener) // Removes the previously added listener
156
166
  - **`removeListener(listener: Listener<CartService>): void`**
157
167
  Removes a previously registered listener.
158
168
 
169
+ - **`updateItemOffer(itemId: string, offer?: ProductOffer): void`**
170
+ Updates or removes an offer for a specific cart item. The offer can include price overrides and quantity constraints.
171
+
172
+ - **`updateCurrentItemOffer(offer?: ProductOffer): void`**
173
+ Updates or removes an offer for the current cart item.
174
+
159
175
  ### NotifiableService
160
176
 
161
177
  #### Methods
@@ -169,6 +185,19 @@ cart.removeListener(listener) // Removes the previously added listener
169
185
  - **`notify(): void`**
170
186
  Notifies all registered listeners.
171
187
 
188
+ ### ProductOffer Interface
189
+
190
+ ```typescript
191
+ interface ProductOffer {
192
+ code: string // Unique identifier for the offer
193
+ title: string // Display title for the offer
194
+ subtitle?: string // Optional subtitle/description
195
+ price?: number // Optional fixed price override
196
+ minQuantity?: number // Minimum quantity required for the offer
197
+ maxQuantity?: number // Maximum quantity allowed for the offer
198
+ }
199
+ ```
200
+
172
201
  ## Best Practices
173
202
 
174
203
  1. **Use Listeners for UI updates**: In reactive frameworks like React, use `addListener` to trigger state updates or side effects based on changes in the `CartService`.
@@ -177,6 +206,10 @@ cart.removeListener(listener) // Removes the previously added listener
177
206
 
178
207
  3. **Optimize with Cached Subtotals**: The `CartService` uses caching for subtotals to avoid recalculations. Rely on `getSubtotal()` and `getTotal()` for efficient price calculations.
179
208
 
209
+ 4. **Handle Offer Constraints**: When applying offers with quantity constraints, the cart will automatically adjust quantities to be within the valid range.
210
+
211
+ 5. **Price Overrides**: When using offers with fixed prices, they take precedence over regular product pricing and discounts.
212
+
180
213
  ## Contributing
181
214
 
182
- Feel free to fork this repository and contribute improvements, bug fixes, or additional features. Open a pull request for any major changes!
215
+ Feel free to fork this repository and contribute improvements, bug fixes, or additional features. Open a pull request for any major changes!
package/build/index.js CHANGED
@@ -345,6 +345,21 @@ var CartService = class extends NotifiableService {
345
345
  this.notify();
346
346
  }
347
347
  }
348
+ /**
349
+ * Clamps the quantity to be within the offer's min/max range
350
+ * @param offer - The offer containing quantity constraints
351
+ * @param quantity - The quantity to clamp
352
+ * @returns The clamped quantity value
353
+ */
354
+ clampQuantityToOfferLimits(offer, quantity) {
355
+ if (offer.minQuantity !== void 0) {
356
+ quantity = Math.max(quantity, offer.minQuantity);
357
+ }
358
+ if (offer.maxQuantity !== void 0) {
359
+ quantity = Math.min(quantity, offer.maxQuantity);
360
+ }
361
+ return quantity;
362
+ }
348
363
  /**
349
364
  * Update item by id.
350
365
  * @param id - The id of the item to update.
@@ -353,7 +368,11 @@ var CartService = class extends NotifiableService {
353
368
  updateItem(id, item, notify = true) {
354
369
  const currentItem = this.items.get(id);
355
370
  if (currentItem) {
356
- this.items.set(id, { ...currentItem, ...item });
371
+ const newItem = { ...currentItem, ...item };
372
+ if (newItem.offer) {
373
+ newItem.quantity = this.clampQuantityToOfferLimits(newItem.offer, newItem.quantity);
374
+ }
375
+ this.items.set(id, newItem);
357
376
  this.cachedSubtotal = null;
358
377
  if (notify) {
359
378
  this.notify();
@@ -523,6 +542,17 @@ var CartService = class extends NotifiableService {
523
542
  }
524
543
  return (price - discount) * quantity;
525
544
  }
545
+ /**
546
+ * Validates if an offer can be applied to the given quantity
547
+ * @param offer - The offer to validate
548
+ * @param quantity - The quantity to check
549
+ * @returns boolean indicating if the offer is valid for the quantity
550
+ */
551
+ isOfferValidForQuantity(offer, quantity) {
552
+ if (offer.minQuantity && quantity < offer.minQuantity) return false;
553
+ if (offer.maxQuantity && quantity > offer.maxQuantity) return false;
554
+ return true;
555
+ }
526
556
  /**
527
557
  * Updates the offer for a specific cart item
528
558
  * @param itemId - The ID of the item to update
@@ -530,11 +560,12 @@ var CartService = class extends NotifiableService {
530
560
  */
531
561
  updateItemOffer(itemId, offer) {
532
562
  const item = this.items.get(itemId);
533
- console.log("item0", item);
534
- if (item) {
535
- this.updateItem(itemId, { ...item, offer });
536
- console.log("item1", item);
563
+ if (!item) return;
564
+ const updatedItem = { ...item, offer };
565
+ if (offer) {
566
+ updatedItem.quantity = this.clampQuantityToOfferLimits(offer, item.quantity);
537
567
  }
568
+ this.updateItem(itemId, updatedItem);
538
569
  this.cachedSubtotal = null;
539
570
  this.notifyIfChanged();
540
571
  }
@@ -543,9 +574,13 @@ var CartService = class extends NotifiableService {
543
574
  * @param offer - The offer to apply, or undefined to remove the offer
544
575
  */
545
576
  updateCurrentItemOffer(offer) {
546
- if (this.currentItem) {
547
- this.updateCurrentItem({ offer });
577
+ if (!this.currentItem) return;
578
+ const updatedItem = { ...this.currentItem };
579
+ updatedItem.offer = offer;
580
+ if (offer) {
581
+ updatedItem.quantity = this.clampQuantityToOfferLimits(offer, this.currentItem.quantity);
548
582
  }
583
+ this.updateCurrentItem(updatedItem);
549
584
  this.cachedSubtotal = null;
550
585
  this.notifyIfChanged();
551
586
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/feeef/feeef.ts","../src/feeef/repositories/repository.ts","../src/feeef/repositories/orders.ts","../src/feeef/repositories/products.ts","../src/feeef/repositories/stores.ts","../src/feeef/repositories/users.ts","../src/core/entities/order.ts","../src/core/entities/shipping_method.ts","../src/feeef/services/service.ts","../src/feeef/services/cart.ts","../src/core/entities/store.ts","../src/core/entities/product.ts","../src/core/embadded/contact.ts","../src/utils.ts"],"sourcesContent":["import axios, { AxiosInstance } from 'axios'\n// import { buildMemoryStorage, buildWebStorage, setupCache } from 'axios-cache-interceptor'\nimport { OrderRepository } from './repositories/orders.js'\nimport { ProductRepository } from './repositories/products.js'\nimport { StoreRepository } from './repositories/stores.js'\nimport { UserRepository } from './repositories/users.js'\nimport { CartService } from './services/cart.js'\n\n/**\n * Configuration options for the FeeeF module.\n */\nexport interface FeeeFConfig {\n /**\n * The API key to be used for authentication.\n */\n apiKey: string\n\n /**\n * An optional Axios instance to be used for making HTTP requests.\n */\n client?: AxiosInstance\n\n /**\n * Specifies whether caching should be enabled or disabled.\n * If set to a number, it represents the maximum number of seconds to cache the responses.\n * If set to `false`, caching will be disabled (5s).\n * cannot be less than 5 seconds\n */\n cache?: false | number\n\n /**\n * The base URL for the API.\n */\n baseURL?: string\n}\n\n/**\n * Represents the FeeeF class.\n */\nexport class FeeeF {\n /**\n * The API key used for authentication.\n */\n apiKey: string\n\n /**\n * The Axios instance used for making HTTP requests.\n */\n client: AxiosInstance\n\n /**\n * The repository for managing stores.\n */\n stores: StoreRepository\n\n /**\n * The repository for managing products.\n */\n products: ProductRepository\n\n /**\n * The repository for managing users.\n */\n users: UserRepository\n\n /**\n * The repository for managing orders.\n */\n orders: OrderRepository\n\n /**\n * The cart service for managing the cart.\n */\n cart: CartService\n\n /**\n * Constructs a new instance of the FeeeF class.\n * @param {FeeeFConfig} config - The configuration object.\n * @param {string} config.apiKey - The API key used for authentication.\n * @param {AxiosInstance} config.client - The Axios instance used for making HTTP requests.\n * @param {boolean | number} config.cache - The caching configuration. Set to `false` to disable caching, or provide a number to set the cache TTL in milliseconds.\n */\n //\n constructor({ apiKey, client, cache, baseURL = 'http://localhost:3333/api/v1' }: FeeeFConfig) {\n console.log(cache)\n this.apiKey = apiKey\n // get th \"cache\" search param\n // const urlParams = new URLSearchParams(window.location.search)\n // const cacheParam = urlParams.get('cache')\n // if is 0 or false, disable cache\n // if (cacheParam == '0') {\n this.client = client || axios\n // } else {\n // this.client = setupCache(client || axios, {\n // ttl: cache === false ? 5 : Math.max(cache!, 5) || 1 * 60 * 1000, // 1 minute by default\n // // for persistent cache use buildWebStorage\n // storage: buildWebStorage(localStorage, 'ff:'),\n // })\n // }\n // set base url\n this.client.defaults.baseURL = baseURL\n this.stores = new StoreRepository(this.client)\n this.products = new ProductRepository(this.client)\n this.users = new UserRepository(this.client)\n this.orders = new OrderRepository(this.client)\n\n // cart\n this.cart = new CartService()\n }\n}\n","import { AxiosInstance } from 'axios'\n\n/**\n * Represents a generic model repository.\n * @template T - The type of the model.\n * @template C - The type of the create options.\n * @template U - The type of the update options.\n */\nexport abstract class ModelRepository<T, C, U> {\n resource: string\n // client\n client: AxiosInstance\n\n /**\n * Constructs a new instance of the ModelRepository class.\n * @param resource - The resource name.\n * @param client - The Axios instance used for making HTTP requests.\n */\n constructor(resource: string, client: AxiosInstance) {\n this.resource = resource\n this.client = client\n }\n\n /**\n * Finds a model by its ID or other criteria.\n * @param options - The options for finding the model.\n * @returns A promise that resolves to the found model.\n */\n async find(options: ModelFindOptions): Promise<T> {\n const { id, by, params } = options\n const res = await this.client.get(`/${this.resource}/${id}`, {\n params: {\n by: by || 'id',\n ...params,\n },\n })\n return res.data\n }\n\n /**\n * Lists models with optional pagination and filtering.\n * @param options - The options for listing the models.\n * @returns A promise that resolves to a list of models.\n */\n async list(options?: ModelListOptions): Promise<ListResponse<T>> {\n const { page, offset, limit, params } = options || {}\n const res = await this.client.get(`/${this.resource}`, {\n params: { page, offset, limit, ...params },\n })\n // if res.data is an array then create ListResponse\n if (Array.isArray(res.data)) {\n return {\n data: res.data,\n }\n } else {\n return {\n data: res.data.data,\n total: res.data.meta.total,\n page: res.data.meta.currentPage,\n limit: res.data.meta.perPage,\n }\n }\n }\n\n /**\n * Creates a new model.\n * @param options - The options for creating the model.\n * @returns A promise that resolves to the created model.\n */\n async create(options: ModelCreateOptions<C>): Promise<T> {\n const { data, params } = options\n const res = await this.client.post(`/${this.resource}`, data, { params })\n return res.data\n }\n\n /**\n * Updates an existing model.\n * @param options - The options for updating the model.\n * @returns A promise that resolves to the updated model.\n */\n async update(options: ModelUpdateOptions<U>): Promise<T> {\n const { id, data, params } = options\n const res = await this.client.put(`/${this.resource}/${id}`, data, {\n params,\n })\n return res.data\n }\n\n /**\n * Deletes a model by its ID or other criteria.\n * @param options - The options for deleting the model.\n * @returns A promise that resolves when the model is deleted.\n */\n async delete(options: ModelFindOptions): Promise<void> {\n const { id, by, params } = options\n await this.client.delete(`/${this.resource}/${id}`, {\n params: {\n by: by || 'id',\n ...params,\n },\n })\n }\n}\n\n/**\n * Represents a list response containing an array of data of type T.\n */\nexport interface ListResponse<T> {\n data: T[]\n total?: number\n page?: number\n limit?: number\n}\n\n/**\n * Represents the options for making a request.\n */\ninterface RequestOptions {\n params?: Record<string, any>\n}\n\nexport interface ModelFindOptions extends RequestOptions {\n /**\n * The ID of the model to find or the value to find by.\n */\n id: string\n /**\n * The field to find by.\n * @default \"id\" - The ID field.\n */\n by?: string\n}\n\n/**\n * Options for listing models.\n */\nexport interface ModelListOptions extends RequestOptions {\n /**\n * The page number to retrieve.\n */\n page?: number\n\n /**\n * The offset from the beginning of the list.\n */\n offset?: number\n\n /**\n * The maximum number of models to retrieve per page.\n */\n limit?: number\n}\n\n/**\n * Represents the options for creating a model.\n * @template T - The type of data being created.\n */\nexport interface ModelCreateOptions<T> extends RequestOptions {\n data: T\n}\n\n/**\n * Represents the options for updating a model.\n * @template T - The type of the data being updated.\n */\nexport interface ModelUpdateOptions<T> extends RequestOptions {\n /**\n * The ID of the model to update.\n */\n id: string\n /**\n * The data to update the model with.\n */\n data: T\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository } from './repository.js'\nimport { OrderEntity, OrderTrackEntity, ShippingType } from '../../core/entities/order.js'\n/**\n * Represents the options for tracking an order.\n */\nexport interface OrderModelTrackOptions {\n id: string\n params?: Record<string, any>\n}\n\nexport interface SendOrderSchema {\n id?: string // Order ID (optional)\n customerName?: string // Name of the customer (optional)\n customerNote?: string // Note from the customer (optional)\n customerPhone: string // Customer's phone number (required)\n shippingAddress?: string // Address for shipping (optional)\n shippingCity?: string // City for shipping (optional)\n shippingState?: string // State for shipping (optional)\n shippingType: ShippingType // Shipping type (required)\n shippingMethodId?: string // ID of the shipping method (optional)\n paymentMethodId?: string // ID of the payment method (optional)\n items: GuestOrderItemSchema[] // Array of order items, must have at least one item\n coupon?: string // Applied coupon code (optional)\n status: 'pending' | 'draft' // Order status (required)\n storeId: string // ID of the store (required)\n metadata?: any // Additional metadata (optional)\n}\n\n// Assuming GuestOrderItemSchema was defined elsewhere, define it here as well if needed.\nexport interface GuestOrderItemSchema {\n productId: string\n offerCode?: string\n variantPath?: string\n quantity: number\n}\n\n/**\n * Represents a repository for managing orders.\n */\nexport class OrderRepository extends ModelRepository<OrderEntity, any, any> {\n /**\n * Constructs a new OrderRepository instance.\n * @param client - The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('orders', client)\n }\n\n /**\n * Sends an order from an anonymous user.\n * @param data - The data representing the order to be sent.\n * @returns A Promise that resolves to the sent OrderEntity.\n */\n async send(data: SendOrderSchema): Promise<OrderEntity> {\n const output = data\n const res = await this.client.post(`/${this.resource}/send`, output)\n\n // Return the sent OrderEntity\n return res.data\n }\n\n /**\n * track the order by the order id\n * it will return the order status and history\n * @param options - The options for finding the model.\n * @returns A promise that resolves to the found model.\n */\n async track(options: OrderModelTrackOptions): Promise<OrderTrackEntity> {\n const { id, params } = options\n const res = await this.client.get(`/${this.resource}/${id}/track`, {\n params: {\n ...params,\n },\n })\n return res.data\n }\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository } from './repository.js'\nimport { ProductEntity } from '../../core/entities/product.js'\n\n/**\n * Represents a repository for managing products.\n */\nexport class ProductRepository extends ModelRepository<ProductEntity, any, any> {\n /**\n * Creates a new instance of the ProductRepository class.\n * @param client - The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('products', client)\n }\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository, ModelCreateOptions } from './repository.js'\nimport { StoreEntity } from '../../core/entities/store.js'\n\n/**\n * Repository for managing Store entities.\n */\nexport class StoreRepository extends ModelRepository<StoreEntity, any, any> {\n /**\n * Constructs a new StoreRepository instance.\n * @param client The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('stores', client)\n }\n\n /**\n * Creates a new Store entity.\n * @param options The options for creating the Store entity.\n * @returns A Promise that resolves to the created Store entity.\n */\n async create(options: ModelCreateOptions<any>): Promise<StoreEntity> {\n const output = options.data\n return super.create({ ...options, data: output })\n }\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository } from './repository.js'\nimport { AuthToken, UserEntity } from '../../core/entities/user.js'\n\n/**\n * Represents the response returned by the authentication process.\n */\nexport interface AuthResponse {\n token: AuthToken\n user: UserEntity\n}\n\n/**\n * Represents a repository for managing user data.\n * Extends the ModelRepository class.\n */\nexport class UserRepository extends ModelRepository<UserEntity, any, any> {\n /**\n * Represents the authentication response.\n */\n auth: AuthResponse | null = null\n\n /**\n * Constructs a new UserRepository instance.\n * @param client - The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('users', client)\n }\n\n /**\n * Signs in a user with the provided credentials.\n * @param credentials - The user credentials.\n * @returns A promise that resolves to the authentication response.\n */\n async signin(credentials: any): Promise<AuthResponse> {\n // validate the input\n const output = credentials\n const res = await this.client.post(`/${this.resource}/auth/signin`, output)\n this.auth = res.data\n return res.data\n }\n\n /**\n * Signs up a new user with the provided credentials.\n * @param credentials - The user credentials.\n * @returns A promise that resolves to the authentication response.\n */\n async signup(credentials: any): Promise<AuthResponse> {\n // validate the input\n const output = credentials\n const res = await this.client.post(`/${this.resource}/auth/signup`, output)\n this.auth = res.data\n return res.data\n }\n\n /**\n * Signs out the currently authenticated user.\n * @returns A promise that resolves when the user is signed out.\n */\n async signout(): Promise<void> {\n this.auth = null\n }\n\n /**\n * Updates the authenticated user's data.\n * @param data - The updated user data.\n * @returns A promise that resolves to the updated user entity.\n */\n async updateMe(data: any): Promise<UserEntity> {\n const output = data\n const res = await this.client.put(`/${this.resource}/auth`, output)\n return res.data\n }\n}\n","export enum OrderStatus {\n draft = 'draft',\n pending = 'pending',\n review = 'review',\n accepted = 'accepted',\n processing = 'processing',\n completed = 'completed',\n cancelled = 'cancelled',\n}\n\n// PaymentStatus\nexport enum PaymentStatus {\n unpaid = 'unpaid',\n paid = 'paid',\n received = 'received',\n}\nexport enum DeliveryStatus {\n pending = 'pending',\n delivering = 'delivering',\n delivered = 'delivered',\n returned = 'returned',\n}\n\nexport enum ShippingType {\n home = 'home',\n pickup = 'pickup',\n store = 'store',\n}\n\nexport interface OrderEntity {\n id: string\n customerName?: string | null\n customerPhone: string\n customerIp?: string | null\n shippingAddress?: string | null\n shippingCity?: string | null\n shippingState?: string | null\n shippingMethodId?: string | null\n shippingType: ShippingType\n paymentMethodId?: string | null\n items: OrderItem[]\n subtotal: number\n shippingPrice: number\n total: number\n discount: number\n coupon?: string | null\n storeId: string\n metadata: OrderMetadata\n status: OrderStatus\n paymentStatus: PaymentStatus\n deliveryStatus: DeliveryStatus\n createdAt: any\n updatedAt: any\n}\nexport interface OrderItem {\n productId: string\n productName: string\n productPhotoUrl?: string | null\n variantPath?: string\n quantity: number\n price: number\n offerCode?: string | null\n offerName?: string | null\n}\n\n// order track entity\nexport interface OrderTrackEntity {\n id: string\n customerName?: string | null\n items: OrderItem[]\n total: number\n createdAt: any\n storeId: string\n status: OrderStatus\n history: OrderTrackHistory[]\n}\n\n// order track history\nexport interface OrderTrackHistory {\n status: OrderStatus\n deliveryStatus: string\n paymentStatus: string\n createdAt: string\n}\n\n// order metadata history\ninterface OrderMetadataHistory {\n status: OrderStatus\n deliveryStatus: string\n paymentStatus: string\n createdAt: string\n message: string\n code: string\n userId: string\n}\n\n// order metadata\ninterface OrderMetadata {\n note?: string\n history?: OrderMetadataHistory[]\n metaPixel?: any\n customOrderTagHistories?: any[]\n [key: string]: any\n}\n\n// utils\n// order entity to order track entity\nexport const convertOrderEntityToOrderTrackEntity = (order: OrderEntity): OrderTrackEntity => {\n return {\n id: order.id,\n customerName: order.customerName,\n items: order.items,\n total: order.total,\n createdAt: order.createdAt,\n storeId: order.storeId,\n status: order.status,\n history:\n order.metadata.history?.map((history) => ({\n status: history.status,\n deliveryStatus: history.deliveryStatus,\n paymentStatus: history.paymentStatus,\n createdAt: history.createdAt,\n })) || [],\n }\n}\n","import { OrderEntity } from './order.js'\n\nexport interface ShippingMethodEntity {\n id: string\n name: string\n description: string | null\n logoUrl: string | null\n ondarkLogoUrl: string | null\n price: number\n forks: number\n sourceId: string\n storeId: string\n rates: (number | null)[][] | null\n status: ShippingMethodStatus\n policy: ShippingMethodPolicy\n verifiedAt: any\n createdAt: any\n updatedAt: any\n orders: OrderEntity[]\n source: ShippingMethodEntity | null\n}\n\nexport enum ShippingMethodStatus {\n draft = 'draft',\n published = 'published',\n archived = 'archived',\n}\n\nexport enum ShippingMethodPolicy {\n private = 'private',\n public = 'public',\n}\n","export type Listener<T extends NotifiableService> = (service: T) => void\n\nexport class NotifiableService {\n // Array of listeners (functions) to notify when changes occur\n private listeners: Set<Listener<typeof this>> = new Set()\n\n /**\n * Adds a listener that gets called when `notify` is triggered.\n * @param listener - The function to be called on notification.\n * @returns The same listener for potential chaining or removal.\n */\n addListener(listener: Listener<typeof this>): Listener<typeof this> {\n this.listeners.add(listener) // Using Set for uniqueness and faster removal\n return listener\n }\n\n /**\n * Removes a previously added listener.\n * @param listener - The function to be removed from the listeners list.\n */\n removeListener(listener: Listener<typeof this>): void {\n this.listeners.delete(listener) // Set deletion is O(1) for better performance\n }\n\n /**\n * Notifies all registered listeners, passing the service instance.\n * This allows listeners to react to changes.\n */\n notify(): void {\n // Iterating over the Set of listeners and invoking each one\n this.listeners.forEach((listener) => listener(this))\n }\n\n /**\n * Clears all listeners, removing any references to them.\n */\n clearListeners(): void {\n this.listeners.clear() // Clears the Set entirely\n }\n\n /**\n * Constructor for NotifiableService, initializes listeners as an empty Set.\n * The Set ensures unique listeners and better management.\n */\n constructor() {\n // Initialization can be skipped since listeners is already initialized as an empty Set\n }\n}\n","import { ShippingType } from '../../core/entities/order.js'\nimport { ProductEntity, ProductOffer } from '../../core/entities/product.js'\nimport {\n ShippingMethodEntity,\n ShippingMethodPolicy,\n ShippingMethodStatus,\n} from '../../core/entities/shipping_method.js'\nimport { StoreEntity } from '../../core/entities/store.js'\nimport { NotifiableService } from './service.js'\n\n/**\n * Represents an item in the cart.\n */\nexport interface CartItem {\n product: ProductEntity\n offer?: ProductOffer\n quantity: number\n variantPath?: string\n}\n\n/**\n * Cart shipping types.\n * - `pickup`: The user will pick up the order from the closest desk.\n * - `home`: The order will be delivered to the user's home.\n * - `store`: The order will be delivered to the store.\n */\n// export type CartShippingTypes = 'pickup' | 'home' | 'store'\n\n/**\n * Interface for a shipping address.\n */\nexport interface CartShippingAddress {\n name: string | null\n phone: string | null\n city: string | null\n state: string | null\n street: string | null\n country: 'dz'\n type: ShippingType\n}\n\n/**\n * Manages the shopping cart and its operations.\n */\nexport class CartService extends NotifiableService {\n private items: Map<string, CartItem> = new Map() // Fast lookup of cart items\n private shippingMethod: ShippingMethodEntity | null = null\n private shippingAddress: CartShippingAddress = {\n name: null,\n phone: null,\n city: null,\n state: null,\n street: null,\n country: 'dz',\n type: ShippingType.pickup,\n }\n private cachedSubtotal: number | null = null // Cache for subtotal to avoid redundant calculations\n private currentItem: CartItem | null = null\n\n /**\n * Sets the current item to be managed in the cart.\n * @param item - The item to be set as current.\n */\n setCurrentItem(item: CartItem, notify = true): void {\n this.currentItem = item\n\n if (this.has(this.currentItem.product.id)) {\n this.items.set(this.currentItem.product.id, this.currentItem)\n }\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Update item by id.\n * @param id - The id of the item to update.\n * @param item - a partial item to update.\n */\n updateItem(id: string, item: Partial<CartItem>, notify = true): void {\n const currentItem = this.items.get(id)\n\n if (currentItem) {\n this.items.set(id, { ...currentItem, ...item })\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n }\n\n /**\n * Update current item.\n * @param item - a partial item to update.\n */\n updateCurrentItem(item: Partial<CartItem>, notify = true): void {\n if (!this.currentItem) return\n\n this.currentItem = { ...this.currentItem, ...item }\n\n if (this.has(this.currentItem.product.id)) {\n this.items.set(this.currentItem.product.id, this.currentItem)\n }\n\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Update shipping address.\n * @param address - a partial address to update.\n */\n updateShippingAddress(address: Partial<CartShippingAddress>, notify = true): void {\n this.shippingAddress = { ...this.shippingAddress, ...address }\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Update shipping method.\n * @param method - a partial shipping method to update.\n */\n updateShippingMethod(method: Partial<ShippingMethodEntity>, notify = true): void {\n if (!this.shippingMethod) return\n\n this.shippingMethod = { ...this.shippingMethod, ...method }\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Retrieves the current item in the cart.\n * @returns The current cart item or null if not set.\n */\n getCurrentItem(): CartItem | null {\n return this.currentItem\n }\n\n /**\n * Checks if the current item is already in the cart.\n * @returns True if the current item is in the cart, false otherwise.\n */\n isCurrentItemInCart(): boolean {\n return this.currentItem ? this.items.has(this.currentItem.product.id) : false\n }\n\n /**\n * Adds the current item to the cart if it's not already present.\n */\n addCurrentItemToCart(): void {\n if (!this.currentItem || this.isCurrentItemInCart()) return\n this.add(this.currentItem)\n this.cachedSubtotal = null\n }\n\n /**\n * Removes the current item from the cart if present.\n */\n removeCurrentItemFromCart(): void {\n if (this.currentItem) {\n this.remove(this.currentItem.product.id)\n }\n }\n\n /**\n * Toggles the current item's presence in the cart (add/remove).\n */\n toggleCurrentItemInCart(): void {\n this.isCurrentItemInCart() ? this.removeCurrentItemFromCart() : this.addCurrentItemToCart()\n }\n\n /**\n * Adds an item to the cart. If the item is already present, increments its quantity.\n * @param item - The cart item to add.\n */\n add(item: CartItem): void {\n const existingItem = this.items.get(item.product.id)\n\n if (existingItem) {\n existingItem.quantity += item.quantity\n } else {\n this.items.set(item.product.id, item)\n }\n\n this.cachedSubtotal = null // Reset subtotal cache\n this.notifyIfChanged()\n }\n\n /**\n * Checks if an item exists in the cart by product ID.\n * @param itemId - The ID of the item to check.\n * @returns True if the item exists in the cart, false otherwise.\n */\n has(itemId: string): boolean {\n return this.items.has(itemId)\n }\n\n /**\n * Removes an item from the cart by product ID.\n * @param itemId - The ID of the item to remove.\n */\n remove(itemId: string): void {\n if (this.items.delete(itemId)) {\n this.cachedSubtotal = null\n this.notifyIfChanged()\n }\n }\n\n /**\n * Clears all items from the cart.\n */\n clear(notify = true): void {\n if (this.items.size > 0) {\n this.items.clear()\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n }\n\n /**\n * Retrieves the subtotal of the cart.\n * @param withCurrentItem - Whether to include the current item in the subtotal.\n * @returns The subtotal amount.\n */\n getSubtotal(withCurrentItem = true): number {\n if (this.cachedSubtotal === null) {\n this.cachedSubtotal = Array.from(this.items.values()).reduce((sum, item) => {\n return sum + this.getItemTotal(item)\n }, 0)\n }\n\n if (withCurrentItem && this.currentItem && !this.has(this.currentItem.product.id)) {\n return this.cachedSubtotal + this.getItemTotal(this.currentItem)\n }\n\n return this.cachedSubtotal\n }\n\n /**\n * Calculates the total price for a cart item.\n * @param item - The cart item.\n * @returns The total price for the item.\n */\n getItemTotal(item: CartItem): number {\n const { product, variantPath, quantity, offer } = item\n let price = product.price\n let discount = product.discount ?? 0\n\n // Handle variant pricing if a variant path exists\n if (variantPath) {\n const parts = variantPath.split('/')\n let currentVariant = product.variant\n\n for (const part of parts) {\n if (!currentVariant) break\n const option = currentVariant.options.find((o) => o.name === part)\n if (!option) break\n price = option.price ?? price\n discount = option.discount ?? discount\n currentVariant = option.child\n }\n }\n\n // Apply offer if present\n if (offer) {\n if (offer.price !== undefined) {\n // If offer has a fixed price, use it\n price = offer.price\n discount = 0 // Reset discount since we're using a fixed price\n }\n }\n\n return (price - discount) * quantity\n }\n\n /**\n * Updates the offer for a specific cart item\n * @param itemId - The ID of the item to update\n * @param offer - The offer to apply, or undefined to remove the offer\n */\n updateItemOffer(itemId: string, offer?: ProductOffer): void {\n const item = this.items.get(itemId)\n console.log('item0', item)\n if (item) {\n this.updateItem(itemId, { ...item, offer })\n console.log('item1', item)\n }\n\n this.cachedSubtotal = null\n this.notifyIfChanged()\n }\n\n /**\n * Updates the offer for the current item\n * @param offer - The offer to apply, or undefined to remove the offer\n */\n updateCurrentItemOffer(offer?: ProductOffer): void {\n if (this.currentItem) {\n this.updateCurrentItem({ offer })\n }\n\n this.cachedSubtotal = null\n this.notifyIfChanged()\n }\n\n /**\n * Sets the shipping method.\n * @param method - Either a store or a shipping method.\n */\n setShippingMethod(method: ShippingMethodEntity | StoreEntity, notify = true): void {\n const store = (method as StoreEntity)?.defaultShippingRates ? (method as StoreEntity) : null\n const shippingMethod = (method as ShippingMethodEntity)?.rates\n ? (method as ShippingMethodEntity)\n : null\n\n if (store) {\n this.shippingMethod = {\n id: store.id,\n name: store.name,\n description: store.description,\n logoUrl: store.logoUrl,\n ondarkLogoUrl: store.ondarkLogoUrl,\n price: 0,\n forks: 0,\n sourceId: store.id,\n storeId: store.id,\n rates: store.defaultShippingRates,\n status: ShippingMethodStatus.published,\n policy: ShippingMethodPolicy.public,\n verifiedAt: null,\n createdAt: null,\n updatedAt: null,\n orders: [],\n source: null,\n }\n if (notify) {\n this.notify()\n }\n } else if (shippingMethod) {\n this.shippingMethod = shippingMethod\n if (notify) {\n this.notify()\n }\n } else {\n throw new Error('Invalid shipping method')\n }\n }\n\n // getAvailableShippingTypes\n /**\n * Retrieves the available shipping types for the current shipping method.\n *\n * rates is a 2D array for example `[[10, 20, 30], [5, 10, 15]]`\n * where the first array is for `home` fees and the second is for `pickup` fees, and the third is for `store` fees\n * if the fee value is 0, then it's free shipping, and if it's null, then it's not available\n *\n * @returns An array of available shipping types.\n */\n getAvailableShippingTypes(): ShippingType[] {\n if (!this.shippingMethod?.rates) return []\n\n var state = Number.parseInt(this.shippingAddress.state!)\n var stateRates = this.shippingMethod.rates[state - 1]\n\n if (!stateRates) return []\n\n var availableTypes: ShippingType[] = []\n\n if (stateRates[0] || stateRates[0] === 0) availableTypes.push(ShippingType.pickup)\n if (stateRates[1] || stateRates[1] === 0) availableTypes.push(ShippingType.home)\n if (stateRates[2] || stateRates[2] === 0) availableTypes.push(ShippingType.store)\n\n return availableTypes\n }\n\n /**\n * Retrieves the current shipping method.\n * @returns The shipping method or null.\n */\n getShippingMethod(): ShippingMethodEntity | null {\n return this.shippingMethod\n }\n\n /**\n * Sets the shipping address for the cart.\n * @param address - The shipping address.\n */\n setShippingAddress(address: CartShippingAddress, notify = true): void {\n if (\n this.shippingAddress.city !== address.city ||\n this.shippingAddress.state !== address.state ||\n this.shippingAddress.type !== address.type\n ) {\n this.shippingAddress = address\n if (notify) {\n this.notify()\n }\n }\n }\n\n /**\n * Retrieves the current shipping address.\n * @returns The shipping address.\n */\n getShippingAddress(): CartShippingAddress {\n return this.shippingAddress\n }\n\n /**\n * Calculates the shipping price based on the address and shipping method.\n * @returns The shipping price or 0 if not applicable.\n */\n getShippingPrice(): number {\n if (!this.shippingMethod) return 0\n if (!this.shippingAddress.state) return this.shippingMethod.price ?? 0\n\n const stateIndex = Number.parseInt(this.shippingAddress.state, 10) - 1\n const rates = this.shippingMethod.rates?.[stateIndex]\n\n return this.shippingAddress.type === 'pickup' ? (rates?.[0] ?? 0) : (rates?.[1] ?? 0)\n }\n\n /**\n * Calculates the total cost of the cart including shipping.\n * @param withCurrentItem - Whether to include the current item in the total.\n * @returns The total cost.\n */\n getTotal(withCurrentItem = true): number {\n return this.getSubtotal(withCurrentItem) + (this.getShippingPrice() ?? 0)\n }\n\n /**\n * Retrieves all items in the cart.\n * @returns An array of cart items.\n */\n getAll(): CartItem[] {\n return Array.from(this.items.values())\n }\n\n /**\n * Checks if the cart is empty.\n * @returns True if the cart is empty, otherwise false.\n */\n isEmpty(): boolean {\n return this.items.size === 0\n }\n\n /**\n * Notifies listeners if the cart state has meaningfully changed.\n */\n private notifyIfChanged(): void {\n // This method could be enhanced to track and notify only meaningful changes\n this.notify()\n }\n}\n","import { EmbaddedAddress } from '../embadded/address.js'\nimport { EmbaddedCategory } from '../embadded/category.js'\nimport { EmbaddedContact } from '../embadded/contact.js'\nimport { OrderEntity } from './order.js'\n// import { OrderEntity } from \"./order.js\";\n// import { ShippingMethodEntity } from \"./shipping_method.js\";\nimport { UserEntity } from './user.js'\nimport { DateTime } from 'luxon'\n\nexport interface StoreEntity {\n id: string\n slug: string\n banner: StoreBanner | null\n action: StoreAction | null\n domain: StoreDomain | null\n decoration: StoreDecoration | null\n name: string\n logoUrl: string | null\n ondarkLogoUrl: string | null\n userId: string\n categories: EmbaddedCategory[]\n title: string | null\n description: string | null\n addresses: EmbaddedAddress[]\n address: EmbaddedAddress | null\n metadata: Record<string, any>\n contacts: EmbaddedContact[]\n integrations: StoreIntegrations\n verifiedAt: any | null\n blockedAt: any | null\n createdAt: any\n updatedAt: any\n // products: ProductEntity[];\n user?: UserEntity\n // orders: OrderEntity[];\n // shippingMethods: ShippingMethodEntity[];\n defaultShippingRates: (number | null)[][] | null\n\n // subscription\n subscription?: any\n due?: number\n\n // StoreConfigs\n configs?: StoreConfigs\n\n // metaPixelIds\n metaPixelIds?: string[] | null\n\n // tiktokPixelIds\n tiktokPixelIds?: string[] | null\n\n // googleAnalyticsId\n googleAnalyticsId?: string | null\n\n // members\n members?: Record<string, StoreMember>\n}\n\nexport enum StoreMemberRole {\n editor = 'editor',\n viewer = 'viewer',\n confermer = 'confermer',\n}\n\nexport interface StoreMember {\n name: string\n userId: string\n role: StoreMemberRole\n acceptedAt: any | null\n expiredAt: any | null\n createdAt: any\n active: boolean\n metadata: Record<string, any>\n}\n\nexport interface StoreConfigs {\n currencies: StoreCurrencyConfig[]\n defaultCurrency: number\n}\n\nexport interface StoreCurrencyConfig {\n code: string\n symbol: string\n precision: number\n rate: number\n}\n\nexport interface StoreDomain {\n name: string\n verifiedAt: any | null\n metadata: Record<string, any>\n}\nexport interface StoreBanner {\n title: string\n url?: string | null\n enabled: boolean\n metadata: Record<string, any>\n}\n\nexport interface StoreDecoration {\n primary: number\n onPrimary?: number\n showStoreLogoInHeader?: boolean\n logoFullHeight?: boolean\n showStoreNameInHeader?: boolean\n metadata?: Record<string, any>\n [key: string]: any\n}\n\nexport interface StoreAction {\n label: string\n url: string\n type: StoreActionType\n}\n\nexport enum StoreActionType {\n link = 'link',\n whatsapp = 'whatsapp',\n telegram = 'telegram',\n phone = 'phone',\n}\nexport interface MetaPixel {\n id: string\n key?: string\n}\n// tiktok pixel\nexport interface TiktokPixel {\n id: string\n key?: string\n}\n// meta pixel integration\nexport interface MetaPixelIntegration {\n id: string\n pixels: MetaPixel[]\n active: boolean\n metadata: Record<string, any>\n}\n// tiktok pixel integration\nexport interface TiktokPixelIntegration {\n id: string\n pixels: TiktokPixel[]\n active: boolean\n metadata: Record<string, any>\n}\n\nexport interface GoogleAnalyticsIntegration {\n id: string\n active: boolean\n metadata: Record<string, any>\n}\n\n// export enum GoogleSheetsColumnType {\n// string = 'string',\n// number = 'number',\n// boolean = 'boolean',\n// date = 'date',\n// }\nexport interface GoogleSheetsColumn<T> {\n field: keyof OrderEntity | null\n name: string\n enabled: boolean\n defaultValue?: T\n // type:\n}\nexport interface GoogleSheetsIntegration {\n id: string\n name: string\n active: boolean\n oauth2?: Record<string, any>\n metadata: Record<string, any>\n columns?: GoogleSheetsColumn<any>[]\n}\nexport interface GoogleTagsIntegration {\n id: string\n active: boolean\n metadata: Record<string, any>\n}\n\nexport interface StoreIntegrations {\n [key: string]: any\n metadata?: Record<string, any>\n\n // @Default('default') String id,\n // @Default([]) List<MetaPixel> pixels,\n // @Default(true) bool active,\n // @Default({}) Map<String, dynamic> metadata,\n metaPixel?: MetaPixelIntegration\n tiktokPixel?: TiktokPixelIntegration\n googleAnalytics?: GoogleAnalyticsIntegration\n googleSheet?: GoogleSheetsIntegration\n googleTags?: GoogleTagsIntegration\n\n sms?: any\n telegram?: any\n yalidine?: any\n maystroDelivery?: any\n echotrak?: any\n procolis?: any\n noest?: any\n}\n\nexport enum StoreSubscriptionStatus {\n active = 'active',\n inactive = 'inactive',\n}\n\nexport enum StoreSubscriptionType {\n free = 'free',\n premium = 'premium',\n vip = 'vip',\n custom = 'custom',\n}\n\nexport interface StoreSubscription {\n type: StoreSubscriptionType\n name: string\n status: StoreSubscriptionStatus\n startedAt: DateTime\n expiresAt: DateTime | null\n quota: number\n consumed: number\n remaining: number\n metadata: Record<string, any>\n}\n","import { EmbaddedCategory } from '../embadded/category.js'\nimport { ShippingMethodEntity } from './shipping_method.js'\nimport { StoreEntity } from './store.js'\n\nexport interface ProductEntity {\n id: string\n\n slug: string\n\n decoration: ProductDecoration | null\n\n name: string | null\n\n photoUrl: string | null\n\n media: string[]\n\n storeId: string\n\n shippingMethodId?: string | null\n\n category: EmbaddedCategory\n\n title: string | null\n\n description: string | null\n\n body: string | null\n\n // sku\n sku: string | null\n\n price: number\n\n cost: number | null\n\n discount: number | null\n\n stock: number | null\n\n sold: number\n\n views: number\n\n likes: number\n\n dislikes: number\n\n variant?: ProductVariant | null\n\n offers?: ProductOffer[] | null\n\n metadata: Record<string, any>\n\n status: ProductStatus\n\n type: ProductType\n\n verifiedAt: any | null\n\n blockedAt: any | null\n\n createdAt: any\n\n updatedAt: any\n\n // relations\n store?: StoreEntity | null\n shippingMethod?: ShippingMethodEntity | null\n}\n\nexport enum ProductStatus {\n draft = 'draft',\n published = 'published',\n archived = 'archived',\n deleted = 'deleted',\n}\n\nexport interface ProductDecoration {\n metadata: Record<string, any>\n}\n\nexport interface ProductVariant {\n name: string\n view?: ProductVariantView\n options: ProductVariantOption[]\n required?: boolean\n}\n\nexport enum ProductVariantView {\n list = 'list',\n chips = 'chips',\n dropdown = 'dropdown',\n}\n\nexport interface ProductVariantOption {\n name: string\n sku?: string | null\n price?: number | null\n discount?: number | null\n stock?: number | null\n sold?: number | null\n type?: VariantOptionType\n child?: ProductVariant | null\n mediaIndex?: number | null\n hint?: string | null\n value?: any\n}\n\nexport enum VariantOptionType {\n color = 'color',\n image = 'image',\n text = 'text',\n}\n\nexport enum ProductType {\n physical = 'physical',\n digital = 'digital',\n service = 'service',\n}\n\nexport interface ProductOffer {\n code: string\n title: string\n subtitle?: string\n price?: number\n}\n","export enum EmbaddedContactType {\n phone = 'phone',\n email = 'email',\n facebook = 'facebook',\n twitter = 'twitter',\n instagram = 'instagram',\n linkedin = 'linkedin',\n website = 'website',\n whatsapp = 'whatsapp',\n telegram = 'telegram',\n signal = 'signal',\n viber = 'viber',\n skype = 'skype',\n zoom = 'zoom',\n other = 'other',\n}\n\n// EmbaddedContactType is not enum but can only be: \"phone\" | \"email\" | \"facebook\" | \"twitter\" | \"instagram\" | \"linkedin\" | \"website\" | \"whatsapp\" | \"telegram\" | \"signal\" | \"viber\" | \"skype\" | \"zoom\" | \"other\n\nexport interface EmbaddedContact {\n type: EmbaddedContactType\n value: string\n name?: string\n metadata?: Record<string, any>\n}\n","/**\n * Converts a Dart color (0xffXXXXXX) to a CSS-compatible number (0xXXXXXXFF).\n *\n * @param dartColor - The Dart color represented as a 32-bit integer (0xffXXXXXX).\n * @returns A number representing the color in CSS format (0xXXXXXXFF).\n */\nexport const convertDartColorToCssNumber = (dartColor: number): number => {\n const alpha = (dartColor >> 24) & 0xff // Extract alpha (high 8 bits)\n const rgb = dartColor & 0xffffff // Extract RGB (low 24 bits)\n\n // Return color as 0xXXXXXXFF (CSS format: RGB + alpha)\n return (rgb << 8) | alpha\n}\n\n/**\n * Converts a CSS color (0xXXXXXXFF) to HSL format.\n *\n * @param cssColor - The CSS color represented as a 32-bit integer (0xXXXXXXFF).\n * @returns An object with HSL values {h, s, l}.\n */\nexport const cssColorToHslString = (cssColor: number): string => {\n const r = ((cssColor >> 24) & 0xff) / 255 // Extract red channel\n const g = ((cssColor >> 16) & 0xff) / 255 // Extract green channel\n const b = ((cssColor >> 8) & 0xff) / 255 // Extract blue channel\n\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n let h = 0\n let s = 0\n let l = (max + min) / 2\n\n if (max !== min) {\n const d = max - min\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0)\n break\n case g:\n h = (b - r) / d + 2\n break\n case b:\n h = (r - g) / d + 4\n break\n }\n h /= 6\n }\n\n return `${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%`\n}\n\n/**\n * Trims and attempts to fix the phone number by:\n * - Removing all non-numeric characters\n * - Ensuring it starts with a '0'\n * @param phone - The input phone number string\n * @returns The cleaned phone number\n */\nexport function tryFixPhoneNumber(phone: string): string {\n phone = phone.trim() // Remove leading/trailing spaces\n // Remove all non-numeric characters\n phone = phone.replace(/\\D/g, '')\n // Ensure the phone number starts with '0'\n if (!phone.startsWith('0')) {\n phone = '0' + phone\n }\n return phone\n}\n\n/**\n * Validates the phone number based on specific rules:\n * - Cannot be empty or just \"0\"\n * - Must start with '05', '06', '07', or '02'\n * - Must be 10 digits for mobile numbers (05, 06, 07)\n * - Must be 9 digits for landline numbers (02)\n * @param phone - The input phone number string\n * @returns Error message if validation fails, otherwise null\n */\nexport function validatePhoneNumber(phone: string): string | null {\n // Helper function to handle length overflow/underflow messages\n const getLengthError = (requiredLength: number, actualLength: number): string => {\n const difference = actualLength - requiredLength\n if (difference > 0) {\n return `عدد الأرقام زائد عن ${requiredLength} رقماً بـ ${difference}`\n } else {\n const missingDigits = -difference\n if (missingDigits === 1) return 'ينقصك رقم واحد'\n if (missingDigits === 2) return 'ينقصك رقمان'\n return `ينقصك ${missingDigits} أرقام`\n }\n }\n\n if (phone === '0') {\n return 'اكمل رقم الهاتف'\n }\n\n // Check if phone number is empty\n if (!phone) {\n return 'رقم الهاتف لا يمكن أن يكون فارغاً.'\n }\n\n // Check if phone number contains only digits\n if (!/^\\d+$/.test(phone)) {\n return 'رقم الهاتف يجب أن يحتوي فقط على أرقام.'\n }\n\n // Ensure the phone starts with valid prefixes\n if (!/^(05|06|07|02)/.test(phone)) {\n return 'يجب أن يبدأ بـ 05, 06, 07, أو 02'\n }\n\n const length = phone.length\n\n // Validate mobile numbers (05, 06, 07 should be 10 digits)\n if (/^(05|06|07)/.test(phone)) {\n if (length !== 10) {\n return getLengthError(10, length)\n }\n }\n\n // Validate landline numbers (02 should be 9 digits)\n else if (phone.startsWith('02')) {\n if (length !== 9) {\n return getLengthError(9, length)\n }\n }\n\n // If all checks pass, return null (no errors)\n return null\n}\n"],"mappings":";AAAA,OAAO,WAA8B;;;ACQ9B,IAAe,kBAAf,MAAwC;AAAA,EAC7C;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAY,UAAkB,QAAuB;AACnD,SAAK,WAAW;AAChB,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,KAAK,SAAuC;AAChD,UAAM,EAAE,IAAI,IA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AAiB,KAAK,KAAK,GAAG;AACjC,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,MAAM;AAGrB,MAAI,cAAc,KAAK,KAAK,GAAG;AAC7B,QAAI,WAAW,IAAI;AACjB,aAAO,eAAe,IAAI,MAAM;AAAA,IAClC;AAAA,EACF,WAGS,MAAM,WAAW,IAAI,GAAG;AAC/B,QAAI,WAAW,GAAG;AAChB,aAAO,eAAe,GAAG,MAAM;AAAA,IACjC;AAAA,EACF;AAGA,SAAO;AACT;","names":["OrderStatus","PaymentStatus","DeliveryStatus","ShippingType","ShippingMethodStatus","ShippingMethodPolicy","StoreMemberRole","StoreActionType","StoreSubscriptionStatus","StoreSubscriptionType","ProductStatus","ProductVariantView","VariantOptionType","ProductType","EmbaddedContactType"]}
1
+ {"version":3,"sources":["../src/feeef/feeef.ts","../src/feeef/repositories/repository.ts","../src/feeef/repositories/orders.ts","../src/feeef/repositories/products.ts","../src/feeef/repositories/stores.ts","../src/feeef/repositories/users.ts","../src/core/entities/order.ts","../src/core/entities/shipping_method.ts","../src/feeef/services/service.ts","../src/feeef/services/cart.ts","../src/core/entities/store.ts","../src/core/entities/product.ts","../src/core/embadded/contact.ts","../src/utils.ts"],"sourcesContent":["import axios, { AxiosInstance } from 'axios'\n// import { buildMemoryStorage, buildWebStorage, setupCache } from 'axios-cache-interceptor'\nimport { OrderRepository } from './repositories/orders.js'\nimport { ProductRepository } from './repositories/products.js'\nimport { StoreRepository } from './repositories/stores.js'\nimport { UserRepository } from './repositories/users.js'\nimport { CartService } from './services/cart.js'\n\n/**\n * Configuration options for the FeeeF module.\n */\nexport interface FeeeFConfig {\n /**\n * The API key to be used for authentication.\n */\n apiKey: string\n\n /**\n * An optional Axios instance to be used for making HTTP requests.\n */\n client?: AxiosInstance\n\n /**\n * Specifies whether caching should be enabled or disabled.\n * If set to a number, it represents the maximum number of seconds to cache the responses.\n * If set to `false`, caching will be disabled (5s).\n * cannot be less than 5 seconds\n */\n cache?: false | number\n\n /**\n * The base URL for the API.\n */\n baseURL?: string\n}\n\n/**\n * Represents the FeeeF class.\n */\nexport class FeeeF {\n /**\n * The API key used for authentication.\n */\n apiKey: string\n\n /**\n * The Axios instance used for making HTTP requests.\n */\n client: AxiosInstance\n\n /**\n * The repository for managing stores.\n */\n stores: StoreRepository\n\n /**\n * The repository for managing products.\n */\n products: ProductRepository\n\n /**\n * The repository for managing users.\n */\n users: UserRepository\n\n /**\n * The repository for managing orders.\n */\n orders: OrderRepository\n\n /**\n * The cart service for managing the cart.\n */\n cart: CartService\n\n /**\n * Constructs a new instance of the FeeeF class.\n * @param {FeeeFConfig} config - The configuration object.\n * @param {string} config.apiKey - The API key used for authentication.\n * @param {AxiosInstance} config.client - The Axios instance used for making HTTP requests.\n * @param {boolean | number} config.cache - The caching configuration. Set to `false` to disable caching, or provide a number to set the cache TTL in milliseconds.\n */\n //\n constructor({ apiKey, client, cache, baseURL = 'http://localhost:3333/api/v1' }: FeeeFConfig) {\n console.log(cache)\n this.apiKey = apiKey\n // get th \"cache\" search param\n // const urlParams = new URLSearchParams(window.location.search)\n // const cacheParam = urlParams.get('cache')\n // if is 0 or false, disable cache\n // if (cacheParam == '0') {\n this.client = client || axios\n // } else {\n // this.client = setupCache(client || axios, {\n // ttl: cache === false ? 5 : Math.max(cache!, 5) || 1 * 60 * 1000, // 1 minute by default\n // // for persistent cache use buildWebStorage\n // storage: buildWebStorage(localStorage, 'ff:'),\n // })\n // }\n // set base url\n this.client.defaults.baseURL = baseURL\n this.stores = new StoreRepository(this.client)\n this.products = new ProductRepository(this.client)\n this.users = new UserRepository(this.client)\n this.orders = new OrderRepository(this.client)\n\n // cart\n this.cart = new CartService()\n }\n}\n","import { AxiosInstance } from 'axios'\n\n/**\n * Represents a generic model repository.\n * @template T - The type of the model.\n * @template C - The type of the create options.\n * @template U - The type of the update options.\n */\nexport abstract class ModelRepository<T, C, U> {\n resource: string\n // client\n client: AxiosInstance\n\n /**\n * Constructs a new instance of the ModelRepository class.\n * @param resource - The resource name.\n * @param client - The Axios instance used for making HTTP requests.\n */\n constructor(resource: string, client: AxiosInstance) {\n this.resource = resource\n this.client = client\n }\n\n /**\n * Finds a model by its ID or other criteria.\n * @param options - The options for finding the model.\n * @returns A promise that resolves to the found model.\n */\n async find(options: ModelFindOptions): Promise<T> {\n const { id, by, params } = options\n const res = await this.client.get(`/${this.resource}/${id}`, {\n params: {\n by: by || 'id',\n ...params,\n },\n })\n return res.data\n }\n\n /**\n * Lists models with optional pagination and filtering.\n * @param options - The options for listing the models.\n * @returns A promise that resolves to a list of models.\n */\n async list(options?: ModelListOptions): Promise<ListResponse<T>> {\n const { page, offset, limit, params } = options || {}\n const res = await this.client.get(`/${this.resource}`, {\n params: { page, offset, limit, ...params },\n })\n // if res.data is an array then create ListResponse\n if (Array.isArray(res.data)) {\n return {\n data: res.data,\n }\n } else {\n return {\n data: res.data.data,\n total: res.data.meta.total,\n page: res.data.meta.currentPage,\n limit: res.data.meta.perPage,\n }\n }\n }\n\n /**\n * Creates a new model.\n * @param options - The options for creating the model.\n * @returns A promise that resolves to the created model.\n */\n async create(options: ModelCreateOptions<C>): Promise<T> {\n const { data, params } = options\n const res = await this.client.post(`/${this.resource}`, data, { params })\n return res.data\n }\n\n /**\n * Updates an existing model.\n * @param options - The options for updating the model.\n * @returns A promise that resolves to the updated model.\n */\n async update(options: ModelUpdateOptions<U>): Promise<T> {\n const { id, data, params } = options\n const res = await this.client.put(`/${this.resource}/${id}`, data, {\n params,\n })\n return res.data\n }\n\n /**\n * Deletes a model by its ID or other criteria.\n * @param options - The options for deleting the model.\n * @returns A promise that resolves when the model is deleted.\n */\n async delete(options: ModelFindOptions): Promise<void> {\n const { id, by, params } = options\n await this.client.delete(`/${this.resource}/${id}`, {\n params: {\n by: by || 'id',\n ...params,\n },\n })\n }\n}\n\n/**\n * Represents a list response containing an array of data of type T.\n */\nexport interface ListResponse<T> {\n data: T[]\n total?: number\n page?: number\n limit?: number\n}\n\n/**\n * Represents the options for making a request.\n */\ninterface RequestOptions {\n params?: Record<string, any>\n}\n\nexport interface ModelFindOptions extends RequestOptions {\n /**\n * The ID of the model to find or the value to find by.\n */\n id: string\n /**\n * The field to find by.\n * @default \"id\" - The ID field.\n */\n by?: string\n}\n\n/**\n * Options for listing models.\n */\nexport interface ModelListOptions extends RequestOptions {\n /**\n * The page number to retrieve.\n */\n page?: number\n\n /**\n * The offset from the beginning of the list.\n */\n offset?: number\n\n /**\n * The maximum number of models to retrieve per page.\n */\n limit?: number\n}\n\n/**\n * Represents the options for creating a model.\n * @template T - The type of data being created.\n */\nexport interface ModelCreateOptions<T> extends RequestOptions {\n data: T\n}\n\n/**\n * Represents the options for updating a model.\n * @template T - The type of the data being updated.\n */\nexport interface ModelUpdateOptions<T> extends RequestOptions {\n /**\n * The ID of the model to update.\n */\n id: string\n /**\n * The data to update the model with.\n */\n data: T\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository } from './repository.js'\nimport { OrderEntity, OrderTrackEntity, ShippingType } from '../../core/entities/order.js'\n/**\n * Represents the options for tracking an order.\n */\nexport interface OrderModelTrackOptions {\n id: string\n params?: Record<string, any>\n}\n\nexport interface SendOrderSchema {\n id?: string // Order ID (optional)\n customerName?: string // Name of the customer (optional)\n customerNote?: string // Note from the customer (optional)\n customerPhone: string // Customer's phone number (required)\n shippingAddress?: string // Address for shipping (optional)\n shippingCity?: string // City for shipping (optional)\n shippingState?: string // State for shipping (optional)\n shippingType: ShippingType // Shipping type (required)\n shippingMethodId?: string // ID of the shipping method (optional)\n paymentMethodId?: string // ID of the payment method (optional)\n items: GuestOrderItemSchema[] // Array of order items, must have at least one item\n coupon?: string // Applied coupon code (optional)\n status: 'pending' | 'draft' // Order status (required)\n storeId: string // ID of the store (required)\n metadata?: any // Additional metadata (optional)\n}\n\n// Assuming GuestOrderItemSchema was defined elsewhere, define it here as well if needed.\nexport interface GuestOrderItemSchema {\n productId: string\n offerCode?: string\n variantPath?: string\n quantity: number\n}\n\n/**\n * Represents a repository for managing orders.\n */\nexport class OrderRepository extends ModelRepository<OrderEntity, any, any> {\n /**\n * Constructs a new OrderRepository instance.\n * @param client - The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('orders', client)\n }\n\n /**\n * Sends an order from an anonymous user.\n * @param data - The data representing the order to be sent.\n * @returns A Promise that resolves to the sent OrderEntity.\n */\n async send(data: SendOrderSchema): Promise<OrderEntity> {\n const output = data\n const res = await this.client.post(`/${this.resource}/send`, output)\n\n // Return the sent OrderEntity\n return res.data\n }\n\n /**\n * track the order by the order id\n * it will return the order status and history\n * @param options - The options for finding the model.\n * @returns A promise that resolves to the found model.\n */\n async track(options: OrderModelTrackOptions): Promise<OrderTrackEntity> {\n const { id, params } = options\n const res = await this.client.get(`/${this.resource}/${id}/track`, {\n params: {\n ...params,\n },\n })\n return res.data\n }\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository } from './repository.js'\nimport { ProductEntity } from '../../core/entities/product.js'\n\n/**\n * Represents a repository for managing products.\n */\nexport class ProductRepository extends ModelRepository<ProductEntity, any, any> {\n /**\n * Creates a new instance of the ProductRepository class.\n * @param client - The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('products', client)\n }\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository, ModelCreateOptions } from './repository.js'\nimport { StoreEntity } from '../../core/entities/store.js'\n\n/**\n * Repository for managing Store entities.\n */\nexport class StoreRepository extends ModelRepository<StoreEntity, any, any> {\n /**\n * Constructs a new StoreRepository instance.\n * @param client The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('stores', client)\n }\n\n /**\n * Creates a new Store entity.\n * @param options The options for creating the Store entity.\n * @returns A Promise that resolves to the created Store entity.\n */\n async create(options: ModelCreateOptions<any>): Promise<StoreEntity> {\n const output = options.data\n return super.create({ ...options, data: output })\n }\n}\n","import { AxiosInstance } from 'axios'\nimport { ModelRepository } from './repository.js'\nimport { AuthToken, UserEntity } from '../../core/entities/user.js'\n\n/**\n * Represents the response returned by the authentication process.\n */\nexport interface AuthResponse {\n token: AuthToken\n user: UserEntity\n}\n\n/**\n * Represents a repository for managing user data.\n * Extends the ModelRepository class.\n */\nexport class UserRepository extends ModelRepository<UserEntity, any, any> {\n /**\n * Represents the authentication response.\n */\n auth: AuthResponse | null = null\n\n /**\n * Constructs a new UserRepository instance.\n * @param client - The AxiosInstance used for making HTTP requests.\n */\n constructor(client: AxiosInstance) {\n super('users', client)\n }\n\n /**\n * Signs in a user with the provided credentials.\n * @param credentials - The user credentials.\n * @returns A promise that resolves to the authentication response.\n */\n async signin(credentials: any): Promise<AuthResponse> {\n // validate the input\n const output = credentials\n const res = await this.client.post(`/${this.resource}/auth/signin`, output)\n this.auth = res.data\n return res.data\n }\n\n /**\n * Signs up a new user with the provided credentials.\n * @param credentials - The user credentials.\n * @returns A promise that resolves to the authentication response.\n */\n async signup(credentials: any): Promise<AuthResponse> {\n // validate the input\n const output = credentials\n const res = await this.client.post(`/${this.resource}/auth/signup`, output)\n this.auth = res.data\n return res.data\n }\n\n /**\n * Signs out the currently authenticated user.\n * @returns A promise that resolves when the user is signed out.\n */\n async signout(): Promise<void> {\n this.auth = null\n }\n\n /**\n * Updates the authenticated user's data.\n * @param data - The updated user data.\n * @returns A promise that resolves to the updated user entity.\n */\n async updateMe(data: any): Promise<UserEntity> {\n const output = data\n const res = await this.client.put(`/${this.resource}/auth`, output)\n return res.data\n }\n}\n","export enum OrderStatus {\n draft = 'draft',\n pending = 'pending',\n review = 'review',\n accepted = 'accepted',\n processing = 'processing',\n completed = 'completed',\n cancelled = 'cancelled',\n}\n\n// PaymentStatus\nexport enum PaymentStatus {\n unpaid = 'unpaid',\n paid = 'paid',\n received = 'received',\n}\nexport enum DeliveryStatus {\n pending = 'pending',\n delivering = 'delivering',\n delivered = 'delivered',\n returned = 'returned',\n}\n\nexport enum ShippingType {\n home = 'home',\n pickup = 'pickup',\n store = 'store',\n}\n\nexport interface OrderEntity {\n id: string\n customerName?: string | null\n customerPhone: string\n customerIp?: string | null\n shippingAddress?: string | null\n shippingCity?: string | null\n shippingState?: string | null\n shippingMethodId?: string | null\n shippingType: ShippingType\n paymentMethodId?: string | null\n items: OrderItem[]\n subtotal: number\n shippingPrice: number\n total: number\n discount: number\n coupon?: string | null\n storeId: string\n metadata: OrderMetadata\n status: OrderStatus\n paymentStatus: PaymentStatus\n deliveryStatus: DeliveryStatus\n createdAt: any\n updatedAt: any\n}\nexport interface OrderItem {\n productId: string\n productName: string\n productPhotoUrl?: string | null\n variantPath?: string\n quantity: number\n price: number\n offerCode?: string | null\n offerName?: string | null\n}\n\n// order track entity\nexport interface OrderTrackEntity {\n id: string\n customerName?: string | null\n items: OrderItem[]\n total: number\n createdAt: any\n storeId: string\n status: OrderStatus\n history: OrderTrackHistory[]\n}\n\n// order track history\nexport interface OrderTrackHistory {\n status: OrderStatus\n deliveryStatus: string\n paymentStatus: string\n createdAt: string\n}\n\n// order metadata history\ninterface OrderMetadataHistory {\n status: OrderStatus\n deliveryStatus: string\n paymentStatus: string\n createdAt: string\n message: string\n code: string\n userId: string\n}\n\n// order metadata\ninterface OrderMetadata {\n note?: string\n history?: OrderMetadataHistory[]\n metaPixel?: any\n customOrderTagHistories?: any[]\n [key: string]: any\n}\n\n// utils\n// order entity to order track entity\nexport const convertOrderEntityToOrderTrackEntity = (order: OrderEntity): OrderTrackEntity => {\n return {\n id: order.id,\n customerName: order.customerName,\n items: order.items,\n total: order.total,\n createdAt: order.createdAt,\n storeId: order.storeId,\n status: order.status,\n history:\n order.metadata.history?.map((history) => ({\n status: history.status,\n deliveryStatus: history.deliveryStatus,\n paymentStatus: history.paymentStatus,\n createdAt: history.createdAt,\n })) || [],\n }\n}\n","import { OrderEntity } from './order.js'\n\nexport interface ShippingMethodEntity {\n id: string\n name: string\n description: string | null\n logoUrl: string | null\n ondarkLogoUrl: string | null\n price: number\n forks: number\n sourceId: string\n storeId: string\n rates: (number | null)[][] | null\n status: ShippingMethodStatus\n policy: ShippingMethodPolicy\n verifiedAt: any\n createdAt: any\n updatedAt: any\n orders: OrderEntity[]\n source: ShippingMethodEntity | null\n}\n\nexport enum ShippingMethodStatus {\n draft = 'draft',\n published = 'published',\n archived = 'archived',\n}\n\nexport enum ShippingMethodPolicy {\n private = 'private',\n public = 'public',\n}\n","export type Listener<T extends NotifiableService> = (service: T) => void\n\nexport class NotifiableService {\n // Array of listeners (functions) to notify when changes occur\n private listeners: Set<Listener<typeof this>> = new Set()\n\n /**\n * Adds a listener that gets called when `notify` is triggered.\n * @param listener - The function to be called on notification.\n * @returns The same listener for potential chaining or removal.\n */\n addListener(listener: Listener<typeof this>): Listener<typeof this> {\n this.listeners.add(listener) // Using Set for uniqueness and faster removal\n return listener\n }\n\n /**\n * Removes a previously added listener.\n * @param listener - The function to be removed from the listeners list.\n */\n removeListener(listener: Listener<typeof this>): void {\n this.listeners.delete(listener) // Set deletion is O(1) for better performance\n }\n\n /**\n * Notifies all registered listeners, passing the service instance.\n * This allows listeners to react to changes.\n */\n notify(): void {\n // Iterating over the Set of listeners and invoking each one\n this.listeners.forEach((listener) => listener(this))\n }\n\n /**\n * Clears all listeners, removing any references to them.\n */\n clearListeners(): void {\n this.listeners.clear() // Clears the Set entirely\n }\n\n /**\n * Constructor for NotifiableService, initializes listeners as an empty Set.\n * The Set ensures unique listeners and better management.\n */\n constructor() {\n // Initialization can be skipped since listeners is already initialized as an empty Set\n }\n}\n","import { ShippingType } from '../../core/entities/order.js'\nimport { ProductEntity, ProductOffer } from '../../core/entities/product.js'\nimport {\n ShippingMethodEntity,\n ShippingMethodPolicy,\n ShippingMethodStatus,\n} from '../../core/entities/shipping_method.js'\nimport { StoreEntity } from '../../core/entities/store.js'\nimport { NotifiableService } from './service.js'\n\n/**\n * Represents an item in the cart.\n */\nexport interface CartItem {\n product: ProductEntity\n offer?: ProductOffer\n quantity: number\n variantPath?: string\n}\n\n/**\n * Cart shipping types.\n * - `pickup`: The user will pick up the order from the closest desk.\n * - `home`: The order will be delivered to the user's home.\n * - `store`: The order will be delivered to the store.\n */\n// export type CartShippingTypes = 'pickup' | 'home' | 'store'\n\n/**\n * Interface for a shipping address.\n */\nexport interface CartShippingAddress {\n name: string | null\n phone: string | null\n city: string | null\n state: string | null\n street: string | null\n country: 'dz'\n type: ShippingType\n}\n\n/**\n * Manages the shopping cart and its operations.\n */\nexport class CartService extends NotifiableService {\n private items: Map<string, CartItem> = new Map() // Fast lookup of cart items\n private shippingMethod: ShippingMethodEntity | null = null\n private shippingAddress: CartShippingAddress = {\n name: null,\n phone: null,\n city: null,\n state: null,\n street: null,\n country: 'dz',\n type: ShippingType.pickup,\n }\n private cachedSubtotal: number | null = null // Cache for subtotal to avoid redundant calculations\n private currentItem: CartItem | null = null\n\n /**\n * Sets the current item to be managed in the cart.\n * @param item - The item to be set as current.\n */\n setCurrentItem(item: CartItem, notify = true): void {\n this.currentItem = item\n\n if (this.has(this.currentItem.product.id)) {\n this.items.set(this.currentItem.product.id, this.currentItem)\n }\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Clamps the quantity to be within the offer's min/max range\n * @param offer - The offer containing quantity constraints\n * @param quantity - The quantity to clamp\n * @returns The clamped quantity value\n */\n private clampQuantityToOfferLimits(offer: ProductOffer, quantity: number): number {\n if (offer.minQuantity !== undefined) {\n quantity = Math.max(quantity, offer.minQuantity)\n }\n if (offer.maxQuantity !== undefined) {\n quantity = Math.min(quantity, offer.maxQuantity)\n }\n return quantity\n }\n\n /**\n * Update item by id.\n * @param id - The id of the item to update.\n * @param item - a partial item to update.\n */\n updateItem(id: string, item: Partial<CartItem>, notify = true): void {\n const currentItem = this.items.get(id)\n\n if (currentItem) {\n const newItem = { ...currentItem, ...item }\n // Clamp quantity if there's an offer with constraints\n if (newItem.offer) {\n newItem.quantity = this.clampQuantityToOfferLimits(newItem.offer, newItem.quantity)\n }\n\n this.items.set(id, newItem)\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n }\n\n /**\n * Update current item.\n * @param item - a partial item to update.\n */\n updateCurrentItem(item: Partial<CartItem>, notify = true): void {\n if (!this.currentItem) return\n\n this.currentItem = { ...this.currentItem, ...item }\n\n if (this.has(this.currentItem.product.id)) {\n this.items.set(this.currentItem.product.id, this.currentItem)\n }\n\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Update shipping address.\n * @param address - a partial address to update.\n */\n updateShippingAddress(address: Partial<CartShippingAddress>, notify = true): void {\n this.shippingAddress = { ...this.shippingAddress, ...address }\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Update shipping method.\n * @param method - a partial shipping method to update.\n */\n updateShippingMethod(method: Partial<ShippingMethodEntity>, notify = true): void {\n if (!this.shippingMethod) return\n\n this.shippingMethod = { ...this.shippingMethod, ...method }\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n\n /**\n * Retrieves the current item in the cart.\n * @returns The current cart item or null if not set.\n */\n getCurrentItem(): CartItem | null {\n return this.currentItem\n }\n\n /**\n * Checks if the current item is already in the cart.\n * @returns True if the current item is in the cart, false otherwise.\n */\n isCurrentItemInCart(): boolean {\n return this.currentItem ? this.items.has(this.currentItem.product.id) : false\n }\n\n /**\n * Adds the current item to the cart if it's not already present.\n */\n addCurrentItemToCart(): void {\n if (!this.currentItem || this.isCurrentItemInCart()) return\n this.add(this.currentItem)\n this.cachedSubtotal = null\n }\n\n /**\n * Removes the current item from the cart if present.\n */\n removeCurrentItemFromCart(): void {\n if (this.currentItem) {\n this.remove(this.currentItem.product.id)\n }\n }\n\n /**\n * Toggles the current item's presence in the cart (add/remove).\n */\n toggleCurrentItemInCart(): void {\n this.isCurrentItemInCart() ? this.removeCurrentItemFromCart() : this.addCurrentItemToCart()\n }\n\n /**\n * Adds an item to the cart. If the item is already present, increments its quantity.\n * @param item - The cart item to add.\n */\n add(item: CartItem): void {\n const existingItem = this.items.get(item.product.id)\n\n if (existingItem) {\n existingItem.quantity += item.quantity\n } else {\n this.items.set(item.product.id, item)\n }\n\n this.cachedSubtotal = null // Reset subtotal cache\n this.notifyIfChanged()\n }\n\n /**\n * Checks if an item exists in the cart by product ID.\n * @param itemId - The ID of the item to check.\n * @returns True if the item exists in the cart, false otherwise.\n */\n has(itemId: string): boolean {\n return this.items.has(itemId)\n }\n\n /**\n * Removes an item from the cart by product ID.\n * @param itemId - The ID of the item to remove.\n */\n remove(itemId: string): void {\n if (this.items.delete(itemId)) {\n this.cachedSubtotal = null\n this.notifyIfChanged()\n }\n }\n\n /**\n * Clears all items from the cart.\n */\n clear(notify = true): void {\n if (this.items.size > 0) {\n this.items.clear()\n this.cachedSubtotal = null\n if (notify) {\n this.notify()\n }\n }\n }\n\n /**\n * Retrieves the subtotal of the cart.\n * @param withCurrentItem - Whether to include the current item in the subtotal.\n * @returns The subtotal amount.\n */\n getSubtotal(withCurrentItem = true): number {\n if (this.cachedSubtotal === null) {\n this.cachedSubtotal = Array.from(this.items.values()).reduce((sum, item) => {\n return sum + this.getItemTotal(item)\n }, 0)\n }\n\n if (withCurrentItem && this.currentItem && !this.has(this.currentItem.product.id)) {\n return this.cachedSubtotal + this.getItemTotal(this.currentItem)\n }\n\n return this.cachedSubtotal\n }\n\n /**\n * Calculates the total price for a cart item.\n * @param item - The cart item.\n * @returns The total price for the item.\n */\n getItemTotal(item: CartItem): number {\n const { product, variantPath, quantity, offer } = item\n let price = product.price\n let discount = product.discount ?? 0\n\n // Handle variant pricing if a variant path exists\n if (variantPath) {\n const parts = variantPath.split('/')\n let currentVariant = product.variant\n\n for (const part of parts) {\n if (!currentVariant) break\n const option = currentVariant.options.find((o) => o.name === part)\n if (!option) break\n price = option.price ?? price\n discount = option.discount ?? discount\n currentVariant = option.child\n }\n }\n\n // Apply offer if present\n if (offer) {\n if (offer.price !== undefined) {\n // If offer has a fixed price, use it\n price = offer.price\n discount = 0 // Reset discount since we're using a fixed price\n }\n }\n\n return (price - discount) * quantity\n }\n\n /**\n * Validates if an offer can be applied to the given quantity\n * @param offer - The offer to validate\n * @param quantity - The quantity to check\n * @returns boolean indicating if the offer is valid for the quantity\n */\n isOfferValidForQuantity(offer: ProductOffer, quantity: number): boolean {\n if (offer.minQuantity && quantity < offer.minQuantity) return false\n if (offer.maxQuantity && quantity > offer.maxQuantity) return false\n return true\n }\n\n /**\n * Updates the offer for a specific cart item\n * @param itemId - The ID of the item to update\n * @param offer - The offer to apply, or undefined to remove the offer\n */\n updateItemOffer(itemId: string, offer?: ProductOffer): void {\n const item = this.items.get(itemId)\n if (!item) return\n\n const updatedItem = { ...item, offer }\n // If applying an offer, ensure quantity is within limits\n if (offer) {\n updatedItem.quantity = this.clampQuantityToOfferLimits(offer, item.quantity)\n }\n\n this.updateItem(itemId, updatedItem)\n this.cachedSubtotal = null\n this.notifyIfChanged()\n }\n\n /**\n * Updates the offer for the current item\n * @param offer - The offer to apply, or undefined to remove the offer\n */\n updateCurrentItemOffer(offer?: ProductOffer): void {\n if (!this.currentItem) return\n\n const updatedItem = { ...this.currentItem }\n updatedItem.offer = offer\n\n // If applying an offer, ensure quantity is within limits\n if (offer) {\n updatedItem.quantity = this.clampQuantityToOfferLimits(offer, this.currentItem.quantity)\n }\n\n this.updateCurrentItem(updatedItem)\n this.cachedSubtotal = null\n this.notifyIfChanged()\n }\n\n /**\n * Sets the shipping method.\n * @param method - Either a store or a shipping method.\n */\n setShippingMethod(method: ShippingMethodEntity | StoreEntity, notify = true): void {\n const store = (method as StoreEntity)?.defaultShippingRates ? (method as StoreEntity) : null\n const shippingMethod = (method as ShippingMethodEntity)?.rates\n ? (method as ShippingMethodEntity)\n : null\n\n if (store) {\n this.shippingMethod = {\n id: store.id,\n name: store.name,\n description: store.description,\n logoUrl: store.logoUrl,\n ondarkLogoUrl: store.ondarkLogoUrl,\n price: 0,\n forks: 0,\n sourceId: store.id,\n storeId: store.id,\n rates: store.defaultShippingRates,\n status: ShippingMethodStatus.published,\n policy: ShippingMethodPolicy.public,\n verifiedAt: null,\n createdAt: null,\n updatedAt: null,\n orders: [],\n source: null,\n }\n if (notify) {\n this.notify()\n }\n } else if (shippingMethod) {\n this.shippingMethod = shippingMethod\n if (notify) {\n this.notify()\n }\n } else {\n throw new Error('Invalid shipping method')\n }\n }\n\n // getAvailableShippingTypes\n /**\n * Retrieves the available shipping types for the current shipping method.\n *\n * rates is a 2D array for example `[[10, 20, 30], [5, 10, 15]]`\n * where the first array is for `home` fees and the second is for `pickup` fees, and the third is for `store` fees\n * if the fee value is 0, then it's free shipping, and if it's null, then it's not available\n *\n * @returns An array of available shipping types.\n */\n getAvailableShippingTypes(): ShippingType[] {\n if (!this.shippingMethod?.rates) return []\n\n var state = Number.parseInt(this.shippingAddress.state!)\n var stateRates = this.shippingMethod.rates[state - 1]\n\n if (!stateRates) return []\n\n var availableTypes: ShippingType[] = []\n\n if (stateRates[0] || stateRates[0] === 0) availableTypes.push(ShippingType.pickup)\n if (stateRates[1] || stateRates[1] === 0) availableTypes.push(ShippingType.home)\n if (stateRates[2] || stateRates[2] === 0) availableTypes.push(ShippingType.store)\n\n return availableTypes\n }\n\n /**\n * Retrieves the current shipping method.\n * @returns The shipping method or null.\n */\n getShippingMethod(): ShippingMethodEntity | null {\n return this.shippingMethod\n }\n\n /**\n * Sets the shipping address for the cart.\n * @param address - The shipping address.\n */\n setShippingAddress(address: CartShippingAddress, notify = true): void {\n if (\n this.shippingAddress.city !== address.city ||\n this.shippingAddress.state !== address.state ||\n this.shippingAddress.type !== address.type\n ) {\n this.shippingAddress = address\n if (notify) {\n this.notify()\n }\n }\n }\n\n /**\n * Retrieves the current shipping address.\n * @returns The shipping address.\n */\n getShippingAddress(): CartShippingAddress {\n return this.shippingAddress\n }\n\n /**\n * Calculates the shipping price based on the address and shipping method.\n * @returns The shipping price or 0 if not applicable.\n */\n getShippingPrice(): number {\n if (!this.shippingMethod) return 0\n if (!this.shippingAddress.state) return this.shippingMethod.price ?? 0\n\n const stateIndex = Number.parseInt(this.shippingAddress.state, 10) - 1\n const rates = this.shippingMethod.rates?.[stateIndex]\n\n return this.shippingAddress.type === 'pickup' ? (rates?.[0] ?? 0) : (rates?.[1] ?? 0)\n }\n\n /**\n * Calculates the total cost of the cart including shipping.\n * @param withCurrentItem - Whether to include the current item in the total.\n * @returns The total cost.\n */\n getTotal(withCurrentItem = true): number {\n return this.getSubtotal(withCurrentItem) + (this.getShippingPrice() ?? 0)\n }\n\n /**\n * Retrieves all items in the cart.\n * @returns An array of cart items.\n */\n getAll(): CartItem[] {\n return Array.from(this.items.values())\n }\n\n /**\n * Checks if the cart is empty.\n * @returns True if the cart is empty, otherwise false.\n */\n isEmpty(): boolean {\n return this.items.size === 0\n }\n\n /**\n * Notifies listeners if the cart state has meaningfully changed.\n */\n private notifyIfChanged(): void {\n // This method could be enhanced to track and notify only meaningful changes\n this.notify()\n }\n}\n","import { EmbaddedAddress } from '../embadded/address.js'\nimport { EmbaddedCategory } from '../embadded/category.js'\nimport { EmbaddedContact } from '../embadded/contact.js'\nimport { OrderEntity } from './order.js'\n// import { OrderEntity } from \"./order.js\";\n// import { ShippingMethodEntity } from \"./shipping_method.js\";\nimport { UserEntity } from './user.js'\nimport { DateTime } from 'luxon'\n\nexport interface StoreEntity {\n id: string\n slug: string\n banner: StoreBanner | null\n action: StoreAction | null\n domain: StoreDomain | null\n decoration: StoreDecoration | null\n name: string\n iconUrl: string | null\n logoUrl: string | null\n // deprecated\n ondarkLogoUrl: string | null\n userId: string\n categories: EmbaddedCategory[]\n title: string | null\n description: string | null\n addresses: EmbaddedAddress[]\n address: EmbaddedAddress | null\n metadata: Record<string, any>\n contacts: EmbaddedContact[]\n integrations: StoreIntegrations\n verifiedAt: any | null\n blockedAt: any | null\n createdAt: any\n updatedAt: any\n // products: ProductEntity[];\n user?: UserEntity\n // orders: OrderEntity[];\n // shippingMethods: ShippingMethodEntity[];\n defaultShippingRates: (number | null)[][] | null\n\n // subscription\n subscription?: any\n due?: number\n\n // StoreConfigs\n configs?: StoreConfigs\n\n // metaPixelIds\n metaPixelIds?: string[] | null\n\n // tiktokPixelIds\n tiktokPixelIds?: string[] | null\n\n // googleAnalyticsId\n googleAnalyticsId?: string | null\n\n // members\n members?: Record<string, StoreMember>\n}\n\nexport enum StoreMemberRole {\n editor = 'editor',\n viewer = 'viewer',\n confermer = 'confermer',\n}\n\nexport interface StoreMember {\n name: string\n userId: string\n role: StoreMemberRole\n acceptedAt: any | null\n expiredAt: any | null\n createdAt: any\n active: boolean\n metadata: Record<string, any>\n}\n\nexport interface StoreConfigs {\n currencies: StoreCurrencyConfig[]\n defaultCurrency: number\n}\n\nexport interface StoreCurrencyConfig {\n code: string\n symbol: string\n precision: number\n rate: number\n}\n\nexport interface StoreDomain {\n name: string\n verifiedAt: any | null\n metadata: Record<string, any>\n}\nexport interface StoreBanner {\n title: string\n url?: string | null\n enabled: boolean\n metadata: Record<string, any>\n}\n\nexport interface StoreDecoration {\n // primary\n primary: number\n onPrimary?: number\n // on dark mode\n primaryDark?: number\n onPrimaryDark?: number\n // secondary\n secondary?: number\n onSecondary?: number\n // on dark mode\n secondaryDark?: number\n onSecondaryDark?: number\n\n useLogoDarkFilter?: boolean\n\n showStoreLogoInHeader?: boolean\n logoFullHeight?: boolean\n showStoreNameInHeader?: boolean\n metadata?: Record<string, any>\n [key: string]: any\n}\n\nexport interface StoreAction {\n label: string\n url: string\n type: StoreActionType\n}\n\nexport enum StoreActionType {\n link = 'link',\n whatsapp = 'whatsapp',\n telegram = 'telegram',\n phone = 'phone',\n}\nexport interface MetaPixel {\n id: string\n key?: string\n}\n// tiktok pixel\nexport interface TiktokPixel {\n id: string\n key?: string\n}\n// meta pixel integration\nexport interface MetaPixelIntegration {\n id: string\n pixels: MetaPixel[]\n active: boolean\n metadata: Record<string, any>\n}\n// tiktok pixel integration\nexport interface TiktokPixelIntegration {\n id: string\n pixels: TiktokPixel[]\n active: boolean\n metadata: Record<string, any>\n}\n\nexport interface GoogleAnalyticsIntegration {\n id: string\n active: boolean\n metadata: Record<string, any>\n}\n\n// export enum GoogleSheetsColumnType {\n// string = 'string',\n// number = 'number',\n// boolean = 'boolean',\n// date = 'date',\n// }\nexport interface GoogleSheetsColumn<T> {\n field: keyof OrderEntity | null\n name: string\n enabled: boolean\n defaultValue?: T\n // type:\n}\nexport interface GoogleSheetsIntegration {\n id: string\n name: string\n active: boolean\n oauth2?: Record<string, any>\n metadata: Record<string, any>\n columns?: GoogleSheetsColumn<any>[]\n}\nexport interface GoogleTagsIntegration {\n id: string\n active: boolean\n metadata: Record<string, any>\n}\n\nexport interface StoreIntegrations {\n [key: string]: any\n metadata?: Record<string, any>\n\n // @Default('default') String id,\n // @Default([]) List<MetaPixel> pixels,\n // @Default(true) bool active,\n // @Default({}) Map<String, dynamic> metadata,\n metaPixel?: MetaPixelIntegration\n tiktokPixel?: TiktokPixelIntegration\n googleAnalytics?: GoogleAnalyticsIntegration\n googleSheet?: GoogleSheetsIntegration\n googleTags?: GoogleTagsIntegration\n\n sms?: any\n telegram?: any\n yalidine?: any\n maystroDelivery?: any\n echotrak?: any\n procolis?: any\n noest?: any\n}\n\nexport enum StoreSubscriptionStatus {\n active = 'active',\n inactive = 'inactive',\n}\n\nexport enum StoreSubscriptionType {\n free = 'free',\n premium = 'premium',\n vip = 'vip',\n custom = 'custom',\n}\n\nexport interface StoreSubscription {\n type: StoreSubscriptionType\n name: string\n status: StoreSubscriptionStatus\n startedAt: DateTime\n expiresAt: DateTime | null\n quota: number\n consumed: number\n remaining: number\n metadata: Record<string, any>\n}\n","import { EmbaddedCategory } from '../embadded/category.js'\nimport { ShippingMethodEntity } from './shipping_method.js'\nimport { StoreEntity } from './store.js'\n\nexport interface ProductEntity {\n id: string\n\n slug: string\n\n decoration: ProductDecoration | null\n\n name: string | null\n\n photoUrl: string | null\n\n media: string[]\n\n storeId: string\n\n shippingMethodId?: string | null\n\n category: EmbaddedCategory\n\n title: string | null\n\n description: string | null\n\n body: string | null\n\n // sku\n sku: string | null\n\n price: number\n\n cost: number | null\n\n discount: number | null\n\n stock: number | null\n\n sold: number\n\n views: number\n\n likes: number\n\n dislikes: number\n\n variant?: ProductVariant | null\n\n offers?: ProductOffer[] | null\n\n metadata: Record<string, any>\n\n status: ProductStatus\n\n type: ProductType\n\n verifiedAt: any | null\n\n blockedAt: any | null\n\n createdAt: any\n\n updatedAt: any\n\n // relations\n store?: StoreEntity | null\n shippingMethod?: ShippingMethodEntity | null\n}\n\nexport enum ProductStatus {\n draft = 'draft',\n published = 'published',\n archived = 'archived',\n deleted = 'deleted',\n}\n\nexport interface ProductDecoration {\n metadata: Record<string, any>\n}\n\nexport interface ProductVariant {\n name: string\n view?: ProductVariantView\n options: ProductVariantOption[]\n required?: boolean\n}\n\nexport enum ProductVariantView {\n list = 'list',\n chips = 'chips',\n dropdown = 'dropdown',\n}\n\nexport interface ProductVariantOption {\n name: string\n sku?: string | null\n price?: number | null\n discount?: number | null\n stock?: number | null\n sold?: number | null\n type?: VariantOptionType\n child?: ProductVariant | null\n mediaIndex?: number | null\n hint?: string | null\n value?: any\n}\n\nexport enum VariantOptionType {\n color = 'color',\n image = 'image',\n text = 'text',\n}\n\nexport enum ProductType {\n physical = 'physical',\n digital = 'digital',\n service = 'service',\n}\n\nexport interface ProductOffer {\n code: string\n title: string\n subtitle?: string\n price?: number\n minQuantity?: number\n maxQuantity?: number\n}\n","export enum EmbaddedContactType {\n phone = 'phone',\n email = 'email',\n facebook = 'facebook',\n twitter = 'twitter',\n instagram = 'instagram',\n linkedin = 'linkedin',\n website = 'website',\n whatsapp = 'whatsapp',\n telegram = 'telegram',\n signal = 'signal',\n viber = 'viber',\n skype = 'skype',\n zoom = 'zoom',\n other = 'other',\n}\n\n// EmbaddedContactType is not enum but can only be: \"phone\" | \"email\" | \"facebook\" | \"twitter\" | \"instagram\" | \"linkedin\" | \"website\" | \"whatsapp\" | \"telegram\" | \"signal\" | \"viber\" | \"skype\" | \"zoom\" | \"other\n\nexport interface EmbaddedContact {\n type: EmbaddedContactType\n value: string\n name?: string\n metadata?: Record<string, any>\n}\n","/**\n * Converts a Dart color (0xffXXXXXX) to a CSS-compatible number (0xXXXXXXFF).\n *\n * @param dartColor - The Dart color represented as a 32-bit integer (0xffXXXXXX).\n * @returns A number representing the color in CSS format (0xXXXXXXFF).\n */\nexport const convertDartColorToCssNumber = (dartColor: number): number => {\n const alpha = (dartColor >> 24) & 0xff // Extract alpha (high 8 bits)\n const rgb = dartColor & 0xffffff // Extract RGB (low 24 bits)\n\n // Return color as 0xXXXXXXFF (CSS format: RGB + alpha)\n return (rgb << 8) | alpha\n}\n\n/**\n * Converts a CSS color (0xXXXXXXFF) to HSL format.\n *\n * @param cssColor - The CSS color represented as a 32-bit integer (0xXXXXXXFF).\n * @returns An object with HSL values {h, s, l}.\n */\nexport const cssColorToHslString = (cssColor: number): string => {\n const r = ((cssColor >> 24) & 0xff) / 255 // Extract red channel\n const g = ((cssColor >> 16) & 0xff) / 255 // Extract green channel\n const b = ((cssColor >> 8) & 0xff) / 255 // Extract blue channel\n\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n let h = 0\n let s = 0\n let l = (max + min) / 2\n\n if (max !== min) {\n const d = max - min\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0)\n break\n case g:\n h = (b - r) / d + 2\n break\n case b:\n h = (r - g) / d + 4\n break\n }\n h /= 6\n }\n\n return `${Math.round(h * 360)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%`\n}\n\n/**\n * Trims and attempts to fix the phone number by:\n * - Removing all non-numeric characters\n * - Ensuring it starts with a '0'\n * @param phone - The input phone number string\n * @returns The cleaned phone number\n */\nexport function tryFixPhoneNumber(phone: string): string {\n phone = phone.trim() // Remove leading/trailing spaces\n // Remove all non-numeric characters\n phone = phone.replace(/\\D/g, '')\n // Ensure the phone number starts with '0'\n if (!phone.startsWith('0')) {\n phone = '0' + phone\n }\n return phone\n}\n\n/**\n * Validates the phone number based on specific rules:\n * - Cannot be empty or just \"0\"\n * - Must start with '05', '06', '07', or '02'\n * - Must be 10 digits for mobile numbers (05, 06, 07)\n * - Must be 9 digits for landline numbers (02)\n * @param phone - The input phone number string\n * @returns Error message if validation fails, otherwise null\n */\nexport function validatePhoneNumber(phone: string): string | null {\n // Helper function to handle length overflow/underflow messages\n const getLengthError = (requiredLength: number, actualLength: number): string => {\n const difference = actualLength - requiredLength\n if (difference > 0) {\n return `عدد الأرقام زائد عن ${requiredLength} رقماً بـ ${difference}`\n } else {\n const missingDigits = -difference\n if (missingDigits === 1) return 'ينقصك رقم واحد'\n if (missingDigits === 2) return 'ينقصك رقمان'\n return `ينقصك ${missingDigits} أرقام`\n }\n }\n\n if (phone === '0') {\n return 'اكمل رقم الهاتف'\n }\n\n // Check if phone number is empty\n if (!phone) {\n return 'رقم الهاتف لا يمكن أن يكون فارغاً.'\n }\n\n // Check if phone number contains only digits\n if (!/^\\d+$/.test(phone)) {\n return 'رقم الهاتف يجب أن يحتوي فقط على أرقام.'\n }\n\n // Ensure the phone starts with valid prefixes\n if (!/^(05|06|07|02)/.test(phone)) {\n return 'يجب أن يبدأ بـ 05, 06, 07, أو 02'\n }\n\n const length = phone.length\n\n // Validate mobile numbers (05, 06, 07 should be 10 digits)\n if (/^(05|06|07)/.test(phone)) {\n if (length !== 10) {\n return getLengthError(10, length)\n }\n }\n\n // Validate landline numbers (02 should be 9 digits)\n else if (phone.startsWith('02')) {\n if (length !== 9) {\n return getLengthError(9, length)\n }\n }\n\n // If all checks pass, return null (no errors)\n return null\n}\n"],"mappings":";AAAA,OAAO,WAA8B;;;ACQ9B,IAAe,kBAAf,MAAwC;AAAA,EAC7C;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,YAAY,UAAkB,QAAuB;AACnD,SAAK,WAAW;AAChB,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,KAAK,SAAuC;AAChD,UAAM,EAAE,I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,KAAK,MAAM,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,IAAI,GAAG,CAAC;AAChF;AASO,SAAS,kBAAkB,OAAuB;AACvD,UAAQ,MAAM,KAAK;AAEnB,UAAQ,MAAM,QAAQ,OAAO,EAAE;AAE/B,MAAI,CAAC,MAAM,WAAW,GAAG,GAAG;AAC1B,YAAQ,MAAM;AAAA,EAChB;AACA,SAAO;AACT;AAWO,SAAS,oBAAoB,OAA8B;AAEhE,QAAM,iBAAiB,CAAC,gBAAwB,iBAAiC;AAC/E,UAAM,aAAa,eAAe;AAClC,QAAI,aAAa,GAAG;AAClB,aAAO,uGAAuB,cAAc,gDAAa,UAAU;AAAA,IACrE,OAAO;AACL,YAAM,gBAAgB,CAAC;AACvB,UAAI,kBAAkB,EAAG,QAAO;AAChC,UAAI,kBAAkB,EAAG,QAAO;AAChC,aAAO,kCAAS,aAAa;AAAA,IAC/B;AAAA,EACF;AAEA,MAAI,UAAU,KAAK;AACjB,WAAO;AAAA,EACT;AAGA,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAGA,MAAI,CAAC,QAAQ,KAAK,KAAK,GAAG;AACxB,WAAO;AAAA,EACT;AAGA,MAAI,CAAC,iBAAiB,KAAK,KAAK,GAAG;AACjC,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,MAAM;AAGrB,MAAI,cAAc,KAAK,KAAK,GAAG;AAC7B,QAAI,WAAW,IAAI;AACjB,aAAO,eAAe,IAAI,MAAM;AAAA,IAClC;AAAA,EACF,WAGS,MAAM,WAAW,IAAI,GAAG;AAC/B,QAAI,WAAW,GAAG;AAChB,aAAO,eAAe,GAAG,MAAM;AAAA,IACjC;AAAA,EACF;AAGA,SAAO;AACT;","names":["OrderStatus","PaymentStatus","DeliveryStatus","ShippingType","ShippingMethodStatus","ShippingMethodPolicy","StoreMemberRole","StoreActionType","StoreSubscriptionStatus","StoreSubscriptionType","ProductStatus","ProductVariantView","VariantOptionType","ProductType","EmbaddedContactType"]}
@@ -83,4 +83,6 @@ export interface ProductOffer {
83
83
  title: string;
84
84
  subtitle?: string;
85
85
  price?: number;
86
+ minQuantity?: number;
87
+ maxQuantity?: number;
86
88
  }
@@ -12,6 +12,7 @@ export interface StoreEntity {
12
12
  domain: StoreDomain | null;
13
13
  decoration: StoreDecoration | null;
14
14
  name: string;
15
+ iconUrl: string | null;
15
16
  logoUrl: string | null;
16
17
  ondarkLogoUrl: string | null;
17
18
  userId: string;
@@ -76,6 +77,13 @@ export interface StoreBanner {
76
77
  export interface StoreDecoration {
77
78
  primary: number;
78
79
  onPrimary?: number;
80
+ primaryDark?: number;
81
+ onPrimaryDark?: number;
82
+ secondary?: number;
83
+ onSecondary?: number;
84
+ secondaryDark?: number;
85
+ onSecondaryDark?: number;
86
+ useLogoDarkFilter?: boolean;
79
87
  showStoreLogoInHeader?: boolean;
80
88
  logoFullHeight?: boolean;
81
89
  showStoreNameInHeader?: boolean;
@@ -44,6 +44,13 @@ export declare class CartService extends NotifiableService {
44
44
  * @param item - The item to be set as current.
45
45
  */
46
46
  setCurrentItem(item: CartItem, notify?: boolean): void;
47
+ /**
48
+ * Clamps the quantity to be within the offer's min/max range
49
+ * @param offer - The offer containing quantity constraints
50
+ * @param quantity - The quantity to clamp
51
+ * @returns The clamped quantity value
52
+ */
53
+ private clampQuantityToOfferLimits;
47
54
  /**
48
55
  * Update item by id.
49
56
  * @param id - The id of the item to update.
@@ -119,6 +126,13 @@ export declare class CartService extends NotifiableService {
119
126
  * @returns The total price for the item.
120
127
  */
121
128
  getItemTotal(item: CartItem): number;
129
+ /**
130
+ * Validates if an offer can be applied to the given quantity
131
+ * @param offer - The offer to validate
132
+ * @param quantity - The quantity to check
133
+ * @returns boolean indicating if the offer is valid for the quantity
134
+ */
135
+ isOfferValidForQuantity(offer: ProductOffer, quantity: number): boolean;
122
136
  /**
123
137
  * Updates the offer for a specific cart item
124
138
  * @param itemId - The ID of the item to update
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "feeef",
3
3
  "description": "feeef sdk for javascript",
4
- "version": "0.4.14",
4
+ "version": "0.5.0",
5
5
  "main": "build/index.js",
6
6
  "type": "module",
7
7
  "files": [