Skip to content

Commit

Permalink
Merge pull request #45 from CrystallizeAPI/fix/shop-operation
Browse files Browse the repository at this point in the history
replace edit operations with hydrate
  • Loading branch information
Plopix authored Jul 23, 2024
2 parents 019ecf7 + 3a28e6c commit a3380b7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 38 deletions.
44 changes: 6 additions & 38 deletions shared/application/use-cases/checkout/handleSaveCart.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addSkuItem, ClientInterface, removeCartItem } from '@crystallize/js-api-client';
import { ClientInterface } from '@crystallize/js-api-client';
import { fetchCart } from '../crystallize/read/fetchCart';
import { hydrateCart } from '../crystallize/write/editCart';

Expand All @@ -15,43 +15,11 @@ export default async (body: any, { apiClient }: Deps, markets?: string[]) => {
quantity: item.quantity,
}));

if (!cart || cart?.state === 'placed') {
return await hydrateCart(localCartItems, { apiClient }, '', markets);
} else {
const remoteCartItems = cart.items.map((item) => ({
sku: item.variant.sku,
quantity: item.quantity,
}));

// compare local and remote cart
for (const localItem of localCartItems) {
const remoteItem = remoteCartItems.find((item) => item.sku === localItem.sku);

if (!remoteItem) {
// item new in local cart, add
await addSkuItem(cartId, localItem.sku, localItem.quantity, {
apiClient,
});
} else if (localItem.quantity !== remoteItem.quantity) {
// item quantity changed, update
const quantityDiff = localItem.quantity - remoteItem.quantity;
if (quantityDiff > 0) {
await addSkuItem(cartId, localItem.sku, quantityDiff, {
apiClient,
});
} else {
await removeCartItem(cartId, localItem.sku, Math.abs(quantityDiff), { apiClient });
}
}
}
if (cartId) {
return await hydrateCart(localCartItems, { apiClient }, cartId, markets);
}

// check and remove items in remote cart that are not in local cart
for (const remoteItem of remoteCartItems) {
const localItem = localCartItems.find((item: any) => item.sku === remoteItem.sku);
if (!localItem) {
await removeCartItem(cartId, remoteItem.sku, remoteItem.quantity, { apiClient });
}
}
return await fetchCart(cartId, { apiClient });
if (!cartId || cart?.state === 'placed') {
return await hydrateCart(localCartItems, { apiClient }, '', markets);
}
};
8 changes: 8 additions & 0 deletions shared/application/use-cases/crystallize/write/editCart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ export const hydrateCart = async (
variant: {
name: true,
sku: true,
price: {
net: true,
gross: true,
taxAmount: true,
discounts: {
amount: true,
},
},
},
price: {
net: true,
Expand Down

0 comments on commit a3380b7

Please sign in to comment.