All files / src/pages/admin taxonomy.tsx

100% Statements 59/59
92.3% Branches 12/13
100% Functions 15/15
100% Lines 57/57

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 215 216 217 218 219                                                80x 80x 80x 80x 80x 80x 80x   80x           80x   80x 115x     80x 6x 6x     80x 4x 4x     80x 4x   4x 1x   3x 3x     4x 1x   3x   3x     3x 3x 3x   1x       80x 3x               1x   2x 2x 1x       1x 1x       80x 2x 2x     1x       1x 1x       80x 4x         2x 2x 1x       1x 1x       80x                                                           5x           2x                                                                 2x 2x                              
import { useState } from "react";
import { notify } from "../../lib/notify";
import { useQueryClient } from "@tanstack/react-query";
import { Plus, Search } from "lucide-react";
 
import { Card } from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { TaxonomyList } from "../../components/admin/taxonomy-list";
import { TaxonomyForm } from "../../components/admin/taxonomy-form";
import { TaxonomyTypeSelector } from "../../components/admin/TaxonomyTypeSelector";
import {
	AdminBand,
	AdminPageHead,
	AdminToolbar,
} from "../../components/admin/AdminPageHead";
import { adminApi, getErrorMessage, type TaxonomyItem } from "../../lib/api";
import { TAXONOMY_CONFIGS, type TaxonomyType } from "./taxonomy.config";
import { useConfirmDialog } from "../../hooks";
import { useAdminTaxonomy } from "../../hooks/queries/useAdminQueries";
import { queryKeys } from "../../lib/query-keys";
import { Checkbox } from "../../components/ui/checkbox";
 
export function AdminTaxonomyPage() {
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
	const [activeTab, setActiveTab] = useState<TaxonomyType>("businessTypes");
	const [search, setSearch] = useState("");
	const [showForm, setShowForm] = useState(false);
	const [editingItem, setEditingItem] = useState<TaxonomyItem | null>(null);
	const [includeInactive, setIncludeInactive] = useState(false);
 
	const { data: items = [], isLoading } = useAdminTaxonomy(
		activeTab,
		includeInactive,
	);
 
	const activeConfig =
		TAXONOMY_CONFIGS.find((c) => c.key === activeTab) || TAXONOMY_CONFIGS[0];
 
	const filteredItems = items.filter((item) =>
		item.name.toLowerCase().includes(search.toLowerCase()),
	);
 
	const handleCreate = () => {
		setEditingItem(null);
		setShowForm(true);
	};
 
	const handleEdit = (item: TaxonomyItem) => {
		setEditingItem(item);
		setShowForm(true);
	};
 
	const handleSubmit = async (data: Record<string, unknown>) => {
		try {
			// Convert pinCodes string to array if present
			if (data.pinCodes && typeof data.pinCodes === "string") {
				data.pinCodes = (data.pinCodes as string)
					.split(",")
					.map((p) => p.trim())
					.filter((p) => p);
			}
 
			if (editingItem) {
				await adminApi.updateTaxonomyItem(activeTab, editingItem.id, data);
			} else {
				await adminApi.createTaxonomyItem(activeTab, data);
			}
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.taxonomy(activeTab),
			});
			notify.success("Saved successfully");
			setShowForm(false);
			setEditingItem(null);
		} catch (err) {
			notify.error(getErrorMessage(err));
		}
	};
 
	const handleDelete = async (item: TaxonomyItem) => {
		if (
			!(await confirm({
				title: "Delete item",
				description: `Are you sure you want to delete "${item.name}"?`,
				confirmLabel: "Delete",
				variant: "destructive",
			}))
		)
			return;
 
		try {
			await adminApi.deleteTaxonomyItem(activeTab, item.id);
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.taxonomy(activeTab),
			});
		} catch (err) {
			console.error("Failed to delete item:", err);
			notify.error("Failed to delete item. Please try again.");
		}
	};
 
	const handleToggleActive = async (item: TaxonomyItem) => {
		try {
			await adminApi.updateTaxonomyItem(activeTab, item.id, {
				isActive: !item.isActive,
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.taxonomy(activeTab),
			});
		} catch (err) {
			console.error("Failed to toggle active status:", err);
			notify.error("Failed to update status. Please try again.");
		}
	};
 
	const handleReorder = async (reorderedItems: TaxonomyItem[]) => {
		const updates = reorderedItems.map((item, index) => ({
			id: item.id,
			sortOrder: index,
		}));
 
		try {
			await adminApi.reorderTaxonomy(activeTab, updates);
			queryClient.invalidateQueries({
				queryKey: queryKeys.admin.taxonomy(activeTab),
			});
		} catch (err) {
			console.error("Failed to reorder items:", err);
			notify.error("Failed to reorder items. Please try again.");
		}
	};
 
	return (
		<div className="space-y-6">
			<AdminPageHead
				title="Taxonomy Management"
				description="Manage all taxonomy data used across the platform."
				actions={
					<Button onClick={handleCreate}>
						<Plus aria-hidden="true" />
						Add {activeConfig.label.slice(0, -1)}
					</Button>
				}
			/>
 
			{/* Tabs */}
			<TaxonomyTypeSelector
				configs={TAXONOMY_CONFIGS}
				activeTab={activeTab}
				onTabChange={setActiveTab}
			/>
 
			<AdminToolbar aria-label="Taxonomy filters">
				<div className="relative min-w-56 max-w-md grow">
					<Search
						aria-hidden="true"
						className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground-subtle"
					/>
					<Input
						placeholder="Search items..."
						aria-label="Search taxonomy items"
						value={search}
						onChange={(e) => setSearch(e.target.value)}
						className="pl-10"
					/>
				</div>
				<Checkbox
					checked={includeInactive}
					onChange={(e) => setIncludeInactive(e.target.checked)}
				>
					Show inactive items
				</Checkbox>
			</AdminToolbar>
 
			<section className="space-y-2">
				<div className="flex items-baseline gap-2">
					<AdminBand title={activeConfig.label} quiet className="grow" />
					<span className="text-xs font-semibold tabular-nums text-foreground-muted">
						({filteredItems.length} items)
					</span>
				</div>
				<p className="text-sm text-foreground-muted">
					{activeConfig.description}
				</p>
				<Card className="overflow-hidden">
					<TaxonomyList
						items={filteredItems}
						isLoading={isLoading}
						onEdit={handleEdit}
						onDelete={handleDelete}
						onToggleActive={handleToggleActive}
						onReorder={handleReorder}
						columns={activeConfig.columns}
					/>
				</Card>
			</section>
 
			{/* Form Modal */}
			<TaxonomyForm
				isOpen={showForm}
				onClose={() => {
					setShowForm(false);
					setEditingItem(null);
				}}
				onSubmit={handleSubmit}
				item={editingItem}
				title={
					editingItem
						? `Edit ${activeConfig.label.slice(0, -1)}`
						: `Add ${activeConfig.label.slice(0, -1)}`
				}
				fields={activeConfig.formFields}
			/>
			{confirmDialog}
		</div>
	);
}