All files / src/stores useCartStore.ts

100% Statements 68/68
100% Branches 32/32
100% Functions 15/15
100% Lines 68/68

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                                                                                                  23x       23x             23x   3x 3x 3x   3x 1x     2x 2x 1x     3x       23x 9x 9x 1x         23x 9x 4x 4x 2x         23x             3x     1x     1x 1x     12x 12x   11x 11x 10x   9x   10x 9x       11x 11x 2x 1x                             11x   1x 1x         5x 1x   4x 1x   3x 3x   1x 1x     2x 2x   1x         6x 1x   5x 5x 1x 1x   4x 4x   1x 1x   3x   3x 3x   2x             23x 61x        
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import axios, { type AxiosInstance } from 'axios';
import { useLanguageStore } from './useLanguageStore';
import { useAuthStore } from './useAuthStore';
import { API_BASE_URL } from '../config';
import { logError, logWarn } from '../utils/logger';
 
interface RawCartItem {
  id:    number | null;
  product_id: number;
  quantity: string | number;
  unit_price: number;
  total_price: number;
  original_price: number | null;
  discount_rate: number | null;
  in_stock: boolean;
  available_quantity: number;
  product: {
    name:  string;
    image: string;
    date:  string;
    time?: string;
    location: string;
  };
}
 
export interface CartItem {
  id: string;
  name: string;
  image: string;
  date: string;
  time?: string;
  location: string;
  quantity: number;
  price: number;
  totalPrice?: number;
  inStock: boolean;
  availableQuantity: number;
  discountRate: number | null;
  originalPrice: number | null;
}
 
interface CartState {
  items: CartItem[];
  guestCartId: string | null;
  cartId: string | null;
  loadCart: () => Promise<void>;
  addItem: (id: string, quantity: number, availableQuantity: number) => Promise<void>;
  clearCart: () => Promise<void>;
  setGuestCartId: (id: string | null) => void;
  setCartId: (id: string | null) => void;
  isLocked: boolean;
  lockCart: () => void;
  unlockCart: () => void;
}
 
export const useCartStore = create<CartState>()(
  persist(
    (set, get) => {
      // Crée une instance Axios
      const axiosInstance: AxiosInstance = axios.create({
        baseURL: API_BASE_URL,
        timeout: Number(import.meta.env.VITE_AXIOS_TIMEOUT) || 5000,
        headers: { 'Content-Type': 'application/json' },
      });
 
      // Intercepteur de requêtes
      axiosInstance.interceptors.request.use((config) => {
        // Récupère le token depuis le store Zustand
        const token = useAuthStore.getState().authToken;
        const lang = useLanguageStore.getState().lang;
        config.headers!['Accept-Language'] = lang;
 
        if (token) {
          config.headers!['Authorization'] = `Bearer ${token}`;
        } else {
          // Si pas de token, on envoie l’UUID du panier invité (s’il existe)
          const guestCartId = get().guestCartId;
          if (guestCartId) {
            config.headers!['X-Guest-Cart-ID'] = guestCartId;
          }
        }
        return config;
      });
 
      // Synchronise guestCartId depuis meta.guest_cart_id
      const syncGuestCartId = (meta: any) => {
        const apiId = meta?.guest_cart_id;
        if (apiId && apiId !== get().guestCartId) {
          set({ guestCartId: apiId });
        }
      };
 
      // Synchronise cartId depuis data.id
      const syncCartId = (resData: any) => {
        if (resData?.id != null) {
          const apiCartId = String(resData.id);
          if (apiCartId !== get().cartId) {
            set({ cartId: apiCartId });
          }
        }
      };
 
      return {
        items: [],
        guestCartId: null,
        cartId: null,
 
        isLocked: false,
        lockCart: () => {
          set({ isLocked: true });
        },
        unlockCart: () => {
          set({ isLocked: false });
        },
 
        setGuestCartId: (id: string | null) => set({ guestCartId: id }),
        setCartId: (id: string | null) => set({ cartId: id }),
 
        loadCart: async () => {
          try {
            const res = await axiosInstance.get('/api/cart');
 
            const payload = res.data;
            if (payload) {
              if (payload.meta) {
                // Met à jour le guestCartId si l'API en retourne un (ou remet à jour le TTL)
                syncGuestCartId(res.data?.meta);
              }
              if (payload.data) {
                syncCartId(payload.data);
              }
            }
            // Mappe les RawCartItem vers CartItem
            const raw: RawCartItem[] = res.data?.data?.cart_items ?? [];
            const items: CartItem[] = raw
              .filter((ci) => ci.in_stock)
              .map((ci: RawCartItem) => ({
                id: ci.product_id.toString(),
                name: ci.product.name,
                image: ci.product.image,
                date: ci.product.date,
                time: ci.product.time ?? undefined,
                location: ci.product.location,
                quantity: Number(ci.quantity),
                price: ci.unit_price,
                totalPrice: ci.total_price,
                inStock: ci.in_stock,
                availableQuantity: ci.available_quantity,
                discountRate: ci.discount_rate,
                originalPrice: ci.original_price,
              }));
            set({ items });
          } catch (err) {
            logError('loadCart', err);
            throw err;
          }
        },
 
        addItem: async (id, quantity, availableQuantity) => {
          if (get().isLocked) {
            throw new Error('CartLocked');
          }
          if (quantity > availableQuantity) {
            throw new Error('Quantity exceeds available stock');
          }
          try {
            await axiosInstance.patch(`/api/cart/items/${id}`, { quantity });
          } catch (err) {
            logError('addItem', err);
            throw err;
          }
          // Tente de recharger le panier sans bloquer sur l’erreur
          try {
            await get().loadCart();
          } catch (warn) {
            logWarn('addItem → loadCart', warn);
          }
        },
 
        clearCart: async () => {
          if (get().isLocked) {
            throw new Error('CartLocked');
          }
          const token = useAuthStore.getState().authToken;
          if (!token) {
            logWarn('clearCart', 'no auth token');
            return;
          }
          try {
            await axiosInstance.delete('/api/cart/items');
          } catch (err) {
            logError('clearCart', err);
            throw err;
          }
          set({ items: [] });
          // Tente de recharger le panier sans bloquer sur l’erreur
          try {
            await get().loadCart();
          } catch (warn) {
            logWarn('clearCart → loadCart', warn);
          }
        },
      };
    },
    {
      name: 'cart-storage',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({ guestCartId: state.guestCartId, cartId: state.cartId }),
    }
  )
);