Introduced `useExactProducts` composable to fetch precise product details for guest cart and wishlist items. Improved cookie-based cart and wishlist fallback handling for unauthenticated users. Updated related components and composables for better synchronization and type safety. - Added `useExactProducts` composable leveraging the `GET_EXACT_PRODUCTS` query. - Enhanced `wishlist.vue` and `cart.vue` for reactive updates on guest state changes. - Improved product synchronization logic in `useOrderSync` and `useWishlistSync`. - Updated translations and fixed minor typos in localization files. Improves user experience by ensuring consistent product details, even for guests. No breaking changes.
73 lines
1.6 KiB
TypeScript
73 lines
1.6 KiB
TypeScript
import { useOrderOverwrite } from '@composables/orders/useOrderOverwrite';
|
|
|
|
export function useOrderSync() {
|
|
const cartStore = useCartStore();
|
|
const userStore = useUserStore();
|
|
const { $appHelpers } = useNuxtApp();
|
|
|
|
const { overwriteOrder } = useOrderOverwrite();
|
|
|
|
const isAuthenticated = computed(() => userStore.isAuthenticated);
|
|
const orderUuid = computed(() => cartStore.currentOrder?.uuid);
|
|
|
|
const cookieCart = useCookie($appHelpers.COOKIES_CART_KEY, {
|
|
default: () => [],
|
|
path: '/',
|
|
});
|
|
|
|
async function syncOrder() {
|
|
if (!isAuthenticated.value || !orderUuid.value) {
|
|
return;
|
|
}
|
|
|
|
const cookieCartItems = cookieCart.value || [];
|
|
|
|
if (cookieCartItems.length === 0) {
|
|
return;
|
|
}
|
|
|
|
const apiCartProducts = cartStore.currentOrder?.orderProducts?.edges || [];
|
|
|
|
const apiProductMap = new Map(
|
|
apiCartProducts.map((e) => [
|
|
e.node.product.uuid,
|
|
e.node.quantity,
|
|
]),
|
|
);
|
|
|
|
const productsToSync = [];
|
|
|
|
for (const cartItem of cookieCartItems) {
|
|
const apiQuantity = apiProductMap.get(cartItem.productUuid) || 0;
|
|
const quantityDifference = cartItem.quantity - apiQuantity;
|
|
|
|
if (quantityDifference > 0) {
|
|
for (let i = 0; i < quantityDifference; i++) {
|
|
productsToSync.push({
|
|
uuid: cartItem.productUuid,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
if (productsToSync.length === 0) {
|
|
cookieCart.value = [];
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await overwriteOrder({
|
|
type: 'bulk',
|
|
bulkAction: 'add',
|
|
isBulkSync: true,
|
|
products: productsToSync,
|
|
});
|
|
} catch (err) {
|
|
console.error('Failed to sync cart:', err);
|
|
}
|
|
}
|
|
|
|
return {
|
|
syncOrder,
|
|
};
|
|
}
|