All files / src/components/CartPreview CartPreview.tsx

100% Statements 43/43
100% Branches 32/32
100% Functions 12/12
100% Lines 37/37

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                                                  31x 31x 31x     31x     31x 31x 31x 31x     31x 31x 31x   31x 31x   31x 15x 15x     31x   31x   12x 4x 4x   8x 8x 1x       1x   7x 7x 5x 3x         2x           2x 1x   1x             31x                                                                                                 25x               4x                                             8x                                                                              
import React, { useState, useCallback } from 'react';
import IconButton    from '@mui/material/IconButton';
import Badge         from '@mui/material/Badge';
import Popover       from '@mui/material/Popover';
import List          from '@mui/material/List';
import ListItem      from '@mui/material/ListItem';
import ListItemText  from '@mui/material/ListItemText';
import Button        from '@mui/material/Button';
import Typography    from '@mui/material/Typography';
import Box           from '@mui/material/Box';
import Tooltip       from '@mui/material/Tooltip';
import OlympicLoader from '../OlympicLoader';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import AddIcon       from '@mui/icons-material/Add';
import RemoveIcon    from '@mui/icons-material/Remove';
import { useCartStore, type CartItem } from '../../stores/useCartStore';
import { useLanguageStore } from '../../stores/useLanguageStore';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { formatCurrency } from '../../utils/format';
import { useReloadCart } from '../../hooks/useReloadCart';
import { useStockChangeNotifier } from '../../hooks/useStockChangeNotifier';
import { useCustomSnackbar } from '../../hooks/useCustomSnackbar';
 
export default function CartPreview() {
  const { t } = useTranslation(['common', 'cart']);
  const { notify } = useCustomSnackbar();
  const lang = useLanguageStore(s => s.lang);
 
  // Reload logic extracted
  const { loading, hasError, reload, isReloading } = useReloadCart();
 
  // Items from store
  const items = useCartStore(s => s.items);
  useStockChangeNotifier(items, isReloading);
  const addItem = useCartStore.getState().addItem;
  const isLocked = useCartStore(s => s.isLocked);
 
  // Popover state
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const open = Boolean(anchorEl);
  const id = open ? 'cart-popover' : undefined;
 
  const cartCount = items.reduce((sum, i) => sum + i.quantity, 0);
  const total = items.reduce((sum, i) => sum + i.quantity * i.price, 0);
 
  const handleOpen = useCallback((e: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(e.currentTarget);
    reload();
  }, [reload]);
 
  const handleClose = useCallback(() => setAnchorEl(null), []);
 
  const adjustQty = useCallback(
    async (item: CartItem, delta: number) => {
      if (isLocked) {
        notify(t('cart:errors.cart_locked'), 'warning');
        return;
      }
      const newQty = Math.max(0, item.quantity + delta);
      if (newQty > item.availableQuantity) {
        notify(
          t('cart:cart.not_enough_stock', { count: item.availableQuantity }),
          'warning'
        );
        return;
      }
      try {
        await addItem(item.id, newQty, item.availableQuantity);
        if (delta > 0) {
        notify(
          t('cart:cart.add_success'),
          'success'
        );
        } else {
          notify(
            t('cart:cart.remove_success'), 
            'success'
          );
        } 
      } catch (err: any) {
        if (err.message === 'CartLocked') {
          notify(t('cart:errors.cart_locked'), 'warning');
        } else {
          notify(t('cart:errors.error_update'), 'error');
        }
      }
    },
    [addItem, notify, t, isLocked]
  );
 
  return (
    <>
      <IconButton
        aria-describedby={id}
        onClick={handleOpen}
        color="inherit"
        aria-label={t('common:navbar.cart')}
      >
        <Badge
          badgeContent={cartCount}
          color="info"
          anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        >
          <ShoppingCartIcon />
        </Badge>
      </IconButton>
 
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        sx={{ '& .MuiPopover-paper': { width: 300, p: 1 } }}
      >
        {isLocked && (
          <Box sx={{ p: 1 }}>
            <Typography variant="body2" color="warning.main">
              {t('cart:cart.payment_in_progress')}
            </Typography>
          </Box>
        )}
        {loading ? (
          <Box sx={{ p: 2, textAlign: 'center' }}>
            <OlympicLoader />
          </Box>
        ) : hasError ? (
          <Typography sx={{ p: 2 }} variant="body2">
            {t('cart:cart.unavailable')}
          </Typography>
        ) : items.length === 0 ? (
          <Typography sx={{ p: 2 }} variant="body2">
            {t('cart:cart.empty')}
          </Typography>
        ) : (
          <Box>
            <List dense aria-live="polite">
              {items.map(item => (
                <ListItem
                  key={item.id}
                  secondaryAction={
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <Tooltip title={isLocked ? t('cart:errors.cart_locked') : t('cart:cart.remove_one')}>
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => adjustQty(item, -1)}
                            disabled={loading || item.quantity <= 0}
                            sx={isLocked ? { opacity: 0.5 } : undefined}
                          >
                            <RemoveIcon fontSize="small" />
                          </IconButton>
                        </span>
                      </Tooltip>
 
                      <Typography sx={{ mx: 0.5 }}>{item.quantity}</Typography>
 
                      <Tooltip
                        title={
                          isLocked
                            ? t('cart:errors.cart_locked')
                            : item.quantity >= item.availableQuantity
                              ? t('cart:cart.max_reached', { count: item.availableQuantity })
                              : t('cart:cart.add_one')
                        }
                      >
                        <span>
                          <IconButton
                            size="small"
                            onClick={() => adjustQty(item, +1)}
                            disabled={loading || item.quantity >= item.availableQuantity}
                            sx={isLocked ? { opacity: 0.5 } : undefined}
                          >
                            <AddIcon fontSize="small" />
                          </IconButton>
                        </span>
                      </Tooltip>
                    </Box>
                  }
                >
                  <ListItemText
                    primary={item.name}
                    secondary={formatCurrency(item.price, lang, 'EUR')}
                  />
                </ListItem>
              ))}
            </List>
 
            <Box sx={{ display: 'flex', justifyContent: 'space-between', p: 1 }}>
              <Typography variant="subtitle1">
                {t('cart:cart.total')} : {formatCurrency(total, lang, 'EUR')}
              </Typography>
              <Button
                component={Link}
                to="/cart"
                variant="contained"
                size="small"
                onClick={handleClose}
                disabled={loading}
              >
                {t('cart:cart.view')}
              </Button>
            </Box>
          </Box>
        )}
      </Popover>
    </>
  );
}