tuman added
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import type { MyDiscrictData } from "@/features/district/lib/data";
|
||||
import { useDebounce } from "@/shared/hooks/useDebounce";
|
||||
import AddedButton from "@/shared/ui/added-button";
|
||||
import { Button } from "@/shared/ui/button";
|
||||
import {
|
||||
@@ -24,9 +25,9 @@ import { Skeleton } from "@/shared/ui/skeleton";
|
||||
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { AxiosError } from "axios";
|
||||
import axios, { AxiosError } from "axios";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import z from "zod";
|
||||
@@ -35,9 +36,13 @@ import { columnsDistrict } from "../lib/column";
|
||||
import { DataTableDistruct } from "../lib/data-table";
|
||||
import { districtForm } from "../lib/form";
|
||||
|
||||
export default function District() {
|
||||
const queryClinent = useQueryClient();
|
||||
interface NominatimResult {
|
||||
place_id: number;
|
||||
display_name: string;
|
||||
}
|
||||
|
||||
export default function District() {
|
||||
const queryClient = useQueryClient();
|
||||
const form = useForm<z.infer<typeof districtForm>>({
|
||||
resolver: zodResolver(districtForm),
|
||||
defaultValues: { name: "" },
|
||||
@@ -49,62 +54,126 @@ export default function District() {
|
||||
const [selectedDistrict, setSelectedDistrict] =
|
||||
useState<MyDiscrictData | null>(null);
|
||||
|
||||
const handleEdit = (district: MyDiscrictData) => {
|
||||
form.reset({ name: district.name });
|
||||
setIsDialogOpen(true);
|
||||
setEditingDistrict(district.id);
|
||||
const [searchResults, setSearchResults] = useState<NominatimResult[]>([]);
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
|
||||
// Debounced query using react-hook-form's value
|
||||
const debouncedQuery = useDebounce(form.watch("name"), 500);
|
||||
|
||||
/** 🔍 Nominatim API fetch */
|
||||
useEffect(() => {
|
||||
if (!debouncedQuery || debouncedQuery.length < 2) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
|
||||
const fetchDistricts = async () => {
|
||||
setIsSearching(true);
|
||||
try {
|
||||
const res = await axios.get(
|
||||
`https://nominatim.openstreetmap.org/search`,
|
||||
{
|
||||
params: {
|
||||
q: debouncedQuery,
|
||||
format: "json",
|
||||
polygon_geojson: 1,
|
||||
countrycodes: "uz",
|
||||
limit: 20,
|
||||
addressdetails: 1,
|
||||
},
|
||||
headers: {
|
||||
"User-Agent": "DistrictAppUZ/1.0 (your.real.email@domain.uz)",
|
||||
Referer: window.location.origin || "https://your-app.uz",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (!active) return;
|
||||
|
||||
// Filter ni yumshatdik: ko'proq natija chiqishi uchun
|
||||
const filtered = res.data.filter(
|
||||
(item: { class: string; type: string; display_name: string }) =>
|
||||
item.class === "place" ||
|
||||
item.class === "boundary" ||
|
||||
item.type === "administrative" ||
|
||||
item.type === "district" ||
|
||||
item.type === "county" ||
|
||||
item.display_name.toLowerCase().includes("tumani") ||
|
||||
item.display_name.toLowerCase().includes("tuman") ||
|
||||
item.display_name.toLowerCase().includes("district"),
|
||||
);
|
||||
|
||||
setSearchResults(filtered);
|
||||
} catch (err) {
|
||||
console.error("Nominatim xatosi:", err);
|
||||
toast.error("Joylashuvni qidirishda xato");
|
||||
} finally {
|
||||
if (active) setIsSearching(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchDistricts();
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [debouncedQuery]);
|
||||
|
||||
/** 🔹 Select suggestion */
|
||||
const handleSelect = (item: NominatimResult) => {
|
||||
const nameToSave = item.display_name
|
||||
.split(",")
|
||||
.slice(0, 2)
|
||||
.join(",")
|
||||
.trim();
|
||||
form.setValue("name", nameToSave);
|
||||
setSearchResults([]);
|
||||
};
|
||||
|
||||
/** 🔹 Edit */
|
||||
const handleEdit = (district: MyDiscrictData) => {
|
||||
form.reset({ name: district.name });
|
||||
setEditingDistrict(district.id);
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
/** 🔹 Delete */
|
||||
const handleDelete = () => {
|
||||
if (!selectedDistrict) return;
|
||||
deleteDis(selectedDistrict.id);
|
||||
};
|
||||
|
||||
/** 🔹 Columns for DataTable */
|
||||
const columns = columnsDistrict({
|
||||
handleEdit,
|
||||
onDeleteClick: (MyDiscrictData) => {
|
||||
setSelectedDistrict(MyDiscrictData);
|
||||
onDeleteClick: (d) => {
|
||||
setSelectedDistrict(d);
|
||||
setDeleteDialog(true);
|
||||
},
|
||||
});
|
||||
|
||||
const { data, isError, isLoading } = useQuery({
|
||||
/** 🔹 Queries */
|
||||
const { data, isLoading, isError } = useQuery({
|
||||
queryKey: ["my_disctrict"],
|
||||
queryFn: () => district_api.getDiscrict(),
|
||||
});
|
||||
|
||||
/** 🔹 Mutations */
|
||||
const { mutate: added, isPending: addedPending } = useMutation({
|
||||
mutationFn: (body: { name: string }) => district_api.added(body),
|
||||
onSuccess: () => {
|
||||
toast.success("Yangi tuman qo'shildi");
|
||||
queryClinent.refetchQueries({ queryKey: ["my_disctrict"] });
|
||||
queryClient.refetchQueries({ queryKey: ["my_disctrict"] });
|
||||
setIsDialogOpen(false);
|
||||
form.reset({ name: "" });
|
||||
},
|
||||
onError: (error: AxiosError) => {
|
||||
const data = error.response?.data as { message?: string };
|
||||
const errorData = error.response?.data as {
|
||||
messages?: {
|
||||
token_class: string;
|
||||
token_type: string;
|
||||
message: string;
|
||||
}[];
|
||||
};
|
||||
const errorName = error.response?.data as {
|
||||
data?: {
|
||||
name: string[];
|
||||
};
|
||||
};
|
||||
|
||||
const message =
|
||||
Array.isArray(errorName.data?.name) && errorName.data.name.length
|
||||
? errorName.data.name[0]
|
||||
: data?.message ||
|
||||
(Array.isArray(errorData?.messages) && errorData.messages.length
|
||||
? errorData.messages[0].message
|
||||
: undefined) ||
|
||||
"Xatolik yuz berdi";
|
||||
|
||||
toast.error(message);
|
||||
toast.error(
|
||||
(error.response?.data as { message: string })?.message ||
|
||||
"Xatolik yuz berdi",
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -113,35 +182,16 @@ export default function District() {
|
||||
district_api.edit({ body, id }),
|
||||
onSuccess: () => {
|
||||
toast.success("Tuman yangilandi");
|
||||
queryClinent.refetchQueries({ queryKey: ["my_disctrict"] });
|
||||
queryClient.refetchQueries({ queryKey: ["my_disctrict"] });
|
||||
setIsDialogOpen(false);
|
||||
setEditingDistrict(null);
|
||||
form.reset({ name: "" });
|
||||
},
|
||||
onError: (error: AxiosError) => {
|
||||
const data = error.response?.data as { message?: string };
|
||||
const errorData = error.response?.data as {
|
||||
messages?: {
|
||||
token_class: string;
|
||||
token_type: string;
|
||||
message: string;
|
||||
}[];
|
||||
};
|
||||
const errorName = error.response?.data as {
|
||||
data?: {
|
||||
name: string[];
|
||||
};
|
||||
};
|
||||
|
||||
const message =
|
||||
Array.isArray(errorName.data?.name) && errorName.data.name.length
|
||||
? errorName.data.name[0]
|
||||
: data?.message ||
|
||||
(Array.isArray(errorData?.messages) && errorData.messages.length
|
||||
? errorData.messages[0].message
|
||||
: undefined) ||
|
||||
"Xatolik yuz berdi";
|
||||
|
||||
toast.error(message);
|
||||
toast.error(
|
||||
(error.response?.data as { message: string })?.message ||
|
||||
"Xatolik yuz berdi",
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -149,49 +199,31 @@ export default function District() {
|
||||
mutationFn: (id: number) => district_api.deleteDistrict(id),
|
||||
onSuccess: () => {
|
||||
toast.success("Tuman o'chirildi");
|
||||
queryClinent.refetchQueries({ queryKey: ["my_disctrict"] });
|
||||
queryClient.refetchQueries({ queryKey: ["my_disctrict"] });
|
||||
setDeleteDialog(false);
|
||||
setSelectedDistrict(null);
|
||||
},
|
||||
onError: (error: AxiosError) => {
|
||||
const data = error.response?.data as { message?: string };
|
||||
const errorData = error.response?.data as {
|
||||
messages?: {
|
||||
token_class: string;
|
||||
token_type: string;
|
||||
message: string;
|
||||
}[];
|
||||
};
|
||||
const errorName = error.response?.data as {
|
||||
data?: {
|
||||
name: string[];
|
||||
};
|
||||
};
|
||||
|
||||
const message =
|
||||
Array.isArray(errorName.data?.name) && errorName.data.name.length
|
||||
? errorName.data.name[0]
|
||||
: data?.message ||
|
||||
(Array.isArray(errorData?.messages) && errorData.messages.length
|
||||
? errorData.messages[0].message
|
||||
: undefined) ||
|
||||
"Xatolik yuz berdi";
|
||||
|
||||
toast.error(message);
|
||||
toast.error(
|
||||
(error.response?.data as { message: string })?.message ||
|
||||
"Xatolik yuz berdi",
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(data: z.infer<typeof districtForm>) {
|
||||
/** 🔹 Submit */
|
||||
const onSubmit = (values: z.infer<typeof districtForm>) => {
|
||||
if (editingDistrict) {
|
||||
edit({ body: { name: data.name }, id: editingDistrict });
|
||||
edit({ id: editingDistrict, body: { name: values.name } });
|
||||
} else {
|
||||
added({ name: data.name });
|
||||
}
|
||||
added({ name: values.name });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardLayout link="/">
|
||||
<>
|
||||
{/* ADD/EDIT DIALOG */}
|
||||
<div className="flex items-center justify-between">
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
@@ -214,20 +246,52 @@ export default function District() {
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormItem className="relative">
|
||||
<Label>Tuman nomi</Label>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Sarlavha"
|
||||
placeholder="Tuman nomini kiriting (masalan: Uchtepa, Chilonzor)"
|
||||
className="focus-visible:ring-0 h-12"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
{/* SEARCH RESULTS */}
|
||||
{searchResults.length > 0 && (
|
||||
<ul className="absolute z-10 w-full mt-1 bg-white border rounded-md shadow-lg max-h-60 top-17 overflow-auto">
|
||||
{isSearching ? (
|
||||
<li className="p-3 text-center text-gray-500">
|
||||
Qidirilmoqda...
|
||||
</li>
|
||||
) : (
|
||||
searchResults.map((item) => (
|
||||
<li
|
||||
key={item.place_id}
|
||||
className="p-3 hover:bg-gray-100 cursor-pointer"
|
||||
onClick={() => handleSelect(item)}
|
||||
>
|
||||
{item.display_name}
|
||||
</li>
|
||||
))
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{!isSearching &&
|
||||
searchResults.length === 0 &&
|
||||
debouncedQuery.length >= 2 && (
|
||||
<p className="text-sm text-amber-600 mt-1">
|
||||
Hech narsa topilmadi. Boshqa nom sinab ko‘ring
|
||||
(masalan: Chilonzor tumani)
|
||||
</p>
|
||||
)}
|
||||
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-col w-full gap-2">
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
@@ -256,10 +320,9 @@ export default function District() {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* DISTRICT LIST */}
|
||||
<div className="space-y-6 mt-6">
|
||||
<h1 className="text-3xl font-bold">Tumanlar ro‘yxati</h1>
|
||||
|
||||
{/* Loading state */}
|
||||
{isLoading ? (
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3].map((i) => (
|
||||
@@ -270,7 +333,7 @@ export default function District() {
|
||||
<p className="text-red-500">
|
||||
Tumanlar yuklanmadi. Qayta urinib ko‘ring.
|
||||
</p>
|
||||
) : data ? (
|
||||
) : data && data.data.data.length > 0 ? (
|
||||
<div className="overflow-x-auto">
|
||||
<DataTableDistruct columns={columns} data={data.data.data} />
|
||||
</div>
|
||||
@@ -278,19 +341,22 @@ export default function District() {
|
||||
<p className="text-gray-500">Tumanlar mavjud emas</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
|
||||
{/* DELETE DIALOG */}
|
||||
<Dialog open={deleteDialog} onOpenChange={setDeleteDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-start">O‘chirish</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p>
|
||||
Siz haqiqatdan ham <strong>{selectedDistrict?.name}</strong> tumanni
|
||||
o‘chirmoqchimisiz?
|
||||
Siz haqiqatdan ham <strong>{selectedDistrict?.name}</strong>{" "}
|
||||
tumanni o‘chirmoqchimisiz?
|
||||
</p>
|
||||
<DialogFooter className="flex flex-row justify-end">
|
||||
<Button variant="secondary" onClick={() => setDeleteDialog(false)}>
|
||||
<DialogFooter className="flex flex-row justify-end gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => setDeleteDialog(false)}
|
||||
>
|
||||
Bekor qilish
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={handleDelete}>
|
||||
@@ -299,6 +365,7 @@ export default function District() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
</DashboardLayout>
|
||||
);
|
||||
}
|
||||
|
||||
19
src/shared/hooks/useDebounce.ts
Normal file
19
src/shared/hooks/useDebounce.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
// hooks/useDebounce.ts
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export function useDebounce<T>(value: T, delay: number = 500): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(value);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = setTimeout(() => {
|
||||
setDebouncedValue(value);
|
||||
}, delay);
|
||||
|
||||
// har yangi value kelganda oldingi timeoutni tozalaymiz
|
||||
return () => {
|
||||
clearTimeout(handler);
|
||||
};
|
||||
}, [value, delay]); // value yoki delay o'zgarsa → qayta ishlaydi
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export default defineConfig({
|
||||
port: 5174,
|
||||
host: true, // barcha hostlarga ruxsat
|
||||
allowedHosts: [
|
||||
"spin-ronald-officers-reasonably.trycloudflare.com", // ngrok host qo'shildi
|
||||
"removed-treasure-discovery-loads.trycloudflare.com", // ngrok host qo'shildi
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user