All files / app/shipping updateShippableItems.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59    6x   6x               6x   9x 9x   9x 3x     8x   6x 5x     6x   6x 17x 7x   7x           10x           6x 2x     4x 4x 6x     6x   4x    
import { Address, Cart, Consignment } from '@bigcommerce/checkout-sdk';
 
import { isEqualAddress } from '../address';
 
import findConsignment from './findConsignment';
import ShippableItem from './ShippableItem';
 
export interface UpdateItemParams {
    updatedItemIndex: number;
    address: Address;
}
 
export default function updateShippableItems(
    items: ShippableItem[],
    { updatedItemIndex, address }: UpdateItemParams,
    { cart, consignments }: { cart?: Cart; consignments?: Consignment[] }
): ShippableItem[] | undefined {
    if (updatedItemIndex < 0 || updatedItemIndex >= items.length || !cart) {
        return;
    }
 
    const cartItemIds = cart.lineItems.physicalItems.map(({ id }) => id);
 
    const updatedConsignment = (consignments || []).find(consignment =>
        isEqualAddress(consignment.shippingAddress, address)
    );
 
    const newId = findNewItemId(items[updatedItemIndex], cart, updatedConsignment);
 
    return items.map((item, i) => {
        if (newId && !cartItemIds.includes(item.id) || i === updatedItemIndex) {
            const itemId = newId ?? item.id;
 
            return {
                ...item,
                id: itemId,
                consignment: findConsignment(consignments || [], itemId as string),
            };
        } else {
            return item;
        }
    });
}
 
function findNewItemId(item: ShippableItem, cart?: Cart, consignment?: Consignment): string | undefined {
    if (!cart || !consignment) {
        return;
    }
 
    const { physicalItems } = cart.lineItems;
    const matchingCartItems = physicalItems.filter(
        ({ productId, variantId }) => productId === item.productId && variantId === item.variantId
    );
 
    const matchingCartItemIds = matchingCartItems.map(({ id }) => id);
 
    return consignment.lineItemIds.find(id => matchingCartItemIds.includes(id));
}