Merge pull request #143 from beatz174-bit/codex/find-and-refactor-duplicated-code
Refactor area and category management UI
This commit is contained in:
@@ -0,0 +1,194 @@
|
|||||||
|
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 {
|
||||||
|
Alert,
|
||||||
|
AlertColor,
|
||||||
|
Button,
|
||||||
|
IconButton,
|
||||||
|
List,
|
||||||
|
ListItem,
|
||||||
|
ListItemText,
|
||||||
|
Stack,
|
||||||
|
TextField,
|
||||||
|
} from '@mui/material';
|
||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
|
||||||
|
export interface EditableEntity {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
secondaryText?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ActionOutcome {
|
||||||
|
text?: string;
|
||||||
|
severity?: AlertColor;
|
||||||
|
success?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EditableEntityListProps {
|
||||||
|
nameLabel: string;
|
||||||
|
addButtonLabel?: string;
|
||||||
|
entityLabel?: string;
|
||||||
|
addPlaceholder?: string;
|
||||||
|
entities: EditableEntity[];
|
||||||
|
validateName?: (name: string, entityId?: string | null) => boolean;
|
||||||
|
onAdd: (name: string) => Promise<ActionOutcome | void>;
|
||||||
|
onUpdate: (id: string, name: string) => Promise<ActionOutcome | void>;
|
||||||
|
onDelete: (id: string, name: string) => Promise<ActionOutcome | void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FeedbackState {
|
||||||
|
text: string;
|
||||||
|
severity: AlertColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EditableEntityList = ({
|
||||||
|
nameLabel,
|
||||||
|
addButtonLabel = 'Add',
|
||||||
|
entityLabel = 'Item',
|
||||||
|
addPlaceholder,
|
||||||
|
entities,
|
||||||
|
validateName,
|
||||||
|
onAdd,
|
||||||
|
onUpdate,
|
||||||
|
onDelete,
|
||||||
|
}: EditableEntityListProps) => {
|
||||||
|
const [newName, setNewName] = useState('');
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [editName, setEditName] = useState('');
|
||||||
|
const [feedback, setFeedback] = useState<FeedbackState | null>(null);
|
||||||
|
|
||||||
|
const isNameValid = useMemo(() => {
|
||||||
|
return (value: string, entityId: string | null) => {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (!trimmed) return false;
|
||||||
|
if (validateName) return validateName(trimmed, entityId);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
}, [validateName]);
|
||||||
|
|
||||||
|
const applyOutcome = (outcome: ActionOutcome | void, defaultText: string, defaultSeverity: AlertColor = 'success') => {
|
||||||
|
const success = outcome?.success ?? outcome?.severity !== 'error';
|
||||||
|
const text = outcome?.text ?? defaultText;
|
||||||
|
const severity = outcome?.severity ?? defaultSeverity;
|
||||||
|
setFeedback({ text, severity });
|
||||||
|
return success;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAdd = async () => {
|
||||||
|
const trimmed = newName.trim();
|
||||||
|
if (!isNameValid(newName, null)) return;
|
||||||
|
try {
|
||||||
|
const success = applyOutcome(await onAdd(trimmed), `${entityLabel} added.`);
|
||||||
|
if (success) {
|
||||||
|
setNewName('');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setFeedback({ text: `Unable to add ${entityLabel.toLowerCase()}.`, severity: 'error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startEditing = (id: string, currentName: string) => {
|
||||||
|
setEditingId(id);
|
||||||
|
setEditName(currentName);
|
||||||
|
setFeedback(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelEditing = () => {
|
||||||
|
setEditingId(null);
|
||||||
|
setEditName('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!editingId) return;
|
||||||
|
const trimmed = editName.trim();
|
||||||
|
if (!isNameValid(editName, editingId)) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const success = applyOutcome(await onUpdate(editingId, trimmed), `${entityLabel} updated.`);
|
||||||
|
if (success) {
|
||||||
|
cancelEditing();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setFeedback({ text: `Unable to update ${entityLabel.toLowerCase()}.`, severity: 'error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (id: string, name: string) => {
|
||||||
|
try {
|
||||||
|
const success = applyOutcome(await onDelete(id, name), `${entityLabel} deleted.`);
|
||||||
|
if (success && editingId === id) {
|
||||||
|
cancelEditing();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setFeedback({ text: `Unable to delete ${entityLabel.toLowerCase()}.`, severity: 'error' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const canAdd = isNameValid(newName, null);
|
||||||
|
const canSave = editingId ? isNameValid(editName, editingId) : false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack spacing={2}>
|
||||||
|
{feedback ? <Alert severity={feedback.severity}>{feedback.text}</Alert> : null}
|
||||||
|
<Stack direction="row" spacing={1}>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
label={nameLabel}
|
||||||
|
placeholder={addPlaceholder}
|
||||||
|
value={newName}
|
||||||
|
onChange={(event) => setNewName(event.target.value)}
|
||||||
|
/>
|
||||||
|
<Button variant="contained" onClick={handleAdd} disabled={!canAdd}>
|
||||||
|
{addButtonLabel}
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
<List>
|
||||||
|
{entities.map((entity) => (
|
||||||
|
<ListItem key={entity.id} divider>
|
||||||
|
{editingId === entity.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={handleSave} disabled={!canSave} aria-label={`Save ${entityLabel}`}>
|
||||||
|
<CheckIcon />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton onClick={cancelEditing} aria-label="Cancel editing">
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
</Stack>
|
||||||
|
) : (
|
||||||
|
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
|
||||||
|
<ListItemText primary={entity.name} secondary={entity.secondaryText} />
|
||||||
|
<Stack direction="row" spacing={0.5}>
|
||||||
|
<IconButton
|
||||||
|
onClick={() => startEditing(entity.id, entity.name)}
|
||||||
|
aria-label={`Edit ${entity.name}`}
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
<EditIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
<IconButton
|
||||||
|
onClick={() => handleDelete(entity.id, entity.name)}
|
||||||
|
aria-label={`Delete ${entity.name}`}
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
<DeleteIcon fontSize="small" />
|
||||||
|
</IconButton>
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
)}
|
||||||
|
</ListItem>
|
||||||
|
))}
|
||||||
|
</List>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default EditableEntityList;
|
||||||
@@ -1,72 +1,35 @@
|
|||||||
import {
|
import { AlertColor, Container, Typography } from '@mui/material';
|
||||||
Alert,
|
|
||||||
AlertColor,
|
|
||||||
Button,
|
|
||||||
Container,
|
|
||||||
IconButton,
|
|
||||||
List,
|
|
||||||
ListItem,
|
|
||||||
ListItemText,
|
|
||||||
Stack,
|
|
||||||
TextField,
|
|
||||||
Typography,
|
|
||||||
} from '@mui/material';
|
|
||||||
import DeleteIcon from '@mui/icons-material/Delete';
|
|
||||||
import EditIcon from '@mui/icons-material/Edit';
|
|
||||||
import CheckIcon from '@mui/icons-material/Check';
|
|
||||||
import CloseIcon from '@mui/icons-material/Close';
|
|
||||||
import { useState } from 'react';
|
|
||||||
import { v4 as uuidv4 } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
import { useAreas } from '../hooks/dataHooks';
|
import { EditableEntityList, ActionOutcome } from '../components/EditableEntityList';
|
||||||
import { useDatabase } from '../context/DBProvider';
|
import { useDatabase } from '../context/DBProvider';
|
||||||
|
import { useAreas } from '../hooks/dataHooks';
|
||||||
|
|
||||||
const ManageAreasScreen = () => {
|
const ManageAreasScreen = () => {
|
||||||
const db = useDatabase();
|
const db = useDatabase();
|
||||||
const areas = useAreas();
|
const areas = useAreas();
|
||||||
const [name, setName] = useState('');
|
|
||||||
const [editingAreaId, setEditingAreaId] = useState<string | null>(null);
|
|
||||||
const [editName, setEditName] = useState('');
|
|
||||||
const [feedback, setFeedback] = useState<{ text: string; severity: AlertColor } | null>(null);
|
|
||||||
|
|
||||||
const addArea = async () => {
|
const addArea = async (name: string): Promise<ActionOutcome> => {
|
||||||
if (!name) return;
|
|
||||||
await db.areas.add({ id: uuidv4(), name, created_at: Date.now(), updated_at: Date.now() });
|
await db.areas.add({ id: uuidv4(), name, created_at: Date.now(), updated_at: Date.now() });
|
||||||
setName('');
|
return { text: 'Area added.', severity: 'success' };
|
||||||
};
|
};
|
||||||
|
|
||||||
const startEditing = (areaId: string, currentName: string) => {
|
const saveArea = async (areaId: string, updatedName: string): Promise<ActionOutcome> => {
|
||||||
setEditingAreaId(areaId);
|
await db.areas.update(areaId, { name: updatedName, updated_at: Date.now() });
|
||||||
setEditName(currentName);
|
return { text: 'Area updated.', severity: 'success' };
|
||||||
setFeedback(null);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const saveArea = async () => {
|
const deleteArea = async (areaId: string): Promise<ActionOutcome> => {
|
||||||
if (!editingAreaId || !editName) return;
|
|
||||||
await db.areas.update(editingAreaId, { name: editName, updated_at: Date.now() });
|
|
||||||
setEditingAreaId(null);
|
|
||||||
setEditName('');
|
|
||||||
setFeedback({ text: 'Area updated.', severity: 'success' });
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelEditing = () => {
|
|
||||||
setEditingAreaId(null);
|
|
||||||
setEditName('');
|
|
||||||
};
|
|
||||||
|
|
||||||
const deleteArea = async (areaId: string) => {
|
|
||||||
const usageCount = await db.pickLists.where('area_id').equals(areaId).count();
|
const usageCount = await db.pickLists.where('area_id').equals(areaId).count();
|
||||||
if (usageCount > 0) {
|
if (usageCount > 0) {
|
||||||
setFeedback({
|
return {
|
||||||
text: `Cannot delete this area while ${usageCount} pick list(s) use it. Remove those lists first.`,
|
text: `Cannot delete this area while ${usageCount} pick list(s) use it. Remove those lists first.`,
|
||||||
severity: 'error',
|
severity: 'error' satisfies AlertColor,
|
||||||
});
|
success: false,
|
||||||
return;
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.areas.delete(areaId);
|
await db.areas.delete(areaId);
|
||||||
if (editingAreaId === areaId) {
|
return { text: 'Area deleted.', severity: 'success' };
|
||||||
cancelEditing();
|
|
||||||
}
|
|
||||||
setFeedback({ text: 'Area deleted.', severity: 'success' });
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -74,59 +37,17 @@ const ManageAreasScreen = () => {
|
|||||||
<Typography variant="h5" gutterBottom>
|
<Typography variant="h5" gutterBottom>
|
||||||
Manage Areas
|
Manage Areas
|
||||||
</Typography>
|
</Typography>
|
||||||
<Stack spacing={2}>
|
<EditableEntityList
|
||||||
{feedback ? <Alert severity={feedback.severity}>{feedback.text}</Alert> : null}
|
nameLabel="Area name"
|
||||||
<Stack direction="row" spacing={1}>
|
addButtonLabel="Add"
|
||||||
<TextField fullWidth label="Area name" value={name} onChange={(event) => setName(event.target.value)} />
|
entityLabel="Area"
|
||||||
<Button variant="contained" onClick={addArea} disabled={!name}>
|
entities={areas.map((area) => ({ id: area.id, name: area.name }))}
|
||||||
Add
|
onAdd={addArea}
|
||||||
</Button>
|
onUpdate={saveArea}
|
||||||
</Stack>
|
onDelete={(areaId, areaName) => deleteArea(areaId)}
|
||||||
<List>
|
/>
|
||||||
{areas.map((area) => (
|
|
||||||
<ListItem key={area.id} divider>
|
|
||||||
{editingAreaId === area.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={saveArea} disabled={!editName} aria-label="Save area">
|
|
||||||
<CheckIcon />
|
|
||||||
</IconButton>
|
|
||||||
<IconButton onClick={cancelEditing} aria-label="Cancel editing">
|
|
||||||
<CloseIcon />
|
|
||||||
</IconButton>
|
|
||||||
</Stack>
|
|
||||||
) : (
|
|
||||||
<Stack direction="row" alignItems="center" spacing={1} sx={{ width: '100%' }}>
|
|
||||||
<ListItemText primary={area.name} />
|
|
||||||
<Stack direction="row" spacing={0.5}>
|
|
||||||
<IconButton
|
|
||||||
onClick={() => startEditing(area.id, area.name)}
|
|
||||||
aria-label={`Edit ${area.name}`}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<EditIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
<IconButton
|
|
||||||
onClick={() => deleteArea(area.id)}
|
|
||||||
aria-label={`Delete ${area.name}`}
|
|
||||||
size="small"
|
|
||||||
>
|
|
||||||
<DeleteIcon fontSize="small" />
|
|
||||||
</IconButton>
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</ListItem>
|
|
||||||
))}
|
|
||||||
</List>
|
|
||||||
</Stack>
|
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ManageAreasScreen
|
export default ManageAreasScreen;
|
||||||
|
|||||||
@@ -1,22 +1,7 @@
|
|||||||
import {
|
import { AlertColor, Container, Typography } from '@mui/material';
|
||||||
Alert,
|
import { useMemo } from 'react';
|
||||||
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 { v4 as uuidv4 } from 'uuid';
|
||||||
|
import { ActionOutcome, EditableEntityList } from '../components/EditableEntityList';
|
||||||
import { useDatabase } from '../context/DBProvider';
|
import { useDatabase } from '../context/DBProvider';
|
||||||
import { useCategories, useProducts } from '../hooks/dataHooks';
|
import { useCategories, useProducts } from '../hooks/dataHooks';
|
||||||
|
|
||||||
@@ -24,179 +9,110 @@ const ManageCategoriesScreen = () => {
|
|||||||
const db = useDatabase();
|
const db = useDatabase();
|
||||||
const categories = useCategories();
|
const categories = useCategories();
|
||||||
const products = useProducts();
|
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 categoriesById = useMemo(() => new Map(categories.map((c) => [c.id, c.name])), [categories]);
|
|
||||||
|
|
||||||
const usageByCategory = useMemo(() => {
|
const usageByCategory = useMemo(() => {
|
||||||
return products.reduce<Record<string, number>>((acc, product) => {
|
const categoriesById = new Map(categories.map((category) => [category.id, category.name]));
|
||||||
const categoryName = categoriesById.get(product.category) ?? product.category ?? '';
|
return products.reduce<Record<string, number>>((acc, product) => {
|
||||||
if (!categoryName) return acc;
|
const categoryName = categoriesById.get(product.category) ?? product.category ?? '';
|
||||||
acc[categoryName] = (acc[categoryName] ?? 0) + 1;
|
if (!categoryName) return acc;
|
||||||
return acc;
|
acc[categoryName] = (acc[categoryName] ?? 0) + 1;
|
||||||
}, {});
|
return acc;
|
||||||
}, [products, categoriesById]);
|
}, {});
|
||||||
|
}, [categories, products]);
|
||||||
|
|
||||||
|
const validateCategoryName = (value: string, editingId?: string | null) => {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (!trimmed) return false;
|
||||||
|
return !categories.some(
|
||||||
|
(category) => category.id !== editingId && category.name.toLowerCase() === trimmed.toLowerCase(),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const addCategory = async () => {
|
const addCategory = async (name: string): Promise<ActionOutcome> => {
|
||||||
const trimmed = name.trim();
|
const trimmed = name.trim();
|
||||||
if (!trimmed) return;
|
|
||||||
const exists = categories.some((category) => category.name.toLowerCase() === trimmed.toLowerCase());
|
const exists = categories.some((category) => category.name.toLowerCase() === trimmed.toLowerCase());
|
||||||
if (exists) {
|
if (exists) {
|
||||||
setFeedback({ text: 'A category with this name already exists.', severity: 'error' });
|
return { text: 'A category with this name already exists.', severity: 'error', success: false };
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.categories.add({ id: uuidv4(), name: trimmed, created_at: Date.now(), updated_at: Date.now() });
|
await db.categories.add({ id: uuidv4(), name: trimmed, created_at: Date.now(), updated_at: Date.now() });
|
||||||
setName('');
|
return { text: 'Category added.', severity: 'success' };
|
||||||
setFeedback({ text: 'Category added.', severity: 'success' });
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const startEditing = (categoryId: string, currentName: string) => {
|
const saveCategory = async (categoryId: string, updatedName: string): Promise<ActionOutcome> => {
|
||||||
setEditingCategoryId(categoryId);
|
const trimmed = updatedName.trim();
|
||||||
setEditName(currentName);
|
const category = categories.find((item) => item.id === categoryId);
|
||||||
setFeedback(null);
|
if (!category) return { text: 'Category not found.', severity: 'error', success: false };
|
||||||
};
|
|
||||||
|
|
||||||
const saveCategory = async () => {
|
const nameExists = categories.some(
|
||||||
if (!editingCategoryId) return;
|
(item) => item.id !== categoryId && item.name.toLowerCase() === trimmed.toLowerCase(),
|
||||||
const trimmed = editName.trim();
|
|
||||||
if (!trimmed) return;
|
|
||||||
|
|
||||||
const category = categories.find((item) => item.id === editingCategoryId);
|
|
||||||
if (!category) return;
|
|
||||||
|
|
||||||
const nameExists = categories.some(
|
|
||||||
(item) => item.id !== editingCategoryId && item.name.toLowerCase() === trimmed.toLowerCase(),
|
|
||||||
);
|
|
||||||
if (nameExists) {
|
|
||||||
setFeedback({ text: 'A category with this name already exists.', severity: 'error' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.transaction('rw', db.categories, db.products, db.pickLists, async () => {
|
|
||||||
// Update category name
|
|
||||||
await db.categories.update(editingCategoryId, { name: trimmed, updated_at: Date.now() });
|
|
||||||
|
|
||||||
// For backward-compat products that stored category as the old name,
|
|
||||||
// update them to reference the new name OR ideally, to the id.
|
|
||||||
// We map products that still have category === oldName to the new name value.
|
|
||||||
// (If you ran the normalization migration earlier, most products will already have ids.)
|
|
||||||
await db.products
|
|
||||||
.where('category')
|
|
||||||
.equals(category.name)
|
|
||||||
.modify({ category: trimmed, updated_at: Date.now() });
|
|
||||||
|
|
||||||
// Update pickLists that used the old category name
|
|
||||||
const pickLists = await db.pickLists.toArray();
|
|
||||||
await Promise.all(
|
|
||||||
pickLists.map(async (pl) => {
|
|
||||||
if (!Array.isArray((pl as any).categories)) return;
|
|
||||||
const needs = (pl as any).categories.includes(category.name);
|
|
||||||
if (!needs) return;
|
|
||||||
const updated = (pl as any).categories.map((c: string) => (c === category.name ? trimmed : c));
|
|
||||||
await db.pickLists.update(pl.id, { categories: updated });
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
});
|
if (nameExists) {
|
||||||
|
return { text: 'A category with this name already exists.', severity: 'error', success: false };
|
||||||
|
}
|
||||||
|
|
||||||
setEditingCategoryId(null);
|
await db.transaction('rw', db.categories, db.products, db.pickLists, async () => {
|
||||||
setEditName('');
|
await db.categories.update(categoryId, { name: trimmed, updated_at: Date.now() });
|
||||||
setFeedback({ text: 'Category updated. Linked products were refreshed.', severity: 'success' });
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancelEditing = () => {
|
await db.products.where('category').equals(category.name).modify({ category: trimmed, updated_at: Date.now() });
|
||||||
setEditingCategoryId(null);
|
|
||||||
setEditName('');
|
const pickLists = await db.pickLists.toArray();
|
||||||
setFeedback(null);
|
await Promise.all(
|
||||||
|
pickLists.map(async (pickList) => {
|
||||||
|
if (!Array.isArray((pickList as any).categories)) return;
|
||||||
|
const needsUpdate = (pickList as any).categories.includes(category.name);
|
||||||
|
if (!needsUpdate) return;
|
||||||
|
const updatedCategories = (pickList as any).categories.map((existing: string) =>
|
||||||
|
existing === category.name ? trimmed : existing,
|
||||||
|
);
|
||||||
|
await db.pickLists.update(pickList.id, { categories: updatedCategories });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { text: 'Category updated. Linked products were refreshed.', severity: 'success' };
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteCategory = async (categoryId: string, categoryName: string) => {
|
const deleteCategory = async (categoryId: string, categoryName: string): Promise<ActionOutcome> => {
|
||||||
// Count products referencing either the id or the name (legacy)
|
const [countById, countByName] = await Promise.all([
|
||||||
const [countById, countByName] = await Promise.all([
|
db.products.where('category').equals(categoryId).count(),
|
||||||
db.products.where('category').equals(categoryId).count(),
|
db.products.where('category').equals(categoryName).count(),
|
||||||
db.products.where('category').equals(categoryName).count(),
|
]);
|
||||||
]);
|
const usageCount = countById + countByName;
|
||||||
const usageCount = countById + countByName;
|
|
||||||
|
|
||||||
if (usageCount > 0) {
|
if (usageCount > 0) {
|
||||||
setFeedback({
|
return {
|
||||||
text: `Cannot delete '${categoryName}' while ${usageCount} product(s) use it. Update those products first.`,
|
text: `Cannot delete '${categoryName}' while ${usageCount} product(s) use it. Update those products first.`,
|
||||||
severity: 'error',
|
severity: 'error' satisfies AlertColor,
|
||||||
});
|
success: false,
|
||||||
return;
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.categories.delete(categoryId);
|
|
||||||
if (editingCategoryId === categoryId) cancelEditing();
|
|
||||||
setFeedback({ text: 'Category deleted.', severity: 'success' });
|
|
||||||
};
|
|
||||||
|
|
||||||
|
await db.categories.delete(categoryId);
|
||||||
|
return { text: 'Category deleted.', severity: 'success' };
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Container sx={{ py: 4 }}>
|
<Container sx={{ py: 4 }}>
|
||||||
<Typography variant="h5" gutterBottom>
|
<Typography variant="h5" gutterBottom>
|
||||||
Manage Categories
|
Manage Categories
|
||||||
</Typography>
|
</Typography>
|
||||||
<Stack spacing={2}>
|
<EditableEntityList
|
||||||
{feedback ? <Alert severity={feedback.severity}>{feedback.text}</Alert> : null}
|
nameLabel="Category name"
|
||||||
<Stack direction="row" spacing={1}>
|
addButtonLabel="Add"
|
||||||
<TextField
|
entityLabel="Category"
|
||||||
fullWidth
|
entities={categories.map((category) => ({
|
||||||
label="Category name"
|
id: category.id,
|
||||||
value={name}
|
name: category.name,
|
||||||
onChange={(event) => setName(event.target.value)}
|
secondaryText: `Used by ${usageByCategory[category.name] ?? 0} product(s)`,
|
||||||
/>
|
}))}
|
||||||
<Button variant="contained" onClick={addCategory} disabled={!name.trim()}>
|
validateName={validateCategoryName}
|
||||||
Add
|
onAdd={addCategory}
|
||||||
</Button>
|
onUpdate={saveCategory}
|
||||||
</Stack>
|
onDelete={deleteCategory}
|
||||||
<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>
|
</Container>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ManageCategoriesScreen
|
export default ManageCategoriesScreen;
|
||||||
|
|||||||
Reference in New Issue
Block a user