Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion cafe-management-sys/src/components/CartContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
generateCartItemId,
cartTotals,
buildOrderItems,
staleItemId,
} from '../utils/cartPricing';

const CartContext = createContext();
Expand Down Expand Up @@ -181,7 +182,19 @@ export const CartProvider = ({ children }) => {

setOrderError(errorMessage);
setOrderConfirmation(null);
throw new Error(errorMessage);
// A stored cart line may reference a menu item that no longer exists
// (e.g. deleted after a menu/DB change). Drop just that line so a
// retry succeeds and the customer can finish checkout.
const staleId = staleItemId(errorMessage);
if (staleId) {
setCartItems(prev => prev.filter((it) => it._id !== staleId));
setOrderError('One item in your cart is no longer available and was removed.');
}
throw new Error(
staleId
? 'An item in your cart is no longer available and was removed. Please review and try again.'
: errorMessage
);
} finally {
setIsLoading(false);
}
Expand Down
6 changes: 6 additions & 0 deletions cafe-management-sys/src/utils/cartPricing.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ export const generateCartItemId = (id, size, options) =>
.map(([key, value]) => `${key}:${value}`)
.join('|')}`;

/** Extracts the menu id from a server 'Menu item not found: <uuid>' error. */
export const staleItemId = (message = '') => {
const m = String(message).match(/Menu item not found: ([0-9a-f-]{8,})/i);
return m ? m[1] : null;
};

/** Shape cart lines into the server's `POST /orders` item contract. */
export const buildOrderItems = (items = []) =>
items.map((item) => ({
Expand Down
8 changes: 8 additions & 0 deletions cafe-management-sys/src/utils/cartPricing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
estimateTotals,
generateCartItemId,
buildOrderItems,
staleItemId,
} from './cartPricing';

const legacy = { _id: 'm1', price: { medium: 100, large: 150 }, quantity: 2, selectedSize: 'large' };
Expand Down Expand Up @@ -96,4 +97,11 @@ describe('cartPricing', () => {
specialInstructions: 'no ice',
});
});

it('staleItemId extracts a stale menu id from the server error', () => {
expect(staleItemId('Menu item not found: 55ffe79f-c6de-4a58-8bf3-7db2992c8fdf'))
.toBe('55ffe79f-c6de-4a58-8bf3-7db2992c8fdf');
expect(staleItemId('Something else')).toBeNull();
expect(staleItemId('')).toBeNull();
});
});
Loading