All files / src/pages/admin taxonomy.tsx

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

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                                              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   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,
	CardContent,
	CardHeader,
	CardTitle,
} 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 { 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";
 
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">
				{/* Header */}
				<div>
					<h1 className="text-2xl font-bold text-foreground-default">
						Taxonomy Management
					</h1>
					<p className="text-foreground-muted">
						Manage all taxonomy data used across the platform.
					</p>
				</div>
 
				{/* Tabs */}
				<TaxonomyTypeSelector
					configs={TAXONOMY_CONFIGS}
					activeTab={activeTab}
					onTabChange={setActiveTab}
				/>
 
				{/* Filters and Actions */}
				<Card>
					<CardContent className="pt-6">
						<div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
							<div className="flex flex-col sm:flex-row gap-4 flex-1 w-full sm:w-auto">
								<div className="relative flex-1 max-w-md">
									<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle" />
									<Input
										placeholder="Search items..."
										value={search}
										onChange={(e) => setSearch(e.target.value)}
										className="pl-10"
									/>
								</div>
								<label className="flex items-center gap-2 cursor-pointer">
									<input
										type="checkbox"
										checked={includeInactive}
										onChange={(e) => setIncludeInactive(e.target.checked)}
										className="rounded border-border-default text-primary-600 focus:ring-primary-500"
									/>
									<span className="text-sm text-foreground-default">
										Show inactive items
									</span>
								</label>
							</div>
							<Button onClick={handleCreate}>
								<Plus className="h-4 w-4 mr-2" />
								Add {activeConfig.label.slice(0, -1)}
							</Button>
						</div>
					</CardContent>
				</Card>
 
				{/* Table */}
				<Card>
					<CardHeader>
						<CardTitle className="text-lg">
							{activeConfig.label}
							<span className="text-foreground-muted font-normal ml-2">
								({filteredItems.length} items)
							</span>
						</CardTitle>
						<p className="text-sm text-foreground-muted">
							{activeConfig.description}
						</p>
					</CardHeader>
					<CardContent>
						<TaxonomyList
							items={filteredItems}
							isLoading={isLoading}
							onEdit={handleEdit}
							onDelete={handleDelete}
							onToggleActive={handleToggleActive}
							onReorder={handleReorder}
							columns={activeConfig.columns}
						/>
					</CardContent>
				</Card>
 
				{/* 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>
	);
}