All files / screens ManageCategoriesScreen.tsx

80.88% Statements 55/68
60.71% Branches 17/28
94.11% Functions 16/17
85.48% Lines 53/62

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                                            1x 28x 28x 28x 28x 28x 28x 28x   28x 4x 4x 4x       28x 2x 2x 2x 2x 1x 1x   1x 1x 1x     28x 1x 1x 1x     28x 1x 1x 1x   1x 1x   1x 1x   1x         1x 1x 1x           1x 1x 1x     28x           28x 1x 1x 1x       1x                 28x                       12x               28x             7x                           1x             1x                                
import {
  Alert,
  AlertColor,
  Button,
  Container,
  IconButton,
  List,
  ListItem,
  ListItemText,
  Stack,
  TextField,
  Typography,
} from '@mui/material';
import CheckIcon from '@mui/icons-material/Check';
import CloseIcon from '@mui/icons-material/Close';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import { useMemo, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { useDatabase } from '../context/DBProvider';
import { useCategories, useProducts } from '../hooks/dataHooks';
 
export const ManageCategoriesScreen = () => {
  const db = useDatabase();
  const categories = useCategories();
  const products = useProducts();
  const [name, setName] = useState('');
  const [editingCategoryId, setEditingCategoryId] = useState<string | null>(null);
  const [editName, setEditName] = useState('');
  const [feedback, setFeedback] = useState<{ text: string; severity: AlertColor } | null>(null);
 
  const usageByCategory = useMemo(() => {
    return products.reduce<Record<string, number>>((acc, product) => {
      acc[product.category] = (acc[product.category] ?? 0) + 1;
      return acc;
    }, {});
  }, [products]);
 
  const addCategory = async () => {
    const trimmed = name.trim();
    Iif (!trimmed) return;
    const exists = categories.some((category) => category.name.toLowerCase() === trimmed.toLowerCase());
    if (exists) {
      setFeedback({ text: 'A category with this name already exists.', severity: 'error' });
      return;
    }
    await db.categories.add({ id: uuidv4(), name: trimmed, created_at: Date.now(), updated_at: Date.now() });
    setName('');
    setFeedback({ text: 'Category added.', severity: 'success' });
  };
 
  const startEditing = (categoryId: string, currentName: string) => {
    setEditingCategoryId(categoryId);
    setEditName(currentName);
    setFeedback(null);
  };
 
  const saveCategory = async () => {
    Iif (!editingCategoryId) return;
    const trimmed = editName.trim();
    Iif (!trimmed) return;
 
    const category = categories.find((item) => item.id === editingCategoryId);
    Iif (!category) return;
 
    const nameExists = categories.some(
      (item) => item.id !== editingCategoryId && item.name.toLowerCase() === trimmed.toLowerCase(),
    );
    Iif (nameExists) {
      setFeedback({ text: 'A category with this name already exists.', severity: 'error' });
      return;
    }
 
    await db.transaction('rw', db.categories, db.products, async () => {
      await db.categories.update(editingCategoryId, { name: trimmed, updated_at: Date.now() });
      await db.products
        .where('category')
        .equals(category.name)
        .modify({ category: trimmed, updated_at: Date.now() });
    });
 
    setEditingCategoryId(null);
    setEditName('');
    setFeedback({ text: 'Category updated. Linked products were refreshed.', severity: 'success' });
  };
 
  const cancelEditing = () => {
    setEditingCategoryId(null);
    setEditName('');
    setFeedback(null);
  };
 
  const deleteCategory = async (categoryId: string, categoryName: string) => {
    const usageCount = usageByCategory[categoryName] ?? 0;
    Eif (usageCount > 0) {
      setFeedback({
        text: `Cannot delete '${categoryName}' while ${usageCount} product(s) use it. Update those products first.`,
        severity: 'error',
      });
      return;
    }
    await db.categories.delete(categoryId);
    if (editingCategoryId === categoryId) {
      cancelEditing();
    }
    setFeedback({ text: 'Category deleted.', severity: 'success' });
  };
 
  return (
    <Container sx={{ py: 4 }}>
      <Typography variant="h5" gutterBottom>
        Manage Categories
      </Typography>
      <Stack spacing={2}>
        {feedback ? <Alert severity={feedback.severity}>{feedback.text}</Alert> : null}
        <Stack direction="row" spacing={1}>
          <TextField
            fullWidth
            label="Category name"
            value={name}
            onChange={(event) => setName(event.target.value)}
          />
          <Button variant="contained" onClick={addCategory} disabled={!name.trim()}>
            Add
          </Button>
        </Stack>
        <List>
          {categories.map((category) => (
            <ListItem key={category.id} divider>
              {editingCategoryId === category.id ? (
                <Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
                  <TextField
                    size="small"
                    fullWidth
                    value={editName}
                    onChange={(event) => setEditName(event.target.value)}
                  />
                  <IconButton color="primary" onClick={saveCategory} disabled={!editName.trim()} aria-label="Save category">
                    <CheckIcon />
                  </IconButton>
                  <IconButton onClick={cancelEditing} aria-label="Cancel editing">
                    <CloseIcon />
                  </IconButton>
                </Stack>
              ) : (
                <Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
                  <ListItemText primary={category.name} secondary={`Used by ${usageByCategory[category.name] ?? 0} product(s)`} />
                  <Stack direction="row" spacing={0.5}>
                    <IconButton
                      onClick={() => startEditing(category.id, category.name)}
                      aria-label={`Edit ${category.name}`}
                      size="small"
                    >
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      onClick={() => deleteCategory(category.id, category.name)}
                      aria-label={`Delete ${category.name}`}
                      size="small"
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Stack>
                </Stack>
              )}
            </ListItem>
          ))}
        </List>
      </Stack>
    </Container>
  );
};