/* eslint-disable @typescript-eslint/no-non-null-assertion */ import * as uuid from 'uuid' import type { AssemblyOptionInput, OrderFormItemInput, CatalogItem, FullItem, Item, } from './typings' export const AVAILABLE = 'available' export const isSameItem = ( input: { id?: string | number; seller: string; options?: any[] }, item: Item, items: Array<{ id: string }> ) => { const isSameId = input.id?.toString() === item.id const isSameSeller = input.seller === item.seller /** * If item is a gift, it should not be considered as the same item of the added one, * otherwise buyer will not see two different products in the cart (the gift and the paid one) */ if (item.isGift) { return false } // input has no options if (input.options == null || !input.options?.length) { // and the comparing item has attachments, not the same item if ((item as any).attachments?.length) { return false } // neither have options, just compare id and seller return isSameId && isSameSeller } // does every option (assuming assembly option) existing in the cart as separate products? const optionsExistInCart = (input.options as AssemblyOptionInput[]).every( (opItem) => items.find((i) => i.id === opItem.id) ) return isSameId && isSameSeller && optionsExistInCart } export const adjustForItemInput = (item: { id?: string index?: number quantity: number seller: string options?: AssemblyOptionInput[] }): OrderFormItemInput => { return { id: +(item.id ?? 0), index: item.index, quantity: item.quantity, seller: item.seller, options: item.options, } } export const mapToOrderFormItem = ( itemInput: OrderFormItemInput, cartItem: Partial ): FullItem => { return { id: cartItem.id!, productId: cartItem.productId!, name: cartItem.name!, skuName: cartItem.skuName!, skuSpecifications: cartItem.skuSpecifications!, imageUrls: { at1x: cartItem.imageUrl!, at2x: cartItem.imageUrl!, at3x: cartItem.imageUrl!, }, price: cartItem.price!, listPrice: cartItem.listPrice!, sellingPrice: cartItem.sellingPrice!, measurementUnit: cartItem.measurementUnit!, quantity: cartItem.quantity ?? 1, unitMultiplier: cartItem.unitMultiplier ?? 1, uniqueId: itemInput.uniqueId ?? uuid.v4(), detailUrl: cartItem.detailUrl!, availability: cartItem.availability ?? AVAILABLE, additionalInfo: cartItem.additionalInfo!, options: cartItem.options, seller: cartItem.seller!, attachmentOfferings: [], attachments: [], bundleItems: [], offerings: [], priceTags: [], isGift: false, } } export const filterUndefined = (value: T | undefined): value is T => { return value !== undefined }