This commit is contained in:
Samandar Turgunboyev
2025-11-27 15:57:26 +05:00
parent 980fb1dd13
commit 969e32be09
177 changed files with 17023 additions and 995 deletions

2
.env
View File

@@ -1 +1 @@
VITE_API_URL=https://jsonplaceholder.typicode.com VITE_API_URL=https://api.meridynpharma.com

View File

@@ -9,5 +9,9 @@
<body> <body>
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
<script
src="https://telegram.org/js/telegram-web-app.js?59"
strategy="afterInteractive"
></script>
</body> </body>
</html> </html>

6758
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -29,7 +29,46 @@
"react-i18next": "^15.7.3", "react-i18next": "^15.7.3",
"react-router-dom": "^7.9.6", "react-router-dom": "^7.9.6",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1",
"tailwindcss": "^4.1.13" "tailwindcss": "^4.1.13",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^5.2.2",
"@pbe/react-yandex-maps": "^1.2.5",
"@radix-ui/react-accordion": "^1.2.8",
"@radix-ui/react-avatar": "^1.1.7",
"@radix-ui/react-checkbox": "^1.2.3",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-navigation-menu": "^1.2.10",
"@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-scroll-area": "^1.2.10",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.4",
"@radix-ui/react-tabs": "^1.1.9",
"@radix-ui/react-toggle": "^1.1.6",
"@radix-ui/react-toggle-group": "^1.1.7",
"@radix-ui/react-tooltip": "^1.2.4",
"@tabler/icons-react": "^3.31.0",
"@tanstack/react-table": "^8.21.3",
"date-fns": "^4.1.0",
"framer-motion": "^12.23.24",
"js-cookie": "^3.0.5",
"leaflet": "^1.9.4",
"leaflet-geosearch": "^4.2.2",
"leaflet-routing-machine": "^3.2.12",
"next": "^15.5.4",
"next-intl": "^4.3.9",
"next-themes": "^0.4.6",
"react-day-picker": "^9.11.1",
"react-hook-form": "^7.66.0",
"react-yandex-maps": "^4.6.0",
"recharts": "^2.15.3",
"sonner": "^2.0.7",
"vaul": "^1.1.2",
"zod": "^4.1.12",
"zustand": "^5.0.8"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.25.0", "@eslint/js": "^9.25.0",
@@ -48,7 +87,16 @@
"typescript": "~5.9.2", "typescript": "~5.9.2",
"typescript-eslint": "^8.44.1", "typescript-eslint": "^8.44.1",
"vite": "^7.1.7", "vite": "^7.1.7",
"vite-tsconfig-paths": "^5.1.4" "vite-tsconfig-paths": "^5.1.4",
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/js-cookie": "^3.0.6",
"@types/leaflet": "^1.9.21",
"@types/leaflet-routing-machine": "^3.2.9",
"eslint-config-next": "15.3.1",
"eslint-config-prettier": "^10.1.2",
"eslint-plugin-prettier": "^5.2.6",
"tailwindcss": "^4"
}, },
"lint-staged": { "lint-staged": {
"*.{js,ts,jsx,tsx}": [ "*.{js,ts,jsx,tsx}": [
@@ -56,4 +104,4 @@
"eslint src --fix" "eslint src --fix"
] ]
} }
} }

View File

@@ -1,11 +1,12 @@
import MainProvider from "@/providers/main"; import MainProvider from "@/providers/main";
import AppRouter from "@/providers/routing/AppRoutes"; import AppRouter from "@/providers/routing/AppRoutes";
import "@/shared/config/i18n"; import { Toaster } from "sonner";
const App = () => { const App = () => {
return ( return (
<MainProvider> <MainProvider>
<AppRouter /> <AppRouter />
<Toaster richColors={true} position="top-center" />
</MainProvider> </MainProvider>
); );
}; };

BIN
src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

View File

@@ -0,0 +1,32 @@
import type {
getRegionsResponse,
LoginRequest,
LoginResponse,
} from "@/features/auth/lib";
import httpClient from "@/shared/config/api/httpClient";
import { CREATE_USER, LOGIN_USER, REGIONS } from "@/shared/config/api/URLs";
import { removeToken } from "@/shared/lib/cookie";
import type { AxiosResponse } from "axios";
export const auth_api = {
//yangi qoshilmoqchi bolgan user uchun register
async create(body: LoginRequest) {
const res = await httpClient.post(CREATE_USER, body);
return res;
},
//userlarni login qilish
async login(body: {
telegram_id: string;
}): Promise<AxiosResponse<LoginResponse>> {
removeToken();
const res = await httpClient.post(LOGIN_USER, body);
return res;
},
//login qilishda tanlanadigan hududlar ro'yxati
async getRegions(): Promise<AxiosResponse<getRegionsResponse>> {
const res = await httpClient.get(REGIONS);
return res;
},
};

View File

@@ -0,0 +1,7 @@
import z from "zod";
export const loginform = z.object({
firstName: z.string().min(1, { message: "Majburiy maydon" }),
lastName: z.string().min(1, { message: "Majburiy maydon" }),
regions: z.string().min(1, { message: "Majburiy maydon" }),
});

View File

@@ -0,0 +1,33 @@
export interface LoginRequest {
first_name: string;
last_name: string;
telegram_id: string;
region: number;
}
export interface getRegionsResponse {
message: string;
status: string;
status_code: number;
data: getRegionsResponseData[];
}
export interface getRegionsResponseData {
created_at: string;
id: number;
name: string;
}
export interface LoginResponse {
message: string;
status: string;
status_code: number;
data: {
first_name: string;
id: number;
is_active: boolean;
last_name: string;
region: string;
token: null;
};
}

View File

@@ -0,0 +1 @@
// Ushbu fayl loyiha structurasi uchun qo'shilgan. O'chirib tashlasangiz bo'ladi

View File

@@ -0,0 +1 @@
// Ushbu fayl loyiha structurasi uchun qo'shilgan. O'chirib tashlasangiz bo'ladi

View File

@@ -0,0 +1,187 @@
"use client";
import LOGO from "@/assets/logo.png";
import type { LoginRequest } from "@/features/auth/lib";
import { userInfoStore } from "@/shared/hooks/user-info";
import { Button } from "@/shared/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/shared/ui/card";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/ui/select";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Loader2 } from "lucide-react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import z from "zod";
import { auth_api } from "../lib/api";
import { loginform } from "../lib/form";
export default function LoginForm() {
const { user, setLoginUser } = userInfoStore();
const form = useForm<z.infer<typeof loginform>>({
resolver: zodResolver(loginform),
defaultValues: {
firstName: "",
lastName: "",
regions: "",
},
});
const { data: regions } = useQuery({
queryKey: ["region"],
queryFn: () => auth_api.getRegions(),
select(data) {
return data.data.data;
},
});
const { mutate, isPending } = useMutation({
mutationFn: (body: LoginRequest) => auth_api.create(body),
onSuccess: () => {
toast.success("Siz ro'yxatdan o'tingiz");
setLoginUser({
active: false,
first_name: form.getValues("firstName"),
last_name: form.getValues("lastName"),
});
},
onError: (error: AxiosError) => {
const data = error.response?.data as { message?: string };
toast.error(data?.message || "Xatolik yuz berdi");
},
});
function handleSubmit(value: z.infer<typeof loginform>) {
mutate({
first_name: value.firstName,
last_name: value.lastName,
region: Number(value.regions),
telegram_id: user.user_id,
});
}
return (
<div className="w-full max-w-md h-screen flex items-center justify-center mx-auto">
<Card className="border-0 w-full shadow-none">
<CardHeader className="text-center">
<CardTitle className="text-2xl w-full flex justify-center items-center">
<img
src={LOGO}
width={300}
height={300}
alt="logo"
className="w-52 h-16"
/>
</CardTitle>
<CardDescription className="text-slate-600 mt-2 text-lg dark:text-slate-400">
Tizimga xush kelibsiz
</CardDescription>
</CardHeader>
<CardContent>
<Form {...form}>
<form
onSubmit={form.handleSubmit(handleSubmit)}
className="space-y-4"
>
<FormField
control={form.control}
name="firstName"
render={({ field }) => (
<FormItem>
<Label>Ism</Label>
<FormControl>
<Input
placeholder="Ismingizni kiriting"
className="h-12 rounded-lg border-slate-200 dark:border-slate-700 focus:ring-2 focus:ring-emerald-500"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lastName"
render={({ field }) => (
<FormItem>
<Label>Familiya</Label>
<FormControl>
<Input
placeholder="Familiyangizni kiriting"
className="h-12 rounded-lg border-slate-200 dark:border-slate-700 focus:ring-2 focus:ring-emerald-500"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="regions"
render={({ field }) => (
<FormItem>
<Label>Hudud</Label>
<FormControl>
<Select
onValueChange={field.onChange}
value={field.value}
>
<SelectTrigger className="!h-12 w-full rounded-lg border-slate-200 dark:border-slate-700 focus:ring-2 focus:ring-emerald-500">
<SelectValue placeholder="Hududingizni tanlang" />
</SelectTrigger>
<SelectContent>
{regions &&
regions.map((region) => (
<SelectItem
key={region.id}
value={String(region.id)}
>
{region.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button
type="submit"
disabled={isPending}
className="w-full h-12 text-lg bg-emerald-600 hover:bg-emerald-700 dark:bg-emerald-500 dark:hover:bg-emerald-600 text-white font-medium rounded-lg transition-colors"
>
{isPending ? <Loader2 className="animate-spin" /> : "Kirish"}
</Button>
</form>
</Form>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,26 @@
import type { MyDiscrict } from "@/features/district/lib/data";
import httpClient from "@/shared/config/api/httpClient";
import { DISCTRICT } from "@/shared/config/api/URLs";
import type { AxiosResponse } from "axios";
export const district_api = {
async added(body: { name: string }) {
const res = await httpClient.post(`${DISCTRICT}create/`, body);
return res;
},
async edit({ body, id }: { body: { name: string }; id: number }) {
const res = await httpClient.patch(`${DISCTRICT}${id}/`, body);
return res;
},
async getDiscrict(): Promise<AxiosResponse<MyDiscrict>> {
const res = await httpClient.get(`${DISCTRICT}list/`);
return res;
},
async deleteDistrict(id: number) {
const res = await httpClient.delete(`${DISCTRICT}${id}/`);
return res;
},
};

View File

@@ -0,0 +1,67 @@
import type { MyDiscrictData } from "@/features/district/lib/data";
import { Button } from "@/shared/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/shared/ui/dropdown-menu";
import type { ColumnDef } from "@tanstack/react-table";
import { Edit, EllipsisVertical, Trash } from "lucide-react";
interface ColumnProps {
handleEdit: (district: MyDiscrictData) => void;
onDeleteClick: (district: MyDiscrictData) => void;
}
export const columnsDistrict = ({
handleEdit,
onDeleteClick,
}: ColumnProps): ColumnDef<MyDiscrictData>[] => [
{
accessorKey: "id",
header: () => <div className="text-center"></div>,
cell: ({ row }) => (
<div className="text-center font-medium">{row.index + 1}</div>
),
},
{
accessorKey: "name",
header: () => <div className="text-center">Tuman nomi</div>,
cell: ({ row }) => (
<div className="text-center font-medium">{row.original.name}</div>
),
},
{
id: "actions",
header: () => <div className="text-center">Amallar</div>,
cell: ({ row }) => {
const district = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-full h-full hover:bg-gray-100">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="flex flex-col gap-1">
<Button
variant="ghost"
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-green-400 hover:text-white text-white bg-green-400"
onClick={() => handleEdit(district)}
>
<Edit size={16} /> Tahrirlash
</Button>
<Button
variant="ghost"
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-red-400 hover:text-white text-white bg-red-400"
onClick={() => onDeleteClick(district)} // faqat signal yuboradi
>
<Trash size={16} /> Ochirish
</Button>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];

View File

@@ -0,0 +1,80 @@
"use client";
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/shared/ui/table";
interface DataTableProps<MyDiscrictData, TValue> {
columns: ColumnDef<MyDiscrictData, TValue>[];
data: MyDiscrictData[];
}
export function DataTableDistruct<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="overflow-hidden rounded-md border">
<Table className="">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} className="border-r">
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="border-r">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -0,0 +1,12 @@
export interface MyDiscrict {
message: string;
status: string;
status_code: number;
data: MyDiscrictData[];
}
export interface MyDiscrictData {
created_at: string;
id: number;
name: string;
}

View File

@@ -0,0 +1,5 @@
import z from "zod";
export const districtForm = z.object({
name: z.string().min(1, { message: "Majburiy maydon" }),
});

View File

@@ -0,0 +1,296 @@
"use client";
import type { MyDiscrictData } from "@/features/district/lib/data";
import AddedButton from "@/shared/ui/added-button";
import { Button } from "@/shared/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/shared/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import { Label } from "@/shared/ui/label";
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 { Loader2 } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import z from "zod";
import { district_api } from "../lib/api";
import { columnsDistrict } from "../lib/column";
import { DataTableDistruct } from "../lib/data-table";
import { districtForm } from "../lib/form";
export default function District() {
const queryClinent = useQueryClient();
const form = useForm<z.infer<typeof districtForm>>({
resolver: zodResolver(districtForm),
defaultValues: { name: "" },
});
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [editingDistrict, setEditingDistrict] = useState<number | null>(null);
const [deleteDialog, setDeleteDialog] = useState(false);
const [selectedDistrict, setSelectedDistrict] =
useState<MyDiscrictData | null>(null);
const handleEdit = (district: MyDiscrictData) => {
form.reset({ name: district.name });
setIsDialogOpen(true);
setEditingDistrict(district.id);
};
const handleDelete = () => {
if (!selectedDistrict) return;
deleteDis(selectedDistrict.id);
};
const columns = columnsDistrict({
handleEdit,
onDeleteClick: (MyDiscrictData) => {
setSelectedDistrict(MyDiscrictData);
setDeleteDialog(true);
},
});
const { data, isError, isLoading } = useQuery({
queryKey: ["my_disctrict"],
queryFn: () => district_api.getDiscrict(),
});
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"] });
setIsDialogOpen(false);
},
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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const { mutate: edit, isPending: editPending } = useMutation({
mutationFn: ({ body, id }: { body: { name: string }; id: number }) =>
district_api.edit({ body, id }),
onSuccess: () => {
toast.success("Tuman yangilandi");
queryClinent.refetchQueries({ queryKey: ["my_disctrict"] });
setIsDialogOpen(false);
setEditingDistrict(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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const { mutate: deleteDis } = useMutation({
mutationFn: (id: number) => district_api.deleteDistrict(id),
onSuccess: () => {
toast.success("Tuman o'chirildi");
queryClinent.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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
async function onSubmit(data: z.infer<typeof districtForm>) {
if (editingDistrict) {
edit({ body: { name: data.name }, id: editingDistrict });
} else {
added({ name: data.name });
}
}
return (
<DashboardLayout>
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-foreground">Tumanlar</h1>
<p className="text-muted-foreground mt-1">Tumanlarni boshqarish</p>
</div>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<AddedButton onClick={() => form.reset({ name: "" })} />
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
{editingDistrict
? "Tumanni tahrirlash"
: "Yangi tuman qoshish"}
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<Label>Tuman nomi</Label>
<FormControl>
<Input
placeholder="Sarlavha"
className="focus-visible:ring-0 h-12"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex flex-col w-full gap-2">
<Button
type="button"
variant="outline"
className="h-10"
onClick={() => setIsDialogOpen(false)}
>
Bekor qilish
</Button>
<Button
type="submit"
className="h-10"
disabled={addedPending || editPending}
>
{addedPending || editPending ? (
<Loader2 className="animate-spin" />
) : editingDistrict ? (
"Saqlash"
) : (
"Qoshish"
)}
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
<div className="space-y-6 mt-5">
<h1 className="text-3xl font-bold">Tumanlar royxati</h1>
{/* Loading state */}
{isLoading ? (
<div className="space-y-3">
{[1, 2, 3].map((i) => (
<Skeleton key={i} className="h-12 w-full rounded-md" />
))}
</div>
) : isError ? (
<p className="text-red-500">
Tumanlar yuklanmadi. Qayta urinib koring.
</p>
) : data ? (
<div className="overflow-x-auto">
<DataTableDistruct columns={columns} data={data.data.data} />
</div>
) : (
<p className="text-gray-500">Tumanlar mavjud emas</p>
)}
</div>
</div>
<Dialog open={deleteDialog} onOpenChange={setDeleteDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-start">Ochirish</DialogTitle>
</DialogHeader>
<p>
Siz haqiqatdan ham <strong>{selectedDistrict?.name}</strong> tumanni
ochirmoqchimisiz?
</p>
<DialogFooter className="flex flex-row justify-end">
<Button variant="secondary" onClick={() => setDeleteDialog(false)}>
Bekor qilish
</Button>
<Button variant="destructive" onClick={handleDelete}>
Ochirish
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DashboardLayout>
);
}

View File

@@ -0,0 +1,29 @@
import type {
CreateDoctorReq,
DoctorListRes,
} from "@/features/doctor/lib/data";
import httpClient from "@/shared/config/api/httpClient";
import { DOCTOR } from "@/shared/config/api/URLs";
import type { AxiosResponse } from "axios";
export const doctor_api = {
async create(body: CreateDoctorReq) {
const res = await httpClient.post(`${DOCTOR}create/`, body);
return res;
},
async edit({ body, id }: { id: number; body: CreateDoctorReq }) {
const res = await httpClient.patch(`${DOCTOR}${id}/`, body);
return res;
},
async delete({ id }: { id: number }) {
const res = await httpClient.delete(`${DOCTOR}${id}/`);
return res;
},
async list(): Promise<AxiosResponse<DoctorListRes>> {
const res = await httpClient.get(`${DOCTOR}list/`);
return res;
},
};

View File

@@ -0,0 +1,111 @@
import type { DoctorListData } from "@/features/doctor/lib/data";
import formatPhone from "@/shared/lib/formatPhone";
import { Button } from "@/shared/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/shared/ui/dropdown-menu";
import type { ColumnDef } from "@tanstack/react-table";
import { Edit, EllipsisVertical, Eye, Trash } from "lucide-react";
import type { NavigateFunction } from "react-router-dom";
interface Props {
router: NavigateFunction;
onDeleteClick: (district: DoctorListData) => void;
}
export const columns = ({
router,
onDeleteClick,
}: Props): ColumnDef<DoctorListData>[] => [
{
accessorKey: "id",
header: () => <div className="text-center"></div>,
cell: ({ row }) => {
return <div className="text-center font-medium">{row.index + 1}</div>;
},
},
{
accessorKey: "name",
header: () => <div className="text-center">Ismi</div>,
cell: ({ row }) => {
return (
<div className="text-center font-medium">
{row.original.first_name} {row.original.last_name}
</div>
);
},
},
{
accessorKey: "districtName",
header: () => <div className="text-center">Ish joyi</div>,
cell: ({ row }) => {
return (
<div className="text-center font-medium">{row.original.work_place}</div>
);
},
},
{
accessorKey: "phone",
header: () => <div className="text-center">Telefon raqami</div>,
cell: ({ row }) => {
return (
<div className="text-center font-medium">
{formatPhone(row.original.phone_number)}
</div>
);
},
},
{
id: "actions",
header: () => <div className="text-center">Amallar</div>,
cell: ({ row }) => {
const obj = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-full h-full hover:bg-gray-100">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="flex flex-col gap-1">
<Button
variant={"ghost"}
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-blue-400 hover:text-white text-white bg-blue-400"
onClick={() => router(`/physician/detail/${row.original.id}`)}
>
<Eye size={16} /> Batafsil
</Button>
<Button
variant={"ghost"}
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-blue-400 hover:text-white text-white bg-blue-400"
onClick={() =>
router(
`/object/location?id=${obj.id}&lat=${obj.latitude}&lon=${obj.longitude}}`,
)
}
>
<Eye size={16} /> {"Lokatsiyani ko'rish"}
</Button>
<Button
variant="ghost"
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-green-400 hover:text-white text-white bg-green-400"
onClick={() => router(`/physician/edit/${obj.id}`)}
>
<Edit size={16} /> Tahrirlash
</Button>
<Button
variant={"destructive"}
size={"lg"}
className="cursor-pointer"
onClick={() => onDeleteClick(obj)}
>
<Trash size={16} /> {"O'chirish"}
</Button>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];

View File

@@ -0,0 +1,80 @@
"use client";
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/shared/ui/table";
interface DataTableProps<DoctorListData, TValue> {
columns: ColumnDef<DoctorListData, TValue>[];
data: DoctorListData[];
}
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="overflow-hidden rounded-md border">
<Table className="">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} className="border-r">
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="border-r">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -0,0 +1,39 @@
export interface CreateDoctorReq {
first_name: string;
last_name: string;
phone_number: string;
work_place: string;
description: string;
district: number;
place: number;
longitude: number;
sphere: string;
latitude: number;
extra_location: { longitude: number; latitude: number };
}
export interface DoctorListRes {
status_code: number;
status: string;
message: string;
data: DoctorListData[];
}
export interface DoctorListData {
id: number;
first_name: string;
last_name: string;
phone_number: string;
sphere: string;
work_place: string;
description: string;
district: number;
place: number;
longitude: number;
latitude: number;
extra_location: {
latitude: number;
longitude: number;
};
created_at: string;
}

View File

@@ -0,0 +1,30 @@
import { z } from "zod";
export const doctorForm = z.object({
first_name: z.string().min(2, {
error: "Eng kamida 2ta belgi bo'lishi kerak",
}),
last_name: z.string().min(2, {
error: "Eng kamida 2ta belgi bo'lishi kerak",
}),
districts: z.string().min(1, {
error: "Majburiy maydon",
}),
streets: z.string().min(1, {
error: "Majburiy maydon",
}),
latitude: z.number({ error: "Majburiy maydon" }),
longitude: z.number({ error: "Majburiy maydon" }),
nearbyCoords: z
.array(
z.object({
lat: z.number(),
lon: z.number(),
}),
)
.optional(),
objectName: z.string().min(2, "Poliklinika/Farmasi nomi kiritilishi shart"),
phone: z.string().min(9, "Telefon raqam kiritilishi shart"),
description: z.string().min(5, "Tavsif kamida 5ta belgi bolishi kerak"),
specialty: z.string().min(2, "Soha kiritilishi shart"),
});

View File

@@ -0,0 +1,627 @@
"use client";
import { district_api } from "@/features/district/lib/api";
import type { CreateDoctorReq } from "@/features/doctor/lib/data";
import { object_api } from "@/features/object/lib/api";
import formatPhone from "@/shared/lib/formatPhone";
import onlyNumber from "@/shared/lib/onlyNumber";
import { Button } from "@/shared/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/ui/select";
import { Textarea } from "@/shared/ui/textarea";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Circle,
Map,
Placemark,
Polygon,
YMaps,
ZoomControl,
} from "@pbe/react-yandex-maps";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Loader2, LocateFixed } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import z from "zod";
import { doctor_api } from "../lib/api";
import { doctorForm } from "../lib/form";
interface CoordsData {
lat: number;
lon: number;
polygon: [number, number][][];
}
const CreateDoctor = () => {
const router = useNavigate();
const queryClinent = useQueryClient();
const mapRef = useRef<ymaps.Map | null>(null);
const { id } = useParams();
const { data } = useQuery({
queryKey: ["doctor_list"],
queryFn: () => doctor_api.list(),
select(data) {
return data.data.data;
},
});
const doctor = data ? data.find((d) => d.id === Number(id)) : null;
const form = useForm<z.infer<typeof doctorForm>>({
resolver: zodResolver(doctorForm),
defaultValues: {
districts: "",
streets: "",
description: "",
objectName: "",
phone: "+998",
specialty: "",
first_name: "",
last_name: "",
},
});
useEffect(() => {
if (doctor) {
form.reset({
description: doctor.description,
districts: String(doctor.district),
first_name: doctor.first_name,
last_name: doctor.last_name,
latitude: doctor.latitude,
longitude: doctor.longitude,
objectName: doctor.work_place,
phone: doctor.phone_number,
specialty: doctor.sphere,
streets: String(doctor.place),
});
}
}, [doctor]);
const { mutate, isPending } = useMutation({
mutationFn: (body: CreateDoctorReq) => doctor_api.create(body),
onSuccess: () => {
router("/physician");
queryClinent.refetchQueries({ queryKey: ["doctor_list"] });
},
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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const { mutate: edit, isPending: editPending } = useMutation({
mutationFn: ({ body, id }: { id: number; body: CreateDoctorReq }) =>
doctor_api.edit({ body, id }),
onSuccess: () => {
router("/physician");
queryClinent.refetchQueries({ queryKey: ["doctor_list"] });
},
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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const { data: districts } = useQuery({
queryKey: ["my_disctrict"],
queryFn: () => district_api.getDiscrict(),
select(data) {
return data.data.data;
},
});
const district_id = form.watch("districts");
const { data: streets } = useQuery({
queryKey: ["object_list", district_id],
queryFn: () => object_api.getAll({ district_id: Number(district_id) }),
select(data) {
return data.data.data;
},
});
const [coords, setCoords] = useState({
latitude: 41.311081,
longitude: 69.240562,
});
const [polygonCoords, setPolygonCoords] = useState<
[number, number][][] | null
>(null);
const getCoords = async (name: string): Promise<CoordsData | null> => {
const res = await fetch(
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(name)}&format=json&polygon_geojson=1&limit=1`,
);
const data = await res.json();
if (data.length > 0 && data[0].geojson) {
const lat = parseFloat(data[0].lat);
const lon = parseFloat(data[0].lon);
let polygon: [number, number][][] = [];
if (data[0].geojson.type === "Polygon") {
polygon = data[0].geojson.coordinates.map((ring: [number, number][]) =>
ring.map((coord: [number, number]) => [coord[1], coord[0]]),
);
} else if (data[0].geojson.type === "MultiPolygon") {
polygon = data[0].geojson.coordinates.map(
(poly: [number, number][][]) =>
poly[0].map((coord: [number, number]) => [coord[1], coord[0]]),
);
}
return { lat, lon, polygon };
}
return null;
};
const handleMapClick = (
e: ymaps.IEvent<MouseEvent, { coords: [number, number] }>,
) => {
const [lat, lon] = e.get("coords");
setCoords({ latitude: lat, longitude: lon });
form.setValue("latitude", lat);
form.setValue("longitude", lon);
};
const [circleCoords, setCircleCoords] = useState<[number, number] | null>(
null,
);
const handleStreetChange = (streetId: string) => {
form.setValue("streets", streetId);
const selectedStreet = streets?.find((s) => s.id === Number(streetId));
if (!selectedStreet) return;
setCoords({
latitude: selectedStreet.latitude,
longitude: selectedStreet.longitude,
});
form.setValue("latitude", selectedStreet.latitude);
form.setValue("longitude", selectedStreet.longitude);
setCircleCoords([selectedStreet.latitude, selectedStreet.longitude]);
if (mapRef.current) {
mapRef.current.setCenter(
[selectedStreet.latitude, selectedStreet.longitude],
16,
);
}
};
const handleShowMyLocation = () => {
if (!navigator.geolocation) {
alert("Sizning brauzeringiz geolokatsiyani qollab-quvvatlamaydi");
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
setCoords({ latitude: lat, longitude: lon });
form.setValue("latitude", lat);
form.setValue("longitude", lon);
if (mapRef.current) {
mapRef.current.setCenter([lat, lon], 20);
}
},
(error) => {
alert("Joylashuv aniqlanmadi: " + error.message);
},
);
};
useEffect(() => {
if (!district_id || !districts || !doctor) return;
const selectedDistrict = districts.find(
(d) => d.id === Number(district_id),
);
if (!selectedDistrict) return;
getCoords(selectedDistrict.name).then((coordsData) => {
if (!coordsData) return;
setCoords({ latitude: doctor.latitude, longitude: doctor.longitude });
setPolygonCoords(coordsData.polygon);
});
}, [district_id, districts]);
useEffect(() => {
if (!streets || !form.getValues("streets")) return;
const streetId = form.getValues("streets");
handleStreetChange(streetId);
}, [streets, doctor]);
const onSubmit = (values: z.infer<typeof doctorForm>) => {
if (id) {
edit({
body: {
first_name: values.first_name,
last_name: values.last_name,
phone_number: onlyNumber(values.phone),
description: values.description,
work_place: values.objectName,
sphere: values.specialty,
district: Number(values.districts),
extra_location: {
latitude: values.latitude,
longitude: values.longitude,
},
latitude: values.latitude,
longitude: values.longitude,
place: Number(values.streets),
},
id: Number(id),
});
} else {
mutate({
first_name: values.first_name,
last_name: values.last_name,
phone_number: onlyNumber(values.phone),
description: values.description,
work_place: values.objectName,
sphere: values.specialty,
district: Number(values.districts),
extra_location: {
latitude: values.latitude,
longitude: values.longitude,
},
latitude: values.latitude,
longitude: values.longitude,
place: Number(values.streets),
});
}
};
return (
<DashboardLayout>
<div className="max-w-3xl mx-auto space-y-6">
<h1 className="text-3xl font-bold">{"Qo'shish"}</h1>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
{/* Nomi */}
<FormField
control={form.control}
name="first_name"
render={({ field }) => (
<FormItem>
<FormLabel>Ism</FormLabel>
<FormControl>
<Input {...field} placeholder="Ismi" className="h-12" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="last_name"
render={({ field }) => (
<FormItem>
<FormLabel>Familiya</FormLabel>
<FormControl>
<Input
{...field}
placeholder="Familiyasi"
className="h-12"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Telefon raqami</FormLabel>
<FormControl>
<Input
{...field}
placeholder="+998 90 123-45-67"
className="h-12"
onChange={(e) => {
const formatted = formatPhone(e.target.value);
field.onChange(formatted);
}}
value={formatPhone(field.value)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="objectName"
render={({ field }) => (
<FormItem>
<FormLabel>Qayerda ishlashi</FormLabel>
<FormControl>
<Input
{...field}
placeholder="114-poliklinika"
className="h-12"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="specialty"
render={({ field }) => (
<FormItem>
<FormLabel>Soha</FormLabel>
<FormControl>
<Input
{...field}
placeholder="Kardiolog"
className="h-12"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Tavsif</FormLabel>
<FormControl>
<Textarea
{...field}
placeholder="Kardiologiya boyicha..."
className="min-h-24 max-h-56"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="districts"
render={({ field }) => (
<FormItem>
<FormLabel>Tuman</FormLabel>
<FormControl>
<Select
key={field.value}
onValueChange={async (id) => {
field.onChange(id);
const selectedDistrict = districts?.find(
(d) => d.id === Number(id),
);
if (!selectedDistrict) return;
const coordsData = await getCoords(
selectedDistrict.name,
);
if (!coordsData) return;
setCoords({
latitude: coordsData.lat,
longitude: coordsData.lon,
});
setPolygonCoords(coordsData.polygon);
}}
value={field.value}
>
<SelectTrigger className="w-full h-12">
<SelectValue placeholder="Tumanlar" />
</SelectTrigger>
<SelectContent>
{districts?.map((d) => (
<SelectItem key={d.id} value={String(d.id)}>
{d.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="streets"
render={({ field }) => (
<FormItem>
<FormLabel>{"Ko'cha"}</FormLabel>
<FormControl>
<Select
key={field.value}
value={field.value}
onValueChange={(value) => {
field.onChange(value);
handleStreetChange(value);
}}
>
<SelectTrigger className="w-full h-12">
<SelectValue placeholder="Ko'chalar" />
</SelectTrigger>
<SelectContent>
{streets?.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>
{s.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="latitude"
render={() => (
<FormItem>
<FormLabel>Xarita</FormLabel>
<FormControl>
<div className="relative h-80 border rounded-lg overflow-hidden">
<YMaps query={{ lang: "en_RU" }}>
<Map
defaultState={{
center: [coords.latitude, coords.longitude],
zoom: 12,
}}
width="100%"
height="100%"
onClick={handleMapClick}
>
<ZoomControl
options={{
position: { right: "10px", bottom: "70px" },
}}
/>
<Placemark
geometry={[coords.latitude, coords.longitude]}
/>
{/* Polygon tuman uchun */}
{polygonCoords && (
<Polygon
geometry={polygonCoords}
options={{
fillColor: "rgba(0, 150, 255, 0.2)",
strokeColor: "rgba(0, 150, 255, 0.8)",
strokeWidth: 2,
interactivityModel: "default#transparent",
}}
/>
)}
{/* Circle street uchun */}
{circleCoords && (
<Circle
geometry={[circleCoords, 500]}
options={{
fillColor: "rgba(255, 100, 0, 0.3)",
strokeColor: "rgba(255, 100, 0, 0.8)",
strokeWidth: 2,
interactivityModel: "default#transparent",
}}
/>
)}
</Map>
</YMaps>
<Button
type="button"
size="sm"
onClick={handleShowMyLocation}
className="absolute bottom-3 right-2.5 shadow-md bg-white text-black hover:bg-gray-100"
>
<LocateFixed className="w-4 h-4 mr-1" />
</Button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
type="button"
className="h-12 p-3"
onClick={() => router("/physician")}
>
Bekor qilish
</Button>
<Button type="submit" className="h-12 p-5" disabled={isPending}>
{isPending || editPending ? (
<Loader2 className="animate-spin" />
) : id ? (
"Tahrirlash"
) : (
"Qo'shish"
)}
</Button>
</div>
</form>
</Form>
</div>
</DashboardLayout>
);
};
export default CreateDoctor;

View File

@@ -0,0 +1,100 @@
"use client";
import formatPhone from "@/shared/lib/formatPhone";
import { Button } from "@/shared/ui/button";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams } from "react-router-dom";
import { doctor_api } from "../lib/api";
const DoctorDetail = () => {
const router = useNavigate();
const { id } = useParams();
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ["doctor_list"],
queryFn: () => doctor_api.list(),
select(data) {
return data.data.data;
},
});
const doctor = data ? data.find((d) => d.id === Number(id)) : null;
if (isLoading) {
return (
<DashboardLayout>
<div className="flex justify-center py-20">
<div className="flex flex-col items-center gap-3">
<div className="h-10 w-10 rounded-full border-4 border-gray-300 border-t-primary animate-spin"></div>
<p className="text-gray-500">Yuklanmoqda...</p>
</div>
</div>
</DashboardLayout>
);
}
if (isError) {
return (
<DashboardLayout>
<div className="flex flex-col items-center py-20 gap-4">
<p className="text-red-500 font-medium">
Ma'lumot yuklashda xatolik yuz berdi.
</p>
<Button onClick={() => refetch()}>Qayta urinib korish</Button>
</div>
</DashboardLayout>
);
}
if (!doctor) {
return (
<DashboardLayout>
<div className="flex flex-col items-center py-20 gap-3 text-center">
<p className="text-gray-500 text-lg">Shifokor topilmadi.</p>
<Button onClick={() => router("/physician")}>
Royxatga qaytish
</Button>
</div>
</DashboardLayout>
);
}
return (
<DashboardLayout>
<div className="max-w-3xl mx-auto bg-white border rounded-xl shadow-sm p-6">
<h1 className="text-2xl font-bold mb-2">
{doctor.first_name} {doctor.last_name}
</h1>
<p className="text-sm text-gray-500 mb-2">
<strong>Telefon:</strong> {formatPhone(doctor.phone_number)}
</p>
<p className="text-sm text-gray-500 mb-2">
<strong>Qayerda ishlashi:</strong> {doctor.work_place}
</p>
<p className="text-sm text-gray-500 mb-2">
<strong>Soha:</strong> {doctor.sphere}
</p>
<p className="text-gray-700 mt-4">
<strong>Tavsif:</strong> {doctor.description}
</p>
<div className="flex gap-2 mt-6">
<Button
onClick={() => router(`/physician/edit/${doctor.id}`)}
variant="outline"
className="w-full"
>
Tahrirlash
</Button>
</div>
</div>
</DashboardLayout>
);
};
export default DoctorDetail;

View File

@@ -0,0 +1,143 @@
"use client";
import type { DoctorListData } from "@/features/doctor/lib/data";
import AddedButton from "@/shared/ui/added-button";
import { Button } from "@/shared/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/shared/ui/dialog";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Loader2 } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { doctor_api } from "../lib/api";
import { columns } from "../lib/column";
import { DataTable } from "../lib/data-table";
const Doctor = () => {
const router = useNavigate();
const queryClinent = useQueryClient();
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ["doctor_list"],
queryFn: () => doctor_api.list(),
select(data) {
return data.data.data;
},
});
const { mutate: deleted, isPending: deletedPending } = useMutation({
mutationFn: ({ id }: { id: number }) => doctor_api.delete({ id }),
onSuccess: () => {
router("/physician");
queryClinent.refetchQueries({ queryKey: ["doctor_list"] });
setSelectedDistrict(null);
setDeleteDialog(false);
},
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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const [deleteDialog, setDeleteDialog] = useState<boolean>(false);
const [selectedDistrict, setSelectedDistrict] =
useState<DoctorListData | null>(null);
const columnsProps = columns({
router: router,
onDeleteClick: (district) => {
setSelectedDistrict(district);
setDeleteDialog(true);
},
});
return (
<DashboardLayout>
<div className="flex justify-between items-center">
<AddedButton onClick={() => router("/physician/added")} />
</div>
<div className="space-y-6">
<h1 className="text-3xl font-bold">Shifokorlar royxati</h1>
{isLoading && (
<div className="w-full flex justify-center py-10">
<div className="flex flex-col items-center gap-2">
<div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-primary"></div>
<p className="text-muted-foreground">Yuklanmoqda...</p>
</div>
</div>
)}
{isError && (
<div className="w-full py-10 flex flex-col items-center gap-3">
<p className="text-red-500 font-medium">
Ma'lumot yuklashda xatolik yuz berdi.
</p>
<Button onClick={() => refetch()}>Qayta yuklash</Button>
</div>
)}
{!isLoading && !isError && (
<div className="overflow-x-auto">
{data && <DataTable columns={columnsProps} data={data} />}
</div>
)}
</div>
<Dialog open={deleteDialog} onOpenChange={setDeleteDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-start">Ochirish</DialogTitle>
</DialogHeader>
<p>
Siz haqiqatdan ham{" "}
<strong>
{selectedDistrict?.first_name} {selectedDistrict?.last_name}
</strong>{" "}
shifokorni ochirmoqchimisiz?
</p>
<DialogFooter className="flex flex-row justify-end">
<Button variant="secondary" onClick={() => setDeleteDialog(false)}>
Bekor qilish
</Button>
<Button
variant="destructive"
onClick={() =>
selectedDistrict && deleted({ id: selectedDistrict.id })
}
>
{deletedPending ? (
<Loader2 className="animate-spin" />
) : (
"O'chirish"
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DashboardLayout>
);
};
export default Doctor;

View File

@@ -0,0 +1,65 @@
import httpClient from "@/shared/config/api/httpClient";
import { LOCATION } from "@/shared/config/api/URLs";
import type { AxiosResponse } from "axios";
export interface SendLocation {
longitude: number;
latitude: number;
}
export interface CreateLocation {
district_id?: number;
place_id?: number;
doctor_id?: number;
pharmacy_id?: number;
longitude: number;
latitude: number;
}
export interface LocationList {
status_code: number;
status: string;
message: string;
data: LocationListData[];
}
export interface LocationListData {
id: number;
longitude: number;
latitude: number;
created_at: string;
district: {
id: number;
name: string;
} | null;
place: {
id: number;
name: string;
} | null;
doctor: {
id: number;
first_name: string;
last_name: string;
} | null;
pharmacy: {
id: number;
name: string;
} | null;
}
export const location_api = {
async send_loaction(body: SendLocation) {
const res = await httpClient.post(`${LOCATION}send/`, body);
return res;
},
async create_location(body: CreateLocation) {
const res = await httpClient.post(`${LOCATION}create/`, body);
return res;
},
async list_location(): Promise<AxiosResponse<LocationList>> {
const res = await httpClient.get(`${LOCATION}list/`);
return res;
},
};

View File

@@ -0,0 +1,86 @@
import {
Calendar,
FileText,
Home,
Layers,
List,
MapPin,
Syringe,
User,
} from "lucide-react";
interface UrlItems {
id: string;
title: string;
desc: string;
Icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
gradient: string;
link: string;
}
export const url_items: UrlItems[] = [
{
id: "reja",
title: "Reja",
desc: "O'z kunlik va haftalik rejalaringizni tuzib, faoliyatingizni samarali boshqaring.",
Icon: Calendar,
gradient: "from-blue-500 to-blue-700",
link: "/plan",
},
{
id: "tuman",
title: "Tuman",
desc: "Faoliyat yuritayotgan tuman va hududlar boyicha tezkor malumot oling.",
Icon: Layers,
gradient: "from-yellow-400 to-orange-600",
link: "/district",
},
{
id: "obyekt",
title: "Obyekt",
desc: "Har bir obyekt haqida toliq malumotni koring va ular ustida ishlang.",
Icon: Home,
gradient: "from-purple-500 to-purple-700",
link: "/object",
},
{
id: "tur-plan",
title: "Tur Plani",
desc: "Tur va plan turlarini boshqarish orqali ish jarayonini yanada qulay tashkil qiling.",
Icon: List,
gradient: "from-green-500 to-green-700",
link: "/plan-tour",
},
{
id: "lokatsiya",
title: "Lokatsiya",
desc: "Hudud va obyektlarning aniq joylashuvini kuzating va xaritadan toping.",
Icon: MapPin,
gradient: "from-pink-500 to-red-600",
link: "/location",
},
{
id: "shifokor",
title: "Shifokor",
desc: "Masul shifokorlarning malumotlari, tajribasi va kontaktlarini koring.",
Icon: User,
gradient: "from-teal-400 to-cyan-600",
link: "/medical-doctor",
},
{
id: "dorixona",
title: "Dorixona",
desc: "Dorixonalar royxati, mavjud dorilar va inventar holatini kuzating.",
Icon: Syringe,
gradient: "from-indigo-500 to-indigo-700",
link: "/pharmacy",
},
{
id: "spetsifikatsiya",
title: "Spetsifikatsiya",
desc: "Texnik yoki tibbiy spetsifikatsiyalarni tezkor korib chiqish imkoniyati.",
Icon: FileText,
gradient: "from-teal-500 to-teal-700",
link: "/specification",
},
];

View File

@@ -0,0 +1,268 @@
import LOGO from "@/assets/logo.png";
import { location_api, type SendLocation } from "@/features/home/lib/api";
import { useMutation } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import clsx from "clsx";
import {
Calendar,
Clipboard,
FileText,
HomeIcon,
Layers,
List,
MapPin,
Syringe,
User,
} from "lucide-react";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "sonner";
interface NavItem {
id: string;
title: string;
link: string;
icon: React.ReactNode;
description: string;
featured?: boolean;
}
const navItems: NavItem[] = [
{
id: "lokatsiya",
title: "Lokatsiya jo'natish",
link: "/location",
icon: <MapPin className="w-8 h-8" />,
description: "Manzilni jo'natish",
featured: true,
},
{
id: "spetsifikatsiya",
title: "Spetsifikatsiya",
link: "/specification",
icon: <FileText className="w-6 h-6" />,
description: "Hujjatlar",
featured: true,
},
{
id: "tour_plan",
title: "Tur plan",
link: "/tour-plan",
icon: <List className="w-6 h-6" />,
description: "Rejalar",
featured: true,
},
];
export default function Home() {
const featuredItems = navItems.filter((item) => item.featured);
const router = useNavigate();
const { mutate } = useMutation({
mutationFn: (body: SendLocation) => location_api.send_loaction(body),
onSuccess: () => {
toast.success("Lokatsiya jo'natildi");
router("/location");
},
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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const handleLocationClick = () => {
navigator.geolocation.getCurrentPosition(
(pos) => {
mutate({
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
});
},
(err) => {
console.error("Lokatsiya olishda xatolik:", err);
},
{
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 0,
},
);
};
return (
<main className="min-h-screen bg-background">
<div className="w-fit mt-5 mx-auto flex flex-col">
<img
src={LOGO}
width={300}
height={300}
alt="logo"
className="w-44 h-12"
/>
</div>
<div className="px-4 sm:px-6 mt-5 lg:px-4 bg-background">
<div className="max-w-6xl mx-auto">
<p className="text-md font-bold text-black mb-5 uppercase">Asosiy</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
{featuredItems.map((item) => {
const isLocation = item.id === "lokatsiya";
return (
<div
key={item.id}
onClick={isLocation ? handleLocationClick : undefined}
className="group relative px-4 cursor-pointer"
>
{!isLocation ? (
<Link to={item.link} className="absolute inset-0"></Link>
) : null}
<div
className={clsx(
"flex items-start gap-6 pb-2 border-b border-border hover:border-primary/30 transition-colors",
isLocation && "shadow-sm p-2 rounded-xl scale-[115%]",
)}
>
<div
className={clsx(
"shrink-0 w-12 h-12 rounded-lg text-primary flex items-center justify-center",
isLocation && "bg-primary text-white",
)}
>
{item.icon}
</div>
<div className="flex-1">
<h3
className={clsx(
"text-lg font-bold text-foreground",
isLocation && "text-primary",
)}
>
{item.title}
</h3>
<p className="text-xs text-muted-foreground">
{item.description}
</p>
</div>
<div className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
<svg
className="w-5 h-5 text-primary"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5l7 7-7 7"
/>
</svg>
</div>
</div>
</div>
);
})}
</div>
</div>
</div>
<div className="mt-5">
<p className="text-md font-bold text-black uppercase px-2">
Boshqaruv paneli
</p>
<div className="flex p-2 gap-2">
<>
<Link
to={"/plan"}
className="relative rounded-lg flex justify-center items-center border border-border w-[60%]"
>
<div className="flex flex-col items-center text-center p-4">
<div className="text-primary/60 group-hover:text-primary transition-colors mb-3">
<Calendar className="w-14 h-14" />
</div>
<h4 className="font-semibold text-foreground text-lg">Reja</h4>
</div>
</Link>
</>
<div className="relative flex flex-col gap-2 w-[40%]">
<Link to={"/district"} className="border border-border rounded-lg">
<div className="flex flex-col items-center text-center p-4">
<div className="text-primary/60 group-hover:text-primary transition-colors mb-3">
<Layers className="w-6 h-6" />
</div>
<h4 className="font-semibold text-foreground text-sm">Tuman</h4>
</div>
</Link>
<Link to={"/object"} className="border border-border rounded-lg">
<div className="flex flex-col items-center text-center p-4">
<div className="text-primary/60 group-hover:text-primary transition-colors mb-3">
<HomeIcon className="w-6 h-6" />
</div>
<h4 className="font-semibold text-foreground text-sm">
Obyekt
</h4>
</div>
</Link>
</div>
</div>
<div className="flex p-2 gap-2">
<div className="relative flex flex-col gap-1 w-[40%]">
<Link to={"/physician"} className="border border-border rounded-lg">
<div className="flex flex-col items-center text-center p-4">
<div className="text-primary/60 group-hover:text-primary transition-colors mb-3">
<User className="w-6 h-6" />
</div>
<h4 className="font-semibold text-foreground text-sm">
Shifokor
</h4>
</div>
</Link>
<Link to={"/pharmacy"} className="border border-border rounded-lg">
<div className="flex flex-col items-center text-center p-4">
<div className="text-primary/60 group-hover:text-primary transition-colors mb-3">
<Syringe className="w-6 h-6" />
</div>
<h4 className="font-semibold text-foreground text-sm">
Dorixona
</h4>
</div>
</Link>
</div>
<>
<Link
to={"/type-plan"}
className="relative rounded-lg flex justify-center items-center border border-border w-[60%]"
>
<div className="flex flex-col items-center text-center p-4">
<div className="text-primary/60 group-hover:text-primary transition-colors mb-3">
<Clipboard className="w-14 h-14" />
</div>
<h4 className="font-semibold text-foreground text-lg">
Hisobotlar
</h4>
</div>
</Link>
</>
</div>
</div>
</main>
);
}

1
src/features/index.ts Normal file
View File

@@ -0,0 +1 @@
// Ushbu fayl loyiha structurasi uchun qo'shilgan. O'chirib tashlasangiz bo'ladi

View File

@@ -0,0 +1,52 @@
import type { LocationListData } from "@/features/home/lib/api";
import formatDate from "@/shared/lib/formatDate";
import type { ColumnDef } from "@tanstack/react-table";
export const columns: ColumnDef<LocationListData>[] = [
{
id: "select",
header: "№",
cell: ({ row }) => <div>{row.original.id}</div>,
},
{
accessorKey: "type",
header: "Turi",
cell: ({ row }) => (
<div className="capitalize">
{row.original.district
? "Tuman"
: row.original.place
? "Obyekt"
: row.original.pharmacy
? "Dorixona"
: row.original.doctor && "Shifokor"}
</div>
),
},
{
accessorKey: "address",
header: "Manzil",
cell: ({ row }) => (
<div className="capitalize">
{" "}
{row.original.district
? row.original.district.name
: row.original.place
? row.original.place.name
: row.original.pharmacy
? row.original.pharmacy.name
: row.original.doctor &&
row.original.doctor.first_name + row.original.doctor.last_name}
</div>
),
},
{
accessorKey: "create_at",
header: "Jo'natilgan",
cell: ({ row }) => (
<div className="capitalize">
{formatDate.format(row.original.created_at, "DD-MM-YYYY HH:mm")}
</div>
),
},
];

View File

@@ -0,0 +1,52 @@
export type LocationItem = {
id: number;
type: "district" | "object" | "doctor" | "pharm";
value: string;
timestamp: string;
};
export const districts = [
"Chilonzor",
"Yunusobod",
"Mirzo Ulug'bek",
"Yakkasaroy",
"Mirobod",
];
export const objects = [
"1-shifoxona",
"2-shifoxona",
"3-poliklinika",
"4-diagnostika markazi",
"5-tibbiy markaz",
];
export const doctors = [
"Dr. Aliyev",
"Dr. Karimova",
"Dr. Normatov",
"Dr. Rahimova",
"Dr. Toshmatov",
];
export const pharm = [
"Dorixona 1",
"Dorixona 2",
"Dorixona 3",
"Dorixona 4",
"Dorixona 5",
];
export interface Payment {
id: number;
type: "district" | "object" | "doctor" | "pharm";
address: string;
create_at: Date;
}
export const fakeLocation: Payment[] = [
{
id: 1,
address: "Yunusobod",
create_at: new Date(),
type: "district",
},
];

View File

@@ -0,0 +1,359 @@
"use client";
import { district_api } from "@/features/district/lib/api";
import { doctor_api } from "@/features/doctor/lib/api";
import { location_api, type CreateLocation } from "@/features/home/lib/api";
import { object_api } from "@/features/object/lib/api";
import { pharmacy_api } from "@/features/phamarcy/lib/api";
import { Button } from "@/shared/ui/button";
import { Card, CardDescription, CardHeader, CardTitle } from "@/shared/ui/card";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/ui/dialog";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/shared/ui/table";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
} from "@tanstack/react-table";
import { AxiosError } from "axios";
import { Loader2, MapPin, Send } from "lucide-react";
import React, { useState } from "react";
import { toast } from "sonner";
import { columns } from "../lib/column";
const MyLocation: React.FC = () => {
const [showMainModal, setShowMainModal] = useState<boolean>(false);
const queryClinent = useQueryClient();
const [showSelectModal, setShowSelectModal] = useState<boolean>(false);
const [selectType, setSelectType] = useState<
"district" | "object" | "doctor" | "pharm" | null
>(null);
const [loadingButtonId, setLoadingButtonId] = useState<number | null>(null);
const mutation = useMutation({
mutationFn: (body: CreateLocation) => location_api.create_location(body),
onSuccess: () => {
toast.success("Lokatsiya jo'natildi");
setShowSelectModal(false);
setLoadingButtonId(null);
queryClinent.refetchQueries({ queryKey: ["location_list"] });
},
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[];
};
};
toast.error(
errorName.data?.name?.[0] ||
data.message ||
errorData?.messages?.[0]?.message ||
"Xatolik yuz berdi",
);
setLoadingButtonId(null);
},
});
const { data: location } = useQuery({
queryKey: ["location_list"],
queryFn: () => location_api.list_location(),
select(data) {
return data.data.data;
},
});
const { data: districts, isLoading: isDistrictsLoading } = useQuery({
queryKey: ["my_disctrict"],
queryFn: () => district_api.getDiscrict(),
select: (data) => data.data.data,
});
const { data: objects, isLoading: isObjectsLoading } = useQuery({
queryKey: ["object_list"],
queryFn: () => object_api.getAll({}),
select: (data) => data.data.data,
});
const { data: doctors, isLoading: isDoctorsLoading } = useQuery({
queryKey: ["doctor_list"],
queryFn: () => doctor_api.list(),
select: (data) => data.data.data,
});
const { data: pharm, isLoading: isPharmLoading } = useQuery({
queryKey: ["pharmacy_list"],
queryFn: () => pharmacy_api.list(),
select: (data) => data.data.data,
});
const getOptions = () => {
if (selectType === "district") return districts;
if (selectType === "object") return objects;
if (selectType === "doctor") return doctors;
if (selectType === "pharm") return pharm;
return [];
};
const isLoading = () => {
if (selectType === "district") return isDistrictsLoading;
if (selectType === "object") return isObjectsLoading;
if (selectType === "doctor") return isDoctorsLoading;
if (selectType === "pharm") return isPharmLoading;
return false;
};
const typeLabel = (type: "district" | "object" | "doctor" | "pharm") => {
if (type === "district") return "Tuman";
if (type === "object") return "Obyekt";
if (type === "doctor") return "Shifokor";
if (type === "pharm") return "Dorixona";
};
const handleAddLocation = (id: number) => {
if (!selectType) return;
setLoadingButtonId(id); // faqat shu button loading
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const body: CreateLocation = {
latitude,
longitude,
};
switch (selectType) {
case "district":
body.district_id = id;
break;
case "object":
body.place_id = id;
break;
case "doctor":
body.doctor_id = id;
break;
case "pharm":
body.pharmacy_id = id;
break;
}
mutation.mutate(body);
},
() => {
toast.error("Geolokatsiya olinmadi");
setLoadingButtonId(null);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 0 },
);
};
const table = useReactTable({
data: location || [],
columns: columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
});
return (
<DashboardLayout>
<div className="space-y-4">
<Card>
<CardHeader className="flex flex-col">
<div className="flex items-center gap-3">
<div className="w-12 h-12 bg-blue-500 rounded-full flex items-center justify-center">
<MapPin className="text-white" size={24} />
</div>
<div>
<CardTitle className="text-2xl">Lokatsiya Tizimi</CardTitle>
<CardDescription>{"Manzil jo'natish va tarix"}</CardDescription>
</div>
</div>
</CardHeader>
</Card>
{/* Main Modal */}
<Dialog open={showMainModal} onOpenChange={setShowMainModal}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="text-2xl">
{"Nimani jo'natasiz?"}
</DialogTitle>
</DialogHeader>
<div className="space-y-3 mt-4">
{(["district", "object", "doctor", "pharm"] as const).map(
(type) => (
<Button
key={type}
onClick={() => {
setSelectType(type);
setShowSelectModal(true);
setShowMainModal(false);
}}
className="w-full h-12 text-lg"
variant="outline"
>
{typeLabel(type)}
</Button>
),
)}
</div>
</DialogContent>
</Dialog>
{/* Select Modal */}
<Dialog open={showSelectModal} onOpenChange={setShowSelectModal}>
<DialogContent className="sm:max-w-md h-[60%] flex flex-col justify-start overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-2xl">
Mavjud {selectType && typeLabel(selectType)}lar
</DialogTitle>
</DialogHeader>
<div className="space-y-2 flex flex-col flex-1">
{isLoading() ? (
<div className="flex flex-col items-center justify-center py-12 gap-3">
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
<p className="text-muted-foreground">Yuklanmoqda...</p>
</div>
) : getOptions()?.length === 0 ? (
<div className="flex items-center justify-center py-12">
<p className="text-muted-foreground">Ma'lumot topilmadi</p>
</div>
) : (
getOptions()?.map((item) => {
const id = item.id;
const label =
"name" in item
? item.name
: `${item.first_name} ${item.last_name}`;
const isButtonLoading = loadingButtonId === id;
return (
<Button
key={id}
onClick={() => handleAddLocation(id)}
variant="outline"
className="w-full justify-start h-auto py-3 flex items-center gap-2"
disabled={isButtonLoading}
>
<MapPin className="h-4 w-4" />
{isButtonLoading ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Yuklanmoqda...
</>
) : (
label
)}
</Button>
);
})
)}
</div>
<Button
onClick={() => setShowSelectModal(false)}
variant="outline"
className="w-full mt-2"
>
Bekor qilish
</Button>
</DialogContent>
</Dialog>
<div className="flex justify-end">
<Button onClick={() => setShowMainModal(true)} className="gap-2">
<Send size={20} />
<span>{"Lokatsiya Jo'natish"}</span>
</Button>
</div>
{/* Table */}
<div className="w-full">
<div className="overflow-hidden rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead
key={header.id}
className="border-r text-center"
>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="border-r text-center"
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext(),
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</div>
</div>
</DashboardLayout>
);
};
export default MyLocation;

View File

@@ -0,0 +1,18 @@
import type { CreateObjectReq, ObjectAll } from "@/features/object/lib/data";
import httpClient from "@/shared/config/api/httpClient";
import { OBJECT } from "@/shared/config/api/URLs";
import type { AxiosResponse } from "axios";
export const object_api = {
async added(body: CreateObjectReq) {
const res = await httpClient.post(`${OBJECT}create/`, body);
return res;
},
async getAll(params: {
district_id?: number;
}): Promise<AxiosResponse<ObjectAll>> {
const res = await httpClient.get(`${OBJECT}list/`, { params });
return res;
},
};

View File

@@ -0,0 +1,98 @@
import type { ObjectAllData } from "@/features/object/lib/data";
import { Button } from "@/shared/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/shared/ui/dropdown-menu";
import type { ColumnDef } from "@tanstack/react-table";
import { EllipsisVertical, Eye } from "lucide-react";
import type { NavigateFunction } from "react-router-dom";
interface ObjectType {
id: string;
name: string;
districtId: string;
districtName: string;
address: string;
latitude: number;
longitude: number;
}
interface ColumnProps {
onDeleteClick: (district: ObjectType) => void;
router: NavigateFunction;
}
export const columnsObject = ({
router,
}: ColumnProps): ColumnDef<ObjectAllData>[] => [
{
accessorKey: "id",
header: () => <div className="text-center"></div>,
cell: ({ row }) => {
return <div className="text-center font-medium">{row.index + 1}</div>;
},
},
{
accessorKey: "name",
header: () => <div className="text-center">Nomi</div>,
cell: ({ row }) => {
return <div className="text-center font-medium">{row.original.name}</div>;
},
},
{
accessorKey: "districtName",
header: () => <div className="text-center">Tuman</div>,
cell: ({ row }) => {
return (
<div className="text-center font-medium">
{row.original.district.name}
</div>
);
},
},
{
id: "actions",
header: () => <div className="text-center">Amallar</div>,
cell: ({ row }) => {
const obj = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-full h-full hover:bg-gray-100">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="flex flex-col gap-1">
<Button
variant={"ghost"}
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-blue-400 hover:text-white text-white bg-blue-400"
onClick={() =>
router(
`/object/location?id=${obj.id}&lat=${obj.latitude}&lon=${obj.longitude}`,
)
}
>
<Eye size={16} /> Korish
</Button>
{/* <Button
variant="ghost"
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-green-400 hover:text-white text-white bg-green-400"
onClick={() => router.push(`/object/edit/${obj.id}`)}
>
<Edit size={16} /> Tahrirlash
</Button>
<Button
variant={'ghost'}
onClick={() => onDeleteClick(obj)}
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-red-400 hover:text-white text-white bg-red-400"
>
<Trash size={16} /> Ochirish
</Button> */}
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];

View File

@@ -0,0 +1,80 @@
"use client";
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/shared/ui/table";
interface DataTableProps<ObjectAllData, TValue> {
columns: ColumnDef<ObjectAllData, TValue>[];
data: ObjectAllData[];
}
export function DataTableObject<ObjectAllData, TValue>({
columns,
data,
}: DataTableProps<ObjectAllData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="overflow-hidden rounded-md border">
<Table className="">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} className="border-r">
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="border-r">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -0,0 +1,33 @@
export interface CreateObjectReq {
name: string;
latitude: number;
longitude: number;
extra_location: {
latitude: number;
longitude: number;
};
district_id: number;
}
export interface ObjectAll {
status_code: number;
status: string;
message: string;
data: ObjectAllData[];
}
export interface ObjectAllData {
id: number;
name: string;
latitude: number;
longitude: number;
extra_location: {
latitude: number;
longitude: number;
};
district: {
id: number;
name: string;
};
created_at: string;
}

View File

@@ -0,0 +1,12 @@
import { z } from "zod";
export const pharmacyForm = z.object({
name: z.string().min(2, {
error: "Eng kamida 2ta belgi bo'lishi kerak",
}),
districts: z.string().min(1, {
error: "Majburiy maydon",
}),
latitude: z.number({ error: "Majburiy maydon" }),
longitude: z.number({ error: "Majburiy maydon" }),
});

View File

@@ -0,0 +1,321 @@
"use client";
import { district_api } from "@/features/district/lib/api";
import type { CreateObjectReq } from "@/features/object/lib/data";
import { Button } from "@/shared/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/ui/select";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Map,
Placemark,
Polygon,
YMaps,
ZoomControl,
} from "@pbe/react-yandex-maps";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Loader2, LocateFixed } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import z from "zod";
import { object_api } from "../lib/api";
import { pharmacyForm } from "../lib/form";
interface CoordsData {
lat: number;
lon: number;
polygon: [number, number][][];
}
const CreateObject = () => {
const router = useNavigate();
const queryClient = useQueryClient();
const form = useForm<z.infer<typeof pharmacyForm>>({
resolver: zodResolver(pharmacyForm),
defaultValues: {
districts: "",
name: "",
},
});
const { data: districts } = useQuery({
queryKey: ["my_disctrict"],
queryFn: () => district_api.getDiscrict(),
select(data) {
return data.data.data;
},
});
const { mutate, isPending } = useMutation({
mutationFn: (body: CreateObjectReq) => {
return object_api.added(body);
},
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ["object_list"] });
router("/object");
},
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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const [coords, setCoords] = useState({
latitude: 41.311081,
longitude: 69.240562,
});
const [polygonCoords, setPolygonCoords] = useState<
[number, number][][] | null
>(null);
const getCoords = async (name: string): Promise<CoordsData | null> => {
const res = await fetch(
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(name)}&format=json&polygon_geojson=1&limit=1`,
);
const data = await res.json();
if (data.length > 0 && data[0].geojson) {
const lat = parseFloat(data[0].lat);
const lon = parseFloat(data[0].lon);
let polygon: [number, number][][] = [];
if (data[0].geojson.type === "Polygon") {
polygon = data[0].geojson.coordinates.map((ring: [number, number][]) =>
ring.map((coord: [number, number]) => [coord[1], coord[0]]),
);
} else if (data[0].geojson.type === "MultiPolygon") {
polygon = data[0].geojson.coordinates.map(
(poly: [number, number][][]) =>
poly[0].map((coord: [number, number]) => [coord[1], coord[0]]),
);
}
return { lat, lon, polygon };
}
return null;
};
const handleMapClick = (
e: ymaps.IEvent<MouseEvent, { coords: [number, number] }>,
) => {
const [lat, lon] = e.get("coords");
setCoords({ latitude: lat, longitude: lon });
form.setValue("latitude", lat);
form.setValue("longitude", lon);
};
const handleShowMyLocation = () => {
if (!navigator.geolocation) {
alert("Sizning brauzeringiz geolokatsiyani qollab-quvvatlamaydi");
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
setCoords({ latitude: lat, longitude: lon });
form.setValue("latitude", lat);
form.setValue("longitude", lon);
},
(error) => {
alert("Joylashuv aniqlanmadi: " + error.message);
},
);
};
async function onSubmit(values: z.infer<typeof pharmacyForm>) {
mutate({
district_id: Number(values.districts),
extra_location: {
latitude: values.latitude,
longitude: values.longitude,
},
latitude: values.latitude,
longitude: values.longitude,
name: values.name,
});
}
return (
<DashboardLayout>
<div className="max-w-3xl mx-auto space-y-6">
<h1 className="text-3xl font-bold">{"Yangi obyekt qo'shish"}</h1>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Nomi</FormLabel>
<FormControl>
<Input
placeholder="Nomi"
className="h-12 focus-visible:ring-0 focus-visible:border-input"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="districts"
render={({ field }) => (
<FormItem>
<FormLabel>Tuman</FormLabel>
<FormControl>
<Select
onValueChange={async (id) => {
field.onChange(id);
const selectedDistrict = districts?.find(
(d) => d.id === Number(id),
);
if (!selectedDistrict) return;
const coordsData = await getCoords(
selectedDistrict.name,
);
if (!coordsData) return;
setCoords({
latitude: coordsData.lat,
longitude: coordsData.lon,
});
setPolygonCoords(coordsData.polygon);
form.setValue("latitude", coordsData.lat);
form.setValue("longitude", coordsData.lon);
}}
value={field.value}
>
<SelectTrigger className="w-full h-12">
<SelectValue placeholder="Tumanlar" />
</SelectTrigger>
<SelectContent>
{districts?.map((e) => (
<SelectItem value={String(e.id)} key={e.id}>
{e.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="latitude"
render={() => (
<FormItem>
<FormLabel>Xarita</FormLabel>
<FormControl>
<div className="relative h-80 border rounded-lg overflow-hidden">
<YMaps query={{ lang: "en_RU" }}>
<Map
defaultState={{
center: [coords.latitude, coords.longitude],
zoom: 12,
}}
width="100%"
height="100%"
onClick={handleMapClick}
>
<ZoomControl
options={{
position: { right: "10px", bottom: "70px" },
}}
/>
<Placemark
geometry={[coords.latitude, coords.longitude]}
/>
{polygonCoords && (
<Polygon
geometry={polygonCoords}
options={{
fillColor: "rgba(0, 150, 255, 0.2)",
strokeColor: "rgba(0, 150, 255, 0.8)",
strokeWidth: 2,
interactivityModel: "default#transparent",
}}
/>
)}
</Map>
</YMaps>
<Button
type="button"
size="sm"
onClick={handleShowMyLocation}
className="absolute bottom-3 right-2.5 shadow-md bg-white text-black hover:bg-gray-100"
>
<LocateFixed className="w-4 h-4 mr-1" />
Mening joylashuvim
</Button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
type={"button"}
className="h-12 p-3"
onClick={() => router("/object")}
>
Bekor qilish
</Button>
<Button type="submit" className="h-12 p-5" disabled={isPending}>
{isPending ? <Loader2 className="animate-spin" /> : "Qo'shish"}
</Button>
</div>
</form>
</Form>
</div>
</DashboardLayout>
);
};
export default CreateObject;

View File

@@ -0,0 +1,119 @@
"use client";
import AddedButton from "@/shared/ui/added-button";
import { Button } from "@/shared/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/shared/ui/dialog";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { object_api } from "../lib/api";
import { columnsObject } from "../lib/column";
import { DataTableObject } from "../lib/data-table";
interface ObjectType {
id: string;
name: string;
districtId: string;
districtName: string;
address: string;
latitude: number;
longitude: number;
}
const ObjectList = () => {
const router = useNavigate();
const [deleteDialog, setDeleteDialog] = useState(false);
const [selectedObject, setSelectedObject] = useState<ObjectType | null>(null);
const {
data: objects,
isLoading,
isError,
} = useQuery({
queryKey: ["object_list"],
queryFn: () => object_api.getAll({}),
select(data) {
return data.data.data;
},
});
const handleDelete = () => {
if (selectedObject) {
// Object o'chirish logikasi shu yerda bo'lishi kerak
setSelectedObject(null);
setDeleteDialog(false);
}
};
const columns = columnsObject({
onDeleteClick: (object) => {
setSelectedObject(object);
setDeleteDialog(true);
},
router: router,
});
return (
<DashboardLayout>
<AddedButton onClick={() => router("/object/added")} />
<div className="space-y-6">
<h1 className="text-3xl font-bold">Obyektlar royxati</h1>
{isLoading && (
<div className="flex justify-center items-center h-64">
<span className="text-gray-500">Yuklanmoqda...</span>
</div>
)}
{isError && (
<div className="flex justify-center items-center h-64">
<span className="text-red-500">
Xatolik yuz berdi. Iltimos, qayta urinib koring.
</span>
</div>
)}
{!isLoading && !isError && objects && objects.length > 0 && (
<div className="overflow-x-auto">
<DataTableObject columns={columns} data={objects} />
</div>
)}
{!isLoading && !isError && objects && objects.length === 0 && (
<div className="flex justify-center items-center h-64">
<span className="text-gray-500">Hech qanday obyekt topilmadi.</span>
</div>
)}
</div>
<Dialog open={deleteDialog} onOpenChange={setDeleteDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-start">Ochirish</DialogTitle>
</DialogHeader>
<p>
Siz haqiqatdan ham <strong>{selectedObject?.name}</strong> obyektni
ochirmoqchimisiz?
</p>
<DialogFooter className="flex flex-row justify-end gap-2">
<Button variant="secondary" onClick={() => setDeleteDialog(false)}>
Bekor qilish
</Button>
<Button variant="destructive" onClick={handleDelete}>
Ochirish
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DashboardLayout>
);
};
export default ObjectList;

View File

@@ -0,0 +1,399 @@
"use client";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import L from "leaflet";
import { useEffect, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
interface RouteData {
distance: string;
duration: number;
}
interface RoutesFoundEvent {
routes: {
summary: {
totalDistance: number;
totalTime: number;
};
}[];
}
interface LeafletRoutingControl extends L.Control {
on(event: "routesfound", callback: (e: RoutesFoundEvent) => void): this;
on(event: "routingerror", callback: () => void): this;
}
const ObjectMapPage = () => {
const [searchParams] = useSearchParams();
const lat = parseFloat(searchParams.get("lat") || "0");
const lon = parseFloat(searchParams.get("lon") || "0");
const name = searchParams.get("name") || "";
const address = searchParams.get("address") || "";
const district = searchParams.get("district") || "";
const [userCoords, setUserCoords] = useState<[number, number] | null>(null);
const [routeData, setRouteData] = useState<RouteData | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>("");
const [showMapModal, setShowMapModal] = useState(false);
const [availableMaps, setAvailableMaps] = useState<
{ name: string; color: string; type: string }[]
>([]);
const mapRef = useRef<HTMLDivElement | null>(null);
const mapInstance = useRef<L.Map | null>(null);
const routeControlRef = useRef<LeafletRoutingControl | null>(null);
const markersRef = useRef<L.Marker[]>([]);
const isInitialized = useRef(false);
// ✅ Xaritalar ro'yxatini aniqlash
useEffect(() => {
const detectMaps = () => {
const maps: { name: string; color: string; type: string }[] = [];
const userAgent = navigator.userAgent.toLowerCase();
if (/android/.test(userAgent)) {
maps.push({
name: "Google Maps",
color: "bg-blue-500",
type: "google",
});
maps.push({ name: "Yandex Maps", color: "bg-red-500", type: "yandex" });
} else if (/iphone|ipad|ipod/.test(userAgent)) {
maps.push({ name: "Apple Maps", color: "bg-gray-700", type: "apple" });
maps.push({
name: "Google Maps",
color: "bg-blue-500",
type: "google",
});
maps.push({ name: "Yandex Maps", color: "bg-red-500", type: "yandex" });
} else {
maps.push({
name: "Google Maps",
color: "bg-blue-500",
type: "google",
});
maps.push({ name: "Yandex Maps", color: "bg-red-500", type: "yandex" });
maps.push({
name: "OpenStreetMap",
color: "bg-green-500",
type: "osm",
});
}
setAvailableMaps(maps);
};
detectMaps();
}, []);
// ✅ Foydalanuvchi geolokatsiyasi
useEffect(() => {
if (navigator.geolocation) {
setLoading(true);
navigator.geolocation.getCurrentPosition(
(pos) => {
setUserCoords([pos.coords.latitude, pos.coords.longitude]);
setLoading(false);
},
(err) => {
console.error("Geolocation xatosi:", err);
setError("Joylashuvni aniqlashda xatolik");
setLoading(false);
},
);
}
}, []);
// ✅ Xarita yaratish va marshrut chizish
useEffect(() => {
const initMap = async () => {
if (
typeof window === "undefined" ||
!mapRef.current ||
isInitialized.current
)
return;
try {
const L = (await import("leaflet")).default;
await import("leaflet/dist/leaflet.css");
await import("leaflet-routing-machine");
await import(
"leaflet-routing-machine/dist/leaflet-routing-machine.css"
);
// Xaritani yaratish
if (!mapInstance.current) {
mapInstance.current = L.map(mapRef.current).setView([lat, lon], 13);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 19,
}).addTo(mapInstance.current);
isInitialized.current = true;
}
// Agar foydalanuvchi koordinatalari mavjud bo'lsa, marshrut chizish
if (userCoords && mapInstance.current) {
setLoading(true);
// Oldingi marshrut va markerlarni o'chirish
if (routeControlRef.current) {
mapInstance.current.removeControl(routeControlRef.current);
routeControlRef.current = null;
}
markersRef.current.forEach((m) =>
mapInstance.current?.removeLayer(m),
);
markersRef.current = [];
// Foydalanuvchi markeri
const userIcon = L.icon({
iconUrl:
"https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-blue.png",
shadowUrl:
"https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
});
const userMarker = L.marker(userCoords, { icon: userIcon })
.addTo(mapInstance.current)
.bindPopup("Sizning joylashuvingiz");
markersRef.current.push(userMarker);
// Manzil markeri
const destIcon = L.icon({
iconUrl:
"https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
shadowUrl:
"https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
});
const destMarker = L.marker([lat, lon], { icon: destIcon })
.addTo(mapInstance.current)
.bindPopup(
`<strong>${name}</strong><br/>${address}<br/>${district}`,
);
markersRef.current.push(destMarker);
// Marshrut control yaratish
const control = (
L.Routing.control as unknown as (options: {
waypoints: L.LatLng[];
router: ReturnType<typeof L.Routing.osrmv1>;
addWaypoints: boolean;
draggableWaypoints: boolean;
fitSelectedRoutes: boolean;
showAlternatives: boolean;
lineOptions: {
styles: { color: string; weight: number; opacity: number }[];
};
createMarker: () => null;
}) => LeafletRoutingControl
)({
waypoints: [
L.latLng(userCoords[0], userCoords[1]),
L.latLng(lat, lon),
],
router: L.Routing.osrmv1({
serviceUrl: "https://router.project-osrm.org/route/v1",
}),
addWaypoints: false,
draggableWaypoints: false,
fitSelectedRoutes: true,
showAlternatives: false,
lineOptions: {
styles: [{ color: "#3b82f6", weight: 6, opacity: 0.7 }],
},
createMarker: () => null,
}).addTo(mapInstance.current);
// Event handlerlar
control.on("routesfound", (e: RoutesFoundEvent) => {
const summary = e.routes[0].summary;
setRouteData({
distance: (summary.totalDistance / 1000).toFixed(2),
duration: Math.round(summary.totalTime / 60),
});
setLoading(false);
setError("");
});
control.on("routingerror", () => {
setError("Marshrut topilmadi");
setLoading(false);
});
// Controlni saqlash
routeControlRef.current = control;
} else if (!userCoords) {
// Faqat manzil markerini ko'rsatish
const destIcon = L.icon({
iconUrl:
"https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
shadowUrl:
"https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
});
const destMarker = L.marker([lat, lon], { icon: destIcon })
.addTo(mapInstance.current)
.bindPopup(
`<strong>${name}</strong><br/>${address}<br/>${district}`,
)
.openPopup();
markersRef.current.push(destMarker);
}
} catch (err) {
console.error("Xarita xatosi:", err);
setError("Xaritani yuklashda xatolik");
setLoading(false);
}
};
initMap();
return () => {
if (mapInstance.current) {
mapInstance.current.remove();
mapInstance.current = null;
isInitialized.current = false;
}
};
}, [userCoords, lat, lon, name, address, district]);
const handleOpenInMap = (type: string) => {
let url = "";
switch (type) {
case "google":
url = `https://www.google.com/maps/dir/?api=1&destination=${lat},${lon}`;
break;
case "yandex":
url = `https://yandex.com/maps/?pt=${lon},${lat}&z=15&l=map`;
break;
case "apple":
url = `http://maps.apple.com/?daddr=${lat},${lon}`;
break;
case "osm":
url = `https://www.openstreetmap.org/directions?from=&to=${lat},${lon}#map=15/${lat}/${lon}`;
break;
default:
url = `https://www.google.com/maps?q=${lat},${lon}`;
}
window.open(url, "_blank");
setShowMapModal(false);
};
if (!lat || !lon)
return (
<DashboardLayout>
<p className="text-red-600">Koordinatalar mavjud emas</p>
</DashboardLayout>
);
return (
<DashboardLayout>
<div className="space-y-4">
{loading && (
<div className="rounded-lg bg-blue-50 p-4">
<p className="text-blue-800">Marshrut yuklanmoqda...</p>
</div>
)}
{error && (
<div className="rounded-lg bg-red-50 p-4">
<p className="text-red-800">{error}</p>
</div>
)}
{routeData && (
<div className="rounded-lg bg-green-50 p-4 text-green-800">
<strong>Masofa:</strong> {routeData.distance} km <br />
<strong>Taxminiy vaqt:</strong> {routeData.duration} daqiqa
</div>
)}
{!userCoords && !loading && !error && (
<div className="rounded-lg bg-yellow-50 p-4">
<p className="text-yellow-800">
{"Marshrut ko'rsatish uchun joylashuvga ruxsat bering"}
</p>
</div>
)}
<button
onClick={() => setShowMapModal(true)}
className="w-full rounded-lg bg-blue-600 px-6 py-3 text-white font-semibold hover:bg-blue-700 transition shadow-lg"
>
Boshqa xarita tanlash
</button>
<div ref={mapRef} className="h-[60vh] w-full rounded-lg shadow-lg" />
</div>
{showMapModal && (
<div
className="fixed inset-0 bg-black/50 z-[999999] flex items-end justify-center"
onClick={() => setShowMapModal(false)}
>
<div
className="bg-white w-full max-w-lg rounded-t-3xl p-6 space-y-2 animate-slide-up"
onClick={(e) => e.stopPropagation()}
>
<div className="w-12 h-1 bg-gray-300 rounded-full mx-auto mb-4" />
<h3 className="text-lg font-bold text-gray-800 mb-4 text-center">
Xaritani tanlang
</h3>
{availableMaps.map((map, index) => (
<button
key={index}
onClick={() => handleOpenInMap(map.type)}
className="w-full flex items-center gap-4 p-4 rounded-xl hover:bg-gray-100 transition border border-gray-200"
>
<span className="text-lg font-medium text-gray-800">
{map.name}
</span>
</button>
))}
<button
onClick={() => setShowMapModal(false)}
className="w-full mt-4 py-3 text-gray-600 font-medium hover:bg-gray-100 rounded-xl transition"
>
Bekor qilish
</button>
</div>
</div>
)}
<style>{`
@keyframes slide-up {
from {
transform: translateY(100%);
}
to {
transform: translateY(0);
}
}
.animate-slide-up {
animation: slide-up 0.3s ease-out;
}
`}</style>
</DashboardLayout>
);
};
export default ObjectMapPage;

View File

@@ -0,0 +1,19 @@
import type {
CreatePharmacyReq,
PharmacyList,
} from "@/features/phamarcy/lib/data";
import httpClient from "@/shared/config/api/httpClient";
import { PHARMACY } from "@/shared/config/api/URLs";
import type { AxiosResponse } from "axios";
export const pharmacy_api = {
async create(body: CreatePharmacyReq) {
const res = await httpClient.post(`${PHARMACY}create/`, body);
return res;
},
async list(): Promise<AxiosResponse<PharmacyList>> {
const res = await httpClient.get(`${PHARMACY}list/`);
return res;
},
};

View File

@@ -0,0 +1,132 @@
import formatPhone from "@/shared/lib/formatPhone";
import { Button } from "@/shared/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/shared/ui/dropdown-menu";
import type { ColumnDef } from "@tanstack/react-table";
import { Edit, EllipsisVertical, Eye, Trash } from "lucide-react";
import type { NavigateFunction } from "react-router-dom";
interface ObjectType {
id: string;
name: string;
inn: string; // INN qoshildi
phoneDirector: string; // Direktor tel raqami
phonePharmacy: string; // Dorixona / masul shaxs tel raqami
districtId: string;
districtName: string;
latitude: number;
longitude: number;
}
interface ColumnProps {
onDeleteClick: (district: ObjectType) => void;
router: NavigateFunction;
}
export const columnsPharmacy = ({
onDeleteClick,
router,
}: ColumnProps): ColumnDef<ObjectType>[] => [
{
accessorKey: "id",
header: () => <div className="text-center"></div>,
cell: ({ row }) => {
return <div className="text-center font-medium">{row.index + 1}</div>;
},
},
{
accessorKey: "name",
header: () => <div className="text-center">Nomi</div>,
cell: ({ row }) => {
return <div className="text-center font-medium">{row.original.name}</div>;
},
},
{
accessorKey: "districtName",
header: () => <div className="text-center">Tuman</div>,
cell: ({ row }) => {
return (
<div className="text-center font-medium">
{row.original.districtName}
</div>
);
},
},
{
accessorKey: "inn",
header: () => <div className="text-center">INN</div>,
cell: ({ row }) => <div className="text-center">{row.original.inn}</div>,
},
{
id: "phones",
header: () => (
<div className="text-center">{"Dorixonaga ma'sul shaxs nomeri"}</div>
),
cell: ({ row }) => {
const pharmacyPhone = row.original.phonePharmacy;
return (
<div className="flex flex-col text-center gap-2">
<span>{formatPhone(pharmacyPhone)}</span>
</div>
);
},
},
{
id: "phones",
header: () => <div className="text-center">Dorixona egasi nomeri</div>,
cell: ({ row }) => {
const directorPhone = row.original.phoneDirector;
return (
<div className="flex flex-col text-center gap-2">
<span>{formatPhone(directorPhone)}</span>
</div>
);
},
},
{
id: "actions",
header: () => <div className="text-center">Amallar</div>,
cell: ({ row }) => {
const obj = row.original;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="w-full h-full hover:bg-gray-100">
<EllipsisVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="flex flex-col gap-1">
<Button
variant={"ghost"}
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-blue-400 hover:text-white text-white bg-blue-400"
onClick={() =>
router(
`/object/location?id=${obj.id}&lat=${obj.latitude}&lon=${obj.longitude}`,
)
}
>
<Eye size={16} /> Korish
</Button>
<Button
variant="ghost"
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-green-400 hover:text-white text-white bg-green-400"
onClick={() => router(`/pharmacy/edit/${obj.id}`)}
>
<Edit size={16} /> Tahrirlash
</Button>
<Button
variant={"ghost"}
onClick={() => onDeleteClick(obj)}
className="flex items-center gap-1 px-4 py-2 w-full text-left hover:bg-red-400 hover:text-white text-white bg-red-400"
>
<Trash size={16} /> Ochirish
</Button>
</DropdownMenuContent>
</DropdownMenu>
);
},
},
];

View File

@@ -0,0 +1,80 @@
"use client";
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/shared/ui/table";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
}
export function DataTableObject<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="overflow-hidden rounded-md border">
<Table className="">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} className="border-r">
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="border-r">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -0,0 +1,41 @@
export interface CreatePharmacyReq {
name: string;
inn: string;
owner_phone: string;
responsible_phone: string;
district_id: number;
place_id: number;
longitude: number;
latitude: number;
extra_location: { longitude: number; latitude: number };
}
export interface PharmacyList {
status_code: number;
status: string;
message: string;
data: PharmacyListData[];
}
export interface PharmacyListData {
id: number;
name: string;
inn: string;
owner_phone: string;
responsible_phone: string;
district: {
id: number;
name: string;
};
place: {
id: number;
name: string;
};
longitude: number;
latitude: number;
extra_location: {
latitude: number;
longitude: number;
};
created_at: string;
}

View File

@@ -0,0 +1,26 @@
import { z } from "zod";
export const objectForm = z.object({
name: z.string().min(2, {
error: "Eng kamida 2ta belgi bo'lishi kerak",
}),
districts: z.string().min(1, {
error: "Majburiy maydon",
}),
streets: z.string().min(1, {
error: "Majburiy maydon",
}),
latitude: z.number({ error: "Majburiy maydon" }),
longitude: z.number({ error: "Majburiy maydon" }),
inn: z.string().min(1, { message: "Majburiy maydon" }),
phoneDirector: z.string().min(17, { message: "Majburiy maydon" }),
phonePharmacy: z.string().min(17, { message: "Majburiy maydon" }),
nearbyCoords: z
.array(
z.object({
lat: z.number(),
lon: z.number(),
}),
)
.optional(),
});

View File

@@ -0,0 +1,471 @@
"use client";
import { district_api } from "@/features/district/lib/api";
import { object_api } from "@/features/object/lib/api";
import type { CreatePharmacyReq } from "@/features/phamarcy/lib/data";
import formatPhone from "@/shared/lib/formatPhone";
import onlyNumber from "@/shared/lib/onlyNumber";
import { Button } from "@/shared/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/ui/select";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Circle,
Map,
Placemark,
Polygon,
YMaps,
ZoomControl,
} from "@pbe/react-yandex-maps";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { Loader2, LocateFixed } from "lucide-react";
import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import z from "zod";
import { pharmacy_api } from "../lib/api";
import { objectForm } from "../lib/form";
interface CoordsData {
lat: number;
lon: number;
polygon: [number, number][][];
}
const CreatePharmacy = () => {
const queryClinent = useQueryClient();
const router = useNavigate();
const mapRef = useRef<ymaps.Map | null>(null);
const form = useForm<z.infer<typeof objectForm>>({
resolver: zodResolver(objectForm),
defaultValues: {
districts: "",
name: "",
inn: "",
phoneDirector: "+998",
phonePharmacy: "+998",
},
});
const { mutate, isPending } = useMutation({
mutationFn: (body: CreatePharmacyReq) => pharmacy_api.create(body),
onSuccess: () => {
router("/pharmacy");
queryClinent.refetchQueries({ queryKey: ["pharmacy_list"] });
},
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[];
};
};
toast.error(
errorName.data?.name[0] ||
data.message ||
errorData?.messages?.[0].message ||
"Xatolik yuz berdi",
);
},
});
const { data: districts } = useQuery({
queryKey: ["my_disctrict"],
queryFn: () => district_api.getDiscrict(),
select(data) {
return data.data.data;
},
});
const district_id = form.watch("districts");
const { data: streets } = useQuery({
queryKey: ["object_list", district_id],
queryFn: () => object_api.getAll({ district_id: Number(district_id) }),
select(data) {
return data.data.data;
},
});
const [coords, setCoords] = useState({
latitude: 41.311081,
longitude: 69.240562,
});
const getCoords = async (name: string): Promise<CoordsData | null> => {
const res = await fetch(
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(name)}&format=json&polygon_geojson=1&limit=1`,
);
const data = await res.json();
if (data.length > 0 && data[0].geojson) {
const lat = parseFloat(data[0].lat);
const lon = parseFloat(data[0].lon);
let polygon: [number, number][][] = [];
if (data[0].geojson.type === "Polygon") {
polygon = data[0].geojson.coordinates.map((ring: [number, number][]) =>
ring.map((coord: [number, number]) => [coord[1], coord[0]]),
);
} else if (data[0].geojson.type === "MultiPolygon") {
polygon = data[0].geojson.coordinates.map(
(poly: [number, number][][]) =>
poly[0].map((coord: [number, number]) => [coord[1], coord[0]]),
);
}
return { lat, lon, polygon };
}
return null;
};
const [polygonCoords, setPolygonCoords] = useState<
[number, number][][] | null
>(null);
const [circleCoords, setCircleCoords] = useState<[number, number] | null>(
null,
);
const handleStreetChange = (streetId: string) => {
form.setValue("streets", streetId);
const selectedStreet = streets?.find((s) => s.id === Number(streetId));
if (!selectedStreet) return;
setCoords({
latitude: selectedStreet.latitude,
longitude: selectedStreet.longitude,
});
form.setValue("latitude", selectedStreet.latitude);
form.setValue("longitude", selectedStreet.longitude);
setCircleCoords([selectedStreet.latitude, selectedStreet.longitude]);
if (mapRef.current) {
mapRef.current.setCenter(
[selectedStreet.latitude, selectedStreet.longitude],
16,
);
}
};
const handleShowMyLocation = () => {
if (!navigator.geolocation) {
alert("Sizning brauzeringiz geolokatsiyani qollab-quvvatlamaydi");
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
setCoords({ latitude: lat, longitude: lon });
form.setValue("latitude", lat);
form.setValue("longitude", lon);
if (mapRef.current) {
mapRef.current.setCenter([lat, lon], 20);
}
},
(error) => {
alert("Joylashuv aniqlanmadi: " + error.message);
},
);
};
const handleMapClick = (
e: ymaps.IEvent<MouseEvent, { coords: [number, number] }>,
) => {
const [lat, lon] = e.get("coords");
setCoords({ latitude: lat, longitude: lon });
form.setValue("latitude", lat);
form.setValue("longitude", lon);
};
const onSubmit = (values: z.infer<typeof objectForm>) => {
mutate({
district_id: Number(values.districts),
extra_location: {
latitude: values.latitude,
longitude: values.longitude,
},
inn: values.inn,
latitude: values.latitude,
longitude: values.longitude,
name: values.name,
owner_phone: onlyNumber(values.phoneDirector),
place_id: Number(values.streets),
responsible_phone: onlyNumber(values.phonePharmacy),
});
};
return (
<DashboardLayout>
<div className="max-w-3xl mx-auto space-y-6">
<h1 className="text-3xl font-bold">{"Qo'shish"}</h1>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Nomi</FormLabel>
<FormControl>
<Input {...field} placeholder="Nomi" className="h-12" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="inn"
render={({ field }) => (
<FormItem>
<FormLabel>INN</FormLabel>
<FormControl>
<Input {...field} placeholder="INN" className="h-12" />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phoneDirector"
render={({ field }) => (
<FormItem>
<FormLabel>Dorixona egasining nomeri</FormLabel>
<FormControl>
<Input
{...field}
placeholder="+998 90 123-45-67"
className="h-12"
onChange={(e) => {
const formatted = formatPhone(e.target.value);
field.onChange(formatted);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phonePharmacy"
render={({ field }) => (
<FormItem>
<FormLabel>Masul shaxsning nomeri</FormLabel>
<FormControl>
<Input
{...field}
placeholder="+998 90 123-45-67"
className="h-12"
onChange={(e) => {
const formatted = formatPhone(e.target.value);
field.onChange(formatted);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="districts"
render={({ field }) => (
<FormItem>
<FormLabel>Tuman</FormLabel>
<FormControl>
<Select
key={field.value}
onValueChange={async (id) => {
field.onChange(id);
const selectedDistrict = districts?.find(
(d) => d.id === Number(id),
);
if (!selectedDistrict) return;
const coordsData = await getCoords(
selectedDistrict.name,
);
if (!coordsData) return;
setCoords({
latitude: coordsData.lat,
longitude: coordsData.lon,
});
setPolygonCoords(coordsData.polygon);
}}
value={field.value}
>
<SelectTrigger className="w-full h-12">
<SelectValue placeholder="Tumanlar" />
</SelectTrigger>
<SelectContent>
{districts?.map((d) => (
<SelectItem key={d.id} value={String(d.id)}>
{d.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="streets"
render={({ field }) => (
<FormItem>
<FormLabel>{"Ko'cha"}</FormLabel>
<FormControl>
<Select
key={field.value}
value={field.value}
onValueChange={(value) => {
field.onChange(value);
handleStreetChange(value);
}}
>
<SelectTrigger className="w-full h-12">
<SelectValue placeholder="Ko'chalar" />
</SelectTrigger>
<SelectContent>
{streets?.map((s) => (
<SelectItem key={s.id} value={String(s.id)}>
{s.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="latitude"
render={() => (
<FormItem>
<FormLabel>Xarita</FormLabel>
<FormControl>
<div className="relative h-80 border rounded-lg overflow-hidden">
<YMaps query={{ lang: "en_RU" }}>
<Map
defaultState={{
center: [coords.latitude, coords.longitude],
zoom: 12,
}}
width="100%"
height="100%"
onClick={handleMapClick}
>
<ZoomControl
options={{
position: { right: "10px", bottom: "70px" },
}}
/>
<Placemark
geometry={[coords.latitude, coords.longitude]}
/>
{polygonCoords && (
<Polygon
geometry={polygonCoords}
options={{
fillColor: "rgba(0, 150, 255, 0.2)",
strokeColor: "rgba(0, 150, 255, 0.8)",
strokeWidth: 2,
interactivityModel: "default#transparent",
}}
/>
)}
{circleCoords && (
<Circle
geometry={[circleCoords, 500]}
options={{
fillColor: "rgba(255, 100, 0, 0.3)",
strokeColor: "rgba(255, 100, 0, 0.8)",
strokeWidth: 2,
interactivityModel: "default#transparent",
}}
/>
)}
</Map>
</YMaps>
<Button
type="button"
size="sm"
onClick={handleShowMyLocation}
className="absolute bottom-3 right-2.5 shadow-md bg-white text-black hover:bg-gray-100"
>
<LocateFixed className="w-4 h-4 mr-1" />
</Button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex gap-2 justify-end">
<Button
variant="outline"
type="button"
className="h-12 p-3"
onClick={() => router("/pharmacy")}
>
Bekor qilish
</Button>
<Button type="submit" className="h-12 p-5">
{isPending ? <Loader2 className="animate-spin" /> : "Qo'shish"}
</Button>
</div>
</form>
</Form>
</div>
</DashboardLayout>
);
};
export default CreatePharmacy;

View File

@@ -0,0 +1,123 @@
"use client";
import formatPhone from "@/shared/lib/formatPhone";
import AddedButton from "@/shared/ui/added-button";
import { Button } from "@/shared/ui/button";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import { useQuery } from "@tanstack/react-query";
import { Eye } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { pharmacy_api } from "../lib/api";
const PharmacyList = () => {
const { data, isLoading, isError } = useQuery({
queryKey: ["pharmacy_list"],
queryFn: () => pharmacy_api.list(),
select(data) {
return data.data.data;
},
});
const router = useNavigate();
const [deleteDialog, setDeleteDialog] = useState(false);
return (
<DashboardLayout>
<div className="flex justify-between items-center">
<AddedButton onClick={() => router("/pharmacy/added")} />
</div>
<div className="space-y-6">
<h1 className="text-3xl font-bold">Dorixonalar royxati</h1>
{isLoading && (
<div className="flex justify-center items-center py-20">
<p className="text-gray-500 animate-pulse">Yuklanmoqda...</p>
</div>
)}
{isError && (
<div className="flex justify-center items-center py-20">
<p className="text-red-500">
Malumotlarni yuklashda xatolik yuz berdi
</p>
</div>
)}
{!isLoading && !isError && data?.length === 0 && (
<div className="flex justify-center items-center py-20">
<p className="text-gray-500">Hech qanday dorixona topilmadi</p>
</div>
)}
{!isLoading && !isError && data && data.length > 0 && (
<div className="grid grid-cols-1 gap-6">
{data.map((obj) => (
<div
key={obj.id}
className="border rounded-lg p-5 shadow-sm flex flex-col justify-between"
>
<div>
<h2 className="text-xl font-semibold">{obj.name}</h2>
<p className="text-gray-500">Tuman: {obj.district.name}</p>
<p className="text-gray-500">INN: {obj.inn}</p>
<p className="text-gray-500">
Direktor: {formatPhone(obj.owner_phone)}
</p>
<p className="text-gray-500">
Masul: {formatPhone(obj.responsible_phone)}
</p>
</div>
<div className="flex gap-2 mt-4 flex-col">
<Button
variant="outline"
size="lg"
onClick={() =>
router(
`/object/location?id=${obj.id}&lat=${obj.latitude}&lon=${obj.longitude}`,
)
}
>
<Eye className="size-4" />
<p className="text-md">Korish</p>
</Button>
</div>
</div>
))}
</div>
)}
</div>
{/* Delete dialog */}
<div>
{deleteDialog && (
<div className="fixed inset-0 bg-black/30 bg-opacity-30 flex items-center justify-center z-50">
<div className="bg-white p-6 rounded-lg w-80">
<h2 className="text-lg font-bold mb-4">Ochirish</h2>
<p>
Siz haqiqatdan ham <strong>{}</strong> obyektni
ochirmoqchimisiz?
</p>
<div className="flex justify-end gap-2 mt-6">
<Button
variant="outline"
size="sm"
onClick={() => setDeleteDialog(false)}
>
Bekor qilish
</Button>
<Button variant="destructive" size="sm">
Ochirish
</Button>
</div>
</div>
</div>
)}
</div>
</DashboardLayout>
);
};
export default PharmacyList;

View File

@@ -0,0 +1,399 @@
"use client";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout";
import L from "leaflet";
import { useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
interface RouteData {
distance: string;
duration: number;
}
interface RoutesFoundEvent {
routes: {
summary: {
totalDistance: number;
totalTime: number;
};
}[];
}
interface LeafletRoutingControl extends L.Control {
on(event: "routesfound", callback: (e: RoutesFoundEvent) => void): this;
on(event: "routingerror", callback: () => void): this;
}
const ObjectMapPage = () => {
const searchParams = useSearchParams();
const lat = parseFloat(searchParams.get("lat") || "0");
const lon = parseFloat(searchParams.get("lon") || "0");
const name = searchParams.get("name") || "";
const address = searchParams.get("address") || "";
const district = searchParams.get("district") || "";
const [userCoords, setUserCoords] = useState<[number, number] | null>(null);
const [routeData, setRouteData] = useState<RouteData | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>("");
const [showMapModal, setShowMapModal] = useState(false);
const [availableMaps, setAvailableMaps] = useState<
{ name: string; color: string; type: string }[]
>([]);
const mapRef = useRef<HTMLDivElement | null>(null);
const mapInstance = useRef<L.Map | null>(null);
const routeControlRef = useRef<LeafletRoutingControl | null>(null);
const markersRef = useRef<L.Marker[]>([]);
const isInitialized = useRef(false);
// ✅ Xaritalar ro'yxatini aniqlash
useEffect(() => {
const detectMaps = () => {
const maps: { name: string; color: string; type: string }[] = [];
const userAgent = navigator.userAgent.toLowerCase();
if (/android/.test(userAgent)) {
maps.push({
name: "Google Maps",
color: "bg-blue-500",
type: "google",
});
maps.push({ name: "Yandex Maps", color: "bg-red-500", type: "yandex" });
} else if (/iphone|ipad|ipod/.test(userAgent)) {
maps.push({ name: "Apple Maps", color: "bg-gray-700", type: "apple" });
maps.push({
name: "Google Maps",
color: "bg-blue-500",
type: "google",
});
maps.push({ name: "Yandex Maps", color: "bg-red-500", type: "yandex" });
} else {
maps.push({
name: "Google Maps",
color: "bg-blue-500",
type: "google",
});
maps.push({ name: "Yandex Maps", color: "bg-red-500", type: "yandex" });
maps.push({
name: "OpenStreetMap",
color: "bg-green-500",
type: "osm",
});
}
setAvailableMaps(maps);
};
detectMaps();
}, []);
// ✅ Foydalanuvchi geolokatsiyasi
useEffect(() => {
if (navigator.geolocation) {
setLoading(true);
navigator.geolocation.getCurrentPosition(
(pos) => {
setUserCoords([pos.coords.latitude, pos.coords.longitude]);
setLoading(false);
},
(err) => {
console.error("Geolocation xatosi:", err);
setError("Joylashuvni aniqlashda xatolik");
setLoading(false);
},
);
}
}, []);
// ✅ Xarita yaratish va marshrut chizish
useEffect(() => {
const initMap = async () => {
if (
typeof window === "undefined" ||
!mapRef.current ||
isInitialized.current
)
return;
try {
const L = (await import("leaflet")).default;
await import("leaflet/dist/leaflet.css");
await import("leaflet-routing-machine");
await import(
"leaflet-routing-machine/dist/leaflet-routing-machine.css"
);
// Xaritani yaratish
if (!mapInstance.current) {
mapInstance.current = L.map(mapRef.current).setView([lat, lon], 13);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
maxZoom: 19,
}).addTo(mapInstance.current);
isInitialized.current = true;
}
// Agar foydalanuvchi koordinatalari mavjud bo'lsa, marshrut chizish
if (userCoords && mapInstance.current) {
setLoading(true);
// Oldingi marshrut va markerlarni o'chirish
if (routeControlRef.current) {
mapInstance.current.removeControl(routeControlRef.current);
routeControlRef.current = null;
}
markersRef.current.forEach((m) =>
mapInstance.current?.removeLayer(m),
);
markersRef.current = [];
// Foydalanuvchi markeri
const userIcon = L.icon({
iconUrl:
"https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-blue.png",
shadowUrl:
"https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
});
const userMarker = L.marker(userCoords, { icon: userIcon })
.addTo(mapInstance.current)
.bindPopup("Sizning joylashuvingiz");
markersRef.current.push(userMarker);
// Manzil markeri
const destIcon = L.icon({
iconUrl:
"https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
shadowUrl:
"https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
});
const destMarker = L.marker([lat, lon], { icon: destIcon })
.addTo(mapInstance.current)
.bindPopup(
`<strong>${name}</strong><br/>${address}<br/>${district}`,
);
markersRef.current.push(destMarker);
// Marshrut control yaratish
const control = (
L.Routing.control as unknown as (options: {
waypoints: L.LatLng[];
router: ReturnType<typeof L.Routing.osrmv1>;
addWaypoints: boolean;
draggableWaypoints: boolean;
fitSelectedRoutes: boolean;
showAlternatives: boolean;
lineOptions: {
styles: { color: string; weight: number; opacity: number }[];
};
createMarker: () => null;
}) => LeafletRoutingControl
)({
waypoints: [
L.latLng(userCoords[0], userCoords[1]),
L.latLng(lat, lon),
],
router: L.Routing.osrmv1({
serviceUrl: "https://router.project-osrm.org/route/v1",
}),
addWaypoints: false,
draggableWaypoints: false,
fitSelectedRoutes: true,
showAlternatives: false,
lineOptions: {
styles: [{ color: "#3b82f6", weight: 6, opacity: 0.7 }],
},
createMarker: () => null,
}).addTo(mapInstance.current);
// Event handlerlar
control.on("routesfound", (e: RoutesFoundEvent) => {
const summary = e.routes[0].summary;
setRouteData({
distance: (summary.totalDistance / 1000).toFixed(2),
duration: Math.round(summary.totalTime / 60),
});
setLoading(false);
setError("");
});
control.on("routingerror", () => {
setError("Marshrut topilmadi");
setLoading(false);
});
// Controlni saqlash
routeControlRef.current = control;
} else if (!userCoords) {
// Faqat manzil markerini ko'rsatish
const destIcon = L.icon({
iconUrl:
"https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
shadowUrl:
"https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png",
iconSize: [25, 41],
iconAnchor: [12, 41],
});
const destMarker = L.marker([lat, lon], { icon: destIcon })
.addTo(mapInstance.current)
.bindPopup(
`<strong>${name}</strong><br/>${address}<br/>${district}`,
)
.openPopup();
markersRef.current.push(destMarker);
}
} catch (err) {
console.error("Xarita xatosi:", err);
setError("Xaritani yuklashda xatolik");
setLoading(false);
}
};
initMap();
return () => {
if (mapInstance.current) {
mapInstance.current.remove();
mapInstance.current = null;
isInitialized.current = false;
}
};
}, [userCoords, lat, lon, name, address, district]);
const handleOpenInMap = (type: string) => {
let url = "";
switch (type) {
case "google":
url = `https://www.google.com/maps/dir/?api=1&destination=${lat},${lon}`;
break;
case "yandex":
url = `https://yandex.com/maps/?pt=${lon},${lat}&z=15&l=map`;
break;
case "apple":
url = `http://maps.apple.com/?daddr=${lat},${lon}`;
break;
case "osm":
url = `https://www.openstreetmap.org/directions?from=&to=${lat},${lon}#map=15/${lat}/${lon}`;
break;
default:
url = `https://www.google.com/maps?q=${lat},${lon}`;
}
window.open(url, "_blank");
setShowMapModal(false);
};
if (!lat || !lon)
return (
<DashboardLayout>
<p className="text-red-600">Koordinatalar mavjud emas</p>
</DashboardLayout>
);
return (
<DashboardLayout>
<div className="space-y-4">
{loading && (
<div className="rounded-lg bg-blue-50 p-4">
<p className="text-blue-800">Marshrut yuklanmoqda...</p>
</div>
)}
{error && (
<div className="rounded-lg bg-red-50 p-4">
<p className="text-red-800">{error}</p>
</div>
)}
{routeData && (
<div className="rounded-lg bg-green-50 p-4 text-green-800">
<strong>Masofa:</strong> {routeData.distance} km <br />
<strong>Taxminiy vaqt:</strong> {routeData.duration} daqiqa
</div>
)}
{!userCoords && !loading && !error && (
<div className="rounded-lg bg-yellow-50 p-4">
<p className="text-yellow-800">
{"Marshrut ko'rsatish uchun joylashuvga ruxsat bering"}
</p>
</div>
)}
<button
onClick={() => setShowMapModal(true)}
className="w-full rounded-lg bg-blue-600 px-6 py-3 text-white font-semibold hover:bg-blue-700 transition shadow-lg"
>
Boshqa xarita tanlash
</button>
<div ref={mapRef} className="h-[60vh] w-full rounded-lg shadow-lg" />
</div>
{showMapModal && (
<div
className="fixed inset-0 bg-black/50 z-[999999] flex items-end justify-center"
onClick={() => setShowMapModal(false)}
>
<div
className="bg-white w-full max-w-lg rounded-t-3xl p-6 space-y-2 animate-slide-up"
onClick={(e) => e.stopPropagation()}
>
<div className="w-12 h-1 bg-gray-300 rounded-full mx-auto mb-4" />
<h3 className="text-lg font-bold text-gray-800 mb-4 text-center">
Xaritani tanlang
</h3>
{availableMaps.map((map, index) => (
<button
key={index}
onClick={() => handleOpenInMap(map.type)}
className="w-full flex items-center gap-4 p-4 rounded-xl hover:bg-gray-100 transition border border-gray-200"
>
<span className="text-lg font-medium text-gray-800">
{map.name}
</span>
</button>
))}
<button
onClick={() => setShowMapModal(false)}
className="w-full mt-4 py-3 text-gray-600 font-medium hover:bg-gray-100 rounded-xl transition"
>
Bekor qilish
</button>
</div>
</div>
)}
<style>{`
@keyframes slide-up {
from {
transform: translateY(100%);
}
to {
transform: translateY(0);
}
}
.animate-slide-up {
animation: slide-up 0.3s ease-out;
}
`}</style>
</DashboardLayout>
);
};
export default ObjectMapPage;

View File

@@ -0,0 +1,56 @@
// TYPES
export interface MonthData {
amount: number;
locked: boolean;
}
export interface Pharmacy {
id: number;
name: string;
district: string;
address: string;
monthlyData: Record<string, MonthData>;
}
export const FalkeDataPlanTour: Pharmacy[] = [
{
id: 1,
name: "Apteka Shifa",
district: "Chilonzor tumani",
address: "Bunyodkor ko'chasi, 12",
monthlyData: {
"2024-10": { amount: 5000000, locked: true },
"2024-11": { amount: 6000000, locked: true },
},
},
{
id: 2,
name: "DorixonaMed",
district: "Yunusobod tumani",
address: "Amir Temur shoh ko'chasi, 45",
monthlyData: {
"2024-10": { amount: 4500000, locked: true },
"2024-11": { amount: 5200000, locked: false },
},
},
{
id: 3,
name: "Farmatsiya Plus",
district: "Mirzo Ulug'bek tumani",
address: "Universitet ko'chasi, 78",
monthlyData: {
"2024-10": { amount: 7000000, locked: true },
"2024-11": { amount: 0, locked: false },
},
},
{
id: 4,
name: "Salomatlik Aptekasi",
district: "Yakkasaroy tumani",
address: "Mustaqillik ko'chasi, 33",
monthlyData: {
"2024-10": { amount: 3500000, locked: true },
"2024-11": { amount: 4000000, locked: false },
},
},
];

View File

@@ -0,0 +1,270 @@
import { LanguageRoutes } from "@/shared/config/i18n/types";
import { formatPrice } from "@/shared/lib/formatPrice";
import { Alert, AlertDescription } from "@/shared/ui/alert";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import { Input } from "@/shared/ui/input";
import { Building2, Check, DollarSign, Edit2, MapPin, X } from "lucide-react";
import { useEffect, useState } from "react";
import { FalkeDataPlanTour } from "../lib/mock";
// TYPES
interface MonthData {
amount: number;
locked: boolean;
}
interface Pharmacy {
id: number;
name: string;
district: string;
address: string;
monthlyData: Record<string, MonthData>;
}
interface PlanPriceProps {
selectedMonth: string;
}
const PlanPrice = ({ selectedMonth }: PlanPriceProps) => {
const [pharmacies, setPharmacies] = useState(FalkeDataPlanTour);
const currentDate = new Date();
const currentMonthKey = `${currentDate.getFullYear()}-${String(
currentDate.getMonth() + 1,
).padStart(2, "0")}`;
useEffect(() => {
setPharmacies((prev) =>
prev.map((pharmacy) => {
if (pharmacy.monthlyData[selectedMonth]) return pharmacy;
return {
...pharmacy,
monthlyData: {
...pharmacy.monthlyData,
[selectedMonth]: { amount: 0, locked: false },
},
};
}),
);
}, [selectedMonth]);
// Editing
const [editingId, setEditingId] = useState<number | null>(null);
const [tempAmount, setTempAmount] = useState<string>("");
const [displayPrice, setDisplayPrice] = useState("");
// === HELPERS ===
const formatCurrency = (amount: number): string =>
new Intl.NumberFormat("uz-UZ").format(amount) + " so'm";
const getMonthName = (monthKey: string): string => {
const months = [
"Yanvar",
"Fevral",
"Mart",
"Aprel",
"May",
"Iyun",
"Iyul",
"Avgust",
"Sentyabr",
"Oktyabr",
"Noyabr",
"Dekabr",
];
const [year, month] = monthKey.split("-");
return `${months[parseInt(month) - 1]} ${year}`;
};
const handleEdit = (pharmacyId: number) => {
const pharmacy = pharmacies.find((p) => p.id === pharmacyId);
const currentAmount = pharmacy?.monthlyData[selectedMonth]?.amount ?? 0;
setEditingId(pharmacyId);
setTempAmount(currentAmount.toString());
};
const handleSave = (pharmacyId: number) => {
const amount = parseInt(tempAmount) || 0;
setPharmacies((prev) =>
prev.map((pharmacy) =>
pharmacy.id === pharmacyId
? {
...pharmacy,
monthlyData: {
...pharmacy.monthlyData,
[selectedMonth]: {
amount,
locked: selectedMonth !== currentMonthKey,
},
},
}
: pharmacy,
),
);
setEditingId(null);
setTempAmount("");
};
const handleCancel = () => {
setEditingId(null);
setTempAmount("");
};
const isLocked = (pharmacy: Pharmacy): boolean =>
pharmacy.monthlyData[selectedMonth]?.locked === true ||
selectedMonth !== currentMonthKey;
const getTotalForMonth = (): number =>
pharmacies.reduce(
(total, pharmacy) =>
total + (pharmacy.monthlyData[selectedMonth]?.amount || 0),
0,
);
return (
<>
<Card className="mb-6 shadow-lg border-0 bg-gradient-to-r from-green-600 to-emerald-600 text-white">
<CardContent className="pt-6">
<div className="flex items-center justify-between">
<div>
<p className="text-green-100 mb-1">
Jami summa ({getMonthName(selectedMonth)})
</p>
<p className="text-3xl font-bold">
{formatCurrency(getTotalForMonth())}
</p>
</div>
<DollarSign className="h-16 w-16 opacity-20" />
</div>
</CardContent>
</Card>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{pharmacies.map((pharmacy) => {
const monthData = pharmacy.monthlyData[selectedMonth];
const amount = monthData?.amount || 0;
const locked = isLocked(pharmacy);
const isEditing = editingId === pharmacy.id;
return (
<Card
key={pharmacy.id}
className="shadow-lg hover:shadow-xl p-0 pb-4 transition-shadow border-0"
>
<CardHeader className="pt-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<CardTitle className="text-xl text-gray-900 mb-2">
{pharmacy.name}
</CardTitle>
<div className="space-y-1">
<div className="flex items-center text-sm text-gray-600">
<MapPin className="h-4 w-4 mr-2 text-blue-600" />
{pharmacy.district}
</div>
<div className="flex items-center text-sm text-gray-600">
<Building2 className="h-4 w-4 mr-2 text-blue-600" />
{pharmacy.address}
</div>
</div>
</div>
{locked && (
<span className="text-xs bg-red-100 text-red-700 px-3 py-1 rounded-full font-medium">
Bloklangan
</span>
)}
</div>
</CardHeader>
<CardContent className="pt-6">
<div className="space-y-4">
<div>
<label className="text-sm font-medium text-gray-700 mb-2 block">
Oylik summa
</label>
{isEditing ? (
<div className="space-y-3 flex flex-col">
<Input
type="text"
inputMode="numeric"
placeholder="1 500 000"
value={displayPrice}
onChange={(e) => {
const raw = e.target.value.replace(/\D/g, "");
const num = Number(raw);
if (!isNaN(num)) {
setTempAmount(String(num));
setDisplayPrice(raw ? formatPrice(num) : "");
}
}}
className="h-12 text-md"
/>
<div className="flex gap-2">
<Button
onClick={() => handleSave(pharmacy.id)}
className="flex-1 bg-green-600 hover:bg-green-700"
>
<Check className="h-4 w-4 mr-2" />
Saqlash
</Button>
<Button
onClick={handleCancel}
variant="outline"
className="flex-1"
>
<X className="h-4 w-4 mr-2" />
Bekor qilish
</Button>
</div>
</div>
) : (
<div className="flex flex-col gap-4 items-center rounded-lg">
<span className="text-2xl font-bold text-gray-900">
{formatPrice(amount, "uz" as LanguageRoutes, true)}
</span>
{!locked && (
<Button
onClick={() => {
handleEdit(pharmacy.id);
setTempAmount("");
setDisplayPrice("");
}}
size="sm"
className="bg-blue-600 w-full hover:bg-blue-700"
>
<Edit2 className="h-4 w-4 mr-2" />
{"O'zgartirish"}
</Button>
)}
</div>
)}
</div>
{locked && selectedMonth !== currentMonthKey && (
<Alert className="bg-amber-50 border-amber-200">
<AlertDescription className="text-amber-800 text-sm">
{"O'tgan oyning ma'lumotlarini o'zgartirib bo'lmaydi"}
</AlertDescription>
</Alert>
)}
</div>
</CardContent>
</Card>
);
})}
</div>
</>
);
};
export default PlanPrice;

View File

@@ -0,0 +1,107 @@
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui";
import { Calendar } from "lucide-react";
import { useEffect, useState } from "react";
import { FalkeDataPlanTour } from "../lib/mock";
import PlanPrice from "./PlanPrice";
const PlanTour = () => {
const [pharmacies, setPharmacies] = useState(FalkeDataPlanTour);
const currentDate = new Date();
const currentMonthKey = `${currentDate.getFullYear()}-${String(
currentDate.getMonth() + 1,
).padStart(2, "0")}`;
useEffect(() => {
setPharmacies((prev) =>
prev.map((pharmacy) => {
if (pharmacy.monthlyData[currentMonthKey]) return pharmacy;
return {
...pharmacy,
monthlyData: {
...pharmacy.monthlyData,
[currentMonthKey]: { amount: 0, locked: false },
},
};
}),
);
}, [currentMonthKey]);
const [selectedMonth, setSelectedMonth] = useState<string>(currentMonthKey);
const getMonthName = (monthKey: string): string => {
const months = [
"Yanvar",
"Fevral",
"Mart",
"Aprel",
"May",
"Iyun",
"Iyul",
"Avgust",
"Sentyabr",
"Oktyabr",
"Noyabr",
"Dekabr",
];
const [year, month] = monthKey.split("-");
return `${months[parseInt(month) - 1]} ${year}`;
};
const availableMonths = (): string[] => {
const months = new Set<string>();
pharmacies.forEach((p) => {
Object.keys(p.monthlyData).forEach((m) => months.add(m));
});
return Array.from(months).sort();
};
return (
<DashboardLayout>
<div>
<div className="max-w-7xl mx-auto">
<h1 className="text-4xl font-bold text-gray-900 mb-2">
Oylik hisobotlar
</h1>
<p className="text-gray-600">
Dorixonalar uchun oylik summalarni boshqaring
</p>
<Card className="mb-4 border-0 p-0 mt-5">
<CardHeader className="bg-blue-500 p-3 from-blue-600 to-indigo-600 text-white">
<CardTitle className="flex items-center gap-2 justify-center">
<Calendar className="h-5 w-5" />
Oy tanlash
</CardTitle>
</CardHeader>
<CardContent className="pb-6">
<div className="flex flex-wrap gap-3">
{availableMonths().map((month) => (
<Button
key={month}
onClick={() => setSelectedMonth(month)}
variant={selectedMonth === month ? "default" : "outline"}
className={`${
selectedMonth === month
? "bg-blue-600 hover:bg-blue-700 text-white"
: "hover:bg-blue-50"
}`}
>
{getMonthName(month)}
{month === currentMonthKey && (
<span className="ml-2 text-xs bg-green-500 text-white px-2 py-0.5 rounded-full">
Joriy
</span>
)}
</Button>
))}
</div>
</CardContent>
</Card>
<PlanPrice selectedMonth={selectedMonth} />
</div>
</div>
</DashboardLayout>
);
};
export default PlanTour;

View File

@@ -0,0 +1,33 @@
import type { CreatePlansReq, GetMyPlansRes } from "@/features/plan/lib/data";
import httpClient from "@/shared/config/api/httpClient";
import { PLANS } from "@/shared/config/api/URLs";
import type { AxiosResponse } from "axios";
export const plans_api = {
async createPlans(body: CreatePlansReq) {
const res = await httpClient.post(PLANS, body);
return res;
},
async edit({ body, id }: { id: number; body: CreatePlansReq }) {
const res = await httpClient.patch(`${PLANS}${id}/update/`, body);
return res;
},
async getMyPloans(params: {
date?: string;
}): Promise<AxiosResponse<GetMyPlansRes>> {
const res = await httpClient.get(PLANS, { params });
return res;
},
async planIsDone(id: number) {
const res = await httpClient.post(`${PLANS}${id}/complite/`);
return res;
},
async delete(id: number) {
const res = await httpClient.delete(`${PLANS}${id}/delete/`);
return res;
},
};

View File

@@ -0,0 +1,29 @@
export interface CreatePlansReq {
title: string;
description: string;
date: string; // '2025-11-26' shu kabi jonatish kera apiga
is_done: boolean;
}
export interface GetMyPlansRes {
status_code: number;
status: string;
message: string;
data: {
id: number;
title: string;
description: string;
date: string;
is_done: boolean;
created_at: string;
}[];
}
export interface Task {
id: number;
title: string;
description: string;
date: string;
is_done: boolean;
created_at: string;
}

View File

@@ -0,0 +1,13 @@
import type { Task } from "@/features/plan/lib/data";
export function groupByDate(tasks: Task[]) {
const groups: Record<string, Task[]> = {};
tasks.forEach((task) => {
const date = task.date; // "2025-12-01" kabi
if (!groups[date]) groups[date] = [];
groups[date].push(task);
});
return groups;
}

View File

@@ -0,0 +1,7 @@
import z from "zod";
export const plansForm = z.object({
title: z.string().min(1, { error: "Majburiy maydon" }),
description: z.string().min(1, { error: "Majburiy maydon" }),
date: z.string().optional(),
});

View File

@@ -0,0 +1,144 @@
import { Button } from "@/shared/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/shared/ui/dialog";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import clsx from "clsx";
import { format } from "date-fns";
import { toast } from "sonner";
import { plans_api } from "../lib/api";
interface Task {
id: number;
title: string;
description: string;
date: string;
is_done: boolean;
created_at: string;
}
interface PlanDetailsDialogProps {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
task: Task | null;
}
export function PlanDetailsDialog({
isOpen,
onOpenChange,
task,
}: PlanDetailsDialogProps) {
const queryClient = useQueryClient();
const { mutate, isPending } = useMutation({
mutationFn: (id: number) => plans_api.planIsDone(id),
onSuccess: () => {
toast.success("Rejangiz bajarildi bo'lib o'zgardi");
onOpenChange(false);
queryClient.refetchQueries({ queryKey: ["my_plans"] });
},
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;
}[];
};
toast.error(
data.message || errorData?.messages?.[0].message || "Xatolik yuz berdi",
);
},
});
if (!task) return null;
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent className="w-[95%] max-w-md">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">
{"Rejani ko'rish"}
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
{/* Status */}
<div className="flex items-center gap-2">
<div>
<p className="text-sm text-muted-foreground">Xolati</p>
<p
className={clsx(
"font-semibold",
task.is_done ? "text-green-500" : "text-foreground",
)}
>
{task.is_done ? "Tugallangan ✓" : "Bajarilmagan"}
</p>
</div>
</div>
{/* Title */}
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Sarlavha</p>
<p
className={clsx(
"text-lg font-semibold break-words",
task.is_done ? "text-green-500" : "text-foreground",
)}
>
{task.title}
</p>
</div>
{/* Description */}
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Tavsifi</p>
<p
className={clsx(
"text-base break-words leading-relaxed",
task.is_done ? "text-green-500" : "text-foreground",
)}
>
{task.description}
</p>
</div>
{/* Date */}
<div className="space-y-1">
<p className="text-sm text-muted-foreground">Sana</p>
<p className="text-base font-medium text-foreground">
{format(task.date, "dd.MM.yyyy")}
</p>
</div>
{/* Close Button */}
<div className="flex justify-end gap-2 pt-4">
<Button
onClick={() => {
mutate(task.id);
}}
disabled={task.is_done || isPending}
className="w-fit p-5 rounded-lg"
>
Bajarildi
</Button>
<Button
disabled={isPending}
onClick={() => onOpenChange(false)}
variant="outline"
className="p-5 rounded-lg"
>
Yopish
</Button>
</div>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,260 @@
"use client";
import type { CreatePlansReq } from "@/features/plan/lib/data";
import formatDate from "@/shared/lib/formatDate";
import AddedButton from "@/shared/ui/added-button";
import { Button } from "@/shared/ui/button";
import { Calendar } from "@/shared/ui/calendar";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/shared/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/shared/ui/form";
import { Input } from "@/shared/ui/input";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { format } from "date-fns";
import { CalendarIcon, Loader2 } from "lucide-react";
import { useEffect, useState, type Dispatch, type SetStateAction } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import z from "zod";
import { plans_api } from "../lib/api";
const plansForm = z.object({
title: z.string().min(1, "Sarlavha kiritish majburiy"),
description: z.string().min(1, "Tavsif kiritish majburiy"),
date: z.string().optional(),
});
interface Task {
id: number;
title: string;
description: string;
date: string;
is_done: boolean;
created_at: string;
}
interface Props {
isDialogOpen: boolean;
setIsDialogOpen: Dispatch<SetStateAction<boolean>>;
newTask: { title: string; description: string; date: Date };
setNewTask: Dispatch<
SetStateAction<{ title: string; description: string; date: Date }>
>;
taskEdit: Task | null;
setTaskEdit: Dispatch<SetStateAction<Task | null>>;
}
export const AddPlans = ({
isDialogOpen,
setIsDialogOpen,
newTask,
setNewTask,
setTaskEdit,
taskEdit,
}: Props) => {
const [isDateDialogOpen, setIsDateDialogOpen] = useState(false);
const queryClient = useQueryClient();
const form = useForm<z.infer<typeof plansForm>>({
resolver: zodResolver(plansForm),
defaultValues: {
title: "",
description: "",
date: formatDate.format(new Date(), "YYYY-MM-DD"),
},
});
const { mutate: added, isPending } = useMutation({
mutationFn: (body: CreatePlansReq) => plans_api.createPlans(body),
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ["my_plans"] });
form.reset();
setIsDialogOpen(false);
toast.success("Reja qo'shildi");
},
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;
}[];
};
toast.error(
data.message || errorData?.messages?.[0].message || "Xatolik yuz berdi",
);
},
});
const { mutate: edit, isPending: editPending } = useMutation({
mutationFn: ({ body, id }: { id: number; body: CreatePlansReq }) =>
plans_api.edit({ body, id }),
onSuccess: () => {
queryClient.refetchQueries({ queryKey: ["my_plans"] });
form.reset();
setIsDialogOpen(false);
toast.success("Reja tahrirlandi");
},
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;
}[];
};
toast.error(
data.message || errorData?.messages?.[0].message || "Xatolik yuz berdi",
);
},
});
useEffect(() => {
if (taskEdit) {
form.setValue("title", taskEdit.title);
form.setValue("description", taskEdit.description);
form.setValue("date", taskEdit.date);
}
}, [taskEdit]);
function onSubmit(values: z.infer<typeof plansForm>) {
if (taskEdit) {
edit({
body: {
title: values.title,
description: values.description,
date: formatDate.format(values.date!, "YYYY-MM-DD"),
is_done: taskEdit.is_done,
},
id: taskEdit.id,
});
} else {
added({
title: values.title,
description: values.description,
date: formatDate.format(values.date!, "YYYY-MM-DD"),
is_done: false,
});
}
}
return (
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<AddedButton onClick={() => setTaskEdit(null)} />
</DialogTrigger>
<DialogContent className="max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
{taskEdit ? "Vazifani tahrirlash" : "Yangi vazifa qoshish"}
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Sarlavha</FormLabel>
<FormControl>
<Input placeholder="Sarlavha" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Tavsif</FormLabel>
<FormControl>
<Input placeholder="Tavsif" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormItem>
<FormLabel>Sana</FormLabel>
<Dialog
open={isDateDialogOpen}
onOpenChange={setIsDateDialogOpen}
>
<DialogTrigger asChild>
<Button variant="outline" className="w-full justify-start">
<CalendarIcon className="mr-2 h-4 w-4" />
{newTask.date
? format(newTask.date, "dd-MM-yyyy")
: "Sanani tanlang"}
</Button>
</DialogTrigger>
<DialogContent className="w-auto p-4">
<Calendar
mode="single"
selected={newTask.date}
onSelect={(date) => {
if (date) {
setNewTask({ ...newTask, date });
form.setValue("date", date.toISOString());
}
}}
initialFocus
/>
<div className="mt-4 flex justify-end">
<Button onClick={() => setIsDateDialogOpen(false)}>
Tanlash
</Button>
</div>
</DialogContent>
</Dialog>
</FormItem>
<div className="flex flex-col gap-2">
<Button
type="button"
variant="outline"
disabled={isPending || editPending}
onClick={() => setIsDialogOpen(false)}
>
Bekor qilish
</Button>
<Button type="submit" disabled={isPending || editPending}>
{isPending || editPending ? (
<Loader2 className="animate-spin" />
) : taskEdit ? (
"Saqlash"
) : (
"Qoshish"
)}
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
);
};

View File

@@ -0,0 +1,299 @@
import { plans_api } from "@/features/plan/lib/api";
import type { Task } from "@/features/plan/lib/data";
import { groupByDate } from "@/features/plan/lib/filteDareHelper";
import { AddPlans } from "@/features/plan/ui/addPlans";
import { PlanDetailsDialog } from "@/features/plan/ui/PlanDetailsDialogProps";
import formatDate from "@/shared/lib/formatDate";
import { Alert, AlertDescription, AlertTitle } from "@/shared/ui/alert";
import { Button } from "@/shared/ui/button";
import { Calendar } from "@/shared/ui/calendar";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/shared/ui/dialog";
import { Skeleton } from "@/shared/ui/skeleton";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { AxiosError } from "axios";
import clsx from "clsx";
import {
CalendarIcon,
Loader2,
Pencil,
Trash,
TriangleAlert,
} from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
export default function Plans() {
const [taskEdit, setTaskEdit] = useState<Task | null>(null);
const queryClient = useQueryClient();
const [selectedDate, setSelectedDate] = useState<Date | null>(null);
const [tempDate, setTempDate] = useState<Date | null>(null);
const { data, isLoading, isError } = useQuery({
queryKey: ["my_plans", selectedDate],
queryFn: () =>
plans_api.getMyPloans({
date: selectedDate ? formatDate.format(selectedDate, "YYYY-MM-DD") : "",
}),
});
const { mutate, isPending } = useMutation({
mutationFn: (id: number) => plans_api.delete(id),
onSuccess: () => {
toast.success("Reja ochirildi");
queryClient.refetchQueries({ queryKey: ["my_plans", selectedDate] });
setDeleteDialogOpen(false);
},
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;
}[];
};
toast.error(
data.message || errorData?.messages?.[0].message || "Xatolik yuz berdi",
);
},
});
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [isPlanDetailsOpen, setIsPlanDetailsOpen] = useState(false);
const [isDateDialogOpen, setIsDateDialogOpen] = useState(false);
const [newTask, setNewTask] = useState({
title: "",
description: "",
date: new Date(),
});
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
const openTaskDetails = (task: Task) => {
setSelectedTask(task);
setIsPlanDetailsOpen(true);
};
const handleDeleteTask = (task: Task) => {
setSelectedTask(task);
setDeleteDialogOpen(true);
};
const grouped = groupByDate(data?.data.data || []);
return (
<DashboardLayout>
<div className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold text-foreground">Kunlik Reja</h1>
<Dialog open={isDateDialogOpen} onOpenChange={setIsDateDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" className="bg-transparent font-normal">
<CalendarIcon className="mr-2 h-4 w-4" />
{selectedDate
? formatDate.format(selectedDate, "dd.MM.yyyy")
: "Barchasi"}
</Button>
</DialogTrigger>
<DialogContent className="w-auto p-4">
<Calendar
mode="single"
selected={tempDate ?? selectedDate ?? undefined}
onSelect={(date) => setTempDate(date ?? null)}
initialFocus
/>
<div className="mt-4 flex justify-end gap-2">
<Button
variant="outline"
onClick={() => {
setIsDateDialogOpen(false);
setTempDate(null);
setSelectedDate(null);
}}
>
Bekor qilish
</Button>
<Button
onClick={() => {
if (tempDate) setSelectedDate(tempDate);
setIsDateDialogOpen(false);
}}
>
Tanlash
</Button>
</div>
</DialogContent>
</Dialog>
</div>
{isLoading && (
<div className="space-y-4">
{[1, 2, 3].map((i) => (
<Card key={i} className="px-0 py-3 gap-0">
<CardHeader className="px-3 py-0">
<Skeleton className="h-5 w-32" />
</CardHeader>
<CardContent className="space-y-3 px-2 py-0">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<div className="grid grid-cols-2 gap-2">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</div>
</CardContent>
</Card>
))}
</div>
)}
{isError && (
<Alert variant="destructive">
<TriangleAlert className="h-4 w-4" />
<AlertTitle>Xatolik!</AlertTitle>
<AlertDescription>
Ma'lumotlarni yuklashda muammo yuz berdi. Qayta urinib koring.
</AlertDescription>
</Alert>
)}
{!isLoading &&
!isError &&
data &&
Object.keys(grouped).length === 0 && (
<Alert className="mt-4">
<AlertTitle>Ma'lumot yoq</AlertTitle>
<AlertDescription>
Tanlangan sana boyicha reja topilmadi.
</AlertDescription>
</Alert>
)}
{data &&
Object.entries(grouped).map(([date, items]) => (
<Card key={date} className="px-0 py-3 gap-0">
<CardHeader className="px-3 py-0">
<CardTitle className="text-lg">
{formatDate.format(new Date(date), "DD.MM.YYYY")}
</CardTitle>
</CardHeader>
<CardContent className="space-y-2 px-2 py-0">
{items.map((item) => (
<div
key={item.id}
onClick={() => openTaskDetails(item)}
className="flex flex-col gap-3 p-3 rounded-md border bg-white group hover:bg-gray-50 transition-colors"
>
<div className="flex gap-3">
<div className="flex-1 flex flex-col">
<h3
className={clsx(
"font-semibold wrap-break-word",
item.is_done ? "text-green-500" : "text-foreground",
)}
>
{item.title}
</h3>
<p
className={clsx(
"text-sm wrap-break-word",
item.is_done
? "text-green-500"
: "text-muted-foreground",
)}
>
{item.description}
</p>
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<Button
size="sm"
variant="outline"
onClick={(e) => {
e.stopPropagation();
setTaskEdit(item);
setIsAddDialogOpen(true);
}}
className="p-4"
disabled={item.is_done}
>
<Pencil className="h-4 w-4" />
<p>Tahrirlash</p>
</Button>
<Button
size="sm"
variant="destructive"
onClick={(e) => {
e.stopPropagation();
handleDeleteTask(item);
}}
className="p-4"
disabled={item.is_done}
>
<Trash className="h-4 w-4" />
<p>{"O'chirish"}</p>
</Button>
</div>
</div>
))}
</CardContent>
</Card>
))}
<AddPlans
isDialogOpen={isAddDialogOpen}
setIsDialogOpen={setIsAddDialogOpen}
newTask={newTask}
setNewTask={setNewTask}
setTaskEdit={setTaskEdit}
taskEdit={taskEdit}
/>
<PlanDetailsDialog
isOpen={isPlanDetailsOpen}
onOpenChange={setIsPlanDetailsOpen}
task={selectedTask}
/>
<Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Rejani ochirish</DialogTitle>
</DialogHeader>
<p>
Siz haqiqatdan ham <strong>{selectedTask?.title}</strong> rejani
ochirmoqchimisiz?
</p>
<DialogFooter className="flex justify-end gap-2">
<Button
variant="outline"
onClick={() => setDeleteDialogOpen(false)}
>
Bekor qilish
</Button>
<Button
variant="destructive"
disabled={isPending}
onClick={() => selectedTask && mutate(selectedTask.id)}
>
{isPending ? <Loader2 className="animate-spin" /> : "O'chirish"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</DashboardLayout>
);
}

View File

@@ -0,0 +1,60 @@
import type { SpecificationHistory } from "@/features/specification/lib/mock";
import { formatPrice } from "@/shared/lib/formatPrice";
import type { ColumnDef } from "@tanstack/react-table";
export const specificationColumns: ColumnDef<SpecificationHistory>[] = [
{
accessorKey: "id",
header: () => <div className="text-center"></div>,
cell: ({ row }) => {
return <div className="text-center">{row.index + 1}</div>;
},
},
{
accessorKey: "date",
header: () => <div className="text-center">Sanasi</div>,
cell: ({ row }) => {
return <div className="text-center font-medium">{row.original.date}</div>;
},
},
{
accessorKey: "pharmacy",
header: () => <div className="text-center">Farmasevtika</div>,
cell: ({ row }) => {
return <div className="text-center">{row.original.pharmacy}</div>;
},
},
{
accessorKey: "totalAmount",
header: () => <div className="text-center">Hisoblangan narxi</div>,
cell: ({ row }) => {
return (
<div className="text-center">
{formatPrice(row.original.totalAmount)}
</div>
);
},
},
{
accessorKey: "paymentPercentage",
header: () => <div className="text-center">{"To'langan foizi"}</div>,
cell: ({ row }) => {
return (
<div className="text-center">
{formatPrice(row.original.paymentPercentage)}%
</div>
);
},
},
{
accessorKey: "paymentAmount",
header: () => <div className="text-center">{"To'langan narxi"}</div>,
cell: ({ row }) => {
return (
<div className="text-center">
{formatPrice(row.original.paymentAmount)}
</div>
);
},
},
];

View File

@@ -0,0 +1,61 @@
// Types
export interface MedicineItem {
id: number;
name: string;
price: number;
quantity: number;
total: number;
}
export interface SpecificationHistory {
id: string;
date: string;
buyerName: string;
pharmacy: string;
paymentPercentage: number;
medicines: MedicineItem[];
totalAmount: number;
paymentAmount: number;
}
export const SAMPLE_HISTORY: SpecificationHistory[] = [
{
id: "1",
date: "2024-11-15 14:30",
buyerName: "Abdullayev Aziz",
pharmacy: "Farmaciya #1",
paymentPercentage: 100,
medicines: [
{ id: 1, name: "Aspirin", price: 3500, quantity: 2, total: 7000 },
{ id: 2, name: "Paracetamol", price: 5500, quantity: 3, total: 16500 },
],
totalAmount: 23500,
paymentAmount: 23500,
},
{
id: "2",
date: "2024-11-14 10:15",
buyerName: "Karimova Malika",
pharmacy: "Farmaciya #2",
paymentPercentage: 50,
medicines: [
{ id: 3, name: "Ibuprofen", price: 10000, quantity: 1, total: 10000 },
{ id: 4, name: "Amoxicillin", price: 15000, quantity: 2, total: 30000 },
{ id: 5, name: "Metformin", price: 20000, quantity: 1, total: 20000 },
],
totalAmount: 60000,
paymentAmount: 30000,
},
{
id: "3",
date: "2024-11-13 16:45",
buyerName: "Tursunov Bobur",
pharmacy: "Farmaciya #3",
paymentPercentage: 75,
medicines: [
{ id: 6, name: "Lisinopril", price: 8500, quantity: 4, total: 34000 },
],
totalAmount: 34000,
paymentAmount: 25500,
},
];

View File

@@ -0,0 +1,199 @@
"use client";
import formatDate from "@/shared/lib/formatDate";
import { formatPrice } from "@/shared/lib/formatPrice";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui";
import { Building2, Calendar, User } from "lucide-react";
import { useParams } from "react-router-dom";
interface MedicineItem {
id: number;
name: string;
price: number;
quantity: number;
total: number;
}
interface SpecificationHistory {
id: string;
date: string;
buyerName: string;
pharmacy: string;
priceType: "regular" | "special";
paymentPercentage: number;
medicines: MedicineItem[];
totalAmount: number;
paymentAmount: number;
}
// Sample data
const SAMPLE_HISTORY: SpecificationHistory[] = [
{
id: "1",
date: "2024-11-15 14:30",
buyerName: "Abdullayev Aziz",
pharmacy: "Farmaciya #1",
priceType: "special",
paymentPercentage: 100,
medicines: [
{ id: 1, name: "Aspirin", price: 3500, quantity: 2, total: 7000 },
{ id: 2, name: "Paracetamol", price: 5500, quantity: 3, total: 16500 },
],
totalAmount: 23500,
paymentAmount: 23500,
},
{
id: "2",
date: "2024-11-14 10:15",
buyerName: "Karimova Malika",
pharmacy: "Farmaciya #2",
priceType: "regular",
paymentPercentage: 50,
medicines: [
{ id: 3, name: "Ibuprofen", price: 10000, quantity: 1, total: 10000 },
{ id: 4, name: "Amoxicillin", price: 15000, quantity: 2, total: 30000 },
{ id: 5, name: "Metformin", price: 20000, quantity: 1, total: 20000 },
],
totalAmount: 60000,
paymentAmount: 30000,
},
{
id: "3",
date: "2024-11-13 16:45",
buyerName: "Tursunov Bobur",
pharmacy: "Farmaciya #3",
priceType: "special",
paymentPercentage: 75,
medicines: [
{ id: 6, name: "Lisinopril", price: 8500, quantity: 4, total: 34000 },
],
totalAmount: 34000,
paymentAmount: 25500,
},
];
export function DetailViewPage() {
const { id } = useParams();
const item = SAMPLE_HISTORY.find((h) => h.id === id);
if (!item) return <div>{"Ma'lumot topilmadi"}</div>;
return (
<DashboardLayout>
<div className="min-h-screen bg-gray-50">
<div className="max-w-5xl mx-auto">
<div className="bg-white rounded-lg shadow-lg overflow-hidden">
{/* Header */}
<div className="bg-blue-500 from-blue-600 to-blue-700 p-6 text-white">
<h1 className="text-2xl font-bold mb-2">Buyurtma Tafsilotlari</h1>
<p className="text-blue-100">ID: {item.id}</p>
</div>
{/* Info Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 p-6 bg-gray-50">
<div className="bg-white p-4 rounded-lg shadow-sm">
<div className="flex items-center gap-3 mb-2">
<Calendar className="text-blue-600" size={20} />
<span className="text-sm text-gray-600">Sana</span>
</div>
<p className="font-semibold text-gray-900">
{formatDate.format(item.date, "DD-MM-YYYY")}
</p>
</div>
<div className="bg-white p-4 rounded-lg shadow-sm">
<div className="flex items-center gap-3 mb-2">
<User className="text-green-600" size={20} />
<span className="text-sm text-gray-600">Xaridor ismi</span>
</div>
<p className="font-semibold text-gray-900">{item.buyerName}</p>
</div>
<div className="bg-white p-4 rounded-lg shadow-sm">
<div className="flex items-center gap-3 mb-2">
<Building2 className="text-purple-600" size={20} />
<span className="text-sm text-gray-600">
Farmasevtikaga tegishli
</span>
</div>
<p className="font-semibold text-gray-900">{item.pharmacy}</p>
</div>
</div>
{/* Medicines Table */}
<div className="p-6">
<h2 className="text-xl font-bold text-gray-900 mb-4">Dorilar</h2>
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-100 border-b-2 border-gray-200">
<tr>
<th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
Dori nomi
</th>
<th className="px-4 py-3 text-right text-sm font-semibold text-gray-700">
Narxi
</th>
<th className="px-4 py-3 text-right text-sm font-semibold text-gray-700">
Soni
</th>
<th className="px-4 py-3 text-right text-sm font-semibold text-gray-700">
Jami
</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-200">
{item.medicines.map((medicine) => (
<tr key={medicine.id} className="hover:bg-gray-50">
<td className="px-4 py-3 text-sm text-gray-900 font-medium">
{medicine.name}
</td>
<td className="px-4 py-3 text-sm text-gray-700 text-right">
{formatPrice(medicine.price)}
</td>
<td className="px-4 py-3 text-sm text-gray-700 text-right">
{medicine.quantity}
</td>
<td className="px-4 py-3 text-sm text-gray-900 font-semibold text-right">
{formatPrice(medicine.total)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Summary */}
<div className="bg-gray-50 p-6 border-t">
<div className="max-w-md ml-auto space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-700">Jami summa:</span>
<span className="text-xl font-bold text-gray-900">
{formatPrice(item.totalAmount)}
</span>
</div>
<div className="flex justify-between items-center pt-3 border-t-2 border-gray-200">
<span className="text-gray-700">
{"To'langan"} ({item.paymentPercentage}%):
</span>
<span className="text-2xl font-bold text-green-600">
{formatPrice(item.paymentAmount)}
</span>
</div>
{item.paymentPercentage < 100 && (
<div className="flex justify-between items-center text-sm pt-2">
<span className="text-gray-600">Qoldiq:</span>
<span className="font-semibold text-red-600">
{formatPrice(item.totalAmount - item.paymentAmount)}
</span>
</div>
)}
</div>
</div>
</div>
</div>
</div>
</DashboardLayout>
);
}

View File

@@ -0,0 +1,108 @@
"use client";
import { formatPrice } from "@/shared/lib/formatPrice";
import AddedButton from "@/shared/ui/added-button";
import { Button } from "@/shared/ui/button";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui";
import { Eye } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { SAMPLE_HISTORY } from "../lib/mock";
export function HistoryListPage() {
const router = useNavigate();
return (
<DashboardLayout>
<div className="min-h-screen bg-gray-50">
<div className="max-w-5xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-3xl font-bold text-gray-900">
Buyurtmalar Tarixi
</h1>
<p className="text-gray-600 mt-1">
{"Barcha buyurtmalar ro'yxati"}
</p>
</div>
<AddedButton onClick={() => router("/specification/added")} />
</div>
<div className="space-y-4">
{SAMPLE_HISTORY.length > 0 ? (
SAMPLE_HISTORY.map((item) => (
<div
key={item.id}
className="bg-white border rounded-xl p-5 shadow-sm hover:shadow-md transition"
>
<div className="flex justify-between items-start">
<div>
<p className="text-lg font-semibold text-gray-900">
Buyurtma {item.id}
</p>
<p className="text-sm text-gray-500 mt-1">
Sana: {item.date}
</p>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4">
<div>
<p className="text-gray-500 text-sm">Mijoz</p>
<p className="font-medium">{item.buyerName}</p>
</div>
<div>
<p className="text-gray-500 text-sm">Farmasevtika</p>
<p className="font-medium">{item.pharmacy}</p>
</div>
<div>
<p className="text-gray-500 text-sm">Hisoblangan narxi</p>
<p className="font-medium">
{formatPrice(item.totalAmount)}
</p>
</div>
<div>
<p className="text-gray-500 text-sm">
{"To'langan foizi"}
</p>
<p className="font-medium">{item.paymentPercentage}%</p>
</div>
<div>
<p className="text-gray-500 text-sm">
{"To'langan narxi"}
</p>
<p className="font-medium">
{formatPrice(item.paymentAmount)}
</p>
</div>
</div>
{/* KORISH BUTTON */}
<div className="flex justify-end mt-4">
<Button
onClick={() =>
router(`/specification/history/${item.id}`)
}
className="px-4 py-2 w-full h-12 rounded-lg bg-blue-600 text-white text-sm hover:bg-blue-700 transition"
>
<Eye className="size-5" />
Batafsil
</Button>
</div>
</div>
))
) : (
<p className="text-center text-gray-500 py-10">
{"Hozircha ma'lumot yoq."}
</p>
)}
</div>
</div>
</div>
</DashboardLayout>
);
}

View File

@@ -0,0 +1,57 @@
"use client";
import { LanguageRoutes } from "@/shared/config/i18n/types";
import { formatPrice } from "@/shared/lib/formatPrice";
import { Input } from "@/shared/ui/input";
import { useParams } from "react-router-dom";
interface Medicine {
id: number;
name: string;
regularPrice: number;
specialPrice: number;
quantity: number;
}
interface MedicineRowProps {
medicine: Medicine;
onQuantityChange: (id: number, quantity: number) => void;
}
export function MedicineRow({ medicine, onQuantityChange }: MedicineRowProps) {
const { locale } = useParams();
const total = medicine.regularPrice * medicine.quantity;
const handleQuantityChange = (value: string) => {
const numValue = parseInt(value, 10) || 0;
onQuantityChange(medicine.id, numValue);
};
return (
<div className="flex flex-col p-3 bg-card border border-border rounded-lg hover:bg-accent/50 transition">
<div className="flex items-center justify-between">
<div className="flex-1">
<p className="font-medium text-foreground">{medicine.name}</p>
<p className="text-sm text-muted-foreground">
Narxi:{" "}
{formatPrice(medicine.regularPrice, locale as LanguageRoutes, true)}
</p>
</div>
<div className="flex flex-col items-center gap-2">
<Input
type="text"
min="0"
value={medicine.quantity}
onChange={(e) => handleQuantityChange(e.target.value)}
className="w-20 text-center"
placeholder="0"
/>
</div>
</div>
<span className="text-sm font-semibold text-foreground w-[80px] text-right mt-2">
{formatPrice(total, locale as LanguageRoutes, true)}
</span>
</div>
);
}

View File

@@ -0,0 +1,31 @@
"use client";
import { Button } from "@/shared/ui/button";
interface PaymentPercentageProps {
paymentPercentage: number;
setPaymentPercentage: (percentage: number) => void;
}
export function PaymentPercentage({
paymentPercentage,
setPaymentPercentage,
}: PaymentPercentageProps) {
const percentages = [20, 30, 50, 100];
return (
<div className="grid grid-cols-4 gap-2">
{percentages.map((percentage) => (
<Button
key={percentage}
variant={paymentPercentage === percentage ? "default" : "outline"}
onClick={() => setPaymentPercentage(percentage)}
size="sm"
className="text-sm h-12"
>
{percentage}%
</Button>
))}
</div>
);
}

View File

@@ -0,0 +1,32 @@
"use client";
import { Button } from "@/shared/ui/button";
interface PriceTypeSelectorProps {
priceType: "regular" | "special";
setPriceType: (type: "regular" | "special") => void;
}
export function PriceTypeSelector({
priceType,
setPriceType,
}: PriceTypeSelectorProps) {
return (
<div className="flex gap-2">
<Button
variant={priceType === "regular" ? "default" : "outline"}
onClick={() => setPriceType("regular")}
className="flex-1"
>
Oddiy Narx
</Button>
<Button
variant={priceType === "special" ? "default" : "outline"}
onClick={() => setPriceType("special")}
className="flex-1"
>
Maxsus Narx
</Button>
</div>
);
}

View File

@@ -0,0 +1,216 @@
"use client";
import type { LanguageRoutes } from "@/shared/config/i18n/types";
import { formatPrice } from "@/shared/lib/formatPrice";
import { Button } from "@/shared/ui/button";
import { Card } from "@/shared/ui/card";
import { Input } from "@/shared/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/ui/select";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui";
import { useState } from "react";
import { MedicineRow } from "./MedicineRow";
import { PaymentPercentage } from "./PaymentPercentageProps";
// Sample medicines data
const MEDICINES_DATA = [
{ id: 1, name: "Aspirin", regularPrice: 5000, specialPrice: 3500 },
{ id: 2, name: "Paracetamol", regularPrice: 8000, specialPrice: 5500 },
{ id: 3, name: "Ibuprofen", regularPrice: 10000, specialPrice: 7000 },
{ id: 4, name: "Amoxicillin", regularPrice: 15000, specialPrice: 10500 },
{ id: 5, name: "Metformin", regularPrice: 20000, specialPrice: 14000 },
{ id: 6, name: "Lisinopril", regularPrice: 12000, specialPrice: 8500 },
];
const PHARMACIES = [
"Farmasevtika #1",
"Farmasevtika #2",
"Farmasevtika #3",
"Farmasevtika #4",
];
interface MedicineItem {
id: number;
name: string;
regularPrice: number;
specialPrice: number;
quantity: number;
}
export function SpecificationPage() {
const [medicines, setMedicines] = useState<MedicineItem[]>(
MEDICINES_DATA.map((m) => ({ ...m, quantity: 0 })),
);
const [selectedPharmacy, setSelectedPharmacy] = useState(PHARMACIES[0]);
const [buyerName, setBuyerName] = useState("");
const [paymentPercentage, setPaymentPercentage] = useState(100);
const handleQuantityChange = (id: number, newQuantity: number) => {
setMedicines(
medicines.map((m) =>
m.id === id ? { ...m, quantity: Math.max(0, newQuantity) } : m,
),
);
};
const getPrice = (medicine: MedicineItem) => {
return medicine.regularPrice;
};
const calculateTotal = () => {
return medicines.reduce((sum, medicine) => {
return sum + getPrice(medicine) * medicine.quantity;
}, 0);
};
const calculatePaymentAmount = () => {
const total = calculateTotal();
return Math.round(total * (paymentPercentage / 100));
};
const handleDownloadPDF = () => {
const selectedMedicines = medicines.filter((m) => m.quantity > 0);
const data = {
buyerName,
pharmacy: selectedPharmacy,
paymentPercentage,
medicines: selectedMedicines.map((m) => ({
id: m.id,
name: m.name,
price: getPrice(m),
quantity: m.quantity,
total: getPrice(m) * m.quantity,
})),
totalAmount: calculateTotal(),
paymentAmount: calculatePaymentAmount(),
};
console.log("PDF Data:", data);
};
const hasSelectedMedicines = medicines.some((m) => m.quantity > 0);
return (
<DashboardLayout>
<div className="min-h-screen">
<div className="max-w-6xl mx-auto">
<h1 className="text-4xl font-bold text-foreground">
Dorilar Boshqaruvi
</h1>
<p className="text-muted-foreground mb-5">
{"Dorilar ro'yxatini tuzib, buyutma yarating"}
</p>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-2">
<div>
<Card className="p-4 shadow-sm">
<h2 className="text-2xl font-semibold text-foreground">
Dorilar
</h2>
<div className="space-y-3">
{medicines.map((medicine) => (
<MedicineRow
key={medicine.id}
medicine={medicine}
onQuantityChange={handleQuantityChange}
/>
))}
</div>
</Card>
</div>
<div className="space-y-2">
<Card className="p-3 shadow-sm gap-2">
<h3 className="font-semibold text-foreground">Farmasevtika</h3>
<Select
value={selectedPharmacy}
onValueChange={setSelectedPharmacy}
>
<SelectTrigger className="w-full h-12">
<SelectValue />
</SelectTrigger>
<SelectContent>
{PHARMACIES.map((pharmacy) => (
<SelectItem key={pharmacy} value={pharmacy}>
{pharmacy}
</SelectItem>
))}
</SelectContent>
</Select>
</Card>
{/* Buyer name */}
<Card className="p-3 shadow-sm gap-2">
<h3 className="font-semibold text-foreground">Xaridor Nomi</h3>
<Input
placeholder="Nomi kiriting..."
value={buyerName}
className="h-12"
onChange={(e) => setBuyerName(e.target.value)}
/>
</Card>
{/* Payment percentage */}
<Card className="p-3 shadow-sm gap-2">
<h3 className="font-semibold text-foreground">
{"To'lov foizi"}
</h3>
<PaymentPercentage
paymentPercentage={paymentPercentage}
setPaymentPercentage={setPaymentPercentage}
/>
</Card>
{/* Summary */}
{hasSelectedMedicines && (
<Card className="p-3 shadow-lg bg-primary text-primary-foreground gap-4">
<h3 className="font-semibold">Xulosa</h3>
<div className="space-y-3">
<div className="flex justify-between">
<span>Jami:</span>
<span className="font-bold">
{formatPrice(
calculateTotal(),
"uz" as LanguageRoutes,
true,
)}
</span>
</div>
<div className="border-t border-primary-foreground/30 pt-3 flex justify-between">
<span>
{"To'lanadi"} ({paymentPercentage}%):
</span>
<span className="font-bold text-lg">
{formatPrice(
calculatePaymentAmount(),
"uz" as LanguageRoutes,
true,
)}
</span>
</div>
</div>
</Card>
)}
{/* Download button */}
{hasSelectedMedicines && (
<Button
onClick={handleDownloadPDF}
className="w-full h-14 text-md bg-green-600 hover:bg-green-700 text-white"
size="lg"
>
PDF ga yuklab olish
</Button>
)}
</div>
</div>
</div>
</div>
</DashboardLayout>
);
}

View File

@@ -0,0 +1,9 @@
import httpClient from "@/shared/config/api/httpClient";
import { TOUR_PLAN } from "@/shared/config/api/URLs";
export const tour_plan_api = {
async list() {
const res = await httpClient.get(TOUR_PLAN);
return res;
},
};

View File

@@ -0,0 +1,46 @@
"use client";
import type { TourItem } from "@/features/tour-plan/lib/types";
import formatDate from "@/shared/lib/formatDate";
import type { ColumnDef } from "@tanstack/react-table";
import { Send } from "lucide-react";
export const getColumns = ({
sendLocation,
canSend,
}: {
sendLocation: (tour: TourItem) => void;
canSend: (date: string) => boolean;
}): ColumnDef<TourItem>[] => [
{
accessorKey: "date",
header: "Sana",
cell: ({ row }) => (
<div className="text-center">
{formatDate.format(new Date(row.original.date), "DD")}
</div>
),
},
{
accessorKey: "district",
header: "Tuman",
},
{
id: "actions",
header: "Lokatsiya jo'natish",
cell: ({ row }) => {
const tour = row.original;
return (
<div className="flex gap-3 items-center justify-center">
<Send
className={`cursor-pointer ${
canSend(tour.date) ? "text-green-600" : "text-gray-400"
}`}
onClick={() => canSend(tour.date) && sendLocation(tour)}
/>
</div>
);
},
},
];

View File

@@ -0,0 +1,77 @@
"use client";
import type { TourItem } from "@/features/tour-plan/lib/types";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/shared/ui/table";
import {
flexRender,
getCoreRowModel,
useReactTable,
type ColumnDef,
} from "@tanstack/react-table";
interface DataTableProps<TourItem> {
columns: ColumnDef<TourItem>[];
data: TourItem[];
}
export function DataTable({ columns, data }: DataTableProps<TourItem>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="overflow-hidden rounded-md border">
<Table className="">
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} className="border-r text-center">
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext(),
)}
</TableHead>
);
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="border-r">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}

View File

@@ -0,0 +1,11 @@
export interface TourItem {
id: number;
date: string;
district: string;
}
export const mockTourData: TourItem[] = [
{ id: 1, date: "2025-11-01", district: "Yunusobod tumani" },
{ id: 2, date: "2025-11-15", district: "Mirzo Ulug'bek tumani" },
{ id: 3, date: "2025-11-20", district: "Chilonzor tumani" },
];

View File

@@ -0,0 +1,138 @@
"use client";
import type { TourItem } from "@/features/tour-plan/lib/types";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/shared/ui/select";
import { DashboardLayout } from "@/widgets/dashboard-layout/ui";
import dynamic from "next/dynamic";
import { useMemo, useState } from "react";
import { getColumns } from "../lib/column";
const DataTable = dynamic(
() => import("../lib/data-table").then((mod) => mod.DataTable),
{ ssr: false },
);
const mockTourData: TourItem[] = [
{
id: 1,
date: "2025-11-01",
district: "Yunusobod tumani",
},
{
id: 2,
date: "2025-11-15",
district: "Mirzo Ulug'bek tumani",
},
{
id: 3,
date: "2025-11-20",
district: "Chilonzor tumani",
},
];
export default function TourPlan() {
const currentYear = new Date().getFullYear().toString();
const currentMonth = (new Date().getMonth() + 1).toString().padStart(2, "0");
const [year, setYear] = useState(currentYear);
const [month, setMonth] = useState(currentMonth);
const sendLocation = () => {
navigator.geolocation.getCurrentPosition(
(pos) => {
console.log("📌 Lokatsiya olindi:");
console.log("Latitude:", pos.coords.latitude);
console.log("Longitude:", pos.coords.longitude);
},
(err) => {
console.error("Lokatsiya olishda xatolik:", err);
},
{
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 0,
},
);
};
const canSend = (date: string) => {
return new Date(date) >= new Date();
};
const columnsProps = getColumns({
sendLocation: sendLocation,
canSend: canSend,
});
const filteredData = useMemo(() => {
return mockTourData.filter((item) => {
const d = new Date(item.date);
const itemYear = d.getFullYear().toString();
const itemMonth = (d.getMonth() + 1).toString().padStart(2, "0");
const yearMatch = year ? itemYear === year : true;
const monthMatch = month ? itemMonth === month : true;
return yearMatch && monthMatch;
});
}, [year, month]);
return (
<DashboardLayout>
<div className="space-y-6">
<h1 className="text-3xl font-bold">Tur Plan</h1>
{/* 🔹 FILTER UI */}
<div className="flex gap-2 justify-end items-end">
<Select onValueChange={(e) => setYear(e)} value={year}>
<SelectTrigger className="w-fit !h-10">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="2025">2025</SelectItem>
<SelectItem value="2024">2024</SelectItem>
<SelectItem value="2023">2023</SelectItem>
<SelectItem value="2022">2022</SelectItem>
<SelectItem value="2021">2021</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
<Select onValueChange={(e) => setMonth(e)} value={month}>
<SelectTrigger className="w-fit !h-10">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="01">Yanvar</SelectItem>
<SelectItem value="02">Fevral</SelectItem>
<SelectItem value="03">Mart</SelectItem>
<SelectItem value="04">Aprel</SelectItem>
<SelectItem value="05">May</SelectItem>
<SelectItem value="06">Iyun</SelectItem>
<SelectItem value="07">Iyul</SelectItem>
<SelectItem value="08">Avgust</SelectItem>
<SelectItem value="09">Sentabr</SelectItem>
<SelectItem value="10">Oktabr</SelectItem>
<SelectItem value="11">Noyabr</SelectItem>
<SelectItem value="12">Dekabr</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
<div className="overflow-x-auto">
<DataTable columns={columnsProps} data={filteredData} />
</div>
</div>
</DashboardLayout>
);
}

13
src/global.d.ts vendored Normal file
View File

@@ -0,0 +1,13 @@
interface Window {
Telegram?: {
WebApp?: {
initDataUnsafe?: {
user?: {
id: number;
first_name: string;
last_name?: string;
};
};
};
};
}

View File

@@ -1,113 +1,122 @@
@import 'tailwindcss'; @import "tailwindcss";
@import 'tw-animate-css'; @import "tw-animate-css";
@custom-variant dark (&:is(.dark *)); @custom-variant dark (&:is(.dark *));
@theme inline { @theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-inter), system-ui, sans-serif;
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px); --radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px); --radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius); --radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px); --radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
} }
/* Soft Blue, White, and Gray Color Palette */
:root { :root {
--radius: 0.625rem; --radius: 0.75rem;
--background: oklch(1 0 0); /* Accent gradient for buttons and active states */
--foreground: oklch(0.145 0 0); --accent-gradient: linear-gradient(135deg, #58a6ff 0%, #7bd0ff 100%);
--accent-gradient-2: linear-gradient(
90deg,
rgba(88, 166, 255, 0.12) 0%,
rgba(123, 208, 255, 0.06) 100%
);
--background: oklch(0.99 0 0);
--foreground: oklch(0.2 0.01 250);
--card: oklch(1 0 0); --card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0); --card-foreground: oklch(0.2 0.01 250);
--popover: oklch(1 0 0); --popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0); --popover-foreground: oklch(0.2 0.01 250);
--primary: oklch(0.205 0 0); --primary: oklch(55% 0.15 240);
--primary-foreground: oklch(0.985 0 0); --primary-foreground: oklch(1 0 0);
--secondary: oklch(0.97 0 0); --secondary: oklch(0.96 0.005 250);
--secondary-foreground: oklch(0.205 0 0); --secondary-foreground: oklch(0.25 0.01 250);
--muted: oklch(0.97 0 0); --muted: oklch(0.95 0.005 250);
--muted-foreground: oklch(0.556 0 0); --muted-foreground: oklch(0.5 0.01 250);
--accent: oklch(0.97 0 0); --accent: oklch(0.94 0.02 240);
--accent-foreground: oklch(0.205 0 0); --accent-foreground: oklch(0.25 0.01 250);
--destructive: oklch(0.577 0.245 27.325); --destructive: oklch(0.6 0.22 25);
--border: oklch(0.922 0 0); --border: oklch(0.9 0.01 250);
--input: oklch(0.922 0 0); --input: oklch(0.93 0.01 250);
--ring: oklch(0.708 0 0); --ring: oklch(55% 0.15 240);
--chart-1: oklch(0.646 0.222 41.116); --chart-1: oklch(55% 0.15 240);
--chart-2: oklch(0.6 0.118 184.704); --chart-2: oklch(60% 0.12 220);
--chart-3: oklch(0.398 0.07 227.392); --chart-3: oklch(50% 0.1 260);
--chart-4: oklch(0.828 0.189 84.429); --chart-4: oklch(65% 0.14 200);
--chart-5: oklch(0.769 0.188 70.08); --chart-5: oklch(58% 0.13 230);
--sidebar: oklch(0.985 0 0); --sidebar: oklch(0.98 0.005 250);
--sidebar-foreground: oklch(0.145 0 0); --sidebar-foreground: oklch(0.25 0.01 250);
--sidebar-primary: oklch(0.205 0 0); --sidebar-primary: oklch(55% 0.15 240);
--sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-primary-foreground: oklch(1 0 0);
--sidebar-accent: oklch(0.97 0 0); --sidebar-accent: oklch(0.94 0.02 240);
--sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-accent-foreground: oklch(0.25 0.01 250);
--sidebar-border: oklch(0.922 0 0); --sidebar-border: oklch(0.9 0.01 250);
--sidebar-ring: oklch(0.708 0 0); --sidebar-ring: oklch(55% 0.15 240);
} }
.dark { .dark {
--background: oklch(0.145 0 0); --background: oklch(0.15 0.01 250);
--foreground: oklch(0.985 0 0); --foreground: oklch(0.95 0.005 250);
--card: oklch(0.205 0 0); --card: oklch(0.2 0.01 250);
--card-foreground: oklch(0.985 0 0); --card-foreground: oklch(0.95 0.005 250);
--popover: oklch(0.205 0 0); --popover: oklch(0.2 0.01 250);
--popover-foreground: oklch(0.985 0 0); --popover-foreground: oklch(0.95 0.005 250);
--primary: oklch(0.922 0 0); --primary: oklch(60% 0.18 240);
--primary-foreground: oklch(0.205 0 0); --primary-foreground: oklch(0.15 0.01 250);
--secondary: oklch(0.269 0 0); --secondary: oklch(0.25 0.01 250);
--secondary-foreground: oklch(0.985 0 0); --secondary-foreground: oklch(0.95 0.005 250);
--muted: oklch(0.269 0 0); --muted: oklch(0.25 0.01 250);
--muted-foreground: oklch(0.708 0 0); --muted-foreground: oklch(0.65 0.01 250);
--accent: oklch(0.269 0 0); --accent: oklch(0.3 0.015 240);
--accent-foreground: oklch(0.985 0 0); --accent-foreground: oklch(0.95 0.005 250);
--destructive: oklch(0.704 0.191 22.216); --destructive: oklch(0.65 0.25 25);
--border: oklch(1 0 0 / 10%); --border: oklch(0.3 0.01 250);
--input: oklch(1 0 0 / 15%); --input: oklch(0.25 0.01 250);
--ring: oklch(0.556 0 0); --ring: oklch(60% 0.18 240);
--chart-1: oklch(0.488 0.243 264.376); --chart-1: oklch(60% 0.18 240);
--chart-2: oklch(0.696 0.17 162.48); --chart-2: oklch(65% 0.15 220);
--chart-3: oklch(0.769 0.188 70.08); --chart-3: oklch(55% 0.12 260);
--chart-4: oklch(0.627 0.265 303.9); --chart-4: oklch(70% 0.16 200);
--chart-5: oklch(0.645 0.246 16.439); --chart-5: oklch(63% 0.14 230);
--sidebar: oklch(0.205 0 0); --sidebar: oklch(0.18 0.01 250);
--sidebar-foreground: oklch(0.985 0 0); --sidebar-foreground: oklch(0.95 0.005 250);
--sidebar-primary: oklch(0.488 0.243 264.376); --sidebar-primary: oklch(60% 0.18 240);
--sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-primary-foreground: oklch(0.15 0.01 250);
--sidebar-accent: oklch(0.269 0 0); --sidebar-accent: oklch(0.3 0.015 240);
--sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-accent-foreground: oklch(0.95 0.005 250);
--sidebar-border: oklch(1 0 0 / 10%); --sidebar-border: oklch(0.3 0.01 250);
--sidebar-ring: oklch(0.556 0 0); --sidebar-ring: oklch(60% 0.18 240);
} }
@layer base { @layer base {
@@ -118,3 +127,22 @@
@apply bg-background text-foreground; @apply bg-background text-foreground;
} }
} }
@layer components {
.custom-container {
@apply container px-4 mx-auto;
}
/* Gradient accent utilities */
.bg-accent-gradient {
background: var(--accent-gradient);
}
.bg-accent-gradient-soft {
background: var(--accent-gradient-2);
}
.rounded-xl-soft {
border-radius: calc(var(--radius) + 6px);
}
}

View File

@@ -1,5 +0,0 @@
import Welcome from "@/widgets/welcome/ui/welcome";
export function Home() {
return <Welcome />;
}

View File

@@ -0,0 +1,3 @@
export default function Page() {
return null;
}

View File

@@ -0,0 +1,10 @@
import District from "@/features/district/ui/district";
import TokenLayout from "@/token-layaout";
export default function DistrictPage() {
return (
<TokenLayout>
<District />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import MyLocation from "@/features/location/ui/MyLocation";
import TokenLayout from "@/token-layaout";
export default function Location() {
return (
<TokenLayout>
<MyLocation />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import CreateObject from "@/features/object/ui/CreateObject";
import TokenLayout from "@/token-layaout";
export default function ObjectAdded() {
return (
<TokenLayout>
<CreateObject />
</TokenLayout>
);
}

View File

@@ -0,0 +1,5 @@
import CreateObject from "@/features/object/ui/CreateObject";
export default function Page() {
return <CreateObject />;
}

View File

@@ -0,0 +1,13 @@
import ObjectMapPage from "@/features/object/ui/ObjectMap";
import TokenLayout from "@/token-layaout";
import { Suspense } from "react";
export default function ObjectLocation() {
return (
<Suspense>
<TokenLayout>
<ObjectMapPage />
</TokenLayout>
</Suspense>
);
}

10
src/pages/object/page.tsx Normal file
View File

@@ -0,0 +1,10 @@
import ObjectList from "@/features/object/ui/ObjectList";
import TokenLayout from "@/token-layaout";
export default function Object() {
return (
<TokenLayout>
<ObjectList />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import CreatePharmacy from "@/features/phamarcy/ui/CreatePharmacy";
import TokenLayout from "@/token-layaout";
export default function Page() {
return (
<TokenLayout>
<CreatePharmacy />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import CreatePharmacy from "@/features/phamarcy/ui/CreatePharmacy";
import TokenLayout from "@/token-layaout";
export default function PharmacyAdded() {
return (
<TokenLayout>
<CreatePharmacy />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import PharmacyList from "@/features/phamarcy/ui/PharmacyList";
import TokenLayout from "@/token-layaout";
export default function Pharmacy() {
return (
<TokenLayout>
<PharmacyList />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import CreateDoctor from "@/features/doctor/ui/CreateDoctor";
import TokenLayout from "@/token-layaout";
export default function PhysicianAdded() {
return (
<TokenLayout>
<CreateDoctor />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import DoctorDetail from "@/features/doctor/ui/DetailDoctor";
import TokenLayout from "@/token-layaout";
export default function PhysicianDetail() {
return (
<TokenLayout>
<DoctorDetail />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import CreateDoctor from "@/features/doctor/ui/CreateDoctor";
import TokenLayout from "@/token-layaout";
export default function PhysicianEdit() {
return (
<TokenLayout>
<CreateDoctor />
</TokenLayout>
);
}

View File

@@ -0,0 +1,10 @@
import Doctor from "@/features/doctor/ui/Doctor";
import TokenLayout from "@/token-layaout";
export default function Physician() {
return (
<TokenLayout>
<Doctor />
</TokenLayout>
);
}

10
src/pages/plan/page.tsx Normal file
View File

@@ -0,0 +1,10 @@
import Plans from "@/features/plan/ui/plans";
import TokenLayout from "@/token-layaout";
export default function Plan() {
return (
<TokenLayout>
<Plans />
</TokenLayout>
);
}

View File

@@ -0,0 +1,7 @@
import { SpecificationPage } from "@/features/specification/ui/Specification";
const SpecificationAdded = () => {
return <SpecificationPage />;
};
export default SpecificationAdded;

View File

@@ -0,0 +1,7 @@
import { DetailViewPage } from "@/features/specification/ui/DetailViewPage";
const SpecificationDetail = () => {
return <DetailViewPage />;
};
export default SpecificationDetail;

View File

@@ -0,0 +1,5 @@
import { HistoryListPage } from "@/features/specification/ui/HistoryListPage";
export default function Specification() {
return <HistoryListPage />;
}

View File

@@ -0,0 +1,7 @@
import TourPlan from "@/features/tour-plan/ui/TourPlan";
export const TourPlanPage = () => {
return <TourPlan />;
};
export default TourPlanPage;

View File

@@ -0,0 +1,5 @@
import PlanTour from "@/features/plan-tour/ui/PlanTour";
export const TypePlan = () => {
return <PlanTour />;
};

View File

@@ -1,4 +1,22 @@
import { Home } from "@/pages/Home"; import Home from "@/features/home/ui/Home";
import DistrictPage from "@/pages/district/page";
import Location from "@/pages/location/page";
import ObjectAdded from "@/pages/object/added/page";
import ObjectLocation from "@/pages/object/location/page";
import Object from "@/pages/object/page";
import PharmacyAdded from "@/pages/pharmacy/edit/[id]/page";
import Pharmacy from "@/pages/pharmacy/page";
import PhysicianAdded from "@/pages/physician/added/page";
import PhysicianDetail from "@/pages/physician/detail/[id]/page";
import PhysicianEdit from "@/pages/physician/edit/[id]/page";
import Physician from "@/pages/physician/page";
import Plan from "@/pages/plan/page";
import SpecificationAdded from "@/pages/specification/added/page";
import SpecificationDetail from "@/pages/specification/history/[id]/page";
import Specification from "@/pages/specification/page";
import TourPlanPage from "@/pages/tour-plan/page";
import { TypePlan } from "@/pages/type-plan/page";
import TokenLayout from "@/token-layaout";
import { Outlet, type RouteObject } from "react-router-dom"; import { Outlet, type RouteObject } from "react-router-dom";
const routesConfig: RouteObject = { const routesConfig: RouteObject = {
@@ -8,7 +26,147 @@ const routesConfig: RouteObject = {
children: [ children: [
{ {
path: "/", path: "/",
element: <Home />, element: (
<TokenLayout>
<Home />
</TokenLayout>
),
},
],
},
{
children: [
{
path: "/plan",
element: <Plan />,
},
],
},
{
children: [
{
path: "/location",
element: <Location />,
},
],
},
{
children: [
{
path: "/specification",
element: <Specification />,
},
],
},
{
children: [
{
path: "/specification/added",
element: <SpecificationAdded />,
},
],
},
{
children: [
{
path: "/specification/history/:id",
element: <SpecificationDetail />,
},
],
},
{
children: [
{
path: "/tour-plan",
element: <TourPlanPage />,
},
],
},
{
children: [
{
path: "/district",
element: <DistrictPage />,
},
],
},
{
children: [
{
path: "/object",
element: <Object />,
},
],
},
{
children: [
{
path: "/object/added",
element: <ObjectAdded />,
},
],
},
{
children: [
{
path: "/object/location",
element: <ObjectLocation />,
},
],
},
{
children: [
{
path: "/physician",
element: <Physician />,
},
],
},
{
children: [
{
path: "/physician/added",
element: <PhysicianAdded />,
},
],
},
{
children: [
{
path: "/physician/edit/:id",
element: <PhysicianEdit />,
},
],
},
{
children: [
{
path: "/physician/detail/:id",
element: <PhysicianDetail />,
},
],
},
{
children: [
{
path: "/pharmacy",
element: <Pharmacy />,
},
],
},
{
children: [
{
path: "/pharmacy/added",
element: <PharmacyAdded />,
},
],
},
{
children: [
{
path: "/type-plan",
element: <TypePlan />,
}, },
], ],
}, },

Some files were not shown because too many files have changed in this diff Show More