feat: add files

This commit is contained in:
2025-04-09 02:01:23 +05:30
commit c1623969c7
129 changed files with 28223 additions and 0 deletions

41
.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
registry=https://reg.thewired.agency/

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM node:21-alpine
WORKDIR /usr/src/app
EXPOSE 3000
COPY package*.json ./
RUN npm install --force
COPY . .
RUN npm run build
RUN ls
CMD ["npm", "run", "start"]

36
README.md Normal file
View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

4
captain-definition Normal file
View File

@@ -0,0 +1,4 @@
{
"schemaVersion":2,
"dockerfilePath":"./Dockerfile"
}

21
components.json Normal file
View File

@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

25
eslint.config.mjs Normal file
View File

@@ -0,0 +1,25 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
rules: {
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-explicit-any": "off",
"react-hooks/rules-of-hooks": "off",
"@typescript-eslint/ban-ts-comment": "off",
"react/no-unescaped-entities": "off",
},
},
];
export default eslintConfig;

7
next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

11283
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

77
package.json Normal file
View File

@@ -0,0 +1,77 @@
{
"name": "inventory-management-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev ",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@anujs.dev/inventory-types-utils": "^1.0.1",
"@autoform/react": "^3.0.0",
"@hookform/resolvers": "^3.10.0",
"@radix-ui/react-accordion": "^1.2.2",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-dialog": "^1.1.6",
"@radix-ui/react-focus-scope": "^1.1.2",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-popover": "^1.1.6",
"@radix-ui/react-popper": "^1.2.2",
"@radix-ui/react-radio-group": "^1.2.2",
"@radix-ui/react-scroll-area": "^1.2.3",
"@radix-ui/react-select": "^2.1.6",
"@radix-ui/react-separator": "^1.1.2",
"@radix-ui/react-slider": "^1.2.3",
"@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-switch": "^1.1.3",
"@radix-ui/react-tabs": "^1.1.3",
"@radix-ui/react-toast": "^1.2.5",
"@radix-ui/react-toggle": "^1.1.2",
"@radix-ui/react-toggle-group": "^1.1.2",
"@radix-ui/react-tooltip": "^1.1.8",
"@tanstack/react-query": "^5.64.2",
"@tanstack/react-table": "^8.20.6",
"axios": "^1.7.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^4.1.0",
"jose": "^5.9.6",
"lucide-react": "^0.474.0",
"next": "^15.2.4",
"react": "^19.0.0",
"react-day-picker": "^8.10.1",
"react-dom": "^19.0.0",
"react-highlight-words": "^0.21.0",
"react-hook-form": "^7.54.2",
"recharts": "^2.15.1",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.24.2"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/jest": "^29.5.14",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/react-highlight-words": "^0.20.0",
"cz-conventional-changelog": "^3.3.0",
"cz-jira-smart-commit": "^3.0.0",
"eslint": "^9",
"eslint-config-next": "15.1.6",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"typescript": "^5"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"overrides": {
"@radix-ui/react-focus-scope": "^1.1.2"
}
}

8
postcss.config.mjs Normal file
View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

BIN
public/ekam.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

1
public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,224 @@
"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import {
BookCheck,
ChefHat,
FileIcon,
LayoutDashboard,
LogOut,
MenuIcon,
Package,
PersonStanding,
ShoppingCart,
User,
} from "lucide-react";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarSeparator,
useSidebar,
} from "@/components/ui/sidebar";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import client from "@/lib/client";
import { logoutFromServer } from "@/app/logout";
export function AdminSidebar() {
const sidebar = useSidebar();
const router = useRouter();
const pathname = usePathname();
const [open, setOpen] = useState(false);
const [activeItem, setActiveItem] = useState("/d/admin/dashboard");
const [sidebarOpen, setSidebarOpen] = useState(false);
useEffect(() => {
if (pathname) {
setActiveItem(pathname);
}
}, [pathname]);
const { mutate: logout } = useMutation({
mutationFn: async () => {
const { data } = await client.post("auth/logout");
return data;
},
onSuccess: () => {
router.push("/");
logoutFromServer();
},
});
const menuCategories = [
{
label: "Overview",
items: [
{
title: "Dashboard",
url: "/d/admin/dashboard",
icon: LayoutDashboard,
},
],
},
{
label: "Orders",
items: [
{
title: "Pending Orders",
url: "/d/admin/orders",
icon: Package,
},
{
title: "Current Orders",
url: "/d/admin/orders/current",
icon: Package,
},
],
},
{
label: "Inventory",
items: [
{
title: "Menu Items",
url: "/d/admin/menu",
icon: MenuIcon,
},
{
title: "Inventory",
url: "/d/admin/inventory",
icon: ShoppingCart,
},
{
title: "Kitchen Transfers",
url: "/d/admin/kitchen-transfers",
icon: FileIcon,
},
],
},
{
label: "Management",
items: [
{
title: "Kitchens",
url: "/d/admin/kitchens",
icon: ChefHat,
},
{
title: "Vendors",
url: "/d/admin/vendors",
icon: PersonStanding,
},
{
title: "Users",
url: "/d/admin/users",
icon: User,
},
{
title: "Logs",
url: "/d/admin/logs",
icon: BookCheck,
},
],
},
];
return (
<Sidebar className="bg-[#272f6f] text-white">
<SidebarHeader className="p-4 bg-white">
<img src="/ekam.png" alt="Ekam Logo" className="h- mx-auto" />
</SidebarHeader>
<SidebarContent className="px-2 py-4">
{menuCategories.map((category, index) => (
<SidebarGroup key={category.label} className="mb-4">
<SidebarGroupLabel className="text-indigo-300 text-xs font-medium px-3 mb-1 uppercase tracking-wider">
{category.label}
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{category.items.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
asChild
className={`${
activeItem === item.url
? "bg-indigo-800 text-white font-medium border-l-2 border-yellow-400"
: "hover:bg-indigo-800 hover:text-white"
}`}
onClick={() => {
setActiveItem(item.url);
sidebar.setOpenMobile(false);
}}
>
<Link href={item.url} className="flex items-center">
<item.icon
className={`h-4 w-4 mr-2 ${
activeItem === item.url
? "text-yellow-400"
: "text-indigo-200"
}`}
/>
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
{index < menuCategories.length - 1 && (
<SidebarSeparator className="my-2 bg-indigo-800" />
)}
</SidebarGroup>
))}
</SidebarContent>
<SidebarFooter className="mt-auto border-t border-indigo-900 p-4">
<SidebarMenu>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<SidebarMenuItem>
<SidebarMenuButton className="text-yellow-400 hover:bg-indigo-800 hover:text-yellow-300">
<LogOut className="h-4 w-4 mr-2" />
<span>Logout</span>
</SidebarMenuButton>
</SidebarMenuItem>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure you want to logout?</DialogTitle>
</DialogHeader>
<div className="flex items-center justify-end gap-5 mt-4">
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
className="bg-indigo-600 hover:bg-indigo-700 text-white"
onClick={() => logout()}
>
Logout
</Button>
</div>
</DialogContent>
</Dialog>
</SidebarMenu>
</SidebarFooter>
</Sidebar>
);
}

View File

@@ -0,0 +1,107 @@
import SortingButton from "@/components/sorting-button";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
export const columns: ColumnDef<any>[] = [
{
header({ column }) {
return <SortingButton column={column}>Transferred On</SortingButton>;
},
accessorKey: "timestamp",
cell: ({ row }) => {
return (
<span>
{format(new Date(row.original.timestamp), "dd MMM yyyy - HH:mm")}
</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Name</SortingButton>;
},
accessorKey: "inventoryName",
cell: ({ row }) => {
return (
<span>
{row.original.details.inventory?.name ||
row.original.details.metadata.inventory?.name}
</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Quantity</SortingButton>;
},
accessorKey: "quantity",
cell: ({ row }) => {
console.log(row.original);
if (row.original.source === "log") {
return (
<span>
{row.original.details.metadata.inventory.quantity}{" "}
{row.original.details.metadata.inventory.unit}
</span>
);
}
return (
<span>
{row.original.details.quantity} {row.original.details.inventory.unit}
</span>
);
},
},
{
header: "From",
accessorKey: "from",
cell: ({ row }) => {
return (
<span>
{row.original.details.fromKitchen?.name ||
row.original.details.metadata?.from ||
"Unknown"}
</span>
);
},
},
{
header: "To",
accessorKey: "to",
cell: ({ row }) => {
return (
<span>
{row.original.details.toKitchen?.name ||
row.original.details.metadata?.to ||
"Unknown"}
</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>User</SortingButton>;
},
accessorKey: "user",
cell: ({ row }) => {
if (row.original.source === "tanstack-query") {
return (
<span>
{row.original.details.user?.name} |{" "}
{row.original.details.user?.email}
</span>
);
} else {
return <span>Admin</span>;
}
},
},
{
header: "Reason",
accessorKey: "reason",
cell: ({ row }) => {
return <span>{row.original.details.reason || "No reason provided"}</span>;
},
},
];

View File

@@ -0,0 +1,377 @@
"use client";
import { DataTable } from "@/components/data-table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import client from "@/lib/client";
import { Order } from "@anujs.dev/inventory-types-utils";
import { useQueries, useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import { useMemo, useState } from "react";
import {
Bar,
BarChart,
Legend,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { columns as transferColumns } from "./columns";
export default function AdminPage() {
const [chartType, setChartType] = useState<"bar" | "line">("line");
const orderStatsQuery = useQuery({
queryKey: ["admin", "order-stats"],
queryFn: async () => {
const { data } = await client.get("/order/all-stats");
return data;
},
});
const orderStatsChartData = useMemo(() => {
if (!orderStatsQuery.data) return [];
return Object.entries(orderStatsQuery.data).map(([status, count]) => ({
status,
count,
}));
}, [orderStatsQuery.data]);
const [transfersQuery, logsQuery] = useQueries({
queries: [
{
queryKey: ["all", "transfers"],
queryFn: async () => {
const { data } = await client.get("kitchen-inventory/transfers/all");
return data;
},
},
{
queryKey: ["transfers", "logs"],
queryFn: async () => {
const { data } = await client.get("logs/inventory-transfers");
return data;
},
},
],
});
const ordersQuery = useQuery<Order[]>({
queryKey: ["admin", "all-orders"],
queryFn: async () => {
const { data } = await client.get("/order");
return data;
},
});
const inventoryQuery = useQuery({
queryKey: ["kitchen-inventory", "all"],
queryFn: async () => {
const { data } = await client.get("/kitchen-inventory");
return data;
},
});
function refetch() {
transfersQuery.refetch();
logsQuery.refetch();
ordersQuery.refetch();
inventoryQuery.refetch();
}
const isLoading =
transfersQuery.isLoading ||
logsQuery.isLoading ||
ordersQuery.isLoading ||
inventoryQuery.isLoading;
const combinedTransfers = useMemo(() => {
if (!transfersQuery.data || !logsQuery.data) return [];
const formattedTransfers = transfersQuery.data.map((entry: any) => ({
timestamp: entry.created_at,
source: "system",
details: entry,
}));
const formattedLogs = logsQuery.data.map((entry: any) => ({
timestamp: entry.timestamp,
source: "log",
details: entry,
}));
return [...formattedTransfers, ...formattedLogs].sort(
(a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
);
}, [transfersQuery.data, logsQuery.data]);
const generalInventoryData = useMemo(() => {
const grouped: Record<string, number> = {};
inventoryQuery.data?.forEach((entry: any) => {
const name = entry.inventory.name;
grouped[name] = (grouped[name] || 0) + Number(entry.stock);
});
return Object.entries(grouped).map(([name, quantity]) => ({
name,
quantity: Number(quantity.toFixed(2)),
}));
}, [inventoryQuery.data]);
const inventoryByKitchen = useMemo(() => {
const kitchens: Record<string, Record<string, number>> = {};
inventoryQuery.data?.forEach((entry: any) => {
const kitchenName = entry.kitchen.name;
const inventoryName = entry.inventory.name;
if (!kitchens[kitchenName]) kitchens[kitchenName] = {};
kitchens[kitchenName][inventoryName] =
(kitchens[kitchenName][inventoryName] || 0) + Number(entry.stock);
});
const allInventoryItems = Array.from(
new Set(inventoryQuery.data?.map((e: any) => e.inventory.name))
);
return allInventoryItems.map((itemName) => {
const obj: any = { name: itemName };
Object.entries(kitchens).forEach(([kitchen, items]) => {
// @ts-ignore
obj[kitchen] = Number((items[itemName] || 0).toFixed(2));
});
return obj;
});
}, [inventoryQuery.data]);
if (isLoading) return <div className="p-6">Loading dashboard...</div>;
return (
<div className="p-6 max-w-7xl mx-auto space-y-10">
<div>
<h1 className="text-2xl font-bold mb-1 text-emerald-800">
📊 Admin Dashboard
</h1>
<p className="text-muted-foreground text-sm">
View transfers, inventory and orders in one place.
</p>
</div>
<div className="flex items-center justify-between mb-2">
<h2 className="text-lg font-semibold text-emerald-700">
📈 Inventory Charts
</h2>
<ToggleGroup
type="single"
value={chartType}
onValueChange={(val) => val && setChartType(val as "bar" | "line")}
className="gap-2"
>
<ToggleGroupItem
value="line"
className="data-[state=on]:bg-[#031274] data-[state=on]:text-white"
>
Line
</ToggleGroupItem>
<ToggleGroupItem
value="bar"
className="data-[state=on]:bg-[#031274] data-[state=on]:text-white"
>
Bar
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-white border border-gray-100 p-4 rounded-md shadow-sm">
<h3 className="font-semibold mb-3 text-sm text-amber-700">
📦 Total Inventory
</h3>
<ResponsiveContainer width="100%" height={300}>
{chartType === "line" ? (
<LineChart data={generalInventoryData}>
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Line
type="monotone"
dataKey="quantity"
stroke="#059669"
strokeWidth={2}
dot={{ r: 3 }}
/>
</LineChart>
) : (
<BarChart data={generalInventoryData}>
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Bar dataKey="quantity" fill="#059669" />
</BarChart>
)}
</ResponsiveContainer>
</div>
<div className="bg-white border border-gray-100 p-4 rounded-md shadow-sm">
<h3 className="font-semibold mb-3 text-sm text-amber-700">
🏪 Inventory by Kitchen
</h3>
<ResponsiveContainer width="100%" height={300}>
{chartType === "line" ? (
<LineChart data={inventoryByKitchen}>
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
{Object.keys(inventoryByKitchen[0] ?? {})
.filter((key) => key !== "name")
.map((kitchen, index) => (
<Line
key={kitchen}
type="monotone"
dataKey={kitchen}
strokeWidth={2}
stroke={
["#059669", "#0d9488", "#0891b2", "#0284c7", "#d97706"][
index % 5
]
}
dot={{ r: 2 }}
/>
))}
</LineChart>
) : (
<BarChart data={inventoryByKitchen}>
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
{Object.keys(inventoryByKitchen[0] ?? {})
.filter((key) => key !== "name")
.map((kitchen, index) => (
<Bar
key={kitchen}
dataKey={kitchen}
fill={
["#059669", "#0d9488", "#0891b2", "#0284c7", "#d97706"][
index % 5
]
}
/>
))}
</BarChart>
)}
</ResponsiveContainer>
</div>
</div>
<div className="space-y-2">
<h2 className="text-lg font-semibold text-emerald-700">
Kitchen Inventory Transfers
</h2>
<div className="bg-white border border-gray-100 rounded-md shadow-sm overflow-hidden">
<DataTable
// @ts-ignore
columns={transferColumns}
data={combinedTransfers}
// @ts-ignore
refetch={refetch}
/>
</div>
</div>
<div className="space-y-4">
<h2 className="text-lg font-semibold text-emerald-700 pt-2">
All Orders
</h2>
{orderStatsQuery.data && (
<div className="grid grid-cols-2 md:grid-cols-6 gap-4">
{Object.entries(orderStatsQuery.data).map(([status, count]) => {
const statusColors: Record<string, string> = {
PENDING: "text-amber-600",
ACCEPTED: "text-blue-600",
PREPARING: "text-indigo-600",
COMPLETED: "text-emerald-600",
CANCELLED: "text-red-600",
DELIVERED: "text-emerald-700",
};
const bgColors: Record<string, string> = {
PENDING: "bg-amber-50 border-amber-200",
ACCEPTED: "bg-blue-50 border-blue-200",
PREPARING: "bg-indigo-50 border-indigo-200",
COMPLETED: "bg-emerald-50 border-emerald-200",
CANCELLED: "bg-red-50 border-red-200",
DELIVERED: "bg-emerald-50 border-emerald-200",
};
const label = status.charAt(0) + status.slice(1).toLowerCase();
return (
<Card
key={status}
className={`shadow-sm border ${bgColors[status]}`}
>
<CardHeader className="pb-2">
<CardTitle
className={`text-sm font-medium ${statusColors[status]}`}
>
{label}
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{count as string}</div>
<p className="text-xs text-muted-foreground">orders</p>
</CardContent>
</Card>
);
})}
</div>
)}
<div className="grid gap-3">
{ordersQuery.data?.map((order) => (
<div
key={order.id}
className="border border-gray-100 rounded-lg p-4 bg-white shadow-sm hover:border-emerald-200 transition-colors"
>
<div className="flex justify-between items-center">
<div>
<p className="text-sm font-medium text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</p>
<p className="text-xs text-muted-foreground">
Placed by: {order.user.name} |{" "}
{order.foodType.toLowerCase()}
</p>
</div>
<span
className={`text-xs px-2 py-1 rounded-full ${
order.status === "COMPLETED"
? "bg-emerald-100 text-emerald-700"
: order.status === "CANCELLED"
? "bg-red-100 text-red-700"
: order.status === "PENDING"
? "bg-amber-100 text-amber-700"
: "bg-blue-100 text-blue-700"
}`}
>
{order.status}
</span>
</div>
{order.kitchen && (
<p className="text-xs text-muted-foreground mt-1">
Kitchen: {order.kitchen.name}
</p>
)}
<p className="text-xs text-muted-foreground mt-1">
Last updated: {format(new Date(order.updated_at), "PPpp")}
</p>
</div>
))}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,353 @@
import { ConfirmAction } from "@/components/confirm-action";
import SortingButton from "@/components/sorting-button";
import AutoForm from "@/components/ui/auto-form";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Slider } from "@/components/ui/slider";
import { toast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { Inventory, Kitchen } from "@anujs.dev/inventory-types-utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery } from "@tanstack/react-query";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import {
Circle,
CircleCheckBig,
Edit2Icon,
RefreshCcw,
Trash2,
} from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
const assignTokitchenForm = z.object({
kitchenId: z.string().uuid(),
inventoryId: z.string().uuid(),
quantity: z.coerce.number().positive(),
unit: z.string(),
});
const updateInventoryDto = z.object({
name: z.string(),
stock: z.coerce.number(),
});
type AssignToKitchenSchema = z.infer<typeof assignTokitchenForm>;
type UpdateInventorySchema = z.infer<typeof updateInventoryDto>;
export const columns: ColumnDef<Inventory>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
},
{
header({ column }) {
return <SortingButton column={column}>Last Updated</SortingButton>;
},
accessorKey: "updated_at",
cell: ({ row, column }) => {
return (
<span>{format(row.original.created_at, "dd MMM yyyy HH:mm")}</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Name</SortingButton>;
},
accessorKey: "name",
},
{
header({ column }) {
return <SortingButton column={column}>In Stock</SortingButton>;
},
accessorKey: "stock",
},
{
header: "Unit",
accessorKey: "unit",
},
{
header: "Actions",
cell: ({ row, table }) => {
const [open, setOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const form = useForm<AssignToKitchenSchema>({
resolver: zodResolver(assignTokitchenForm),
defaultValues: {
inventoryId: row.original.id,
kitchenId: "",
quantity: 0,
unit: row.original.unit,
},
});
console.log(row.original.unit);
const updateForm = useForm<UpdateInventorySchema>({
resolver: zodResolver(updateInventoryDto),
values: {
name: row.original.name,
stock: row.original.stock,
},
});
const {
data: kitchens,
isLoading,
refetch,
} = useQuery({
queryKey: ["kitchens"],
queryFn: async () => {
const { data } = await client.get("user/kitchens");
return data;
},
refetchOnWindowFocus: false,
refetchInterval: false,
});
const [selected, setSelected] = useState<string | null>(null);
const { mutate: transferToKitchen } = useMutation({
mutationFn: async (values: AssignToKitchenSchema) => {
const { data } = await client.post("kitchen-inventory/add", values);
return data;
},
onSuccess: () => {
setOpen(false);
toast({
title: "Transfer Complete",
description: `${row.original.name} has been transferred to kitchen`,
});
refetch();
// @ts-expect-error sent to the main table
table.options.meta.refetch();
form.setValue("quantity", 0);
form.setValue("kitchenId", "");
setSelected("");
},
});
function onSubmit(data: AssignToKitchenSchema) {
transferToKitchen(data);
}
const { mutate: deleteInventory } = useMutation({
mutationFn: async ({ name }: { name: string }) => {
const { data } = await client.delete(`im/inventory/${name}`);
return data;
},
onSuccess: () => {
toast({
title: "Deleted successfully",
});
// @ts-expect-error sent to the main table
table.options.meta.refetch();
},
});
const { mutate: updateInventory } = useMutation({
mutationFn: async (values: UpdateInventorySchema) => {
const { data } = await client.put(
`im/inventory/${row.original.id}`,
values
);
return data;
},
onSuccess: () => {
toast({
title: "Inventory Item Updated",
});
setEditOpen(false);
// @ts-ignore
table.options.meta.refetch();
},
});
if (isLoading)
return (
<Button size={"icon"}>
<RefreshCcw></RefreshCcw>
</Button>
);
return (
<div className="justify-center items-center flex gap-5">
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant={"outline"}>Assign to kitchen</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Assign {row.original.name} to kitchen</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField
control={form.control}
name="kitchenId"
render={({ field }) => (
<FormItem>
<FormLabel>Select Kitchen</FormLabel>
<FormControl className="">
<div className="grid grid-cols-2 gap-4">
{kitchens?.map((kitchen: Kitchen) => (
<div
key={kitchen.id}
className={`rounded border p-2 flex flex-col`}
onClick={() => {
field.onChange(kitchen.id);
setSelected(kitchen.id);
}}
>
<div className="flex justify-between items-center">
<p className="text-sm font-medium">
{kitchen.name}
</p>
{selected !== kitchen.id ? (
<Circle size={16} />
) : (
<CircleCheckBig
size={16}
className="text-green-700"
/>
)}
</div>
<div className="text-sm pt-3">
Current Stock:{" "}
{kitchen.kitchenInventory.filter(
() =>
// @ts-expect-error it does exist but cannot be assigned on the type
x.inventory.name === row.original.name
)[0]?.stock ?? 0}{" "}
{row.original.unit}
</div>
</div>
))}
</div>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
)}
></FormField>
<FormField
control={form.control}
name="quantity"
render={({ field }) => (
<FormItem>
<FormLabel>
Quantity
<span className="px-3 text-green-500">
(Current Quantity: {row.original.stock})
</span>
</FormLabel>
<FormControl className="w-full">
<div className="w-full gap-5 flex items-center">
<Slider
className="w-[70%]"
min={0}
max={row.original.stock}
step={1}
onValueChange={(value) => {
field.onChange(value[0]);
}}
value={[field.value]}
></Slider>
<Input
className={"w-32"}
type="number"
value={field.value}
onChange={field.onChange}
max={row.original.stock}
></Input>
<p>{row.original.unit}</p>
</div>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
)}
></FormField>
<Button
type="submit"
disabled={!form.formState.isValid}
className="w-full"
>
Transfer
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
<Dialog open={editOpen} onOpenChange={setEditOpen}>
<DialogTrigger asChild>
<Button variant={"outline"} size="icon">
<Edit2Icon />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit ${row.original.name}</DialogTitle>
</DialogHeader>
<AutoForm
values={{
name: row.original.name,
stock: row.original.stock,
// @ts-expect-error correct type is passed
unit: row.original.unit,
}}
onSubmit={(values) => {
updateInventory(values);
}}
formSchema={updateInventoryDto}
>
<Button className={"w-full"}>Save</Button>
</AutoForm>
</DialogContent>
</Dialog>
<ConfirmAction
onOpenChange={setDeleteOpen}
open={deleteOpen}
onConfirm={() => {
deleteInventory({ name: row.original.name });
}}
>
<Button variant={"destructive"} size={"icon"}>
<Trash2 />
</Button>
</ConfirmAction>
</div>
);
},
},
];

View File

@@ -0,0 +1,469 @@
"use client";
import {
type ColumnDef,
type ColumnFiltersState,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
type SortingState,
useReactTable,
} from "@tanstack/react-table";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Slider } from "@/components/ui/slider";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { useToast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { zodResolver } from "@hookform/resolvers/zod";
import type { QueryObserverResult, RefetchOptions } from "@tanstack/query-core";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
ChevronLeft,
ChevronRight,
Circle,
CircleCheckBig,
Search,
MoveIcon as TransferIcon,
} from "lucide-react";
import React, { useState } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { z } from "zod";
import { Kitchen } from "@anujs.dev/inventory-types-utils";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
refetch: (
options?: RefetchOptions | undefined
) => Promise<QueryObserverResult<any, Error>>;
columnVisibility?: Record<string, boolean>;
}
const InventoryTransferSchema = z.object({
inventoryId: z.string().uuid({ message: "Invalid inventory ID format" }),
quantity: z
.number()
.positive({ message: "Quantity must be greater than zero" }),
unit: z.string().min(1, { message: "Unit is required" }),
});
export const AddMultipleInventoriesToKitchenSchema = z.object({
kitchenId: z.string().uuid({ message: "Invalid kitchen ID format" }),
inventories: z
.array(InventoryTransferSchema)
.min(1, { message: "At least one inventory item is required" }),
});
export type AddMultipleInventoriesToKitchenDto = z.infer<
typeof AddMultipleInventoriesToKitchenSchema
>;
export function DataTableSelection<TData, TValue>({
columns,
data,
refetch,
columnVisibility = {},
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
);
const [rowSelection, setRowSelection] = React.useState({});
const mergedColumnVisibility = {
id: false,
userType: false,
...columnVisibility,
};
const table = useReactTable({
initialState: {
columnVisibility: mergedColumnVisibility,
},
meta: {
refetch,
},
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onRowSelectionChange: setRowSelection,
onColumnFiltersChange: setColumnFilters,
state: {
sorting,
rowSelection,
columnFilters,
},
});
const form = useForm<AddMultipleInventoriesToKitchenDto>({
resolver: zodResolver(AddMultipleInventoriesToKitchenSchema),
defaultValues: {
inventories: [],
kitchenId: "",
},
});
const { fields, append, update, remove } = useFieldArray({
control: form.control,
name: "inventories",
});
const { data: kitchens } = useQuery({
queryKey: ["kitchens"],
queryFn: async () => {
const { data } = await client.get("user/kitchens");
return data;
},
refetchOnWindowFocus: false,
refetchInterval: false,
});
const [selected, setSelected] = useState("");
const [open, setOpen] = useState(false);
const { toast } = useToast();
const { mutate: transfer } = useMutation({
mutationFn: async (values: AddMultipleInventoriesToKitchenDto) => {
await client.post(`kitchen-inventory/add-multiple/${values.kitchenId}`, {
inventories: values.inventories,
});
},
onSuccess: () => {
toast({
title: "Transfer Complete",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
refetch();
setOpen(false);
remove();
},
});
function onSubmit(values: AddMultipleInventoriesToKitchenDto) {
transfer(values);
}
return (
<div className="w-full">
<div className="flex items-center justify-between p-4 border-b border-gray-100">
<div className="text-sm text-gray-500">
{table.getFilteredSelectedRowModel().rows.length > 0 && (
<span className="font-medium text-emerald-700">
{table.getFilteredSelectedRowModel().rows.length} items selected
</span>
)}
</div>
<div className="flex items-center gap-3">
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="Search inventory..."
value={
(table.getColumn("name")?.getFilterValue() as string) ?? ""
}
onChange={(event) =>
table.getColumn("name")?.setFilterValue(event.target.value)
}
className="pl-9 w-[250px] border-gray-200 focus:ring-emerald-500"
/>
</div>
{table.getFilteredSelectedRowModel().rows.length > 0 && (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button
variant="outline"
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<TransferIcon className="mr-2 h-4 w-4" />
Transfer Selected
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="text-emerald-800">
Transfer Items to Kitchen
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField
control={form.control}
name="kitchenId"
render={({ field }) => (
<FormItem>
<FormLabel className="text-emerald-700">
Select Kitchen
</FormLabel>
<FormControl>
<div className="grid grid-cols-2 gap-3">
{kitchens?.map((kitchen: Kitchen) => (
<div
key={kitchen.id}
className={`rounded-md border p-3 flex flex-col cursor-pointer transition-colors ${
selected === kitchen.id
? "border-emerald-500 bg-emerald-50"
: "border-gray-200 hover:border-emerald-300 hover:bg-emerald-50/50"
}`}
onClick={() => {
field.onChange(kitchen.id);
setSelected(kitchen.id);
}}
>
<div className="flex justify-between items-center">
<p className="text-sm font-medium">
{kitchen.name}
</p>
{selected !== kitchen.id ? (
<Circle
size={16}
className="text-gray-400"
/>
) : (
<CircleCheckBig
size={16}
className="text-emerald-600"
/>
)}
</div>
</div>
))}
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="space-y-3 max-h-[300px] overflow-y-auto pr-1">
<h3 className="text-sm font-medium text-gray-700">
Transfer Quantities
</h3>
{table.getSelectedRowModel().rows.map((row: any) => {
const existsIndex = fields.findIndex(
(x) => x.inventoryId === row.original.id
);
const quantity =
existsIndex !== -1 ? fields[existsIndex].quantity : 0;
const handleQuantityChange = (value: number) => {
if (existsIndex !== -1) {
update(existsIndex, {
inventoryId: row.original.id,
quantity: value,
unit: row.original.unit,
});
} else {
append({
inventoryId: row.original.id,
quantity: value,
unit: row.original.unit,
});
}
};
return (
<div
key={row.id}
className="p-3 border border-gray-200 rounded-md bg-white"
>
<div className="flex justify-between items-center mb-2">
<div className="font-medium text-emerald-800">
{row.original.name}
</div>
<div className="text-xs text-emerald-600 font-medium">
Available: {row.original.stock}{" "}
{row.original.unit}
</div>
</div>
<div className="flex items-center gap-3">
<Slider
className="flex-1"
min={0}
max={row.original.stock}
step={1}
value={[quantity]}
onValueChange={(value) =>
handleQuantityChange(value[0])
}
/>
<Input
className="w-16 text-center border-gray-200"
type="number"
min={0}
max={row.original.stock}
value={quantity}
onChange={(e) => {
const newValue = Math.min(
Math.max(e.target.valueAsNumber || 0, 0),
row.original.stock
);
handleQuantityChange(newValue);
}}
/>
<span className="text-sm text-gray-500 w-8">
{row.original.unit}
</span>
</div>
</div>
);
})}
</div>
<div className="flex justify-end gap-3 pt-2">
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
className="border-gray-200"
>
Cancel
</Button>
<Button
type="submit"
disabled={!form.formState.isValid}
className="bg-[#031274] hover:bg-emerald-700"
>
Complete Transfer
</Button>
</div>
</form>
</Form>
</DialogContent>
</Dialog>
)}
</div>
</div>
<div className="border-t border-gray-100">
<Table>
<TableHeader className="bg-gray-50">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead
key={header.id}
className="text-center border-r border-gray-100 [&:last-child]:border-r-0 text-emerald-700 font-medium py-3"
>
{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"}
className={`hover:bg-emerald-50 transition-colors border-b border-gray-100 [&:last-child]:border-b-0 ${
row.getIsSelected() ? "bg-emerald-50/70" : ""
}`}
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="text-center border-r border-gray-100 [&:last-child]:border-r-0 py-3"
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center text-gray-500"
>
No inventory items found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between p-4 border-t border-gray-100 bg-gray-50">
<div className="text-sm text-gray-500">
Showing{" "}
{table.getState().pagination.pageIndex *
table.getState().pagination.pageSize +
1}{" "}
to{" "}
{Math.min(
(table.getState().pagination.pageIndex + 1) *
table.getState().pagination.pageSize,
table.getRowModel().rows.length
)}{" "}
of {table.getRowModel().rows.length} entries
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800 disabled:opacity-50"
>
<ChevronLeft className="h-4 w-4 mr-1" /> Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800 disabled:opacity-50"
>
Next <ChevronRight className="h-4 w-4 ml-1" />
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,469 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { useToast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { InwardEntry, PaymentStatus } from "@anujs.dev/inventory-types-utils";
import { useMutation, useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import {
ArrowLeft,
CheckCircle,
ExternalLink,
FileText,
Link2,
Receipt,
Store,
User,
} from "lucide-react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
export default function InwardDetailsPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const [openBillUrl, setOpenBillUrl] = useState(false);
const [openPaymentStatus, setOpenPaymentStatus] = useState(false);
const { toast } = useToast();
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ["inward", id],
queryFn: async () => {
const { data } = await client.get(`im/inwards/${id}`);
return data;
},
});
const { mutate: updateBill, isPending: isUpdating } = useMutation({
mutationFn: async (values: {
bill_url?: string;
payment_status?: PaymentStatus;
}) => {
const { data } = await client.patch(`im/inwards/${id}`, values);
return data;
},
onSuccess: () => {
toast({
title: "Inward updated successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
setBillUrl("");
// @ts-ignore
setPaymentStatus(null);
refetch();
setOpenBillUrl(false);
setOpenPaymentStatus(false);
},
onError: () => {
toast({
title: "Failed to update inward",
description: "Please try again or contact support",
variant: "destructive",
});
},
});
const [billUrl, setBillUrl] = useState("");
const [paymentStatus, setPaymentStatus] = useState<PaymentStatus>(
PaymentStatus.UNPAID
);
useEffect(() => {
if (data) {
setBillUrl(data.bill_url || "");
setPaymentStatus(data.payment_status || PaymentStatus.UNPAID);
}
}, [data]);
if (isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex items-center mb-6">
<Skeleton className="h-8 w-[200px]" />
</div>
<Card className="border-gray-200 shadow-sm mb-6">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<Skeleton className="h-5 w-[150px]" />
</CardHeader>
<CardContent className="p-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-5">
{[...Array(6)].map((_, i) => (
<div key={i}>
<Skeleton className="h-4 w-[100px] mb-2" />
<Skeleton className="h-5 w-[150px]" />
</div>
))}
</div>
<div className="mt-6">
<Skeleton className="h-9 w-[150px]" />
</div>
</CardContent>
</Card>
<div className="mb-4">
<Skeleton className="h-6 w-[150px]" />
</div>
<Card className="border-gray-200 shadow-sm">
<CardContent className="p-0">
<div className="h-[300px] flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading inward details...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load inward details
</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the information
</p>
<div className="flex justify-center gap-3">
<Button
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
onClick={() => router.back()}
>
<ArrowLeft className="mr-2 h-4 w-4" /> Go Back
</Button>
<Button
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
onClick={() => refetch()}
>
Try Again
</Button>
</div>
</div>
</div>
);
}
const totalAmount = data.entries.reduce(
(sum: number, entry: InwardEntry) => sum + entry.amount,
0
);
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex items-center mb-6">
<Link
href="/d/admin/inventory"
className="text-emerald-700 hover:text-emerald-800 flex items-center text-sm font-medium mr-4"
>
<ArrowLeft className="mr-2 h-4 w-4" /> Back to Inventory
</Link>
<h1 className="text-2xl font-bold text-emerald-800">Inward Details</h1>
</div>
<Card className="border-gray-200 shadow-sm mb-6">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<Receipt className="mr-2 h-5 w-5 text-emerald-600" />
Inward Information
</CardTitle>
</CardHeader>
<CardContent className="p-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-5">
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">Vendor Name</p>
<p className="font-medium flex items-center">
<User className="h-4 w-4 mr-1.5 text-emerald-600" />
{data.vendor.name}
</p>
</div>
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">Store Name</p>
<p className="font-medium flex items-center">
<Store className="h-4 w-4 mr-1.5 text-emerald-600" />
{data.vendor.store_name}
</p>
</div>
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">GSTIN</p>
<p className="font-medium">{data.vendor.gstin || "N/A"}</p>
</div>
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">Bill No</p>
<p className="font-medium flex items-center">
<FileText className="h-4 w-4 mr-1.5 text-emerald-600" />
{data.bill_no}
</p>
</div>
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">Bill Date</p>
<p className="font-medium">
{format(new Date(data.date), "dd MMM yyyy")}
</p>
</div>
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">
Payment Status
</p>
<Badge
className={
data.payment_status === "PAID"
? "bg-emerald-100 text-emerald-800 border-emerald-200"
: data.payment_status === "PENDING"
? "bg-amber-100 text-amber-800 border-amber-200"
: "bg-red-100 text-red-800 border-red-200"
}
>
{data.payment_status}
</Badge>
</div>
{data.payment_date && (
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">
Payment Date
</p>
<p className="font-medium">
{format(new Date(data.payment_date), "dd MMM yyyy - h:mm a")}
</p>
</div>
)}
{data.bill_url && (
<div className="space-y-1">
<p className="text-xs font-semibold text-gray-500">Bill URL</p>
<Link
href={data.bill_url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-800 flex items-center"
>
<ExternalLink className="h-3.5 w-3.5 mr-1" />
View Bill
</Link>
</div>
)}
</div>
<div className="flex items-center pt-6 gap-3">
<Dialog open={openBillUrl} onOpenChange={setOpenBillUrl}>
<DialogTrigger asChild>
<Button
variant="outline"
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Link2 className="mr-2 h-4 w-4" />
Update Bill URL
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-emerald-800">
Update Bill URL
</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
e.preventDefault();
updateBill({
bill_url: billUrl,
});
}}
className="space-y-4 pt-2"
>
<Input
type="url"
value={billUrl}
onChange={(e) => setBillUrl(e.target.value)}
placeholder="Enter bill URL"
className="border-gray-200 focus:ring-emerald-500"
/>
<Button
disabled={!billUrl || isUpdating}
className="w-full bg-emerald-600 hover:bg-emerald-700"
type="submit"
>
{isUpdating ? "Updating..." : "Update Bill URL"}
</Button>
</form>
</DialogContent>
</Dialog>
<Dialog
open={openPaymentStatus}
onOpenChange={setOpenPaymentStatus}
>
<DialogTrigger asChild>
<Button
variant="outline"
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<CheckCircle className="mr-2 h-4 w-4" />
Update Payment Status
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-emerald-800">
Update Payment Status
</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
e.preventDefault();
updateBill({
payment_status: paymentStatus,
});
}}
className="space-y-4 pt-2"
>
<Select
value={paymentStatus}
onValueChange={(value) =>
setPaymentStatus(value as PaymentStatus)
}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Select payment status" />
</SelectTrigger>
<SelectContent>
<SelectItem value={PaymentStatus.PAID}>Paid</SelectItem>
<SelectItem value={PaymentStatus.UNPAID}>
Unpaid
</SelectItem>
</SelectContent>
</Select>
<Button
className="w-full bg-emerald-600 hover:bg-emerald-700"
type="submit"
disabled={isUpdating}
>
{isUpdating ? "Updating..." : "Update Payment Status"}
</Button>
</form>
</DialogContent>
</Dialog>
</div>
</CardContent>
</Card>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-center">
<CardTitle className="text-lg font-semibold text-emerald-800">
Inward Entries
</CardTitle>
<div className="text-sm font-medium text-emerald-700">
Total Amount: {totalAmount}
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="overflow-x-auto">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="text-center text-emerald-700 font-medium w-[80px]">
S. No
</TableHead>
<TableHead className="text-center text-emerald-700 font-medium">
Description
</TableHead>
<TableHead className="text-center text-emerald-700 font-medium">
HSN/SAC
</TableHead>
<TableHead className="text-center text-emerald-700 font-medium">
GST Rate
</TableHead>
<TableHead className="text-center text-emerald-700 font-medium">
Quantity
</TableHead>
<TableHead className="text-center text-emerald-700 font-medium">
Rate/Quantity
</TableHead>
<TableHead className="text-center text-emerald-700 font-medium">
Unit
</TableHead>
<TableHead className="text-center text-emerald-700 font-medium">
Amount
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.entries.map(
(entry: InwardEntry & { id: string }, index: number) => (
<TableRow key={entry.id} className="hover:bg-emerald-50">
<TableCell className="text-center font-medium">
{index + 1}
</TableCell>
<TableCell className="text-center">
{entry.description}
</TableCell>
<TableCell className="text-center">
{entry.hsn_sac || "—"}
</TableCell>
<TableCell className="text-center">
{entry.gst_rate}%
</TableCell>
<TableCell className="text-center">
{entry.quantity}
</TableCell>
<TableCell className="text-center">
{entry.rate}
</TableCell>
<TableCell className="text-center">
{entry.unit}
</TableCell>
<TableCell className="text-center font-medium">
{entry.amount}
</TableCell>
</TableRow>
)
)}
{data.entries.length === 0 && (
<TableRow>
<TableCell
colSpan={8}
className="h-24 text-center text-gray-500"
>
No entries found for this inward.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,53 @@
import SortingButton from "@/components/sorting-button";
import { Inward } from "@anujs.dev/inventory-types-utils";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import Link from "next/link";
export const inwardColumns: ColumnDef<Inward>[] = [
{ accessorKey: "id" },
{
header({ column }) {
return <SortingButton column={column}>Added On</SortingButton>;
},
accessorKey: "created_at",
cell: ({ row }) => {
return <span>{format(row.original.created_at, "dd MMM yyyy")}</span>;
},
enableSorting: true,
},
{
header({ column }) {
return <SortingButton column={column}>Vendor</SortingButton>;
},
accessorKey: "vendor",
cell: ({ row }) => {
return <span>{row.original.vendor.name}</span>;
},
},
{
header({ column }) {
return <SortingButton column={column}>Bill No</SortingButton>;
},
accessorKey: "bill_no",
},
{
header({ column }) {
return <SortingButton column={column}>Bill Date</SortingButton>;
},
accessorKey: "date",
cell: ({ row }) => {
return <span>{format(row.original.date, "dd MMM yyyy")}</span>;
},
},
{
header: "Entries",
accessorKey: "entries",
cell: ({ row }) => {
return (
// @ts-ignore
<Link href={`/d/admin/inventory/inward/${row.original.id}`}>View</Link>
);
},
},
];

View File

@@ -0,0 +1,769 @@
"use client";
import { DataTable } from "@/components/data-table";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { DatePicker } from "@/components/ui/date-picker";
import {
Dialog,
DialogContent,
DialogHeader,
DialogOverlay,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { useToast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import { CalendarIcon, Plus, Trash2 } from "lucide-react";
import { useEffect, useState } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { z } from "zod";
import { columns } from "./columns";
import { DataTableSelection } from "./data-table-selection";
import { inwardColumns } from "./inward/columns";
import {
calculateAmount,
cn,
filterInwardByDescriptions,
filterInwardBySelectedDates,
getUniqueDescriptions,
Inward,
} from "@anujs.dev/inventory-types-utils";
const createInwardEntrySchema = z.object({
description: z.string().min(1, "Description is required"),
hsn_sac: z.string().optional(),
gst_rate: z.coerce.number().min(0, "GST rate must be a non-negative number"),
quantity: z.coerce.number().int().positive("Quantity must be greter than 0"),
rate: z.number().int().positive("Rate must be greater than 0"),
unit: z.string().min(1, "Unit is required"),
amount: z.number().positive("Amount must be greater than 0"),
company_name: z.string(),
manufacturing_date: z.date(),
});
const createInwardSchema = z.object({
vendorId: z.string().min(1, "Vendor ID is required"),
bill_no: z.coerce
.number()
.int()
.positive("Bill number must be a positive integer"),
bill_url: z.string().optional(),
date: z.string().refine((date) => !isNaN(Date.parse(date)), {
message: "Invalid date format",
}),
entries: z
.array(createInwardEntrySchema)
.min(1, "At least one inward entry is required"),
});
type CreateInwardSchema = z.infer<typeof createInwardSchema>;
type CreateInwardSchemaEntry = z.infer<typeof createInwardEntrySchema>;
export default function InventoryPage() {
const [open, setOpen] = useState(false);
const { data: vendors } = useQuery({
queryKey: ["vendors"],
queryFn: async () => {
const { data } = await client.get("vendor");
return data;
},
});
const { toast } = useToast();
const { data: inventory, refetch: inventoryRefetch } = useQuery({
queryKey: ["inventory"],
queryFn: async () => {
const { data } = await client.get("im/inventory");
return data;
},
});
const { data: inwards, refetch: inwardsRefetch } = useQuery({
queryKey: ["inwards"],
queryFn: async () => {
const { data } = await client.get("im/inwards");
return data;
},
});
const { mutate: addInward } = useMutation({
mutationFn: async (vendor: CreateInwardSchema) => {
const { data } = await client.post("im/inwards", vendor);
return data;
},
onSuccess: () => {
toast({
title: "Inventory updated successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
setOpen(false);
inventoryRefetch();
inwardsRefetch();
form.reset();
},
});
const form = useForm<CreateInwardSchema>({
resolver: zodResolver(createInwardSchema),
defaultValues: {
vendorId: "",
bill_no: 0,
bill_url: "",
date: "",
entries: [],
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "entries",
});
function onSubmit(values: CreateInwardSchema) {
addInward(values);
}
const [filteredInwards, setFilteredInwards] = useState<
Inward[] & { id: string }[]
>([]);
const [filterItems, setFilterItems] = useState<string[]>();
const [selectedFilter, setSelectedFilter] = useState("");
useEffect(() => {
if (inwards) {
setFilteredInwards(inwards);
const items = getUniqueDescriptions(inwards);
setFilterItems(items);
}
}, [inwards]);
const [dates, setDates] = useState<string[]>([]);
useEffect(() => {
if (dates.length > 0 && inwards) {
const filtered = filterInwardBySelectedDates(inwards, dates);
// @ts-ignore
setFilteredInwards(filtered);
} else {
if (dates.length == 0 && inwards) {
setFilteredInwards(inwards);
}
}
}, [dates]);
useEffect(() => {
if (selectedFilter && inwards) {
const filtered = filterInwardByDescriptions(inwards, [selectedFilter]);
// @ts-ignore
setFilteredInwards(filtered);
} else {
setFilteredInwards(inwards);
}
}, [selectedFilter]);
return (
<div className="px-10 py-8 w-full">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-emerald-800">
Manage Inventory
</h1>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-[#031274] hover:bg-emerald-700">
<Plus className="mr-2 h-4 w-4" /> Add Inward
</Button>
</DialogTrigger>
<DialogOverlay />
<DialogContent className="max-w-screen-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-emerald-800">
Add Inventory
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
className="space-y-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField
control={form.control}
name="vendorId"
render={({ field }) => (
<FormItem>
<FormLabel className="text-emerald-700">Vendor</FormLabel>
<FormControl>
<Select
onValueChange={field.onChange}
value={field.value}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Select Vendor" />
</SelectTrigger>
<SelectContent>
{vendors?.map(
(vendor: { id: string; name: string }) => (
<SelectItem key={vendor.id} value={vendor.id}>
{vendor.name}
</SelectItem>
)
)}
</SelectContent>
</Select>
</FormControl>
</FormItem>
)}
/>
<div className="flex gap-5 items-center">
<FormField
control={form.control}
name="bill_no"
render={({ field }) => (
<FormItem className="w-full flex flex-col">
<FormLabel className="text-emerald-700">
Bill No
</FormLabel>
<FormControl>
<Input
{...field}
className="border-gray-200 focus:ring-emerald-500"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="bill_url"
render={({ field }) => (
<FormItem className="w-full flex flex-col">
<FormLabel className="text-emerald-700">
Bill Url
</FormLabel>
<FormControl>
<Input
{...field}
className="border-gray-200 focus:ring-emerald-500"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="date"
render={({ field }) => (
<FormItem className="w-full flex flex-col">
<FormLabel className="text-emerald-700">
Bill Date
</FormLabel>
<FormControl>
<DatePicker
setDate={(date) => {
// @ts-expect-error date is a date object
field.onChange(format(date, "yyyy-MM-dd"));
}}
// @ts-expect-error correct value is passed
date={field.value}
></DatePicker>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<Table>
<TableHeader className="bg-emerald-50">
<TableRow>
<TableHead className="text-emerald-700">
Description
</TableHead>
<TableHead className="text-emerald-700 font-medium">
Company Name
</TableHead>
<TableHead className="text-emerald-700 font-medium">
Manufacturing Date
</TableHead>
<TableHead className="text-emerald-700">
HSN/SAC
</TableHead>
<TableHead className="text-emerald-700">
GST Rate
</TableHead>
<TableHead className="text-emerald-700">
Quantity
</TableHead>
<TableHead className="text-emerald-700">
Rate/Quantity
</TableHead>
<TableHead className="text-emerald-700">Unit</TableHead>
<TableHead className="text-emerald-700">Amount</TableHead>
<TableHead className="text-emerald-700">Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.map((field, index) => (
<TableRow key={field.id} className="hover:bg-emerald-50">
<TableCell className="w-[300px]">
<FormField
control={form.control}
name={`entries.${index}.description`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
placeholder="Description"
{...field}
className="border-gray-200 focus:ring-emerald-500"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.company_name`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
placeholder="Company Name"
{...field}
className="border-gray-200 focus:ring-emerald-500"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.manufacturing_date`}
render={({ field }) => (
<FormItem>
<FormControl>
<Popover modal>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"w-full justify-start text-left font-normal border-gray-200",
!field.value &&
"text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{field.value ? (
format(new Date(field.value), "PPP")
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={
field.value
? new Date(field.value)
: undefined
}
onSelect={(date) =>
field.onChange(
date
? format(date, "yyyy-MM-dd")
: ""
)
}
initialFocus
/>
</PopoverContent>
</Popover>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.hsn_sac`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
placeholder="HSN/SAC"
{...field}
className="border-gray-200 focus:ring-emerald-500"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.gst_rate`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
type="number"
placeholder="GST Rate"
value={field.value === 0 ? "" : field.value}
className="border-gray-200 focus:ring-emerald-500"
// {...field}
onChange={(e) => {
let inputValue = e.target.value;
inputValue = inputValue.replace(
/^0+(?=\d)/,
""
);
const gst_rate =
Number.parseFloat(inputValue) || 0;
const quantity =
form.getValues(
`entries.${index}.quantity`
) || 0;
const rate =
form.getValues(
`entries.${index}.rate`
) || 0;
field.onChange(gst_rate);
form.setValue(
`entries.${index}.amount`,
calculateAmount(
quantity,
rate,
gst_rate
)
);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.quantity`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
type="number"
placeholder="Quantity"
{...field}
className="border-gray-200 focus:ring-emerald-500"
value={field.value === 0 ? "" : field.value}
onChange={(e) => {
let inputValue = e.target.value;
inputValue = inputValue.replace(
/^0+(?=\d)/,
""
);
const quantity =
Number.parseInt(inputValue, 10) || 0;
const rate =
form.getValues(
`entries.${index}.rate`
) || 0;
field.onChange(quantity);
form.setValue(
`entries.${index}.amount`,
calculateAmount(
quantity,
rate,
form.getValues(
`entries.${index}.gst_rate`
)
)
);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.rate`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
type="number"
placeholder="Rate"
{...field}
className="border-gray-200 focus:ring-emerald-500"
value={field.value === 0 ? "" : field.value}
onChange={(e) => {
let inputValue = e.target.value;
inputValue = inputValue.replace(
/^0+(?=\d)/,
""
);
const rate =
Number.parseFloat(inputValue) || 0;
const quantity =
form.getValues(
`entries.${index}.quantity`
) || 0;
field.onChange(rate);
form.setValue(
`entries.${index}.amount`,
calculateAmount(
quantity,
rate,
form.getValues(
`entries.${index}.gst_rate`
)
)
);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.unit`}
render={({ field }) => (
<FormItem>
<FormControl>
<Select
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Unit" />
</SelectTrigger>
<SelectContent>
<SelectItem value="kg">kg</SelectItem>
<SelectItem value="g">g</SelectItem>
<SelectItem value="pcs">pcs</SelectItem>
<SelectItem value="box">box</SelectItem>
<SelectItem value="bag">bag</SelectItem>
<SelectItem value="no">No</SelectItem>
<SelectItem value="nos">Nos</SelectItem>
<SelectItem value="packet">
packet
</SelectItem>
<SelectItem value="dozen">
dozen
</SelectItem>
</SelectContent>
</Select>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<FormField
control={form.control}
name={`entries.${index}.amount`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
type="number"
placeholder="Amount"
{...field}
className="border-gray-200 focus:ring-emerald-500"
onChange={(e) =>
field.onChange(
Number.parseFloat(e.target.value)
)
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell>
<Button
variant="destructive"
onClick={() => remove(index)}
>
<Trash2 className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
<TableCaption>
<Button
onClick={() =>
append({
amount: 0,
description: "",
gst_rate: 0,
hsn_sac: "",
quantity: 0,
rate: 0,
unit: "",
company_name: "",
manufacturing_date: new Date(),
})
}
type="button"
className="bg-amber-600 hover:bg-amber-700"
>
<Plus className="mr-2 h-4 w-4" /> Add Item
</Button>
</TableCaption>
</Table>
<Button
type="submit"
className="w-full bg-[#031274] hover:bg-emerald-700"
>
Save
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
<div className="*:self-start pt-5 w-full gap-5">
<div className="bg-white border border-gray-100 rounded-md shadow-sm overflow-hidden mb-8">
<div className="p-4 border-b border-gray-100 bg-emerald-50">
<h2 className="text-lg font-semibold text-emerald-800">
Current Inventory
</h2>
</div>
<DataTableSelection
refetch={inventoryRefetch}
columns={columns}
data={inventory ?? []}
/>
</div>
<div className="bg-white border border-gray-100 rounded-md shadow-sm overflow-hidden">
<div className="flex items-center justify-between p-4 border-b border-gray-100 bg-emerald-50">
<h2 className="text-lg font-semibold text-emerald-800">
Manage Inwards
</h2>
<div className="flex items-center gap-4">
<Popover>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"justify-start text-left font-normal border-gray-200",
!dates && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4 text-amber-600" />
{dates.length > 0 ? (
dates.map((date) => `${format(date, "dd/MM, ")}`)
) : (
<span>Filter by dates</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0 pointer-events-auto">
<Calendar
mode="multiple"
// @ts-ignore
selected={dates}
// @ts-ignore
onSelect={setDates}
className="rounded-md border"
/>
</PopoverContent>
</Popover>
<Select
value={selectedFilter}
onValueChange={(value) => {
if (value === "all") {
setSelectedFilter("");
} else {
setSelectedFilter(value);
}
}}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Filter by item"></SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value={"all"}>All</SelectItem>
{filterItems?.map((item) => (
<SelectItem key={item} value={item}>
{item}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<DataTable
refetch={inwardsRefetch}
columns={inwardColumns}
data={filteredInwards ?? []}
/>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,107 @@
import SortingButton from "@/components/sorting-button";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
export const columns: ColumnDef<any>[] = [
{
header({ column }) {
return <SortingButton column={column}>Transferred On</SortingButton>;
},
accessorKey: "timestamp",
cell: ({ row }) => {
return (
<span>
{format(new Date(row.original.timestamp), "dd MMM yyyy - HH:mm")}
</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Name</SortingButton>;
},
accessorKey: "inventoryName",
cell: ({ row }) => {
return (
<span>
{row.original.details.inventory?.name ||
row.original.details.metadata.inventory?.name}
</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Quantity</SortingButton>;
},
accessorKey: "quantity",
cell: ({ row }) => {
console.log(row.original);
if (row.original.source === "log") {
return (
<span>
{row.original.details.metadata.inventory.quantity}{" "}
{row.original.details.metadata.inventory.unit}
</span>
);
}
return (
<span>
{row.original.details.quantity} {row.original.details.inventory.unit}
</span>
);
},
},
{
header: "From",
accessorKey: "from",
cell: ({ row }) => {
return (
<span>
{row.original.details.fromKitchen?.name ||
row.original.details.metadata?.from ||
"Unknown"}
</span>
);
},
},
{
header: "To",
accessorKey: "to",
cell: ({ row }) => {
return (
<span>
{row.original.details.toKitchen?.name ||
row.original.details.metadata?.to ||
"Unknown"}
</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>User</SortingButton>;
},
accessorKey: "user",
cell: ({ row }) => {
if (row.original.source === "tanstack-query") {
return (
<span>
{row.original.details.user?.name} |{" "}
{row.original.details.user?.email}
</span>
);
} else {
return <span>Admin</span>;
}
},
},
{
header: "Reason",
accessorKey: "reason",
cell: ({ row }) => {
return <span>{row.original.details.reason || "No reason provided"}</span>;
},
},
];

View File

@@ -0,0 +1,157 @@
"use client";
import { DataTable } from "@/components/data-table";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import client from "@/lib/client";
import { useQueries } from "@tanstack/react-query";
import { RefreshCcw } from "lucide-react";
import { useMemo } from "react";
import { columns } from "./columns";
export default function KitchenTransfersPage() {
const [transfersQuery, logsQuery] = useQueries({
queries: [
{
queryKey: ["all", "transfers"],
queryFn: async () => {
const { data } = await client.get("kitchen-inventory/transfers/all");
return data;
},
},
{
queryKey: ["transfers", "logs"],
queryFn: async () => {
const { data } = await client.get("logs/inventory-transfers");
return data;
},
},
],
});
function refetch() {
transfersQuery.refetch();
logsQuery.refetch();
}
const isLoading = transfersQuery.isLoading || logsQuery.isLoading;
const isError = transfersQuery.isError || logsQuery.isError;
const combinedData = useMemo(() => {
if (!transfersQuery.data || !logsQuery.data) return [];
const formattedTransfers = transfersQuery.data.map((entry: any) => ({
timestamp: entry.created_at,
source: "system",
details: entry,
}));
const formattedLogs = logsQuery.data.map((entry: any) => ({
timestamp: entry.timestamp,
source: "log",
details: entry,
}));
return [...formattedTransfers, ...formattedLogs].sort(
(a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
);
}, [transfersQuery.data, logsQuery.data]);
if (isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<Skeleton className="h-8 w-[300px] mb-4" />
<Skeleton className="h-4 w-[200px] mb-6" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[200px]" />
<div className="flex gap-2">
<Skeleton className="h-9 w-[120px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[400px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading transfer data...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Kitchen Inventory Transfers
</h1>
<p className="text-sm text-gray-500 mb-6">
Track and manage inventory transfers between kitchens
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load transfer data
</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the transfer information
</p>
<Button
onClick={refetch}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Kitchen Inventory Transfers
</h1>
<p className="text-sm text-gray-500 mb-6">
Track and manage inventory transfers between kitchens
</p>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800">
Transfer History
</CardTitle>
<div className="flex items-center gap-3">
<Button
variant="outline"
size="sm"
onClick={refetch}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<DataTable
// @ts-ignore
refetch={refetch}
columns={columns}
data={combinedData}
/>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,295 @@
import { ConfirmAction } from "@/components/confirm-action";
import SortingButton from "@/components/sorting-button";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { toast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { KitchenInventory } from "@anujs.dev/inventory-types-utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery } from "@tanstack/react-query";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import { ArrowRightCircle, Trash2Icon } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
const transferToKitchenForm = z.object({
fromKitchenId: z.string().uuid(),
toKitchenId: z.string().uuid(),
inventoryId: z.string().uuid(),
quantity: z.coerce.number().positive(),
unit: z.string(),
reason: z.string().min(3, "Reason must be atleast 3 characters long"),
});
type TransferToKitchenSchema = z.infer<typeof transferToKitchenForm>;
export const columns: ColumnDef<KitchenInventory>[] = [
{
header({ column }) {
return <SortingButton column={column}>Last Updated on</SortingButton>;
},
accessorKey: "updated_at",
cell: ({ row }) => {
return (
<span>{format(row.original.updated_at, "dd MMM yyyy - HH:MM")}</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Name</SortingButton>;
},
accessorKey: "name",
},
{
header({ column }) {
return <SortingButton column={column}>Stock</SortingButton>;
},
accessorKey: "stock",
},
{
accessorKey: "kitchen",
enableHiding: true,
},
{
header: "Unit",
accessorKey: "unit",
},
{
header: "Actions",
cell: ({ row, table }) => {
const form = useForm<TransferToKitchenSchema>({
resolver: zodResolver(transferToKitchenForm),
defaultValues: {
fromKitchenId: row.original.kitchen.id,
toKitchenId: "",
inventoryId: row.original.id,
quantity: 0,
unit: row.original.unit,
reason: "",
},
});
const [deleteOpen, setDeleteOpen] = useState(false);
const [open, setOpen] = useState(false);
const {
data: kitchens,
isLoading,
refetch,
} = useQuery({
queryKey: ["kitchen inventories"],
queryFn: async () => {
const { data } = await client.get("kitchen-inventory");
return data;
},
select(data) {
const kitchenMap = new Map();
data.forEach((item: KitchenInventory) => {
const kitchenId = item.kitchen.id;
const kitchenName = item.kitchen.name;
if (row.original.kitchen.id !== kitchenId) {
kitchenMap.set(kitchenId, { id: kitchenId, name: kitchenName });
}
});
return Array.from(kitchenMap.values());
},
});
const { mutate: transferToKitchen } = useMutation({
mutationFn: async (values: TransferToKitchenSchema) => {
const { data } = await client.post(
"kitchen-inventory/transfer",
values
);
return data;
},
onSuccess: () => {
toast({
title: "Transfer Complete",
});
refetch();
// @ts-expect-error sent to the main table
table.options.meta.refetch();
form.setValue("quantity", 0);
form.setValue("toKitchenId", "");
setOpen(false);
},
});
function onSubmit(data: TransferToKitchenSchema) {
transferToKitchen(data);
}
const { mutate: deleteFromKitchen } = useMutation({
mutationFn: async (id: string) => {
const { data } = await client.delete(`kitchen-inventory/ki/${id}`);
return data;
},
onSuccess: () => {
toast({
title: "Deleted successfully",
});
// @ts-ignore
table.options.meta.refetch();
},
});
return (
<div className="flex justify-center gap-4 items-ccenter">
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant={"outline"}>Transfer</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Transfer Inventory</DialogTitle>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField
name="toKitchenId"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Transfer beteen Kitchens</FormLabel>
<div className="flex gap-5 items-center justify-between">
<Input
value={row.original.kitchen.name}
disabled
></Input>
<ArrowRightCircle
size={30}
className="w-20 text-green-500"
></ArrowRightCircle>
<FormControl className="">
<Select
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger>
<SelectValue placeholder="Select Kitchen"></SelectValue>
</SelectTrigger>
<SelectContent>
{kitchens?.map((kitchen: any) => (
<SelectItem
key={kitchen.id}
value={kitchen.id}
>
{kitchen.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
</div>
</FormItem>
)}
></FormField>
<FormField
control={form.control}
name="quantity"
render={({ field }) => (
<FormItem>
<FormLabel>
Quantity
<span className="px-3 text-green-500">
(Current Quantity: {row.original.stock})
</span>
</FormLabel>
<FormControl className="w-full">
<div className="w-full gap-5 flex items-center">
<Slider
className="w-[70%]"
min={0}
max={row.original.stock}
step={1}
onValueChange={(value) => {
console.log(value);
field.onChange(value[0]);
}}
value={[field.value]}
></Slider>
<Input
className={"w-32"}
type="number"
value={field.value}
onChange={field.onChange}
max={row.original.stock}
></Input>
<p>{row.original.unit}</p>
</div>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
)}
></FormField>
<FormField
control={form.control}
name="reason"
render={({ field }) => (
<FormItem>
<FormLabel>Reason for transfer</FormLabel>
<FormControl className="w-full">
<Input {...field}></Input>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
)}
></FormField>
<Button
disabled={!form.formState.isValid}
className="w-full"
>
Transfer Now
</Button>
</form>
</Form>
</DialogHeader>
</DialogContent>
</Dialog>
<ConfirmAction
onConfirm={() => {
// @ts-ignore
deleteFromKitchen(row.original.kid);
}}
onOpenChange={setDeleteOpen}
open={deleteOpen}
>
<Button variant={"destructive"} size="icon">
<Trash2Icon />
</Button>
</ConfirmAction>
</div>
);
},
},
];

View File

@@ -0,0 +1,258 @@
"use client";
import { DataTable } from "@/components/data-table";
import { columns } from "./columns";
import { useQuery } from "@tanstack/react-query";
import client from "@/lib/client";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { RefreshCcw, Search, Store } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { useState } from "react";
import { KitchenInventory } from "@anujs.dev/inventory-types-utils";
export default function KitchenInventoryPage() {
const [searchTerm, setSearchTerm] = useState("");
const {
data: kitchens,
isLoading,
isError,
refetch,
} = useQuery({
queryKey: ["kitchen inventories"],
queryFn: async () => {
const { data } = await client.get("kitchen-inventory");
return data;
},
select(data) {
const grouped = data.reduce((acc: any, item: KitchenInventory) => {
const kitchenId = item.kitchen.id;
const kitchenName = item.kitchen.name;
if (!acc[kitchenId]) {
acc[kitchenId] = {
id: kitchenId,
name: kitchenName,
inventories: [],
};
}
acc[kitchenId].inventories.push({
id: item.inventory.id,
kid: item.id,
name: item.inventory.name,
stock: item.stock,
unit: item.unit,
updated_at: item.updated_at,
});
return acc;
}, {});
return Object.values(grouped);
},
});
if (isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<Skeleton className="h-8 w-[300px] mb-4" />
<Skeleton className="h-4 w-[200px] mb-6" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[200px]" />
<div className="flex gap-2">
<Skeleton className="h-9 w-[120px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[400px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading inventory data...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Kitchen Inventories
</h1>
<p className="text-sm text-gray-500 mb-6">
View and manage inventory across all kitchens
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load inventory data
</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the inventory information
</p>
<Button
onClick={() => refetch()}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
if (!kitchens || kitchens.length === 0) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Kitchen Inventories
</h1>
<p className="text-sm text-gray-500 mb-6">
View and manage inventory across all kitchens
</p>
<Card className="border-gray-200 shadow-sm">
<CardContent className="flex flex-col items-center justify-center py-12">
<div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
<Store className="h-8 w-8 text-emerald-600" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No Kitchens Found
</h3>
<p className="text-gray-500 max-w-md text-center">
There are no kitchens with inventory items in the system. Please
add kitchens and inventory items first.
</p>
<Button
variant="outline"
className="mt-6 border-gray-200"
onClick={() => refetch()}
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</CardContent>
</Card>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Kitchen Inventories
</h1>
<p className="text-sm text-gray-500 mt-1">
View and manage inventory across all kitchens
</p>
</div>
<Button
variant="outline"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800">
Inventory by Kitchen
</CardTitle>
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="Search inventory..."
className="pl-9 max-w-xs h-9 border-gray-200 focus:ring-emerald-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{/* @ts-ignore */}
<Tabs defaultValue={kitchens[0]?.id ?? ""} className="w-full">
<TabsList className="w-full justify-start rounded-none border-b bg-transparent p-0">
{kitchens?.map((kitchen: any) => (
<TabsTrigger
key={kitchen.id}
value={kitchen.id}
className="rounded-none border-b-2 border-transparent px-4 py-3 data-[state=active]:border-emerald-600 data-[state=active]:bg-transparent data-[state=active]:shadow-none"
>
{kitchen.name}
</TabsTrigger>
))}
</TabsList>
{kitchens?.map((kitchen: any) => {
// Filter inventories based on search term
const filteredInventories = kitchen.inventories.filter(
(inv: any) =>
inv.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<TabsContent
key={kitchen.id}
value={kitchen.id}
className="pt-4"
>
<div className="flex items-center justify-between mb-4">
<h2 className="font-medium text-emerald-800 flex items-center">
<Store className="mr-2 h-4 w-4 text-emerald-600" />
{kitchen.name} Inventory
</h2>
<div className="text-sm text-gray-500">
{filteredInventories.length}{" "}
{filteredInventories.length === 1 ? "item" : "items"}
</div>
</div>
{filteredInventories.length > 0 ? (
<DataTable
refetch={refetch}
columns={columns}
columnVisibility={{
kitchen: false,
}}
data={filteredInventories.map((inv: any) => ({
...inv,
kitchen: {
id: kitchen.id,
name: kitchen.name,
},
}))}
/>
) : (
<div className="text-center py-12 bg-gray-50 rounded-md border border-gray-200">
<p className="text-gray-500">
{searchTerm
? `No inventory items matching "${searchTerm}" found in ${kitchen.name}`
: `No inventory items found in ${kitchen.name}`}
</p>
</div>
)}
</TabsContent>
);
})}
</Tabs>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,24 @@
import Link from "next/link";
import React from "react";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import { AdminSidebar } from "./components/sidebar";
export default function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<SidebarProvider>
<AdminSidebar></AdminSidebar>
<main className="w-full min-h-screen items-start justify-between flex flex-col">
<div className="w-full ">
<SidebarTrigger />
<div className="w-full">{children}</div>
</div>
<p className="justify-self-end w-full text-sm text-center bg-emerald-700 text-white ">
Powered by Aurelion Future Forge
</p>
</main>
</SidebarProvider>
);
}

View File

@@ -0,0 +1,39 @@
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import SortingButton from "@/components/sorting-button";
import { Log, ServiceMappings } from "@anujs.dev/inventory-types-utils";
export const columns: ColumnDef<Log>[] = [
{
header({ column }) {
return <SortingButton column={column}>Log time</SortingButton>;
},
accessorKey: "timestamp",
cell: ({ row }) => {
return (
<span>{format(row.original.timestamp, "MMM d, yyyy h:mm a")}</span>
);
},
},
{
header: "Action",
accessorKey: "metadata.context",
cell: ({ row }) => {
// @ts-expect-error it is mapped using this
return <span>{ServiceMappings[row.original.context]}</span>;
},
},
{
header: "User",
accessorKey: "metadata.user.name",
},
{
header: "Role",
accessorKey: "metadata.user.role",
},
{
header: "Description",
accessorKey: "metadata.activity",
},
];

View File

@@ -0,0 +1,209 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import client from "@/lib/client";
import { useQuery } from "@tanstack/react-query";
import { FileText, RefreshCcw, Search } from "lucide-react";
import { useEffect, useState } from "react";
import { columns } from "./columns";
import { DataTable } from "@/components/data-table";
import { Log, ServiceMappings } from "@anujs.dev/inventory-types-utils";
export default function LogsPage() {
const [filter, setFilter] = useState("all");
const [searchTerm, setSearchTerm] = useState("");
const [filtered, setFiltered] = useState<Log[]>([]);
const { data, refetch, isLoading, isError } = useQuery<Log[]>({
queryKey: ["logs"],
queryFn: async () => {
const { data } = await client.get("logs/app");
return data;
},
});
useEffect(() => {
if (data) {
let filteredData = data;
if (filter !== "all") {
filteredData = filteredData.filter(
(log) => log.metadata.context === filter
);
}
if (searchTerm) {
filteredData = filteredData.filter(
(log) =>
log.message.toLowerCase().includes(searchTerm.toLowerCase()) ||
// @ts-ignore
(log.user?.name &&
// @ts-ignore
log.user.name.toLowerCase().includes(searchTerm.toLowerCase())) ||
(log.metadata &&
JSON.stringify(log.metadata)
.toLowerCase()
.includes(searchTerm.toLowerCase()))
);
}
setFiltered(filteredData);
}
}, [data, filter, searchTerm]);
if (isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<Skeleton className="h-8 w-[200px] mb-4" />
<Skeleton className="h-4 w-[200px] mb-6" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[200px]" />
<div className="flex gap-2">
<Skeleton className="h-9 w-[120px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[400px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading logs...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Application Logs
</h1>
<p className="text-sm text-gray-500 mb-6">
View and filter system logs across all services
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">Failed to load logs</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the log information
</p>
<Button
onClick={() => refetch()}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Application Logs
</h1>
<p className="text-sm text-gray-500 mt-1">
View and filter system logs across all services
</p>
</div>
<Button
variant="outline"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<FileText className="mr-2 h-5 w-5 text-emerald-600" />
System Logs
{filtered && (
<Badge className="ml-2 bg-emerald-100 text-emerald-800 border-emerald-200">
{filtered.length} entries
</Badge>
)}
</CardTitle>
<div className="flex items-center gap-3">
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="Search logs..."
className="pl-9 max-w-xs h-9 border-gray-200 focus:ring-emerald-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<Select
value={filter}
onValueChange={(value) => setFilter(value)}
>
<SelectTrigger className="w-[180px] border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Filter by service" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Services</SelectItem>
{Object.entries(ServiceMappings).map(([key, label]) => (
<SelectItem key={key} value={key}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{filtered && filtered.length > 0 ? (
<DataTable refetch={refetch} columns={columns} data={filtered} />
) : (
<div className="text-center py-12">
<p className="text-gray-500">
{searchTerm || filter !== "all"
? "No logs match your current filters"
: "No logs found in the system"}
</p>
{(searchTerm || filter !== "all") && (
<Button
variant="outline"
className="mt-4 border-gray-200"
onClick={() => {
setSearchTerm("");
setFilter("all");
}}
>
Clear Filters
</Button>
)}
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,252 @@
import { ConfirmAction } from "@/components/confirm-action";
import SortingButton from "@/components/sorting-button";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DatePicker } from "@/components/ui/date-picker";
import { Dialog, DialogTrigger } from "@/components/ui/dialog";
import {
FormField,
FormItem,
FormLabel,
FormControl,
FormMessage,
Form,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { MultiSelection } from "@/components/ui/multi-selection";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import { toast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { FoodType, Menu } from "@anujs.dev/inventory-types-utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation } from "@tanstack/react-query";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import { Edit2, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
const FoodTypeEnum = z.nativeEnum(FoodType);
const updateMenuSchema = z.object({
name: z.string(),
type: z.array(FoodTypeEnum),
publishDate: z.date(),
});
type UpdateMenuSchema = z.infer<typeof updateMenuSchema>;
export const columns: ColumnDef<Menu>[] = [
{
header({ column }) {
return <SortingButton column={column}>Added On</SortingButton>;
},
accessorKey: "created_at",
cell: ({ row }) => {
return (
<span>{format(row.original.created_at, "MMM d, yyyy h:mm a")}</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Food Name</SortingButton>;
},
accessorKey: "name",
},
{
header({ column }) {
return <SortingButton column={column}>Type</SortingButton>;
},
accessorKey: "type",
cell: ({ row }) => {
return (
<div className="gap-3 flex items-center">
{row.original.type.map((type) => (
<Badge
key={type}
variant={"outline"}
className="capitalize rounded-full"
>
{type}
</Badge>
))}
</div>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Publish Date</SortingButton>;
},
accessorKey: "publishDate",
cell: ({ row }) => {
return <span>{format(row.original.publishDate, "MMM d, yyyy")}</span>;
},
},
{
header: "Actions",
accessorKey: "updated_at",
cell: ({ row, table }) => {
const router = useRouter();
const [open, setOpen] = useState(false);
const [del, setDel] = useState(false);
const form = useForm<UpdateMenuSchema>({
resolver: zodResolver(updateMenuSchema),
defaultValues: {
name: row.original.name,
type: row.original.type,
publishDate: row.original.publishDate,
},
});
const { mutate: updateMenu } = useMutation({
mutationFn: async (values: UpdateMenuSchema) => {
const { data } = await client.put(`menu/${row.original.id}`, values);
return data;
},
onSuccess: () => {
// @ts-expect-error it is being passed form the table.
table.options.meta.refetch();
toast({
title: "Updated Menu",
});
setOpen(false);
router.refresh();
},
});
const { mutate: deleteMenu } = useMutation({
mutationFn: async () => {
const { data } = await client.delete(`menu/${row.original.id}`);
return data;
},
onSuccess: () => {
// @ts-expect-error it is being passed form the table.
table.options.meta.refetch();
toast({
title: "Deleted Menu",
});
setDel(false);
},
});
function onSubmit(values: UpdateMenuSchema) {
updateMenu(values);
}
return (
<div className="flex items-center gap-2">
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button variant={"outline"} size={"icon"}>
<Edit2 />
</Button>
</SheetTrigger>
<SheetContent>
<SheetHeader>
<SheetTitle>Update {row.original.name}</SheetTitle>
</SheetHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField
control={form.control}
name="name"
render={({ field }) => {
return (
<FormItem>
<FormLabel>Food Name</FormLabel>
<FormControl>
<Input {...field}></Input>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
);
}}
/>
<FormField
control={form.control}
name="type"
render={({ field }) => {
return (
<FormItem>
<FormLabel>Food Type</FormLabel>
<FormControl>
<MultiSelection
onValueSelected={field.onChange}
value={field.value}
options={[
{
label: "Breakfast",
value: FoodType.BREAKFAST,
},
{
label: "Lunch",
value: FoodType.LUNCH,
},
{
label: "Dinner",
value: FoodType.DINNER,
},
]}
></MultiSelection>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
);
}}
/>
<FormField
control={form.control}
name="publishDate"
render={({ field }) => {
return (
<FormItem>
<FormLabel>Select a date</FormLabel>
<FormControl>
<DatePicker
date={field.value}
setDate={field.onChange}
/>
</FormControl>
</FormItem>
);
}}
></FormField>
<Button className="w-full" type="submit">
Update
</Button>
</form>
</Form>
</SheetContent>
</Sheet>
<ConfirmAction
open={del}
onOpenChange={setDel}
onConfirm={deleteMenu}
>
<Button variant={"destructive"}>
<Trash2 />
</Button>
</ConfirmAction>
</div>
);
},
},
];

View File

@@ -0,0 +1,407 @@
"use client";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import client from "@/lib/client";
import { DataTable } from "@/components/data-table";
import { columns } from "./columns";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { MultiSelection } from "@/components/ui/multi-selection";
import { DatePicker } from "@/components/ui/date-picker";
import { useToast } from "@/hooks/use-toast";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CalendarIcon, Plus, RefreshCcw } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Skeleton } from "@/components/ui/skeleton";
const createMenuSchema = z.object({
name: z.string().min(1, "Menu name is required"),
type: z.array(z.string()).min(1, "At least one food type is required"),
publishDate: z.date(),
});
type CreateMenuSchema = z.infer<typeof createMenuSchema>;
export default function MenuManagementPage() {
const [open, setOpen] = useState(false);
const queryClient = useQueryClient();
const { toast } = useToast();
const form = useForm<CreateMenuSchema>({
resolver: zodResolver(createMenuSchema),
defaultValues: {
name: "",
type: [],
},
});
const {
data: menus,
isLoading: isMenusLoading,
refetch,
isError: isMenusError,
} = useQuery({
queryKey: ["menu", "active"],
queryFn: async () => {
const { data } = await client.get("menu/today/user");
return data;
},
});
const {
data: pastMenus,
isLoading: isPastMenusLoading,
refetch: refetchPast,
isError: isPastMenusError,
} = useQuery({
queryKey: ["menu", "past"],
queryFn: async () => {
const { data } = await client.get("menu/past");
return data;
},
});
const {
data: upcomingMenus,
isLoading: isUpcomingMenusLoading,
refetch: refetchUpcoming,
isError: isUpcomingMenusError,
} = useQuery({
queryKey: ["menu", "upcoming"],
queryFn: async () => {
const { data } = await client.get("menu/upcoming");
return data;
},
});
const { mutate: createMenu, isPending: isCreating } = useMutation({
mutationFn: async (values: CreateMenuSchema) => {
return client.post("menu", values);
},
onSuccess: () => {
toast({
title: "Menu created successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
refetch();
refetchUpcoming();
refetchPast();
setOpen(false);
form.reset();
},
onError: () => {
toast({
title: "Failed to create menu",
description: "Please check your input and try again",
variant: "destructive",
});
},
});
function onSubmit(values: CreateMenuSchema) {
createMenu(values);
}
const isLoading =
isMenusLoading || isPastMenusLoading || isUpcomingMenusLoading;
const isError = isMenusError || isPastMenusError || isUpcomingMenusError;
if (isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<div className="flex justify-between items-center">
<Skeleton className="h-8 w-[200px]" />
<Skeleton className="h-10 w-[120px]" />
</div>
<Tabs defaultValue="active">
<TabsList className="w-full justify-start">
<Skeleton className="h-10 w-[100px] rounded-md" />
<Skeleton className="h-10 w-[100px] rounded-md ml-1" />
<Skeleton className="h-10 w-[100px] rounded-md ml-1" />
</TabsList>
<div className="mt-6">
<Skeleton className="h-6 w-[150px] mb-4" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[150px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[300px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading menu data...</p>
</div>
</div>
</CardContent>
</Card>
</div>
</Tabs>
</div>
);
}
if (isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Menu Management
</h1>
<p className="text-sm text-gray-500 mb-6">
Create and manage food menus for your kitchens
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load menu data
</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the menu information
</p>
<div className="flex justify-center gap-3">
<Button
onClick={() => {
refetch();
refetchPast();
refetchUpcoming();
}}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Menu Management
</h1>
<p className="text-sm text-gray-500 mt-1">
Create and manage food menus for your kitchens
</p>
</div>
<Dialog open={open} onOpenChange={setOpen} modal>
<DialogTrigger asChild>
<Button className="bg-[#031274] hover:bg-emerald-700 text-white">
<Plus className="mr-2 h-4 w-4" /> Add Menu
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-emerald-800">
Add New Menu
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel className="text-emerald-700">
Menu Name
</FormLabel>
<FormControl>
<Input
{...field}
className="border-gray-200 focus:ring-emerald-500"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem>
<FormLabel className="text-emerald-700">
Food Type
</FormLabel>
<FormControl>
<MultiSelection
options={[
{ label: "Breakfast", value: "BREAKFAST" },
{ label: "Lunch", value: "LUNCH" },
{ label: "Dinner", value: "DINNER" },
{ label: "Snacks", value: "SNACKS" },
]}
value={field.value}
onValueSelected={field.onChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="publishDate"
render={({ field }) => (
<FormItem>
<FormLabel className="text-emerald-700">
Publish Date
</FormLabel>
<FormControl>
<DatePicker
fromDate={new Date()}
date={field.value}
setDate={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<Button
type="submit"
className="w-full bg-[#031274] hover:bg-emerald-700 text-white"
disabled={isCreating}
>
{isCreating ? "Creating..." : "Add Menu"}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
</div>
<Tabs defaultValue="active" className="space-y-6">
<TabsList className="w-full justify-start border-b rounded-none bg-transparent p-0">
<TabsTrigger
value="active"
className="rounded-none border-b-2 border-transparent px-4 py-3 data-[state=active]:border-emerald-600 data-[state=active]:bg-transparent data-[state=active]:shadow-none"
>
Active Menus
</TabsTrigger>
<TabsTrigger
value="upcoming"
className="rounded-none border-b-2 border-transparent px-4 py-3 data-[state=active]:border-emerald-600 data-[state=active]:bg-transparent data-[state=active]:shadow-none"
>
Upcoming Menus
</TabsTrigger>
<TabsTrigger
value="past"
className="rounded-none border-b-2 border-transparent px-4 py-3 data-[state=active]:border-emerald-600 data-[state=active]:bg-transparent data-[state=active]:shadow-none"
>
Previous Menus
</TabsTrigger>
</TabsList>
<TabsContent value="active" className="space-y-4">
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-center">
<CardTitle className="text-lg font-semibold text-emerald-800">
Active Menus
</CardTitle>
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</CardHeader>
<CardContent className="p-0">
<DataTable
refetch={refetch}
columns={columns}
data={menus ?? []}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="upcoming" className="space-y-4">
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-center">
<CardTitle className="text-lg font-semibold text-emerald-800">
Upcoming Menus
</CardTitle>
<Button
variant="outline"
size="sm"
onClick={() => refetchUpcoming()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</CardHeader>
<CardContent className="p-0">
<DataTable
refetch={refetchUpcoming}
columns={columns}
data={upcomingMenus ?? []}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="past" className="space-y-4">
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-center">
<CardTitle className="text-lg font-semibold text-emerald-800">
Previous Menus
</CardTitle>
<Button
variant="outline"
size="sm"
onClick={() => refetchPast()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</CardHeader>
<CardContent className="p-0">
<DataTable
refetch={refetchPast}
columns={columns}
data={pastMenus ?? []}
columnVisibility={{ updated_at: false }}
/>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
);
}

View File

@@ -0,0 +1,425 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import client from "@/lib/client";
import { getProgressColor, getStatusColor, getStatusIcon, getStatusProgress } from "@/lib/status-progress";
import { OrderStatus, Order } from "@anujs.dev/inventory-types-utils";
import { useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import {
AlertCircle,
Calendar,
CheckCircle2,
ChevronRight,
Clock,
CookingPot,
Package,
Search,
Store,
Truck,
User,
XCircle,
} from "lucide-react";
import Link from "next/link";
import { useState } from "react";
export default function AdminOrdersPage() {
const [searchTerm, setSearchTerm] = useState("");
const [statusFilter, setStatusFilter] = useState<string>("all");
const [foodTypeFilter, setFoodTypeFilter] = useState<string>("all");
const {
data: orders,
isLoading,
error,
} = useQuery<Order[]>({
queryKey: ["admin-orders"],
queryFn: async () => {
const { data } = await client.get("order");
return data;
},
});
const filteredOrders = orders?.filter((order) => {
const matchesSearch =
searchTerm === "" ||
order.id.toLowerCase().includes(searchTerm.toLowerCase()) ||
(order.user?.name &&
order.user.name.toLowerCase().includes(searchTerm.toLowerCase())) ||
(order.kitchen?.name &&
order.kitchen.name.toLowerCase().includes(searchTerm.toLowerCase()));
const matchesStatus =
statusFilter === "all" || order.status === statusFilter;
const matchesFoodType =
foodTypeFilter === "all" || order.foodType === foodTypeFilter;
return matchesSearch && matchesStatus && matchesFoodType;
});
const foodTypes = orders
? [...new Set(orders.map((order) => order.foodType))]
: [];
const orderCounts =
orders?.reduce((acc, order) => {
acc[order.status] = (acc[order.status] || 0) + 1;
return acc;
}, {} as Record<string, number>) || {};
if (isLoading)
return (
<div className="p-6 flex justify-center items-center h-[calc(100vh-100px)]">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading orders...</p>
</div>
</div>
);
if (error)
return (
<div className="p-6 max-w-5xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-4 text-red-700">
<p className="font-medium">Error loading orders</p>
<p className="text-sm mt-1">
Please try refreshing the page or contact support if the problem
persists.
</p>
</div>
</div>
);
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Order Management
</h1>
<p className="text-sm text-gray-500 mt-1">
View and manage all customer orders
</p>
</div>
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-4 mb-6">
<Card className="shadow-sm">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500">Total Orders</p>
<p className="text-2xl font-bold text-emerald-800">
{orders?.length || 0}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center">
<Package className="h-5 w-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="shadow-sm bg-amber-50 border-amber-200">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-amber-600">Pending</p>
<p className="text-2xl font-bold text-amber-800">
{orderCounts["PENDING"] || 0}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-amber-100 flex items-center justify-center">
<AlertCircle className="h-5 w-5 text-amber-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="shadow-sm bg-blue-50 border-blue-200">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-blue-600">Accepted</p>
<p className="text-2xl font-bold text-blue-800">
{orderCounts["ACCEPTED"] || 0}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
<CheckCircle2 className="h-5 w-5 text-blue-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="shadow-sm bg-orange-50 border-orange-200">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-orange-600">Preparing</p>
<p className="text-2xl font-bold text-orange-800">
{orderCounts["PREPARING"] || 0}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-orange-100 flex items-center justify-center">
<CookingPot className="h-5 w-5 text-orange-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="shadow-sm bg-emerald-50 border-emerald-200">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-emerald-600">Completed</p>
<p className="text-2xl font-bold text-emerald-800">
{orderCounts["COMPLETED"] || 0}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center">
<Truck className="h-5 w-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
</div>
<Card className="shadow-sm mb-6">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-lg font-semibold text-emerald-800">
Filter Orders
</CardTitle>
</CardHeader>
<CardContent className="p-4">
<div className="flex flex-col md:flex-row gap-4">
<div className="relative flex-1">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="Search by order ID, customer or kitchen..."
className="pl-9 border-gray-200 focus:ring-emerald-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<div className="flex gap-4">
<Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger className="w-[180px] border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Filter by status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Statuses</SelectItem>
<SelectItem value="PENDING">Pending</SelectItem>
<SelectItem value="ACCEPTED">Accepted</SelectItem>
<SelectItem value="PREPARING">Preparing</SelectItem>
<SelectItem value="COMPLETED">Completed</SelectItem>
<SelectItem value="CANCELLED">Cancelled</SelectItem>
</SelectContent>
</Select>
<Select value={foodTypeFilter} onValueChange={setFoodTypeFilter}>
<SelectTrigger className="w-[180px] border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Filter by food type" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Food Types</SelectItem>
{foodTypes.map((type) => (
<SelectItem key={type} value={type}>
{type}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</CardContent>
</Card>
<div className="space-y-4">
{filteredOrders && filteredOrders.length > 0 ? (
filteredOrders.map((order) => {
const progress = getStatusProgress(order.status);
const statusColor = getStatusColor(order.status);
const progressColor = getProgressColor(order.status);
const statusIcon = getStatusIcon(order.status);
return (
<Link
href={`/d/admin/orders/current/status/${order.id}`}
key={order.id}
className="block"
>
<Card className="shadow-sm hover:shadow-md transition-shadow border-gray-200">
<CardContent className="p-0">
<div className="p-4 border-b border-gray-100">
<div className="flex justify-between items-start">
<div className="flex items-start gap-3">
<div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center mt-1">
<Package className="h-5 w-5 text-emerald-600" />
</div>
<div>
<h2 className="font-semibold text-lg text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</h2>
<div className="flex items-center gap-3 text-sm text-gray-500 mt-1">
<div className="flex items-center">
<Calendar className="h-3.5 w-3.5 mr-1" />
{format(
new Date(order.created_at),
"dd MMM yyyy"
)}
</div>
<div className="flex items-center">
<Clock className="h-3.5 w-3.5 mr-1" />
{format(new Date(order.created_at), "hh:mm a")}
</div>
<div>{order.foodType}</div>
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Badge className={statusColor}>
<span className="flex items-center gap-1">
{statusIcon}
{order.status.charAt(0) +
order.status.slice(1).toLowerCase()}
</span>
</Badge>
<ChevronRight className="h-5 w-5 text-gray-400" />
</div>
</div>
{order.description && (
<div className="mt-3 bg-gray-50 p-3 rounded-md">
<p className="text-sm text-gray-600 italic">
<span className="font-medium">Cook note:</span> "
{order.description}"
</p>
</div>
)}
</div>
<div className="p-4 border-b border-gray-100">
<h3 className="font-medium text-emerald-700 mb-3">
Order Items
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="bg-gray-50 p-3 rounded-md"
>
<h4 className="text-sm font-semibold text-emerald-700 mb-2">
{category}
</h4>
<ul className="space-y-1">
{details.items.map((item, index) => (
<li
key={index}
className="text-sm text-gray-700 flex justify-between"
>
<span>{item.menu}</span>
<span className="font-medium text-amber-600">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
<div className="p-4">
{order.status !== "CANCELLED" && (
<div className="mb-4">
<div className="h-2 bg-gray-100 rounded-full overflow-hidden">
<div
className={`h-2 transition-all ${progressColor}`}
style={{ width: `${progress}%` }}
/>
</div>
<div className="flex justify-between text-xs text-gray-500 mt-1">
<span>Order Placed</span>
<span>Preparing</span>
<span>Completed</span>
</div>
</div>
)}
<div className="flex justify-between items-center text-sm text-gray-600">
<div className="flex items-center">
<User className="h-4 w-4 mr-1.5 text-gray-400" />
<span className="font-medium mr-1">
Customer:
</span>{" "}
{order.user?.name ?? "N/A"}
</div>
<div className="flex items-center">
<Store className="h-4 w-4 mr-1.5 text-gray-400" />
<span className="font-medium mr-1">
Kitchen:
</span>{" "}
{order.kitchen?.name ?? "N/A"}
</div>
</div>
</div>
</CardContent>
</Card>
</Link>
);
})
) : (
<Card className="shadow-sm">
<CardContent className="p-8 text-center">
<div className="mx-auto w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4">
<Package className="h-8 w-8 text-gray-400" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No orders found
</h3>
<p className="text-gray-500 max-w-md mx-auto">
{searchTerm ||
statusFilter !== "all" ||
foodTypeFilter !== "all"
? "Try adjusting your filters to see more results"
: "There are no orders in the system yet"}
</p>
{(searchTerm ||
statusFilter !== "all" ||
foodTypeFilter !== "all") && (
<Button
variant="outline"
className="mt-4 border-gray-200"
onClick={() => {
setSearchTerm("");
setStatusFilter("all");
setFoodTypeFilter("all");
}}
>
Clear Filters
</Button>
)}
</CardContent>
</Card>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,318 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useToast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { getProgressColor, getStatusColor, getStatusProgress } from "@/lib/status-progress";
import { Order, OrderStatus } from "@anujs.dev/inventory-types-utils";
import { useMutation, useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import {
ArrowLeft,
CheckCircle2,
Clock,
RefreshCcw,
Store,
User,
} from "lucide-react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
export default function AdminOrderDetailsPage() {
const { id } = useParams();
const router = useRouter();
const { toast } = useToast();
const [newStatus, setNewStatus] = useState<OrderStatus | "">("");
const {
data: order,
isLoading,
error,
refetch,
} = useQuery<Order>({
queryKey: ["orders", id],
queryFn: async () => {
const { data } = await client.get(`order/${id}`);
return data;
},
refetchInterval: 3e5,
});
const { mutate: updateOrderStatus, isPending: isUpdating } = useMutation({
mutationFn: async (status: OrderStatus) => {
const { data } = await client.patch(`order/${id}/status`, { status });
return data;
},
onSuccess: () => {
toast({
title: "Order status updated successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
refetch();
setNewStatus("");
},
onError: () => {
toast({
title: "Failed to update order status",
description: "Please try again or contact support",
variant: "destructive",
});
},
});
if (isLoading)
return (
<div className="p-6 flex justify-center items-center h-[calc(100vh-100px)]">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading order details...</p>
</div>
</div>
);
if (error)
return (
<div className="p-6 max-w-5xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-4 text-red-700">
<p className="font-medium">Error loading order details</p>
<p className="text-sm mt-1">
Please try refreshing the page or contact support if the problem
persists.
</p>
<Button
variant="outline"
className="mt-4"
onClick={() => router.back()}
>
<ArrowLeft className="mr-2 h-4 w-4" /> Go Back
</Button>
</div>
</div>
);
if (!order)
return (
<div className="p-6 max-w-5xl mx-auto">
<div className="bg-amber-50 border border-amber-200 rounded-md p-4 text-amber-700">
<p className="font-medium">Order not found</p>
<p className="text-sm mt-1">
The requested order could not be found.
</p>
<Button
variant="outline"
className="mt-4"
onClick={() => router.back()}
>
<ArrowLeft className="mr-2 h-4 w-4" /> Go Back
</Button>
</div>
</div>
);
const progress = getStatusProgress(order.status);
const statusColor = getStatusColor(order.status);
const progressColor = getProgressColor(order.status);
return (
<div className="p-6 max-w-5xl mx-auto">
<div className="mb-6">
<Link
href="/d/admin/orders"
className="text-emerald-700 hover:text-emerald-800 flex items-center text-sm font-medium"
>
<ArrowLeft className="mr-2 h-4 w-4" /> Back to Orders
</Link>
</div>
<Card className="shadow-sm border-gray-200">
<CardHeader className="bg-emerald-50 border-b border-gray-200">
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-xl font-bold text-emerald-800">
Order Details
</CardTitle>
<p className="text-sm text-gray-500 mt-1">
ID: {order.id.slice(0, 8).toUpperCase()}
</p>
</div>
<Badge
className={`px-3 py-1 text-sm font-medium capitalize ${statusColor}`}
>
{order.status.toLowerCase()}
</Badge>
</div>
</CardHeader>
<CardContent className="p-6">
{order.status !== "CANCELLED" && (
<div className="mb-6">
<div className="h-2 bg-gray-100 rounded-full overflow-hidden">
<div
className={`h-2 transition-all ${progressColor}`}
style={{ width: `${progress}%` }}
/>
</div>
<div className="flex justify-between text-xs text-gray-500 mt-1">
<span>Order Placed</span>
<span>Accepted</span>
<span>Preparing</span>
<span>Completed</span>
</div>
</div>
)}
{order.description && (
<div className="mb-6 bg-gray-50 p-4 rounded-md border border-gray-100">
<h3 className="font-medium text-sm text-emerald-700 mb-1">
Cook Notes
</h3>
<p className="italic text-sm text-gray-700">
"{order.description}"
</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
<div className="space-y-4">
<h3 className="font-medium text-emerald-700">
Order Information
</h3>
<div className="bg-gray-50 p-4 rounded-md border border-gray-100">
<dl className="grid grid-cols-2 gap-3 text-sm">
<dt className="text-gray-600 font-medium">Date:</dt>
<dd>{format(new Date(order.created_at), "PPpp")}</dd>
<dt className="text-gray-600 font-medium">Meal Type:</dt>
<dd className="capitalize">{order.foodType.toLowerCase()}</dd>
<dt className="text-gray-600 font-medium">Last Updated:</dt>
<dd>{format(new Date(order.updated_at), "PPpp")}</dd>
<dt className="text-gray-600 font-medium">User:</dt>
<dd className="flex items-center">
<User className="h-3.5 w-3.5 mr-1 text-gray-400" />
{order.user?.name ?? "N/A"}
</dd>
<dt className="text-gray-600 font-medium">Kitchen:</dt>
<dd className="flex items-center">
<Store className="h-3.5 w-3.5 mr-1 text-gray-400" />
{order.kitchen?.name ?? "N/A"}
</dd>
</dl>
</div>
</div>
<div className="space-y-4">
<h3 className="font-medium text-emerald-700">Order Status</h3>
<div className="bg-gray-50 p-4 rounded-md border border-gray-100 space-y-4">
<div className="flex items-center gap-2">
<div
className={`h-8 w-8 rounded-full flex items-center justify-center ${
order.isAccepted ? "bg-emerald-100" : "bg-amber-100"
}`}
>
{order.isAccepted ? (
<CheckCircle2 className="h-4 w-4 text-emerald-600" />
) : (
<Clock className="h-4 w-4 text-amber-600" />
)}
</div>
<span className="text-sm font-medium">
{order.isAccepted ? "Order Accepted" : "Pending Acceptance"}
</span>
</div>
<div className="pt-3 border-t border-gray-200">
<h4 className="text-sm font-medium text-gray-700 mb-2">
Update Status
</h4>
</div>
</div>
</div>
</div>
<div className="border-t border-gray-200 pt-6">
<h3 className="text-lg font-medium text-emerald-700 mb-4">
Order Items
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="bg-gray-50 p-4 rounded-md border border-gray-100"
>
<h4 className="text-sm font-semibold text-emerald-700 mb-3">
{category}
</h4>
<ul className="space-y-2">
{details.items.map((item, index) => (
<li
key={index}
className="flex justify-between items-center p-2 bg-white rounded-md border border-gray-100"
>
<span className="text-sm">{item.menu}</span>
<span className="text-sm font-medium text-amber-600">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
<div className="flex justify-between items-center mt-6 pt-4 border-t border-gray-200">
<Button
variant="outline"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh Order Status
</Button>
</div>
</CardContent>
</Card>
{order.ingredientUsageLogs && order.ingredientUsageLogs.length > 0 && (
<Card className="shadow-sm mt-6 border-gray-200">
<CardHeader className="bg-emerald-50 border-b border-gray-200">
<CardTitle className="text-lg font-semibold text-emerald-800">
Ingredient Usage Log
</CardTitle>
</CardHeader>
<CardContent className="p-6 space-y-4">
{order.ingredientUsageLogs.map((log: any) => (
<div
key={log.id}
className="border border-gray-200 rounded-md px-4 py-3 flex flex-col sm:flex-row justify-between sm:items-center hover:bg-gray-50"
>
<div className="space-y-1">
<p className="text-sm font-medium text-emerald-700">
{log.inventory.name}{" "}
<span className="text-gray-600 font-normal">
({log.quantity} {log.inventory.unit})
</span>
</p>
<p className="text-xs text-gray-500">
Used by <span className="font-medium">{log.user.name}</span>{" "}
for {log.description} on{" "}
{format(new Date(log.usedAt), "PPp")}
</p>
</div>
</div>
))}
</CardContent>
</Card>
)}
</div>
);
}

View File

@@ -0,0 +1,315 @@
"use client";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import {
Select,
SelectTrigger,
SelectValue,
SelectContent,
SelectItem,
} from "@/components/ui/select";
import client from "@/lib/client";
import { useMutation, useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import { useToast } from "@/hooks/use-toast";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { ArrowLeft, Clock, Package, RefreshCcw, User } from "lucide-react";
import Link from "next/link";
import { Order } from "@anujs.dev/inventory-types-utils";
export default function CookOrdersPage() {
const router = useRouter();
const { toast } = useToast();
const [selectedKitchens, setSelectedKitchens] = useState<{
[orderId: string]: string;
}>({});
const {
data: orders,
isLoading,
error,
refetch,
} = useQuery<Order[]>({
queryKey: ["all-orders"],
queryFn: async () => {
const { data } = await client.get("order");
return data;
},
refetchInterval: 5000,
});
const { data: kitchens, isLoading: loadingKitchens } = useQuery({
queryKey: ["admin-kitchens"],
queryFn: async () => {
const { data } = await client.get("user/kitchens");
return data;
},
});
const { mutate: assignToKitchen, isPending: isAssigning } = useMutation({
mutationFn: async ({
orderId,
kitchenId,
}: {
orderId: string;
kitchenId: string;
}) => {
return client.patch(`order/${orderId}/accept/${kitchenId}`);
},
onSuccess: () => {
toast({
title: "Order Assigned",
description: "Order successfully assigned to kitchen",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
router.push("/d/admin/orders/current");
},
onError: () => {
toast({
title: "Error",
description: "Assignment failed. Please try again.",
variant: "destructive",
});
},
});
if (isLoading || loadingKitchens) {
return (
<div className="p-6 max-w-6xl mx-auto space-y-4">
<Skeleton className="h-8 w-[200px]" />
{[1, 2, 3].map((i) => (
<Card key={i} className="border-gray-200 shadow-sm">
<CardHeader>
<Skeleton className="h-4 w-[150px]" />
<Skeleton className="h-3 w-[200px]" />
</CardHeader>
<CardContent>
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-full" />
</CardContent>
<CardFooter>
<Skeleton className="h-9 w-[120px]" />
</CardFooter>
</Card>
))}
</div>
);
}
if (error) {
return (
<div className="p-6 max-w-6xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-4 text-red-700">
<p className="font-medium">Failed to load orders</p>
<p className="text-sm mt-1">
Please check your connection and try again
</p>
<Button variant="outline" className="mt-4" onClick={() => refetch()}>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
const pendingOrders = orders?.filter((order) => !order.isAccepted) || [];
return (
<div className="p-6 max-w-6xl mx-auto space-y-6">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2">
<Link
href="/d/admin/orders"
className="text-emerald-700 hover:text-emerald-800 flex items-center text-sm font-medium"
>
<ArrowLeft className="mr-1 h-4 w-4" /> All Orders
</Link>
</div>
<h1 className="text-2xl font-bold text-emerald-800 mt-2">
Pending Orders
</h1>
<p className="text-sm text-gray-500 mt-1">
Assign orders to kitchens for processing
</p>
</div>
<div className="flex items-center gap-3">
<Badge
variant="outline"
className="text-sm bg-amber-50 border-amber-200 text-amber-800 px-3 py-1"
>
<Clock className="mr-1 h-3.5 w-3.5" />
{pendingOrders.length} Pending
</Badge>
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
className="border-gray-200"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</div>
{pendingOrders.length === 0 ? (
<Card className="border-gray-200 shadow-sm">
<CardContent className="flex flex-col items-center justify-center py-12">
<div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
<Package className="h-8 w-8 text-emerald-600" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No pending orders
</h3>
<p className="text-gray-500 max-w-md text-center">
All current orders have been accepted and assigned to kitchens
</p>
<Button
variant="outline"
className="mt-6 border-gray-200"
onClick={() => router.push("/d/admin/orders")}
>
View All Orders
</Button>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{pendingOrders.map((order) => (
<Card
key={order.id}
className="hover:shadow-md transition-shadow border-gray-200 shadow-sm"
>
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</CardTitle>
<CardDescription className="mt-1 text-gray-500">
{format(new Date(order.created_at), "PPpp")}
</CardDescription>
</div>
<Badge className="bg-amber-100 text-amber-800 border-amber-200">
{order.status.toLowerCase()}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4 p-4">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">Meal Type</p>
<p className="font-medium capitalize text-emerald-700">
{order.foodType.toLowerCase()}
</p>
</div>
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">Last Updated</p>
<p className="font-medium text-emerald-700">
{format(new Date(order.updated_at), "PPpp")}
</p>
</div>
<div className="p-3 rounded-md bg-emerald-700">
<p className="text-xs text-gray-200">User</p>
<div className="font-medium text-white flex items-center">
<User className="h-3.5 w-3.5 mr-1 text-gray-200" />
{order.user.name}
</div>
</div>
</div>
<div className="border-t border-gray-100 pt-4">
<p className="text-sm font-medium text-emerald-700 mb-3">
Order Items
</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="border border-gray-200 rounded-lg p-3 bg-gray-50"
>
<p className="font-medium text-sm text-emerald-800 mb-2">
{category}
</p>
<ul className="space-y-1">
{details.items.map((item, index) => (
<li
key={index}
className="flex justify-between text-sm"
>
<span>{item.menu}</span>
<span className="text-amber-600 font-medium">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
<div className="space-y-2 pt-2">
<p className="text-sm font-medium text-emerald-700">
Assign to Kitchen
</p>
<Select
value={selectedKitchens[order.id] || ""}
onValueChange={(val) =>
setSelectedKitchens((prev) => ({
...prev,
[order.id]: val,
}))
}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Choose a kitchen" />
</SelectTrigger>
<SelectContent>
{kitchens?.map((kitchen: any) => (
<SelectItem key={kitchen.id} value={kitchen.id}>
{kitchen.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</CardContent>
<CardFooter className="border-t border-gray-100 pt-4 p-4 bg-gray-50">
<Button
disabled={isAssigning || !selectedKitchens[order.id]}
onClick={() =>
assignToKitchen({
orderId: order.id,
kitchenId: selectedKitchens[order.id],
})
}
className="w-full bg-[#031274] hover:bg-emerald-700"
>
{isAssigning ? "Assigning..." : "Assign to Kitchen"}
</Button>
</CardFooter>
</Card>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,349 @@
"use client";
import AutoForm, { AutoFormSubmit } from "@/components/ui/auto-form";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import { useToast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import { ArrowUpDown, Edit, Key, User } from "lucide-react";
import { useCallback, useState } from "react";
import { z } from "zod";
export const columns: ColumnDef<any>[] = [
{
accessorKey: "name",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="hover:bg-emerald-50 hover:text-emerald-800"
>
Name
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
return (
<div className="font-medium flex items-center">
<User className="mr-2 h-4 w-4 text-emerald-600" />
{row.getValue("name")}
</div>
);
},
},
{
accessorKey: "email",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="hover:bg-emerald-50 hover:text-emerald-800"
>
Email
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
return <div>{row.getValue("email")}</div>;
},
},
{
accessorKey: "phone",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="hover:bg-emerald-50 hover:text-emerald-800"
>
Phone
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
return <div>{row.getValue("phone") || "N/A"}</div>;
},
},
{
accessorKey: "role",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
className="hover:bg-emerald-50 hover:text-emerald-800"
>
Role
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
const role = row.getValue("role") as { name: string };
let badgeClass = "bg-gray-100 text-gray-800 border-gray-200";
switch (role?.name) {
case "Admin":
badgeClass = "bg-purple-100 text-purple-800 border-purple-200";
break;
case "Cook":
badgeClass = "bg-orange-100 text-orange-800 border-orange-200";
break;
case "User":
badgeClass = "bg-blue-100 text-blue-800 border-blue-200";
break;
case "Manager":
badgeClass = "bg-emerald-100 text-emerald-800 border-emerald-200";
break;
}
return <Badge className={badgeClass}>{role?.name || "Unknown"}</Badge>;
},
},
{
accessorKey: "userType",
header: "User Type",
},
{
accessorKey: "info",
header: "Info",
cell: ({ row }) => {
const userType = row.getValue("userType");
const kitchen = row.original.kitchen;
if (!userType && !kitchen) {
return <span className="text-gray-500">N/A</span>;
}
return userType ? (
<Badge className="bg-amber-100 text-amber-800 border-amber-200">
{userType as string}
</Badge>
) : (
kitchen && (
<Badge className="bg-emerald-100 text-emerald-800 border-emerald-200">
{kitchen.name}
</Badge>
)
);
},
},
{
id: "actions",
header: "Actions",
cell: ({ row, table }) => {
const user = row.original;
const [open, setOpen] = useState(false);
const [passwordOpen, setPasswordOpen] = useState(false);
const [password, setPassword] = useState("");
const queryClient = useQueryClient();
const { toast } = useToast();
const { data: userData } = useQuery({
queryKey: ["user", user.id],
queryFn: async () => {
const { data } = await client.get(`user/${user.id}`);
return data;
},
enabled: open,
refetchInterval: false,
});
const processedUserData = userData
? {
name: userData.name,
email: userData.email,
phone: userData.phone,
}
: null;
const [update, setUpdate] = useState(false);
const updateUserSchema = useCallback(
() =>
z.object({
name: z.string().min(3, "Name must be at least 3 characters long"),
email: z.string().email("Invalid email address"),
phone: z
.string()
.min(10, "Phone number must be at least 10 characters long")
.max(10, "Phone number must be 10 characters"),
}),
[]
);
const { mutate: updateUserProfile, isPending: isUpdating } = useMutation({
mutationFn: async (update: any) => {
return client.patch(`user/${user.id}`, update);
},
onSuccess: () => {
toast({
title: "User updated successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
setOpen(false);
queryClient.invalidateQueries({ queryKey: ["users"] });
// @ts-ignore
table.options.meta.refetch();
},
onError: () => {
toast({
title: "Failed to update user",
description: "Please check the data and try again",
variant: "destructive",
});
},
});
const { mutate: updatePassword, isPending: isUpdatingPassword } =
useMutation({
mutationFn: async (data: { password: string }) => {
return client.patch(`user/${user.id}/pwd`, data);
},
onSuccess: () => {
toast({
title: "Password updated successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
setPassword("");
setPasswordOpen(false);
},
onError: () => {
toast({
title: "Failed to update password",
description: "Please try again or contact support",
variant: "destructive",
});
},
});
const { mutate: deleteUser, isPending: isDeleting } = useMutation({
mutationFn: async () => {
return client.delete(`user/${user.id}`);
},
onSuccess: () => {
toast({
title: "User deleted successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
queryClient.invalidateQueries({ queryKey: ["users"] });
},
onError: () => {
toast({
title: "Failed to delete user",
description:
"This user may have associated data or you don't have permission",
variant: "destructive",
});
},
});
return (
<div className="flex items-center gap-2 justify-center">
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button
size="icon"
variant="outline"
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Edit className="h-4 w-4" />
<span className="sr-only">Edit</span>
</Button>
</SheetTrigger>
<SheetContent>
<SheetHeader>
<SheetTitle className="text-emerald-800">Edit User</SheetTitle>
</SheetHeader>
{processedUserData && (
<AutoForm
formSchema={updateUserSchema()}
values={processedUserData}
onValuesChange={() => setUpdate(true)}
onSubmit={(values) => updateUserProfile(values)}
className="mt-4 space-y-4"
>
<AutoFormSubmit
disabled={!update || isUpdating}
className="w-full bg-[#031274] hover:bg-emerald-700 text-white"
>
{isUpdating ? "Updating..." : "Update User"}
</AutoFormSubmit>
</AutoForm>
)}
</SheetContent>
</Sheet>
<Dialog open={passwordOpen} onOpenChange={setPasswordOpen}>
<DialogTrigger asChild>
<Button
size="icon"
variant="outline"
className="border-gray-200 bg-blue-50 text-blue-700 hover:bg-blue-100 hover:text-blue-800"
>
<Key className="h-4 w-4" />
<span className="sr-only">Change Password</span>
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle className="text-blue-800">
Update Password
</DialogTitle>
</DialogHeader>
<form
onSubmit={(e) => {
e.preventDefault();
updatePassword({ password });
}}
className="space-y-4 pt-2"
>
<Input
type="password"
required
minLength={8}
placeholder="Enter new password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="border-gray-200 focus:ring-blue-500"
/>
<Button
type="submit"
disabled={password.length < 8 || isUpdatingPassword}
className="w-full bg-blue-600 hover:bg-blue-700"
>
{isUpdatingPassword ? "Updating..." : "Update Password"}
</Button>
</form>
</DialogContent>
</Dialog>
</div>
);
},
},
];

View File

@@ -0,0 +1,329 @@
"use client";
import { columns } from "./columns";
import { useMutation, useQueries } from "@tanstack/react-query";
import client from "@/lib/client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogHeader,
DialogContent,
DialogTrigger,
DialogTitle,
} from "@/components/ui/dialog";
import { z } from "zod";
import AutoForm, { AutoFormSubmit } from "@/components/ui/auto-form";
import { useCallback, useState } from "react";
import { DependencyType } from "@/components/ui/auto-form/types";
import { useToast } from "@/hooks/use-toast";
import { DataTable } from "@/components/data-table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Plus, RefreshCcw, Search, Users } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
function findUserByName(
items: {
id: string;
name: string;
}[],
name: string
): string | undefined {
return items?.find((item) => item.name === name)?.id;
}
export default function UsersPage() {
const [open, setOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const { toast } = useToast();
const [
{ data: users, refetch, isLoading: isLoadingUsers, isError: isErrorUsers },
{ data: roles, isLoading: isLoadingRoles, isError: isErrorRoles },
{ data: kitchens, isLoading: isLoadingKitchens, isError: isErrorKitchens },
] = useQueries({
queries: [
{
queryKey: ["users"],
queryFn: async () => {
const { data } = await client.get("user");
return data;
},
},
{
queryKey: ["roles"],
queryFn: async () => {
const { data } = await client.get("user/roles");
return data;
},
refetchInterval: false,
},
{
queryKey: ["kitchens"],
queryFn: async () => {
const { data } = await client.get("user/kitchens");
return data;
},
refetchInterval: false,
},
],
});
const { mutate: createUser, isPending: isCreating } = useMutation({
mutationFn: async (values: any) => {
const { data } = await client.post("user", {
...values,
roleId: findUserByName(roles, values.role),
kitchenId: findUserByName(kitchens, values.kitchen),
});
return data;
},
onSuccess: () => {
refetch();
toast({
title: "User created successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
setOpen(false);
},
onError: (error) => {
toast({
title: "Failed to create user",
description: "Please check the form and try again",
variant: "destructive",
});
},
});
function onSubmit(values: any) {
createUser(values);
}
const createUserSchema = useCallback(
() =>
z.object({
name: z.string().min(3, "Name must be at least 3 characters long"),
email: z.string().email("Invalid email address"),
phone: z
.string()
.min(10, "Phone number must be at least 10 characters long")
.max(10, "Phone number must be 10 digits"),
password: z
.string()
.min(8, "Password must be at least 8 characters long"),
role: z.enum(
roles == undefined
? [""]
: roles?.map((role: { name: string }) => role.name)
),
kitchen: z
.enum(
kitchens == undefined
? [""]
: kitchens?.map((kitchen: { name: string }) => kitchen.name)
)
.optional(),
userType: z.enum(["Jains", "Dasas", "Staff"]).optional(),
}),
[kitchens, roles]
);
const isLoading = isLoadingUsers || isLoadingRoles || isLoadingKitchens;
const isError = isErrorUsers || isErrorRoles || isErrorKitchens;
const filteredUsers =
searchTerm && users
? users.filter(
(user: any) =>
user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
(user.phone && user.phone.includes(searchTerm)) ||
(user.role &&
user.role.name.toLowerCase().includes(searchTerm.toLowerCase()))
)
: users;
if (isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<Skeleton className="h-8 w-[200px] mb-4" />
<Skeleton className="h-4 w-[200px] mb-6" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[200px]" />
<div className="flex gap-2">
<Skeleton className="h-9 w-[120px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[400px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading user data...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Manage Users
</h1>
<p className="text-sm text-gray-500 mb-6">
Add, edit, and manage user accounts
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load user data
</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the user information
</p>
<Button
onClick={() => refetch()}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">Manage Users</h1>
<p className="text-sm text-gray-500 mt-1">
Add, edit, and manage user accounts
</p>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-[#031274] hover:bg-emerald-700 text-white">
<Plus className="mr-2 h-4 w-4" /> Add User
</Button>
</DialogTrigger>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="text-emerald-800">
Add New User
</DialogTitle>
</DialogHeader>
<AutoForm
fieldConfig={{
role: {
description: "Select the user's role in the system",
},
kitchen: {
description: "Required for users with Cook role",
},
userType: {
label: "User Type",
description: "Required for users with User role",
},
password: {
inputProps: {
type: "password",
},
},
}}
dependencies={[
{
sourceField: "role",
targetField: "kitchen",
type: DependencyType.HIDES,
when: (sourceFieldValue) => {
return sourceFieldValue !== "Cook";
},
},
{
sourceField: "role",
targetField: "userType",
type: DependencyType.HIDES,
when: (sourceFieldValue) => {
return sourceFieldValue !== "User";
},
},
]}
onSubmit={onSubmit}
formSchema={createUserSchema()}
className="space-y-4"
>
<AutoFormSubmit className="w-full bg-[#031274] hover:bg-emerald-700 text-white">
{isCreating ? "Creating..." : "Add User"}
</AutoFormSubmit>
</AutoForm>
</DialogContent>
</Dialog>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<Users className="mr-2 h-5 w-5 text-emerald-600" />
User Accounts
</CardTitle>
<div className="flex items-center gap-3">
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="Search users..."
className="pl-9 max-w-xs h-9 border-gray-200 focus:ring-emerald-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{filteredUsers && filteredUsers.length > 0 ? (
<DataTable
refetch={refetch}
columns={columns}
data={filteredUsers}
/>
) : (
<div className="text-center py-12">
<p className="text-gray-500">
{searchTerm
? `No users matching "${searchTerm}" found`
: "No users found in the system"}
</p>
{searchTerm && (
<Button
variant="outline"
className="mt-4 border-gray-200"
onClick={() => setSearchTerm("")}
>
Clear Search
</Button>
)}
</div>
)}
</CardContent>
</Card>
</div>
);
}

61
src/app/d/admin/vendors/columns.tsx vendored Normal file
View File

@@ -0,0 +1,61 @@
import { Button } from "@/components/ui/button";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import { Vendor } from "@anujs.dev/inventory-types-utils/dist/types/vendor";
import { useQuery } from "@tanstack/react-query";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import { Edit } from "lucide-react";
export const columns: ColumnDef<Vendor>[] = [
{
header: "Added On",
accessorKey: "created_at",
cell: ({ row }) => {
return <span>{format(row.original.created_at, "dd MMM yyyy")}</span>;
},
enableSorting: true,
},
{
header: "Name",
accessorKey: "name",
},
{
header: "Store",
accessorKey: "store_name",
},
{
header: "Phone",
accessorKey: "phone_number",
},
{
header: "State",
accessorKey: "state",
},
{
header: "Actions",
cell: ({ row }) => {
const { data } = useQuery({
queryKey: ["vendor", row.original.id],
});
return (
<Sheet>
<SheetTrigger asChild>
<Button size={"icon"} variant={"outline"}>
<Edit />
</Button>
</SheetTrigger>
<SheetContent>
<SheetHeader>
<SheetTitle>Edit Vendor</SheetTitle>
</SheetHeader>
</SheetContent>
</Sheet>
);
},
},
];

80
src/app/d/admin/vendors/data-table.tsx vendored Normal file
View File

@@ -0,0 +1,80 @@
import {
ColumnDef,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
}
export function DataTable<TData, TValue>({
columns,
data,
}: DataTableProps<TData, TValue>) {
const table = useReactTable({
initialState: {
columnVisibility: {
id: false,
},
},
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{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}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{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>
);
}

645
src/app/d/admin/vendors/page.tsx vendored Normal file
View File

@@ -0,0 +1,645 @@
"use client";
import { useMutation, useQuery } from "@tanstack/react-query";
import client from "@/lib/client";
import { Button, buttonVariants } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogOverlay,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { z } from "zod";
import AutoForm, { AutoFormSubmit } from "@/components/ui/auto-form";
import { useToast } from "@/hooks/use-toast";
import { useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Edit2Icon,
Plus,
Search,
Store,
User,
FileText,
Phone,
Mail,
MapPin,
Building,
CreditCard,
Landmark,
} from "lucide-react";
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { format } from "date-fns";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Vendor } from "@anujs.dev/inventory-types-utils/dist/types/vendor";
const vendorSchema = z.object({
name: z.string().min(1, { message: "Name cannot be empty" }),
store_name: z.string().min(1, { message: "Store name cannot be empty" }),
phone_number: z
.string()
.regex(/^\d{10}$/, { message: "Phone number must be exactly 10 digits" }),
gstin: z.string().optional(),
email: z.string().email().optional(),
address: z.string().optional(),
city: z.string().optional(),
state: z.string().optional(),
pincode: z.coerce.number().optional(),
vendor_code: z.string().optional(),
bank_name: z.string().optional(),
account_number: z.coerce.number().optional(),
ifsc_code: z.string().optional(),
branch_name: z.string().optional(),
});
type VendorFormSchema = z.infer<typeof vendorSchema>;
export default function VendorsPage() {
const [open, setOpen] = useState(false);
const [selected, setSelected] = useState<Vendor>();
const [search, setSearch] = useState("");
const [openEdit, setOpenEdit] = useState(false);
const [filteredData, setFilteredData] = useState<Vendor[]>();
const { toast } = useToast();
const { data: vendors, refetch } = useQuery<Vendor[]>({
queryKey: ["vendors", "with inward"],
queryFn: async () => {
const { data } = await client.get("vendor?inwards=true");
return data;
},
});
const { mutate: addVendor } = useMutation({
mutationFn: async (vendor: VendorFormSchema) => {
const { data } = await client.post("vendor", vendor);
return data;
},
onSuccess: () => {
toast({
title: "Vendor added successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
setOpen(false);
refetch();
},
});
const { mutate: updateVendor } = useMutation({
mutationFn: async (vendor: VendorFormSchema) => {
const { data } = await client.patch(`vendor/${selected?.id}`, vendor);
return data;
},
onSuccess: (data) => {
toast({
title: "Vendor updated successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
refetch();
setSelected(data);
setOpenEdit(false);
},
});
useEffect(() => {
if (search !== "") {
const filteredVendors = vendors?.filter(
(vendor) =>
vendor.name.toLowerCase().includes(search.toLowerCase()) ||
vendor.store_name.toLowerCase().includes(search.toLowerCase())
);
setFilteredData(filteredVendors);
} else {
setFilteredData(vendors);
}
}, [search, vendors]);
function onSubmit(values: VendorFormSchema) {
addVendor(values);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex items-center justify-between mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Manage Vendors
</h1>
<p className="text-sm text-gray-500 mt-1">
Add, edit and manage your vendor information
</p>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button className="bg-[#031274] hover:bg-emerald-700 text-white">
<Plus className="mr-2 h-4 w-4" /> Add Vendor
</Button>
</DialogTrigger>
<DialogOverlay />
<DialogContent className="max-h-[90vh] overflow-auto">
<DialogHeader>
<DialogTitle className="text-xl text-emerald-800">
Add New Vendor
</DialogTitle>
</DialogHeader>
<AutoForm
className="space-y-4"
fieldConfig={{
store_name: {
label: "Store name",
description: "The name of the vendor's store",
},
phone_number: {
label: "Phone number",
description: "10-digit phone number",
},
vendor_code: {
label: "Vendor code",
description: "Unique identifier for this vendor",
},
gstin: {
label: "GSTIN",
description: "GST Identification Number",
},
ifsc_code: {
label: "IFSC Code",
description: "Bank IFSC code",
},
branch_name: {
label: "Branch Name",
description: "Bank branch name",
},
account_number: {
label: "Account Number",
description: "Bank account number",
},
bank_name: {
label: "Bank Name",
description: "Name of the bank",
},
}}
onSubmit={onSubmit}
formSchema={vendorSchema}
>
<AutoFormSubmit className="w-full bg-[#031274] hover:bg-emerald-700">
Add Vendor
</AutoFormSubmit>
</AutoForm>
</DialogContent>
</Dialog>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<Card className="md:col-span-1 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<Store className="h-5 w-5 mr-2 text-emerald-600" />
Vendor Directory
</CardTitle>
<div className="relative mt-2">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value ?? "")}
placeholder="Search vendors..."
className="pl-9 border-gray-200 focus:ring-emerald-500"
/>
</div>
</CardHeader>
<CardContent className="p-0">
<ScrollArea className="h-[calc(100vh-280px)]">
{filteredData && filteredData.length > 0 ? (
<div className="divide-y divide-gray-100">
{filteredData.map((vendor: Vendor) => (
<div
onClick={() => {
if (selected?.id !== vendor.id) {
setSelected(vendor);
}
}}
className={`p-4 hover:bg-emerald-50 transition-colors cursor-pointer ${
selected?.id === vendor.id
? "bg-emerald-50 border-l-4 border-emerald-600"
: ""
}`}
key={vendor.id}
>
<h3 className="font-medium text-emerald-800">
{vendor.store_name}
</h3>
<div className="flex items-center mt-1 text-sm text-gray-500">
<User className="h-3.5 w-3.5 mr-1" />
{vendor.name}
</div>
{vendor.phone_number && (
<div className="flex items-center mt-1 text-sm text-gray-500">
<Phone className="h-3.5 w-3.5 mr-1" />
{vendor.phone_number}
</div>
)}
</div>
))}
</div>
) : (
<div className="p-8 text-center text-gray-500">
{search ? "No vendors match your search" : "No vendors found"}
</div>
)}
</ScrollArea>
</CardContent>
</Card>
{selected ? (
<Card className="md:col-span-2 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800">
{selected.store_name}
</CardTitle>
<Sheet open={openEdit} onOpenChange={setOpenEdit}>
<SheetTrigger asChild>
<Button
variant="outline"
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Edit2Icon className="h-4 w-4 mr-2" /> Edit Vendor
</Button>
</SheetTrigger>
<SheetContent className="w-[400px] sm:max-w-md overflow-auto">
<SheetHeader className="pb-4">
<SheetTitle className="text-emerald-800">
Edit {selected.store_name}
</SheetTitle>
</SheetHeader>
<AutoForm
className="space-y-4"
formSchema={vendorSchema}
// @ts-ignore
values={selected}
onSubmit={(values) => {
updateVendor(values);
}}
>
<AutoFormSubmit className="w-full bg-[#031274] hover:bg-emerald-700">
Update Vendor
</AutoFormSubmit>
</AutoForm>
</SheetContent>
</Sheet>
</div>
</CardHeader>
<CardContent className="p-0">
<Tabs defaultValue="details" className="w-full">
<TabsList className="w-full justify-start rounded-none border-b bg-transparent p-0">
<TabsTrigger
value="details"
className="rounded-none border-b-2 border-transparent px-4 py-3 data-[state=active]:border-emerald-600 data-[state=active]:bg-transparent data-[state=active]:shadow-none"
>
Vendor Details
</TabsTrigger>
<TabsTrigger
value="inwards"
className="rounded-none border-b-2 border-transparent px-4 py-3 data-[state=active]:border-emerald-600 data-[state=active]:bg-transparent data-[state=active]:shadow-none"
>
Inward History
</TabsTrigger>
</TabsList>
<TabsContent value="details" className="p-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-medium text-gray-500">
Contact Information
</h3>
<div className="bg-gray-50 p-4 rounded-md space-y-3">
<div className="flex items-start">
<User className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.name}
</div>
<div className="text-xs text-gray-500">
Contact Person
</div>
</div>
</div>
{selected.phone_number && (
<div className="flex items-start">
<Phone className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.phone_number}
</div>
<div className="text-xs text-gray-500">
Phone Number
</div>
</div>
</div>
)}
{selected.email && (
<div className="flex items-start">
<Mail className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.email}
</div>
<div className="text-xs text-gray-500">
Email
</div>
</div>
</div>
)}
</div>
</div>
{(selected.address ||
selected.city ||
selected.state ||
selected.pincode) && (
<div className="space-y-1">
<h3 className="text-sm font-medium text-gray-500">
Address
</h3>
<div className="bg-gray-50 p-4 rounded-md space-y-3">
{selected.address && (
<div className="flex items-start">
<MapPin className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.address}
</div>
<div className="text-xs text-gray-500">
Street Address
</div>
</div>
</div>
)}
{(selected.city ||
selected.state ||
selected.pincode) && (
<div className="flex items-start">
<Building className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{[
selected.city,
selected.state,
selected.pincode,
]
.filter(Boolean)
.join(", ")}
</div>
<div className="text-xs text-gray-500">
City, State, Pincode
</div>
</div>
</div>
)}
</div>
</div>
)}
</div>
<div className="space-y-4">
{selected.vendor_code && (
<div className="space-y-1">
<h3 className="text-sm font-medium text-gray-500">
Business Information
</h3>
<div className="bg-gray-50 p-4 rounded-md space-y-3">
<div className="flex items-start">
<Store className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.store_name}
</div>
<div className="text-xs text-gray-500">
Store Name
</div>
</div>
</div>
{selected.vendor_code && (
<div className="flex items-start">
<FileText className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.vendor_code}
</div>
<div className="text-xs text-gray-500">
Vendor Code
</div>
</div>
</div>
)}
{selected.gstin && (
<div className="flex items-start">
<FileText className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.gstin}
</div>
<div className="text-xs text-gray-500">
GSTIN
</div>
</div>
</div>
)}
</div>
</div>
)}
{(selected.bank_name ||
selected.account_number ||
selected.ifsc_code ||
selected.branch_name) && (
<div className="space-y-1">
<h3 className="text-sm font-medium text-gray-500">
Banking Details
</h3>
<div className="bg-gray-50 p-4 rounded-md space-y-3">
{selected.bank_name && (
<div className="flex items-start">
<Landmark className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.bank_name}
</div>
<div className="text-xs text-gray-500">
Bank Name
</div>
</div>
</div>
)}
{selected.account_number && (
<div className="flex items-start">
<CreditCard className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{selected.account_number}
</div>
<div className="text-xs text-gray-500">
Account Number
</div>
</div>
</div>
)}
{(selected.ifsc_code || selected.branch_name) && (
<div className="flex items-start">
<Landmark className="h-4 w-4 mt-0.5 mr-2 text-emerald-600" />
<div>
<div className="text-sm font-medium">
{[selected.ifsc_code, selected.branch_name]
.filter(Boolean)
.join(" - ")}
</div>
<div className="text-xs text-gray-500">
IFSC Code - Branch
</div>
</div>
</div>
)}
</div>
</div>
)}
</div>
</div>
</TabsContent>
<TabsContent value="inwards" className="p-0">
<div className="p-6">
<h3 className="text-lg font-medium text-emerald-800 mb-4">
Inward History
</h3>
{selected.inwards && selected.inwards.length > 0 ? (
<div className="border border-gray-200 rounded-md overflow-hidden">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="text-emerald-700 font-medium">
Date
</TableHead>
<TableHead className="text-emerald-700 font-medium">
Bill No
</TableHead>
<TableHead className="text-emerald-700 font-medium">
Payment Status
</TableHead>
<TableHead className="text-emerald-700 font-medium text-right">
Actions
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{selected.inwards
.sort(
(a, b) =>
// @ts-ignore
new Date(b.date).getTime() -
// @ts-ignore
new Date(a.date).getTime()
)
.map((inward: Record<string, any>) => {
return (
<TableRow
key={inward.id}
className="hover:bg-emerald-50"
>
<TableCell className="font-medium">
{format(
new Date(inward.date),
"dd MMM yyyy"
)}
</TableCell>
<TableCell>{inward.bill_no}</TableCell>
<TableCell>
<Badge
variant={
inward.payment_status === "PAID"
? "success"
: inward.payment_status ===
"PENDING"
? "warning"
: "default"
}
>
{inward.payment_status || "N/A"}
</Badge>
</TableCell>
<TableCell className="text-right">
<Link
href={`/d/admin/inventory/inward/${inward.id}`}
className={buttonVariants({
variant: "outline",
size: "sm",
className:
"border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",
})}
>
View Details
</Link>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
) : (
<div className="text-center p-8 bg-gray-50 rounded-md border border-gray-200">
<p className="text-gray-500">
No inward entries found for this vendor
</p>
</div>
)}
</div>
</TabsContent>
</Tabs>
</CardContent>
</Card>
) : (
<Card className="md:col-span-2 shadow-sm">
<CardContent className="flex items-center justify-center h-[calc(100vh-280px)]">
<div className="text-center p-8">
<Store className="h-12 w-12 mx-auto text-gray-300 mb-4" />
<h3 className="text-lg font-medium text-gray-700 mb-2">
No Vendor Selected
</h3>
<p className="text-gray-500 max-w-md">
Select a vendor from the list to view their details, or add a
new vendor using the "Add Vendor" button.
</p>
</div>
</CardContent>
</Card>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,511 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { format } from "date-fns";
import { useParams, useRouter } from "next/navigation";
import { useEffect } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { z } from "zod";
import client from "@/lib/client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import {
ArrowLeft,
FileText,
Plus,
RefreshCcw,
Trash2,
User,
} from "lucide-react";
import Link from "next/link";
import { KitchenInventory, Order, OrderStatus } from "@anujs.dev/inventory-types-utils";
const formSchema = z.object({
status: z.nativeEnum(OrderStatus),
description: z.string().optional(),
usedIngredients: z
.array(
z.object({
inventoryId: z.string().min(1, "Select inventory item"),
quantity: z.coerce.number().gt(0, "Quantity must be greater than 0"),
description: z.string().optional(),
})
)
.optional(),
});
type FormData = z.infer<typeof formSchema>;
export default function CookUpdateOrderPage() {
const router = useRouter();
const queryClient = useQueryClient();
const { id } = useParams();
const { toast } = useToast();
const {
data: order,
isLoading,
error,
refetch,
} = useQuery<Order>({
queryKey: ["order", id],
queryFn: async () => {
const { data } = await client.get(`/order/${id}`);
return data;
},
});
const { data: inventoryList, isLoading: loadingInventory } = useQuery({
queryKey: ["kitchen-inventory"],
queryFn: async () => {
const { data } = await client.get("/kitchen-inventory/me");
return data;
},
});
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
status: OrderStatus.PREPARING,
description: "",
usedIngredients: [],
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "usedIngredients",
});
useEffect(() => {
if (order) {
form.reset({
status: order.status,
description: order.description ?? "",
usedIngredients: [],
});
}
}, [order, form]);
const { mutate, isPending } = useMutation({
mutationFn: async (data: FormData) => {
await client.patch(`/order/${id}/progress`, data);
},
onSuccess: () => {
toast({
title: "Order updated successfully",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
queryClient.invalidateQueries({ queryKey: ["accepted-orders"] });
refetch();
},
onError: (err) => {
toast({
title: "Failed to update order",
variant: "destructive",
});
},
});
function getStatusColor(status: OrderStatus) {
switch (status) {
case OrderStatus.PENDING:
return "bg-amber-100 text-amber-800 border-amber-200";
case OrderStatus.ACCEPTED:
return "bg-blue-100 text-blue-800 border-blue-200";
case OrderStatus.PREPARING:
return "bg-orange-100 text-orange-800 border-orange-200";
case OrderStatus.COMPLETED:
return "bg-emerald-100 text-emerald-800 border-emerald-200";
case OrderStatus.CANCELLED:
return "bg-red-100 text-red-800 border-red-200";
default:
return "bg-gray-100 text-gray-800 border-gray-200";
}
}
if (isLoading || loadingInventory) {
return (
<div className="p-6 max-w-3xl mx-auto">
<div className="mb-6">
<Skeleton className="h-8 w-[200px]" />
<Skeleton className="h-4 w-[300px] mt-2" />
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<Skeleton className="h-5 w-[150px]" />
</CardHeader>
<CardContent className="p-6">
<div className="space-y-6">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-24 w-full" />
<Skeleton className="h-40 w-full" />
</div>
</CardContent>
<CardFooter className="border-t border-gray-100 p-4">
<Skeleton className="h-9 w-[120px] ml-auto" />
</CardFooter>
</Card>
</div>
);
}
if (!order || error) {
return (
<div className="p-6 max-w-3xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">Failed to load order</p>
<p className="text-sm text-red-600 mb-4">
Please try refreshing the page or contact support if the problem
persists.
</p>
<div className="flex justify-center gap-3">
<Button
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
onClick={() => router.back()}
>
<ArrowLeft className="mr-2 h-4 w-4" /> Go Back
</Button>
<Button
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
onClick={() => refetch()}
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
</div>
);
}
const readonly =
order.status === OrderStatus.COMPLETED ||
order.status === OrderStatus.CANCELLED;
return (
<div className="p-6 max-w-3xl mx-auto space-y-6">
<div className="mb-6">
<Link
href="/d/cook/accepted-orders"
className="text-emerald-700 hover:text-emerald-800 flex items-center text-sm font-medium"
>
<ArrowLeft className="mr-2 h-4 w-4" /> Back to Accepted Orders
</Link>
<h1 className="text-2xl font-bold text-emerald-800 mt-2">
Update Order
</h1>
<p className="text-sm text-gray-500 mt-1">
Order #{order.id.slice(0, 8).toUpperCase()} {" "}
{format(new Date(order.created_at), "PPpp")}
</p>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-center">
<div>
<CardTitle className="text-lg font-semibold text-emerald-800">
Order Details
</CardTitle>
<CardDescription className="text-gray-500">
Update the status and track ingredients used
</CardDescription>
</div>
<Badge className={getStatusColor(order.status)}>
{order.status.charAt(0) + order.status.slice(1).toLowerCase()}
</Badge>
</div>
</CardHeader>
<CardContent className="p-6">
<form
onSubmit={form.handleSubmit((data) => mutate(data))}
className="space-y-6"
>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 bg-gray-50 p-4 rounded-md border border-gray-100">
<div className="space-y-1">
<p className="text-xs font-medium text-gray-500">Meal Type</p>
<p className="font-medium capitalize text-emerald-700">
{order.foodType.toLowerCase()}
</p>
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-gray-500">User</p>
<div className="font-medium text-emerald-700 flex items-center">
<User className="h-3.5 w-3.5 mr-1 text-gray-400" />
{order.user?.name}
</div>
</div>
<div className="space-y-1">
<p className="text-xs font-medium text-gray-500">
Last Updated
</p>
<p className="font-medium text-emerald-700">
{format(new Date(order.updated_at), "PPpp")}
</p>
</div>
</div>
<div className="space-y-3">
<Label className="text-sm font-medium text-emerald-700">
Order Items
</Label>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="border border-gray-200 rounded-lg p-3 bg-gray-50"
>
<p className="font-medium text-sm text-emerald-800 mb-2">
{category}
</p>
<ul className="space-y-1">
{details.items.map((item, index) => (
<li
key={index}
className="flex justify-between text-sm"
>
<span>{item.menu}</span>
<span className="text-amber-600 font-medium">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
<div className="space-y-2">
<Label
htmlFor="status"
className="text-sm font-medium text-emerald-700"
>
Order Status
</Label>
<Select
value={form.watch("status")}
disabled={readonly}
onValueChange={(value) =>
form.setValue("status", value as OrderStatus)
}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent>
{Object.values(OrderStatus).map((status) => (
<SelectItem key={status} value={status}>
{status.charAt(0) + status.slice(1).toLowerCase()}
</SelectItem>
))}
</SelectContent>
</Select>
{readonly && (
<p className="text-xs text-amber-600 italic">
This order is {order.status.toLowerCase()} and cannot be
modified
</p>
)}
</div>
<div className="space-y-2">
<Label
htmlFor="description"
className="text-sm font-medium text-emerald-700"
>
Cook Notes
</Label>
<Textarea
placeholder="e.g. Heating oil, waiting for delivery..."
className="min-h-[80px] border-gray-200 focus:ring-emerald-500"
disabled={readonly}
{...form.register("description")}
/>
</div>
<div className="space-y-3">
<div className="flex justify-between items-center">
<Label className="text-sm font-medium text-emerald-700">
Ingredients Used
</Label>
<Button
type="button"
variant="outline"
size="sm"
disabled={readonly}
onClick={() => append({ inventoryId: "", quantity: 1 })}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Plus className="mr-2 h-4 w-4" /> Add Ingredient
</Button>
</div>
{fields.length === 0 && (
<p className="text-sm text-gray-500 italic bg-gray-50 p-3 rounded-md border border-gray-200">
No ingredients added yet. Click "Add Ingredient" to track
inventory usage.
</p>
)}
<div className="space-y-4">
{fields.map((field, index) => (
<div
key={field.id}
className="border border-gray-200 p-4 rounded-lg space-y-4 bg-gray-50"
>
<div className="grid grid-cols-12 gap-4">
<div className="col-span-12 md:col-span-5">
<Label className="text-xs text-gray-500">
Inventory Item
</Label>
<Select
value={form.watch(
`usedIngredients.${index}.inventoryId`
)}
onValueChange={(value) =>
form.setValue(
`usedIngredients.${index}.inventoryId`,
value
)
}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Select item" />
</SelectTrigger>
<SelectContent>
{inventoryList?.map((item: KitchenInventory) => (
<SelectItem
key={item.id}
value={item.inventory.id}
>
{item.inventory.name} (Stock: {item.stock}{" "}
{item.unit})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="col-span-6 md:col-span-3">
<Label className="text-xs text-gray-500">
Quantity
</Label>
<Input
type="number"
step={0.01}
className="border-gray-200 focus:ring-emerald-500"
{...form.register(
`usedIngredients.${index}.quantity`
)}
/>
</div>
<div className="col-span-6 md:col-span-4 flex items-end">
<Button
disabled={readonly}
type="button"
variant="outline"
size="sm"
className="w-full border-red-200 text-red-700 hover:bg-red-50 hover:text-red-800"
onClick={() => remove(index)}
>
<Trash2 className="mr-2 h-4 w-4" /> Remove
</Button>
</div>
</div>
<div>
<Label className="text-xs text-gray-500">
Usage Description
</Label>
<Textarea
disabled={readonly}
placeholder="e.g. Used for marination"
className="border-gray-200 focus:ring-emerald-500"
{...form.register(
`usedIngredients.${index}.description`
)}
/>
</div>
</div>
))}
</div>
</div>
<div className="flex justify-end pt-4 border-t border-gray-100">
<Button
type="submit"
disabled={isPending || readonly}
className="bg-emerald-600 hover:bg-emerald-700"
>
{isPending ? "Saving..." : "Update Order"}
</Button>
</div>
</form>
</CardContent>
</Card>
{order.ingredientUsageLogs && order.ingredientUsageLogs.length > 0 && (
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<FileText className="mr-2 h-5 w-5 text-emerald-600" />
Ingredient Usage Log
</CardTitle>
</CardHeader>
<CardContent className="p-6 space-y-4">
{order.ingredientUsageLogs.map((log: any) => (
<div
key={log.id}
className="border border-gray-200 rounded-md px-4 py-3 flex flex-col sm:flex-row justify-between sm:items-center hover:bg-gray-50"
>
<div className="space-y-1">
<p className="text-sm font-medium text-emerald-700">
{log.inventory.name}{" "}
<span className="text-gray-600 font-normal">
({log.quantity} {log.inventory.unit})
</span>
</p>
<p className="text-xs text-gray-500">
Used by <span className="font-medium">{log.user.name}</span>{" "}
for {log.description} on{" "}
{format(new Date(log.usedAt), "PPp")}
</p>
</div>
</div>
))}
</CardContent>
</Card>
)}
</div>
);
}

View File

@@ -0,0 +1,241 @@
"use client";
import { Button } from "@/components/ui/button";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import client from "@/lib/client";
import { useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import { useToast } from "@/hooks/use-toast";
import Link from "next/link";
import { ChefHat, Clock, Package, RefreshCcw, User } from "lucide-react";
import { Order } from "@anujs.dev/inventory-types-utils";
export default function CookAcceptedOrdersPage() {
const { toast } = useToast();
const {
data: orders,
isLoading,
error,
refetch,
} = useQuery<Order[]>({
queryKey: ["accepted-orders"],
queryFn: async () => {
const { data } = await client.get(`order/accepted`);
return data;
},
refetchInterval: 5000,
});
if (isLoading) {
return (
<div className="p-6 max-w-6xl mx-auto space-y-4">
<Skeleton className="h-8 w-[200px]" />
<div className="grid gap-4">
{[1, 2, 3].map((i) => (
<Card key={i} className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<Skeleton className="h-4 w-[150px]" />
<Skeleton className="h-3 w-[200px]" />
</CardHeader>
<CardContent className="p-4">
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-full" />
</CardContent>
<CardFooter className="border-t border-gray-100 p-4">
<Skeleton className="h-9 w-[120px]" />
</CardFooter>
</Card>
))}
</div>
</div>
);
}
if (error) {
return (
<div className="p-6 max-w-6xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">Failed to load orders</p>
<p className="text-sm text-red-600 mb-4">
Please check your connection and try again
</p>
<Button
onClick={() => refetch()}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
return (
<div className="p-6 max-w-6xl mx-auto space-y-6">
<div className="flex justify-between items-center">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Accepted Orders
</h1>
<p className="text-sm text-gray-500 mt-1">
Manage and process your kitchen's accepted orders
</p>
</div>
<div className="flex items-center gap-3">
<Badge className="bg-emerald-100 text-emerald-800 border-emerald-200 px-3 py-1">
<Clock className="mr-1 h-3.5 w-3.5" />
{orders?.length} {orders?.length === 1 ? "Order" : "Orders"}
</Badge>
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</div>
{orders?.length === 0 ? (
<Card className="border-gray-200 shadow-sm">
<CardContent className="flex flex-col items-center justify-center py-12">
<div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
<Package className="h-8 w-8 text-emerald-600" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No accepted orders
</h3>
<p className="text-gray-500 max-w-md text-center">
There are no orders currently assigned to your kitchen
</p>
<Button
variant="outline"
className="mt-6 border-gray-200 text-emerald-700 hover:bg-emerald-50"
onClick={() => refetch()}
>
<RefreshCcw className="mr-2 h-4 w-4" /> Check Again
</Button>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{orders?.map((order) => (
<Link key={order.id} href={`/d/cook/accepted-orders/${order.id}`}>
<Card className="border-gray-200 shadow-sm hover:border-emerald-200 hover:shadow-md transition-all">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</CardTitle>
<CardDescription className="mt-1 text-gray-500">
{format(new Date(order.created_at), "PPpp")}
</CardDescription>
</div>
<Badge
className={
order.status === "ACCEPTED"
? "bg-blue-100 text-blue-800 border-blue-200"
: order.status === "PREPARING"
? "bg-orange-100 text-orange-800 border-orange-200"
: "bg-emerald-100 text-emerald-800 border-emerald-200"
}
>
{order.status.charAt(0) +
order.status.slice(1).toLowerCase()}
</Badge>
</div>
</CardHeader>
<CardContent className="p-4 space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">Meal Type</p>
<p className="font-medium capitalize text-emerald-700">
{order.foodType.toLowerCase()}
</p>
</div>
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">Last Updated</p>
<p className="font-medium text-emerald-700">
{format(new Date(order.updated_at), "PPpp")}
</p>
</div>
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">User</p>
<div className="font-medium text-emerald-700 flex items-center">
<User className="h-3.5 w-3.5 mr-1 text-gray-400" />
{order.user?.name}
</div>
</div>
</div>
{order.description && (
<div className="bg-amber-50 p-3 rounded-md border border-amber-100">
<p className="text-sm text-amber-700 italic">
<span className="font-medium">Note:</span>{" "}
{order.description}
</p>
</div>
)}
<div className="border-t border-gray-100 pt-4">
<p className="text-sm font-medium text-emerald-700 mb-3">
Order Items
</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="border border-gray-200 rounded-lg p-3 bg-gray-50"
>
<p className="font-medium text-sm text-emerald-800 mb-2">
{category}
</p>
<ul className="space-y-1">
{details.items.map((item, index) => (
<li
key={index}
className="flex justify-between text-sm"
>
<span>{item.menu}</span>
<span className="text-amber-600 font-medium">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
</CardContent>
<CardFooter className="border-t border-gray-100 p-4 bg-gray-50">
<div className="flex items-center text-sm text-emerald-700">
<ChefHat className="h-4 w-4 mr-2" />
<span>Click to view order details and update status</span>
</div>
</CardFooter>
</Card>
</Link>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,164 @@
"use client";
import { useMutation } from "@tanstack/react-query";
import {
BookCheck,
Columns2,
LayoutDashboard,
ListOrderedIcon,
LogOut,
ShoppingCart,
} from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useState } from "react";
import { logoutFromServer } from "@/app/logout";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import client from "@/lib/client";
export function CookSidebar() {
const router = useRouter();
const pathname = usePathname();
const { setOpenMobile } = useSidebar();
const [open, setOpen] = useState(false);
const { mutate: logout } = useMutation({
mutationFn: async () => {
const { data } = await client.post("auth/logout");
return data;
},
onSuccess: () => {
router.push("/");
logoutFromServer();
},
});
// Menu categories
const menuItems = [
{
title: "Dashboard",
url: "/d/cook/dashboard",
icon: LayoutDashboard,
},
{
title: "Pending Orders",
url: "/d/cook/orders",
icon: ListOrderedIcon,
},
{
title: "Accepted Orders",
url: "/d/cook/accepted-orders",
icon: ListOrderedIcon,
},
{
title: "Inventory",
url: "/d/cook/inventory",
icon: ShoppingCart,
},
{
title: "Transfers",
url: "/d/cook/transfers",
icon: Columns2,
},
{
title: "Logs",
url: "/d/cook/logs",
icon: BookCheck,
},
];
return (
<Sidebar className="bg-[#272f6f] text-white">
<SidebarHeader className="p-4 bg-white">
<img src="/ekam.png" alt="Ekam Logo" className="h- mx-auto" />
</SidebarHeader>
<SidebarContent className="px-2 py-4">
<SidebarGroup className="mb-4">
<SidebarGroupLabel className="text-indigo-300 text-xs font-medium px-3 mb-1 uppercase tracking-wider">
Kitchen Management
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{menuItems.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
asChild
className={`${
pathname === item.url
? "bg-indigo-800 text-white font-medium border-l-2 border-yellow-400"
: "hover:bg-indigo-800 hover:text-white"
}`}
>
<Link href={item.url} onClick={() => setOpenMobile(false)}>
<item.icon
className={`h-4 w-4 mr-2 ${
pathname === item.url
? "text-yellow-400"
: "text-indigo-200"
}`}
/>
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
<SidebarFooter className="mt-auto border-t border-indigo-900 p-4">
<SidebarMenu>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<SidebarMenuItem>
<SidebarMenuButton className="text-yellow-400 hover:bg-indigo-800 hover:text-yellow-300">
<LogOut className="h-4 w-4 mr-2" />
<span>Logout</span>
</SidebarMenuButton>
</SidebarMenuItem>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure you want to logout?</DialogTitle>
</DialogHeader>
<div className="flex items-center justify-end gap-5 mt-4">
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
className="bg-indigo-600 hover:bg-indigo-700 text-white"
onClick={() => logout()}
>
Logout
</Button>
</div>
</DialogContent>
</Dialog>
</SidebarMenu>
</SidebarFooter>
</Sidebar>
);
}

View File

@@ -0,0 +1,202 @@
"use client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { WelcomeMessage } from "@/components/welcome-message";
import client from "@/lib/client";
import { KitchenInventory, Order } from "@anujs.dev/inventory-types-utils";
import { useQuery } from "@tanstack/react-query";
import { formatDistanceToNow } from "date-fns";
import {
AlertTriangle,
BarChartIcon as ChartBar,
ClipboardList,
Package,
ShoppingCart,
} from "lucide-react";
import {
Bar,
BarChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
export default function KitchenDashboard() {
const { data: inventory = [], isLoading: loadingInventory } = useQuery<
KitchenInventory[]
>({
queryKey: ["kitchen-inventory"],
queryFn: async () => {
const { data } = await client.get("/kitchen-inventory/me");
return data;
},
});
const { data: orders = [], isLoading: loadingOrders } = useQuery<Order[]>({
queryKey: ["accepted-orders"],
queryFn: async () => {
const { data } = await client.get("/order/accepted");
return data;
},
});
const totalItems = inventory.length;
const totalStock = inventory.reduce(
(sum, item) => sum + Number(item.stock),
0
);
const lowStock = inventory.filter((item) => Number(item.stock) < 2);
const chartData = inventory.map((item) => ({
name: item.inventory.name,
quantity: Number(item.stock),
}));
return (
<div className="p-6 max-w-7xl mx-auto space-y-6">
<div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
🍽 Kitchen Dashboard
</h1>
<WelcomeMessage />
</div>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-emerald-800 flex items-center">
<Package className="h-5 w-5 mr-2 text-emerald-600" />
Total Items
</CardTitle>
</CardHeader>
<CardContent className="pt-4">
<p className="text-2xl font-bold text-emerald-700">{totalItems}</p>
</CardContent>
</Card>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-emerald-800 flex items-center">
<ShoppingCart className="h-5 w-5 mr-2 text-emerald-600" />
Total Stock
</CardTitle>
</CardHeader>
<CardContent className="pt-4">
<p className="text-2xl font-bold text-emerald-700">
{totalStock.toFixed(2)}
</p>
<p className="text-xs text-gray-500">across all units</p>
</CardContent>
</Card>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-emerald-800 flex items-center">
<AlertTriangle className="h-5 w-5 mr-2 text-amber-600" />
Low Stock Items
</CardTitle>
</CardHeader>
<CardContent className="pt-4">
<p className="text-2xl font-bold text-red-600">{lowStock.length}</p>
<p className="text-xs text-gray-500">items below threshold</p>
</CardContent>
</Card>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-emerald-800 flex items-center">
<ChartBar className="h-5 w-5 mr-2 text-emerald-600" />
Inventory Quantity Chart
</CardTitle>
</CardHeader>
<CardContent className="h-96 pt-6">
{chartData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData}>
<XAxis dataKey="name" tick={{ fontSize: 12 }} />
<YAxis />
<Tooltip />
<Bar dataKey="quantity" fill="#059669" />
</BarChart>
</ResponsiveContainer>
) : (
<div className="flex items-center justify-center h-full">
<p className="text-gray-500 text-sm">
No inventory data available.
</p>
</div>
)}
</CardContent>
</Card>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-emerald-800 flex items-center">
<ClipboardList className="h-5 w-5 mr-2 text-emerald-600" />
Accepted Orders
</CardTitle>
</CardHeader>
<CardContent className="pt-6 space-y-4">
{orders.length === 0 ? (
<div className="text-center py-8 bg-gray-50 rounded-md border border-gray-200">
<p className="text-gray-500">No accepted orders currently.</p>
</div>
) : (
orders.map((order) => (
<div
key={order.id}
className="border border-gray-200 rounded-md p-4 space-y-2 hover:bg-emerald-50 transition-colors"
>
<div className="flex justify-between items-center">
<p className="font-medium text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</p>
<span className="text-xs px-2 py-1 bg-emerald-100 text-emerald-700 rounded-full">
{formatDistanceToNow(new Date(order.updated_at))} ago
</span>
</div>
<p className="text-sm text-gray-500 capitalize">
{order.foodType.toLowerCase()} {order.status.toLowerCase()}
</p>
{order.description && (
<div className="bg-amber-50 p-2 rounded-md border border-amber-100 mt-2">
<p className="text-xs italic text-amber-700">
<span className="font-medium">Note:</span>{" "}
{order.description}
</p>
</div>
)}
<div className="mt-3 pt-2 border-t border-gray-100">
<p className="text-xs font-medium text-gray-500 mb-1">
Order Items:
</p>
<ul className="text-sm space-y-1">
{Object.entries(order.orderDetails).flatMap(
([group, details]) =>
details.items.map((item, index) => (
<li
key={`${group}-${index}`}
className="flex justify-between"
>
<span>{item.menu}</span>
<span className="font-medium text-emerald-600">
x{item.count}
</span>
</li>
))
)}
</ul>
</div>
</div>
))
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,267 @@
import SortingButton from "@/components/sorting-button";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { toast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { KitchenInventory } from "@anujs.dev/inventory-types-utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery } from "@tanstack/react-query";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import { ArrowRightCircle } from "lucide-react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
const transferToKitchenForm = z.object({
fromKitchenId: z.string().uuid(),
toKitchenId: z.string().uuid(),
inventoryId: z.string().uuid(),
quantity: z.number().positive(),
unit: z.string(),
reason: z.string().min(3, "Reason must be atleast 3 characters long"),
});
type TransferToKitchenSchema = z.infer<typeof transferToKitchenForm>;
export const columns: ColumnDef<KitchenInventory>[] = [
{
header({ column }) {
return <SortingButton column={column}>Last Updated on</SortingButton>;
},
accessorKey: "updated_at",
cell: ({ row }) => {
return (
<span>{format(row.original.updated_at, "dd MMM yyyy - HH:MM")}</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Name</SortingButton>;
},
accessorKey: "inventory",
cell: ({ row }) => {
return <span>{row.original.inventory.name}</span>;
},
},
{
header({ column }) {
return <SortingButton column={column}>Stock</SortingButton>;
},
accessorKey: "stock",
},
{
accessorKey: "id",
},
{
header: "Unit",
accessorKey: "unit",
},
{
header: "Actions",
cell: ({ row, table }) => {
const form = useForm<TransferToKitchenSchema>({
resolver: zodResolver(transferToKitchenForm),
defaultValues: {
fromKitchenId: row.original.kitchen.id,
toKitchenId: "",
inventoryId: row.original.inventory.id,
quantity: 0,
unit: row.original.unit,
reason: "",
},
});
console.log("rows");
const [open, setOpen] = useState(false);
const {
data: kitchens,
isLoading,
refetch,
} = useQuery({
queryKey: ["kitchen inventories"],
queryFn: async () => {
const { data } = await client.get("kitchen-inventory");
return data;
},
select(data) {
const kitchenMap = new Map();
data.forEach((item: KitchenInventory) => {
const kitchenId = item.kitchen.id;
const kitchenName = item.kitchen.name;
if (row.original.kitchen.id !== kitchenId) {
kitchenMap.set(kitchenId, { id: kitchenId, name: kitchenName });
}
});
return Array.from(kitchenMap.values());
},
});
const { mutate: transferToKitchen } = useMutation({
mutationFn: async (values: TransferToKitchenSchema) => {
const { data } = await client.post(
"kitchen-inventory/transfer",
values
);
return data;
},
onSuccess: () => {
toast({
title: "Transfer Complete",
// description: `${row} has been transferred to kitchen`,
});
refetch();
// @ts-expect-error sent to the main table
table.options.meta.refetch();
form.setValue("quantity", 0);
form.setValue("toKitchenId", "");
setOpen(false);
},
});
function onSubmit(data: TransferToKitchenSchema) {
transferToKitchen(data);
}
return (
<div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant={"outline"} size={"sm"}>
Transfer
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Transfer Inventory</DialogTitle>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
>
<FormField
name="toKitchenId"
control={form.control}
render={({ field }) => (
<FormItem>
<FormLabel>Transfer beteen Kitchens</FormLabel>
<div className="flex gap-5 items-center justify-between">
<Input
value={row.original.kitchen.name}
disabled
></Input>
<ArrowRightCircle
size={30}
className="w-20 text-green-500"
></ArrowRightCircle>
<FormControl className="">
<Select
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger>
<SelectValue placeholder="Select Kitchen"></SelectValue>
</SelectTrigger>
<SelectContent>
{kitchens?.map((kitchen: any) => (
<SelectItem
key={kitchen.id}
value={kitchen.id}
>
{kitchen.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
</div>
</FormItem>
)}
></FormField>
<FormField
control={form.control}
name="quantity"
render={({ field }) => (
<FormItem>
<FormLabel>Quantity</FormLabel>
<FormControl className="w-full">
<div className="w-full gap-5 flex items-center">
<Slider
className="w-[70%]"
min={0}
max={row.original.stock}
step={1}
onValueChange={(value) => {
console.log(value);
field.onChange(value[0]);
}}
value={[field.value]}
></Slider>
<Input
className={"w-32"}
type="number"
value={field.value}
onChange={field.onChange}
max={row.original.stock}
></Input>
<p>{row.original.unit}</p>
</div>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
)}
></FormField>
<FormField
control={form.control}
name="reason"
render={({ field }) => (
<FormItem>
<FormLabel>Reason for transfer</FormLabel>
<FormControl className="w-full">
<Input {...field}></Input>
</FormControl>
<FormMessage></FormMessage>
</FormItem>
)}
></FormField>
<Button
disabled={!form.formState.isValid}
className="w-full"
>
Transfer Now
</Button>
</form>
</Form>
</DialogHeader>
</DialogContent>
</Dialog>
</div>
);
},
},
];

View File

@@ -0,0 +1,235 @@
"use client";
import { DataTable } from "@/components/data-table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import client from "@/lib/client";
import { useQuery } from "@tanstack/react-query";
import { RefreshCcw, Search, ShoppingCart, Store } from "lucide-react";
import { useState } from "react";
import { columns } from "./columns";
import { KitchenInventory } from "@anujs.dev/inventory-types-utils";
export default function KitchenInventoryPage() {
const [searchTerm, setSearchTerm] = useState("");
const user = useQuery({
queryFn: async () => {
const { data } = await client.get("auth/me");
return data;
},
queryKey: ["user"],
});
const {
data: kitchens,
isLoading,
isError,
refetch,
} = useQuery({
enabled: user.isSuccess,
queryKey: ["kitchen inventory", user.data?.kitchen.id],
queryFn: async () => {
const { data } = await client.get(
`kitchen-inventory/${user.data.kitchen.id}`
);
return data;
},
});
// Filter inventory based on search term
const filteredInventory =
searchTerm && kitchens
? kitchens.filter((item: KitchenInventory) =>
item.inventory.name.toLowerCase().includes(searchTerm.toLowerCase())
)
: kitchens;
// Count low stock items (less than 5 units)
const lowStockCount =
kitchens?.filter((item: KitchenInventory) => Number(item.stock) < 5)
.length || 0;
if (isLoading || user.isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<Skeleton className="h-8 w-[300px] mb-4" />
<Skeleton className="h-4 w-[200px] mb-6" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[200px]" />
<div className="flex gap-2">
<Skeleton className="h-9 w-[120px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[400px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading inventory data...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isError || user.isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Kitchen Inventory
</h1>
<p className="text-sm text-gray-500 mb-6">
View and manage your kitchen's inventory items
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load inventory data
</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the inventory information
</p>
<Button
onClick={() => refetch()}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Kitchen Inventory
</h1>
<p className="text-sm text-gray-500 mt-1">
View and manage your kitchen's inventory items
</p>
</div>
<Button
variant="outline"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6">
<Card className="border-gray-200 shadow-sm">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500">Total Items</p>
<p className="text-2xl font-bold text-emerald-800">
{kitchens?.length || 0}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center">
<ShoppingCart className="h-5 w-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="shadow-sm bg-amber-50 border-amber-200">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-amber-600">Low Stock</p>
<p className="text-2xl font-bold text-amber-800">
{lowStockCount}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-amber-100 flex items-center justify-center">
<ShoppingCart className="h-5 w-5 text-amber-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="shadow-sm bg-blue-50 border-blue-200">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-blue-600">Kitchen</p>
<p className="text-lg font-bold text-blue-800 truncate max-w-[180px]">
{user.data?.kitchen.name}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
<Store className="h-5 w-5 text-blue-600" />
</div>
</div>
</CardContent>
</Card>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<Store className="mr-2 h-5 w-5 text-emerald-600" />
{user.data?.kitchen.name} Inventory
{kitchens?.length > 0 && (
<Badge className="ml-2 bg-emerald-100 text-emerald-800 border-emerald-200">
{kitchens.length} items
</Badge>
)}
</CardTitle>
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="Search inventory..."
className="pl-9 max-w-xs h-9 border-gray-200 focus:ring-emerald-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{filteredInventory && filteredInventory.length > 0 ? (
<DataTable
refetch={refetch}
columns={columns}
data={filteredInventory}
/>
) : (
<div className="text-center py-12">
<p className="text-gray-500">
{searchTerm
? `No inventory items matching "${searchTerm}" found`
: "No inventory items found"}
</p>
{searchTerm && (
<Button
variant="outline"
className="mt-4 border-gray-200"
onClick={() => setSearchTerm("")}
>
Clear Search
</Button>
)}
</div>
)}
</CardContent>
</Card>
</div>
);
}

23
src/app/d/cook/layout.tsx Normal file
View File

@@ -0,0 +1,23 @@
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import React from "react";
import { CookSidebar } from "./components/sidebar";
export default function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<SidebarProvider>
<CookSidebar />
<main className="w-full min-h-screen items-start justify-between flex flex-col">
<div className="w-full ">
<SidebarTrigger />
<div className="w-full">{children}</div>
</div>
<p className="justify-self-end w-full text-sm text-center bg-emerald-700 text-white ">
Powered by Aurelion Future Forge
</p>
</main>
</SidebarProvider>
);
}

View File

@@ -0,0 +1,39 @@
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import SortingButton from "@/components/sorting-button";
import { Log, ServiceMappings } from "@anujs.dev/inventory-types-utils";
export const columns: ColumnDef<Log>[] = [
{
header({ column }) {
return <SortingButton column={column}>Log time</SortingButton>;
},
accessorKey: "timestamp",
cell: ({ row }) => {
return (
<span>{format(row.original.timestamp, "MMM d, yyyy h:mm a")}</span>
);
},
},
{
header: "Action",
accessorKey: "metadata.context",
cell: ({ row }) => {
// @ts-expect-error it is mapped using this
return <span>{ServiceMappings[row.original.context]}</span>;
},
},
{
header: "User",
accessorKey: "metadata.user.name",
},
{
header: "Role",
accessorKey: "metadata.user.role",
},
{
header: "Description",
accessorKey: "metadata.activity",
},
];

View File

@@ -0,0 +1,205 @@
"use client";
import { columns } from "./columns";
import { useQuery } from "@tanstack/react-query";
import client from "@/lib/client";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FileText, RefreshCcw, Search } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { Log, ServiceMappings } from "@anujs.dev/inventory-types-utils";
import { DataTable } from "@/components/data-table";
export default function Logs() {
const [filter, setFilter] = useState("all");
const [searchTerm, setSearchTerm] = useState("");
const [filtered, setFiltered] = useState<Log[]>([]);
const { data, isLoading, isError, refetch } = useQuery<Log[]>({
queryKey: ["logs"],
queryFn: async () => {
const { data } = await client.get(`logs/by-kitchen`);
return data;
},
});
useEffect(() => {
if (data) {
let filteredData = data;
if (filter !== "all") {
filteredData = filteredData.filter(
(log) => log.metadata.context === filter
);
}
if (searchTerm) {
filteredData = filteredData.filter(
(log) =>
log.message.toLowerCase().includes(searchTerm.toLowerCase()) ||
(log.user?.name &&
log.user.name.toLowerCase().includes(searchTerm.toLowerCase())) ||
(log.metadata &&
JSON.stringify(log.metadata)
.toLowerCase()
.includes(searchTerm.toLowerCase()))
);
}
setFiltered(filteredData);
}
}, [data, filter, searchTerm]);
if (isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<Skeleton className="h-8 w-[200px] mb-4" />
<Skeleton className="h-4 w-[200px] mb-6" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[200px]" />
<div className="flex gap-2">
<Skeleton className="h-9 w-[120px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[400px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading logs...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Kitchen Logs
</h1>
<p className="text-sm text-gray-500 mb-6">
View system logs for your kitchen
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">Failed to load logs</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the log information
</p>
<Button
onClick={() => refetch()}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">Kitchen Logs</h1>
<p className="text-sm text-gray-500 mt-1">
View and filter system logs for your kitchen
</p>
</div>
<Button
variant="outline"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<FileText className="mr-2 h-5 w-5 text-emerald-600" />
System Logs
{filtered && (
<Badge className="ml-2 bg-emerald-100 text-emerald-800 border-emerald-200">
{filtered.length} entries
</Badge>
)}
</CardTitle>
<div className="flex items-center gap-3">
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-400" />
<Input
placeholder="Search logs..."
className="pl-9 max-w-xs h-9 border-gray-200 focus:ring-emerald-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<Select
value={filter}
onValueChange={(value) => setFilter(value)}
>
<SelectTrigger className="w-[180px] border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Filter by service" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Services</SelectItem>
{Object.entries(ServiceMappings).map(([key, label]) => (
<SelectItem key={key} value={key}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{filtered && filtered.length > 0 ? (
<DataTable refetch={refetch} columns={columns} data={filtered} />
) : (
<div className="text-center py-12">
<p className="text-gray-500">
{searchTerm || filter !== "all"
? "No logs match your current filters"
: "No logs found in the system"}
</p>
{(searchTerm || filter !== "all") && (
<Button
variant="outline"
className="mt-4 border-gray-200"
onClick={() => {
setSearchTerm("");
setFilter("all");
}}
>
Clear Filters
</Button>
)}
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,262 @@
"use client";
import { Button } from "@/components/ui/button";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import client from "@/lib/client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { format } from "date-fns";
import { useToast } from "@/hooks/use-toast";
import { Clock, Package, RefreshCcw, User } from "lucide-react";
import { Order } from "@anujs.dev/inventory-types-utils";
export default function CookOrdersPage() {
const queryClient = useQueryClient();
const { toast } = useToast();
const {
data: orders,
isLoading,
error,
refetch,
} = useQuery<Order[]>({
queryKey: ["all-orders"],
queryFn: async () => {
const { data } = await client.get("order");
return data;
},
refetchInterval: 5000,
});
const { mutate: acceptOrder, isPending: isAccepting } = useMutation({
mutationFn: async (orderId: string) => {
return client.patch(`order/${orderId}/accept`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["all-orders"] });
toast({
title: "Order Accepted",
description: "Order successfully accepted",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
},
onError: () => {
toast({
title: "Error",
description: "Accept failed. Please try again.",
variant: "destructive",
});
},
});
if (isLoading) {
return (
<div className="p-6 max-w-6xl mx-auto space-y-4">
<Skeleton className="h-8 w-[200px]" />
{[1, 2, 3].map((i) => (
<Card key={i} className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<Skeleton className="h-4 w-[150px]" />
<Skeleton className="h-3 w-[200px]" />
</CardHeader>
<CardContent className="p-4">
<Skeleton className="h-4 w-full mb-2" />
<Skeleton className="h-4 w-full" />
</CardContent>
<CardFooter className="border-t border-gray-100 p-4">
<Skeleton className="h-9 w-[120px]" />
</CardFooter>
</Card>
))}
</div>
);
}
if (error) {
return (
<div className="p-6 max-w-6xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">Failed to load orders</p>
<p className="text-sm text-red-600 mb-4">
Please check your connection and try again
</p>
<Button
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
onClick={() => refetch()}
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
const pendingOrders = orders?.filter((order) => !order.isAccepted) || [];
return (
<div className="p-6 max-w-6xl mx-auto space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Pending Orders
</h1>
<p className="text-sm text-gray-500 mt-1">
Accept and manage new orders for your kitchen
</p>
</div>
<div className="flex items-center gap-3">
<Badge
variant="outline"
className="text-sm bg-amber-50 border-amber-200 text-amber-800 px-3 py-1"
>
<Clock className="mr-1 h-3.5 w-3.5" />
{pendingOrders.length} Pending
</Badge>
<Button
variant="outline"
size="sm"
onClick={() => refetch()}
className="border-gray-200"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
</div>
{pendingOrders.length === 0 ? (
<Card className="border-gray-200 shadow-sm">
<CardContent className="flex flex-col items-center justify-center py-12">
<div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
<Package className="h-8 w-8 text-emerald-600" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No pending orders
</h3>
<p className="text-gray-500 max-w-md text-center">
All current orders have been accepted or there are no new orders
at this time
</p>
<Button
variant="outline"
className="mt-6 border-gray-200"
onClick={() => refetch()}
>
<RefreshCcw className="mr-2 h-4 w-4" /> Check Again
</Button>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{pendingOrders.map((order) => (
<Card
key={order.id}
className="hover:shadow-md transition-shadow border-gray-200 shadow-sm"
>
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-start">
<div>
<CardTitle className="text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</CardTitle>
<CardDescription className="mt-1 text-gray-500">
{format(new Date(order.created_at), "PPpp")}
</CardDescription>
</div>
<Badge className="bg-amber-100 text-amber-800 border-amber-200">
{order.status.toLowerCase()}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4 p-4">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">Meal Type</p>
<p className="font-medium capitalize text-emerald-700">
{order.foodType.toLowerCase()}
</p>
</div>
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">Last Updated</p>
<p className="font-medium text-emerald-700">
{format(new Date(order.updated_at), "PPpp")}
</p>
</div>
<div className="bg-gray-50 p-3 rounded-md">
<p className="text-xs text-gray-500">User</p>
<div className="font-medium text-emerald-700 flex items-center">
<User className="h-3.5 w-3.5 mr-1 text-gray-400" />
{order.user.name}
</div>
</div>
</div>
{order.description && (
<div className="bg-amber-50 p-3 rounded-md border border-amber-100">
<p className="text-sm text-amber-700 italic">
<span className="font-medium">Note:</span>{" "}
{order.description}
</p>
</div>
)}
<div className="border-t border-gray-100 pt-4">
<p className="text-sm font-medium text-emerald-700 mb-3">
Order Items
</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="border border-gray-200 rounded-lg p-3 bg-gray-50"
>
<p className="font-medium text-sm text-emerald-800 mb-2">
{category}
</p>
<ul className="space-y-1">
{details.items.map((item, index) => (
<li
key={index}
className="flex justify-between text-sm"
>
<span>{item.menu}</span>
<span className="text-amber-600 font-medium">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
</CardContent>
<CardFooter className="border-t border-gray-100 p-4 bg-gray-50">
<Button
onClick={() => acceptOrder(order.id)}
disabled={isAccepting}
className="w-full bg-emerald-600 hover:bg-emerald-700"
>
{isAccepting ? "Accepting..." : "Accept Order"}
</Button>
</CardFooter>
</Card>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,157 @@
"use client";
import { DataTable } from "@/components/data-table";
import { useQuery } from "@tanstack/react-query";
import client from "@/lib/client";
import { transferColumns } from "./transfer-columns";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { ArrowLeftRight, RefreshCcw, Store } from "lucide-react";
export default function KitchenTransfersPage() {
const user = useQuery({
queryFn: async () => {
const { data } = await client.get("auth/me");
return data;
},
queryKey: ["user"],
});
const transfers = useQuery({
queryKey: ["kitchen-transfers", user.data?.kitchen?.id],
queryFn: async () => {
const { data } = await client.get("kitchen-inventory/transfers/kitchen");
return data;
},
enabled: !!user.data?.kitchen?.id,
});
if (user.isLoading || transfers.isLoading) {
return (
<div className="p-6 max-w-7xl mx-auto">
<Skeleton className="h-8 w-[250px] mb-4" />
<Skeleton className="h-4 w-[200px] mb-6" />
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-gray-50 border-b border-gray-100">
<div className="flex justify-between items-center">
<Skeleton className="h-5 w-[200px]" />
<Skeleton className="h-9 w-[100px]" />
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[400px] w-full flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-emerald-600 mx-auto mb-4"></div>
<p className="text-emerald-800">Loading transfer data...</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (user.isError || transfers.isError) {
return (
<div className="p-6 max-w-7xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-1">
Kitchen Transfers
</h1>
<p className="text-sm text-gray-500 mb-6">
View inventory transfers for your kitchen
</p>
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load transfer data
</p>
<p className="text-sm text-red-600 mb-4">
There was an error retrieving the transfer information
</p>
<Button
onClick={() => {
user.refetch();
transfers.refetch();
}}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
Kitchen Transfers
</h1>
<p className="text-sm text-gray-500 mt-1">
View and manage inventory transfers for your kitchen
</p>
</div>
<Button
variant="outline"
onClick={() => transfers.refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex items-center justify-between">
<CardTitle className="text-lg font-semibold text-emerald-800 flex items-center">
<Store className="mr-2 h-5 w-5 text-emerald-600" />
{user.data?.kitchen?.name} Transfers
{transfers.data?.length > 0 && (
<Badge className="ml-2 bg-emerald-100 text-emerald-800 border-emerald-200">
{transfers.data.length} transfers
</Badge>
)}
</CardTitle>
<Badge className="bg-blue-100 text-blue-800 border-blue-200 flex items-center">
<ArrowLeftRight className="mr-1.5 h-3.5 w-3.5" />
Inventory Movement
</Badge>
</div>
</CardHeader>
<CardContent className="p-0">
{transfers.data?.length > 0 ? (
<DataTable
refetch={transfers.refetch}
columns={transferColumns}
data={transfers.data}
/>
) : (
<div className="text-center py-12 bg-gray-50">
<div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4">
<ArrowLeftRight className="h-8 w-8 text-emerald-600" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No transfers found
</h3>
<p className="text-gray-500 max-w-md mx-auto">
There are no inventory transfers recorded for your kitchen yet.
</p>
<Button
variant="outline"
className="mt-6 border-gray-200"
onClick={() => transfers.refetch()}
>
<RefreshCcw className="mr-2 h-4 w-4" /> Check Again
</Button>
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,75 @@
import SortingButton from "@/components/sorting-button";
import { ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
export const transferColumns: ColumnDef<any>[] = [
{
header({ column }) {
return <SortingButton column={column}>Transferred On</SortingButton>;
},
accessorKey: "created_at",
cell: ({ row }) => {
return (
<span>
{format(new Date(row.original.created_at), "dd MMM yyyy - HH:mm")}
</span>
);
},
},
{
header({ column }) {
return <SortingButton column={column}>Name</SortingButton>;
},
accessorKey: "inventoryName",
cell: ({ row }) => {
return <span>{row.original.inventory?.name}</span>;
},
},
{
header({ column }) {
return <SortingButton column={column}>Quantity</SortingButton>;
},
accessorKey: "quantity",
cell: ({ row }) => {
return (
<span>
{row.original.quantity} {row.original.inventory.unit}
</span>
);
},
},
{
header: "From",
accessorKey: "from",
cell: ({ row }) => {
return <span>{row.original.fromKitchen?.name}</span>;
},
},
{
header: "To",
accessorKey: "to",
cell: ({ row }) => {
return <span>{row.original.toKitchen?.name}</span>;
},
},
{
header({ column }) {
return <SortingButton column={column}>User</SortingButton>;
},
accessorKey: "user",
cell: ({ row }) => {
return (
<span>
{row.original.user?.name} | {row.original.user?.email}
</span>
);
},
},
{
header: "Reason",
accessorKey: "reason",
cell: ({ row }) => {
return <span>{row.original.reason || "No reason provided"}</span>;
},
},
];

View File

@@ -0,0 +1,174 @@
"use client";
import { useMutation } from "@tanstack/react-query";
import {
ClipboardList,
History,
LayoutDashboard,
LogOut,
ShoppingCart,
} from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import * as React from "react";
import { logoutFromServer } from "@/app/logout";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import client from "@/lib/client";
const data = {
navMain: [
{
title: "",
url: "",
items: [
{
title: "Dashboard",
url: "/d/user/dashboard",
icon: LayoutDashboard,
},
],
},
{
title: "Manage Orders",
url: "#",
items: [
{
title: "Place new order",
url: "/d/user/dashboard/orders/new",
icon: ShoppingCart,
},
{
title: "View order status",
url: "/d/user/dashboard/orders/current",
icon: ClipboardList,
},
{
title: "Previous Orders",
url: "/d/user/dashboard/orders/history",
icon: History,
},
],
},
],
};
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const pathname = usePathname();
const { setOpenMobile } = useSidebar();
const [open, setOpen] = React.useState(false);
const router = useRouter();
const { mutate: logout } = useMutation({
mutationFn: async () => {
const { data } = await client.post("auth/logout");
return data;
},
onSuccess: () => {
router.push("/");
logoutFromServer();
},
});
return (
<Sidebar className=" bg-[#272f6f] text-white" {...props}>
<SidebarHeader className="p-4 bg-white">
<img src="/ekam.png" alt="EKAM Logo" className="mx-auto" />
</SidebarHeader>
<SidebarContent className="px-2 py-4">
{data.navMain.map((section) => (
<SidebarGroup key={section.title} className="mb-4">
{section.title && (
<SidebarGroupLabel className="text-indigo-300 text-xs font-medium px-3 mb-1 uppercase tracking-wider">
{section.title}
</SidebarGroupLabel>
)}
<SidebarGroupContent>
<SidebarMenu>
{section.items.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton
asChild
className={`${
pathname === item.url
? "bg-indigo-800 text-white font-medium border-l-2 border-yellow-400"
: "hover:bg-indigo-800 hover:text-white"
}`}
>
<Link
href={item.url}
onClick={() => setOpenMobile(false)}
>
{item.icon && (
<item.icon
className={`h-4 w-4 mr-2 ${
pathname === item.url
? "text-yellow-400"
: "text-indigo-200"
}`}
/>
)}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
))}
</SidebarContent>
<SidebarFooter className="mt-auto border-t border-indigo-900 p-4">
<SidebarMenu>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<SidebarMenuItem>
<SidebarMenuButton className="text-yellow-400 hover:bg-indigo-800 hover:text-yellow-300">
<LogOut className="h-4 w-4 mr-2" />
<span>Logout</span>
</SidebarMenuButton>
</SidebarMenuItem>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure you want to logout?</DialogTitle>
</DialogHeader>
<div className="flex items-center justify-end gap-5 mt-4">
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
className="bg-indigo-600 hover:bg-indigo-700 text-white"
onClick={() => logout()}
>
Logout
</Button>
</div>
</DialogContent>
</Dialog>
</SidebarMenu>
</SidebarFooter>
</Sidebar>
);
}

View File

@@ -0,0 +1,237 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import client from "@/lib/client";
import { getProgressColor, getStatusColor, getStatusProgress } from "@/lib/status-progress";
import { Order } from "@anujs.dev/inventory-types-utils";
import { useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import {
CheckCircle2,
ChevronRight,
Clock,
Package,
RefreshCcw,
} from "lucide-react";
import Link from "next/link";
export default function MyOrdersPage() {
const {
data: orders,
isLoading,
error,
refetch,
} = useQuery<Order[]>({
queryKey: ["orders"],
queryFn: async () => {
const { data } = await client.get("order/mine");
return data;
},
});
if (isLoading) {
return (
<div className="p-6 max-w-4xl mx-auto">
<Skeleton className="h-8 w-[150px] mb-6" />
{[1, 2, 3].map((i) => (
<div key={i} className="mb-4">
<Skeleton className="h-[200px] w-full rounded-lg" />
</div>
))}
</div>
);
}
if (error) {
return (
<div className="p-6 max-w-4xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">Failed to load orders</p>
<p className="text-sm text-red-600 mb-4">
Please check your connection and try again
</p>
<Button
variant="outline"
onClick={() => refetch()}
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
if (!orders || orders.length === 0) {
return (
<div className="p-6 max-w-4xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-6">My Orders</h1>
<Card className="border-gray-200 shadow-sm">
<CardContent className="flex flex-col items-center justify-center py-12">
<div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
<Package className="h-8 w-8 text-emerald-600" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No orders found
</h3>
<p className="text-gray-500 max-w-md text-center mb-4">
You haven't placed any orders yet. Start by creating a new order.
</p>
<Button className="bg-emerald-600 hover:bg-emerald-700" asChild>
<Link href="/d/user/dashboard/orders/new">
Place Your First Order
</Link>
</Button>
</CardContent>
</Card>
</div>
);
}
return (
<div className="p-6 max-w-4xl mx-auto">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold text-emerald-800">My Orders</h1>
<Button
variant="outline"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
<div className="space-y-4">
{orders.map((order) => {
const progress = getStatusProgress(order.status);
const statusColor = getStatusColor(order.status);
const progressColor = getProgressColor(order.status);
return (
<Card
key={order.id}
className="border-gray-200 shadow-sm hover:border-emerald-200 hover:shadow-md transition-all"
>
<CardContent className="p-4">
<div className="flex justify-between items-start mb-4">
<div>
<h2 className="font-semibold text-lg text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</h2>
<p className="text-sm text-gray-500">
{format(
new Date(order.created_at),
"dd MMM yyyy hh:mm aa"
)}{" "}
{" "}
<span className="capitalize">
{order.foodType.toLowerCase()}
</span>
</p>
</div>
<Badge className={statusColor}>
{order.status.charAt(0) +
order.status.slice(1).toLowerCase()}
</Badge>
</div>
{order.description && (
<div className="mb-4 bg-amber-50 p-3 rounded-md border border-amber-100">
<p className="text-sm italic text-amber-700">
<span className="font-medium">Cook note:</span> "
{order.description}"
</p>
</div>
)}
<div className="mb-4">
<h3 className="font-medium text-emerald-700 mb-2">
Order Details
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="border border-gray-200 rounded-lg p-3 bg-gray-50"
>
<h4 className="text-sm font-semibold text-emerald-800 mb-2">
{category}
</h4>
<ul className="space-y-1">
{details.items.map((item, index) => (
<li
key={index}
className="flex justify-between text-sm"
>
<span>{item.menu}</span>
<span className="text-amber-600 font-medium">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
{order.status !== "CANCELLED" && (
<div className="mb-4">
<div className="h-2 bg-gray-100 rounded-full overflow-hidden">
<div
className={`h-2 transition-all ${progressColor}`}
style={{ width: `${progress}%` }}
/>
</div>
<div className="flex justify-between text-xs text-gray-500 mt-1">
<span>Order Placed</span>
<span>Accepted</span>
<span>Preparing</span>
<span>Completed</span>
</div>
</div>
)}
<div className="flex justify-between items-center border-t border-gray-100 pt-3 mt-2">
<div className="flex items-center gap-2 text-sm text-gray-600">
<span>Status:</span>
<div className="flex items-center">
{order.isAccepted ? (
<>
<CheckCircle2 className="h-4 w-4 text-emerald-600 mr-1" />
<span className="text-emerald-600">Accepted</span>
</>
) : (
<>
<Clock className="h-4 w-4 text-amber-600 mr-1" />
<span className="text-amber-600">Pending</span>
</>
)}
</div>
</div>
<Button
variant="outline"
size="sm"
asChild
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Link href={`/d/user/dashboard/orders/status/${order.id}`}>
View Details <ChevronRight className="ml-1 h-4 w-4" />
</Link>
</Button>
</div>
</CardContent>
</Card>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,242 @@
"use client";
import client from "@/lib/client";
import { useQuery } from "@tanstack/react-query";
import { format } from "date-fns";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Clock, RefreshCcw, ChevronRight, History } from "lucide-react";
import { Order } from "@anujs.dev/inventory-types-utils";
import {
getProgressColor,
getStatusColor,
getStatusProgress,
} from "@/lib/status-progress";
export default function MyOrderHistoryPage() {
const {
data: orders,
isLoading,
error,
refetch,
} = useQuery<Order[]>({
queryKey: ["orders-history"],
queryFn: async () => {
const { data } = await client.get("order/mine/history");
return data;
},
});
if (isLoading) {
return (
<div className="p-6 max-w-4xl mx-auto">
<Skeleton className="h-8 w-[200px] mb-6" />
{[1, 2, 3].map((i) => (
<div key={i} className="mb-4">
<Skeleton className="h-[200px] w-full rounded-lg" />
</div>
))}
</div>
);
}
if (error) {
return (
<div className="p-6 max-w-4xl mx-auto">
<div className="bg-red-50 border border-red-200 rounded-md p-6 text-center">
<p className="text-red-700 font-medium mb-2">
Failed to load order history
</p>
<p className="text-sm text-red-600 mb-4">
Please check your connection and try again
</p>
<Button
variant="outline"
onClick={() => refetch()}
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Try Again
</Button>
</div>
</div>
);
}
if (!orders || orders.length === 0) {
return (
<div className="p-6 max-w-4xl mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-6">
Order History
</h1>
<Card className="border-gray-200 shadow-sm">
<CardContent className="flex flex-col items-center justify-center py-12">
<div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
<History className="h-8 w-8 text-emerald-600" />
</div>
<h3 className="text-lg font-medium text-gray-700 mb-2">
No order history found
</h3>
<p className="text-gray-500 max-w-md text-center mb-4">
You don't have any past orders yet. Once you complete orders, they
will appear here.
</p>
<Button className="bg-emerald-600 hover:bg-emerald-700" asChild>
<Link href="/d/user/dashboard/orders/new">Place an Order</Link>
</Button>
</CardContent>
</Card>
</div>
);
}
return (
<div className="p-6 max-w-4xl mx-auto">
<div className="flex justify-between items-center mb-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">Order History</h1>
<p className="text-sm text-gray-500 mt-1">
View your past orders and their details
</p>
</div>
<Button
variant="outline"
onClick={() => refetch()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<RefreshCcw className="mr-2 h-4 w-4" /> Refresh
</Button>
</div>
<div className="space-y-4">
{orders.map((order) => {
const progress = getStatusProgress(order.status);
const statusColor = getStatusColor(order.status);
const progressColor = getProgressColor(order.status);
return (
<Card
key={order.id}
className="border-gray-200 shadow-sm hover:border-emerald-200 hover:shadow-md transition-all"
>
<CardContent className="p-4">
<div className="flex justify-between items-start mb-4">
<div>
<h2 className="font-semibold text-lg text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</h2>
<p className="text-sm text-gray-500">
{format(
new Date(order.created_at),
"dd MMM yyyy hh:mm aa"
)}{" "}
{" "}
<span className="capitalize">
{order.foodType.toLowerCase()}
</span>
</p>
</div>
<Badge className={statusColor}>
{order.status.charAt(0) +
order.status.slice(1).toLowerCase()}
</Badge>
</div>
{order.description && (
<div className="mb-4 bg-amber-50 p-3 rounded-md border border-amber-100">
<p className="text-sm italic text-amber-700">
<span className="font-medium">Cook note:</span> "
{order.description}"
</p>
</div>
)}
<div className="mb-4">
<h3 className="font-medium text-emerald-700 mb-2">
Order Details
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div
key={category}
className="border border-gray-200 rounded-lg p-3 bg-gray-50"
>
<h4 className="text-sm font-semibold text-emerald-800 mb-2">
{category}
</h4>
<ul className="space-y-1">
{details.items.map((item, index) => (
<li
key={index}
className="flex justify-between text-sm"
>
<span>{item.menu}</span>
<span className="text-amber-600 font-medium">
x{item.count}
</span>
</li>
))}
</ul>
</div>
)
)}
</div>
</div>
{order.status === "COMPLETED" && (
<div className="mb-4">
<div className="h-2 bg-gray-100 rounded-full overflow-hidden">
<div
className="h-2 bg-emerald-500 transition-all"
style={{ width: "100%" }}
/>
</div>
<div className="flex justify-between text-xs text-gray-500 mt-1">
<span>Order Placed</span>
<span>Accepted</span>
<span>Preparing</span>
<span>Completed</span>
</div>
</div>
)}
{order.status === "CANCELLED" && (
<div className="mb-4 bg-red-50 p-3 rounded-md border border-red-200">
<p className="text-sm text-red-700 flex items-center">
<Clock className="h-4 w-4 mr-2" />
This order was cancelled
</p>
</div>
)}
<div className="flex justify-between items-center border-t border-gray-100 pt-3 mt-2">
<div className="text-sm text-gray-600">
<span>Completed on: </span>
<span className="font-medium">
{format(new Date(order.updated_at), "dd MMM yyyy")}
</span>
</div>
<Button
variant="outline"
size="sm"
asChild
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Link href={`/d/user/dashboard/orders/status/${order.id}`}>
View Details <ChevronRight className="ml-1 h-4 w-4" />
</Link>
</Button>
</div>
</CardContent>
</Card>
);
})}
</div>
</div>
);
}

View File

@@ -0,0 +1,542 @@
"use client";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import client from "@/lib/client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useForm, useFieldArray } from "react-hook-form";
import { z } from "zod";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Plus,
Minus,
Trash2,
UtensilsCrossed,
AlertCircle,
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Skeleton } from "@/components/ui/skeleton";
import { FoodType, Menu, UserTypes } from "@anujs.dev/inventory-types-utils";
const CreateOrderSchema = z
.object({
foodType: z.nativeEnum(FoodType, {
required_error: "Please select a meal type",
}),
description: z.string().optional(),
orderDetails: z.record(
z.nativeEnum(UserTypes),
z.object({
items: z
.array(
z.object({
menu: z.string().min(1, "Menu item is required"),
count: z.number().min(1, "Minimum quantity is 1"),
})
)
.default([]),
})
),
})
.superRefine((data, ctx) => {
const {
JAINS,
DASAS,
"INDIAN GUESTS": INDIAN_GUESTS,
"INTERNATIONAL GUESTS": INTERNATIONAL_GUESTS,
STAFF,
} = data.orderDetails;
if (
JAINS?.items.length === 0 &&
DASAS?.items.length === 0 &&
INDIAN_GUESTS?.items.length === 0 &&
INTERNATIONAL_GUESTS?.items.length === 0 &&
STAFF?.items.length === 0
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"At least one order is required for either JAINS, DASAS, INDIAN GUESTS, INTERNATIONAL GUESTS OR STAFF",
path: ["orderDetails"],
});
}
});
type CreateOrderDto = z.infer<typeof CreateOrderSchema>;
export default function PlaceOrderPage() {
const router = useRouter();
const { toast } = useToast();
const { mutate: order, isPending } = useMutation({
mutationFn: async (createOrderDto: CreateOrderDto) => {
await client.post("order", createOrderDto);
},
onSuccess: () => {
toast({
title: "Order Created Successfully",
description: "Your order has been placed",
className: "bg-emerald-50 border-emerald-200 text-emerald-800",
});
form.reset();
router.push("/d/user/dashboard/orders/current");
},
onError: () => {
toast({
title: "Failed to create order",
description: "Please try again or contact support",
variant: "destructive",
});
},
});
const form = useForm<CreateOrderDto>({
resolver: zodResolver(CreateOrderSchema),
defaultValues: {
foodType: undefined,
description: "",
orderDetails: {
JAINS: { items: [] },
DASAS: { items: [] },
"INDIAN GUESTS": { items: [] },
"INTERNATIONAL GUESTS": { items: [] },
STAFF: { items: [] },
},
},
});
const {
fields: jainFields,
append: appendJain,
remove: removeJain,
} = useFieldArray({
control: form.control,
name: "orderDetails.JAINS.items",
});
const {
fields: dasaFields,
append: appendDasa,
remove: removeDasa,
} = useFieldArray({
control: form.control,
name: "orderDetails.DASAS.items",
});
const {
fields: indianGuestFields,
append: appendIndianGuest,
remove: removeIndianGuest,
} = useFieldArray({
control: form.control,
name: "orderDetails.INDIAN GUESTS.items",
});
const {
fields: internationalGuestFields,
append: appendInternationalGuest,
remove: removeInternationalGuest,
} = useFieldArray({
control: form.control,
name: "orderDetails.INTERNATIONAL GUESTS.items",
});
const {
fields: staffFields,
append: appendStaff,
remove: removeStaff,
} = useFieldArray({
control: form.control,
name: "orderDetails.STAFF.items",
});
const { data: menus, isLoading } = useQuery<Menu[]>({
queryKey: ["menu"],
queryFn: async () => {
const { data } = await client.get("menu/today/user");
return data;
},
});
const onSubmit = (data: CreateOrderDto) => {
order(data);
};
const getAvailableMenus = (
foodType: FoodType | undefined,
selectedMenus: string[],
currentMenuItem?: string
) => {
return menus?.filter(
(menu) =>
(!foodType || menu.type.includes(foodType)) &&
(!selectedMenus.includes(menu.name) || menu.name === currentMenuItem)
);
};
const handleCountChange = (
index: number,
userType: UserTypes,
action: "increment" | "decrement"
) => {
const path = `orderDetails.${userType}.items.${index}.count`;
const currentCount = form.getValues(path as any);
const newCount =
action === "increment" ? currentCount + 1 : Math.max(1, currentCount - 1);
form.setValue(path as any, newCount);
};
const renderOrderSection = (
userType: UserTypes,
fields: any[],
append: any,
remove: any
) => {
const selectedMenus = fields.map((field) => field.menu);
const foodType = form.watch("foodType");
return (
<section className="space-y-4">
<div className="flex justify-between items-center">
<h3 className="font-medium text-emerald-800 flex items-center">
{userType} Orders
{fields.length > 0 && (
<Badge className="ml-2 bg-emerald-100 text-emerald-800 border-emerald-200">
{fields.length} {fields.length === 1 ? "item" : "items"}
</Badge>
)}
</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ menu: "", count: 1 })}
disabled={!getAvailableMenus(foodType, selectedMenus)?.length}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Plus className="mr-2 h-4 w-4" /> Add Item
</Button>
</div>
{fields.length === 0 ? (
<div className="text-center py-4 bg-gray-50 rounded-md border border-gray-200">
<p className="text-sm text-gray-500">
No items added yet. Click "Add Item" to begin.
</p>
</div>
) : (
<div className="space-y-3">
{fields.map((field, index) => {
const currentMenu = field.menu;
const availableMenus = getAvailableMenus(
foodType,
selectedMenus,
currentMenu
);
return (
<div
key={field.id}
className="flex gap-3 items-center border border-gray-200 p-3 rounded-md bg-gray-50"
>
<FormField
control={form.control}
name={`orderDetails.${userType}.items.${index}.menu`}
render={({ field }) => (
<FormItem className="flex-1 mb-0">
<Select
value={field.value}
onValueChange={field.onChange}
>
<SelectTrigger className="border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Select item" />
</SelectTrigger>
<SelectContent>
{availableMenus?.map((menu) => (
<SelectItem key={menu.name} value={menu.name}>
{menu.name}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() =>
handleCountChange(index, userType, "decrement")
}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50"
>
<Minus className="h-4 w-4" />
</Button>
<Input
{...form.register(
`orderDetails.${userType}.items.${index}.count`,
{ valueAsNumber: true }
)}
className="w-16 text-center border-gray-200 focus:ring-emerald-500"
min={1}
type="number"
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() =>
handleCountChange(index, userType, "increment")
}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50"
>
<Plus className="h-4 w-4" />
</Button>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => remove(index)}
className="text-red-500 hover:text-red-700 hover:bg-red-50"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
);
})}
</div>
)}
</section>
);
};
return (
<div className="p-6 max-w-7xl lg:mx-auto">
<h1 className="text-2xl font-bold text-emerald-800 mb-6">
Place New Order
</h1>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-lg font-semibold text-emerald-800">
Order Information
</CardTitle>
</CardHeader>
<CardContent className="p-6">
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-6"
>
<FormField
control={form.control}
name="foodType"
render={({ field }) => (
<FormItem>
<FormLabel className="text-emerald-700">
Meal Type
</FormLabel>
<Select
onValueChange={field.onChange}
value={field.value}
>
<SelectTrigger className="w-full border-gray-200 focus:ring-emerald-500">
<SelectValue placeholder="Select meal type" />
</SelectTrigger>
<SelectContent>
{Object.values(FoodType).map((type) => (
<SelectItem key={type} value={type}>
{type.charAt(0) + type.slice(1).toLowerCase()}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
{form.watch("foodType") && (
<>
<div className="space-y-6 pt-2 border-t border-gray-100">
{renderOrderSection(
UserTypes.JAINS,
jainFields,
appendJain,
removeJain
)}
</div>
<div className="space-y-6 pt-2 border-t border-gray-100">
{renderOrderSection(
UserTypes.DASAS,
dasaFields,
appendDasa,
removeDasa
)}
</div>
<div className="space-y-6 pt-2 border-t border-gray-100">
{renderOrderSection(
UserTypes.INDIAN_GUESTS,
indianGuestFields,
appendIndianGuest,
removeIndianGuest
)}
</div>
<div className="space-y-6 pt-2 border-t border-gray-100">
{renderOrderSection(
UserTypes.INTERNATIONAL_GUESTS,
internationalGuestFields,
appendInternationalGuest,
removeInternationalGuest
)}
</div>
<div className="space-y-6 pt-2 border-t border-gray-100">
{renderOrderSection(
UserTypes.STAFF,
staffFields,
appendStaff,
removeStaff
)}
</div>
{form.formState.errors.orderDetails && (
<div className="bg-red-50 p-3 rounded-md border border-red-200 flex items-start">
<AlertCircle className="h-5 w-5 text-red-500 mr-2 mt-0.5" />
<p className="text-sm text-red-700">
{form.formState.errors.orderDetails.message}
</p>
</div>
)}
<Button
type="submit"
className="w-full mt-6 bg-emerald-600 hover:bg-emerald-700"
disabled={!form.formState.isValid || isPending}
>
{isPending ? "Placing Order..." : "Place Order"}
</Button>
</>
)}
</form>
</Form>
</CardContent>
</Card>
</div>
<div className="space-y-4">
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<CardTitle className="text-lg font-semibold text-emerald-800">
Today's Menu
</CardTitle>
</CardHeader>
<CardContent className="p-0">
<Table>
<TableHeader className="bg-gray-50">
<TableRow>
<TableHead className="w-[50px] text-emerald-700 font-medium">
#
</TableHead>
<TableHead className="text-emerald-700 font-medium">
Item Name
</TableHead>
<TableHead className="text-emerald-700 font-medium">
Type
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoading ? (
Array(3)
.fill(0)
.map((_, i) => (
<TableRow key={i}>
<TableCell>
<Skeleton className="h-4 w-4" />
</TableCell>
<TableCell>
<Skeleton className="h-4 w-full" />
</TableCell>
<TableCell>
<Skeleton className="h-4 w-20" />
</TableCell>
</TableRow>
))
) : menus?.length ? (
menus.map((menu, index) => (
<TableRow key={menu.id} className="hover:bg-emerald-50">
<TableCell>{index + 1}</TableCell>
<TableCell className="font-medium text-emerald-700">
{menu.name}
</TableCell>
<TableCell>
<div className="flex gap-1 flex-wrap">
{menu.type.map((type) => (
<Badge
key={type}
className="bg-amber-100 text-amber-800 border-amber-200"
>
{type.charAt(0) + type.slice(1).toLowerCase()}
</Badge>
))}
</div>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={3} className="text-center py-8">
<div className="flex flex-col items-center text-gray-500">
<UtensilsCrossed className="h-8 w-8 text-gray-300 mb-2" />
<p>No menu available today</p>
</div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,368 @@
"use client";
import client from "@/lib/client";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import { format } from "date-fns";
import {
AlertCircle,
CheckCircle2,
Clock,
RefreshCw,
ShoppingBag,
XCircle,
ArrowLeft,
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import Link from "next/link";
import {
getStatusColor,
getStatusIcon,
getStatusProgress,
} from "@/lib/status-progress";
import { Order } from "@anujs.dev/inventory-types-utils";
export default function Page() {
const { id } = useParams();
const {
data: order,
isLoading,
error,
refetch,
isFetching,
} = useQuery<Order>({
queryKey: ["orders", id],
queryFn: async () => {
const { data } = await client.get(`order/${id}`);
return data;
},
refetchInterval: 3e5,
});
if (isLoading) {
return (
<div className="p-3 sm:p-6 max-w-4xl mx-auto">
<div className="mb-4 flex items-center">
<Link
href="/d/user/dashboard/orders/current"
className="text-emerald-600 hover:text-emerald-700 flex items-center"
>
<ArrowLeft className="h-4 w-4 mr-1" />
<span className="text-sm">Back to Orders</span>
</Link>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 p-4 sm:p-6">
<Skeleton className="h-7 sm:h-8 w-36 sm:w-48" />
<Skeleton className="h-4 w-28 sm:w-32 mt-2" />
</CardHeader>
<CardContent className="p-4 sm:p-6">
<div className="space-y-4 sm:space-y-6">
<Skeleton className="h-2 w-full rounded-full" />
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">
<div className="space-y-3 sm:space-y-4">
<Skeleton className="h-5 w-32" />
<div className="space-y-2">
<div className="flex justify-between">
<Skeleton className="h-4 w-20 sm:w-24" />
<Skeleton className="h-4 w-24 sm:w-32" />
</div>
<div className="flex justify-between">
<Skeleton className="h-4 w-20 sm:w-24" />
<Skeleton className="h-4 w-24 sm:w-32" />
</div>
</div>
</div>
<div className="space-y-3 sm:space-y-4">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-12 w-full rounded-lg" />
</div>
</div>
<Skeleton className="h-6 w-32 mt-4" />
<div className="space-y-3">
<Skeleton className="h-12 w-full rounded-lg" />
<Skeleton className="h-12 w-full rounded-lg" />
</div>
<div className="flex justify-center sm:justify-end">
<Skeleton className="h-9 sm:h-10 w-36 sm:w-40 rounded-lg" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (error) {
return (
<div className="p-3 sm:p-6 max-w-4xl mx-auto">
<div className="mb-4 flex items-center">
<Link
href="/d/user/dashboard/orders/current"
className="text-emerald-600 hover:text-emerald-700 flex items-center"
>
<ArrowLeft className="h-4 w-4 mr-1" />
<span className="text-sm">Back to Orders</span>
</Link>
</div>
<Card className="border-red-200 shadow-sm">
<CardContent className="p-4 sm:p-6">
<div className="flex flex-col items-center justify-center text-center py-6 sm:py-10">
<AlertCircle className="h-10 sm:h-12 w-10 sm:w-12 text-red-500 mb-3 sm:mb-4" />
<h3 className="text-base sm:text-lg font-medium text-red-800 mb-2">
Error Loading Order
</h3>
<p className="text-red-600 mb-4 sm:mb-6">
We couldn't load the order details. Please try again.
</p>
<Button
onClick={() => refetch()}
variant="outline"
className="border-red-200 text-red-700 hover:bg-red-50"
>
<RefreshCw className="mr-2 h-4 w-4" />
Try Again
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
if (!order) {
return (
<div className="p-3 sm:p-6 max-w-4xl mx-auto">
<div className="mb-4 flex items-center">
<Link
href="/d/user/dashboard/orders/current"
className="text-emerald-600 hover:text-emerald-700 flex items-center"
>
<ArrowLeft className="h-4 w-4 mr-1" />
<span className="text-sm">Back to Orders</span>
</Link>
</div>
<Card className="border-amber-200 shadow-sm">
<CardContent className="p-4 sm:p-6">
<div className="flex flex-col items-center justify-center text-center py-6 sm:py-10">
<AlertCircle className="h-10 sm:h-12 w-10 sm:w-12 text-amber-500 mb-3 sm:mb-4" />
<h3 className="text-base sm:text-lg font-medium text-amber-800 mb-2">
Order Not Found
</h3>
<p className="text-amber-600 mb-4 sm:mb-6">
The order you're looking for doesn't exist or may have been
removed.
</p>
<Button
onClick={() => window.history.back()}
variant="outline"
className="border-amber-200 text-amber-700 hover:bg-amber-50"
>
Go Back
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
const progress = getStatusProgress(order.status);
const statusColor = getStatusColor(order.status);
const statusIcon = getStatusIcon(order.status);
return (
<div className="p-3 sm:p-6 max-w-4xl mx-auto">
<div className="mb-4 flex items-center">
<Link
href="/d/user/dashboard/orders/current"
className="text-emerald-600 hover:text-emerald-700 flex items-center"
>
<ArrowLeft className="h-4 w-4 mr-1" />
<span className="text-sm">Back to Orders</span>
</Link>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 p-4 sm:p-6">
<div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-2 sm:gap-0">
<div>
<CardTitle className="text-xl sm:text-2xl font-bold text-emerald-800">
Order Details
</CardTitle>
<p className="text-sm text-emerald-600 mt-1">ID: {order.id}</p>
</div>
<Badge
className={`px-3 py-1.5 rounded-full text-sm font-medium capitalize flex items-center gap-1.5 self-start sm:self-auto ${statusColor}`}
variant="outline"
>
{statusIcon}
{order.status.toLowerCase()}
</Badge>
</div>
</CardHeader>
<CardContent className="p-4 sm:p-6">
{order.status !== "CANCELLED" ? (
<div className="mb-4 sm:mb-6">
<div className="h-2.5 bg-gray-100 rounded-full overflow-hidden border border-gray-200">
<div
className={`h-2.5 ${
order.status === "COMPLETED"
? "bg-emerald-500"
: "bg-emerald-400"
} transition-all duration-500 ease-in-out`}
style={{ width: `${progress}%` }}
/>
</div>
<div className="flex justify-between mt-2 text-[10px] sm:text-xs">
<p className="text-emerald-700 font-medium">Order Placed</p>
<p className="text-emerald-700 font-medium">Preparing</p>
<p className="text-emerald-700 font-medium">Completed</p>
</div>
</div>
) : (
<div className="mb-4 sm:mb-6 p-3 bg-red-50 border border-red-100 rounded-lg flex items-center gap-2 text-red-700">
<XCircle className="h-5 w-5 text-red-500 flex-shrink-0" />
<p className="text-sm font-medium">
This order has been cancelled
</p>
</div>
)}
{order.description && (
<div className="mb-4 sm:mb-6 p-3 sm:p-4 bg-emerald-50 border border-emerald-100 rounded-lg">
<h3 className="font-medium text-sm text-emerald-700 mb-1">
Cook Update
</h3>
<p className="italic text-sm text-emerald-800 break-words">
"{order.description}"
</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
<Card className="border-gray-200 shadow-sm">
<CardHeader className="pb-2 pt-3 px-3 sm:px-4">
<CardTitle className="text-sm font-medium text-emerald-700">
Order Information
</CardTitle>
</CardHeader>
<CardContent className="pt-0 px-3 sm:px-4 pb-3">
<dl className="grid grid-cols-2 gap-2 text-sm">
<dt className="text-gray-600 font-medium">Order Date:</dt>
<dd className="text-gray-800 text-right sm:text-left break-words">
{format(new Date(order.created_at), "PP")}
<span className="block text-xs text-gray-500">
{format(new Date(order.created_at), "p")}
</span>
</dd>
<dt className="text-gray-600 font-medium">Meal Type:</dt>
<dd className="text-gray-800 text-right sm:text-left capitalize">
{order.foodType.toLowerCase()}
</dd>
<dt className="text-gray-600 font-medium">Last Updated:</dt>
<dd className="text-gray-800 text-right sm:text-left break-words">
{format(new Date(order.updated_at), "PP")}
<span className="block text-xs text-gray-500">
{format(new Date(order.updated_at), "p")}
</span>
</dd>
</dl>
</CardContent>
</Card>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="pb-2 pt-3 px-3 sm:px-4">
<CardTitle className="text-sm font-medium text-emerald-700">
Acceptance Status
</CardTitle>
</CardHeader>
<CardContent className="pt-0 px-3 sm:px-4 pb-3">
<div
className={`flex items-center gap-3 p-3 rounded-lg ${
order.isAccepted
? "bg-emerald-50 border border-emerald-100"
: "bg-amber-50 border border-amber-100"
}`}
>
{order.isAccepted ? (
<CheckCircle2 className="h-5 w-5 text-emerald-500 flex-shrink-0" />
) : (
<Clock className="h-5 w-5 text-amber-500 flex-shrink-0" />
)}
<span
className={`text-sm font-medium ${
order.isAccepted ? "text-emerald-700" : "text-amber-700"
}`}
>
{order.isAccepted ? "Order Accepted" : "Pending Acceptance"}
</span>
</div>
</CardContent>
</Card>
</div>
<div className="pt-2">
<h3 className="text-base sm:text-lg font-medium text-emerald-800 mb-3 sm:mb-4">
Order Items
</h3>
<Separator className="mb-4 sm:mb-6 bg-gray-200" />
{Object.entries(order.orderDetails).map(
([category, details]) =>
details.items.length > 0 && (
<div key={category} className="mb-4 sm:mb-6 last:mb-0">
<h4 className="font-medium text-emerald-700 mb-2 sm:mb-3 pb-2 border-b border-gray-200 flex flex-wrap items-center gap-2">
<span>{category}</span>
<Badge
variant="outline"
className="bg-emerald-50 text-emerald-700 border-emerald-200"
>
{details.items.length}{" "}
{details.items.length === 1 ? "item" : "items"}
</Badge>
</h4>
<div className="grid grid-cols-1 gap-2">
{details.items.map((item, index) => (
<div
key={index}
className="flex justify-between items-center p-3 bg-gray-50 rounded-lg border border-gray-200 hover:bg-gray-100 transition-colors"
>
<span className="font-medium text-gray-800 break-words pr-2">
{item.menu}
</span>
<Badge className="bg-emerald-100 text-emerald-800 hover:bg-emerald-200 border-none flex-shrink-0">
x{item.count}
</Badge>
</div>
))}
</div>
</div>
)
)}
</div>
<div className="mt-6 sm:mt-8 flex justify-center sm:justify-end">
<Button
onClick={() => refetch()}
className="bg-emerald-600 hover:bg-emerald-700 text-white w-full sm:w-auto"
disabled={isFetching}
>
<RefreshCw
className={`mr-2 h-4 w-4 ${isFetching ? "animate-spin" : ""}`}
/>
{isFetching ? "Refreshing..." : "Refresh Order Status"}
</Button>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,222 @@
"use client";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import client from "@/lib/client";
import { Order } from "@anujs.dev/inventory-types-utils";
import { useQuery } from "@tanstack/react-query";
import { formatDistanceToNow } from "date-fns";
import {
CheckCircle2,
ChevronRight,
Clock,
LayoutDashboard,
} from "lucide-react";
import Link from "next/link";
export default function UserDashboard() {
const { data: orders, isLoading } = useQuery<Order[]>({
queryKey: ["orders"],
queryFn: async () => {
const { data } = await client.get("/order/mine");
return data;
},
});
const totalOrders = orders?.length ?? 0;
const completedOrders =
orders?.filter((o) => o.status === "COMPLETED").length ?? 0;
const pendingOrders =
orders?.filter((o) => o.status !== "COMPLETED" && o.status !== "CANCELLED")
.length ?? 0;
const latestOrders = orders?.slice(0, 3) ?? [];
if (isLoading) {
return (
<div className="p-6 max-w-6xl mx-auto space-y-6">
<div>
<Skeleton className="h-8 w-[250px] mb-2" />
<Skeleton className="h-4 w-[300px]" />
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
{[1, 2, 3].map((i) => (
<Card key={i} className="border-gray-200 shadow-sm">
<CardContent className="p-4">
<Skeleton className="h-4 w-[100px] mb-2" />
<Skeleton className="h-8 w-[60px]" />
</CardContent>
</Card>
))}
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="pb-2">
<Skeleton className="h-6 w-[150px]" />
</CardHeader>
<CardContent>
{[1, 2, 3].map((i) => (
<div key={i} className="mb-3">
<Skeleton className="h-20 w-full rounded-md" />
</div>
))}
</CardContent>
</Card>
</div>
);
}
return (
<div className="p-6 max-w-6xl mx-auto space-y-6">
<div>
<h1 className="text-2xl font-bold text-emerald-800">
👋 Welcome back!
</h1>
<p className="text-sm text-gray-500 mt-1">
Here&apos;s what&apos;s happening with your orders.
</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card className="border-gray-200 shadow-sm">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500 mb-1">Total Orders</p>
<p className="text-2xl font-bold text-emerald-800">
{totalOrders}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center">
<LayoutDashboard className="h-5 w-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="border-gray-200 shadow-sm">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500 mb-1">Completed</p>
<p className="text-2xl font-bold text-emerald-700">
{completedOrders}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center">
<CheckCircle2 className="h-5 w-5 text-emerald-600" />
</div>
</div>
</CardContent>
</Card>
<Card className="border-gray-200 shadow-sm">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-500 mb-1">Active</p>
<p className="text-2xl font-bold text-amber-600">
{pendingOrders}
</p>
</div>
<div className="h-10 w-10 rounded-full bg-amber-100 flex items-center justify-center">
<Clock className="h-5 w-5 text-amber-600" />
</div>
</div>
</CardContent>
</Card>
</div>
<Card className="border-gray-200 shadow-sm">
<CardHeader className="bg-emerald-50 border-b border-gray-200 py-4">
<div className="flex justify-between items-center">
<CardTitle className="text-lg font-semibold text-emerald-800">
Recent Orders
</CardTitle>
<Button
variant="outline"
size="sm"
asChild
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Link href="/d/user/dashboard/orders/current">
View All <ChevronRight className="ml-1 h-4 w-4" />
</Link>
</Button>
</div>
</CardHeader>
<CardContent className="p-4">
{latestOrders.length === 0 ? (
<div className="text-center py-8 bg-gray-50 rounded-md border border-gray-200">
<p className="text-gray-500">You have no orders yet.</p>
<Button
className="mt-4 bg-emerald-600 hover:bg-emerald-700"
asChild
>
<Link href="/d/user/dashboard/orders/new">
Place Your First Order
</Link>
</Button>
</div>
) : (
<ul className="space-y-3">
{latestOrders.map((order) => (
<li
key={order.id}
className="border border-gray-200 rounded-md p-4 hover:border-emerald-200 hover:shadow-sm transition-all"
>
<div className="flex justify-between items-start">
<div>
<p className="font-medium text-emerald-800">
Order #{order.id.slice(0, 8).toUpperCase()}
</p>
<p className="text-xs text-gray-500 mt-1">
{formatDistanceToNow(new Date(order.created_at))} ago {" "}
<span className="capitalize">
{order.foodType.toLowerCase()}
</span>
</p>
</div>
<Badge
className={
order.status === "COMPLETED"
? "bg-emerald-100 text-emerald-800 border-emerald-200"
: order.status === "PENDING"
? "bg-amber-100 text-amber-800 border-amber-200"
: order.status === "CANCELLED"
? "bg-red-100 text-red-800 border-red-200"
: "bg-blue-100 text-blue-800 border-blue-200"
}
>
{order.status.charAt(0) +
order.status.slice(1).toLowerCase()}
</Badge>
</div>
<div className="mt-3 flex justify-end">
<Button
variant="outline"
size="sm"
asChild
className="text-xs border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800"
>
<Link
href={`/d/user/dashboard/orders/status/${order.id}`}
>
View Details
</Link>
</Button>
</div>
</li>
))}
</ul>
)}
</CardContent>
</Card>
</div>
);
}

20
src/app/d/user/layout.tsx Normal file
View File

@@ -0,0 +1,20 @@
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import React from "react";
import { AppSidebar } from "./components/user-sidebar";
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<SidebarProvider>
<AppSidebar />
<main className="w-full min-h-screen items-start justify-between flex flex-col">
<div className="w-full">
<SidebarTrigger />
<div className="w-full">{children}</div>
</div>
<p className="justify-self-end w-full text-sm text-center bg-emerald-700 text-white ">
Powered by Aurelion Future Forge
</p>
</main>
</SidebarProvider>
);
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

111
src/app/globals.css Normal file
View File

@@ -0,0 +1,111 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
font-family: var(--font-inter), Arial, Helvetica, sans-serif;
}
@layer base {
:root {
}
}
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 0 0% 3.9%;
--card: 0 0% 100%;
--card-foreground: 0 0% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 3.9%;
--primary: 0 0% 9%;
--primary-foreground: 0 0% 98%;
--secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%;
--accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 89.8%;
--input: 0 0% 89.8%;
--ring: 0 0% 3.9%;
--radius: 0.3rem;
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
--sidebar-background: 233 48% 29%;
--sidebar-foreground: 0 0% 100%;
--sidebar-primary: 0 0% 100%;
--sidebar-primary-foreground: 233 48% 29%;
--sidebar-accent: 233 48% 22%;
--sidebar-accent-foreground: 0 0% 100%;
--sidebar-border: 233 48% 22%;
--sidebar-ring: 233 48% 45%;
}
.dark {
--background: 0 0% 3.9%;
--foreground: 0 0% 98%;
--card: 0 0% 3.9%;
--card-foreground: 0 0% 98%;
--popover: 0 0% 3.9%;
--popover-foreground: 0 0% 98%;
--primary: 0 0% 98%;
--primary-foreground: 0 0% 9%;
--secondary: 0 0% 14.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 14.9%;
--muted-foreground: 0 0% 63.9%;
--accent: 0 0% 14.9%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 14.9%;
--input: 0 0% 14.9%;
--ring: 0 0% 83.1%;
--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
--sidebar-background: 240 5.9% 10%;
--sidebar-foreground: 240 4.8% 95.9%;
--sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-border: 240 3.7% 15.9%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
.gr-to-gold {
background: linear-gradient(
to right,
/* #bf953f,
#fcf6ba, */ #b38728,
#fbf5b7,
#aa771c
);
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

41
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,41 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono, Inter } from "next/font/google";
import "./globals.css";
import RootProviders from "./providers";
import { Toaster } from "@/components/ui/toaster";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
const inter = Inter({
variable: "--font-inter",
subsets: ["latin"],
weight: ["400", "500", "600", "700"],
});
export const metadata: Metadata = {
title: "Ekam",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`${inter.variable} antialiased`}>
<RootProviders>{children}</RootProviders>
<Toaster />
</body>
</html>
);
}

10
src/app/logout.ts Normal file
View File

@@ -0,0 +1,10 @@
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export async function logoutFromServer() {
(await cookies()).delete("token");
redirect("/");
}

213
src/app/page.tsx Normal file
View File

@@ -0,0 +1,213 @@
"use client";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import client from "@/lib/client";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { CheckCircle2, EyeIcon, EyeOff, ShoppingBag } from "lucide-react";
const loginSchema = z.object({
email: z.string().email("Invalid email address"),
password: z.string().min(4, {
message: "Password must be at least 4 characters.",
}),
});
type FormType = z.infer<typeof loginSchema>;
export default function Home() {
const router = useRouter();
const [verified, setVerified] = useState(false);
const { toast } = useToast();
const [showPassword, setShowPassword] = useState(false);
const [isCheckingEmail, setIsCheckingEmail] = useState(false);
const [isLoggingIn, setIsLoggingIn] = useState(false);
const { mutate: checkEmail } = useMutation({
mutationFn: async () => {
setIsCheckingEmail(true);
await client.get(`user/check/${form.getValues("email")}`);
},
onSuccess: () => {
setVerified(true);
setIsCheckingEmail(false);
},
onError: () => {
toast({
title: "Email not found",
description: "Please check your email address and try again",
variant: "destructive",
});
setIsCheckingEmail(false);
},
});
const { mutate: login } = useMutation({
mutationFn: async () => {
setIsLoggingIn(true);
await client.post(`auth/login`, {
email: form.getValues("email"),
password: form.getValues("password"),
});
},
onSuccess: () => {
toast({
title: "Login successful 👍",
duration: 800,
className: "bg-emerald-500 text-white",
});
router.refresh();
},
onError: () => {
toast({
title: "Login failed",
description: "Incorrect password. Please try again.",
variant: "destructive",
});
setIsLoggingIn(false);
},
});
const form = useForm<FormType>({
defaultValues: {
email: "",
password: "",
},
resolver: zodResolver(loginSchema),
});
function onSubmit(values: FormType) {
login();
}
return (
<div className="flex px-5 items-center justify-center min-h-screen bg-gray-50">
<div className="w-full max-w-4xl mx-auto shadow-lg rounded-lg overflow-hidden bg-white">
<div className="grid lg:grid-cols-2">
<div className="p-10 row-start-2 lg:row-start-1">
<div className="mb-8">
<h2 className="text-2xl font-bold text-gray-800">Sign in</h2>
<p className="text-gray-600">to access Food Admin</p>
</div>
<Form {...form}>
<form
className="space-y-4"
onSubmit={form.handleSubmit(onSubmit)}
>
<div className="space-y-6">
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="relative">
<Input
type="email"
placeholder="Email address"
className="h-12 border-gray-300 focus:border-emerald-500 focus:ring-emerald-500 rounded-md"
disabled={verified}
{...field}
/>
{verified && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<CheckCircle2 className="h-5 w-5 text-emerald-500" />
</div>
)}
</div>
</FormControl>
<FormMessage className="text-red-500 text-sm" />
</FormItem>
)}
/>
{!verified ? (
<Button
className="w-full h-12 bg-emerald-500 hover:bg-emerald-600 text-white font-medium rounded-md"
type="button"
onClick={() => checkEmail()}
disabled={
!form.getFieldState("email").isDirty || isCheckingEmail
}
>
{isCheckingEmail ? "Checking..." : "Next"}
</Button>
) : (
<>
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormControl>
<div className="relative">
<Input
className="h-12 border-gray-300 focus:border-emerald-500 focus:ring-emerald-500 rounded-md pr-10"
type={showPassword ? "text" : "password"}
placeholder="Password"
{...field}
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-emerald-600"
>
{showPassword ? (
<EyeOff className="h-5 w-5" />
) : (
<EyeIcon className="h-5 w-5" />
)}
</button>
</div>
</FormControl>
<FormMessage className="text-red-500 text-sm" />
</FormItem>
)}
/>
<Button
className="w-full h-12 bg-emerald-500 hover:bg-emerald-600 text-white font-medium rounded-md"
type="submit"
disabled={!form.formState.isValid || isLoggingIn}
>
{isLoggingIn ? "Signing in..." : "Sign in"}
</Button>
</>
)}
</div>
</form>
</Form>
</div>
<div className="bg-emerald-50 flex flex-col items-center justify-center p-10">
<div className="w-full max-w-xs">
<img
src="/ekam.png"
alt="Food Admin Illustration"
className="w-full h-auto"
/>
</div>
</div>
</div>
</div>
<div className="absolute bottom-4 text-center text-xs text-gray-500">
Powered by Aurelion Future Forge
</div>
</div>
);
}

29
src/app/providers.tsx Normal file
View File

@@ -0,0 +1,29 @@
"use client";
import { useToast } from "@/hooks/use-toast";
import { ToastAction } from "@radix-ui/react-toast";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
export default function RootProviders({
children,
}: {
children: React.ReactNode;
}) {
const { toast } = useToast();
const qc = new QueryClient({
defaultOptions: {
mutations: {
onError(error, variables, context) {
toast({
title: "❕ Uh oh! Something went wrong.",
// @ts-expect-error error is not typed
description: error.response.data.message ?? "Something went wrong",
variant: "destructive",
duration: 800,
});
},
},
},
});
return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}

View File

@@ -0,0 +1,40 @@
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Trash2 } from "lucide-react";
import React from "react";
export function ConfirmAction(props: {
open: boolean;
onOpenChange: (value: ((prevState: boolean) => boolean) | boolean) => void;
onConfirm: () => void;
children: React.ReactNode;
}) {
return (
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
<DialogTrigger asChild>{props.children}</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure?</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
This action cannot be undone.
</p>
<DialogFooter className="pt-4">
<Button variant="outline" onClick={() => props.onOpenChange(false)}>
Cancel
</Button>
<Button variant="destructive" onClick={props.onConfirm}>
Confirm
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,163 @@
"use client";
import {
type ColumnDef,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
type SortingState,
useReactTable,
} from "@tanstack/react-table";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import React, { useState } from "react";
import type { QueryObserverResult, RefetchOptions } from "@tanstack/query-core";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
refetch: (
options?: RefetchOptions | undefined
) => Promise<QueryObserverResult<any, Error>>;
columnVisibility?: Record<string, boolean>;
}
export function DataTable<TData, TValue>({
columns,
data,
refetch,
columnVisibility = {},
}: DataTableProps<TData, TValue>) {
const [sorting, setSorting] = React.useState<SortingState>([]);
const [dateFilter, setDateFilter] = React.useState<SortingState>([]);
const [globalFilter, setGlobalFilter] = useState<any>([]);
const mergedColumnVisibility = {
id: false,
userType: false,
...columnVisibility,
};
const table = useReactTable({
initialState: {
columnVisibility: mergedColumnVisibility,
},
meta: {
refetch,
},
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
state: {
sorting,
},
});
return (
<div>
<div className="border-t border-gray-100">
<Table>
<TableHeader className="bg-gray-50">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead
key={header.id}
className="text-center border-r border-gray-100 [&:last-child]:border-r-0 text-emerald-700 font-medium py-3"
>
{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}
className="hover:bg-emerald-50 transition-colors border-b border-gray-100 [&:last-child]:border-b-0"
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="text-center border-r border-gray-100 [&:last-child]:border-r-0 py-3"
>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center text-gray-500"
>
No results found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-between p-4 border-t border-gray-100 bg-gray-50">
<div className="text-sm text-gray-500">
Showing{" "}
{table.getState().pagination.pageIndex *
table.getState().pagination.pageSize +
1}{" "}
to{" "}
{Math.min(
(table.getState().pagination.pageIndex + 1) *
table.getState().pagination.pageSize,
table.getRowModel().rows.length
)}{" "}
of {table.getRowModel().rows.length} entries
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800 disabled:opacity-50"
>
<ChevronLeft className="h-4 w-4 mr-1" /> Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
className="border-gray-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800 disabled:opacity-50"
>
Next <ChevronRight className="h-4 w-4 ml-1" />
</Button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,23 @@
import React from "react";
import { Button } from "./ui/button";
import { Column } from "@tanstack/react-table";
import { ArrowUpDown } from "lucide-react";
interface ISortingButtonProps {
children: React.ReactNode;
column: Column<any, unknown>;
}
export default function SortingButton({
children,
column,
}: ISortingButtonProps) {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
{children}
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
}

View File

@@ -0,0 +1,57 @@
"use client";
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDown } from "lucide-react";
import { cn } from "@anujs.dev/inventory-types-utils";
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
{...props}
/>
));
AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline text-left [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };

View File

@@ -0,0 +1,59 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@anujs.dev/inventory-types-utils";
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };

View File

@@ -0,0 +1,23 @@
import { FormLabel } from "@/components/ui/form";
import { cn } from "@anujs.dev/inventory-types-utils";
function AutoFormLabel({
label,
isRequired,
className,
}: {
label: string;
isRequired: boolean;
className?: string;
}) {
return (
<>
<FormLabel className={cn(className)}>
{label}
{isRequired && <span className="text-destructive"> *</span>}
</FormLabel>
</>
);
}
export default AutoFormLabel;

View File

@@ -0,0 +1,13 @@
function AutoFormTooltip({ fieldConfigItem }: { fieldConfigItem: any }) {
return (
<>
{fieldConfigItem?.description && (
<p className="text-sm text-gray-500 dark:text-white">
{fieldConfigItem.description}
</p>
)}
</>
);
}
export default AutoFormTooltip;

View File

@@ -0,0 +1,31 @@
import AutoFormCheckbox from "./fields/checkbox";
import AutoFormDate from "./fields/date";
import AutoFormEnum from "./fields/enum";
import AutoFormFile from "./fields/file";
import AutoFormInput from "./fields/input";
import AutoFormNumber from "./fields/number";
import AutoFormRadioGroup from "./fields/radio-group";
import AutoFormSwitch from "./fields/switch";
import AutoFormTextarea from "./fields/textarea";
export const INPUT_COMPONENTS = {
checkbox: AutoFormCheckbox,
date: AutoFormDate,
select: AutoFormEnum,
radio: AutoFormRadioGroup,
switch: AutoFormSwitch,
textarea: AutoFormTextarea,
number: AutoFormNumber,
file: AutoFormFile,
fallback: AutoFormInput,
};
export const DEFAULT_ZOD_HANDLERS: {
[key: string]: keyof typeof INPUT_COMPONENTS;
} = {
ZodBoolean: "checkbox",
ZodDate: "date",
ZodEnum: "select",
ZodNativeEnum: "select",
ZodNumber: "number",
};

View File

@@ -0,0 +1,57 @@
import { FieldValues, UseFormWatch } from "react-hook-form";
import { Dependency, DependencyType, EnumValues } from "./types";
import * as z from "zod";
export default function resolveDependencies<
SchemaType extends z.infer<z.ZodObject<any, any>>,
>(
dependencies: Dependency<SchemaType>[],
currentFieldName: keyof SchemaType,
watch: UseFormWatch<FieldValues>,
) {
let isDisabled = false;
let isHidden = false;
let isRequired = false;
let overrideOptions: EnumValues | undefined;
const currentFieldValue = watch(currentFieldName as string);
const currentFieldDependencies = dependencies.filter(
(dependency) => dependency.targetField === currentFieldName,
);
for (const dependency of currentFieldDependencies) {
const watchedValue = watch(dependency.sourceField as string);
const conditionMet = dependency.when(watchedValue, currentFieldValue);
switch (dependency.type) {
case DependencyType.DISABLES:
if (conditionMet) {
isDisabled = true;
}
break;
case DependencyType.REQUIRES:
if (conditionMet) {
isRequired = true;
}
break;
case DependencyType.HIDES:
if (conditionMet) {
isHidden = true;
}
break;
case DependencyType.SETS_OPTIONS:
if (conditionMet) {
overrideOptions = dependency.options;
}
break;
}
}
return {
isDisabled,
isHidden,
isRequired,
overrideOptions,
};
}

View File

@@ -0,0 +1,93 @@
import {
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { Plus, Trash } from "lucide-react";
import { useFieldArray, useForm } from "react-hook-form";
import * as z from "zod";
import { beautifyObjectName } from "../utils";
import AutoFormObject from "./object";
function isZodArray(
item: z.ZodArray<any> | z.ZodDefault<any>,
): item is z.ZodArray<any> {
return item instanceof z.ZodArray;
}
function isZodDefault(
item: z.ZodArray<any> | z.ZodDefault<any>,
): item is z.ZodDefault<any> {
return item instanceof z.ZodDefault;
}
export default function AutoFormArray({
name,
item,
form,
path = [],
fieldConfig,
}: {
name: string;
item: z.ZodArray<any> | z.ZodDefault<any>;
form: ReturnType<typeof useForm>;
path?: string[];
fieldConfig?: any;
}) {
const { fields, append, remove } = useFieldArray({
control: form.control,
name,
});
const title = item._def.description ?? beautifyObjectName(name);
const itemDefType = isZodArray(item)
? item._def.type
: isZodDefault(item)
? item._def.innerType._def.type
: null;
return (
<AccordionItem value={name} className="border-none">
<AccordionTrigger>{title}</AccordionTrigger>
<AccordionContent>
{fields.map((_field, index) => {
const key = _field.id;
return (
<div className="mt-4 flex flex-col" key={`${key}`}>
<AutoFormObject
schema={itemDefType as z.ZodObject<any, any>}
form={form}
fieldConfig={fieldConfig}
path={[...path, index.toString()]}
/>
<div className="my-4 flex justify-end">
<Button
variant="secondary"
size="icon"
type="button"
className="hover:bg-zinc-300 hover:text-black focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0 dark:bg-white dark:text-black dark:hover:bg-zinc-300 dark:hover:text-black dark:hover:ring-0 dark:hover:ring-offset-0 dark:focus-visible:ring-0 dark:focus-visible:ring-offset-0"
onClick={() => remove(index)}
>
<Trash className="size-4 " />
</Button>
</div>
<Separator />
</div>
);
})}
<Button
type="button"
variant="secondary"
onClick={() => append({})}
className="mt-4 flex items-center"
>
<Plus className="mr-2" size={16} />
Add
</Button>
</AccordionContent>
</AccordionItem>
);
}

View File

@@ -0,0 +1,34 @@
import { Checkbox } from "@/components/ui/checkbox";
import { FormControl, FormItem } from "@/components/ui/form";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
import AutoFormLabel from "../common/label";
export default function AutoFormCheckbox({
label,
isRequired,
field,
fieldConfigItem,
fieldProps,
}: AutoFormInputComponentProps) {
return (
<div>
<FormItem>
<div className="mb-3 flex items-center gap-3">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
{...fieldProps}
/>
</FormControl>
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
</div>
</FormItem>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
</div>
);
}

View File

@@ -0,0 +1,32 @@
import { DatePicker } from "@/components/ui/date-picker";
import { FormControl, FormItem, FormMessage } from "@/components/ui/form";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
export default function AutoFormDate({
label,
isRequired,
field,
fieldConfigItem,
fieldProps,
}: AutoFormInputComponentProps) {
return (
<FormItem>
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
<FormControl>
<DatePicker
date={field.value}
setDate={field.onChange}
{...fieldProps}
/>
</FormControl>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
<FormMessage />
</FormItem>
);
}

View File

@@ -0,0 +1,67 @@
import { FormControl, FormItem, FormMessage } from "@/components/ui/form";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import * as z from "zod";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
import { getBaseSchema } from "../utils";
export default function AutoFormEnum({
label,
isRequired,
field,
fieldConfigItem,
zodItem,
fieldProps,
}: AutoFormInputComponentProps) {
const baseValues = (getBaseSchema(zodItem) as unknown as z.ZodEnum<any>)._def
.values;
let values: [string, string][] = [];
if (!Array.isArray(baseValues)) {
values = Object.entries(baseValues);
} else {
values = baseValues.map((value) => [value, value]);
}
function findItem(value: any) {
return values.find((item) => item[0] === value);
}
return (
<FormItem>
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
<FormControl>
<Select
onValueChange={field.onChange}
defaultValue={field.value}
{...fieldProps}
>
<SelectTrigger className={fieldProps.className}>
<SelectValue placeholder={fieldConfigItem.inputProps?.placeholder}>
{field.value ? findItem(field.value)?.[1] : "Select an option"}
</SelectValue>
</SelectTrigger>
<SelectContent>
{values.map(([value, label]) => (
<SelectItem value={label} key={value}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
<FormMessage />
</FormItem>
);
}

View File

@@ -0,0 +1,67 @@
import { FormControl, FormItem, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Trash2 } from "lucide-react";
import { ChangeEvent, useState } from "react";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
export default function AutoFormFile({
label,
isRequired,
fieldConfigItem,
fieldProps,
field,
}: AutoFormInputComponentProps) {
const { showLabel: _showLabel, ...fieldPropsWithoutShowLabel } = fieldProps;
const showLabel = _showLabel === undefined ? true : _showLabel;
const [file, setFile] = useState<string | null>(null);
const [fileName, setFileName] = useState<string | null>(null);
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onloadend = () => {
setFile(reader.result as string);
setFileName(file.name);
field.onChange(reader.result as string);
};
reader.readAsDataURL(file);
}
};
const handleRemoveClick = () => {
setFile(null);
};
return (
<FormItem>
{showLabel && (
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
)}
{!file && (
<FormControl>
<Input
type="file"
{...fieldPropsWithoutShowLabel}
onChange={handleFileChange}
value={""}
/>
</FormControl>
)}
{file && (
<div className="flex h-[40px] w-full flex-row items-center justify-between space-x-2 rounded-sm border p-2 text-black focus-visible:ring-0 focus-visible:ring-offset-0 dark:bg-white dark:text-black dark:focus-visible:ring-0 dark:focus-visible:ring-offset-0">
<p>{fileName}</p>
<button onClick={handleRemoveClick} aria-label="Remove image">
<Trash2 size={16} />
</button>
</div>
)}
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
<FormMessage />
</FormItem>
);
}

View File

@@ -0,0 +1,34 @@
import { FormControl, FormItem, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
export default function AutoFormInput({
label,
isRequired,
fieldConfigItem,
fieldProps,
}: AutoFormInputComponentProps) {
const { showLabel: _showLabel, ...fieldPropsWithoutShowLabel } = fieldProps;
const showLabel = _showLabel === undefined ? true : _showLabel;
const type = fieldProps.type || "text";
return (
<div className="flex flex-row items-center space-x-2">
<FormItem className="flex w-full flex-col justify-start">
{showLabel && (
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
)}
<FormControl>
<Input type={type} {...fieldPropsWithoutShowLabel} />
</FormControl>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
<FormMessage />
</FormItem>
</div>
);
}

View File

@@ -0,0 +1,31 @@
import { FormControl, FormItem, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
export default function AutoFormNumber({
label,
isRequired,
fieldConfigItem,
fieldProps,
}: AutoFormInputComponentProps) {
const { showLabel: _showLabel, ...fieldPropsWithoutShowLabel } = fieldProps;
const showLabel = _showLabel === undefined ? true : _showLabel;
return (
<FormItem>
{showLabel && (
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
)}
<FormControl>
<Input type="number" {...fieldPropsWithoutShowLabel} />
</FormControl>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
<FormMessage />
</FormItem>
);
}

View File

@@ -0,0 +1,186 @@
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { FormField } from "@/components/ui/form";
import { useForm, useFormContext } from "react-hook-form";
import * as z from "zod";
import { DEFAULT_ZOD_HANDLERS, INPUT_COMPONENTS } from "../config";
import { Dependency, FieldConfig, FieldConfigItem } from "../types";
import {
beautifyObjectName,
getBaseSchema,
getBaseType,
sortFieldsByOrder,
zodToHtmlInputProps,
} from "../utils";
import AutoFormArray from "./array";
import resolveDependencies from "../dependencies";
function DefaultParent({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
export default function AutoFormObject<
SchemaType extends z.ZodObject<any, any>,
>({
schema,
form,
fieldConfig,
path = [],
dependencies = [],
}: {
schema: SchemaType | z.ZodEffects<SchemaType>;
form: ReturnType<typeof useForm>;
fieldConfig?: FieldConfig<z.infer<SchemaType>>;
path?: string[];
dependencies?: Dependency<z.infer<SchemaType>>[];
}) {
const { watch } = useFormContext(); // Use useFormContext to access the watch function
if (!schema) {
return null;
}
const { shape } = getBaseSchema<SchemaType>(schema) || {};
if (!shape) {
return null;
}
const handleIfZodNumber = (item: z.ZodAny) => {
const isZodNumber = (item as any)._def.typeName === "ZodNumber";
const isInnerZodNumber =
(item._def as any).innerType?._def?.typeName === "ZodNumber";
if (isZodNumber) {
(item as any)._def.coerce = true;
} else if (isInnerZodNumber) {
(item._def as any).innerType._def.coerce = true;
}
return item;
};
const sortedFieldKeys = sortFieldsByOrder(fieldConfig, Object.keys(shape));
return (
<Accordion type="multiple" className="space-y-5 border-none">
{sortedFieldKeys.map((name) => {
let item = shape[name] as z.ZodAny;
item = handleIfZodNumber(item) as z.ZodAny;
const zodBaseType = getBaseType(item);
const itemName = item._def.description ?? beautifyObjectName(name);
const key = [...path, name].join(".");
const {
isHidden,
isDisabled,
isRequired: isRequiredByDependency,
overrideOptions,
} = resolveDependencies(dependencies, name, watch);
if (isHidden) {
return null;
}
if (zodBaseType === "ZodObject") {
return (
<AccordionItem value={name} key={key} className="border-none">
<AccordionTrigger>{itemName}</AccordionTrigger>
<AccordionContent className="p-2">
<AutoFormObject
schema={item as unknown as z.ZodObject<any, any>}
form={form}
fieldConfig={
(fieldConfig?.[name] ?? {}) as FieldConfig<
z.infer<typeof item>
>
}
path={[...path, name]}
/>
</AccordionContent>
</AccordionItem>
);
}
if (zodBaseType === "ZodArray") {
return (
<AutoFormArray
key={key}
name={name}
item={item as unknown as z.ZodArray<any>}
form={form}
fieldConfig={fieldConfig?.[name] ?? {}}
path={[...path, name]}
/>
);
}
const fieldConfigItem: FieldConfigItem = fieldConfig?.[name] ?? {};
const zodInputProps = zodToHtmlInputProps(item);
const isRequired =
isRequiredByDependency ||
zodInputProps.required ||
fieldConfigItem.inputProps?.required ||
false;
if (overrideOptions) {
item = z.enum(overrideOptions) as unknown as z.ZodAny;
}
return (
<FormField
control={form.control}
name={key}
key={key}
render={({ field }) => {
const inputType =
fieldConfigItem.fieldType ??
DEFAULT_ZOD_HANDLERS[zodBaseType] ??
"fallback";
const InputComponent =
typeof inputType === "function"
? inputType
: INPUT_COMPONENTS[inputType];
const ParentElement =
fieldConfigItem.renderParent ?? DefaultParent;
const defaultValue = fieldConfigItem.inputProps?.defaultValue;
const value = field.value ?? defaultValue ?? "";
const fieldProps = {
...zodToHtmlInputProps(item),
...field,
...fieldConfigItem.inputProps,
disabled: fieldConfigItem.inputProps?.disabled || isDisabled,
ref: undefined,
value: value,
};
if (InputComponent === undefined) {
return <></>;
}
return (
<ParentElement key={`${key}.parent`}>
<InputComponent
zodInputProps={zodInputProps}
field={field}
fieldConfigItem={fieldConfigItem}
label={itemName}
isRequired={isRequired}
zodItem={item}
fieldProps={fieldProps}
className={fieldProps.className}
/>
</ParentElement>
);
}}
/>
);
})}
</Accordion>
);
}

View File

@@ -0,0 +1,63 @@
import {
FormControl,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import * as z from "zod";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
import { getBaseSchema } from "../utils";
export default function AutoFormRadioGroup({
label,
isRequired,
field,
zodItem,
fieldProps,
fieldConfigItem,
}: AutoFormInputComponentProps) {
const baseValues = (getBaseSchema(zodItem) as unknown as z.ZodEnum<any>)._def
.values;
let values: string[] = [];
if (!Array.isArray(baseValues)) {
values = Object.entries(baseValues).map((item) => item[0]);
} else {
values = baseValues;
}
return (
<div>
<FormItem>
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
<FormControl>
<RadioGroup
onValueChange={field.onChange}
defaultValue={field.value}
{...fieldProps}
>
{values?.map((value: any) => (
<FormItem
key={value}
className="mb-2 flex items-center gap-3 space-y-0"
>
<FormControl>
<RadioGroupItem value={value} />
</FormControl>
<FormLabel className="font-normal">{value}</FormLabel>
</FormItem>
))}
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
</div>
);
}

View File

@@ -0,0 +1,34 @@
import { FormControl, FormItem } from "@/components/ui/form";
import { Switch } from "@/components/ui/switch";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
export default function AutoFormSwitch({
label,
isRequired,
field,
fieldConfigItem,
fieldProps,
}: AutoFormInputComponentProps) {
return (
<div>
<FormItem>
<div className="flex items-center gap-3">
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
{...fieldProps}
/>
</FormControl>
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
</div>
</FormItem>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
</div>
);
}

View File

@@ -0,0 +1,30 @@
import { FormControl, FormItem, FormMessage } from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
import AutoFormLabel from "../common/label";
import AutoFormTooltip from "../common/tooltip";
import { AutoFormInputComponentProps } from "../types";
export default function AutoFormTextarea({
label,
isRequired,
fieldConfigItem,
fieldProps,
}: AutoFormInputComponentProps) {
const { showLabel: _showLabel, ...fieldPropsWithoutShowLabel } = fieldProps;
const showLabel = _showLabel === undefined ? true : _showLabel;
return (
<FormItem>
{showLabel && (
<AutoFormLabel
label={fieldConfigItem?.label || label}
isRequired={isRequired}
/>
)}
<FormControl>
<Textarea {...fieldPropsWithoutShowLabel} />
</FormControl>
<AutoFormTooltip fieldConfigItem={fieldConfigItem} />
<FormMessage />
</FormItem>
);
}

View File

@@ -0,0 +1,129 @@
"use client";
import { Form } from "@/components/ui/form";
import React from "react";
import {
DefaultValues,
FormState,
useForm,
UseFormReturn,
} from "react-hook-form";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { cn } from "@anujs.dev/inventory-types-utils";
import { zodResolver } from "@hookform/resolvers/zod";
import AutoFormObject from "./fields/object";
import { Dependency, FieldConfig } from "./types";
import {
getDefaultValues,
getObjectFormSchema,
ZodObjectOrWrapped,
} from "./utils";
export function AutoFormSubmit({
children,
className,
disabled,
}: {
children?: React.ReactNode;
className?: string;
disabled?: boolean;
}) {
return (
<Button type="submit" disabled={disabled} className={className}>
{children ?? "Submit"}
</Button>
);
}
function AutoForm<SchemaType extends ZodObjectOrWrapped>({
formSchema,
values: valuesProp,
onValuesChange: onValuesChangeProp,
onParsedValuesChange,
onSubmit: onSubmitProp,
fieldConfig,
children,
className,
dependencies,
}: {
formSchema: SchemaType;
values?: Partial<z.infer<SchemaType>>;
onValuesChange?: (
values: Partial<z.infer<SchemaType>>,
form: UseFormReturn<z.infer<SchemaType>>
) => void;
onParsedValuesChange?: (
values: Partial<z.infer<SchemaType>>,
form: UseFormReturn<z.infer<SchemaType>>
) => void;
onSubmit?: (
values: z.infer<SchemaType>,
form: UseFormReturn<z.infer<SchemaType>>
) => void;
fieldConfig?: FieldConfig<z.infer<SchemaType>>;
children?:
| React.ReactNode
| ((formState: FormState<z.infer<SchemaType>>) => React.ReactNode);
className?: string;
dependencies?: Dependency<z.infer<SchemaType>>[];
}) {
const objectFormSchema = getObjectFormSchema(formSchema);
const defaultValues: DefaultValues<z.infer<typeof objectFormSchema>> | null =
getDefaultValues(objectFormSchema, fieldConfig);
const form = useForm<z.infer<typeof objectFormSchema>>({
resolver: zodResolver(formSchema),
defaultValues: defaultValues ?? undefined,
values: valuesProp,
});
function onSubmit(values: z.infer<typeof formSchema>) {
const parsedValues = formSchema.safeParse(values);
if (parsedValues.success) {
onSubmitProp?.(parsedValues.data, form);
}
}
React.useEffect(() => {
const subscription = form.watch((values) => {
onValuesChangeProp?.(values, form);
const parsedValues = formSchema.safeParse(values);
if (parsedValues.success) {
onParsedValuesChange?.(parsedValues.data, form);
}
});
return () => subscription.unsubscribe();
}, [form, formSchema, onValuesChangeProp, onParsedValuesChange]);
const renderChildren =
typeof children === "function"
? children(form.formState as FormState<z.infer<SchemaType>>)
: children;
return (
<div className="w-full">
<Form {...form}>
<form
onSubmit={(e) => {
form.handleSubmit(onSubmit)(e);
}}
className={cn("space-y-5", className)}
>
<AutoFormObject
schema={objectFormSchema}
form={form}
dependencies={dependencies}
fieldConfig={fieldConfig}
/>
{renderChildren}
</form>
</Form>
</div>
);
}
export default AutoForm;

View File

@@ -0,0 +1,74 @@
import { ControllerRenderProps, FieldValues } from "react-hook-form";
import * as z from "zod";
import { INPUT_COMPONENTS } from "./config";
export type FieldConfigItem = {
description?: React.ReactNode;
inputProps?: React.InputHTMLAttributes<HTMLInputElement> &
React.TextareaHTMLAttributes<HTMLTextAreaElement> & {
showLabel?: boolean;
};
label?: string;
fieldType?:
| keyof typeof INPUT_COMPONENTS
| React.FC<AutoFormInputComponentProps>;
renderParent?: (props: {
children: React.ReactNode;
}) => React.ReactElement | null;
order?: number;
};
export type FieldConfig<SchemaType extends z.infer<z.ZodObject<any, any>>> = {
[Key in keyof SchemaType]?: SchemaType[Key] extends object
? FieldConfig<z.infer<SchemaType[Key]>>
: FieldConfigItem;
};
export enum DependencyType {
DISABLES,
REQUIRES,
HIDES,
SETS_OPTIONS,
}
type BaseDependency<SchemaType extends z.infer<z.ZodObject<any, any>>> = {
sourceField: keyof SchemaType;
type: DependencyType;
targetField: keyof SchemaType;
when: (sourceFieldValue: any, targetFieldValue: any) => boolean;
};
export type ValueDependency<SchemaType extends z.infer<z.ZodObject<any, any>>> =
BaseDependency<SchemaType> & {
type:
| DependencyType.DISABLES
| DependencyType.REQUIRES
| DependencyType.HIDES;
};
export type EnumValues = readonly [string, ...string[]];
export type OptionsDependency<
SchemaType extends z.infer<z.ZodObject<any, any>>
> = BaseDependency<SchemaType> & {
type: DependencyType.SETS_OPTIONS;
options: EnumValues;
};
export type Dependency<SchemaType extends z.infer<z.ZodObject<any, any>>> =
| ValueDependency<SchemaType>
| OptionsDependency<SchemaType>;
export type AutoFormInputComponentProps = {
zodInputProps: React.InputHTMLAttributes<HTMLInputElement>;
field: ControllerRenderProps<FieldValues, any>;
fieldConfigItem: FieldConfigItem;
label: string;
isRequired: boolean;
fieldProps: any;
zodItem: z.ZodAny;
className?: string;
};

View File

@@ -0,0 +1,169 @@
import React from "react";
import { DefaultValues } from "react-hook-form";
import { z } from "zod";
import { FieldConfig } from "./types";
export type ZodObjectOrWrapped =
| z.ZodObject<any, any>
| z.ZodEffects<z.ZodObject<any, any>>;
export function beautifyObjectName(string: string) {
let output = string.replace(/([A-Z])/g, " $1");
output = output.charAt(0).toUpperCase() + output.slice(1);
return output;
}
export function getBaseSchema<
ChildType extends z.ZodAny | z.AnyZodObject = z.ZodAny
>(schema: ChildType | z.ZodEffects<ChildType>): ChildType | null {
if (!schema) return null;
if ("innerType" in schema._def) {
return getBaseSchema(schema._def.innerType as ChildType);
}
if ("schema" in schema._def) {
return getBaseSchema(schema._def.schema as ChildType);
}
return schema as ChildType;
}
export function getBaseType(schema: z.ZodAny): string {
const baseSchema = getBaseSchema(schema);
return baseSchema ? baseSchema._def.typeName : "";
}
export function getDefaultValueInZodStack(schema: z.ZodAny): any {
const typedSchema = schema as unknown as z.ZodDefault<
z.ZodNumber | z.ZodString
>;
if (typedSchema._def.typeName === "ZodDefault") {
return typedSchema._def.defaultValue();
}
if ("innerType" in typedSchema._def) {
return getDefaultValueInZodStack(
typedSchema._def.innerType as unknown as z.ZodAny
);
}
if ("schema" in typedSchema._def) {
return getDefaultValueInZodStack(
(typedSchema._def as any).schema as z.ZodAny
);
}
return undefined;
}
export function getDefaultValues<Schema extends z.ZodObject<any, any>>(
schema: Schema,
fieldConfig?: FieldConfig<z.infer<Schema>>
) {
if (!schema) return null;
const { shape } = schema;
type DefaultValuesType = DefaultValues<Partial<z.infer<Schema>>>;
const defaultValues = {} as DefaultValuesType;
if (!shape) return defaultValues;
for (const key of Object.keys(shape)) {
const item = shape[key] as z.ZodAny;
if (getBaseType(item) === "ZodObject") {
const defaultItems = getDefaultValues(
getBaseSchema(item) as unknown as z.ZodObject<any, any>,
fieldConfig?.[key] as FieldConfig<z.infer<Schema>>
);
if (defaultItems !== null) {
for (const defaultItemKey of Object.keys(defaultItems)) {
const pathKey = `${key}.${defaultItemKey}` as keyof DefaultValuesType;
defaultValues[pathKey] = defaultItems[defaultItemKey];
}
}
} else {
let defaultValue = getDefaultValueInZodStack(item);
if (
(defaultValue === null || defaultValue === "") &&
fieldConfig?.[key]?.inputProps
) {
defaultValue = (fieldConfig?.[key]?.inputProps as unknown as any)
.defaultValue;
}
if (defaultValue !== undefined) {
defaultValues[key as keyof DefaultValuesType] = defaultValue;
}
}
}
return defaultValues;
}
export function getObjectFormSchema(
schema: ZodObjectOrWrapped
): z.ZodObject<any, any> {
if (schema?._def.typeName === "ZodEffects") {
const typedSchema = schema as z.ZodEffects<z.ZodObject<any, any>>;
return getObjectFormSchema(typedSchema._def.schema);
}
return schema as z.ZodObject<any, any>;
}
export function zodToHtmlInputProps(
schema:
| z.ZodNumber
| z.ZodString
| z.ZodOptional<z.ZodNumber | z.ZodString>
| any
): React.InputHTMLAttributes<HTMLInputElement> {
if (["ZodOptional", "ZodNullable"].includes(schema._def.typeName)) {
const typedSchema = schema as z.ZodOptional<z.ZodNumber | z.ZodString>;
return {
...zodToHtmlInputProps(typedSchema._def.innerType),
required: false,
};
}
const typedSchema = schema as z.ZodNumber | z.ZodString;
if (!("checks" in typedSchema._def))
return {
required: true,
};
const { checks } = typedSchema._def;
const inputProps: React.InputHTMLAttributes<HTMLInputElement> = {
required: true,
};
const type = getBaseType(schema);
for (const check of checks) {
if (check.kind === "min") {
if (type === "ZodString") {
inputProps.minLength = check.value;
} else {
inputProps.min = check.value;
}
}
if (check.kind === "max") {
if (type === "ZodString") {
inputProps.maxLength = check.value;
} else {
inputProps.max = check.value;
}
}
}
return inputProps;
}
export function sortFieldsByOrder<SchemaType extends z.ZodObject<any, any>>(
fieldConfig: FieldConfig<z.infer<SchemaType>> | undefined,
keys: string[]
) {
const sortedFields = keys.sort((a, b) => {
const fieldA: number = (fieldConfig?.[a]?.order as number) ?? 0;
const fieldB = (fieldConfig?.[b]?.order as number) ?? 0;
return fieldA - fieldB;
});
return sortedFields;
}

View File

@@ -0,0 +1,41 @@
import type * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@anujs.dev/inventory-types-utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
success:
"border-transparent bg-emerald-100 text-emerald-800 hover:bg-emerald-200/80",
warning:
"border-transparent bg-amber-100 text-amber-800 hover:bg-amber-200/80",
info: "border-transparent bg-blue-100 text-blue-800 hover:bg-blue-200/80",
},
},
defaultVariants: {
variant: "default",
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,57 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@anujs.dev/inventory-types-utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@@ -0,0 +1,76 @@
"use client";
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@anujs.dev/inventory-types-utils";
import { buttonVariants } from "@/components/ui/button";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell:
"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: cn(
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md",
props.mode === "range"
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
: "[&:has([aria-selected])]:rounded-md"
),
day: cn(
buttonVariants({ variant: "ghost" }),
"h-8 w-8 p-0 font-normal aria-selected:opacity-100"
),
day_range_start: "day-range-start",
day_range_end: "day-range-end",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ className, ...props }) => (
<ChevronLeft className={cn("h-4 w-4", className)} {...props} />
),
IconRight: ({ className, ...props }) => (
<ChevronRight className={cn("h-4 w-4", className)} {...props} />
),
}}
{...props}
/>
);
}
Calendar.displayName = "Calendar";
export { Calendar };

View File

@@ -0,0 +1,83 @@
import * as React from "react";
import { cn } from "@anujs.dev/inventory-types-utils";
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
));
CardFooter.displayName = "CardFooter";
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};

View File

@@ -0,0 +1,30 @@
"use client";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@anujs.dev/inventory-types-utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };

View File

@@ -0,0 +1,154 @@
// @ts-nocheck
"use client";
import * as React from "react";
import { type DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "@anujs.dev/inventory-types-utils";
import { Dialog, DialogContent } from "@/components/ui/dialog";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
const CommandDialog = ({ children, ...props }: DialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
);
};
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 h-px bg-border", className)}
{...props}
/>
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
className
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className
)}
{...props}
/>
);
};
CommandShortcut.displayName = "CommandShortcut";
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};

View File

@@ -0,0 +1,51 @@
"use client";
import { format } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";
import { cn } from "@anujs.dev/inventory-types-utils";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { forwardRef } from "react";
export const DatePicker = forwardRef<
HTMLDivElement,
{
date?: Date;
setDate: (date?: Date) => void;
fromDate?: Date;
}
>(function DatePickerCmp({ date, setDate, fromDate }, ref) {
return (
<Popover>
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"w-full justify-start text-left font-normal",
!date && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{date ? format(date, "PPP") : <span>Pick a date</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0 pointer-events-auto" ref={ref}>
{fromDate ? (
<Calendar
mode="single"
selected={date}
onSelect={setDate}
fromDate={fromDate}
/>
) : (
<Calendar mode="single" selected={date} onSelect={setDate} />
)}
</PopoverContent>
</Popover>
);
});

View File

@@ -0,0 +1,122 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@anujs.dev/inventory-types-utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

179
src/components/ui/form.tsx Normal file
View File

@@ -0,0 +1,179 @@
"use client";
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form";
import { cn } from "@anujs.dev/inventory-types-utils";
import { Label } from "@/components/ui/label";
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
);
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
);
});
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
);
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
});
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-[0.8rem] text-muted-foreground", className)}
{...props}
/>
);
});
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
if (!body) {
return null;
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-[0.8rem] font-medium text-destructive", className)}
{...props}
>
{body}
</p>
);
});
FormMessage.displayName = "FormMessage";
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
};

View File

@@ -0,0 +1,22 @@
import * as React from "react";
import { cn } from "@anujs.dev/inventory-types-utils";
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = "Input";
export { Input };

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