function getExistingLineItem( item, order ) { const lineItems = order.line_items || []; const matchedItem = ! item.productId ? { product_id: item.id } : { product_id: item.productId, variation_id: item.id }; const existingLineItem = find( lineItems, matchedItem ); if ( existingLineItem ) { const quantity = existingLineItem.quantity + 1; const subtotal = getOrderItemCost( order, existingLineItem.id ) * quantity; existingLineItem.quantity = quantity; existingLineItem.subtotal = subtotal; existingLineItem.total = subtotal; return existingLineItem; } return false; }
renderPrice = item => { const { order } = this.props; if ( this.isDiscountedProduct( item ) ) { const preDiscountCost = getOrderItemCost( order, item.id ); return ( <Fragment> <ins className="order-details__item-with-discount"> { formatCurrency( item.price, order.currency ) } </ins> <del className="order-details__item-pre-discount"> { formatCurrency( preDiscountCost, order.currency ) } </del> </Fragment> ); } return formatCurrency( item.price, order.currency ); };
onChange = event => { const { order } = this.props; // Name is `quantity-x`, where x is the ID of the item let id = event.target.name.split( '-' )[ 1 ]; if ( ! isNaN( parseInt( id ) ) ) { id = parseInt( id ); } const item = find( order.line_items, { id } ); if ( ! item ) { return; } const index = findIndex( order.line_items, { id } ); // A zero quantity does strange things with the price, so we'll force 1 const quantity = parseInt( event.target.value ) || 1; const subtotal = getOrderItemCost( order, id ) * quantity; const total = subtotal; const newItem = { ...item, quantity, subtotal, total }; this.props.onChange( { line_items: { [ index ]: newItem } } ); };