Vendor Dashboard updated

This commit is contained in:
2026-04-09 14:14:57 +05:30
commit dd3e811cdf
113 changed files with 16725 additions and 0 deletions

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

73
frontend/README.md Normal file
View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
frontend/eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3973
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

43
frontend/package.json Normal file
View File

@@ -0,0 +1,43 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@types/date-fns": "^2.5.3",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"framer-motion": "^12.38.0",
"lucide-react": "^1.7.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-router-dom": "^7.14.0",
"recharts": "^3.8.1",
"tailwind-merge": "^3.5.0"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@tailwindcss/postcss": "^4.2.2",
"@tailwindcss/vite": "^4.2.2",
"@types/node": "^24.12.2",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"autoprefixer": "^10.4.27",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"postcss": "^8.5.8",
"tailwindcss": "^4.2.2",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.0",
"vite": "^8.0.4"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

24
frontend/public/icons.svg Normal file
View File

@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

184
frontend/src/App.css Normal file
View File

@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}

97
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,97 @@
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Layout from './components/Layout.tsx';
import Dashboard from './pages/Dashboard.tsx';
import StoreDashboard from './pages/StoreDashboard.tsx';
import BaseMenu from './pages/BaseMenu.tsx';
import Products from './pages/Products.tsx';
import Orders from './pages/Orders.tsx';
import ArchivedOrders from './pages/ArchivedOrders.tsx';
import Customers from './pages/Customers.tsx';
import Login from './pages/Login.tsx';
import Managers from './pages/Managers.tsx';
import Stalls from './pages/Stalls.tsx';
import Staff from './pages/Staff.tsx';
import Terminals from './pages/Terminals.tsx';
import Vendors from './pages/Vendors.tsx';
import Purchases from './pages/Purchases.tsx';
import VendorDashboard from './pages/VendorDashboard.tsx';
import PurchaseAnalytics from './pages/PurchaseAnalytics.tsx';
import Bills from './pages/Bills.tsx';
import PurchaseSummary from './pages/PurchaseSummary.tsx';
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
const isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true';
return isLoggedIn ? <>{children}</> : <Navigate to="/login" replace />;
};
const PlaceholderPage = ({ title }: { title: string }) => (
<div className="p-8">
<h1 className="text-2xl font-bold text-[#1e293b]">{title}</h1>
<div className="mt-8 p-12 border-2 border-dashed border-[#e2e8f0] rounded-xl flex flex-col items-center justify-center text-[#64748b]">
<p className="text-lg font-medium">This page is under development</p>
<p className="text-sm">We're working hard to bring you the best experience for {title}.</p>
</div>
</div>
);
function App() {
return (
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={
<ProtectedRoute>
<Layout />
</ProtectedRoute>
}>
<Route index element={<Navigate to="/dashboard" replace />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="store-dashboard" element={<StoreDashboard />} />
{/* Sale */}
<Route path="sale/orders" element={<Orders />} />
<Route path="sale/archived-bills" element={<ArchivedOrders />} />
{/* Customers */}
<Route path="customers/orders" element={<Customers />} />
{/* Purchases */}
<Route path="purchases/dashboard" element={<VendorDashboard />} />
<Route path="purchases/orders" element={<Purchases />} />
<Route path="purchases/summary" element={<PurchaseSummary />} />
<Route path="purchases/bills" element={<Bills />} />
<Route path="purchases/vendor" element={<Vendors />} />
<Route path="purchases/analytics" element={<PurchaseAnalytics />} />
{/* Inventory */}
<Route path="inventory/base" element={<BaseMenu />} />
<Route path="inventory/products" element={<Products />} />
<Route path="inventory/online" element={<Navigate to="/inventory/products" replace />} />
{/* Expense */}
<Route path="expense/overview" element={<PlaceholderPage title="Expense Overview" />} />
<Route path="expense/category" element={<PlaceholderPage title="Expense Category" />} />
{/* Others */}
<Route path="reports" element={<PlaceholderPage title="Reports" />} />
<Route path="table" element={<PlaceholderPage title="Table Management" />} />
<Route path="wallet" element={<PlaceholderPage title="Wallet" />} />
<Route path="feedback" element={<PlaceholderPage title="Feedback" />} />
{/* Stores */}
<Route path="stores/terminals" element={<Terminals />} />
<Route path="stores/managers" element={<Managers />} />
<Route path="stores/staffs" element={<Staff />} />
<Route path="stores/stalls" element={<Stalls />} />
{/* Promotions */}
<Route path="promotions/discounts" element={<PlaceholderPage title="Discounts" />} />
<Route path="promotions/coupon" element={<PlaceholderPage title="Coupons" />} />
<Route path="promotions/coupon-template" element={<PlaceholderPage title="Coupon Templates" />} />
</Route>
</Routes>
</Router>
);
}
export default App;

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@@ -0,0 +1,149 @@
import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Monitor, MapPin, Lock } from 'lucide-react';
import Numpad from './Numpad.tsx';
interface AddTerminalModalProps {
isOpen: boolean;
onClose: () => void;
onSuccess: () => void;
}
const AddTerminalModal: React.FC<AddTerminalModalProps> = ({ isOpen, onClose, onSuccess }) => {
const [name, setName] = useState('');
const [location, setLocation] = useState('');
const [pin, setPin] = useState('');
const [step, setStep] = useState(1); // 1: Details, 2: PIN
const [loading, setLoading] = useState(false);
const handleSubmit = async () => {
setLoading(true);
try {
const response = await fetch('/api/terminals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, location, pin }),
});
if (response.ok) {
onSuccess();
reset();
onClose();
}
} catch (error) {
console.error('Failed to create terminal:', error);
} finally {
setLoading(false);
}
};
const reset = () => {
setName('');
setLocation('');
setPin('');
setStep(1);
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
<motion.div
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 20 }}
className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden relative"
>
<div className="p-6 border-b border-gray-100 flex items-center justify-between">
<h3 className="text-xl font-bold text-[#231651]">Register New Terminal</h3>
<button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
<X size={20} className="text-gray-400" />
</button>
</div>
<div className="p-8">
<AnimatePresence mode="wait">
{step === 1 ? (
<motion.div
key="step1"
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
className="space-y-6"
>
<div className="space-y-2">
<label className="text-sm font-semibold text-gray-700 flex items-center gap-2">
<Monitor size={16} className="text-[#231651]" /> Terminal Name
</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Counter 1"
className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#231651]/20 focus:border-[#231651] outline-none transition-all"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-gray-700 flex items-center gap-2">
<MapPin size={16} className="text-[#231651]" /> Location
</label>
<input
type="text"
value={location}
onChange={(e) => setLocation(e.target.value)}
placeholder="e.g. Main Entrance"
className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#231651]/20 focus:border-[#231651] outline-none transition-all"
/>
</div>
<button
disabled={!name || !location}
onClick={() => setStep(2)}
className="w-full h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all disabled:opacity-50 disabled:scale-100"
>
Set Security PIN
</button>
</motion.div>
) : (
<motion.div
key="step2"
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
className="space-y-6"
>
<div className="text-center mb-4">
<div className="inline-flex p-3 bg-purple-50 text-[#231651] rounded-2xl mb-3">
<Lock size={24} />
</div>
<h4 className="text-lg font-bold text-gray-900">Create Security PIN</h4>
<p className="text-sm text-gray-500">This PIN is required to access the API Key</p>
</div>
<Numpad value={pin} onChange={setPin} maxLength={4} />
<div className="flex gap-3 pt-4">
<button
onClick={() => setStep(1)}
className="flex-1 h-14 bg-gray-100 text-gray-600 rounded-2xl font-bold hover:bg-gray-200 transition-all"
>
Back
</button>
<button
disabled={pin.length < 4 || loading}
onClick={handleSubmit}
className="flex-[2] h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all disabled:opacity-50 disabled:scale-100"
>
{loading ? 'Registering...' : 'Register Terminal'}
</button>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</motion.div>
</div>
);
};
export default AddTerminalModal;

View File

@@ -0,0 +1,49 @@
import { Bell, Search, Settings, HelpCircle, Calendar } from 'lucide-react';
const Header = () => {
const currentDate = new Date().toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
});
return (
<header className="h-16 bg-white/80 backdrop-blur-md border-b border-[#e2e8f0] px-8 flex items-center justify-between sticky top-0 z-40">
<div className="flex items-center gap-4 flex-1">
<div className="relative group w-full max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#64748b] group-focus-within:text-[#231651] transition-colors" size={18} />
<input
type="text"
placeholder="Search dashboard..."
className="w-full bg-gray-50 border border-transparent rounded-lg py-2 pl-10 pr-4 text-sm focus:outline-none focus:bg-white focus:border-[#231651]/30 transition-all shadow-sm"
/>
</div>
</div>
<div className="flex items-center gap-6">
<div className="hidden lg:flex items-center gap-2 text-[#64748b] text-sm">
<Calendar size={16} />
<span>{currentDate}</span>
</div>
<div className="flex items-center gap-4 border-l border-[#e2e8f0] pl-6">
<button className="relative p-2 text-[#64748b] hover:text-[#1e293b] hover:bg-gray-100 rounded-lg transition-all group">
<Bell size={20} />
<span className="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full border-2 border-white"></span>
</button>
<button className="p-2 text-[#64748b] hover:text-[#1e293b] hover:bg-gray-100 rounded-lg transition-all">
<Settings size={20} />
</button>
<button className="p-2 text-[#64748b] hover:text-[#1e293b] hover:bg-gray-100 rounded-lg transition-all">
<HelpCircle size={20} />
</button>
</div>
</div>
</header>
);
};
export default Header;

View File

@@ -0,0 +1,21 @@
import { Outlet } from 'react-router-dom';
import Sidebar from './Sidebar.tsx';
import Header from './Header.tsx';
const Layout = () => {
return (
<div className="flex min-h-screen bg-[#f8fafc]">
<Sidebar />
<main className="flex-1 ml-64 flex flex-col min-w-0">
<Header />
<div className="flex-1 overflow-x-hidden overflow-y-auto">
<div className="container mx-auto">
<Outlet />
</div>
</div>
</main>
</div>
);
};
export default Layout;

View File

@@ -0,0 +1,81 @@
import { motion } from 'framer-motion';
import { Delete } from 'lucide-react';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
interface NumpadProps {
value: string;
onChange: (value: string) => void;
maxLength?: number;
}
const Numpad: React.FC<NumpadProps> = ({ value, onChange, maxLength = 4 }) => {
const handleNumberClick = (num: string) => {
if (value.length < maxLength) {
onChange(value + num);
}
};
const handleDelete = () => {
onChange(value.slice(0, -1));
};
const handleClear = () => {
onChange('');
};
const buttons = [
'1', '2', '3',
'4', '5', '6',
'7', '8', '9',
'C', '0', 'DEL'
];
return (
<div className="w-full max-w-[280px] mx-auto p-4 bg-gray-50/50 rounded-2xl border border-gray-100">
{/* PIN Display Dots */}
<div className="flex justify-center gap-3 mb-8">
{[...Array(maxLength)].map((_, i) => (
<motion.div
key={i}
initial={false}
animate={{
scale: i < value.length ? 1.2 : 1,
backgroundColor: i < value.length ? '#231651' : '#e2e8f0'
}}
className="w-3 h-3 rounded-full"
/>
))}
</div>
{/* Grid */}
<div className="grid grid-cols-3 gap-3">
{buttons.map((btn) => (
<motion.button
key={btn}
whileHover={{ scale: 1.05, backgroundColor: '#f8fafc' }}
whileTap={{ scale: 0.95 }}
onClick={() => {
if (btn === 'C') handleClear();
else if (btn === 'DEL') handleDelete();
else handleNumberClick(btn);
}}
className={cn(
"h-14 flex items-center justify-center rounded-xl text-lg font-bold transition-all",
btn === 'C' ? "text-red-500 hover:text-red-600" :
btn === 'DEL' ? "text-gray-500" : "text-[#231651]"
)}
>
{btn === 'DEL' ? <Delete size={20} /> : btn}
</motion.button>
))}
</div>
</div>
);
};
export default Numpad;

View File

@@ -0,0 +1,85 @@
import React from 'react';
import {
ChevronLeft,
ChevronRight,
ChevronDown
} from 'lucide-react';
interface PaginationProps {
currentPage: number; // 0-indexed
pageSize: number;
totalElements: number;
onPageChange: (page: number) => void;
onPageSizeChange: (size: number) => void;
}
const Pagination: React.FC<PaginationProps> = ({
currentPage,
pageSize,
totalElements,
onPageChange,
onPageSizeChange
}) => {
const totalPages = Math.ceil(totalElements / pageSize);
const startRange = totalElements === 0 ? 0 : currentPage * pageSize + 1;
const endRange = Math.min((currentPage + 1) * pageSize, totalElements);
return (
<div className="flex items-center justify-end px-4 py-3 bg-white border-t border-slate-100 gap-8">
{/* Rows per page */}
<div className="flex items-center gap-3">
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Rows per page</span>
<div className="relative group">
<select
value={pageSize}
onChange={(e) => onPageSizeChange(Number(e.target.value))}
className="appearance-none bg-slate-50 border border-slate-200 rounded-lg pl-3 pr-8 py-1.5 text-xs font-bold text-slate-700 outline-none cursor-pointer hover:border-slate-300 transition-all"
>
<option value={10}>10</option>
<option value={20}>20</option>
<option value={30}>30</option>
<option value={50}>50</option>
</select>
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400 group-hover:text-slate-600 transition-colors">
<ChevronDown size={14} />
</div>
</div>
</div>
{/* Range display */}
<div className="text-xs font-bold text-slate-600 tracking-tight">
{startRange}{endRange} of <span className="font-black text-slate-900">{totalElements}</span>
</div>
{/* Navigation buttons */}
<div className="flex items-center gap-1">
<button
onClick={() => onPageChange(currentPage - 1)}
disabled={currentPage === 0}
className={`p-1.5 rounded-lg transition-all ${
currentPage === 0
? 'text-slate-200 cursor-not-allowed'
: 'text-slate-500 hover:bg-slate-50 hover:text-slate-900 active:scale-90'
}`}
title="Previous Page"
>
<ChevronLeft size={20} />
</button>
<button
onClick={() => onPageChange(currentPage + 1)}
disabled={currentPage >= totalPages - 1}
className={`p-1.5 rounded-lg transition-all ${
currentPage >= totalPages - 1
? 'text-slate-200 cursor-not-allowed'
: 'text-slate-500 hover:bg-slate-50 hover:text-slate-900 active:scale-90'
}`}
title="Next Page"
>
<ChevronRight size={20} />
</button>
</div>
</div>
);
};
export default Pagination;

View File

@@ -0,0 +1,182 @@
import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Lock, Copy, CheckCircle2, AlertCircle } from 'lucide-react';
import Numpad from './Numpad.tsx';
interface PinVerificationModalProps {
isOpen: boolean;
onClose: () => void;
terminalId: number | null;
terminalName: string;
}
const PinVerificationModal: React.FC<PinVerificationModalProps> = ({
isOpen,
onClose,
terminalId,
terminalName
}) => {
const [pin, setPin] = useState('');
const [apiKey, setApiKey] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
const handleVerify = async (freshPin?: string) => {
if (!terminalId) return;
const pinToVerify = freshPin || pin;
if (!pinToVerify || pinToVerify.length < 4) return;
setLoading(true);
setError(null);
try {
const response = await fetch(`/api/terminals/${terminalId}/verify-pin`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pin: pinToVerify }),
});
const data = await response.json();
if (response.ok) {
setApiKey(data.apiKey);
} else {
setError(data.message || 'Verification failed');
setPin('');
}
} catch (err) {
setError('Connection error');
} finally {
setLoading(false);
}
};
const copyToClipboard = () => {
if (apiKey) {
navigator.clipboard.writeText(apiKey);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
};
const handleClose = () => {
setPin('');
setApiKey(null);
setError(null);
onClose();
};
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
<motion.div
initial={{ opacity: 0, scale: 0.95, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 20 }}
className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden relative"
>
<div className="p-6 border-b border-gray-100 flex items-center justify-between">
<h3 className="text-xl font-bold text-[#231651]">Security Authentication</h3>
<button onClick={handleClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
<X size={20} className="text-gray-400" />
</button>
</div>
<div className="p-8">
<AnimatePresence mode="wait">
{!apiKey ? (
<motion.div
key="verification"
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 1.05 }}
className="space-y-6 text-center"
>
<div className="inline-flex p-4 bg-orange-50 text-orange-600 rounded-2xl mb-2">
<Lock size={32} />
</div>
<div>
<h4 className="text-lg font-bold text-gray-900">{terminalName}</h4>
<p className="text-sm text-gray-500 mt-1">Enter your 4-digit security PIN to view the API Key</p>
</div>
{error && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="p-3 bg-red-50 text-red-600 rounded-xl text-sm font-medium flex items-center justify-center gap-2"
>
<AlertCircle size={16} />
{error}
</motion.div>
)}
<Numpad value={pin} onChange={(v) => {
setPin(v);
if (v.length === 4) {
// Slight delay for visual feedback of the last dot
setTimeout(() => handleVerify(v), 100);
}
}} maxLength={4} />
<button
disabled={pin.length < 4 || loading}
onClick={() => handleVerify()}
className="w-full h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all disabled:opacity-50 disabled:scale-100"
>
{loading ? 'Verifying...' : 'Verify PIN'}
</button>
</motion.div>
) : (
<motion.div
key="result"
initial={{ opacity: 0, scale: 1.1 }}
animate={{ opacity: 1, scale: 1 }}
className="space-y-8 text-center"
>
<div className="inline-flex p-4 bg-green-50 text-green-600 rounded-full mb-2">
<CheckCircle2 size={40} />
</div>
<div>
<h4 className="text-xl font-bold text-gray-900">Authentication Successful</h4>
<p className="text-sm text-gray-500 mt-1">Below is the API key for physical device integration</p>
</div>
<div className="relative group">
<div className="absolute -inset-1 bg-gradient-to-r from-purple-600 to-[#231651] rounded-2xl blur opacity-20 group-hover:opacity-40 transition duration-1000"></div>
<div className="relative p-5 bg-gray-50 border border-gray-200 rounded-2xl break-all font-mono text-sm text-[#231651] flex items-center justify-between gap-4">
<span className="text-left">{apiKey}</span>
<button
onClick={copyToClipboard}
className="p-2 hover:bg-white rounded-lg transition-colors shadow-sm shrink-0"
>
{copied ? <CheckCircle2 size={18} className="text-green-600" /> : <Copy size={18} className="text-[#231651]" />}
</button>
</div>
</div>
<div className="p-4 bg-blue-50/50 rounded-2xl flex gap-3 text-left">
<AlertCircle size={20} className="text-blue-600 shrink-0 mt-0.5" />
<p className="text-[12px] text-blue-700 leading-relaxed font-medium">
This API key allows the terminal to communicate with the central server. Keep it secure and never share it publicly.
</p>
</div>
<button
onClick={handleClose}
className="w-full h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all"
>
Close Session
</button>
</motion.div>
)}
</AnimatePresence>
</div>
</motion.div>
</div>
);
};
export default PinVerificationModal;

View File

@@ -0,0 +1,312 @@
import React, { useState } from 'react';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
import {
BarChart3,
ChevronRight,
CreditCard,
Gauge,
LayoutGrid,
Megaphone,
MessageSquare,
ShoppingCart,
Store,
Table2,
Users,
Wallet,
ShoppingBag,
Receipt,
Search,
LogOut
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import collegeLogo from '../assets/college-logo.png';
function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
interface MenuItem {
title: string;
icon: React.ElementType;
path?: string;
subMenu?: { title: string; path: string }[];
}
const menuItems: MenuItem[] = [
{ title: 'Dashboard', icon: Gauge, path: '/dashboard' },
{ title: 'Store Dashboard', icon: LayoutGrid, path: '/store-dashboard' },
{
title: 'Sale',
icon: Receipt,
subMenu: [
{ title: 'Orders', path: '/sale/orders' },
{ title: 'Archived Bills', path: '/sale/archived-bills' }
]
},
{
title: 'Customers',
icon: Users,
subMenu: [
{ title: 'Orders', path: '/customers/orders' }
]
},
{
title: 'Vendors',
icon: ShoppingBag,
subMenu: [
{ title: 'Dashboard', path: '/purchases/dashboard' },
{ title: 'Orders', path: '/purchases/orders' },
{ title: 'Summary', path: '/purchases/summary' },
{ title: 'Bills', path: '/purchases/bills' },
{ title: 'Vendors', path: '/purchases/vendor' },
{ title: 'Purchase Analytics', path: '/purchases/analytics' }
]
},
{
title: 'Inventory',
icon: ShoppingCart,
subMenu: [
{ title: 'Base Items', path: '/inventory/base' },
{ title: 'Products', path: '/inventory/products' }
]
},
{
title: 'Expense',
icon: Wallet,
subMenu: [
{ title: 'Overview', path: '/expense/overview' },
{ title: 'Category', path: '/expense/category' }
]
},
{ title: 'Reports', icon: BarChart3, path: '/reports' },
{
title: 'Stores',
icon: Store,
subMenu: [
{ title: 'Terminals', path: '/stores/terminals' },
{ title: 'Managers', path: '/stores/managers' },
{ title: 'Staffs', path: '/stores/staffs' },
{ title: 'Stalls', path: '/stores/stalls' }
]
},
{ title: 'Table', icon: Table2, path: '/table' },
{ title: 'Wallet', icon: CreditCard, path: '/wallet' },
{
title: 'Promotions',
icon: Megaphone,
subMenu: [
{ title: 'Discounts', path: '/promotions/discounts' },
{ title: 'Coupon', path: '/promotions/coupon' },
{ title: 'CouponTemplate', path: '/promotions/coupon-template' }
]
},
{ title: 'Feedback', icon: MessageSquare, path: '/feedback' },
];
const Sidebar = () => {
const [openMenus, setOpenMenus] = useState<string[]>([]);
const location = useLocation();
const navigate = useNavigate();
// Permission Logic
const userRole = sessionStorage.getItem('userRole') || 'master';
const userPermissions = JSON.parse(sessionStorage.getItem('userPermissions') || '[]');
const filteredMenuItems = menuItems.filter(item => {
if (userRole === 'master') return true;
// Map title to permission ID
const permissionMap: Record<string, string> = {
'Dashboard': 'dashboard',
'Store Dashboard': 'dashboard',
'Sale': 'sale',
'Customers': 'customers',
'Vendors': 'purchases',
'Inventory': 'inventory',
'Expense': 'expense',
'Reports': 'reports',
'Stores': 'stores',
'Table': 'table',
'Wallet': 'wallet',
'Promotions': 'promotions',
'Feedback': 'feedback'
};
return userPermissions.includes(permissionMap[item.title]);
});
const handleLogout = () => {
sessionStorage.removeItem('isLoggedIn');
sessionStorage.removeItem('userRole');
sessionStorage.removeItem('userPermissions');
navigate('/login');
};
const toggleMenu = (title: string) => {
setOpenMenus((prev) =>
prev.includes(title)
? prev.filter((item) => item !== title)
: [...prev, title]
);
};
// Check if a sub-menu should be open based on the current location
React.useEffect(() => {
const currentMenu = menuItems.find(item =>
item.subMenu?.some(sub => location.pathname.startsWith(sub.path))
);
if (currentMenu && !openMenus.includes(currentMenu.title)) {
setOpenMenus(prev => [...prev, currentMenu.title]);
}
}, [location.pathname]);
return (
<div className="w-64 bg-white h-screen border-r border-[#e2e8f0] flex flex-col fixed left-0 top-0 z-50 shadow-sm overflow-hidden font-inter">
{/* Branding Section */}
<div className="px-5 pt-8 pb-4 flex items-center">
<img src={collegeLogo} alt="Branding" className="h-14 w-auto object-contain brightness-[1.05]" />
</div>
{/* Premium Search Integration (Modern Dashboards usually have this) */}
<div className="px-3 mb-4">
<div className="relative flex items-center group">
<div className="absolute left-3 flex items-center justify-center pointer-events-none">
<Search size={16} className="text-[#64748b] group-focus-within:text-[#231651] transition-colors" />
</div>
<input
type="text"
placeholder="Search Menu..."
title="Search for a specific module or page"
className="w-full h-10 bg-gray-50 border border-[#e2e8f0] rounded-xl pl-10 pr-4 text-[13px] font-medium outline-none transition-all focus:bg-white focus:border-[#231651]/30 focus:shadow-sm placeholder:text-[#94a3b8] text-[#1e293b]"
/>
</div>
</div>
{/* The main dashboard list starts here */}
<div className="flex-1 overflow-y-auto px-3 custom-scrollbar">
<ul className="space-y-1">
{filteredMenuItems.map((item) => (
<li key={item.title}>
{item.subMenu ? (
<div>
<button
onClick={() => toggleMenu(item.title)}
title={`Expand/Collapse ${item.title}`}
className={cn(
"w-full flex items-center justify-between p-2.5 rounded-xl text-sm font-semibold transition-all duration-200 group",
openMenus.includes(item.title)
? "text-[#521c4b] bg-[#521c4b]/5"
: "text-[#475569] hover:bg-gray-50 hover:text-[#1e293b]"
)}
>
<div className="flex items-center gap-3">
<item.icon size={18} strokeWidth={2} className={cn(
"transition-colors",
openMenus.includes(item.title) ? "text-[#231651]" : "text-[#64748b] group-hover:text-[#475569]"
)} />
<span className="tracking-tight">{item.title}</span>
</div>
<div className={cn(
"transition-transform duration-300",
openMenus.includes(item.title) ? "rotate-90" : ""
)}>
<ChevronRight size={14} className="opacity-60" />
</div>
</button>
<AnimatePresence initial={false}>
{openMenus.includes(item.title) && (
<motion.ul
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={{ duration: 0.3, ease: "easeInOut" }}
className="ml-6 mt-1 mb-2 space-y-0.5 border-l border-[#e2e8f0]/60 overflow-hidden"
>
{item.subMenu.map((sub) => (
<li key={sub.title}>
<NavLink
to={sub.path}
title={`Go to ${sub.title}`}
className={({ isActive }) => cn(
"flex items-center gap-3 py-2 px-4 rounded-lg text-[13px] font-medium transition-all group relative",
isActive
? "text-white bg-[#521c4b] shadow-md shadow-[#521c4b]/10"
: "text-[#64748b] hover:text-[#1e293b] hover:translate-x-1"
)}
>
{({ isActive }) => (
<>
<div className={cn(
"w-1.5 h-1.5 rounded-full transition-all duration-300",
isActive ? "bg-[#231651] scale-125" : "bg-gray-300 group-hover:bg-gray-400"
)} />
<span>{sub.title}</span>
{isActive && (
<motion.div
layoutId="activeSubMenu"
className="absolute left-[-1.5px] top-1/4 bottom-1/4 w-[3px] bg-[#231651] rounded-full"
/>
)}
</>
)}
</NavLink>
</li>
))}
</motion.ul>
)}
</AnimatePresence>
</div>
) : (
<NavLink
to={item.path!}
title={`Go to ${item.title}`}
className={({ isActive }) => cn(
"flex items-center gap-3 p-2.5 rounded-xl text-sm font-semibold transition-all duration-200 group",
isActive
? "bg-[#521c4b] text-white shadow-lg shadow-[#521c4b]/15"
: "text-[#475569] hover:bg-gray-50 hover:text-[#1e293b]"
)}
>
{({ isActive }) => (
<>
<item.icon size={18} strokeWidth={2} className={cn(
"transition-colors",
isActive ? "text-white" : "text-[#64748b] group-hover:text-[#475569]"
)} />
<span className="tracking-tight">{item.title}</span>
</>
)}
</NavLink>
)}
</li>
))}
</ul>
</div>
<div className="p-4 bg-gray-50/50 border-t border-[#e2e8f0]">
<button
onClick={handleLogout}
title="Sign out of your account"
className="w-full flex items-center gap-3 p-2.5 rounded-xl text-red-600 hover:bg-red-50 transition-all font-semibold text-sm group"
>
<LogOut size={18} className="group-hover:-translate-x-1 transition-transform" />
<span>Logout</span>
</button>
</div>
<style dangerouslySetInnerHTML={{ __html: `
.custom-scrollbar::-webkit-scrollbar { width: 4px; }
.custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
.custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
.font-inter { font-family: 'Inter', sans-serif; }
` }} />
</div>
);
};
export default Sidebar;

113
frontend/src/index.css Normal file
View File

@@ -0,0 +1,113 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
@import "tailwindcss";
@theme {
--font-sans: "Inter", "system-ui", "-apple-system", "sans-serif";
--color-primary: #231651;
--color-primary-light: #35217a;
--color-primary-glow: rgba(35, 22, 81, 0.1);
--color-bg-main: #D6FFF6;
--color-bg-sidebar: #ffffff;
--color-text-dark: #231651;
--color-text-primary: #231651;
--color-text-secondary: #4a3e7a;
--color-text-muted: #7b71af;
--color-border: rgba(35, 22, 81, 0.1);
--color-border-light: rgba(35, 22, 81, 0.05);
}
@layer base {
* {
@apply border-border;
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
@apply bg-bg-main text-text-primary antialiased;
font-family: var(--font-sans);
}
h1, h2, h3, h4, h5, h6 {
@apply font-bold tracking-tight text-text-dark;
}
}
@layer components {
.premium-card {
@apply bg-white rounded-[2rem] border border-border shadow-sm transition-all duration-500 hover:shadow-xl hover:shadow-primary/5 hover:-translate-y-1;
}
.glass-effect {
@apply bg-white/80 backdrop-blur-md border border-white/20;
}
.btn-primary {
@apply bg-primary text-white px-6 py-3 rounded-2xl font-bold transition-all duration-300 hover:bg-[#4a0a38] hover:scale-105 active:scale-95 shadow-lg shadow-primary/20;
}
.btn-secondary {
@apply bg-white text-text-primary px-6 py-3 rounded-2xl font-bold border-2 border-border transition-all duration-300 hover:bg-gray-50 hover:border-primary/20;
}
}
/* Custom Scrollbar Override for v4 */
* {
scrollbar-width: thin;
scrollbar-color: var(--color-border) transparent;
}
::-webkit-scrollbar {
width: 5px;
height: 5px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background-color: var(--color-border);
border-radius: 100px;
}
::-webkit-scrollbar-thumb:hover {
background-color: var(--color-text-muted);
}
/* Animations */
@keyframes slideUp {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-slideUp {
animation: slideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
/* Chart Tooltip Customization (v4 compatibility) */
.recharts-default-tooltip {
background-color: rgba(255, 255, 255, 0.95) !important;
backdrop-filter: blur(8px) !important;
border: 1px solid var(--color-border) !important;
border-radius: 1rem !important;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1) !important;
padding: 1rem !important;
}
.recharts-tooltip-label {
font-size: 0.7rem !important;
font-weight: 900 !important;
color: var(--color-text-muted) !important;
text-transform: uppercase !important;
letter-spacing: 0.1em !important;
margin-bottom: 0.5rem !important;
}
.recharts-tooltip-item {
color: var(--color-primary) !important;
font-weight: 800 !important;
font-size: 0.85rem !important;
}

10
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,432 @@
import React, { useState, useEffect, useMemo } from 'react';
import {
Search,
Calendar,
Filter,
CreditCard,
User,
ShoppingBag,
MoreVertical,
RefreshCw,
Archive,
RotateCcw,
CheckCircle,
Clock,
ArrowLeft
} from 'lucide-react';
import { format, subDays } from 'date-fns';
import Pagination from '../components/Pagination';
interface OrderItem {
id?: number;
productName: string;
quantity: number;
price: number;
productId: number;
}
interface UserData {
name: string;
mobileNumber: string;
}
interface Order {
id: number;
orderNumber: string;
displayOrderId: string;
totalAmount: number;
status: string;
paymentMethod: string;
createdAt: string;
user: UserData;
items: OrderItem[];
}
const ArchivedOrders: React.FC = () => {
const [orders, setOrders] = useState<Order[]>([]);
const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [statusFilter, setStatusFilter] = useState('');
const [paymentFilter, setPaymentFilter] = useState('');
// Default to showing yesterday's orders in the archive view
const [startDate, setStartDate] = useState(format(subDays(new Date(), 30), 'yyyy-MM-dd'));
const [endDate, setEndDate] = useState(format(subDays(new Date(), 1), 'yyyy-MM-dd'));
// Pagination States
const [currentPage, setCurrentPage] = useState(0);
const [pageSize, setPageSize] = useState(10);
const [totalElements, setTotalElements] = useState(0);
useEffect(() => {
fetchArchivedOrders();
}, [startDate, endDate, statusFilter, paymentFilter, currentPage, pageSize]);
const fetchArchivedOrders = async () => {
setLoading(true);
try {
const params = new URLSearchParams();
params.append('archived', 'true'); // Explicitly request archived orders
if (startDate) params.append('startDate', `${startDate}T00:00:00`);
if (endDate) params.append('endDate', `${endDate}T23:59:59`);
if (statusFilter) params.append('status', statusFilter);
if (paymentFilter) params.append('paymentType', paymentFilter);
if (searchQuery) params.append('search', searchQuery);
params.append('page', currentPage.toString());
params.append('size', pageSize.toString());
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/all?${params.toString()}`);
const data = await response.json();
if (data && data.content && Array.isArray(data.content)) {
setOrders(data.content);
setTotalElements(data.totalElements);
if (data.content.length > 0) {
setSelectedOrder(data.content[0]);
} else {
setSelectedOrder(null);
}
} else {
setOrders([]);
setTotalElements(0);
}
} catch (error) {
console.error('Error fetching archived orders:', error);
setOrders([]);
} finally {
setLoading(false);
}
};
const handleSearchSubmit = (e: React.FormEvent) => {
e.preventDefault();
fetchArchivedOrders();
};
const getStatusColor = (status: string) => {
switch (status.toUpperCase()) {
case 'COMPLETED': return 'bg-emerald-50 text-emerald-600 border-emerald-100';
case 'PAID': return 'bg-indigo-50 text-indigo-600 border-indigo-100';
case 'PENDING': return 'bg-amber-50 text-amber-600 border-amber-100';
case 'CANCELLED': return 'bg-rose-50 text-rose-600 border-rose-100';
default: return 'bg-slate-50 text-slate-600 border-slate-100';
}
};
return (
<div className="flex flex-col h-[calc(100vh-64px)] bg-[#f8fafc] animate-in fade-in duration-500">
{/* Top Filter Bar */}
<div className="bg-white border-b border-slate-200 p-4 sticky top-0 z-10 shadow-sm">
<form onSubmit={handleSearchSubmit} className="flex flex-wrap items-center gap-4 max-w-[1600px] mx-auto">
<div className="flex items-center gap-3 mr-4">
<div className="w-10 h-10 bg-slate-900 rounded-xl flex items-center justify-center text-white shadow-lg shadow-slate-200">
<Archive size={20} />
</div>
<div>
<h1 className="text-lg font-black text-slate-900 leading-none">Archived Bills</h1>
<p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest mt-1">Transaction History</p>
</div>
</div>
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 focus-within:border-slate-400 transition-all">
<Calendar size={18} className="text-slate-400" />
<input
type="date"
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
/>
<span className="text-slate-300">to</span>
<input
type="date"
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
/>
</div>
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 min-w-[140px]">
<Filter size={18} className="text-slate-400" />
<select
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none w-full cursor-pointer"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
>
<option value="">All Status</option>
<option value="PAID">Paid</option>
<option value="COMPLETED">Completed</option>
<option value="CANCELLED">Cancelled</option>
</select>
</div>
<div className="flex-1 flex items-center bg-slate-50 border border-slate-200 rounded-lg px-4 py-2 gap-3 focus-within:bg-white focus-within:border-slate-400 transition-all shadow-inner">
<Search size={18} className="text-slate-400" />
<input
type="text"
placeholder="Search history by ID, Name or Mobile..."
className="bg-transparent border-none text-sm w-full outline-none text-slate-700 placeholder:text-slate-400"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<button
type="submit"
className="bg-slate-900 hover:bg-black text-white rounded-lg px-6 py-2 text-sm font-semibold transition-all shadow-md flex items-center gap-2 active:scale-95"
>
Search Archives
</button>
</form>
</div>
{/* Main Content Area */}
<div className="flex-1 overflow-hidden flex max-w-[1800px] mx-auto w-full p-4 gap-4">
{/* Left Column: Archived List */}
<div className="w-[400px] flex flex-col gap-3 overflow-y-auto pr-2 custom-scrollbar pb-4">
{loading ? (
<div className="flex items-center justify-center p-12 text-slate-400 gap-2">
<RefreshCw className="animate-spin" size={20} />
<span>Scanning archives...</span>
</div>
) : orders.length === 0 ? (
<div className="bg-white rounded-xl border border-slate-200 p-12 text-center shadow-sm">
<Archive size={48} className="mx-auto text-slate-100 mb-4" />
<h3 className="text-slate-600 font-semibold mb-1">No archived bills recorded</h3>
<p className="text-slate-400 text-sm">Try expanding the date range</p>
</div>
) : (
orders.map((order) => (
<div
key={order.id}
onClick={() => setSelectedOrder(order)}
className={`group relative bg-white border rounded-xl p-4 cursor-pointer transition-all hover:shadow-lg active:scale-[0.98] ${
selectedOrder?.id === order.id
? 'border-slate-900 ring-1 ring-slate-900 shadow-md'
: 'border-slate-200 hover:border-slate-400'
}`}
>
<div className="flex justify-between items-start mb-3">
<div className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold tracking-wider uppercase border opacity-70 ${getStatusColor(order.status)}`}>
{order.status}
</div>
<div className="text-right">
<div className="text-[10px] text-slate-400 font-medium uppercase mb-0.5">Grand Total</div>
<div className="text-lg font-black text-slate-900 leading-none">{order.totalAmount.toFixed(2)}</div>
</div>
</div>
<div className="flex items-end justify-between">
<div>
<div className="text-xs text-slate-400 font-medium mb-1 tracking-wider uppercase">Order #</div>
<div className="text-2xl font-black text-slate-800 leading-none tracking-tight">#{order.displayOrderId}</div>
</div>
<div className="text-right">
<div className="text-xs font-bold text-slate-700 mb-1">
{order.user?.name || 'Anonymous User'}
</div>
<div className="text-[10px] text-slate-400 font-medium flex items-center justify-end gap-1">
<Clock size={10} />
{format(new Date(order.createdAt), 'dd MMMM yyyy')}
</div>
</div>
</div>
{selectedOrder?.id === order.id && (
<div className="absolute left-0 top-0 bottom-0 w-1 bg-slate-900 rounded-l-xl" />
)}
</div>
))
)}
<Pagination
currentPage={currentPage}
pageSize={pageSize}
totalElements={totalElements}
onPageChange={setCurrentPage}
onPageSizeChange={(newSize) => {
setPageSize(newSize);
setCurrentPage(0);
}}
/>
</div>
{/* Right Column: Order Details */}
<div className="flex-1 bg-white border border-slate-200 rounded-2xl flex flex-col shadow-sm overflow-hidden relative mb-4">
{selectedOrder ? (
<>
{/* Order Detail Header */}
<div className="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50 sticky top-0 z-10">
<div className="flex items-center gap-4">
<div className="bg-slate-900 p-3 rounded-xl text-white shadow-lg shadow-slate-200">
<Archive size={24} />
</div>
<div>
<h2 className="text-2xl font-black text-slate-900 flex items-center gap-2 tracking-tight uppercase">
Archived Receipt #{selectedOrder.displayOrderId}
</h2>
<p className="text-xs text-slate-400 font-black tracking-[0.2em] uppercase">Security ID: {selectedOrder.orderNumber}</p>
</div>
</div>
<div className="flex items-center gap-2">
<div className="text-right mr-3">
<div className="text-[10px] text-slate-400 font-black uppercase tracking-widest leading-none mb-1">Issued Date</div>
<div className="text-xs font-bold text-slate-700">{format(new Date(selectedOrder.createdAt), 'EEEE, MMMM dd yyyy')}</div>
</div>
<div className={`px-4 py-1.5 rounded-lg text-xs font-black uppercase border shadow-sm ${getStatusColor(selectedOrder.status)}`}>
{selectedOrder.status}
</div>
</div>
</div>
{/* Content Scroll Area */}
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
<div className="grid grid-cols-2 gap-8 mb-12">
<div className="p-6 rounded-2xl border border-slate-100 bg-slate-50 flex items-center gap-6">
<div className="w-14 h-14 bg-white rounded-xl shadow-sm flex items-center justify-center text-slate-400">
<User size={28} />
</div>
<div>
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1">Customer Info</div>
<div className="text-lg font-black text-slate-800 leading-none mb-1">{selectedOrder.user?.name || 'Walk-in Customer'}</div>
<div className="text-xs font-bold text-slate-400">{selectedOrder.user?.mobileNumber || 'No Contact Data'}</div>
</div>
</div>
<div className="p-6 rounded-2xl border border-slate-100 bg-slate-50 flex items-center gap-6">
<div className="w-14 h-14 bg-white rounded-xl shadow-sm flex items-center justify-center text-indigo-500">
<CreditCard size={28} />
</div>
<div>
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1">Payment Method</div>
<div className="text-lg font-black text-slate-800 leading-none mb-1">{selectedOrder.paymentMethod.toUpperCase()}</div>
<div className="text-xs font-bold text-emerald-500 flex items-center gap-1"><CheckCircle size={10} /> Verified Record</div>
</div>
</div>
</div>
<div className="space-y-4">
<div className="flex justify-between items-center border-b border-slate-100 pb-3">
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Archived Line Items</h3>
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Value</h3>
</div>
<div className="divide-y divide-slate-50">
{selectedOrder.items.map((item, idx) => (
<div key={idx} className="py-5 flex justify-between items-center group hover:bg-slate-50/50 transition-colors rounded-lg -mx-2 px-2">
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center text-slate-400 font-bold text-xs uppercase group-hover:bg-slate-900 group-hover:text-white transition-colors">
{item.productName.substring(0, 2)}
</div>
<div>
<div className="font-black text-slate-800 text-sm italic">{item.productName}</div>
<div className="text-[10px] text-slate-400 font-bold tracking-widest uppercase">Qty: {item.quantity} Unit(s)</div>
</div>
</div>
<div className="text-right">
<div className="text-sm font-black text-slate-900">{(item.price * item.quantity).toLocaleString()}</div>
<div className="text-[10px] font-bold text-slate-400 uppercase tracking-tighter">@ {item.price}</div>
</div>
</div>
))}
</div>
</div>
</div>
{/* Bottom Totals Summary */}
<div className="bg-slate-900 p-8 text-white">
<div className="flex justify-between">
<div className="flex gap-12">
<div>
<div className="text-[10px] text-slate-500 uppercase font-black tracking-widest mb-2">Unique Items</div>
<div className="text-2xl font-black">{selectedOrder.items.length}</div>
</div>
<div>
<div className="text-[10px] text-slate-500 uppercase font-black tracking-widest mb-2">Record Status</div>
<div className="text-xs font-black px-3 py-1 bg-white/10 rounded-full border border-white/20 inline-flex items-center gap-2 uppercase">
<Clock size={12} /> Closed File
</div>
</div>
</div>
<div className="text-right flex flex-col gap-1 min-w-[250px]">
<div className="text-[10px] text-slate-500 uppercase font-black tracking-widest mb-1">Final Settlement</div>
<div className="text-4xl font-black text-emerald-400 leading-none mb-1">{selectedOrder.totalAmount.toLocaleString()}</div>
<div className="text-[10px] text-slate-500 font-bold uppercase tracking-[0.2em]">Transaction Fully Reconciled</div>
</div>
</div>
<div className="mt-8 pt-8 border-t border-white/10 flex justify-between items-center">
<p className="text-[9px] text-slate-500 uppercase font-bold tracking-widest max-w-sm">This is a permanent historical record. Modifications are disabled for archived data to maintain audit integrity.</p>
<button
onClick={() => window.print()}
className="px-8 py-3 bg-white text-slate-900 rounded-xl font-black text-xs uppercase tracking-widest hover:bg-slate-200 transition-all active:scale-[0.98] flex items-center gap-2 shadow-xl"
>
Print Copy <ShoppingBag size={14} />
</button>
</div>
</div>
</>
) : (
<div className="flex-1 flex flex-col items-center justify-center p-12 text-center text-slate-400">
<div className="bg-slate-50 p-6 rounded-full mb-6">
<Archive size={48} className="text-slate-100" />
</div>
<h3 className="text-slate-600 font-bold text-lg mb-2">Select a historical file</h3>
<p className="max-w-xs mx-auto text-sm italic font-medium">Browse through your previous days' turnover by selecting an entry from the ledger on the left.</p>
</div>
)}
</div>
</div>
<style>{`
.custom-scrollbar::-webkit-scrollbar {
width: 5px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 10px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: #cbd5e1;
}
@media print {
body * {
visibility: hidden;
}
.flex-1.bg-white.border.border-slate-200.rounded-2xl,
.flex-1.bg-white.border.border-slate-200.rounded-2xl * {
visibility: visible;
}
.flex-1.bg-white.border.border-slate-200.rounded-2xl {
position: absolute;
left: 0;
top: 0;
width: 100%;
border: none !important;
box-shadow: none !important;
}
button,
.sticky {
display: none !important;
}
.bg-slate-900 {
background-color: #f1f5f9 !important;
color: #000 !important;
}
.text-emerald-400 {
color: #059669 !important;
}
.text-slate-500 {
color: #64748b !important;
}
}
`}</style>
</div>
);
};
export default ArchivedOrders;

View File

@@ -0,0 +1,400 @@
import React, { useState, useEffect, useRef } from 'react';
import { Plus, X, Search, Filter, MoreVertical, RefreshCw, Edit2, Power, PowerOff, ShoppingCart, Package, ExternalLink } from 'lucide-react';
interface BaseItem {
id: number;
name: string;
description: string;
active: boolean;
}
interface Product {
id: number;
name: string;
price: number;
category: string;
active: boolean;
}
const BaseMenu = () => {
const [items, setItems] = useState<BaseItem[]>([]);
const [loading, setLoading] = useState(true);
const [showModal, setShowModal] = useState(false);
const [editingItem, setEditingItem] = useState<BaseItem | null>(null);
const [newItem, setNewItem] = useState({ name: '', description: '', active: true });
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
// Associated Products State
const [selectedBaseItem, setSelectedBaseItem] = useState<BaseItem | null>(null);
const [associatedProducts, setAssociatedProducts] = useState<Product[]>([]);
const [productsLoading, setProductsLoading] = useState(false);
const [showProductsModal, setShowProductsModal] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
useEffect(() => {
fetchItems();
const handleClickOutside = (event: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setOpenMenuId(null);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const fetchItems = async () => {
setLoading(true);
try {
const response = await fetch('http://localhost:8080/api/base-items');
const data = await response.json();
setItems(data);
} catch (error) {
console.error('Error fetching items:', error);
} finally {
setLoading(false);
}
};
const fetchAssociatedProducts = async (baseItem: BaseItem) => {
setSelectedBaseItem(baseItem);
setShowProductsModal(true);
setProductsLoading(true);
try {
const response = await fetch(`http://localhost:8080/api/products/category/${encodeURIComponent(baseItem.name)}`);
const data = await response.json();
setAssociatedProducts(data);
} catch (error) {
console.error('Error fetching associated products:', error);
} finally {
setProductsLoading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const url = editingItem
? `http://localhost:8080/api/base-items/${editingItem.id}`
: 'http://localhost:8080/api/base-items';
const method = editingItem ? 'PUT' : 'POST';
try {
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newItem),
});
if (response.ok) {
setShowModal(false);
setEditingItem(null);
setNewItem({ name: '', description: '', active: true });
fetchItems();
}
} catch (error) {
console.error('Error saving item:', error);
}
};
const handleEdit = (item: BaseItem) => {
setEditingItem(item);
setNewItem({ name: item.name, description: item.description, active: item.active });
setShowModal(true);
setOpenMenuId(null);
};
const handleToggleActive = async (item: BaseItem) => {
try {
const response = await fetch(`http://localhost:8080/api/base-items/${item.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...item, active: !item.active }),
});
if (response.ok) {
fetchItems();
setOpenMenuId(null);
}
} catch (error) {
console.error('Error toggling active status:', error);
}
};
return (
<div className="p-8 font-inter">
<div className="flex justify-between items-center mb-8">
<div>
<h1 className="text-2xl font-bold text-[#1e293b]">Base Items</h1>
<p className="text-sm text-[#64748b]">Manage your base inventory items</p>
</div>
<button
onClick={() => {
setEditingItem(null);
setNewItem({ name: '', description: '', active: true });
setShowModal(true);
}}
className="bg-[#231651] text-white px-4 py-2 rounded-xl flex items-center gap-2 shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all"
>
<Plus size={20} />
<span>Add New Item</span>
</button>
</div>
{/* Filters Bar */}
<div className="bg-white p-4 rounded-xl border border-[#e2e8f0] mb-6 flex flex-wrap gap-4 items-center justify-between shadow-sm">
<div className="flex gap-4 items-center flex-1">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={18} />
<input
type="text"
placeholder="Search items..."
className="w-full pl-10 pr-4 py-2 bg-gray-50 border border-[#e2e8f0] rounded-lg text-sm focus:outline-none focus:border-[#231651]/30 transition-all"
/>
</div>
<button className="flex items-center gap-2 px-3 py-2 border border-[#e2e8f0] rounded-lg text-sm text-[#64748b] hover:bg-gray-50 transition-all">
<Filter size={16} />
<span>Filter</span>
</button>
</div>
<button onClick={fetchItems} className="p-2 text-[#64748b] hover:bg-gray-100 rounded-lg transition-all">
<RefreshCw size={18} className={loading ? 'animate-spin' : ''} />
</button>
</div>
{/* Table */}
<div className="bg-white rounded-xl border border-[#e2e8f0] shadow-sm overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">ID</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Item Name</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Description</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-center">Products</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{loading ? (
<tr>
<td colSpan={6} className="px-6 py-12 text-center text-[#64748b]">
<div className="flex flex-col items-center gap-3">
<RefreshCw className="animate-spin" size={24} />
<p>Loading items...</p>
</div>
</td>
</tr>
) : items.length === 0 ? (
<tr>
<td colSpan={6} className="px-6 py-12 text-center text-[#64748b]">
<p className="text-lg font-medium mb-1">No items found</p>
<p className="text-sm">Click "Add New Item" to create your first item.</p>
</td>
</tr>
) : (
items.map((item) => (
<tr key={item.id} className="hover:bg-gray-50/50 transition-all group">
<td className="px-6 py-4 text-sm font-medium text-[#64748b]">#{item.id}</td>
<td className="px-6 py-4">
<span className="text-sm font-bold text-[#1e293b]">{item.name}</span>
</td>
<td className="px-6 py-4 text-sm text-[#64748b] max-w-xs truncate">{item.description}</td>
<td className="px-6 py-4 text-center">
<button
onClick={() => fetchAssociatedProducts(item)}
className="p-2 text-[#231651] bg-[#231651]/5 hover:bg-[#231651]/10 rounded-xl transition-all"
title="View Associated Products"
>
<ShoppingCart size={18} />
</button>
</td>
<td className="px-6 py-4">
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold ${
item.active
? 'bg-green-100 text-green-700'
: 'bg-gray-100 text-gray-600'
}`}>
<div className={`w-1.5 h-1.5 rounded-full ${item.active ? 'bg-green-500' : 'bg-gray-400'}`} />
{item.active ? 'Active' : 'Inactive'}
</span>
</td>
<td className="px-6 py-4 text-right relative">
<button
onClick={() => setOpenMenuId(openMenuId === item.id ? null : item.id)}
className="p-1.5 text-[#94a3b8] hover:text-[#231651] hover:bg-[#231651]/5 rounded-lg transition-all"
>
<MoreVertical size={18} />
</button>
{openMenuId === item.id && (
<div
ref={menuRef}
className="absolute right-6 top-12 w-48 bg-white rounded-xl shadow-xl border border-[#e2e8f0] z-[60] overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200"
>
<button
onClick={() => handleEdit(item)}
className="w-full flex items-center gap-3 px-4 py-3 text-sm text-[#475569] hover:bg-gray-50 hover:text-[#231651] transition-all"
>
<Edit2 size={16} />
<span className="font-semibold">Edit Item</span>
</button>
<button
onClick={() => handleToggleActive(item)}
className="w-full flex items-center gap-3 px-4 py-3 text-sm text-[#475569] hover:bg-gray-50 hover:text-[#231651] transition-all border-t border-[#e2e8f0]/50"
>
{item.active ? (
<>
<PowerOff size={16} className="text-red-500" />
<span className="font-semibold">Mark as Inactive</span>
</>
) : (
<>
<Power size={16} className="text-green-500" />
<span className="font-semibold">Mark as Active</span>
</>
)}
</button>
</div>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{/* Associated Products Modal */}
{showProductsModal && (
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
<div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
<div className="px-8 py-6 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<div>
<h2 className="text-xl font-bold text-[#1e293b]">Products for: {selectedBaseItem?.name}</h2>
<p className="text-xs text-[#64748b] mt-0.5">Showing all associated products in this category</p>
</div>
<button onClick={() => setShowProductsModal(false)} className="p-2 hover:bg-gray-200 rounded-full transition-all">
<X size={24} className="text-[#64748b]" />
</button>
</div>
<div className="p-8 max-h-[60vh] overflow-y-auto">
{productsLoading ? (
<div className="flex flex-col items-center py-12 text-[#64748b]">
<RefreshCw className="animate-spin mb-4" size={32} />
<p className="font-medium">Fetching associated products...</p>
</div>
) : associatedProducts.length === 0 ? (
<div className="flex flex-col items-center py-12 text-center">
<div className="w-16 h-16 bg-gray-100 rounded-2xl flex items-center justify-center text-[#94a3b8] mb-4">
<Package size={32} />
</div>
<h3 className="text-lg font-bold text-[#1e293b]">No Products Found</h3>
<p className="text-sm text-[#64748b] mt-1 max-w-xs">There are no products currently linked to the "{selectedBaseItem?.name}" category.</p>
</div>
) : (
<div className="space-y-3">
{associatedProducts.map(product => (
<div key={product.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-2xl border border-[#e2e8f0] hover:border-[#231651]/20 transition-all group">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-white rounded-xl flex items-center justify-center text-[#231651] shadow-sm group-hover:scale-105 transition-transform">
<Package size={24} />
</div>
<div>
<p className="font-bold text-[#1e293b]">{product.name}</p>
<span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded ${product.active ? 'text-green-600 bg-green-100' : 'text-gray-500 bg-gray-200'}`}>
{product.active ? 'Active' : 'Inactive'}
</span>
</div>
</div>
<div className="text-right">
<p className="text-lg font-bold text-[#231651]">{product.price}</p>
<p className="text-[10px] text-[#64748b] font-medium">Sale Price</p>
</div>
</div>
))}
</div>
)}
</div>
<div className="px-8 py-6 bg-gray-50/50 border-t border-[#e2e8f0] flex justify-end">
<button
onClick={() => setShowProductsModal(false)}
className="px-6 py-2.5 bg-[#231651] text-white font-bold rounded-xl shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2"
>
Close View
</button>
</div>
</div>
</div>
)}
{/* Standard Modal (Add/Edit) */}
{showModal && (
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
<div className="bg-white rounded-2xl w-full max-w-md shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
<div className="px-6 py-4 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<h2 className="text-lg font-bold text-[#1e293b]">
{editingItem ? 'Edit Base Item' : 'Add New Base Item'}
</h2>
<button onClick={() => setShowModal(false)} className="p-1 hover:bg-gray-200 rounded-lg transition-all">
<X size={20} className="text-[#64748b]" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-6 space-y-4">
<div>
<label className="block text-sm font-bold text-[#475569] mb-1.5">Item Name</label>
<input
required
type="text"
value={newItem.name}
onChange={(e) => setNewItem({ ...newItem, name: e.target.value })}
placeholder="e.g. Fresh Tomato"
className="w-full px-4 py-2.5 border border-[#e2e8f0] rounded-xl focus:outline-none focus:border-[#231651] focus:ring-1 focus:ring-[#231651] transition-all text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-[#475569] mb-1.5">Description</label>
<textarea
value={newItem.description}
onChange={(e) => setNewItem({ ...newItem, description: e.target.value })}
placeholder="Tell us more about this item..."
rows={3}
className="w-full px-4 py-2.5 border border-[#e2e8f0] rounded-xl focus:outline-none focus:border-[#231651] focus:ring-1 focus:ring-[#231651] transition-all text-sm resize-none"
/>
</div>
<div className="flex items-center gap-3 py-2">
<button
type="button"
onClick={() => setNewItem({ ...newItem, active: !newItem.active })}
className={`w-11 h-6 rounded-full transition-all relative ${newItem.active ? 'bg-[#231651]' : 'bg-gray-300'}`}
>
<div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${newItem.active ? 'translate-x-5' : ''}`} />
</button>
<span className="text-sm font-semibold text-[#1e293b]">Mark as Active</span>
</div>
<div className="pt-4 flex gap-3">
<button
type="button"
onClick={() => setShowModal(false)}
className="flex-1 px-4 py-2.5 border border-[#e2e8f0] text-[#64748b] font-bold rounded-xl hover:bg-gray-50 transition-all text-sm"
>
Cancel
</button>
<button
type="submit"
className="flex-1 px-4 py-2.5 bg-[#231651] text-white font-bold rounded-xl shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all text-sm"
>
{editingItem ? 'Update Item' : 'Save Item'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
};
export default BaseMenu;

View File

@@ -0,0 +1,331 @@
import React, { useState, useEffect } from 'react';
import { Search, ChevronRight, Filter, Loader2, Download, Printer, X } from 'lucide-react';
import { format } from 'date-fns';
interface PurchaseOrder {
id: number;
purchaseId: string;
date: string;
vendor: { id: number; name: string };
amount: number;
paidTotal: number;
status: string;
referenceId: string;
}
const Bills: React.FC = () => {
const [orders, setOrders] = useState<PurchaseOrder[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [statusFilter, setStatusFilter] = useState('All');
const [searchTerm, setSearchTerm] = useState('');
const [selectedOrder, setSelectedOrder] = useState<PurchaseOrder | null>(null);
const [showPayModal, setShowPayModal] = useState(false);
const [paymentAmount, setPaymentAmount] = useState<number>(0);
const [isSaving, setIsSaving] = useState(false);
useEffect(() => {
fetchOrders();
}, []);
const fetchOrders = async () => {
try {
setIsLoading(true);
const response = await fetch('/api/purchases/orders');
if (response.ok) {
const data = await response.json();
setOrders(data);
}
} catch (error) {
console.error('Error fetching orders:', error);
} finally {
setIsLoading(false);
}
};
const handleRecordPayment = async () => {
if (!selectedOrder) return;
try {
setIsSaving(true);
const updatedPaidTotal = Number(selectedOrder.paidTotal) + Number(paymentAmount);
const response = await fetch('/api/purchases/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...selectedOrder,
paidTotal: updatedPaidTotal,
status: updatedPaidTotal >= selectedOrder.amount ? 'CLOSE' : 'PARTIALLY PAID'
}),
});
if (response.ok) {
await fetchOrders();
setShowPayModal(false);
setSelectedOrder(null);
setPaymentAmount(0);
}
} catch (error) {
console.error('Error recording payment:', error);
} finally {
setIsSaving(false);
}
};
const filteredOrders = orders.filter(order => {
const matchesSearch = order.purchaseId.toLowerCase().includes(searchTerm.toLowerCase()) ||
order.referenceId?.toLowerCase().includes(searchTerm.toLowerCase());
const matchesStatus = statusFilter === 'All' || order.status === statusFilter;
return matchesSearch && matchesStatus;
});
const getStatusColor = (status: string) => {
switch (status) {
case 'BILLED':
return 'bg-green-100 text-green-700 border-green-200';
case 'CLOSE':
case 'CLOSED':
return 'bg-red-100 text-red-700 border-red-200';
case 'OPEN':
return 'bg-blue-100 text-blue-700 border-blue-200';
case 'PARTIALLY PAID':
return 'bg-amber-100 text-amber-700 border-amber-200';
default:
return 'bg-slate-100 text-slate-700 border-slate-200';
}
};
return (
<div className="flex flex-col h-full bg-slate-50/50">
{/* Header Section */}
<div className="p-6 bg-white border-b border-slate-200">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-slate-900">Purchase Bills</h1>
<p className="text-sm text-slate-500 mt-1">Manage and track your vendor payments and payables</p>
</div>
<div className="flex items-center gap-3">
<button
title="Download bill report"
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-all shadow-sm"
>
<Download size={18} />
Export
</button>
<button
title="Print all bills"
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-all shadow-md shadow-indigo-100"
>
<Printer size={18} />
Print Batch
</button>
</div>
</div>
{/* Filters and Search */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mt-6">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
<input
type="text"
placeholder="Search by ID or Reference..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
title="Search through bills"
className="w-full pl-10 pr-4 py-2 bg-slate-100 border-transparent focus:bg-white focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 rounded-xl text-sm transition-all outline-none"
/>
</div>
<div className="flex items-center gap-3">
<div className="relative min-w-[160px]">
<Filter className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
title="Filter by payment status"
className="w-full pl-10 pr-4 py-2 bg-white border border-slate-200 rounded-lg text-sm appearance-none focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
>
<option value="All">All Status</option>
<option value="BILLED">Billed</option>
<option value="CLOSE">Closed</option>
<option value="OPEN">Open</option>
<option value="PARTIALLY PAID">Partially Paid</option>
</select>
</div>
</div>
</div>
</div>
{/* Table Section */}
<div className="flex-1 overflow-auto p-6">
<div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-slate-50 border-b border-slate-200">
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Purchase ID</th>
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Date</th>
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider text-right">Order Amount ()</th>
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider text-right">Paid Total ()</th>
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider text-right">Payables ()</th>
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Reference ID</th>
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider"></th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{isLoading ? (
<tr>
<td colSpan={8} className="px-6 py-12 text-center text-slate-400">
<div className="flex flex-col items-center gap-2">
<Loader2 size={24} className="animate-spin text-indigo-500" />
<span>Loading bills...</span>
</div>
</td>
</tr>
) : filteredOrders.length === 0 ? (
<tr>
<td colSpan={8} className="px-6 py-12 text-center text-slate-400">
No matching bills found
</td>
</tr>
) : (
filteredOrders.map((order) => {
const payables = Number(order.amount) - Number(order.paidTotal);
return (
<tr key={order.id} className="hover:bg-slate-50 transition-colors group">
<td className="px-6 py-4">
<span className="font-semibold text-slate-900">{order.purchaseId}</span>
</td>
<td className="px-6 py-4 text-[13px] text-slate-600">
{order.date ? format(new Date(order.date), 'dd-MMM-yyyy hh:mm a') : '-'}
</td>
<td className="px-6 py-4">
<span className={`px-3 py-1 rounded-full text-[11px] font-bold border ${getStatusColor(order.status)} uppercase`}>
{order.status}
</span>
</td>
<td className="px-6 py-4 text-[13px] font-bold text-slate-900 text-right">
{Number(order.amount).toFixed(2)}
</td>
<td className="px-6 py-4 text-[13px] font-medium text-slate-600 text-right">
{Number(order.paidTotal).toFixed(2)}
</td>
<td className={`px-6 py-4 text-[13px] font-bold text-right ${payables > 0 ? 'text-red-600' : 'text-green-600'}`}>
{payables.toFixed(2)}
</td>
<td className="px-6 py-4 text-[13px] text-slate-500">
{order.referenceId || '-'}
</td>
<td className="px-6 py-4 text-right">
<button
onClick={() => {
setSelectedOrder(order);
setPaymentAmount(payables);
setShowPayModal(true);
}}
title="Record Payment"
className="p-2 text-slate-300 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all"
>
<ChevronRight size={20} className="group-hover:translate-x-0.5 transition-transform" />
</button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
</div>
{/* Payment Modal */}
{showPayModal && selectedOrder && (
<div className="fixed inset-0 bg-slate-900/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in duration-200">
<div className="p-6 border-b border-slate-100">
<div className="flex items-center justify-between">
<h2 className="text-xl font-bold text-slate-900">Record Payment</h2>
<button
onClick={() => setShowPayModal(false)}
className="p-2 hover:bg-slate-100 rounded-full transition-colors"
>
<X size={20} className="text-slate-400" />
</button>
</div>
<p className="text-sm text-slate-500 mt-1">Order #{selectedOrder.purchaseId}</p>
</div>
<div className="p-6 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="p-4 bg-slate-50 rounded-xl">
<p className="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Order Total</p>
<p className="text-lg font-bold text-slate-900">{Number(selectedOrder.amount).toFixed(2)}</p>
</div>
<div className="p-4 bg-red-50 rounded-xl">
<p className="text-[11px] font-bold text-red-500 uppercase tracking-wider">Remaining</p>
<p className="text-lg font-bold text-red-600">{(selectedOrder.amount - selectedOrder.paidTotal).toFixed(2)}</p>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-semibold text-slate-700">Payment Amount ()</label>
<input
type="number"
value={paymentAmount}
onChange={(e) => setPaymentAmount(Number(e.target.value))}
className="w-full px-4 py-3 bg-slate-100 border-transparent focus:bg-white focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 rounded-xl text-lg font-bold outline-none transition-all"
/>
</div>
</div>
<div className="p-6 bg-slate-50 flex items-center gap-3">
<button
onClick={() => setShowPayModal(false)}
className="flex-1 px-4 py-3 text-sm font-semibold text-slate-700 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 transition-all"
>
Cancel
</button>
<button
onClick={handleRecordPayment}
disabled={isSaving || paymentAmount <= 0}
className="flex-[2] px-8 py-3 text-sm font-semibold text-white bg-indigo-600 rounded-xl hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg shadow-indigo-100 flex items-center justify-center gap-2"
>
{isSaving ? <Loader2 size={18} className="animate-spin" /> : 'Confirm Payment'}
</button>
</div>
</div>
</div>
)}
{/* Footer / Pagination */}
<div className="p-4 px-6 bg-white border-t border-slate-200 flex items-center justify-between text-sm text-slate-500">
<div>
Showing {filteredOrders.length} of {orders.length} bills
</div>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<span>Show:</span>
<select className="bg-slate-50 border border-slate-200 rounded px-2 py-1 outline-none">
<option>10</option>
<option>20</option>
<option>50</option>
</select>
</div>
<div className="flex items-center gap-1">
<button className="p-2 hover:bg-slate-100 rounded">
<ChevronRight size={18} className="rotate-180" />
</button>
<span className="px-3">1 of 1</span>
<button className="p-2 hover:bg-slate-100 rounded">
<ChevronRight size={18} />
</button>
</div>
</div>
</div>
</div>
);
};
export default Bills;

View File

@@ -0,0 +1,487 @@
import React, { useState, useEffect } from 'react';
import { Search, User, Phone, Tag, ChevronRight, UserCheck, UserMinus, MoreVertical, LayoutGrid, List, Edit2, Trash2, Shield, X, Eye, EyeOff, Loader2, AlertCircle, CheckCircle } from 'lucide-react';
import Pagination from '../components/Pagination';
interface UserDto {
id: number;
mobileNumber: string;
name: string;
loggedIn: boolean;
}
const Customers: React.FC = () => {
const [users, setUsers] = useState<UserDto[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
// Pagination States
const [currentPage, setCurrentPage] = useState(0);
const [pageSize, setPageSize] = useState(10);
const [totalElements, setTotalElements] = useState(0);
// Edit Modal State
const [showEditModal, setShowEditModal] = useState(false);
const [editingUser, setEditingUser] = useState<UserDto | null>(null);
const [editForm, setEditForm] = useState({ name: '', mobileNumber: '', pin: '' });
const [isSaving, setIsSaving] = useState(false);
const [showPin, setShowPin] = useState(false);
const [errors, setErrors] = useState<{[key: string]: string}>({});
// Notification State
const [toast, setToast] = useState<{message: string, type: 'success' | 'error'} | null>(null);
// Action Menu State
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
useEffect(() => {
fetchUsers();
}, [currentPage, pageSize]);
const fetchUsers = async () => {
try {
setIsLoading(true);
const host = window.location.hostname;
const response = await fetch(`http://${host}:8080/api/auth/users?page=${currentPage}&size=${pageSize}`);
if (response.ok) {
const data = await response.json();
if (data && data.content) {
setUsers(data.content);
setTotalElements(data.totalElements);
} else {
setUsers([]);
setTotalElements(0);
}
}
} catch (error) {
console.error('Error fetching users:', error);
} finally {
setIsLoading(false);
}
};
const showNotification = (message: string, type: 'success' | 'error') => {
setToast({ message, type });
setTimeout(() => setToast(null), 3000);
};
const handleEditClick = (user: UserDto) => {
setEditingUser(user);
setEditForm({ name: user.name, mobileNumber: user.mobileNumber, pin: '' });
setShowEditModal(true);
setOpenMenuId(null);
setErrors({});
setShowPin(false);
};
const handleDeleteClick = async (user: UserDto) => {
if (!window.confirm(`Are you sure you want to permanently delete ${user.name}? This action cannot be undone.`)) return;
try {
const host = window.location.hostname;
const response = await fetch(`http://${host}:8080/api/auth/users/${user.id}`, {
method: 'DELETE',
});
if (response.ok) {
showNotification(`${user.name} deleted successfully`, 'success');
fetchUsers();
setOpenMenuId(null);
} else {
showNotification('Failed to delete user', 'error');
}
} catch (error) {
console.error('Error deleting user:', error);
showNotification('Error connecting to server', 'error');
}
};
const validateForm = () => {
const newErrors: {[key: string]: string} = {};
if (!editForm.name.trim()) newErrors.name = 'Full Name is required';
if (!/^[0-9]{10}$/.test(editForm.mobileNumber)) {
newErrors.mobileNumber = 'Mobile number must be exactly 10 digits';
}
if (editForm.pin && !/^[0-9]{6}$/.test(editForm.pin)) {
newErrors.pin = 'PIN must be exactly 6 digits';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleUpdateSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!editingUser) return;
if (!validateForm()) return;
setIsSaving(true);
try {
const host = window.location.hostname;
const response = await fetch(`http://${host}:8080/api/auth/users/${editingUser.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(editForm),
});
if (response.ok) {
showNotification('Customer profile updated successfully', 'success');
setShowEditModal(false);
fetchUsers();
} else {
const error = await response.json();
showNotification(error.message || 'Failed to update user', 'error');
}
} catch (error) {
console.error('Error updating user:', error);
showNotification('Connection error, try again later', 'error');
} finally {
setIsSaving(false);
}
};
const getInitials = (name: string) => {
if (!name) return '??';
return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
};
const filteredUsers = users.filter(user =>
user.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
user.mobileNumber?.includes(searchTerm)
);
return (
<>
{/* Toast Notification - Moved outside animation trapping */}
{toast && (
<div className="fixed top-8 left-1/2 -translate-x-1/2 z-[200] animate-in fade-in slide-in-from-top-4 duration-300">
<div className={`px-6 py-3 rounded-2xl shadow-2xl flex items-center gap-3 border ${
toast.type === 'success'
? 'bg-emerald-50 border-emerald-100 text-emerald-800'
: 'bg-red-50 border-red-100 text-red-800'
}`}>
{toast.type === 'success' ? <CheckCircle size={20} className="text-emerald-500" /> : <AlertCircle size={20} className="text-red-500" />}
<span className="text-sm font-bold">{toast.message}</span>
</div>
</div>
)}
{/* Main Animated Container */}
<div className="flex flex-col h-full bg-[#f8fafc] p-8 gap-8 overflow-y-auto animate-slideUp font-inter relative">
{/* Header Section */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6 max-w-[1600px]">
<div className="flex items-center gap-5">
<div className="w-14 h-14 bg-[#231651] rounded-xl flex items-center justify-center shadow-lg shadow-[#231651]/20">
<User className="text-white w-7 h-7" />
</div>
<div>
<h1 className="text-2xl font-bold text-[#1e293b]">Customer Management</h1>
<p className="text-sm text-[#64748b]">View and manage customers registered through the ordering site</p>
</div>
</div>
<div className="flex items-center gap-4">
<div className="relative group min-w-[320px]">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8] group-focus-within:text-[#231651] transition-colors" size={18} />
<input
type="text"
placeholder="Search customers..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full pl-10 pr-4 py-2 bg-white border border-[#e2e8f0] rounded-xl text-sm focus:outline-none focus:border-[#231651]/30 transition-all shadow-sm"
/>
</div>
<div className="flex p-1 bg-white border border-[#e2e8f0] rounded-xl shadow-sm">
<button
className={`p-1.5 rounded-lg transition-all ${viewMode === 'table' ? 'bg-[#231651] text-white' : 'text-[#64748b] hover:bg-gray-50'}`}
onClick={() => setViewMode('table')}
>
<List size={20} />
</button>
<button
className={`p-1.5 rounded-lg transition-all ${viewMode === 'grid' ? 'bg-[#231651] text-white' : 'text-[#64748b] hover:bg-gray-50'}`}
onClick={() => setViewMode('grid')}
>
<LayoutGrid size={20} />
</button>
</div>
</div>
</div>
{/* Main Content */}
<div className="max-w-[1600px]">
{isLoading ? (
<div className="flex flex-col items-center justify-center py-24 bg-white rounded-xl border border-[#e2e8f0] shadow-sm">
<div className="w-10 h-10 border-4 border-[#231651]/10 border-t-[#231651] rounded-full animate-spin"></div>
<p className="mt-4 text-[#64748b] font-medium text-sm">Loading customer base...</p>
</div>
) : (
<div className="bg-white rounded-xl border border-[#e2e8f0] shadow-sm">
{viewMode === 'table' ? (
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Customer Info</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Contact Info</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Membership</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{filteredUsers.length > 0 ? (
filteredUsers.map((user) => (
<tr key={user.id} className="hover:bg-gray-50/50 transition-all">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-[#231651] rounded-lg flex items-center justify-center text-white font-bold text-sm">
{getInitials(user.name)}
</div>
<div>
<p className="text-sm font-bold text-[#1e293b]">{user.name}</p>
<p className="text-[11px] text-[#64748b]">ID: {user.id.toString().padStart(4, '0')}</p>
</div>
</div>
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2 text-sm text-[#1e293b] font-medium">
<Phone size={14} className="text-[#94a3b8]" />
<span>{user.mobileNumber}</span>
</div>
</td>
<td className="px-6 py-4">
<span className="px-2.5 py-1 bg-blue-50 text-blue-600 rounded-lg text-xs font-semibold whitespace-nowrap">
REGULAR CUSTOMER
</span>
</td>
<td className="px-6 py-4">
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold ${
user.loggedIn
? 'bg-green-100 text-green-700'
: 'bg-gray-100 text-gray-600'
}`}>
<div className={`w-1.5 h-1.5 rounded-full ${user.loggedIn ? 'bg-green-500' : 'bg-gray-400'}`} />
{user.loggedIn ? 'Active Now' : 'Offline'}
</span>
</td>
<td className="px-6 py-4 text-right relative">
<button onClick={() => setOpenMenuId(openMenuId === user.id ? null : user.id)} className="p-1.5 text-[#94a3b8] hover:text-[#231651] rounded-lg transition-colors">
<MoreVertical size={18} />
</button>
{openMenuId === user.id && (
<div className="absolute right-6 top-10 w-40 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-50 overflow-hidden animate-in fade-in slide-in-from-top-2">
<button onClick={() => handleEditClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium border-b border-[#f1f5f9]">
<Edit2 size={16} /> Edit User
</button>
<button onClick={() => handleDeleteClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-red-600 font-medium font-bold">
<Trash2 size={16} /> Delete User
</button>
</div>
)}
</td>
</tr>
))
) : (
<tr>
<td colSpan={5} className="px-6 py-12 text-center text-[#64748b]">
<div className="flex flex-col items-center justify-center">
<User size={40} className="mb-2 opacity-20" />
<p className="font-medium">No customers found</p>
</div>
</td>
</tr>
)}
</tbody>
</table>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 p-6">
{filteredUsers.map(user => (
<div key={user.id} className="group relative p-6 bg-white border border-[#e2e8f0] rounded-xl flex flex-col items-center text-center transition-all hover:shadow-lg hover:-translate-y-1">
<div className="absolute top-4 right-4">
<button onClick={() => setOpenMenuId(openMenuId === user.id ? null : user.id)} className="p-1.5 text-[#94a3b8] hover:text-[#231651] rounded-lg">
<MoreVertical size={18} />
</button>
{openMenuId === user.id && (
<div className="absolute right-0 mt-2 w-40 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-50 overflow-hidden">
<button onClick={() => handleEditClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium">
<Edit2 size={16} /> Edit
</button>
<button onClick={() => handleDeleteClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-red-600 font-medium">
<Trash2 size={16} /> Delete
</button>
</div>
)}
</div>
<div className="relative mb-4">
<div className="w-20 h-20 bg-[#231651] rounded-2xl flex items-center justify-center text-2xl font-bold text-white shadow-lg shadow-[#231651]/20">
{getInitials(user.name)}
</div>
<div className={`absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-4 border-white shadow-sm ${user.loggedIn ? 'bg-green-500' : 'bg-gray-400'}`}></div>
</div>
<h3 className="text-lg font-bold text-[#1e293b] mb-0.5">{user.name}</h3>
<p className="text-sm text-[#64748b] font-medium mb-4">{user.mobileNumber}</p>
<div className="flex items-center gap-2 mb-6">
<span className="px-2 py-0.5 bg-blue-50 text-blue-600 text-[10px] font-bold rounded-lg border border-blue-100 uppercase tracking-wider">
RIT STUDENT
</span>
</div>
<button onClick={() => handleEditClick(user)} className="w-full py-2.5 bg-gray-50 border border-[#e2e8f0] text-[#1e293b] hover:bg-[#231651] hover:text-white rounded-xl flex items-center justify-center gap-2 text-sm font-bold transition-all">
Edit Profile <Edit2 size={16} />
</button>
</div>
))}
</div>
)}
<Pagination
currentPage={currentPage}
pageSize={pageSize}
totalElements={totalElements}
onPageChange={setCurrentPage}
onPageSizeChange={(newSize) => {
setPageSize(newSize);
setCurrentPage(0);
}}
/>
</div>
)}
</div>
</div>
{/* Edit User Modal - Positioned absolutely relative to viewport */}
{showEditModal && (
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4 overflow-y-auto">
<div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden animate-in zoom-in duration-300 my-auto">
<div className="px-10 py-8 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-[#231651]/5 rounded-xl flex items-center justify-center text-[#231651]">
<Edit2 size={24} />
</div>
<div>
<h2 className="text-2xl font-bold text-[#1e293b]">Edit Customer</h2>
<p className="text-sm text-[#64748b]">Update account details and security credentials</p>
</div>
</div>
<button onClick={() => setShowEditModal(false)} className="p-2 hover:bg-gray-200 rounded-full transition-colors">
<X size={24} className="text-[#64748b]" />
</button>
</div>
<form onSubmit={handleUpdateSubmit} className="p-10 space-y-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
<div>
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-2.5 tracking-widest ml-1">Full Name</label>
<div className="relative">
<User size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-[#94a3b8]" />
<input
required
type="text"
value={editForm.name}
onChange={(e) => {
setEditForm({...editForm, name: e.target.value});
if (errors.name) setErrors({...errors, name: ''});
}}
className={`w-full pl-12 pr-4 py-4 bg-slate-50 border rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none ${
errors.name ? 'border-red-500 ring-4 ring-red-500/5' : 'border-[#e2e8f0]'
}`}
placeholder="e.g. John Doe"
/>
</div>
{errors.name && <p className="text-xs text-red-500 mt-2 font-bold flex items-center gap-1 ml-1"><AlertCircle size={12} />{errors.name}</p>}
</div>
<div>
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-2.5 tracking-widest ml-1">Mobile Number</label>
<div className="relative">
<Phone size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-[#94a3b8]" />
<input
required
type="text"
maxLength={10}
value={editForm.mobileNumber}
onChange={(e) => {
const val = e.target.value.replace(/\D/g, '');
setEditForm({...editForm, mobileNumber: val});
if (errors.mobileNumber) setErrors({...errors, mobileNumber: ''});
}}
className={`w-full pl-12 pr-4 py-4 bg-slate-50 border rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none ${
errors.mobileNumber ? 'border-red-500 ring-4 ring-red-500/5' : 'border-[#e2e8f0]'
}`}
placeholder="10-digit number"
/>
</div>
{errors.mobileNumber && <p className="text-xs text-red-500 mt-2 font-bold flex items-center gap-1 ml-1"><AlertCircle size={12} />{errors.mobileNumber}</p>}
</div>
</div>
<div className="p-6 bg-slate-50 rounded-[2rem] border border-[#e2e8f0] border-dashed">
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-3 tracking-widest ml-1">Reset Security PIN (Optional)</label>
<div className="relative max-w-sm">
<Shield size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-[#94a3b8]" />
<input
type={showPin ? "text" : "password"}
maxLength={6}
value={editForm.pin}
onChange={(e) => {
const val = e.target.value.replace(/\D/g, '');
setEditForm({...editForm, pin: val});
if (errors.pin) setErrors({...errors, pin: ''});
}}
className={`w-full pl-12 pr-12 py-4 bg-white border rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none ${
errors.pin ? 'border-red-500 ring-4 ring-red-500/5' : 'border-[#e2e8f0]'
}`}
placeholder="Enter new 6-digit PIN"
/>
<button
type="button"
onClick={() => setShowPin(!showPin)}
className="absolute right-4 top-1/2 -translate-y-1/2 text-[#94a3b8] hover:text-[#231651] transition-colors p-1"
>
{showPin ? <EyeOff size={20} /> : <Eye size={20} />}
</button>
</div>
{errors.pin ? (
<p className="text-xs text-red-500 mt-2 font-bold flex items-center gap-1 ml-1"><AlertCircle size={12} />{errors.pin}</p>
) : (
<p className="text-xs text-[#94a3b8] mt-3 font-semibold ml-1">Only update this if the student has forgotten their credentials.</p>
)}
</div>
<div className="flex gap-4 pt-6">
<button
type="button"
onClick={() => setShowEditModal(false)}
className="flex-1 px-8 py-4 border-2 border-[#e2e8f0] text-[#64748b] font-bold rounded-2xl hover:bg-gray-50 transition-all text-sm"
>
Discard Changes
</button>
<button
type="submit"
disabled={isSaving}
className="flex-[1.5] px-8 py-4 bg-[#231651] text-white font-bold rounded-2xl shadow-xl shadow-[#231651]/20 hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-3 text-sm"
>
{isSaving ? (
<><Loader2 size={20} className="animate-spin" /> Syncing Details...</>
) : (
<><Edit2 size={20} /> Save Account Updates</>
)}
</button>
</div>
</form>
</div>
</div>
)}
</>
);
};
export default Customers;

View File

@@ -0,0 +1,306 @@
import { useState, useEffect } from 'react';
import {
Target,
ChevronRight,
ShoppingBag,
ArrowRight,
Wallet
} from 'lucide-react';
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
PieChart,
Pie,
Cell
} from 'recharts';
import { motion } from 'framer-motion';
const Dashboard = () => {
const [activeTab, setActiveTab] = useState('Sales');
const [timeRange, setTimeRange] = useState('Today');
const [data, setData] = useState<any>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
const response = await fetch('/api/dashboard/stats');
if (response.ok) {
const result = await response.json();
setData(result);
}
} catch (error) {
console.error('Error fetching dashboard data:', error);
} finally {
setIsLoading(false);
}
};
fetchData();
}, []);
if (isLoading || !data) {
return (
<div className="h-screen flex items-center justify-center bg-slate-50/50">
<motion.div
animate={{ scale: [1, 1.1, 1], opacity: [0.5, 1, 0.5] }}
transition={{ repeat: Infinity, duration: 1.5 }}
className="text-[#521c4b] font-black uppercase tracking-widest text-sm"
>
Loading Business Intelligence...
</motion.div>
</div>
);
}
const { stats, storeOverview, hourlySales, insights } = data;
const pieData = [
{ name: 'Full Payment', value: stats.totalSales, color: '#8b5cf6' },
{ name: 'Credit', value: 0, color: '#fbbf24' } // Credits logic can be added later
];
return (
<div className="p-8 space-y-8 bg-slate-50/50 min-h-screen font-inter">
{/* Top Header */}
<div className="flex items-center justify-between">
<div className="flex flex-col">
<div className="flex items-center gap-2 mb-1">
<button title="Navigate back to previous section" className="p-1.5 hover:bg-slate-100 rounded-lg transition-all">
<ArrowRight className="rotate-180 text-slate-400" size={18} />
</button>
<h2 className="text-xs font-black text-[#521c4b] uppercase tracking-widest">Dashboard</h2>
</div>
<h1 className="text-2xl font-black text-slate-800">Good morning</h1>
<p className="text-[10px] text-slate-400 font-medium flex items-center gap-1.5">
<span className="p-0.5 bg-slate-200 rounded text-slate-500">i</span>
The default time settings for the merchant view are from 12:00 AM to 11:59 PM.
</p>
</div>
<div className="flex items-center gap-3">
<div className="relative group">
<select title="Filter by store type or category" className="appearance-none bg-white border border-slate-200 rounded-xl px-4 py-2 pr-10 text-xs font-bold text-slate-600 outline-none focus:border-[#521c4b] transition-all cursor-pointer shadow-sm">
<option>Store Type: All</option>
</select>
<div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
<ChevronRight size={14} className="rotate-90 text-slate-400" />
</div>
</div>
</div>
</div>
{/* Main Stats Grid */}
<div className="grid grid-cols-12 gap-6">
{/* Sales Chart Section */}
<div className="col-span-12 lg:col-span-5 bg-white p-6 rounded-[32px] border border-slate-100 shadow-sm relative overflow-hidden group">
<div className="flex items-center gap-8 mb-8 border-b border-slate-50">
{['Sales', 'Payments'].map(tab => (
<button
key={tab}
title={`View ${tab} analysis and trends`}
onClick={() => setActiveTab(tab)}
className={`pb-4 text-[11px] font-black uppercase tracking-widest transition-all relative ${activeTab === tab ? 'text-[#521c4b]' : 'text-slate-400 hover:text-slate-600'}`}
>
{tab}
{activeTab === tab && (
<motion.div layoutId="tabLineMain" className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#521c4b]" />
)}
</button>
))}
</div>
<div className="flex items-center justify-end mb-4 gap-4">
<div className="flex items-center gap-2">
<div className="w-2.5 h-2.5 rounded-full border-2 border-[#521c4b]/30 bg-[#521c4b]/10" />
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Today's Revenue</span>
</div>
</div>
<div className="h-[280px] w-full mt-4">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={hourlySales}>
<defs>
<linearGradient id="colorSalesMain" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#f43f5e" stopOpacity={0.2}/>
<stop offset="95%" stopColor="#f43f5e" stopOpacity={0}/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="time" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} />
<YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} tickFormatter={(v) => v >= 1000 ? `₹${v/1000}k` : `₹${v}`} />
<Tooltip contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }} />
<Area type="monotone" dataKey="value" stroke="#f43f5e" strokeWidth={3} fillOpacity={1} fill="url(#colorSalesMain)" />
</AreaChart>
</ResponsiveContainer>
</div>
</div>
{/* Total Sales Gauge */}
<div className="col-span-12 lg:col-span-4 bg-white p-6 rounded-[32px] border border-slate-100 shadow-sm relative">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Total Revenue</h3>
<Target size={14} className="text-slate-300" />
</div>
</div>
<div className="relative h-[280px] flex flex-col items-center justify-center">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={pieData}
cx="50%"
cy="50%"
innerRadius={75}
outerRadius={100}
paddingAngle={0}
dataKey="value"
startAngle={210}
endAngle={-30}
>
{pieData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
</PieChart>
</ResponsiveContainer>
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center">
<h2 className="text-3xl font-black text-slate-800 tracking-tighter">₹{stats.totalSales.toLocaleString()}</h2>
<p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Life Time</p>
</div>
<div className="flex gap-6 mt-2">
{pieData.map(item => (
<div key={item.name} className="flex items-center gap-2">
<div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: item.color }} />
<span className="text-[9px] font-black text-slate-500 uppercase tracking-widest font-black">{item.name}</span>
</div>
))}
</div>
</div>
</div>
{/* Right Stats Column */}
<div className="col-span-12 lg:col-span-3 space-y-6">
{/* Filters */}
<div className="flex items-center justify-between overflow-x-auto gap-2 pb-2 scrollbar-none">
{['Yesterday', 'Today', 'Week', '30 Days'].map(range => (
<button
key={range}
title={`Analyze data from ${range.toLowerCase()}`}
onClick={() => setTimeRange(range)}
className={`whitespace-nowrap px-3 py-2 text-[10px] font-black uppercase tracking-widest transition-all rounded-xl ${timeRange === range ? 'text-white bg-[#521c4b] shadow-md shadow-[#521c4b]/20' : 'text-slate-400 hover:text-slate-600'}`}
>
{range}
</button>
))}
</div>
{/* Total Orders Card */}
<div title="View detailed order volume and throughput" className="bg-white p-6 rounded-[24px] border border-slate-100 shadow-sm relative h-[180px] flex flex-col justify-between group hover:border-[#521c4b]/30 transition-all cursor-pointer">
<div className="flex items-center gap-3">
<div className="p-2 bg-amber-50 text-amber-500 rounded-xl group-hover:scale-110 transition-transform">
<ShoppingBag size={20} />
</div>
<h4 className="text-[11px] font-black text-slate-400 uppercase tracking-widest leading-none">Total Orders</h4>
</div>
<div className="flex flex-col items-center">
<h2 className="text-5xl font-black text-slate-800 tracking-tighter">{stats.activeOrders}</h2>
<div className="w-full h-1 bg-green-500 rounded-full mt-4 shadow-sm" />
</div>
</div>
{/* Expenses Card */}
<div title="Track operational expenditures and overhead" className="bg-white p-6 rounded-[24px] border border-slate-100 shadow-sm h-[130px] flex flex-col justify-between group hover:border-[#521c4b]/30 transition-all cursor-pointer">
<div className="flex items-center gap-3">
<div className="p-2 bg-slate-50 text-[#521c4b] rounded-xl shadow-sm group-hover:bg-[#521c4b]/10 transition-colors">
<Wallet size={20} />
</div>
<h4 className="text-[11px] font-black text-slate-400 uppercase tracking-widest leading-none">Total Expenses</h4>
</div>
<div className="text-center pb-2">
<h2 className="text-3xl font-black text-slate-800 tracking-tighter">₹0</h2>
</div>
</div>
</div>
</div>
{/* Bottom Section */}
<div className="grid grid-cols-12 gap-8 mt-4 pb-12">
{/* Store Insights */}
<div className="col-span-12 lg:col-span-5 bg-white rounded-[32px] border border-slate-100 shadow-sm p-8 flex flex-col">
<h3 className="text-sm font-black text-slate-800 tracking-tight mb-8 uppercase tracking-widest">Business Intelligence</h3>
<div className="space-y-4 flex-1">
{insights.map((insight: string, idx: number) => (
<motion.div
initial={{ x: -20, opacity: 0 }}
animate={{ x: 0, opacity: 1 }}
transition={{ delay: idx * 0.1 }}
key={idx}
className="p-5 rounded-2xl border border-slate-100 bg-slate-50/50 hover:bg-white hover:shadow-md hover:border-transparent transition-all cursor-default"
>
<p className="text-[11px] font-black text-slate-600 leading-relaxed uppercase tracking-tight">{insight}</p>
</motion.div>
))}
</div>
<div className="mt-8">
<button title="Refresh and sync comprehensive business insights" className="w-full py-3 border border-dashed border-slate-200 rounded-2xl text-[10px] font-black text-slate-400 uppercase tracking-widest hover:border-[#521c4b]/30 hover:text-[#521c4b] transition-all">
Generate More Insights
</button>
</div>
</div>
{/* Store Overview */}
<div className="col-span-12 lg:col-span-7 bg-white rounded-[32px] border border-slate-100 shadow-sm p-8">
<div className="flex items-center justify-between mb-8">
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Store Performance</h3>
<button title="View detailed metrics for all geographic locations" className="text-[10px] font-black text-[#521c4b] uppercase tracking-widest hover:underline">View All Locations</button>
</div>
<div className="space-y-6">
{(storeOverview.length > 0 ? storeOverview : [{name: 'No active sales currently', sale: 0, orders: 0, taxes: 0, purchase: 0}]).map((store: any, idx: number) => (
<div key={idx} className="p-6 rounded-[28px] border border-slate-50 bg-slate-50/30 group hover:bg-white hover:shadow-lg hover:border-transparent transition-all border-l-4 border-l-[#521c4b]/30">
<p className="text-xs font-black text-slate-800 mb-6 uppercase tracking-widest flex items-center justify-between">
{store.name}
<ArrowRight size={14} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#521c4b]" />
</p>
<div className="grid grid-cols-4 gap-4">
<div className="space-y-1.5">
<p className="text-[9px] font-black text-rose-500 uppercase tracking-widest opacity-60">Gross Sale</p>
<p className="text-lg font-black text-slate-800 tracking-tighter">{Number(store.sale).toLocaleString()}</p>
</div>
<div className="space-y-1.5">
<p className="text-[9px] font-black text-blue-500 uppercase tracking-widest opacity-60">Volume</p>
<p className="text-lg font-black text-slate-800 tracking-tighter">{store.orders} Orders</p>
</div>
<div className="space-y-1.5">
<p className="text-[9px] font-black text-indigo-500 uppercase tracking-widest opacity-60">Taxation</p>
<p className="text-lg font-black text-slate-800 tracking-tighter">{store.taxes}</p>
</div>
<div className="space-y-1.5 text-right">
<p className="text-[9px] font-black text-amber-500 uppercase tracking-widest opacity-60">Procurement</p>
<p className="text-lg font-black text-slate-800 tracking-tighter">{store.purchase}</p>
</div>
</div>
</div>
))}
</div>
<div className="mt-10 flex justify-center">
<button title="Execute a granular comparison across different store cohorts" className="flex items-center gap-3 px-8 py-3 bg-[#521c4b] text-white text-[11px] font-black uppercase tracking-widest rounded-2xl shadow-xl shadow-[#521c4b]/20 hover:scale-105 transition-all group">
Detailed Comparison
<ArrowRight size={16} className="group-hover:translate-x-1 transition-transform" />
</button>
</div>
</div>
</div>
</div>
);
};
export default Dashboard;

View File

@@ -0,0 +1,225 @@
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
User,
Lock,
Eye,
EyeOff,
ArrowRight,
ShieldCheck,
UserCircle2
} from 'lucide-react';
import { useNavigate } from 'react-router-dom';
// Import Assets
import collegeLogo from '../assets/college-logo.png';
import buildingPhoto from '../assets/ritchennai.webp';
const Login = () => {
const [role, setRole] = useState<'manager' | 'master'>('manager');
const [showPassword, setShowPassword] = useState(false);
const [username, setUsername] = useState('admin');
const [password, setPassword] = useState('admin');
const navigate = useNavigate();
// Ensure any previous session is completely wiped out when arriving at the login screen
useEffect(() => {
sessionStorage.removeItem('isLoggedIn');
sessionStorage.removeItem('userRole');
sessionStorage.removeItem('userPermissions');
}, []);
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch('/api/system/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: username, password })
});
if (response.ok) {
const user = await response.json();
// Strict Role Validation
if (user.role.toLowerCase() !== role) {
alert(`Access Denied: You are trying to login as ${role.toUpperCase()}, but your credentials belong to a ${user.role.toUpperCase()} account.`);
return;
}
sessionStorage.setItem('isLoggedIn', 'true');
sessionStorage.setItem('userRole', user.role.toLowerCase());
sessionStorage.setItem('userPermissions', JSON.stringify(user.permissions || []));
navigate('/store-dashboard');
} else {
const error = await response.text();
alert(error || 'Invalid credentials');
}
} catch (err) {
console.error('Login error:', err);
alert('Network error - make sure backend is running');
}
};
return (
<div className="min-h-screen bg-[#f8fafc] flex flex-col md:flex-row overflow-hidden font-inter">
{/* Left Section: Login Form */}
<div className="w-full md:w-[45%] lg:w-[40%] flex flex-col p-8 md:p-12 lg:p-16 relative z-10 bg-white shadow-2xl">
{/* Top Logo */}
<motion.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
className="mb-16"
>
<img src={collegeLogo} alt="College Logo" className="h-16 md:h-20 object-contain" />
</motion.div>
{/* Login Container */}
<motion.div
initial={{ opacity: 0, x: -30 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.2 }}
className="flex-1 flex flex-col justify-center max-w-sm mx-auto w-full"
>
<div className="text-center mb-10">
<h2 className="text-[10px] font-black tracking-[0.3em] text-[#1e293b] uppercase mb-2">
Canteen Management System
</h2>
<div className="w-12 h-1 bg-[#231651] mx-auto rounded-full"></div>
</div>
{/* Role Toggle */}
<div className="bg-[#f1f5f9] p-1.5 rounded-2xl flex gap-1 mb-8 relative">
<motion.div
className="absolute h-[calc(100%-12px)] top-1.5 bg-white rounded-xl shadow-sm z-0"
initial={false}
animate={{
left: role === 'manager' ? '6px' : '50%',
width: 'calc(50% - 9px)'
}}
transition={{ type: "spring", stiffness: 300, damping: 30 }}
/>
<button
onClick={() => setRole('manager')}
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-xs font-bold transition-all relative z-10 ${role === 'manager' ? 'text-[#231651]' : 'text-[#94a3b8] hover:text-[#64748b]'
}`}
>
<UserCircle2 size={16} />
MANAGER
</button>
<button
onClick={() => setRole('master')}
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-xs font-bold transition-all relative z-10 ${role === 'master' ? 'text-[#231651]' : 'text-[#94a3b8] hover:text-[#64748b]'
}`}
>
<ShieldCheck size={16} />
MASTER
</button>
</div>
{/* Form */}
<form onSubmit={handleLogin} className="space-y-6">
<div className="space-y-2">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">
Secure User ID
</label>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8] group-focus-within:text-[#231651] transition-colors">
<User size={18} />
</div>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-4 pl-12 pr-4 text-sm font-semibold outline-none transition-all placeholder:text-[#cbd5e1]"
/>
</div>
</div>
<div className="space-y-2">
<div className="flex justify-between items-center pl-1">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">
Passcode
</label>
<button type="button" className="text-[10px] font-black text-[#231651] uppercase hover:underline">
Forgot Access?
</button>
</div>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8] group-focus-within:text-[#231651] transition-colors">
<Lock size={18} />
</div>
<input
type={showPassword ? 'text' : 'password'}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-4 pl-12 pr-12 text-sm font-semibold outline-none transition-all placeholder:text-[#cbd5e1]"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute inset-y-0 right-0 pr-4 flex items-center text-[#94a3b8] hover:text-[#64748b] transition-colors"
>
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
</button>
</div>
</div>
<button
type="submit"
className="w-full bg-[#231651] text-white rounded-2xl py-4 font-black text-sm flex items-center justify-center gap-3 shadow-xl shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all overflow-hidden group relative"
>
<span className="relative z-10">CONNECT TO PORTAL</span>
<ArrowRight size={18} className="relative z-10 group-hover:translate-x-1 transition-transform" />
<motion.div
className="absolute inset-0 bg-white/10"
initial={{ x: '-100%' }}
whileHover={{ x: '100%' }}
transition={{ duration: 0.6 }}
/>
</button>
</form>
</motion.div>
{/* Footer */}
<div className="mt-auto text-center">
<p className="text-[10px] font-black text-[#cbd5e1] uppercase tracking-[0.2em]">
© 2026 RITCHENNAI SYSTEM PORTAL
</p>
</div>
</div>
{/* Right Section: Visual */}
<div className="hidden md:flex flex-1 relative bg-[#f8fafc] items-center justify-center p-8 overflow-hidden">
{/* Decorative Circles */}
<div className="absolute top-20 right-20 w-64 h-64 bg-[#231651]/5 rounded-full blur-3xl"></div>
<div className="absolute bottom-20 left-40 w-96 h-96 bg-[#231651]/5 rounded-full blur-3xl"></div>
{/* Image Container with Custom Shape (using clip-path or rounded corners) */}
<motion.div
initial={{ opacity: 0, scale: 0.95, x: 50 }}
animate={{ opacity: 1, scale: 1, x: 0 }}
transition={{ duration: 0.8 }}
className="w-full h-full relative z-10"
>
<div className="w-full h-full overflow-hidden shadow-2xl border-[12px] border-white bg-white">
<img
src={buildingPhoto}
alt="RIT Chennai Building"
className="w-full h-full object-cover"
/>
{/* Overlay Gradient */}
<div className="absolute inset-0 bg-gradient-to-tr from-[#231651]/20 to-transparent"></div>
</div>
</motion.div>
</div>
</div>
);
};
export default Login;

View File

@@ -0,0 +1,377 @@
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
UserPlus,
Search,
Trash2,
Shield,
Mail,
Lock,
Check,
X,
LayoutGrid,
Receipt,
Users,
ShoppingBag,
ShoppingCart,
Wallet,
BarChart3,
Table2,
CreditCard,
Megaphone,
MessageSquare,
Store
} from 'lucide-react';
interface Manager {
id: string;
name: string;
email: string;
role: string;
sections: string[];
status: 'active' | 'inactive';
}
const ALL_SECTIONS = [
{ id: 'dashboard', label: 'Dashboard', icon: LayoutGrid },
{ id: 'sale', label: 'Sale', icon: Receipt },
{ id: 'customers', label: 'Customers', icon: Users },
{ id: 'purchases', label: 'Purchases', icon: ShoppingBag },
{ id: 'inventory', label: 'Inventory', icon: ShoppingCart },
{ id: 'expense', label: 'Expense', icon: Wallet },
{ id: 'reports', label: 'Reports', icon: BarChart3 },
{ id: 'table', label: 'Table Management', icon: Table2 },
{ id: 'wallet', label: 'Wallet', icon: CreditCard },
{ id: 'promotions', label: 'Promotions', icon: Megaphone },
{ id: 'feedback', label: 'Feedback', icon: MessageSquare },
{ id: 'stores', label: 'Stores', icon: Store }
];
const Managers = () => {
const [managers, setManagers] = useState<Manager[]>([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [loading, setLoading] = useState(true);
// Form State
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
viewOnly: false,
selectedSections: [] as string[]
});
// Fetch from Backend
const fetchManagers = async () => {
setLoading(true);
try {
const res = await fetch('/api/system/managers');
if (res.ok) {
const data = await res.json();
// Backend uses 'permissions' field, map it to 'sections' for the component if needed
const mappedData = data.map((m: any) => ({
...m,
sections: m.permissions || []
}));
setManagers(mappedData);
}
} catch (err) {
console.error('Error fetching managers:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchManagers();
}, []);
const toggleSection = (sectionId: string) => {
setFormData(prev => ({
...prev,
selectedSections: prev.selectedSections.includes(sectionId)
? prev.selectedSections.filter(id => id !== sectionId)
: [...prev.selectedSections, sectionId]
}));
};
const handleCreateAccount = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch('/api/system/managers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: formData.name,
email: formData.email,
password: formData.password,
viewOnly: formData.viewOnly,
permissions: formData.selectedSections
})
});
if (response.ok) {
fetchManagers();
setIsModalOpen(false);
setFormData({ name: '', email: '', password: '', viewOnly: false, selectedSections: [] });
} else {
alert('Failed to create manager');
}
} catch (err) {
console.error('Create manager error:', err);
alert('Network error - make sure backend is running');
}
};
const dismissManager = async (id: string) => {
if (window.confirm('Are you sure you want to dismiss this manager?')) {
try {
const response = await fetch(`/api/system/managers/${id}`, {
method: 'DELETE'
});
if (response.ok) {
fetchManagers();
}
} catch (err) {
console.error('Delete error:', err);
}
}
};
return (
<div className="p-8 space-y-8 bg-[#f8fafc] min-h-screen font-inter">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-black text-[#231651]">Managers</h1>
<p className="text-[#64748b] text-sm mt-1">Manage portal access and role assignments</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center gap-2 bg-[#231651] text-white px-6 py-3 rounded-2xl font-bold shadow-xl shadow-[#231651]/20 hover:scale-105 transition-all"
>
<UserPlus size={20} />
<span>Add New Member</span>
</button>
</div>
{/* Search & Stats */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="md:col-span-2 relative group flex items-center">
<div className="absolute left-5 flex items-center justify-center pointer-events-none">
<Search className="text-[#94a3b8] group-focus-within:text-[#231651] transition-colors" size={20} />
</div>
<input
type="text"
placeholder="Search by name or email..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full h-14 bg-white border border-[#e2e8f0] rounded-2xl pl-14 pr-4 text-sm font-semibold outline-none transition-all focus:border-[#231651]/30 focus:shadow-md shadow-sm text-[#1e293b] placeholder:text-[#94a3b8]"
/>
</div>
<div className="bg-white p-4 rounded-2xl border border-[#e2e8f0] shadow-sm flex items-center justify-between">
<div>
<p className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Active Managers</p>
<h3 className="text-2xl font-black text-[#231651]">{managers.length}</h3>
</div>
<div className="p-3 bg-emerald-50 text-emerald-600 rounded-xl">
<Shield size={24} />
</div>
</div>
</div>
{/* Managers List */}
<div className="bg-white rounded-3xl border border-[#e2e8f0] shadow-sm overflow-hidden">
<table className="w-full text-left">
<thead className="bg-gray-50 border-b border-[#e2e8f0]">
<tr>
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Manager</th>
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Role</th>
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Permissions</th>
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Status</th>
<th className="px-6 py-4"></th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{managers.filter(m => m.name.toLowerCase().includes(searchQuery.toLowerCase()) || m.email.toLowerCase().includes(searchQuery.toLowerCase())).map((manager) => (
<tr key={manager.id} className="hover:bg-gray-50/50 transition-colors">
<td className="px-6 py-5">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-[#231651] text-white flex items-center justify-center font-bold">
{manager.name.charAt(0)}
</div>
<div>
<p className="text-sm font-black text-[#1e293b]">{manager.name}</p>
<p className="text-xs font-medium text-[#94a3b8]">{manager.email}</p>
</div>
</div>
</td>
<td className="px-6 py-5">
<span className="px-3 py-1 rounded-full bg-blue-50 text-blue-600 text-[10px] font-black uppercase tracking-wider">
{manager.role}
</span>
</td>
<td className="px-6 py-5">
<div className="flex flex-wrap gap-1 max-w-[200px]">
{manager.sections.map(s => (
<span key={s} className="px-2 py-0.5 rounded-md bg-gray-100 text-[#64748b] text-[9px] font-bold uppercase">
{s}
</span>
))}
</div>
</td>
<td className="px-6 py-5">
<div className="flex items-center gap-1.5">
<div className="w-2 h-2 rounded-full bg-emerald-500"></div>
<span className="text-[10px] font-black text-emerald-600 uppercase">Active</span>
</div>
</td>
<td className="px-6 py-5 text-right">
<button
onClick={() => dismissManager(manager.id)}
className="p-2 text-[#94a3b8] hover:text-red-600 hover:bg-red-50 rounded-xl transition-all"
>
<Trash2 size={18} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Create Account Modal */}
<AnimatePresence>
{isModalOpen && (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setIsModalOpen(false)}
className="absolute inset-0 bg-[#1e293b]/60 backdrop-blur-sm"
/>
<motion.div
initial={{ opacity: 0, scale: 0.9, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
className="relative bg-white w-full max-w-2xl rounded-[2.5rem] shadow-2xl overflow-hidden"
>
<div className="p-8 md:p-10">
<div className="flex justify-between items-start mb-8">
<div>
<h2 className="text-2xl font-black text-[#1e293b]">Create manager account for <span className="text-[#231651]">RIT Canteen</span></h2>
</div>
<button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-gray-100 rounded-full transition-colors text-[#94a3b8]">
<X size={24} />
</button>
</div>
<form onSubmit={handleCreateAccount} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Name / Terminal Name</label>
<div className="relative group">
<input
required
type="text"
value={formData.name}
onChange={(e) => setFormData({...formData, name: e.target.value})}
placeholder="e.g. Main Desk"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-4 pr-4 text-sm font-semibold outline-none transition-all"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Email Address</label>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8]">
<Mail size={16} />
</div>
<input
required
type="email"
value={formData.email}
onChange={(e) => setFormData({...formData, email: e.target.value})}
placeholder="manager@rit.edu"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-11 pr-4 text-sm font-semibold outline-none transition-all"
/>
</div>
</div>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Password (Optional)</label>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8]">
<Lock size={16} />
</div>
<input
type="password"
value={formData.password}
onChange={(e) => setFormData({...formData, password: e.target.value})}
placeholder="••••••••"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-11 pr-4 text-sm font-semibold outline-none transition-all"
/>
</div>
</div>
<div className="flex items-center gap-3 py-2">
<div
onClick={() => setFormData({...formData, viewOnly: !formData.viewOnly})}
className={cn(
"w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-all",
formData.viewOnly ? "bg-[#231651] border-[#231651]" : "border-[#e2e8f0]"
)}
>
{formData.viewOnly && <Check size={14} className="text-white" />}
</div>
<span className="text-sm font-bold text-[#64748b]">View only access</span>
</div>
{/* Sections Selection */}
<div className="space-y-4">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Accessible Sections</label>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
{ALL_SECTIONS.map((section) => (
<div
key={section.id}
onClick={() => toggleSection(section.id)}
className={cn(
"flex flex-col items-center justify-center p-4 rounded-2xl border-2 cursor-pointer transition-all gap-2",
formData.selectedSections.includes(section.id)
? "bg-[#231651]/5 border-[#231651] text-[#231651]"
: "bg-white border-[#e2e8f0] text-[#94a3b8] hover:border-[#231651]/30"
)}
>
<section.icon size={20} />
<span className="text-[9px] font-black uppercase text-center">{section.label}</span>
</div>
))}
</div>
</div>
<div className="pt-4">
<button
type="submit"
className="w-full bg-[#231651] text-white rounded-2xl py-4 font-black text-sm shadow-xl shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all"
>
Create Account
</button>
</div>
</form>
</div>
</motion.div>
</div>
)}
</AnimatePresence>
</div>
);
};
// Helper for class names
function cn(...inputs: any[]) {
return inputs.filter(Boolean).join(' ');
}
export default Managers;

View File

@@ -0,0 +1,819 @@
import React, { useState, useEffect, useMemo } from 'react';
import {
Search,
Calendar,
Filter,
CreditCard,
User,
ShoppingBag,
MoreVertical,
MessageCircle,
RefreshCw,
Trash2,
Plus,
Minus,
Check,
X as XIcon,
RotateCcw,
Edit2
} from 'lucide-react';
import { format } from 'date-fns';
import Pagination from '../components/Pagination';
interface OrderItem {
id?: number;
productName: string;
quantity: number;
price: number;
productId: number;
}
interface Product {
id: number;
name: string;
price: number;
category: string;
}
interface UserData {
name: string;
mobileNumber: string;
}
interface Order {
id: number;
orderNumber: string;
displayOrderId: string;
totalAmount: number;
status: string;
paymentMethod: string;
createdAt: string;
user: UserData;
items: OrderItem[];
}
const Orders: React.FC = () => {
const [orders, setOrders] = useState<Order[]>([]);
const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [statusFilter, setStatusFilter] = useState('');
const [paymentFilter, setPaymentFilter] = useState('');
const [startDate, setStartDate] = useState(format(new Date(), 'yyyy-MM-dd'));
const [endDate, setEndDate] = useState(format(new Date(), 'yyyy-MM-dd'));
// Pagination States
const [currentPage, setCurrentPage] = useState(0);
const [pageSize, setPageSize] = useState(10);
const [totalElements, setTotalElements] = useState(0);
// Action Menu & Edit Modal States
const [showActionMenu, setShowActionMenu] = useState(false);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [allProducts, setAllProducts] = useState<Product[]>([]);
const [editSearchQuery, setEditSearchQuery] = useState('');
const [editingItems, setEditingItems] = useState<OrderItem[]>([]);
const [isUpdatingOrder, setIsUpdatingOrder] = useState(false);
useEffect(() => {
fetchOrders();
fetchProducts();
}, [startDate, endDate, statusFilter, paymentFilter, currentPage, pageSize]);
const fetchProducts = async () => {
try {
const response = await fetch(`http://${window.location.hostname}:8080/api/products`);
if (response.ok) {
const data = await response.json();
setAllProducts(data);
}
} catch (error) {
console.error('Error fetching products:', error);
}
};
const fetchOrders = async () => {
setLoading(true);
try {
// Build query params
const params = new URLSearchParams();
params.append('archived', 'false'); // Only show live orders
if (startDate) params.append('startDate', `${startDate}T00:00:00`);
if (endDate) params.append('endDate', `${endDate}T23:59:59`);
if (statusFilter) params.append('status', statusFilter);
if (paymentFilter) params.append('paymentType', paymentFilter);
if (searchQuery) params.append('search', searchQuery);
params.append('page', currentPage.toString());
params.append('size', pageSize.toString());
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/all?${params.toString()}`);
const data = await response.json();
if (data && data.content && Array.isArray(data.content)) {
setOrders(data.content);
setTotalElements(data.totalElements);
// If we have a selected order, try to refresh it from the data list
if (selectedOrder) {
const updated = data.content.find((o: Order) => o.id === selectedOrder.id);
if (updated) setSelectedOrder(updated);
} else if (data.content.length > 0) {
setSelectedOrder(data.content[0]);
}
} else {
console.error('API did not return a valid Page object:', data);
setOrders([]);
setTotalElements(0);
}
} catch (error) {
console.error('Error fetching orders:', error);
setOrders([]);
} finally {
setLoading(false);
}
};
const handleApproveOrder = async (orderId: number) => {
try {
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/${orderId}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'COMPLETED' })
});
if (response.ok) {
fetchOrders();
} else {
alert('Failed to update order status');
}
} catch (error) {
console.error('Error updating order:', error);
}
};
const handleMarkUndelivered = async (orderId: number) => {
try {
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/${orderId}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 'PAID' })
});
if (response.ok) {
setShowActionMenu(false);
fetchOrders();
}
} catch (error) {
console.error('Error marking undelivered:', error);
}
};
const handleEditOrder = () => {
if (!selectedOrder) return;
setEditingItems([...selectedOrder.items]);
setIsEditModalOpen(true);
setShowActionMenu(false);
};
const updateItemQuantity = (index: number, delta: number) => {
const newItems = [...editingItems];
newItems[index].quantity = Math.max(1, newItems[index].quantity + delta);
setEditingItems(newItems);
};
const removeItem = (index: number) => {
setEditingItems(editingItems.filter((_, i) => i !== index));
};
const addProductToOrder = (product: Product) => {
// Check if product already in list
const existing = editingItems.findIndex(item => item.productId === product.id);
if (existing !== -1) {
updateItemQuantity(existing, 1);
} else {
setEditingItems([...editingItems, {
productId: product.id,
productName: product.name,
price: product.price,
quantity: 1
}]);
}
setEditSearchQuery('');
};
const editTotal = useMemo(() => {
return editingItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}, [editingItems]);
const saveOrderEdits = async () => {
if (!selectedOrder) return;
setIsUpdatingOrder(true);
try {
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/${selectedOrder.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...selectedOrder,
items: editingItems,
totalAmount: editTotal
})
});
if (response.ok) {
setIsEditModalOpen(false);
fetchOrders();
} else {
alert('Failed to update order details');
}
} catch (error) {
console.error('Error saving edits:', error);
} finally {
setIsUpdatingOrder(false);
}
};
const filteredProducts = useMemo(() => {
if (!editSearchQuery.trim()) return [];
return allProducts.filter(p =>
p.name.toLowerCase().includes(editSearchQuery.toLowerCase()) ||
p.category.toLowerCase().includes(editSearchQuery.toLowerCase())
).slice(0, 5); // Limit results
}, [allProducts, editSearchQuery]);
const handleSearchSubmit = (e: React.FormEvent) => {
e.preventDefault();
fetchOrders();
};
const getStatusColor = (status: string) => {
switch (status.toUpperCase()) {
case 'COMPLETED': return 'bg-emerald-50 text-emerald-600 border-emerald-100';
case 'PAID': return 'bg-indigo-50 text-indigo-600 border-indigo-100';
case 'PENDING': return 'bg-amber-50 text-amber-600 border-amber-100';
case 'CANCELLED': return 'bg-rose-50 text-rose-600 border-rose-100';
default: return 'bg-slate-50 text-slate-600 border-slate-100';
}
};
return (
<div className="flex flex-col h-[calc(100vh-64px)] bg-[#f8fafc]">
{/* Top Filter Bar */}
<div className="bg-white border-b border-slate-200 p-4 sticky top-0 z-10 shadow-sm">
<form onSubmit={handleSearchSubmit} className="flex flex-wrap items-center gap-4 max-w-[1600px] mx-auto">
{/* Date Picker */}
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 focus-within:border-indigo-400 focus-within:ring-1 focus-within:ring-indigo-400 transition-all">
<Calendar size={18} className="text-slate-400" />
<input
type="date"
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
/>
<span className="text-slate-300">|</span>
<input
type="date"
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
/>
</div>
{/* Status Select */}
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 min-w-[140px]">
<Filter size={18} className="text-slate-400" />
<select
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none w-full cursor-pointer"
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
>
<option value="">All Status</option>
<option value="PAID">Paid</option>
<option value="COMPLETED">Completed</option>
<option value="PENDING">Pending</option>
<option value="CANCELLED">Cancelled</option>
</select>
</div>
{/* Payment Type */}
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 min-w-[140px]">
<CreditCard size={18} className="text-slate-400" />
<select
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none w-full cursor-pointer"
value={paymentFilter}
onChange={(e) => setPaymentFilter(e.target.value)}
>
<option value="">Payment Type</option>
<option value="UPI">UPI Payment</option>
<option value="CREDIT">Credit</option>
<option value="CASH">Cash</option>
</select>
</div>
{/* Search Box */}
<div className="flex-1 flex items-center bg-slate-50 border border-slate-200 rounded-lg px-4 py-2 gap-3 focus-within:bg-white focus-within:border-indigo-400 focus-within:ring-1 focus-within:ring-indigo-400 transition-all shadow-inner">
<Search size={18} className="text-slate-400" />
<input
type="text"
placeholder="Search Order ID, Customer Name, Mobile..."
className="bg-transparent border-none text-sm w-full outline-none text-slate-700 placeholder:text-slate-400"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<button
type="submit"
title="Filter orders by date and criteria"
className="bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg px-6 py-2 text-sm font-semibold transition-all shadow-md shadow-indigo-100 flex items-center gap-2 active:scale-95"
>
Apply Filters
</button>
<button
type="button"
onClick={() => {
setSearchQuery('');
setStatusFilter('');
setPaymentFilter('');
setStartDate(format(new Date(), 'yyyy-MM-dd'));
setEndDate(format(new Date(), 'yyyy-MM-dd'));
}}
className="text-slate-500 hover:bg-slate-100 p-2 rounded-lg transition-colors border border-transparent hover:border-slate-200"
title="Clear Filters"
>
<RefreshCw size={18} />
</button>
</form>
</div>
{/* Main Content Area */}
<div className="flex-1 overflow-hidden flex max-w-[1800px] mx-auto w-full p-4 gap-4">
{/* Left Column: Orders List */}
<div className="w-[400px] flex flex-col gap-3 overflow-y-auto pr-2 custom-scrollbar pb-4">
{loading ? (
<div className="flex items-center justify-center p-12 text-slate-400 gap-2">
<RefreshCw className="animate-spin" size={20} />
<span>Loading orders...</span>
</div>
) : orders.length === 0 ? (
<div className="bg-white rounded-xl border border-slate-200 p-12 text-center shadow-sm">
<ShoppingBag size={48} className="mx-auto text-slate-200 mb-4" />
<h3 className="text-slate-600 font-semibold mb-1">No orders found</h3>
<p className="text-slate-400 text-sm">Try adjusting your filters</p>
</div>
) : (
orders.map((order) => (
<div
key={order.id}
onClick={() => setSelectedOrder(order)}
className={`group relative bg-white border rounded-xl p-4 cursor-pointer transition-all hover:shadow-lg active:scale-[0.98] ${
selectedOrder?.id === order.id
? 'border-indigo-600 ring-1 ring-indigo-600 shadow-md'
: 'border-slate-200 hover:border-indigo-300'
}`}
>
<div className="flex justify-between items-start mb-3">
<div className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold tracking-wider uppercase border ${getStatusColor(order.status)}`}>
{order.status}
</div>
<div className="text-right">
<div className="text-[10px] text-slate-400 font-medium uppercase mb-0.5">Grand Total</div>
<div className="text-lg font-black text-slate-900 leading-none">{order.totalAmount.toFixed(2)}</div>
</div>
</div>
<div className="flex items-end justify-between">
<div>
<div className="text-xs text-slate-400 font-medium mb-1">Order #</div>
<div className="text-2xl font-black text-slate-800 leading-none tracking-tight">#{order.displayOrderId}</div>
<div className="mt-4 flex items-center gap-2 text-xs font-semibold px-2 py-1 bg-slate-100 text-slate-600 rounded-md w-fit uppercase">
<CreditCard size={12} />
{order.paymentMethod}
</div>
</div>
<div className="text-right">
<div className="text-xs font-bold text-slate-700 mb-1 truncate max-w-[150px]">
{order.user?.name || 'Anonymous User'}
</div>
<div className="text-[10px] text-slate-400 font-medium">
{format(new Date(order.createdAt), 'dd/MM/yy HH:mm')}
</div>
<div className="mt-3 text-[10px] inline-flex items-center gap-1 font-bold px-2 py-0.5 bg-[#231651] text-white rounded shadow-sm uppercase">
<User size={10} />
{order.user?.name ? 'REGISTERED' : 'WALK-IN'}
</div>
</div>
</div>
{selectedOrder?.id === order.id && (
<div className="absolute left-0 top-0 bottom-0 w-1 bg-indigo-600 rounded-l-xl" />
)}
</div>
))
)}
<Pagination
currentPage={currentPage}
pageSize={pageSize}
totalElements={totalElements}
onPageChange={setCurrentPage}
onPageSizeChange={(newSize) => {
setPageSize(newSize);
setCurrentPage(0); // Reset to first page on size change
}}
/>
</div>
{/* Right Column: Order Details */}
<div className="flex-1 bg-white border border-slate-200 rounded-2xl flex flex-col shadow-sm overflow-hidden relative mb-4">
{selectedOrder ? (
<>
{/* Order Detail Header */}
<div className="p-6 border-b border-slate-100 flex justify-between items-center bg-white sticky top-0 z-10">
<div className="flex items-center gap-4">
<div className="bg-indigo-50 p-3 rounded-xl text-indigo-600">
<ShoppingBag size={24} />
</div>
<div>
<h2 className="text-2xl font-black text-slate-900 flex items-center gap-2 tracking-tight">
Order #{selectedOrder.displayOrderId}
</h2>
<p className="text-xs text-slate-400 font-medium tracking-wide">ID: {selectedOrder.orderNumber}</p>
</div>
</div>
<div className="flex items-center gap-3">
<button className="text-emerald-500 hover:bg-emerald-50 p-2 rounded-lg transition-colors border border-transparent hover:border-emerald-100">
<MessageCircle size={20} />
</button>
<div className="relative action-menu-container">
<button
onClick={() => setShowActionMenu(!showActionMenu)}
title="More actions"
className={`p-2 rounded-lg transition-all ${showActionMenu ? 'bg-slate-100 text-indigo-600' : 'text-slate-400 hover:bg-slate-50'}`}
>
<MoreVertical size={20} />
</button>
{showActionMenu && (
<div className="absolute right-0 mt-2 w-56 bg-white border border-slate-200 rounded-xl shadow-2xl z-20 overflow-hidden py-1 animate-in fade-in zoom-in duration-200">
<div className="px-4 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest border-b border-slate-50">Manual Actions</div>
<button
onClick={() => handleMarkUndelivered(selectedOrder.id)}
className="w-full text-left px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 flex items-center gap-3 transition-colors"
>
<RotateCcw size={16} className="text-amber-500" /> Mark Undelivered
</button>
<button
onClick={handleEditOrder}
title="Modify items in this order"
className="w-full text-left px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 flex items-center gap-3 transition-colors"
>
<Edit2 size={16} className="text-indigo-500" /> Edit Order Items
</button>
</div>
)}
</div>
<div className={`ml-2 px-4 py-1.5 rounded-lg text-xs font-bold uppercase border shadow-sm ${getStatusColor(selectedOrder.status)}`}>
{selectedOrder.status}
</div>
</div>
</div>
{/* Tabs Container */}
<div className="px-6 bg-white border-b border-slate-50 flex gap-8">
{['Orders', 'Payment Information', 'Customer Details'].map((tab, idx) => (
<button
key={tab}
className={`py-4 text-xs font-bold uppercase tracking-widest relative transition-colors ${
idx === 0 ? 'text-indigo-600' : 'text-slate-400 hover:text-slate-600'
}`}
>
{tab}
{idx === 0 && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600" />}
</button>
))}
</div>
{/* Content Scroll Area */}
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
<div className="grid grid-cols-3 gap-12 mb-12">
<div className="space-y-1.5">
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest">Date & Time</div>
<div className="text-sm font-bold text-slate-700 bg-slate-50 p-3 rounded-lg border border-slate-100">
{format(new Date(selectedOrder.createdAt), 'yyyy-MM-dd HH:mm:ss')}
</div>
</div>
<div className="space-y-1.5">
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest">Payment Type</div>
<div className="text-sm font-bold text-indigo-900 bg-indigo-50 p-3 rounded-lg border border-indigo-100 flex items-center gap-2">
<CreditCard size={14} />
{selectedOrder.paymentMethod.toUpperCase()}
</div>
</div>
<div className="space-y-1.5">
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest">Payment ID</div>
<div className="text-sm font-mono font-medium text-slate-600 bg-slate-50 p-3 rounded-lg border border-slate-100 flex items-center justify-between group">
<span className="truncate">Pay_{selectedOrder.orderNumber.split('-')[1] || '000'}...</span>
<button className="opacity-0 group-hover:opacity-100 transition-opacity"><RefreshCw size={12} /></button>
</div>
</div>
</div>
<div className="space-y-4">
<div className="flex justify-between items-center border-b border-slate-100 pb-3">
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Items</h3>
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Price</h3>
</div>
<div className="divide-y divide-slate-50">
{selectedOrder.items.map((item, idx) => (
<div key={idx} className="py-5 flex justify-between items-center group hover:bg-slate-50/50 transition-colors rounded-lg -mx-2 px-2">
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center text-slate-400 font-bold text-xs uppercase">
{item.productName.substring(0, 2)}
</div>
<div>
<div className="font-black text-slate-800 text-sm">{item.productName}</div>
<div className="text-xs text-slate-400 font-medium">Standard Portion</div>
</div>
</div>
<div className="flex items-center gap-8">
<div className="text-right">
<div className="text-sm font-black text-slate-900">{(item.price * item.quantity).toLocaleString()}</div>
<div className="text-[10px] font-bold text-slate-400">
{item.quantity} x <span className="text-indigo-400 font-black">{item.price}</span>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
{/* Bottom Summary Panel */}
<div className="bg-slate-50 p-8 border-t border-slate-100 shadow-[0_-4px_20px_rgba(0,0,0,0.02)]">
<div className="flex justify-between mb-8">
<div className="flex gap-12">
<div>
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1.5">Total Items</div>
<div className="text-xl font-black text-slate-800">{selectedOrder.items.length}</div>
</div>
<div>
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1.5">Total Quantity</div>
<div className="text-xl font-black text-slate-800">
{selectedOrder.items.reduce((sum, item) => sum + item.quantity, 0)}
</div>
</div>
</div>
<div className="text-right flex flex-col gap-2 min-w-[200px]">
<div className="flex justify-between items-center text-xs text-slate-500 font-bold">
<span>Order Summary</span>
<span className="font-black">{selectedOrder.totalAmount.toLocaleString()}</span>
</div>
<div className="flex justify-between items-center text-base text-slate-900 font-black pt-2 border-t border-slate-200">
<span>Total Sum</span>
<span className="text-2xl text-emerald-600">{selectedOrder.totalAmount.toLocaleString()}</span>
</div>
<div className={`flex justify-between items-center text-sm font-black pt-1 ${selectedOrder.status.toUpperCase() === 'COMPLETED' ? 'text-slate-400' : 'text-rose-600'}`}>
<span>Balance Due</span>
<span>{selectedOrder.status.toUpperCase() === 'COMPLETED' ? '0.00' : selectedOrder.totalAmount.toLocaleString()}</span>
</div>
</div>
</div>
<div className="flex gap-3">
<button
onClick={() => window.print()}
className="flex-1 bg-white border border-slate-200 text-slate-700 py-3 rounded-xl font-black text-xs uppercase tracking-widest hover:bg-slate-50 transition-all active:scale-[0.98]"
>
Print Receipt
</button>
<button
onClick={() => handleApproveOrder(selectedOrder.id)}
disabled={selectedOrder.status.toUpperCase() === 'COMPLETED'}
className={`flex-1 py-3 rounded-xl font-black text-xs uppercase tracking-widest transition-all shadow-md active:scale-[0.98] ${
selectedOrder.status.toUpperCase() === 'COMPLETED'
? 'bg-emerald-500 text-white cursor-not-allowed opacity-80'
: 'bg-indigo-600 text-white hover:bg-indigo-700 shadow-indigo-100'
}`}
>
{selectedOrder.status.toUpperCase() === 'COMPLETED' ? 'Order Completed' : 'Approve Order'}
</button>
</div>
</div>
</>
) : (
<div className="flex-1 flex flex-col items-center justify-center p-12 text-center text-slate-400">
<div className="bg-slate-50 p-6 rounded-full mb-6">
<ShoppingBag size={48} className="text-slate-200" />
</div>
<h3 className="text-slate-600 font-bold text-lg mb-2">Select an order to view details</h3>
<p className="max-w-xs mx-auto text-sm">Pick an order from the list on the left to see full transaction history, items, and customer info.</p>
</div>
)}
</div>
</div>
{/* Edit Order Modal */}
{isEditModalOpen && (
<div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[100] flex items-center justify-center p-4 animate-in fade-in duration-300">
<div className="bg-white rounded-3xl w-full max-w-4xl max-h-[90vh] flex flex-col shadow-2xl overflow-hidden border border-slate-200">
{/* Modal Header */}
<div className="px-8 py-6 border-b border-slate-100 flex justify-between items-center bg-white sticky top-0 z-10">
<div className="flex items-center gap-4">
<div className="bg-indigo-600 p-2.5 rounded-xl text-white">
<ShoppingBag size={24} />
</div>
<div>
<h2 className="text-xl font-black text-slate-900 tracking-tight">Edit Order Items</h2>
<p className="text-xs text-slate-400 font-bold uppercase tracking-wider">Order #{selectedOrder?.displayOrderId}</p>
</div>
</div>
<button
onClick={() => setIsEditModalOpen(false)}
className="text-slate-400 hover:bg-slate-100 p-2 rounded-xl transition-all hover:rotate-90"
>
<XIcon size={24} />
</button>
</div>
<div className="flex-1 overflow-hidden flex">
{/* Left Column: Line Items */}
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar border-r border-slate-50">
<div className="flex justify-between items-center mb-6">
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Current Items</h3>
<span className="text-[10px] font-black bg-indigo-50 text-indigo-600 px-2.5 py-1 rounded-full uppercase tracking-widest">{editingItems.length} Total</span>
</div>
<div className="space-y-3">
{editingItems.length === 0 ? (
<div className="text-center py-12 bg-slate-50 rounded-2xl border-2 border-dashed border-slate-200">
<ShoppingBag className="mx-auto text-slate-300 mb-2" size={32} />
<p className="text-sm font-bold text-slate-400">No items in this order</p>
</div>
) : (
editingItems.map((item, idx) => (
<div key={idx} className="flex items-center justify-between p-4 bg-white border border-slate-100 rounded-2xl group hover:border-indigo-200 hover:shadow-md transition-all">
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-slate-50 rounded-lg flex items-center justify-center font-black text-slate-400 text-xs uppercase border border-slate-100 group-hover:bg-indigo-600 group-hover:text-white group-hover:border-indigo-600 transition-colors">
{item.productName.substring(0, 2)}
</div>
<div>
<div className="font-bold text-slate-800 text-sm">{item.productName}</div>
<div className="text-[10px] font-black text-indigo-400 uppercase">{item.price} each</div>
</div>
</div>
<div className="flex items-center gap-6">
<div className="flex items-center bg-slate-50 rounded-xl p-1 border border-slate-100">
<button
onClick={() => updateItemQuantity(idx, -1)}
className="p-1.5 hover:bg-white hover:text-rose-500 rounded-lg transition-all active:scale-90"
>
<Minus size={14} />
</button>
<span className="w-10 text-center text-sm font-black text-slate-700">{item.quantity}</span>
<button
onClick={() => updateItemQuantity(idx, 1)}
className="p-1.5 hover:bg-white hover:text-emerald-500 rounded-lg transition-all active:scale-90"
>
<Plus size={14} />
</button>
</div>
<div className="text-right min-w-[80px]">
<div className="text-sm font-black text-slate-900 leading-none mb-1">{(item.price * item.quantity).toFixed(2)}</div>
<button
onClick={() => removeItem(idx)}
className="text-[10px] font-black text-rose-400 hover:text-rose-600 uppercase tracking-widest transition-colors flex items-center gap-1 active:scale-95"
>
<Trash2 size={10} /> Delete
</button>
</div>
</div>
</div>
))
)}
</div>
</div>
{/* Right Column: Search Items to Add */}
<div className="w-[350px] bg-slate-50/50 p-8 flex flex-col">
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-4">Add Items</h3>
<div className="relative mb-6">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400">
<Plus size={16} />
</div>
<input
type="text"
placeholder="Search food items..."
className="w-full bg-white border border-slate-200 rounded-xl py-2.5 pl-10 pr-4 text-sm font-medium outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all shadow-sm"
value={editSearchQuery}
onChange={(e) => setEditSearchQuery(e.target.value)}
/>
</div>
<div className="flex-1 space-y-2 overflow-y-auto custom-scrollbar">
{filteredProducts.length > 0 ? (
filteredProducts.map(product => (
<button
key={product.id}
onClick={() => addProductToOrder(product)}
className="w-full text-left p-3 bg-white border border-slate-100 rounded-xl hover:border-indigo-400 hover:shadow-md transition-all group flex justify-between items-center animate-in slide-in-from-right-4 duration-300"
>
<div>
<div className="font-bold text-slate-800 text-sm group-hover:text-indigo-600 transition-colors">{product.name}</div>
<div className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{product.category}</div>
</div>
<div className="font-black text-emerald-600 text-xs">{product.price}</div>
</button>
))
) : editSearchQuery ? (
<div className="text-center py-6 text-slate-400 italic text-sm">No items matching your search</div>
) : (
<div className="text-center py-6 flex flex-col items-center gap-2">
<div className="bg-white p-3 rounded-2xl shadow-sm text-slate-200">
<Search size={24} />
</div>
<p className="text-xs font-bold text-slate-400 max-w-[150px] mx-auto">Start typing to add delicious items to the order</p>
</div>
)}
</div>
<div className="mt-8 pt-8 border-t border-slate-200">
<div className="flex justify-between items-center mb-4">
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">New Order Total</span>
<span className="text-2xl font-black text-emerald-600 tracking-tighter">{editTotal.toFixed(2)}</span>
</div>
<button
onClick={saveOrderEdits}
disabled={isUpdatingOrder || editingItems.length === 0}
className={`w-full py-4 rounded-2xl text-xs font-black uppercase tracking-[0.2em] shadow-xl transition-all active:scale-[0.98] flex items-center justify-center gap-2 ${
isUpdatingOrder || editingItems.length === 0
? 'bg-slate-200 text-slate-400 cursor-not-allowed'
: 'bg-[#231651] text-white hover:bg-[#2d1b66] shadow-indigo-100'
}`}
>
{isUpdatingOrder ? <RefreshCw className="animate-spin" size={14} /> : <Check size={14} />}
{isUpdatingOrder ? 'Updating...' : 'Update Order'}
</button>
</div>
</div>
</div>
</div>
</div>
)}
<style>{`
.custom-scrollbar::-webkit-scrollbar {
width: 5px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 10px;
}
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
background: #cbd5e1;
}
.action-menu-container .animate-in {
transform-origin: top right;
}
@media print {
/* Hide everything except the order detail container */
body * {
visibility: hidden;
}
.flex-1.bg-white.border.border-slate-200.rounded-2xl,
.flex-1.bg-white.border.border-slate-200.rounded-2xl * {
visibility: visible;
}
.flex-1.bg-white.border.border-slate-200.rounded-2xl {
position: absolute;
left: 0;
top: 0;
width: 100%;
border: none !important;
box-shadow: none !important;
}
/* Hide buttons and tabs in print */
button,
.px-6.bg-white.border-b.border-slate-50.flex.gap-8,
.action-menu-container {
display: none !important;
}
/* Optimize for receipt layout */
.p-8 {
padding: 20px !important;
}
}
`}</style>
</div>
);
};
export default Orders;

View File

@@ -0,0 +1,537 @@
import React, { useState, useEffect, useRef } from 'react';
import { Plus, X, Search, Filter, MoreVertical, RefreshCw, Edit2, Power, PowerOff, Tag, Package, Image as ImageIcon, Barcode, DollarSign, ChevronDown, Clock, Check, Trash2, Database } from 'lucide-react';
interface ProductSession {
id?: number;
dayOfWeek: string;
active: boolean;
startTime: string;
endTime: string;
}
interface Product {
id?: number;
productId: string;
name: string;
category: string;
description: string;
basePrice: number;
price: number;
offerPrice: number;
discountPercent: number;
discountAmount: number;
counter: string;
tag: string;
parcelCharges: number;
barcode: string;
attributesOptional: boolean;
veg: boolean;
hasAllergy: boolean;
parcelNotAllowed: boolean;
sessionOptional: boolean;
sessions: ProductSession[];
imageData: string;
active: boolean;
stock: number;
stalls?: { id: number; name: string }[];
}
interface Stall {
id: number;
name: string;
baseItems?: { id: number; name: string }[];
}
interface BaseItem {
id: number;
name: string;
}
const DAYS = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
const getDefaultSessions = (): ProductSession[] =>
DAYS.map(day => ({ dayOfWeek: day, active: true, startTime: '00:00', endTime: '23:59' }));
const emptyProduct: Product = {
productId: '',
name: '',
category: '',
description: '',
basePrice: 0,
price: 0,
offerPrice: 0,
discountPercent: 0,
discountAmount: 0,
counter: '',
tag: '',
parcelCharges: 0,
barcode: '',
attributesOptional: false,
veg: false,
hasAllergy: false,
parcelNotAllowed: false,
sessionOptional: false,
sessions: getDefaultSessions(),
imageData: '',
active: true,
stock: 0
};
const Products = () => {
const [products, setProducts] = useState<Product[]>([]);
const [baseItems, setBaseItems] = useState<BaseItem[]>([]);
const [loading, setLoading] = useState(true);
const [showModal, setShowModal] = useState(false);
const [showSessionModal, setShowSessionModal] = useState(false);
const [editingProduct, setEditingProduct] = useState<Product | null>(null);
const [formData, setFormData] = useState<Product>(emptyProduct);
const [allStalls, setAllStalls] = useState<Stall[]>([]);
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
const menuRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
fetchProducts();
fetchBaseItems();
fetchAllStalls();
const handleClickOutside = (event: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setOpenMenuId(null);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const fetchProducts = async () => {
setLoading(true);
try {
const response = await fetch('http://localhost:8080/api/products');
const data = await response.json();
setProducts(data);
} catch (error) {
console.error('Error fetching products:', error);
} finally {
setLoading(false);
}
};
const fetchBaseItems = async () => {
try {
const response = await fetch('http://localhost:8080/api/base-items');
const data = await response.json();
setBaseItems(data);
} catch (error) {
console.error('Error fetching base items:', error);
}
};
const fetchAllStalls = async () => {
try {
const response = await fetch('http://localhost:8080/api/stalls');
const data = await response.json();
setAllStalls(data);
} catch (error) {
console.error('Error fetching stalls:', error);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const url = editingProduct
? `http://localhost:8080/api/products/${editingProduct.id}`
: 'http://localhost:8080/api/products';
const method = editingProduct ? 'PUT' : 'POST';
try {
const response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData),
});
if (response.ok) {
setShowModal(false);
setEditingProduct(null);
setFormData(emptyProduct);
fetchProducts();
}
} catch (error) {
console.error('Error saving product:', error);
}
};
const handleEdit = (product: Product) => {
setEditingProduct(product);
setFormData({
...product,
sessions: product.sessions && product.sessions.length > 0 ? product.sessions : getDefaultSessions()
});
setShowModal(true);
setOpenMenuId(null);
};
const handleToggleActive = async (product: Product) => {
try {
const response = await fetch(`http://localhost:8080/api/products/${product.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...product, active: !product.active }),
});
if (response.ok) {
fetchProducts();
setOpenMenuId(null);
}
} catch (error) {
console.error('Error toggling active status:', error);
}
};
const handleToggleStock = async (product: Product) => {
try {
const response = await fetch(`http://localhost:8080/api/products/${product.id}/toggle-stock`, {
method: 'PATCH',
});
if (response.ok) {
fetchProducts();
setOpenMenuId(null);
}
} catch (error) {
console.error('Error toggling stock status:', error);
}
};
const handleDelete = async (product: Product) => {
if (!window.confirm(`Are you sure you want to delete ${product.name}?`)) return;
try {
const response = await fetch(`http://localhost:8080/api/products/${product.id}`, {
method: 'DELETE',
});
if (response.ok) {
fetchProducts();
setOpenMenuId(null);
}
} catch (error) {
console.error('Error deleting product:', error);
}
};
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onloadend = () => {
setFormData({ ...formData, imageData: reader.result as string });
};
reader.readAsDataURL(file);
}
};
const updateSession = (index: number, updates: Partial<ProductSession>) => {
const newSessions = [...formData.sessions];
newSessions[index] = { ...newSessions[index], ...updates };
setFormData({ ...formData, sessions: newSessions });
};
return (
<div className="p-8 font-inter">
<div className="flex justify-between items-center mb-8">
<div>
<h1 className="text-2xl font-bold text-[#1e293b]">Products</h1>
<p className="text-sm text-[#64748b]">Manage your product catalog and inventory</p>
</div>
<button
onClick={() => {
setEditingProduct(null);
setFormData(emptyProduct);
setShowModal(true);
}}
className="bg-[#231651] text-white px-4 py-2 rounded-xl flex items-center gap-2 shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all"
>
<Plus size={20} />
<span>Add New Product</span>
</button>
</div>
{/* Filters Bar */}
<div className="bg-white p-4 rounded-xl border border-[#e2e8f0] mb-6 flex flex-wrap gap-4 items-center justify-between shadow-sm">
<div className="flex gap-4 items-center flex-1">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={18} />
<input
type="text"
placeholder="Search products..."
className="w-full pl-10 pr-4 py-2 bg-gray-50 border border-[#e2e8f0] rounded-lg text-sm focus:outline-none focus:border-[#231651]/30 transition-all"
/>
</div>
</div>
<button onClick={fetchProducts} className="p-2 text-[#64748b] hover:bg-gray-100 rounded-lg transition-all">
<RefreshCw size={18} className={loading ? 'animate-spin' : ''} />
</button>
</div>
{/* Table */}
<div className="bg-white rounded-xl border border-[#e2e8f0] shadow-sm">
<div className="overflow-x-visible">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Product Info</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Category</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Selling at</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Price Details</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{loading ? (
<tr><td colSpan={5} className="px-6 py-12 text-center text-[#64748b]"><RefreshCw className="animate-spin inline mr-2" />Loading...</td></tr>
) : products.map((product) => (
<tr key={product.id} className="hover:bg-gray-50/50 transition-all">
<td className="px-6 py-4">
<div className="flex items-center gap-3">
{product.imageData ? (
<img src={product.imageData} alt={product.name} className="w-10 h-10 rounded-lg object-cover" />
) : (
<div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-[#231651]"><Package size={20} /></div>
)}
<div>
<p className="text-sm font-bold text-[#1e293b]">{product.name}</p>
<p className="text-[11px] text-[#64748b]">ID: {product.productId || 'N/A'}</p>
</div>
</div>
</td>
<td className="px-6 py-4">
<span className="px-2.5 py-1 bg-blue-50 text-blue-600 rounded-lg text-xs font-semibold">{product.category}</span>
</td>
<td className="px-6 py-4">
<div className="flex flex-wrap gap-1">
{(() => {
// Combine direct stalls with stalls that have this product's category in their baseItems
const directStalls = product.stalls || [];
const indirectStalls = allStalls.filter(s =>
s.baseItems?.some(bi => bi.name.toLowerCase() === product.category?.toLowerCase())
).map(s => ({ id: s.id, name: s.name }));
// Unique stalls by ID
const combinedStalls = Array.from(
new Map([...directStalls, ...indirectStalls].map(s => [s.id, s])).values()
);
return combinedStalls.length > 0 ? (
combinedStalls.map(stall => (
<span key={stall.id} className="px-2 py-0.5 bg-purple-50 text-purple-600 rounded-md text-[10px] font-bold border border-purple-100 italic whitespace-nowrap">
{stall.name}
</span>
))
) : (
<span className="text-[10px] text-[#94a3b8] italic">Not Assigned</span>
);
})()}
</div>
</td>
<td className="px-6 py-4 text-sm font-bold text-[#1e293b]">{product.price}</td>
<td className="px-6 py-4">
<div className="flex flex-col gap-1.5">
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold w-fit ${product.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'}`}>
<div className={`w-1.5 h-1.5 rounded-full ${product.active ? 'bg-green-500' : 'bg-gray-400'}`} />
{product.active ? 'Active' : 'Inactive'}
</span>
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold w-fit ${product.stock > 0 ? 'bg-orange-100 text-orange-700' : 'bg-red-100 text-red-700'}`}>
<Database size={12} />
{product.stock > 0 ? `In Stock (${product.stock})` : 'Out of Stock'}
</span>
</div>
</td>
<td className={`px-6 py-4 text-right relative ${openMenuId === product.id ? 'z-[100]' : 'z-0'}`}>
<button onClick={() => setOpenMenuId(openMenuId === product.id ? null : (product.id as number))} className="p-1.5 text-[#94a3b8] hover:text-[#231651] rounded-lg transition-colors">
<MoreVertical size={18} />
</button>
{openMenuId === product.id && (
<div
ref={menuRef}
onMouseDown={(e) => e.stopPropagation()}
className="absolute right-6 top-12 w-48 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-[110] overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200"
>
<button onClick={() => handleEdit(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium"><Edit2 size={16} />Edit</button>
<button onClick={() => handleToggleStock(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium border-t border-[#f1f5f9]">
<Database size={16} className={product.stock > 0 ? "text-orange-500" : "text-green-500"} />
{product.stock > 0 ? "Mark Out of Stock" : "Mark In Stock"}
</button>
<button onClick={() => handleToggleActive(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium border-t border-[#f1f5f9]">
{product.active ? <><PowerOff size={16} className="text-red-500" />Deactivate</> : <><Power size={16} className="text-green-500" />Activate</>}
</button>
<button onClick={() => handleDelete(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-red-600 font-medium border-t border-[#f1f5f9]"><Trash2 size={16} />Delete</button>
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Product Modal */}
{showModal && (
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4 overflow-y-auto">
<div className="bg-white rounded-3xl w-full max-w-5xl shadow-2xl my-8 overflow-hidden">
<div className="px-8 py-6 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<h2 className="text-xl font-bold text-[#1e293b]">{editingProduct ? 'Edit Product' : 'Add New Product'}</h2>
<button onClick={() => setShowModal(false)} className="p-2 hover:bg-gray-200 rounded-full"><X size={24} className="text-[#64748b]" /></button>
</div>
<form onSubmit={handleSubmit} className="p-8">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="space-y-4">
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Product ID</label><input type="text" value={formData.productId} onChange={(e) => setFormData({ ...formData, productId: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Product Name *</label><input required type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm font-semibold" /></div>
<div>
<label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Category</label>
<select required value={formData.category} onChange={(e) => setFormData({ ...formData, category: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm">
<option value="">Select Category</option>
{baseItems.map(item => <option key={item.id} value={item.name}>{item.name}</option>)}
</select>
</div>
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Description</label><textarea value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} rows={3} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm resize-none" /></div>
</div>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Base Price</label><input type="number" value={formData.basePrice} onChange={(e) => setFormData({ ...formData, basePrice: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Sale Price</label><input type="number" value={formData.price} onChange={(e) => setFormData({ ...formData, price: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm font-bold" /></div>
</div>
<div className="grid grid-cols-2 gap-4">
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Discount %</label><input type="number" value={formData.discountPercent} onChange={(e) => setFormData({ ...formData, discountPercent: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Offer Price</label><input type="number" value={formData.offerPrice} onChange={(e) => setFormData({ ...formData, offerPrice: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
</div>
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Barcode</label><input type="text" value={formData.barcode} onChange={(e) => setFormData({ ...formData, barcode: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Stock Quantity</label><input type="number" value={formData.stock} onChange={(e) => setFormData({ ...formData, stock: parseInt(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm font-semibold" /></div>
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Counter</label>
<select value={formData.counter} onChange={(e) => setFormData({ ...formData, counter: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm"><option value="">Select Counter</option><option value="Main Counter">Main Counter</option></select></div>
</div>
<div className="space-y-4">
<div className="group">
<label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5 ml-1">Product Image</label>
<div
onClick={() => fileInputRef.current?.click()}
className="border-2 border-dashed border-[#e2e8f0] rounded-2xl p-6 flex flex-col items-center justify-center text-[#94a3b8] hover:border-[#231651]/30 hover:bg-gray-50 transition-all cursor-pointer h-40 overflow-hidden"
>
{formData.imageData ? (
<img src={formData.imageData} alt="Preview" className="w-full h-full object-contain" />
) : (
<>
<ImageIcon size={32} strokeWidth={1.5} className="mb-2" />
<p className="text-[10px] font-bold uppercase tracking-wider text-center">Drop or Select image</p>
</>
)}
</div>
<input ref={fileInputRef} type="file" accept="image/*" onChange={handleImageChange} className="hidden" />
</div>
</div>
</div>
{/* Advanced Options */}
<div className="mt-8 space-y-6">
<div className="flex flex-wrap gap-8 p-6 bg-gray-50 rounded-2xl border border-[#e2e8f0]">
<div className="flex flex-col gap-4 min-w-[200px]">
<div className="flex items-center justify-between gap-4">
<div><p className="text-sm font-bold text-[#1e293b]">Additional Attributes</p></div>
<button type="button" onClick={() => setFormData({ ...formData, attributesOptional: !formData.attributesOptional })} className={`w-11 h-6 rounded-full relative transition-all ${formData.attributesOptional ? 'bg-[#231651]' : 'bg-gray-300'}`}><div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${formData.attributesOptional ? 'translate-x-5' : ''}`} /></button>
</div>
{formData.attributesOptional && (
<div className="flex gap-4 animate-in fade-in slide-in-from-left-2">
<label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={formData.veg} onChange={(e) => setFormData({ ...formData, veg: e.target.checked })} className="w-4 h-4 rounded text-[#231651]" /><span className="text-xs font-semibold">Veg</span></label>
<label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={formData.hasAllergy} onChange={(e) => setFormData({ ...formData, hasAllergy: e.target.checked })} className="w-4 h-4 rounded text-[#231651]" /><span className="text-xs font-semibold">Allergy</span></label>
</div>
)}
</div>
<div className="flex flex-col gap-4 min-w-[200px]">
<div className="flex items-center justify-between gap-4">
<div><p className="text-sm font-bold text-[#1e293b]">Session</p></div>
<button type="button" onClick={() => setFormData({ ...formData, sessionOptional: !formData.sessionOptional })} className={`w-11 h-6 rounded-full relative transition-all ${formData.sessionOptional ? 'bg-[#231651]' : 'bg-gray-300'}`}><div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${formData.sessionOptional ? 'translate-x-5' : ''}`} /></button>
</div>
{formData.sessionOptional && (
<button type="button" onClick={() => setShowSessionModal(true)} className="flex items-center gap-2 px-4 py-2 bg-white border border-[#231651]/20 text-[#231651] text-xs font-bold rounded-xl hover:bg-[#231651]/5 transition-all w-fit animate-in fade-in slide-in-from-left-2"><Clock size={14} /> Configure Session</button>
)}
</div>
</div>
</div>
<div className="flex gap-4 mt-10">
<button type="button" onClick={() => setShowModal(false)} className="flex-1 px-8 py-4 border-2 border-[#e2e8f0] text-[#64748b] font-bold rounded-2xl hover:bg-gray-50 transition-all">Discard</button>
<button type="submit" className="flex-[2] px-8 py-4 bg-[#231651] text-white font-bold rounded-2xl shadow-xl hover:scale-[1.01] transition-all flex items-center justify-center gap-2"><Package size={20} /><span>{editingProduct ? 'Update Product' : 'Save Product'}</span></button>
</div>
</form>
</div>
</div>
)}
{/* Session Configuration Modal */}
{showSessionModal && (
<div className="fixed inset-0 bg-[#231651]/40 backdrop-blur-md z-[110] flex items-center justify-center p-4">
<div className="bg-white rounded-[40px] w-full max-w-4xl shadow-2xl overflow-hidden animate-in zoom-in duration-300">
<div className="p-10">
<h2 className="text-2xl font-bold text-[#1e293b] text-center mb-8">Select the session that the time product show in menu</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-h-[60vh] overflow-y-auto px-2 custom-scrollbar">
{formData.sessions.map((session, index) => (
<div key={session.dayOfWeek} className="p-6 rounded-3xl border-2 border-[#e2e8f0] relative">
<div className="flex items-center justify-center gap-3 mb-6">
<div
onClick={() => updateSession(index, { active: !session.active })}
className={`w-6 h-6 rounded-md flex items-center justify-center cursor-pointer transition-all ${session.active ? 'bg-[#51133d]' : 'bg-gray-200'}`}
>
{session.active && <Check size={14} className="text-white" strokeWidth={4} />}
</div>
<span className="text-lg font-bold text-[#1e293b]">{session.dayOfWeek}</span>
</div>
<div className="space-y-4 opacity-100 transition-opacity">
<div className="relative">
<label className="absolute -top-2 left-4 bg-white px-1 text-[10px] font-bold text-[#94a3b8] z-10">Start Time</label>
<div className="flex items-center justify-between px-5 py-4 bg-white border border-[#e2e8f0] rounded-2xl">
<input
type="time"
disabled={!session.active}
value={session.startTime}
onChange={(e) => updateSession(index, { startTime: e.target.value })}
className="bg-transparent border-none outline-none text-sm font-bold text-[#1e293b] w-full disabled:text-gray-400"
/>
<Clock size={18} className="text-[#94a3b8]" />
</div>
</div>
<div className="relative">
<label className="absolute -top-2 left-4 bg-white px-1 text-[10px] font-bold text-[#94a3b8] z-10">End Time</label>
<div className="flex items-center justify-between px-5 py-4 bg-white border border-[#e2e8f0] rounded-2xl">
<input
type="time"
disabled={!session.active}
value={session.endTime}
onChange={(e) => updateSession(index, { endTime: e.target.value })}
className="bg-transparent border-none outline-none text-sm font-bold text-[#1e293b] w-full disabled:text-gray-400"
/>
<Clock size={18} className="text-[#94a3b8]" />
</div>
</div>
</div>
</div>
))}
</div>
<div className="flex justify-end gap-4 mt-10 pt-4">
<button onClick={() => setShowSessionModal(false)} className="px-10 py-4 bg-[#f46d43] text-white font-bold rounded-2xl shadow-lg hover:scale-105 transition-all">Close</button>
<button onClick={() => setShowSessionModal(false)} className="px-10 py-4 bg-[#3d1351] text-white font-bold rounded-2xl shadow-lg hover:scale-105 transition-all">Submit</button>
</div>
</div>
</div>
</div>
)}
<style dangerouslySetInnerHTML={{ __html: `
.custom-scrollbar::-webkit-scrollbar { width: 6px; }
.custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
.custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
` }} />
</div>
);
};
export default Products;

View File

@@ -0,0 +1,325 @@
import React, { useState, useEffect } from 'react';
import {
TrendingUp,
TrendingDown,
Calendar,
Filter,
DollarSign,
Percent,
Search,
Loader2
} from 'lucide-react';
import { format, startOfMonth, endOfMonth } from 'date-fns';
interface StatBoxProps {
title: string;
value: string | number;
subtext: string;
icon: any;
colorClass: string;
}
const StatBox = ({ title, value, subtext, icon: Icon, colorClass }: StatBoxProps) => (
<div className="bg-white p-6 rounded-2xl border border-[#e2e8f0] flex-1 shadow-sm">
<div className="flex justify-between items-start mb-4">
<div>
<p className="text-[10px] font-bold text-[#64748b] uppercase tracking-wider mb-1">{title}</p>
<h3 className="text-2xl font-black text-[#1e293b]">{value}</h3>
</div>
<div className={`p-2.5 rounded-xl ${colorClass}`}>
<Icon size={18} />
</div>
</div>
<p className="text-[11px] text-[#94a3b8] font-medium leading-relaxed">{subtext}</p>
</div>
);
interface ProductAnalytics {
product: string;
qty: number;
basePrice: number;
currentPrice: number;
inflatedAmount: number;
deflatedAmount: number;
rate: number;
trend: 'up' | 'down' | 'stable';
}
const PurchaseAnalytics = () => {
const [searchTerm, setSearchTerm] = useState('');
const [isLoading, setIsLoading] = useState(true);
const [analytics, setAnalytics] = useState<ProductAnalytics[]>([]);
const [filterType, setFilterType] = useState<'all' | 'up' | 'down'>('all');
const [summary, setSummary] = useState({
totalBase: 0,
totalInflated: 0,
totalDeflated: 0,
inflationRate: 0,
inflatedCount: 0,
deflatedCount: 0
});
const [dateRange] = useState({
start: startOfMonth(new Date()),
end: endOfMonth(new Date())
});
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
setIsLoading(true);
const response = await fetch('/api/purchases/orders');
if (response.ok) {
const data = await response.json();
processAnalytics(data);
}
} catch (error) {
console.error('Error fetching analytics:', error);
} finally {
setIsLoading(false);
}
};
const processAnalytics = (purchaseOrders: any[]) => {
const productStats: Record<string, { qty: number, prices: { date: Date, rate: number }[] }> = {};
purchaseOrders.forEach(order => {
order.items?.forEach((item: any) => {
if (!productStats[item.productName]) {
productStats[item.productName] = { qty: 0, prices: [] };
}
productStats[item.productName].qty += item.quantity;
productStats[item.productName].prices.push({
date: new Date(order.date),
rate: item.rate
});
});
});
let totalBase = 0;
let totalInflated = 0;
let totalDeflated = 0;
let inflatedCount = 0;
let deflatedCount = 0;
const analyzedData: ProductAnalytics[] = Object.keys(productStats).map(productName => {
const stats = productStats[productName];
stats.prices.sort((a, b) => a.date.getTime() - b.date.getTime());
const basePrice = stats.prices[0].rate;
const currentPrice = stats.prices[stats.prices.length - 1].rate;
const qty = stats.qty;
const priceDiff = currentPrice - basePrice;
const impactAmount = Math.abs(priceDiff * qty);
let inflatedAmount = 0;
let deflatedAmount = 0;
let trend: 'up' | 'down' | 'stable' = 'stable';
if (priceDiff > 0) {
inflatedAmount = impactAmount;
totalInflated += inflatedAmount;
inflatedCount++;
trend = 'up';
} else if (priceDiff < 0) {
deflatedAmount = impactAmount;
totalDeflated += deflatedAmount;
deflatedCount++;
trend = 'down';
}
totalBase += basePrice * qty;
const rate = basePrice !== 0 ? (Math.abs(priceDiff) / basePrice) * 100 : 0;
return {
product: productName,
qty,
basePrice,
currentPrice,
inflatedAmount,
deflatedAmount,
rate,
trend
};
});
const inflationRate = totalBase !== 0 ? (totalInflated / totalBase) * 100 : 0;
setAnalytics(analyzedData);
setSummary({
totalBase,
totalInflated,
totalDeflated,
inflationRate,
inflatedCount,
deflatedCount
});
};
const filteredAnalytics = analytics.filter(item => {
const matchesSearch = item.product.toLowerCase().includes(searchTerm.toLowerCase());
const matchesFilter = filterType === 'all' || item.trend === filterType;
return matchesSearch && matchesFilter;
});
if (isLoading) {
return (
<div className="h-full flex flex-col items-center justify-center gap-4">
<Loader2 className="animate-spin text-[#521c4b]" size={40} />
<p className="text-sm font-bold text-slate-500 uppercase tracking-widest">Calculating Market Analytics...</p>
</div>
);
}
return (
<div className="p-8 space-y-8 animate-in fade-in duration-500">
{/* Header */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-black text-[#521c4b] tracking-tight uppercase">Purchase Analytics</h1>
<div className="flex items-center gap-2 mt-1">
<span className="bg-[#521c4b]/10 text-[#521c4b] text-[10px] font-bold px-2 py-0.5 rounded-full uppercase">
Start: {format(dateRange.start, 'yyyy-MM-dd')}
</span>
<span className="bg-[#521c4b]/10 text-[#521c4b] text-[10px] font-bold px-2 py-0.5 rounded-full uppercase">
End: {format(dateRange.end, 'yyyy-MM-dd')}
</span>
</div>
</div>
<div className="flex items-center gap-3">
<button
onClick={() => setFilterType('all')}
className={`px-4 py-2 rounded-xl text-xs font-bold uppercase transition-all ${filterType === 'all' ? 'bg-[#521c4b] text-white shadow-lg' : 'bg-white border text-slate-500 border-slate-200 hover:bg-slate-50'}`}
>
Show All
</button>
<button title="Calendar" className="p-2.5 bg-white border border-[#e2e8f0] rounded-xl text-[#64748b] transition-all"><Calendar size={18} /></button>
<button title="Filter" className="p-2.5 bg-white border border-[#e2e8f0] rounded-xl text-[#64748b] transition-all"><Filter size={18} /></button>
</div>
</div>
{/* Top Stats */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<StatBox title="Total Base Amount" value={summary.totalBase.toFixed(2)} subtext="Initial purchase costs" icon={DollarSign} colorClass="bg-gray-100 text-gray-500" />
<StatBox title="Total Inflated Amount" value={summary.totalInflated.toFixed(2)} subtext="Extra cost from hikes" icon={TrendingUp} colorClass="bg-rose-100 text-rose-500" />
<StatBox title="Total Deflated Amount" value={summary.totalDeflated.toFixed(2)} subtext="Actual savings realized" icon={TrendingDown} colorClass="bg-emerald-100 text-emerald-500" />
<div className="bg-white p-6 rounded-2xl border border-[#e2e8f0] flex-1 shadow-sm">
<div className="flex justify-between items-start mb-4">
<div>
<p className="text-[10px] font-bold text-[#64748b] uppercase tracking-wider mb-1">Inflation Rate</p>
<h3 className="text-2xl font-black text-[#1e293b]">{summary.inflationRate.toFixed(2)}%</h3>
</div>
<div className="p-2.5 rounded-xl bg-violet-100 text-violet-500"><Percent size={18} /></div>
</div>
<p className="text-[11px] text-[#94a3b8] font-medium leading-relaxed">Overall price impact percentage</p>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
<div className="lg:col-span-2 bg-white rounded-3xl border border-[#e2e8f0] shadow-sm overflow-hidden">
<div className="p-6 border-b border-[#e2e8f0] flex items-center justify-between bg-slate-50/30">
<h3 className="text-sm font-black text-[#1e293b] uppercase tracking-wider">
{filterType === 'up' ? 'Price Hikes (Inflated)' : filterType === 'down' ? 'Savings (Deflated)' : 'Market Price Status'}
</h3>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={14} />
<input
type="text"
placeholder="Search products..."
className="pl-9 pr-4 py-2 border border-[#e2e8f0] rounded-xl text-xs outline-none focus:border-[#521c4b]/30 transition-all font-medium"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left">
<thead>
<tr className="bg-slate-50/50">
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none">Product</th>
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none">Qty</th>
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none text-right">Base Price</th>
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none text-right">Impact Amount</th>
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none text-center">Impact Rate</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{filteredAnalytics.length === 0 ? (
<tr><td colSpan={5} className="px-6 py-12 text-center text-slate-400 text-sm">No matching trends found</td></tr>
) : (
filteredAnalytics.map((item, idx) => (
<tr key={idx} className="hover:bg-gray-50/50 transition-colors group">
<td className="px-6 py-4"><p className="text-xs font-bold text-[#1e293b] group-hover:text-[#521c4b]">{item.product}</p></td>
<td className="px-6 py-4 text-xs font-bold text-[#475569]">{item.qty}</td>
<td className="px-6 py-4 text-xs font-bold text-[#475569] text-right">{item.basePrice.toFixed(2)}</td>
<td className="px-6 py-4 text-right">
<div className="flex flex-col items-end">
<span className={`text-xs font-black ${item.trend === 'up' ? 'text-rose-500' : item.trend === 'down' ? 'text-emerald-500' : 'text-slate-400'}`}>
{item.trend === 'up' ? '+' : item.trend === 'down' ? '-' : ''}{(item.inflatedAmount || item.deflatedAmount).toFixed(2)}
</span>
<p className="text-[10px] font-bold text-[#94a3b8] uppercase tracking-tighter">
{item.trend === 'up' ? 'Incurred' : item.trend === 'down' ? 'Saved' : 'Neutral'}
</p>
</div>
</td>
<td className="px-6 py-4 text-center">
<span className={`inline-flex items-center px-2 py-0.5 rounded-lg text-[10px] font-bold ${item.trend === 'up' ? 'bg-rose-50 text-rose-600' : item.trend === 'down' ? 'bg-emerald-50 text-emerald-600' : 'bg-gray-100 text-gray-500'}`}>
{item.rate.toFixed(1)}%
</span>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
<div className="space-y-6">
<div className="bg-white p-6 rounded-3xl border border-[#e2e8f0] shadow-sm">
<h3 className="text-sm font-black text-[#1e293b] uppercase tracking-wider mb-6">Market Trends</h3>
<div className="grid grid-cols-2 gap-4">
<button
onClick={() => setFilterType('up')}
className={`p-4 rounded-2xl flex flex-col items-center justify-center gap-2 transition-all cursor-pointer hover:border-[#521c4b]/50 border-2 ${filterType === 'up' ? 'bg-[#521c4b] text-white border-[#521c4b]' : 'bg-gray-50 text-slate-400 border-transparent hover:bg-slate-100'}`}
>
<TrendingUp size={20} />
<span className="text-[10px] font-bold uppercase tracking-wider">Inflation</span>
<span className="text-sm font-black">{summary.inflatedCount}</span>
</button>
<button
onClick={() => setFilterType('down')}
className={`p-4 rounded-2xl flex flex-col items-center justify-center gap-2 transition-all cursor-pointer hover:border-emerald-600/50 border-2 ${filterType === 'down' ? 'bg-emerald-600 text-white border-emerald-600' : 'bg-gray-50 text-slate-400 border-transparent hover:bg-slate-100'}`}
>
<TrendingDown size={20} />
<span className="text-[10px] font-bold uppercase tracking-wider">Deflation</span>
<span className="text-sm font-black">{summary.deflatedCount}</span>
</button>
</div>
<div className="mt-8 flex flex-col items-center py-8">
<div className="relative w-32 h-32 flex items-center justify-center">
<div className="absolute inset-0 rounded-full border-[10px] border-slate-100"></div>
<div className="text-center">
<p className="text-3xl font-black text-[#1e293b]">{filterType === 'up' ? summary.inflatedCount : filterType === 'down' ? summary.deflatedCount : summary.inflatedCount + summary.deflatedCount}</p>
<p className="text-[10px] font-bold text-[#94a3b8] uppercase">Selected</p>
</div>
</div>
<div className={`mt-8 w-full p-4 rounded-2xl border ${filterType === 'up' ? 'bg-rose-50 border-rose-100 text-rose-600' : filterType === 'down' ? 'bg-emerald-50 border-emerald-100 text-emerald-600' : 'bg-slate-50 border-slate-200 text-slate-600'}`}>
<p className="text-[10px] font-bold text-center uppercase">
{filterType === 'up' ? 'Showing all price hikes' : filterType === 'down' ? 'Showing all price drops' : 'Select a trend to filter table'}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default PurchaseAnalytics;

View File

@@ -0,0 +1,219 @@
import { useState, useEffect } from 'react';
import {
Filter,
ArrowRight,
Search,
CheckCircle2,
AlertCircle
} from 'lucide-react';
import {
AreaChart,
Area,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer
} from 'recharts';
import { motion } from 'framer-motion';
const PurchaseSummary = () => {
const [activeRange, setActiveRange] = useState('Today');
const [data, setData] = useState<any>(null);
const [bills, setBills] = useState<any[]>([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
// Fetch summary and bills in parallel
const [summaryRes, billsRes] = await Promise.all([
fetch('/api/purchases/summary'),
fetch('/api/purchases/orders')
]);
if (summaryRes.ok && billsRes.ok) {
const summaryData = await summaryRes.json();
const billsData = await billsRes.json();
setData(summaryData);
setBills(billsData);
}
} catch (error) {
console.error('Error fetching purchase summary:', error);
} finally {
setIsLoading(false);
}
};
fetchData();
}, []);
if (isLoading || !data) {
return (
<div className="h-screen flex items-center justify-center bg-slate-50/50">
<motion.div
animate={{ scale: [1, 1.05, 1] }}
transition={{ repeat: Infinity, duration: 2 }}
className="text-[#521c4b] font-black uppercase tracking-widest text-xs"
>
Compiling Fiscal Intelligence...
</motion.div>
</div>
);
}
const summaryStats = [
{ title: "Total Purchases", value: `${data.totalAmount.toLocaleString()}`, icon: AlertCircle, color: "text-rose-500", bg: "bg-rose-50" },
{ title: "Total Credits", value: `${data.balanceAmount.toLocaleString()}`, icon: AlertCircle, color: "text-amber-500", bg: "bg-amber-50" },
{ title: "Credit Paid", value: `${data.paidAmount.toLocaleString()}`, icon: AlertCircle, color: "text-emerald-500", bg: "bg-emerald-50" },
{ title: "Balance Credit", value: `${data.balanceAmount.toLocaleString()}`, icon: AlertCircle, color: "text-indigo-500", bg: "bg-indigo-50" },
{ title: "Bills to Pay", value: data.unpaidCount.toString(), icon: AlertCircle, color: "text-blue-500", bg: "bg-blue-50" }
];
return (
<div className="p-8 space-y-8 bg-slate-50/50 min-h-screen font-inter">
{/* Top Header */}
<div className="flex items-center justify-between">
<div className="flex flex-col">
<div className="flex items-center gap-2 mb-1">
<button title="Back" className="p-1.5 hover:bg-slate-100 rounded-lg transition-all">
<ArrowRight className="rotate-180 text-slate-400" size={18} />
</button>
<h2 className="text-xs font-black text-[#521c4b] uppercase tracking-widest">Purchases</h2>
</div>
<h1 className="text-2xl font-black text-slate-800">Summary</h1>
</div>
<div className="flex items-center gap-2 bg-white p-1 rounded-2xl border border-slate-200 shadow-sm">
{['Yesterday', 'Today', 'Week', '30 Days'].map(range => (
<button
key={range}
onClick={() => setActiveRange(range)}
className={`px-4 py-2 text-[10px] font-black uppercase tracking-widest transition-all rounded-xl ${activeRange === range ? 'text-white bg-[#521c4b] shadow-md shadow-[#521c4b]/20' : 'text-slate-400 hover:text-slate-600'}`}
>
{range}
</button>
))}
</div>
</div>
<div className="grid grid-cols-12 gap-8">
<div className="col-span-12 lg:col-span-5 space-y-6">
<div className="grid grid-cols-2 gap-4">
{summaryStats.map((stat, idx) => (
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: idx * 0.05 }}
key={idx}
whileHover={{ y: -4 }}
className="bg-white p-6 rounded-[28px] border border-slate-100 shadow-sm transition-all"
>
<div className="flex items-center gap-3 mb-4">
<div className={`p-2.5 rounded-xl ${stat.bg} ${stat.color}`}>
<stat.icon size={20} />
</div>
<h3 className="text-[9px] font-black text-slate-400 uppercase tracking-widest leading-none">{stat.title}</h3>
</div>
<p className="text-2xl font-black text-slate-800">{stat.value}</p>
</motion.div>
))}
<div className="col-span-2 bg-[#521c4b] p-6 rounded-[32px] shadow-lg shadow-[#521c4b]/20 text-white relative overflow-hidden group">
<div className="absolute -right-8 -top-8 w-32 h-32 bg-white/10 rounded-full blur-3xl" />
<div className="relative z-10 flex items-end justify-between">
<div>
<h3 className="text-[10px] font-black uppercase tracking-widest opacity-80 text-white/70 mb-8">Bill Fulfillment</h3>
<p className="text-4xl font-black mb-1">{bills.filter(b => b.status === 'PAID').length}</p>
<p className="text-[10px] font-bold uppercase tracking-widest opacity-60">Cleared Bills</p>
</div>
<div className="text-right">
<CheckCircle2 size={32} className="text-emerald-400 mb-6 ml-auto" />
<p className="text-lg font-black text-emerald-400">
{bills.length > 0 ? Math.round((bills.filter(b => b.status === 'PAID').length / bills.length) * 100) : 0}%
</p>
<p className="text-[9px] font-bold uppercase tracking-widest opacity-60">Success Rate</p>
</div>
</div>
</div>
</div>
</div>
<div className="col-span-12 lg:col-span-7 space-y-8">
<div className="bg-white p-8 rounded-[40px] border border-slate-100 shadow-sm h-full">
<div className="flex items-center justify-between mb-8">
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Purchase Trends</h3>
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full bg-[#f43f5e]" />
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Procurement Volume</span>
</div>
</div>
<div className="h-[280px]">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={data.trend}>
<defs>
<linearGradient id="purchaseGradSum" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#f43f5e" stopOpacity={0.1}/>
<stop offset="95%" stopColor="#f43f5e" stopOpacity={0}/>
</linearGradient>
</defs>
<XAxis dataKey="date" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} />
<YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} tickFormatter={(v) => `${v/1000}k`} />
<Tooltip contentStyle={{ borderRadius: '16px', border: 'none', boxShadow: '0 10px 25px -5px rgb(0 0 0 / 0.1)' }} />
<Area type="monotone" dataKey="amount" stroke="#f43f5e" strokeWidth={4} fillOpacity={1} fill="url(#purchaseGradSum)" />
</AreaChart>
</ResponsiveContainer>
</div>
</div>
</div>
</div>
<div className="bg-white rounded-[32px] border border-slate-100 shadow-sm p-8 pb-12">
<div className="flex items-center justify-between mb-8">
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Recent Activity</h3>
<div className="flex items-center gap-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
<input type="text" title="Search" placeholder="Filter bills..." className="pl-9 pr-4 py-2 bg-slate-50 border border-slate-100 rounded-xl text-xs font-bold outline-none focus:border-[#521c4b] transition-all" />
</div>
<button title="Filter" className="p-2.5 bg-slate-50 rounded-xl text-slate-500 border border-slate-100"><Filter size={16} /></button>
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="bg-slate-50/50">
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Bill No</th>
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Date</th>
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Vendor</th>
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Status</th>
<th className="px-6 py-4 text-right text-[10px] font-black text-slate-400 uppercase tracking-widest">Balance</th>
<th className="px-6 py-4 text-right text-[10px] font-black text-slate-400 uppercase tracking-widest">Amount</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-50">
{bills.map((bill: any, idx: number) => (
<tr key={idx} className="hover:bg-slate-50/50 transition-all cursor-pointer group">
<td className="px-6 py-5 text-xs font-black text-slate-800">{bill.purchaseId}</td>
<td className="px-6 py-5 text-xs font-bold text-slate-400">{bill.date}</td>
<td className="px-6 py-5">
<span className="text-xs font-black text-slate-700">{bill.vendor?.name || 'Walk-in'}</span>
</td>
<td className="px-6 py-5">
<span className={`px-3 py-1.5 rounded-xl text-[9px] font-black uppercase tracking-widest ${bill.status === 'PAID' ? 'bg-emerald-50 text-emerald-600' : 'bg-rose-50 text-rose-600'}`}>
{bill.status}
</span>
</td>
<td className="px-6 py-5 text-right text-xs font-black text-rose-500">{bill.balance.toLocaleString()}</td>
<td className="px-6 py-5 text-right text-xs font-black text-[#521c4b]">{bill.amount.toLocaleString()}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
};
export default PurchaseSummary;

View File

@@ -0,0 +1,531 @@
import React, { useState, useEffect } from 'react';
import { Search, ShoppingCart, Eye, Plus, X, Loader2, CheckCircle, Trash2, Edit2 } from 'lucide-react';
interface PurchaseOrderItem {
productName: string;
quantity: number;
rate: number;
total: number;
}
interface PurchaseOrder {
id: number;
purchaseId: string;
date: string;
vendor: { id: number; name: string };
amount: number;
paidTotal: number;
status: 'OPEN' | 'TRANSIT' | 'CANCELLED' | 'BILLED' | 'RECEIVED' | 'PARTIALLY PAID' | 'CLOSE';
referenceId: string;
items: PurchaseOrderItem[];
}
const Purchases: React.FC = () => {
const [orders, setOrders] = useState<PurchaseOrder[]>([]);
const [vendors, setVendors] = useState<{id: number, name: string}[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [showAddModal, setShowAddModal] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [editingOrder, setEditingOrder] = useState<PurchaseOrder | null>(null);
const [showHistoryModal, setShowHistoryModal] = useState(false);
const [orderHistory, setOrderHistory] = useState<any[]>([]);
const [activeHistoryOrder, setActiveHistoryOrder] = useState<PurchaseOrder | null>(null);
// New Order Form State
const initialOrderState = {
purchaseId: `PO_${Math.floor(1000 + Math.random() * 9000)}`,
date: new Date().toISOString().split('T')[0],
vendorId: '',
status: 'OPEN',
discount: 0,
referenceId: '',
instruction: '',
items: [{ productName: '', quantity: 1, rate: 0, total: 0 }]
};
const [newOrder, setNewOrder] = useState(initialOrderState);
useEffect(() => {
fetchOrders();
fetchVendors();
}, []);
const fetchOrders = async () => {
try {
setIsLoading(true);
const response = await fetch('/api/purchases/orders');
if (response.ok) {
const data = await response.json();
setOrders(data);
}
} catch (error) {
console.error('Error fetching orders:', error);
} finally {
setIsLoading(false);
}
};
const fetchVendors = async () => {
try {
const response = await fetch('/api/purchases/vendors');
if (response.ok) {
const data = await response.json();
setVendors(data);
}
} catch (error) {
console.error('Error fetching vendors:', error);
}
};
const handleAddItem = () => {
setNewOrder({
...newOrder,
items: [...newOrder.items, { productName: '', quantity: 1, rate: 0, total: 0 }]
});
};
const handleItemChange = (index: number, field: keyof PurchaseOrderItem, value: string | number) => {
const updatedItems = [...newOrder.items];
const item = { ...updatedItems[index], [field]: value };
if (field === 'quantity' || field === 'rate') {
item.total = Number(item.quantity) * Number(item.rate);
}
updatedItems[index] = item;
setNewOrder({ ...newOrder, items: updatedItems });
};
const calculateTotal = () => {
return newOrder.items.reduce((sum, item) => sum + item.total, 0) - newOrder.discount;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSaving(true);
try {
const payload = {
...newOrder,
id: editingOrder?.id,
vendor: { id: parseInt(newOrder.vendorId) },
amount: calculateTotal(),
date: new Date(newOrder.date).toISOString()
};
const response = await fetch('/api/purchases/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (response.ok) {
setShowAddModal(false);
setEditingOrder(null);
setNewOrder(initialOrderState);
fetchOrders();
}
} catch (error) {
console.error('Error saving order:', error);
} finally {
setIsSaving(false);
}
};
const deleteOrder = async (id: number) => {
if (!window.confirm('Delete this purchase order?')) return;
try {
await fetch(`/api/purchases/orders/${id}`, { method: 'DELETE' });
fetchOrders();
} catch (error) {
console.error('Error deleting order:', error);
}
}
const getStatusColor = (status: string) => {
switch (status) {
case 'OPEN': return 'bg-blue-100 text-blue-700';
case 'TRANSIT': return 'bg-indigo-100 text-indigo-700';
case 'BILLED': return 'bg-amber-100 text-amber-700';
case 'RECEIVED': return 'bg-emerald-100 text-emerald-700';
case 'PARTIALLY PAID': return 'bg-violet-100 text-violet-700';
case 'CLOSE': return 'bg-gray-100 text-gray-700';
case 'CANCELLED': return 'bg-rose-100 text-rose-700';
default: return 'bg-gray-100 text-gray-700';
}
};
const updateOrderStatus = async (orderId: number, newStatus: string) => {
try {
const order = orders.find(o => o.id === orderId);
if (!order) return;
const response = await fetch(`/api/purchases/orders`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...order, status: newStatus })
});
if (response.ok) {
fetchOrders();
}
} catch (error) {
console.error('Error updating status:', error);
}
};
const handleEditOrder = (order: PurchaseOrder) => {
setEditingOrder(order);
setNewOrder({
purchaseId: order.purchaseId,
date: order.date.split('T')[0],
vendorId: order.vendor.id.toString(),
status: order.status,
discount: 0, // We should ideally store discount in DB too, but for now 0
referenceId: order.referenceId || '',
instruction: '', // Same for instruction
items: order.items.map(item => ({...item}))
});
setShowAddModal(true);
};
const fetchOrderHistory = async (order: PurchaseOrder) => {
try {
setActiveHistoryOrder(order);
const response = await fetch(`/api/purchases/orders/${order.id}/history`);
if (response.ok) {
const data = await response.json();
setOrderHistory(data);
setShowHistoryModal(true);
}
} catch (error) {
console.error('Error fetching history:', error);
}
};
return (
<div className="flex flex-col h-full bg-[#f8fafc] p-8 gap-8 font-inter overflow-y-auto">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6 max-w-[1600px]">
<div className="flex items-center gap-5">
<div className="w-14 h-14 bg-[#231651] rounded-xl flex items-center justify-center shadow-lg shadow-[#231651]/20">
<ShoppingCart className="text-white w-7 h-7" />
</div>
<div>
<h1 className="text-2xl font-bold text-[#1e293b]">Purchase Orders</h1>
<p className="text-sm text-[#64748b]">Track and manage your inventory procurement</p>
</div>
</div>
<div className="flex items-center gap-4">
<button
onClick={() => setShowAddModal(true)}
title="Create a new procurement order"
className="px-5 py-2.5 bg-[#231651] text-white rounded-xl text-sm font-bold flex items-center gap-2 hover:scale-105 transition-all shadow-lg"
>
<Plus size={18} />
Create Purchase
</button>
<div className="relative group min-w-[320px]">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={18} />
<input
type="text"
placeholder="Search purchases..."
className="w-full pl-10 pr-4 py-2.5 bg-white border border-[#e2e8f0] rounded-xl text-sm focus:outline-none focus:border-[#231651]/30 transition-all shadow-sm"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
</div>
</div>
<div className="max-w-[1600px] bg-white rounded-xl border border-[#e2e8f0] shadow-sm overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Purchase ID</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Date</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Vendor</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Amount</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Reference ID</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{isLoading ? (
<tr>
<td colSpan={8} className="px-6 py-12 text-center">
<Loader2 className="animate-spin inline-block mr-2" /> Loading records...
</td>
</tr>
) : orders.filter(o => o.purchaseId.toLowerCase().includes(searchTerm.toLowerCase())).map((order) => (
<tr key={order.id} className="hover:bg-gray-50/50 transition-all font-medium">
<td className="px-6 py-4 text-sm font-bold text-[#231651]">{order.purchaseId}</td>
<td className="px-6 py-4 text-sm text-[#64748b]">{new Date(order.date).toLocaleDateString()}</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2">
<div className="w-7 h-7 bg-indigo-50 text-indigo-600 rounded-lg flex items-center justify-center text-[10px] font-bold">
{order.vendor.name.charAt(0)}
</div>
<span className="text-sm text-[#1e293b]">{order.vendor.name}</span>
</div>
</td>
<td className="px-6 py-4 text-sm font-bold text-[#1e293b]">{order.amount.toLocaleString()}</td>
<td className="px-6 py-4">
<select
value={order.status}
onChange={(e) => updateOrderStatus(order.id, e.target.value)}
className={`px-2 py-1 rounded-lg text-[10px] font-bold uppercase tracking-wider outline-none border-none cursor-pointer ${getStatusColor(order.status)}`}
>
<option value="OPEN">OPEN</option>
<option value="TRANSIT">TRANSIT</option>
<option value="BILLED">BILLED</option>
<option value="RECEIVED">RECEIVED</option>
<option value="PARTIALLY PAID">PARTIALLY PAID</option>
<option value="CLOSE">CLOSE</option>
<option value="CANCELLED">CANCELLED</option>
</select>
</td>
<td className="px-6 py-4 text-[10px] font-bold text-[#64748b] font-mono">
{order.referenceId || `Pur_${Math.random().toString(36).substring(2, 10).toUpperCase()}`}
</td>
<td className="px-6 py-4 text-right">
<div className="flex items-center justify-end gap-2">
<button
onClick={() => fetchOrderHistory(order)}
title="View audit history of price changes"
className="p-2 text-[#94a3b8] hover:text-[#231651] hover:bg-indigo-50 rounded-lg transition-all"
>
<Eye size={18} />
</button>
<button
onClick={() => handleEditOrder(order)}
title="Edit purchase order details"
className="p-2 text-[#94a3b8] hover:text-[#231651] hover:bg-indigo-50 rounded-lg transition-all"
>
<Edit2 size={18} />
</button>
<button
onClick={() => deleteOrder(order.id)}
title="Delete this purchase order permanently"
className="p-2 text-[#94a3b8] hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
>
<Trash2 size={18} />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{showAddModal && (
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
<div className="bg-white rounded-3xl w-full max-w-5xl max-h-[90vh] shadow-2xl overflow-hidden flex flex-col animate-in zoom-in duration-300">
<div className="px-8 py-6 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-[#231651] rounded-xl flex items-center justify-center text-white">
{editingOrder ? <ShoppingCart size={20} /> : <Plus size={20} />}
</div>
<div>
<h2 className="text-xl font-bold text-[#1e293b]">{editingOrder ? 'Edit Purchase Order' : 'Create New Purchase'}</h2>
<p className="text-xs text-[#64748b]">{editingOrder ? 'Update terms or quantities' : 'Draft a new inventory procurement order'}</p>
</div>
</div>
<button onClick={() => { setShowAddModal(false); setEditingOrder(null); setNewOrder(initialOrderState); }} title="Close window" className="p-2 hover:bg-gray-200 rounded-full transition-colors">
<X size={20} className="text-[#64748b]" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-8 overflow-y-auto space-y-8">
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Purchase ID</label>
<input type="text" value={newOrder.purchaseId} readOnly className="w-full px-4 py-3 bg-slate-50 border border-[#e2e8f0] rounded-xl text-sm font-bold text-[#231651] outline-none" />
</div>
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Date</label>
<input type="date" value={newOrder.date} onChange={e => setNewOrder({...newOrder, date: e.target.value})} className="w-full px-4 py-3 bg-white border border-[#e2e8f0] rounded-xl text-sm font-bold outline-none focus:border-[#231651]" />
</div>
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Vendor</label>
<select
required
value={newOrder.vendorId}
onChange={e => setNewOrder({...newOrder, vendorId: e.target.value})}
className="w-full px-4 py-3 bg-white border border-[#e2e8f0] rounded-xl text-sm font-bold outline-none focus:border-[#231651]"
>
<option value="">Select Vendor</option>
{vendors.map(v => <option key={v.id} value={v.id}>{v.name}</option>)}
</select>
</div>
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Status</label>
<select value={newOrder.status} onChange={e => setNewOrder({...newOrder, status: e.target.value as any})} className="w-full px-4 py-3 bg-white border border-[#e2e8f0] rounded-xl text-sm font-bold outline-none focus:border-[#231651]">
<option value="OPEN">OPEN</option>
<option value="TRANSIT">TRANSIT</option>
<option value="BILLED">BILLED</option>
<option value="RECEIVED">RECEIVED</option>
<option value="PARTIALLY PAID">PARTIALLY PAID</option>
<option value="CLOSE">CLOSE</option>
<option value="CANCELLED">CANCELLED</option>
</select>
</div>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-black text-[#1e293b] uppercase tracking-wider">Order Items</h3>
<button type="button" onClick={handleAddItem} className="text-xs font-bold text-[#231651] hover:underline flex items-center gap-1">
<Plus size={14} /> Add Item
</button>
</div>
<div className="border border-[#e2e8f0] rounded-2xl overflow-hidden">
<table className="w-full text-left">
<thead className="bg-gray-50 border-b border-[#e2e8f0]">
<tr>
<th className="px-4 py-3 text-[10px] font-black text-[#64748b] uppercase">Product Name</th>
<th className="px-4 py-3 text-[10px] font-black text-[#64748b] uppercase w-32">Quantity</th>
<th className="px-4 py-3 text-[10px] font-black text-[#64748b] uppercase w-40">Rate</th>
<th className="px-4 py-3 text-[10px] font-black text-[#64748b] uppercase w-40">Total</th>
<th className="px-4 py-3 text-[10px] font-black text-[#64748b] uppercase w-16"></th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{newOrder.items.map((item, idx) => (
<tr key={idx}>
<td className="px-4 py-3">
<input type="text" placeholder="Product name..." value={item.productName} onChange={e => handleItemChange(idx, 'productName', e.target.value)} className="w-full bg-transparent text-sm font-bold outline-none" />
</td>
<td className="px-4 py-3">
<input type="number" value={item.quantity} onChange={e => handleItemChange(idx, 'quantity', parseFloat(e.target.value))} className="w-full bg-transparent text-sm font-bold outline-none" />
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-1">
<span className="text-[#94a3b8] text-sm"></span>
<input type="number" value={item.rate} onChange={e => handleItemChange(idx, 'rate', parseFloat(e.target.value))} className="w-full bg-transparent text-sm font-bold outline-none" />
</div>
</td>
<td className="px-4 py-3 text-sm font-black text-[#1e293b]">
{item.total.toLocaleString()}
</td>
<td className="px-4 py-3">
<button type="button" onClick={() => setNewOrder({...newOrder, items: newOrder.items.filter((_, i) => i !== idx)})} className="text-red-400 hover:text-red-600">
<Trash2 size={16} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-12 pt-4">
<div className="space-y-4">
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Reference ID</label>
<input type="text" value={newOrder.referenceId} onChange={e => setNewOrder({...newOrder, referenceId: e.target.value})} className="w-full px-4 py-3 bg-white border border-[#e2e8f0] rounded-xl text-sm font-bold outline-none focus:border-[#231651]" placeholder="Optional ref #" />
</div>
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Instruction</label>
<textarea rows={3} value={newOrder.instruction} onChange={e => setNewOrder({...newOrder, instruction: e.target.value})} className="w-full px-4 py-3 bg-white border border-[#e2e8f0] rounded-xl text-sm font-bold outline-none focus:border-[#231651]" placeholder="Any notes..." />
</div>
</div>
<div className="bg-slate-50 rounded-2xl p-6 space-y-4">
<div className="flex justify-between items-center text-sm">
<span className="font-bold text-[#64748b]">Subtotal</span>
<span className="font-black text-[#1e293b]">{newOrder.items.reduce((s, i) => s + i.total, 0).toLocaleString()}</span>
</div>
<div className="flex justify-between items-center text-sm">
<span className="font-bold text-[#64748b]">Discount</span>
<div className="flex items-center gap-2">
<span className="text-red-500 font-bold">-</span>
<input type="number" value={newOrder.discount} onChange={e => setNewOrder({...newOrder, discount: parseFloat(e.target.value) || 0})} className="w-24 text-right bg-white border border-[#e2e8f0] rounded-lg px-2 py-1 text-sm font-black text-red-500 outline-none" />
</div>
</div>
<div className="h-[1px] bg-[#e2e8f0] my-2"></div>
<div className="flex justify-between items-center">
<span className="font-black text-[#1e293b]">Net Amount</span>
<span className="text-xl font-black text-[#231651]">{calculateTotal().toLocaleString()}</span>
</div>
</div>
</div>
<div className="flex gap-4 pt-4">
<button type="button" onClick={() => setShowAddModal(false)} className="px-10 py-4 border-2 border-[#e2e8f0] text-[#64748b] font-bold rounded-2xl hover:bg-gray-50 transition-all">Cancel</button>
<button type="submit" disabled={isSaving} className="flex-1 px-10 py-4 bg-[#231651] text-white font-bold rounded-2xl shadow-xl shadow-[#231651]/20 hover:scale-[1.01] transition-all flex items-center justify-center gap-3">
{isSaving ? <Loader2 className="animate-spin" /> : <><CheckCircle size={20} /> Finalize Purchase Order</>}
</button>
</div>
</form>
</div>
</div>
)}
{showHistoryModal && activeHistoryOrder && (
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[110] flex items-center justify-center p-4">
<div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden animate-in zoom-in duration-300">
<div className="px-8 py-6 border-b border-[#e2e8f0] flex justify-between items-center bg-[#231651] text-white">
<div className="flex items-center gap-4">
<Eye size={20} />
<div>
<h2 className="text-xl font-bold">Audit History: {activeHistoryOrder.purchaseId}</h2>
<p className="text-xs text-indigo-200">Tracking amount adjustments</p>
</div>
</div>
<button onClick={() => setShowHistoryModal(false)} className="p-2 hover:bg-white/10 rounded-full transition-colors">
<X size={20} />
</button>
</div>
<div className="p-8 max-h-[60vh] overflow-y-auto">
{orderHistory.length === 0 ? (
<div className="text-center py-10 text-[#64748b]">
<p className="text-sm font-bold uppercase tracking-widest">No adjustments recorded</p>
<p className="text-xs mt-1 italic">This order amount hasn't changed since creation.</p>
</div>
) : (
<div className="space-y-6">
{orderHistory.map((h, i) => (
<div key={i} className="flex gap-4 relative">
{i !== orderHistory.length - 1 && (
<div className="absolute left-3 top-7 bottom-0 w-[2px] bg-slate-100 -mb-6"></div>
)}
<div className="w-6 h-6 rounded-full bg-indigo-100 flex-shrink-0 flex items-center justify-center z-10">
<div className="w-2 h-2 rounded-full bg-indigo-600"></div>
</div>
<div className="flex-1 pb-4">
<div className="flex justify-between items-start mb-2">
<span className="text-xs font-black text-[#231651] uppercase tracking-wider bg-slate-100 px-2 py-0.5 rounded">
{new Date(h.changeDate).toLocaleString()}
</span>
<span className="text-[10px] font-bold text-[#94a3b8] italic">Amount Change</span>
</div>
<div className="flex items-center gap-4 text-sm font-bold">
<span className="text-red-400">{h.oldAmount.toLocaleString()}</span>
<span className="text-[#94a3b8]"></span>
<span className="text-emerald-500">{h.newAmount.toLocaleString()}</span>
</div>
<p className="text-xs text-[#64748b] mt-1 italic">Reason: {h.reason}</p>
</div>
</div>
))}
</div>
)}
</div>
<div className="p-6 bg-slate-50 flex justify-end px-8">
<button onClick={() => setShowHistoryModal(false)} className="px-6 py-2 bg-[#231651] text-white rounded-xl text-sm font-bold">Close Record</button>
</div>
</div>
</div>
)}
</div>
);
};
export default Purchases;

View File

@@ -0,0 +1,313 @@
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
UserPlus,
Search,
Trash2,
Shield,
Mail,
Lock,
Check,
X,
LayoutGrid,
Receipt,
Users,
ShoppingBag,
ShoppingCart,
Wallet,
BarChart3,
Table2,
CreditCard,
Megaphone,
MessageSquare,
Store,
Contact
} from 'lucide-react';
interface StaffMember {
id: string;
name: string;
email: string; // Used as username
role: string;
permissions: string[];
viewOnly: boolean;
}
const Staff = () => {
const [staffList, setStaffList] = useState<StaffMember[]>([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [loading, setLoading] = useState(true);
// Form State
const [formData, setFormData] = useState({
name: '',
email: '', // Username
password: '',
viewOnly: false
});
const fetchStaff = async () => {
setLoading(true);
try {
const res = await fetch('/api/system/staff');
if (res.ok) {
const data = await res.json();
setStaffList(data);
}
} catch (err) {
console.error('Error fetching staff:', err);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchStaff();
}, []);
const handleCreateStaff = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch('/api/system/staff', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: formData.name,
email: formData.email,
password: formData.password,
viewOnly: formData.viewOnly,
permissions: [] // Staff will use a different portal, no internal permissions needed
})
});
if (response.ok) {
fetchStaff();
setIsModalOpen(false);
setFormData({ name: '', email: '', password: '', viewOnly: false });
} else {
alert('Failed to create staff member');
}
} catch (err) {
console.error('Create staff error:', err);
alert('Network error - make sure server is running');
}
};
const deleteStaff = async (id: string) => {
if (window.confirm('Are you sure you want to remove this staff member?')) {
try {
const response = await fetch(`/api/system/staff/${id}`, {
method: 'DELETE'
});
if (response.ok) {
fetchStaff();
}
} catch (err) {
console.error('Delete error:', err);
}
}
};
const filteredStaff = staffList.filter(s =>
s.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
s.email.toLowerCase().includes(searchQuery.toLowerCase())
);
return (
<div className="p-8 space-y-8 bg-[#f8fafc] min-h-screen font-inter">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-black text-[#231651]">Staff Management</h1>
<p className="text-[#64748b] text-sm mt-1">Manage your team members and their portal permissions</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center gap-2 bg-[#231651] text-white px-6 py-3 rounded-2xl font-bold shadow-xl shadow-[#231651]/20 hover:scale-105 transition-all"
>
<UserPlus size={20} />
<span>Add Staff Member</span>
</button>
</div>
{/* Search & Stats */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="md:col-span-2 relative group flex items-center">
<div className="absolute left-5 flex items-center justify-center pointer-events-none text-[#94a3b8]">
<Search size={20} />
</div>
<input
type="text"
placeholder="Search by name or username..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full h-14 bg-white border border-[#e2e8f0] rounded-2xl pl-14 pr-4 text-sm font-semibold outline-none transition-all focus:border-[#231651]/30 focus:shadow-md shadow-sm text-[#1e293b] placeholder:text-[#94a3b8]"
/>
</div>
<div className="bg-white p-4 rounded-2xl border border-[#e2e8f0] shadow-sm flex items-center justify-between">
<div>
<p className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Total Staff</p>
<h3 className="text-2xl font-black text-[#231651]">{staffList.length}</h3>
</div>
<div className="p-3 bg-indigo-50 text-indigo-600 rounded-xl">
<Contact size={24} />
</div>
</div>
</div>
{/* Staff List Table */}
<div className="bg-white rounded-3xl border border-[#e2e8f0] shadow-sm overflow-hidden">
<table className="w-full text-left">
<thead className="bg-gray-50 border-b border-[#e2e8f0]">
<tr>
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Team Member</th>
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Username</th>
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Access</th>
<th className="px-6 py-4"></th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{loading ? (
<tr><td colSpan={5} className="px-6 py-10 text-center text-[#94a3b8] font-bold">Loading staff data...</td></tr>
) : filteredStaff.length === 0 ? (
<tr><td colSpan={5} className="px-6 py-10 text-center text-[#94a3b8] font-bold">No staff members found matching your search</td></tr>
) : filteredStaff.map((staff) => (
<tr key={staff.id} className="hover:bg-gray-50/50 transition-colors">
<td className="px-6 py-5">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-[#231651] text-white flex items-center justify-center font-bold">
{staff.name.charAt(0)}
</div>
<div>
<p className="text-sm font-black text-[#1e293b]">{staff.name}</p>
<span className="text-[9px] font-black bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded uppercase tracking-tighter">ID: {staff.id}</span>
</div>
</div>
</td>
<td className="px-6 py-5">
<p className="text-xs font-bold text-[#1e293b]">{staff.email}</p>
</td>
<td className="px-6 py-5">
<span className={`px-2.5 py-1 rounded-full text-[10px] font-black uppercase tracking-wider ${staff.viewOnly ? 'bg-amber-50 text-amber-600' : 'bg-emerald-50 text-emerald-600'}`}>
{staff.viewOnly ? 'View Only' : 'Full Access'}
</span>
</td>
<td className="px-6 py-5 text-right">
<button
onClick={() => deleteStaff(staff.id)}
className="p-2 text-[#94a3b8] hover:text-red-600 hover:bg-red-50 rounded-xl transition-all"
>
<Trash2 size={18} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Add Staff Modal */}
<AnimatePresence>
{isModalOpen && (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setIsModalOpen(false)}
className="absolute inset-0 bg-[#1e293b]/60 backdrop-blur-sm"
/>
<motion.div
initial={{ opacity: 0, scale: 0.9, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
className="relative bg-white w-full max-w-2xl rounded-[2.5rem] shadow-2xl overflow-hidden"
>
<div className="p-8 md:p-10 max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-start mb-8">
<div>
<h2 className="text-2xl font-black text-[#1e293b]">Add New <span className="text-[#231651]">Staff Member</span></h2>
<p className="text-xs font-bold text-gray-400 mt-1">Configure account details and portal access</p>
</div>
<button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-gray-100 rounded-full transition-colors text-[#94a3b8]">
<X size={24} />
</button>
</div>
<form onSubmit={handleCreateStaff} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="space-y-2">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Name</label>
<input
required
type="text"
value={formData.name}
onChange={(e) => setFormData({...formData, name: e.target.value})}
placeholder="John Doe"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 px-4 text-sm font-semibold outline-none transition-all"
/>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Username (Email)</label>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8]">
<Mail size={16} />
</div>
<input
required
type="email"
value={formData.email}
onChange={(e) => setFormData({...formData, email: e.target.value})}
placeholder="staff@rit.edu"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-11 pr-4 text-sm font-semibold outline-none transition-all"
/>
</div>
</div>
</div>
<div className="space-y-2">
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Password</label>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8]">
<Lock size={16} />
</div>
<input
required
type="password"
value={formData.password}
onChange={(e) => setFormData({...formData, password: e.target.value})}
placeholder="••••••••"
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-11 pr-4 text-sm font-semibold outline-none transition-all"
/>
</div>
</div>
<div className="flex items-center gap-3 py-2">
<div
onClick={() => setFormData({...formData, viewOnly: !formData.viewOnly})}
className={`w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-all ${formData.viewOnly ? "bg-[#231651] border-[#231651]" : "border-[#e2e8f0]"}`}
>
{formData.viewOnly && <Check size={14} className="text-white" />}
</div>
<span className="text-sm font-bold text-[#64748b]">View only access</span>
</div>
<div className="pt-4 pb-2">
<button
type="submit"
className="w-full bg-[#231651] text-white rounded-2xl py-4 font-black text-sm shadow-xl shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all"
>
Create Staff Account
</button>
</div>
</form>
</div>
</motion.div>
</div>
)}
</AnimatePresence>
</div>
);
};
export default Staff;

View File

@@ -0,0 +1,786 @@
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
Plus,
MoreVertical,
Store,
Image as ImageIcon,
X,
Edit2,
Trash2,
Check,
Loader2,
Package,
Layers,
Search as SearchIcon,
Clock,
Calendar,
AlertCircle
} from 'lucide-react';
interface BaseItem {
id: number;
name: string;
}
interface Product {
id: number;
name: string;
category: string;
price: number;
}
interface StallSession {
id?: number;
dayOfWeek: string;
active: boolean;
startTime: string;
endTime: string;
}
interface Stall {
id: number;
name: string;
description: string;
imageData?: string;
active: boolean;
temporarilyClosed: boolean;
sessionOptional: boolean;
sessions: StallSession[];
products: Product[];
baseItems: BaseItem[];
}
const DAYS = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
const getDefaultSessions = (): StallSession[] =>
DAYS.map(day => ({ dayOfWeek: day, active: true, startTime: '00:00', endTime: '23:59' }));
const Stalls: React.FC = () => {
const [stalls, setStalls] = useState<Stall[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [isModalOpen, setIsModalOpen] = useState(false);
const [editingStall, setEditingStall] = useState<Stall | null>(null);
// Form State
const [formData, setFormData] = useState({
name: '',
description: '',
imageData: '' as string | undefined,
temporarilyClosed: false,
sessionOptional: false,
sessions: getDefaultSessions()
});
const [isSaving, setIsSaving] = useState(false);
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
const [showSessionModal, setShowSessionModal] = useState(false);
// Item Linking State
const [isItemModalOpen, setIsItemModalOpen] = useState(false);
const [selectedStall, setSelectedStall] = useState<Stall | null>(null);
const [allProducts, setAllProducts] = useState<Product[]>([]);
const [allBaseItems, setAllBaseItems] = useState<BaseItem[]>([]);
const [tempProductIds, setTempProductIds] = useState<number[]>([]);
const [tempBaseItemIds, setTempBaseItemIds] = useState<number[]>([]);
const [itemSearchQuery, setItemSearchQuery] = useState('');
const [activeTab, setActiveTab] = useState<'products' | 'baseItems'>('products');
useEffect(() => {
fetchStalls();
}, []);
const fetchStalls = async () => {
try {
setLoading(true);
const host = window.location.hostname;
const response = await fetch(`http://${host}:8080/api/stalls`);
if (response.ok) {
const data = await response.json();
setStalls(data);
}
} catch (error) {
console.error('Error fetching stalls:', error);
} finally {
setLoading(false);
}
};
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onloadend = () => {
setFormData(prev => ({ ...prev, imageData: reader.result as string }));
};
reader.readAsDataURL(file);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSaving(true);
try {
const host = window.location.hostname;
const url = editingStall
? `http://${host}:8080/api/stalls/${editingStall.id}`
: `http://${host}:8080/api/stalls`;
const response = await fetch(url, {
method: editingStall ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...formData,
active: true
})
});
if (response.ok) {
setIsModalOpen(false);
setEditingStall(null);
setFormData({
name: '',
description: '',
imageData: '',
temporarilyClosed: false,
sessionOptional: false,
sessions: getDefaultSessions()
});
fetchStalls();
}
} catch (error) {
console.error('Error saving stall:', error);
} finally {
setIsSaving(false);
}
};
const handleEdit = (stall: Stall) => {
setOpenMenuId(null);
setEditingStall(stall);
setFormData({
name: stall.name,
description: stall.description,
imageData: stall.imageData,
temporarilyClosed: stall.temporarilyClosed,
sessionOptional: stall.sessionOptional,
sessions: stall.sessions && stall.sessions.length > 0 ? stall.sessions : getDefaultSessions()
});
setIsModalOpen(true);
};
const handleDelete = async (id: number) => {
if (!window.confirm('Are you sure you want to delete this stall?')) return;
try {
const host = window.location.hostname;
const response = await fetch(`http://${host}:8080/api/stalls/${id}`, {
method: 'DELETE'
});
if (response.ok) {
fetchStalls();
}
} catch (error) {
console.error('Error deleting stall:', error);
}
};
const openLinkModal = async (stall: Stall) => {
setOpenMenuId(null);
setSelectedStall(stall);
setTempProductIds(stall.products?.map(p => p.id) || []);
setTempBaseItemIds(stall.baseItems?.map(b => b.id) || []);
setIsItemModalOpen(true);
try {
const host = window.location.hostname;
const [prodRes, baseRes] = await Promise.all([
fetch(`http://${host}:8080/api/products`),
fetch(`http://${host}:8080/api/base-items`)
]);
if (prodRes.ok) setAllProducts(await prodRes.json());
if (baseRes.ok) setAllBaseItems(await baseRes.json());
} catch (error) {
console.error('Error fetching available items:', error);
}
};
const saveItemAssociations = async () => {
if (!selectedStall) return;
setIsSaving(true);
try {
const host = window.location.hostname;
const response = await fetch(`http://${host}:8080/api/stalls/${selectedStall.id}/items`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
productIds: tempProductIds,
baseItemIds: tempBaseItemIds
})
});
if (response.ok) {
setIsItemModalOpen(false);
fetchStalls();
} else {
const errorData = await response.json();
window.alert(`Failed to save inventory: ${errorData.message || 'Unknown error'}`);
}
} catch (error) {
console.error('Error updating stall items:', error);
window.alert('A network error occurred while updating stall inventory.');
} finally {
setIsSaving(false);
}
};
const filteredStalls = stalls.filter(s =>
s.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
s.description.toLowerCase().includes(searchQuery.toLowerCase())
);
const isStallOpen = (stall: Stall) => {
if (stall.temporarilyClosed) return false;
if (!stall.sessionOptional) return true;
const now = new Date();
const currentDay = DAYS[now.getDay()];
const currentTimeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
const session = stall.sessions?.find(s => s.dayOfWeek === currentDay);
if (!session || !session.active) return false;
return currentTimeStr >= session.startTime && currentTimeStr <= session.endTime;
};
const updateSession = (index: number, updates: Partial<StallSession>) => {
const newSessions = [...formData.sessions];
newSessions[index] = { ...newSessions[index], ...updates };
setFormData({ ...formData, sessions: newSessions });
};
return (
<div className="flex flex-col h-full bg-[#f8fafc] p-8 gap-8 animate-in fade-in duration-500 overflow-y-auto font-inter">
{/* Header Section */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6 max-w-[1600px]">
<div className="flex items-center gap-5">
<div className="w-14 h-14 bg-[#231651] rounded-xl flex items-center justify-center shadow-lg shadow-[#231651]/20">
<Store className="text-white w-7 h-7" />
</div>
<div>
<h1 className="text-2xl font-bold text-[#1e293b]">Stalls Management</h1>
<p className="text-sm text-[#64748b]">Configure and manage your independent canteen service counters</p>
</div>
</div>
<div className="flex items-center gap-4">
<div className="relative group min-w-[320px]">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8] group-focus-within:text-[#231651] transition-colors" size={18} />
<input
type="text"
placeholder="Search stalls..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full pl-10 pr-4 py-2 bg-white border border-[#e2e8f0] rounded-xl text-sm focus:outline-none focus:border-[#231651]/30 transition-all shadow-sm"
/>
</div>
<button
onClick={() => {
setEditingStall(null);
setFormData({
name: '',
description: '',
imageData: '',
temporarilyClosed: false,
sessionOptional: false,
sessions: getDefaultSessions()
});
setIsModalOpen(true);
}}
className="px-6 py-2.5 bg-[#231651] text-white rounded-xl font-bold text-sm flex items-center gap-2 shadow-lg shadow-[#231651]/20 hover:scale-[1.01] active:scale-95 transition-all"
>
<Plus size={18} /> Add Stall
</button>
</div>
</div>
{/* Main Grid Area */}
<div className="max-w-[1600px]">
{loading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{[1, 2, 3, 4].map(i => (
<div key={i} className="bg-white rounded-2xl h-[350px] animate-pulse border border-[#e2e8f0]" />
))}
</div>
) : filteredStalls.length === 0 ? (
<div className="bg-white rounded-xl p-24 text-center border border-[#e2e8f0] shadow-sm">
<Store size={48} className="text-slate-200 mx-auto mb-4" />
<h3 className="text-lg font-bold text-slate-800 mb-1">No stalls established</h3>
<p className="text-slate-500 text-sm">Start by adding your first service counter.</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
{filteredStalls.map(stall => (
<div
key={stall.id}
onClick={() => openLinkModal(stall)}
className="group cursor-pointer bg-white rounded-2xl overflow-hidden border border-[#e2e8f0] hover:border-[#231651]/30 transition-all hover:shadow-xl flex flex-col relative"
>
{/* Image Section */}
<div className="h-48 bg-slate-50 relative overflow-hidden flex items-center justify-center border-b border-[#e2e8f0]">
{stall.imageData ? (
<img src={stall.imageData} alt={stall.name} className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" />
) : (
<Store size={40} className="text-slate-200" />
)}
<div className="absolute top-4 right-4 z-10" onClick={(e) => e.stopPropagation()}>
<button
disabled={isModalOpen || isItemModalOpen}
onClick={() => setOpenMenuId(openMenuId === stall.id ? null : stall.id)}
className={`w-9 h-9 bg-white shadow-lg rounded-xl flex items-center justify-center text-slate-600 hover:bg-slate-50 transition-colors border border-[#e2e8f0] ${(isModalOpen || isItemModalOpen) ? 'opacity-20 cursor-not-allowed cursor-default filter blur-md pointer-events-none' : ''}`}
>
<MoreVertical size={16} />
</button>
<AnimatePresence>
{openMenuId === stall.id && (
<motion.div
initial={{ opacity: 0, scale: 0.95, y: -10 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: -10 }}
className="absolute right-0 mt-2 w-40 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-20 overflow-hidden"
>
<button onClick={() => handleEdit(stall)} className="w-full flex items-center gap-2.5 px-4 py-3 text-xs font-bold text-[#475569] hover:bg-gray-50 transition-colors border-b border-[#f1f5f9]">
<Edit2 size={14} className="text-indigo-500" /> Edit Details
</button>
<button onClick={() => handleDelete(stall.id)} className="w-full flex items-center gap-2.5 px-4 py-3 text-xs font-bold text-rose-600 hover:bg-rose-50 transition-colors">
<Trash2 size={14} /> Delete
</button>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
{/* Content Section */}
<div className="p-6 flex-1 flex flex-col">
<div className="flex justify-between items-start mb-2">
<h3 className="text-lg font-bold text-[#1e293b] truncate">{stall.name}</h3>
<div className={`px-2 py-0.5 text-[10px] font-bold rounded-lg border uppercase tracking-wider ${
isStallOpen(stall)
? 'bg-green-50 text-green-600 border-green-100'
: 'bg-rose-50 text-rose-600 border-rose-100'
}`}>
{stall.temporarilyClosed ? 'Closed' : isStallOpen(stall) ? 'Active' : 'Offline'}
</div>
</div>
<p className="text-[#64748b] text-sm font-medium line-clamp-2 leading-relaxed mb-6 h-10">
{stall.description || 'Dedicated food service counter for our premium canteen offerings.'}
</p>
<div className="mt-auto pt-4 border-t border-[#f1f5f9] flex items-center justify-between">
<div className="flex gap-4">
<div className="flex flex-col">
<span className="text-[10px] uppercase font-bold text-[#94a3b8] tracking-wider">Products</span>
<span className="text-sm font-bold text-[#1e293b]">{stall.products?.length || 0}</span>
</div>
<div className="w-[1px] h-8 bg-[#f1f5f9]" />
<div className="flex flex-col">
<span className="text-[10px] uppercase font-bold text-[#94a3b8] tracking-wider">Base Items</span>
<span className="text-sm font-bold text-[#1e293b]">{stall.baseItems?.length || 0}</span>
</div>
</div>
<div className="w-9 h-9 bg-gray-50 border border-[#e2e8f0] rounded-xl flex items-center justify-center text-[#231651] group-hover:border-[#231651] group-hover:bg-indigo-50 group-hover:text-indigo-600 transition-all shadow-sm">
<Plus size={16} strokeWidth={3} />
</div>
</div>
</div>
</div>
))}
</div>
)}
</div>
{/* Edit Stall Modal - Replicated from Customer Design */}
<AnimatePresence>
{isModalOpen && (
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4 overflow-y-auto">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden my-auto"
>
<div className="px-10 py-8 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-[#231651]/5 rounded-xl flex items-center justify-center text-[#231651]">
<Store size={24} />
</div>
<div>
<h2 className="text-2xl font-bold text-[#1e293b]">{editingStall ? 'Edit Stall' : 'Create New Stall'}</h2>
<p className="text-sm text-[#64748b]">Configure your canteen service counter details</p>
</div>
</div>
<button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-gray-200 rounded-full transition-colors">
<X size={24} className="text-[#64748b]" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-10 space-y-8">
<div className="space-y-6">
<div>
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-2.5 tracking-widest ml-1">Stall Name</label>
<input
required
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full px-5 py-4 bg-slate-50 border border-[#e2e8f0] rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none"
placeholder="e.g. Continental Corner"
/>
</div>
<div>
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-2.5 tracking-widest ml-1">Description</label>
<textarea
required
rows={3}
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
className="w-full px-5 py-4 bg-slate-50 border border-[#e2e8f0] rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none resize-none"
placeholder="Briefly describe the counter's specialty..."
/>
</div>
<div className="p-6 bg-slate-50 rounded-[2rem] border border-[#e2e8f0] border-dashed">
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-4 tracking-widest ml-1">Visual Branding</label>
<div className="flex items-center gap-6">
<div className="w-24 h-24 bg-white rounded-2xl border border-[#e2e8f0] flex items-center justify-center overflow-hidden relative group shadow-sm">
{formData.imageData ? (
<>
<img src={formData.imageData} alt="Preview" className="w-full h-full object-cover" />
<button type="button" onClick={() => setFormData({ ...formData, imageData: '' })} className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center text-white">
<X size={20} />
</button>
</>
) : (
<ImageIcon size={32} className="text-slate-200" />
)}
</div>
<div className="flex-1">
<input type="file" id="stall-image" hidden accept="image/*" onChange={handleImageChange} />
<label htmlFor="stall-image" className="inline-flex items-center gap-2 px-6 py-2.5 bg-white border border-[#e2e8f0] rounded-xl font-bold text-xs text-slate-600 hover:bg-gray-50 hover:border-slate-300 cursor-pointer shadow-sm transition-all active:scale-95">
<ImageIcon size={14} /> Upload Banner
</label>
<p className="mt-3 text-[10px] text-slate-400 font-medium tracking-wide">Recommended aspect ratio 4:3 (Max 2MB)</p>
</div>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 pt-2">
<div className={`p-6 rounded-2xl border transition-all ${formData.temporarilyClosed ? 'bg-rose-50 border-rose-200' : 'bg-slate-50 border-[#e2e8f0]'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-3">
<div className={`p-2 rounded-lg ${formData.temporarilyClosed ? 'bg-rose-100 text-rose-600' : 'bg-white text-slate-400'}`}>
<AlertCircle size={18} />
</div>
<span className="text-sm font-bold text-[#1e293b]">Quick Close</span>
</div>
<button
type="button"
onClick={() => setFormData({ ...formData, temporarilyClosed: !formData.temporarilyClosed })}
className={`w-11 h-6 rounded-full relative transition-all ${formData.temporarilyClosed ? 'bg-rose-500' : 'bg-gray-300'}`}
>
<div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${formData.temporarilyClosed ? 'translate-x-5' : ''}`} />
</button>
</div>
<p className="text-[11px] text-[#64748b] font-medium leading-relaxed">Manually mark this stall as closed, overriding all schedules.</p>
</div>
<div className={`p-6 rounded-2xl border transition-all ${formData.sessionOptional ? 'bg-indigo-50 border-indigo-200' : 'bg-slate-50 border-[#e2e8f0]'}`}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-3">
<div className={`p-2 rounded-lg ${formData.sessionOptional ? 'bg-indigo-100 text-indigo-600' : 'bg-white text-slate-400'}`}>
<Clock size={18} />
</div>
<span className="text-sm font-bold text-[#1e293b]">Automated Schedule</span>
</div>
<button
type="button"
onClick={() => setFormData({ ...formData, sessionOptional: !formData.sessionOptional })}
className={`w-11 h-6 rounded-full relative transition-all ${formData.sessionOptional ? 'bg-indigo-600' : 'bg-gray-300'}`}
>
<div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${formData.sessionOptional ? 'translate-x-5' : ''}`} />
</button>
</div>
{formData.sessionOptional ? (
<button
type="button"
onClick={() => setShowSessionModal(true)}
className="mt-2 w-full py-2 bg-white border border-indigo-200 text-indigo-600 rounded-xl text-xs font-bold hover:bg-indigo-50 transition-all flex items-center justify-center gap-2"
>
<Calendar size={14} /> Configure Hours
</button>
) : (
<p className="text-[11px] text-[#64748b] font-medium leading-relaxed">Let the counter open/close automatically based on time.</p>
)}
</div>
</div>
</div>
<div className="flex gap-4 pt-6">
<button
type="button"
onClick={() => setIsModalOpen(false)}
className="flex-1 px-8 py-4 border-2 border-[#e2e8f0] text-[#64748b] font-bold rounded-2xl hover:bg-gray-50 transition-all text-sm"
>
Discard
</button>
<button
type="submit"
disabled={isSaving}
className="flex-[1.5] px-8 py-4 bg-[#231651] text-white font-bold rounded-2xl shadow-xl shadow-[#231651]/20 hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-3 text-sm"
>
{isSaving ? (
<><Loader2 size={20} className="animate-spin" /> Saving...</>
) : (
editingStall ? 'Update Stall' : 'Create Stall'
)}
</button>
</div>
</form>
</motion.div>
</div>
)}
</AnimatePresence>
{/* Item Configuration Modal - Resized but same style */}
<AnimatePresence>
{isItemModalOpen && selectedStall && (
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[150] flex items-center justify-center p-4 overflow-y-auto">
<motion.div
initial={{ opacity: 0, scale: 0.95, y: 30 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.95, y: 30 }}
className="bg-white rounded-3xl w-full max-w-4xl shadow-2xl overflow-hidden flex flex-col h-[85vh] my-auto"
>
<div className="px-10 py-8 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<div className="flex items-center gap-4">
<div className="w-12 h-12 bg-[#231651]/5 rounded-xl flex items-center justify-center text-[#231651]">
<Package size={24} />
</div>
<div>
<h2 className="text-2xl font-bold text-[#1e293b]">Inventory: {selectedStall.name}</h2>
<p className="text-sm text-[#64748b]">Configure available items and stock for this counter</p>
</div>
</div>
<button onClick={() => setIsItemModalOpen(false)} className="p-2 hover:bg-gray-200 rounded-full transition-colors">
<X size={24} className="text-[#64748b]" />
</button>
</div>
<div className="flex-1 overflow-hidden flex flex-col p-10 gap-8">
{/* Selection Controls */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
<div className="flex p-1 bg-gray-100 rounded-xl w-fit">
<button
onClick={() => setActiveTab('products')}
className={`px-8 py-2.5 rounded-lg text-xs font-bold transition-all ${
activeTab === 'products' ? 'bg-[#231651] text-white shadow-md' : 'text-[#64748b] hover:text-[#231651]'
}`}
>
Products ({allProducts.length})
</button>
<button
onClick={() => setActiveTab('baseItems')}
className={`px-8 py-2.5 rounded-lg text-xs font-bold transition-all ${
activeTab === 'baseItems' ? 'bg-[#231651] text-white shadow-md' : 'text-[#64748b] hover:text-[#231651]'
}`}
>
Base Items ({allBaseItems.length})
</button>
</div>
<div className="relative flex-1 max-w-md">
<SearchIcon className="absolute left-4 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={18} />
<input
type="text"
placeholder={`Search ${activeTab === 'products' ? 'products' : 'items'}...`}
value={itemSearchQuery}
onChange={(e) => setItemSearchQuery(e.target.value)}
className="w-full pl-12 pr-4 py-2 bg-white border border-[#e2e8f0] rounded-xl text-sm focus:outline-none focus:border-[#231651] transition-all"
/>
</div>
</div>
{/* Selection Grid */}
<div className="flex-1 overflow-y-auto pr-2 custom-scrollbar bg-slate-50/50 rounded-2xl border border-[#e2e8f0] p-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-4">
{activeTab === 'products' ? (
allProducts
.filter(p => p.name.toLowerCase().includes(itemSearchQuery.toLowerCase()))
.map(product => {
const isSelected = tempProductIds.includes(product.id);
return (
<div
key={product.id}
onClick={() => setTempProductIds(prev => isSelected ? prev.filter(id => id !== product.id) : [...prev, product.id])}
className={`p-5 rounded-xl border-2 transition-all flex items-center justify-between cursor-pointer group hover:scale-[1.01] ${isSelected ? 'bg-white border-[#231651] shadow-lg shadow-[#231651]/5' : 'bg-white border-transparent hover:border-[#e2e8f0]'}`}
>
<div className="flex items-center gap-4">
<div className={`w-11 h-11 rounded-lg flex items-center justify-center transition-colors ${isSelected ? 'bg-[#231651] text-white' : 'bg-gray-100 text-slate-400'}`}>
<Package size={20} />
</div>
<div>
<p className="font-bold text-[#1e293b] text-sm">{product.name}</p>
<p className="text-[10px] font-bold text-[#94a3b8] uppercase tracking-wider">{product.price} {product.category}</p>
</div>
</div>
<div className={`w-6 h-6 rounded flex items-center justify-center border-2 transition-all ${isSelected ? 'bg-[#231651] border-[#231651]' : 'border-slate-200 bg-white'}`}>
{isSelected && <Check size={14} className="text-white" strokeWidth={4} />}
</div>
</div>
)
})
) : (
allBaseItems
.filter(b => b.name.toLowerCase().includes(itemSearchQuery.toLowerCase()))
.map(baseItem => {
const isSelected = tempBaseItemIds.includes(baseItem.id);
return (
<div
key={baseItem.id}
onClick={() => setTempBaseItemIds(prev => isSelected ? prev.filter(id => id !== baseItem.id) : [...prev, baseItem.id])}
className={`p-5 rounded-xl border-2 transition-all flex items-center justify-between cursor-pointer group hover:scale-[1.01] ${isSelected ? 'bg-white border-[#231651] shadow-lg shadow-[#231651]/5' : 'bg-white border-transparent hover:border-[#e2e8f0]'}`}
>
<div className="flex items-center gap-4">
<div className={`w-11 h-11 rounded-lg flex items-center justify-center transition-colors ${isSelected ? 'bg-[#231651] text-white' : 'bg-gray-100 text-slate-400'}`}>
<Layers size={20} />
</div>
<p className="font-bold text-[#1e293b] text-sm">{baseItem.name}</p>
</div>
<div className={`w-6 h-6 rounded flex items-center justify-center border-2 transition-all ${isSelected ? 'bg-[#231651] border-[#231651]' : 'border-slate-200 bg-white'}`}>
{isSelected && <Check size={14} className="text-white" strokeWidth={4} />}
</div>
</div>
)
})
)}
</div>
</div>
</div>
{/* Modal Footer */}
<div className="px-10 py-6 bg-gray-50 border-t border-[#e2e8f0] flex items-center justify-between">
<div className="flex items-center gap-6">
<div className="flex flex-col">
<span className="text-[10px] uppercase font-bold text-[#94a3b8] tracking-widest">Active Selections</span>
<span className="text-sm font-bold text-[#231651]">{tempProductIds.length} Products, {tempBaseItemIds.length} Items</span>
</div>
</div>
<div className="flex gap-4">
<button onClick={() => setIsItemModalOpen(false)} className="px-6 py-2.5 text-slate-400 font-bold hover:text-slate-600 transition-colors uppercase tracking-[0.1em] text-[10px]">
Cancel
</button>
<button
onClick={saveItemAssociations}
disabled={isSaving}
className="px-8 py-2.5 bg-[#231651] text-white font-bold rounded-xl shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all text-sm flex items-center gap-2"
>
{isSaving ? <Loader2 size={16} className="animate-spin" /> : <><Check size={16} strokeWidth={3} /> Save Inventory</>}
</button>
</div>
</div>
</motion.div>
</div>
)}
</AnimatePresence>
{/* Session Configuration Modal */}
<AnimatePresence>
{showSessionModal && (
<div className="fixed inset-0 bg-[#231651]/40 backdrop-blur-md z-[200] flex items-center justify-center p-4">
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="bg-white rounded-[40px] w-full max-w-4xl shadow-2xl overflow-hidden"
>
<div className="p-10">
<div className="flex justify-between items-center mb-8">
<div>
<h2 className="text-2xl font-bold text-[#1e293b]">Operating Hours</h2>
<p className="text-sm text-[#64748b]">Select the days and times this counter will be active</p>
</div>
<button onClick={() => setShowSessionModal(false)} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
<X size={24} className="text-[#64748b]" />
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-h-[60vh] overflow-y-auto px-2 custom-scrollbar">
{formData.sessions.map((session, index) => (
<div key={session.dayOfWeek} className={`p-6 rounded-3xl border-2 transition-all ${session.active ? 'border-indigo-100 bg-indigo-50/30' : 'border-slate-100 bg-slate-50/50 opacity-60'}`}>
<div className="flex items-center justify-between mb-6">
<span className="text-lg font-bold text-[#1e293b]">{session.dayOfWeek}</span>
<div
onClick={() => updateSession(index, { active: !session.active })}
className={`w-12 h-6 rounded-full relative cursor-pointer transition-all ${session.active ? 'bg-indigo-600' : 'bg-slate-300'}`}
>
<div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${session.active ? 'translate-x-6' : ''}`} />
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="relative">
<label className="block text-[10px] font-bold text-[#94a3b8] mb-1.5 uppercase ml-1">Start Time</label>
<div className="flex items-center px-4 py-3 bg-white border border-[#e2e8f0] rounded-2xl">
<input
type="time"
disabled={!session.active}
value={session.startTime}
onChange={(e) => updateSession(index, { startTime: e.target.value })}
className="bg-transparent border-none outline-none text-sm font-bold text-[#1e293b] w-full disabled:text-gray-300"
/>
<Clock size={16} className={session.active ? "text-indigo-400" : "text-slate-200"} />
</div>
</div>
<div className="relative">
<label className="block text-[10px] font-bold text-[#94a3b8] mb-1.5 uppercase ml-1">End Time</label>
<div className="flex items-center px-4 py-3 bg-white border border-[#e2e8f0] rounded-2xl">
<input
type="time"
disabled={!session.active}
value={session.endTime}
onChange={(e) => updateSession(index, { endTime: e.target.value })}
className="bg-transparent border-none outline-none text-sm font-bold text-[#1e293b] w-full disabled:text-gray-300"
/>
<Clock size={16} className={session.active ? "text-indigo-400" : "text-slate-200"} />
</div>
</div>
</div>
</div>
))}
</div>
<div className="flex justify-end gap-4 mt-10">
<button onClick={() => setShowSessionModal(false)} className="px-10 py-4 bg-[#231651] text-white font-bold rounded-2xl shadow-xl shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all">
Done
</button>
</div>
</div>
</motion.div>
</div>
)}
</AnimatePresence>
<style dangerouslySetInnerHTML={{ __html: `
.custom-scrollbar::-webkit-scrollbar { width: 4px; }
.custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
.custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
` }} />
</div>
);
};
export default Stalls;

View File

@@ -0,0 +1,342 @@
import { useState, useEffect } from 'react';
import {
ChevronRight,
ShoppingBag,
Wallet,
ArrowRight,
RotateCcw,
Star
} from 'lucide-react';
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
PieChart,
Pie,
Cell
} from 'recharts';
import { motion } from 'framer-motion';
const salesData = [
{ time: '12am', value: 0 },
{ time: '2am', value: 0 },
{ time: '4am', value: 0 },
{ time: '6am', value: 0 },
{ time: '8am', value: 5000 },
{ time: '10am', value: 16000 },
{ time: '12pm', value: 6000 },
];
const trendingItems = [
{ name: "GHEE ROAST", category: "BREAK FAST", qty: 64, image: "https://images.unsplash.com/photo-1668236543090-82eba5ee5976?w=200&q=80" },
{ name: "KAL DOSA (2pcs)", category: "BREAK FAST", qty: 60, image: "https://images.unsplash.com/photo-1589301760014-d929f3979dbc?w=200&q=80" },
{ name: "VEG S.W", category: "SNACKS", qty: 51, image: "https://images.unsplash.com/photo-1528735602780-2552fd46c7af?w=200&q=80" },
{ name: "PLAIN DOSA", category: "BREAK FAST", qty: 51, image: "https://images.unsplash.com/photo-1610192244261-3f33de3f55e4?w=200&q=80" }
];
const StoreDashboard = () => {
const [activeTab, setActiveTab] = useState('Sales');
const [timeRange, setTimeRange] = useState('Today');
const [stats, setStats] = useState({
totalSales: 48438,
activeOrders: 912,
dailyCustomers: 813,
revenueGrowth: 12.5
});
useEffect(() => {
const fetchStats = async () => {
try {
const response = await fetch('/api/dashboard/stats');
if (response.ok) {
const data = await response.json();
// Find RIT Canteen in storeOverview if available, otherwise use general stats
if (data.storeOverview && data.storeOverview.length > 0) {
const ritStore = data.storeOverview.find((s: any) => s.name === 'RIT Canteen');
if (ritStore) {
setStats({
totalSales: ritStore.sale,
activeOrders: ritStore.orders,
dailyCustomers: ritStore.orders * 0.9, // Approximation
revenueGrowth: 12.5
});
} else {
setStats(data.stats);
}
} else {
setStats(data.stats);
}
}
} catch (error) {
console.error('Error fetching dashboard stats:', error);
}
};
fetchStats();
}, []);
const pieData = [
{ name: 'Full Payment', value: stats.totalSales, color: '#8b5cf6' },
{ name: 'Credit', value: 0, color: '#fbbf24' }
];
const insights = [
{ text: `${stats.activeOrders} orders at RIT Canteen! Clearly the crowd's found their happy place 💃🕺`, color: "bg-rose-50 text-rose-600 border-rose-100" },
{ text: `${(stats.totalSales / (stats.activeOrders || 1)).toFixed(2)} average order value at RIT Canteen! Either everyone's hungry or just living large 🔥😋`, color: "bg-emerald-50 text-emerald-600 border-emerald-100" },
{ text: `RIT Canteen had ${stats.activeOrders} orders but only ${Math.round(stats.dailyCustomers)} customers — Maybe customers are shy and didn't give their names 🥰`, color: "bg-orange-50 text-orange-600 border-orange-100" },
{ text: `RIT Canteen clocked ₹${stats.totalSales.toLocaleString()} — ka-ching! That's called business booming 💸📈`, color: "bg-blue-50 text-blue-600 border-blue-100" },
{ text: "RIT Canteen reaches its morning sales peak around 9AM — breakfast rush in full swing 🍳🥞", color: "bg-indigo-50 text-indigo-600 border-indigo-100" }
];
return (
<div className="p-8 space-y-8 bg-slate-50/50 min-h-screen font-inter">
{/* Top Header */}
<div className="flex items-center justify-between">
<div className="flex flex-col">
<div className="flex items-center gap-2 mb-1">
<button title="Return to previous screen" className="p-1.5 hover:bg-slate-100 rounded-lg transition-all">
<ArrowRight className="rotate-180 text-slate-400" size={18} />
</button>
<h2 className="text-xs font-black text-[#521c4b] uppercase tracking-widest">Store Dashboard</h2>
</div>
<h1 className="text-2xl font-black text-slate-800">Good morning, RIT Canteen</h1>
</div>
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<div className="relative group">
<select title="Switch established store location" className="appearance-none bg-white border border-slate-200 rounded-xl px-4 py-2 pr-10 text-xs font-bold text-slate-600 outline-none focus:border-[#521c4b] transition-all cursor-pointer shadow-sm">
<option>RIT Canteen</option>
</select>
<div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
<ChevronRight size={14} className="rotate-90 text-slate-400" />
</div>
</div>
<div className="relative group">
<select title="Toggle between available display views" className="appearance-none bg-white border border-slate-200 rounded-xl px-4 py-2 pr-10 text-xs font-bold text-slate-600 outline-none focus:border-[#521c4b] transition-all cursor-pointer shadow-sm">
<option>All</option>
</select>
<div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
<ChevronRight size={14} className="rotate-90 text-slate-400" />
</div>
</div>
</div>
<div className="flex items-center gap-2">
<button title="Synchronize latest live data from backend" className="p-2 bg-white border border-slate-200 rounded-xl text-slate-400 hover:text-slate-600 transition-all shadow-sm">
<RotateCcw size={18} />
</button>
<button title="Mark this store dashboard as favorite for quick access" className="p-2 bg-white border border-slate-200 rounded-xl text-amber-500 hover:scale-110 transition-all shadow-sm">
<Star size={18} fill="#f59e0b" />
</button>
</div>
<div title="Authenticated User: Abiram" className="w-8 h-8 rounded-full bg-[#521c4b] text-white flex items-center justify-center font-bold text-sm shadow-md cursor-pointer hover:ring-2 ring-[#521c4b]/20 transition-all">
A
</div>
</div>
</div>
{/* Main Stats Grid */}
<div className="grid grid-cols-12 gap-6">
{/* Sales Chart Section */}
<div className="col-span-12 lg:col-span-5 bg-white p-6 rounded-[32px] border border-slate-100 shadow-sm relative overflow-hidden group">
<div className="flex items-center gap-8 mb-8 border-b border-slate-50">
{['Sales', 'Payments'].map(tab => (
<button
key={tab}
title={`Visualize ${tab.toLowerCase()} throughput data`}
onClick={() => setActiveTab(tab)}
className={`pb-4 text-[11px] font-black uppercase tracking-widest transition-all relative ${activeTab === tab ? 'text-[#521c4b]' : 'text-slate-400 hover:text-slate-600'}`}
>
{tab}
{activeTab === tab && (
<motion.div layoutId="tabLineStore" className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#521c4b]" />
)}
</button>
))}
</div>
<div className="h-[280px] w-full mt-4">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={salesData}>
<defs>
<linearGradient id="colorSalesStore" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#f43f5e" stopOpacity={0.2}/>
<stop offset="95%" stopColor="#f43f5e" stopOpacity={0}/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="time" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} />
<YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} tickFormatter={(v) => v >= 1000 ? `${v/1000}k` : v} />
<Tooltip contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }} />
<Area type="monotone" dataKey="value" stroke="#f43f5e" strokeWidth={3} fillOpacity={1} fill="url(#colorSalesStore)" />
</AreaChart>
</ResponsiveContainer>
</div>
</div>
{/* Total Sales Gauge */}
<div className="col-span-12 lg:col-span-4 bg-white p-6 rounded-[32px] border border-slate-100 shadow-sm relative">
<div className="relative h-[280px] flex flex-col items-center justify-center mt-8">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie
data={pieData}
cx="50%"
cy="50%"
innerRadius={80}
outerRadius={105}
paddingAngle={0}
dataKey="value"
startAngle={210}
endAngle={-150}
>
{pieData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
</PieChart>
</ResponsiveContainer>
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center">
<h2 className="text-3xl font-black text-slate-800 tracking-tighter">{stats.totalSales.toLocaleString()}</h2>
</div>
<div className="flex gap-6 mt-4">
<div className="flex items-center gap-2">
<div className="w-2.5 h-2.5 rounded-full bg-[#8b5cf6]" />
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Full-Payment</span>
</div>
<div className="flex items-center gap-2">
<div className="w-2.5 h-2.5 rounded-full bg-[#fbbf24]" />
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Credit</span>
</div>
</div>
</div>
</div>
{/* Right Stats Column */}
<div className="col-span-12 lg:col-span-3 space-y-6">
{/* Filters */}
<div className="flex items-center justify-between overflow-x-auto gap-2 pb-2 scrollbar-none">
{['Yesterday', 'Today', 'Week', '30 Days', 'Custom'].map(range => (
<button
key={range}
title={`Filter metrics by ${range.toLowerCase()}`}
onClick={() => setTimeRange(range)}
className={`whitespace-nowrap px-2 py-2 text-[10px] font-black uppercase tracking-tighter transition-all relative ${timeRange === range ? 'text-[#521c4b]' : 'text-slate-400 hover:text-slate-600'}`}
>
{range}
{timeRange === range && (
<motion.div layoutId="rangeLineStore" className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#521c4b]" />
)}
</button>
))}
</div>
{/* Total Orders Card */}
<div title="View detailed store volume and throughput" className="bg-white p-6 rounded-[24px] border border-slate-100 shadow-sm relative h-[180px] flex flex-col justify-between group cursor-pointer hover:border-[#521c4b]/30 transition-all">
<div className="flex items-center gap-3">
<div className="p-2 bg-amber-50 text-amber-500 rounded-xl group-hover:scale-110 transition-transform">
<ShoppingBag size={20} />
</div>
<h4 className="text-[11px] font-black text-slate-400 uppercase tracking-widest leading-none">Total Sales</h4>
</div>
<div className="flex flex-col items-center">
<h2 className="text-5xl font-black text-slate-800 tracking-tighter">{stats.activeOrders}</h2>
<div className="w-full h-1 bg-green-500 rounded-full mt-4 shadow-sm" />
</div>
</div>
{/* Expenses Card */}
<div title="Monitor store operational expenditures" className="bg-white p-6 rounded-[24px] border border-slate-100 shadow-sm h-[150px] flex flex-col justify-between group cursor-pointer hover:border-[#521c4b]/30 transition-all">
<div className="flex items-center gap-3">
<div className="p-2 bg-amber-100 text-[#521c4b] rounded-xl shadow-sm">
<Wallet size={20} />
</div>
<h4 className="text-[11px] font-black text-slate-400 uppercase tracking-widest leading-none">Expenses</h4>
</div>
<div className="text-center">
<h2 className="text-4xl font-black text-slate-800 tracking-tighter">0</h2>
</div>
</div>
</div>
</div>
{/* Bottom Section */}
<div className="grid grid-cols-12 gap-8 mt-4 pb-12">
{/* Trending Items */}
<div className="col-span-12 lg:col-span-6 bg-white rounded-[32px] border border-slate-100 shadow-sm p-6">
<div className="flex items-center justify-between mb-8">
<div className="flex items-center gap-3">
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Trending Items</h3>
<div className="p-1 px-2 bg-indigo-50 rounded-lg text-indigo-400">
<Star size={12} fill="currentColor" />
</div>
</div>
<div className="flex items-center gap-1.5 p-1 bg-slate-50 rounded-lg border border-slate-100">
<button title="View inventory metrics" className="p-1.5 text-slate-400 hover:text-slate-600 transition-all"><ShoppingBag size={14} /></button>
<button title="View price distributions" className="text-[10px] font-black text-slate-400 px-1"></button>
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="text-left border-b border-slate-50">
<th className="pb-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">Items</th>
<th className="pb-4 text-[10px] font-black text-slate-400 uppercase tracking-widest text-right">Sold Quantity</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-50">
{trendingItems.map((item, idx) => (
<tr key={idx} className="group cursor-pointer hover:bg-slate-50/50 transition-all">
<td className="py-4">
<div className="flex items-center gap-4">
<div className="w-12 h-12 rounded-xl overflow-hidden bg-slate-100 border border-slate-50 group-hover:scale-105 transition-transform">
<img src={item.image} alt={item.name} className="w-full h-full object-cover" />
</div>
<div className="space-y-0.5">
<p className="text-[9px] font-black text-[#521c4b] uppercase tracking-widest brightness-110">{item.category}</p>
<p className="text-xs font-black text-slate-800 uppercase tracking-tight">{item.name}</p>
</div>
</div>
</td>
<td className="py-4 text-right">
<span className="text-sm font-black text-slate-800">{item.qty}</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Store Insights */}
<div className="col-span-12 lg:col-span-6 bg-white rounded-[32px] border border-slate-100 shadow-sm p-6 flex flex-col">
<h3 className="text-sm font-black text-slate-800 tracking-tight mb-8 uppercase tracking-widest">Store Insights</h3>
<div className="space-y-4 flex-1 overflow-y-auto max-h-[480px] custom-scrollbar pr-2">
{insights.map((insight, idx) => (
<div key={idx} className={`p-4 rounded-2xl border transition-all hover:translate-x-1 ${insight.color} flex items-center gap-3`}>
<div className="w-6 h-6 rounded-full bg-white/50 backdrop-blur-sm flex items-center justify-center shrink-0">
<Star size={12} className="opacity-70" />
</div>
<p className="text-[11px] font-bold leading-relaxed">{insight.text}</p>
</div>
))}
</div>
<div className="mt-8 flex justify-end">
<button title="Analyze subsequent business cycles" className="flex items-center gap-2 px-6 py-2.5 bg-[#521c4b]/5 hover:bg-[#521c4b]/10 text-[#521c4b] text-[11px] font-black uppercase tracking-widest rounded-2xl transition-all group">
Next
<ArrowRight size={14} className="group-hover:translate-x-1 transition-transform" />
</button>
</div>
</div>
</div>
</div>
);
};
export default StoreDashboard;

View File

@@ -0,0 +1,236 @@
import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
Monitor,
Plus,
MapPin,
ShieldCheck,
Trash2,
Search,
ExternalLink,
Info,
Key
} from 'lucide-react';
import AddTerminalModal from '../components/AddTerminalModal.tsx';
import PinVerificationModal from '../components/PinVerificationModal.tsx';
interface Terminal {
id: number;
name: string;
location: string;
apiKey: string;
}
const Terminals = () => {
const [terminals, setTerminals] = useState<Terminal[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
const [isPinModalOpen, setIsPinModalOpen] = useState(false);
const [selectedTerminal, setSelectedTerminal] = useState<Terminal | null>(null);
const fetchTerminals = async () => {
setLoading(true);
try {
const response = await fetch('/api/terminals');
if (response.ok) {
const data = await response.json();
setTerminals(data);
}
} catch (error) {
console.error('Failed to fetch terminals:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchTerminals();
}, []);
const handleDelete = async (id: number, e: React.MouseEvent) => {
e.stopPropagation();
if (window.confirm('Are you sure you want to remove this terminal?')) {
try {
const response = await fetch(`/api/terminals/${id}`, { method: 'DELETE' });
if (response.ok) fetchTerminals();
} catch (error) {
console.error('Failed to delete terminal:', error);
}
}
};
const filteredTerminals = terminals.filter(t =>
t.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
t.location.toLowerCase().includes(searchQuery.toLowerCase())
);
return (
<div className="p-8 max-w-7xl mx-auto space-y-8 font-inter">
{/* Header Section */}
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
<div>
<h1 className="text-3xl font-bold text-[#1e293b]">Physical Terminals</h1>
<p className="text-[#64748b] mt-1 font-medium">Manage counter devices and device authentication keys</p>
</div>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={() => setIsAddModalOpen(true)}
className="flex items-center justify-center gap-2 bg-[#231651] text-white px-6 py-3.5 rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:bg-[#2d1d66] transition-all"
>
<Plus size={20} />
Add Terminal
</motion.button>
</div>
{/* Stats/Info Banner */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="bg-gradient-to-br from-[#231651] to-[#3d2b7a] p-6 rounded-3xl text-white shadow-xl">
<div className="flex items-center gap-4">
<div className="p-3 bg-white/10 rounded-2xl">
<Monitor size={24} />
</div>
<div>
<p className="text-white/60 text-sm font-medium">Active Devices</p>
<p className="text-2xl font-bold">{terminals.length}</p>
</div>
</div>
</div>
<div className="bg-white p-6 rounded-3xl border border-gray-100 shadow-sm flex items-center gap-4">
<div className="p-3 bg-green-50 text-green-600 rounded-2xl">
<ShieldCheck size={24} />
</div>
<div>
<p className="text-gray-500 text-sm font-medium">System Status</p>
<p className="text-xl font-bold text-gray-900 border-b-2 border-green-500 inline-block leading-tight">Secure & Online</p>
</div>
</div>
<div className="bg-blue-50 p-6 rounded-3xl flex items-center gap-4 border border-blue-100">
<Info size={24} className="text-blue-600 shrink-0" />
<p className="text-sm text-blue-700 font-medium leading-relaxed">
Terminals are used at physical counters to scan order QRs and print bills.
</p>
</div>
</div>
{/* Search and Filters */}
<div className="bg-white p-2 rounded-2xl border border-gray-100 shadow-sm flex items-center group focus-within:ring-2 focus-within:ring-[#231651]/10 transition-all">
<div className="p-3">
<Search size={20} className="text-gray-400 group-focus-within:text-[#231651] transition-colors" />
</div>
<input
type="text"
placeholder="Search by terminal name or location..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full h-12 bg-transparent outline-none text-sm font-medium text-gray-700 placeholder:text-gray-400"
/>
</div>
{/* Grid of Terminals */}
{loading ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{[1,2,3].map(i => (
<div key={i} className="h-64 bg-gray-100 rounded-3xl animate-pulse" />
))}
</div>
) : filteredTerminals.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{filteredTerminals.map((terminal) => (
<motion.div
layout
key={terminal.id}
whileHover={{ y: -5 }}
onClick={() => {
setSelectedTerminal(terminal);
setIsPinModalOpen(true);
}}
className="bg-white p-6 rounded-[2.5rem] border border-gray-100 shadow-sm hover:shadow-xl hover:shadow-[#231651]/5 transition-all cursor-pointer group relative overflow-hidden"
>
{/* Card Background Pattern */}
<div className="absolute -right-8 -top-8 text-[#231651]/5 rotate-12 transition-transform group-hover:rotate-0 duration-500">
<Monitor size={140} />
</div>
<div className="relative z-10 space-y-4">
<div className="flex items-start justify-between">
<div className="p-4 bg-gray-50 text-[#231651] rounded-2xl border border-gray-200 group-hover:bg-[#231651] group-hover:text-white transition-colors duration-300">
<Monitor size={28} />
</div>
<button
onClick={(e) => handleDelete(terminal.id, e)}
className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-all"
>
<Trash2 size={18} />
</button>
</div>
<div>
<h4 className="text-xl font-bold text-gray-900 group-hover:text-[#231651] transition-colors">{terminal.name}</h4>
<div className="flex items-center gap-1.5 text-gray-500 mt-1 font-medium text-sm">
<MapPin size={14} />
<span>{terminal.location}</span>
</div>
</div>
<div className="pt-4 flex items-center justify-between border-t border-gray-50">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
<span className="text-[12px] font-bold text-gray-500 uppercase tracking-wider">Device Ready</span>
</div>
<div className="flex items-center gap-2 text-[#231651] font-bold text-sm">
<Key size={16} />
<span>View API Key</span>
<ExternalLink size={14} />
</div>
</div>
</div>
</motion.div>
))}
</div>
) : (
<div className="flex flex-col items-center justify-center p-20 bg-gray-50/50 rounded-[3rem] border-2 border-dashed border-gray-200">
<div className="p-6 bg-white rounded-full shadow-sm mb-4">
<Monitor size={48} className="text-gray-300" />
</div>
<p className="text-lg font-bold text-gray-900">No terminals found</p>
<p className="text-gray-500 max-w-xs text-center mt-1">Start by adding your first counter device terminal to manage device authentication.</p>
<button
onClick={() => setIsAddModalOpen(true)}
className="mt-6 text-[#231651] font-bold hover:underline underline-offset-4"
>
Add your first terminal
</button>
</div>
)}
{/* Modals */}
<AddTerminalModal
isOpen={isAddModalOpen}
onClose={() => setIsAddModalOpen(false)}
onSuccess={fetchTerminals}
/>
<PinVerificationModal
isOpen={isPinModalOpen}
onClose={() => {
setIsPinModalOpen(false);
setSelectedTerminal(null);
}}
terminalId={selectedTerminal?.id || null}
terminalName={selectedTerminal?.name || ''}
/>
<style dangerouslySetInnerHTML={{ __html: `
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
.font-inter { font-family: 'Inter', sans-serif; }
` }} />
</div>
);
};
export default Terminals;

View File

@@ -0,0 +1,161 @@
import { motion } from 'framer-motion';
import {
ShoppingBag,
TrendingUp,
Users,
Clock,
ArrowUpRight,
Package,
DollarSign,
BarChart3
} from 'lucide-react';
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
BarChart,
Bar
} from 'recharts';
const data = [
{ month: 'Jan', purchases: 4500, orders: 12 },
{ month: 'Feb', purchases: 5200, orders: 15 },
{ month: 'Mar', purchases: 4800, orders: 14 },
{ month: 'Apr', purchases: 6100, orders: 18 },
{ month: 'May', purchases: 5500, orders: 16 },
{ month: 'Jun', purchases: 6700, orders: 20 },
];
const StatCard = ({ title, value, change, icon: Icon, color, delay }: any) => (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay, duration: 0.5 }}
className="bg-white p-6 rounded-2xl border border-[#e2e8f0] shadow-sm hover:shadow-md transition-all"
>
<div className="flex items-center justify-between mb-4">
<div className={`p-3 rounded-xl ${color} bg-opacity-10 text-${color.split('-')[1]}-600`}>
<Icon size={20} />
</div>
<div className="flex items-center gap-1 text-emerald-600 text-[10px] font-bold bg-emerald-50 px-2 py-0.5 rounded-full">
<ArrowUpRight size={10} />
{change}%
</div>
</div>
<p className="text-xs font-bold text-[#64748b] uppercase tracking-wider mb-1">{title}</p>
<h3 className="text-xl font-black text-[#1e293b]">{value}</h3>
</motion.div>
);
const VendorDashboard = () => {
return (
<div className="p-8 space-y-8 animate-in fade-in duration-500">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-black text-[#231651] tracking-tight">Vendor Dashboard</h1>
<p className="text-[#64748b] text-sm font-medium">Monitoring procurement, supplier health, and order cycles.</p>
</div>
<div className="flex items-center gap-3">
<button className="px-4 py-2 bg-white border border-[#e2e8f0] rounded-xl text-xs font-bold text-[#1e293b] hover:bg-gray-50 flex items-center gap-2">
<Clock size={14} /> Last 30 Days
</button>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<StatCard title="Total Procurement" value="$28,450.00" change={12} icon={DollarSign} color="bg-blue-500" delay={0.1} />
<StatCard title="Active Vendors" value="24" change={5} icon={Users} color="bg-emerald-500" delay={0.2} />
<StatCard title="Pending POs" value="08" change={2} icon={Package} color="bg-amber-500" delay={0.3} />
<StatCard title="Supply Fill Rate" value="94.2%" change={1.5} icon={TrendingUp} color="bg-violet-500" delay={0.4} />
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
className="bg-white p-6 rounded-3xl border border-[#e2e8f0] shadow-sm"
>
<div className="flex items-center justify-between mb-8">
<h3 className="text-lg font-bold text-[#1e293b] flex items-center gap-2">
<BarChart3 size={18} className="text-[#231651]" />
Purchase Trends
</h3>
</div>
<div className="h-[300px] w-full">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={data}>
<defs>
<linearGradient id="colorPurchases" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#231651" stopOpacity={0.1}/>
<stop offset="95%" stopColor="#231651" stopOpacity={0}/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="month" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 11, fontWeight: 700}} dy={10} />
<YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 11, fontWeight: 700}} />
<Tooltip />
<Area type="monotone" dataKey="purchases" stroke="#231651" strokeWidth={3} fillOpacity={1} fill="url(#colorPurchases)" />
</AreaChart>
</ResponsiveContainer>
</div>
</motion.div>
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
className="bg-white p-6 rounded-3xl border border-[#e2e8f0] shadow-sm"
>
<div className="flex items-center justify-between mb-8">
<h3 className="text-lg font-bold text-[#1e293b] flex items-center gap-2">
<ShoppingBag size={18} className="text-[#231651]" />
Orders by Volume
</h3>
</div>
<div className="h-[300px] w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data}>
<XAxis dataKey="month" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 11, fontWeight: 700}} dy={10} />
<YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 11, fontWeight: 700}} />
<Tooltip />
<Bar dataKey="orders" fill="#231651" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
</motion.div>
</div>
<div className="bg-white rounded-3xl border border-[#e2e8f0] shadow-sm p-6 overflow-hidden">
<h3 className="text-lg font-bold text-[#1e293b] mb-6">Top Performing Vendors</h3>
<div className="space-y-4">
{[
{ name: 'Fresh Foods Co.', orders: 45, volume: '$12,400', color: 'bg-blue-100 text-blue-600' },
{ name: 'Dairy Plus', orders: 28, volume: '$8,200', color: 'bg-emerald-100 text-emerald-600' },
{ name: 'Bakery World', orders: 15, volume: '$3,150', color: 'bg-amber-100 text-amber-600' },
].map((v, i) => (
<div key={i} className="flex items-center justify-between p-4 bg-gray-50/50 rounded-2xl hover:bg-gray-50 transition-all cursor-pointer group">
<div className="flex items-center gap-4">
<div className={`w-10 h-10 rounded-xl ${v.color} flex items-center justify-center font-bold text-sm`}>
{v.name.charAt(0)}
</div>
<div>
<p className="text-sm font-bold text-[#1e293b] group-hover:text-[#231651] transition-colors">{v.name}</p>
<p className="text-[10px] font-bold text-[#94a3b8] uppercase tracking-wider">{v.orders} Orders this month</p>
</div>
</div>
<div className="text-right">
<p className="text-sm font-black text-[#1e293b]">{v.volume}</p>
<p className="text-[10px] font-bold text-emerald-600 uppercase">Excellent Status</p>
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default VendorDashboard;

View File

@@ -0,0 +1,416 @@
import React, { useState, useEffect } from 'react';
import { Search, Building2, Phone, Mail, MoreVertical, List, LayoutGrid, Edit2, Trash2, X, Loader2, AlertCircle, CheckCircle, Plus } from 'lucide-react';
import Pagination from '../components/Pagination';
interface VendorDto {
id: number;
name: string;
companyName: string;
contactNumber: string;
email: string;
totalOrders: number;
totalAmount: number;
}
const Vendors: React.FC = () => {
const [vendors, setVendors] = useState<VendorDto[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState('');
const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
// Pagination States
const [currentPage, setCurrentPage] = useState(0);
const [pageSize, setPageSize] = useState(10);
const [totalElements, setTotalElements] = useState(0);
// Modal States
const [showModal, setShowModal] = useState(false);
const [editingVendor, setEditingVendor] = useState<VendorDto | null>(null);
const [form, setForm] = useState({ name: '', companyName: '', contactNumber: '', email: '' });
const [isSaving, setIsSaving] = useState(false);
const [errors, setErrors] = useState<{[key: string]: string}>({});
// Notification State
const [toast, setToast] = useState<{message: string, type: 'success' | 'error'} | null>(null);
// Action Menu State
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
useEffect(() => {
fetchVendors();
}, [currentPage, pageSize]);
const fetchVendors = async () => {
try {
setIsLoading(true);
const response = await fetch('/api/purchases/vendors');
if (response.ok) {
const data = await response.json();
setVendors(data);
setTotalElements(data.length);
}
} catch (error) {
console.error('Error fetching vendors:', error);
} finally {
setIsLoading(false);
}
};
const showNotification = (message: string, type: 'success' | 'error') => {
setToast({ message, type });
setTimeout(() => setToast(null), 3000);
};
const handleAddClick = () => {
setEditingVendor(null);
setForm({ name: '', companyName: '', contactNumber: '', email: '' });
setShowModal(true);
setErrors({});
};
const handleEditClick = (vendor: VendorDto) => {
setEditingVendor(vendor);
setForm({
name: vendor.name,
companyName: vendor.companyName,
contactNumber: vendor.contactNumber,
email: vendor.email
});
setShowModal(true);
setOpenMenuId(null);
setErrors({});
};
const handleDeleteClick = async (vendor: VendorDto) => {
if (!window.confirm(`Are you sure you want to delete ${vendor.name}?`)) return;
try {
const response = await fetch(`/api/purchases/vendors/${vendor.id}`, {
method: 'DELETE',
});
if (response.ok) {
showNotification(`${vendor.name} deleted successfully`, 'success');
fetchVendors();
}
} catch (error) {
showNotification('Failed to delete vendor', 'error');
}
};
const validateForm = () => {
const newErrors: {[key: string]: string} = {};
if (!form.name.trim()) newErrors.name = 'Vendor Name is required';
if (!form.contactNumber.trim()) newErrors.contactNumber = 'Contact Number is required';
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateForm()) return;
setIsSaving(true);
try {
const response = await fetch('/api/purchases/vendors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(editingVendor ? { ...form, id: editingVendor.id } : form),
});
if (response.ok) {
showNotification(`Vendor ${editingVendor ? 'updated' : 'created'} successfully`, 'success');
setShowModal(false);
fetchVendors();
} else {
const errorText = await response.text();
console.error('Backend error:', errorText);
showNotification(`Failed to save: ${errorText || response.statusText}`, 'error');
}
} catch (error) {
console.error('Fetch error:', error);
showNotification('Could not connect to server', 'error');
} finally {
setIsSaving(false);
}
};
const filteredVendors = vendors.filter(v =>
v.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
v.companyName?.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<>
{toast && (
<div className="fixed top-8 left-1/2 -translate-x-1/2 z-[200] animate-in fade-in slide-in-from-top-4 duration-300">
<div className={`px-6 py-3 rounded-2xl shadow-2xl flex items-center gap-3 border ${
toast.type === 'success' ? 'bg-emerald-50 border-emerald-100 text-emerald-800' : 'bg-red-50 border-red-100 text-red-800'
}`}>
{toast.type === 'success' ? <CheckCircle size={20} className="text-emerald-500" /> : <AlertCircle size={20} className="text-red-500" />}
<span className="text-sm font-bold">{toast.message}</span>
</div>
</div>
)}
<div className="flex flex-col h-full bg-[#f8fafc] p-8 gap-8 overflow-y-auto animate-slideUp font-inter relative">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6 max-w-[1600px]">
<div className="flex items-center gap-5">
<div className="w-14 h-14 bg-[#231651] rounded-xl flex items-center justify-center shadow-lg shadow-[#231651]/20">
<Building2 className="text-white w-7 h-7" />
</div>
<div>
<h1 className="text-2xl font-bold text-[#1e293b]">Vendor Management</h1>
<p className="text-sm text-[#64748b]">Manage your product suppliers and their contact information</p>
</div>
</div>
<div className="flex items-center gap-4">
<button
onClick={handleAddClick}
title="Register a new supplier in the database"
className="px-5 py-2.5 bg-[#231651] text-white rounded-xl text-sm font-bold flex items-center gap-2 hover:scale-105 transition-all shadow-lg shadow-[#231651]/20"
>
<Plus size={18} />
Add Vendor
</button>
<div className="relative group min-w-[320px]">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={18} />
<input
type="text"
placeholder="Search vendors..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full pl-10 pr-4 py-2.5 bg-white border border-[#e2e8f0] rounded-xl text-sm focus:outline-none focus:border-[#231651]/30 transition-all shadow-sm"
/>
</div>
<div className="flex p-1 bg-white border border-[#e2e8f0] rounded-xl shadow-sm">
<button
title="Table View"
className={`p-1.5 rounded-lg transition-all ${viewMode === 'table' ? 'bg-[#231651] text-white' : 'text-[#64748b] hover:bg-gray-50'}`}
onClick={() => setViewMode('table')}
>
<List size={20} />
</button>
<button
title="Grid View"
className={`p-1.5 rounded-lg transition-all ${viewMode === 'grid' ? 'bg-[#231651] text-white' : 'text-[#64748b] hover:bg-gray-50'}`}
onClick={() => setViewMode('grid')}
>
<LayoutGrid size={20} />
</button>
</div>
</div>
</div>
<div className="max-w-[1600px]">
{isLoading ? (
<div className="flex flex-col items-center justify-center py-24 bg-white rounded-xl border border-[#e2e8f0]">
<div className="w-10 h-10 border-4 border-[#231651]/10 border-t-[#231651] rounded-full animate-spin"></div>
<p className="mt-4 text-[#64748b] font-medium text-sm">Loading vendors...</p>
</div>
) : (
<div className="bg-white rounded-xl border border-[#e2e8f0] shadow-sm">
{viewMode === 'table' ? (
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead>
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">ID</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Vendor Info</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Contact</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Total Orders</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Total Amount</th>
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e2e8f0]">
{filteredVendors.map((vendor) => (
<tr key={vendor.id} className="hover:bg-gray-50/50 transition-all">
<td className="px-6 py-4 text-sm font-bold text-[#64748b]">{vendor.id}</td>
<td className="px-6 py-4">
<div>
<p className="text-sm font-bold text-[#1e293b]">{vendor.name}</p>
<p className="text-[11px] text-[#64748b] uppercase font-bold">{vendor.companyName}</p>
</div>
</td>
<td className="px-6 py-4">
<div className="space-y-1">
<div className="flex items-center gap-2 text-[13px] text-[#1e293b] font-medium">
<Phone size={12} className="text-[#94a3b8]" />
<span>{vendor.contactNumber}</span>
</div>
<div className="flex items-center gap-2 text-[13px] text-[#64748b]">
<Mail size={12} className="text-[#94a3b8]" />
<span>{vendor.email}</span>
</div>
</div>
</td>
<td className="px-6 py-4">
<span className="px-2.5 py-1 bg-blue-50 text-blue-600 rounded-lg text-xs font-bold transition-all">
{vendor.totalOrders || 0} Orders
</span>
</td>
<td className="px-6 py-4 text-sm font-black text-[#1e293b]">
{(vendor.totalAmount || 0).toLocaleString()}
</td>
<td className="px-6 py-4 text-right relative">
<button
onClick={() => setOpenMenuId(openMenuId === vendor.id ? null : vendor.id)}
title="Open actions menu"
className="p-1.5 text-[#94a3b8] hover:text-[#231651] rounded-lg"
>
<MoreVertical size={18} />
</button>
{openMenuId === vendor.id && (
<div className="absolute right-6 top-10 w-40 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-50 overflow-hidden">
<button onClick={() => handleEditClick(vendor)} title="Edit vendor contact and profile" className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium border-b border-[#f1f5f9]">
<Edit2 size={16} /> Edit Vendor
</button>
<button onClick={() => handleDeleteClick(vendor)} title="Delete vendor permanently" className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-red-600 font-bold">
<Trash2 size={16} /> Delete
</button>
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 p-6">
{filteredVendors.map(vendor => (
<div key={vendor.id} className="p-6 bg-white border border-[#e2e8f0] rounded-2xl flex flex-col items-center text-center hover:shadow-xl transition-all hover:-translate-y-1">
<div className="w-16 h-16 bg-[#231651] rounded-2xl flex items-center justify-center text-xl font-bold text-white mb-4">
{vendor.name.charAt(0)}
</div>
<h3 className="text-lg font-bold text-[#1e293b]">{vendor.name}</h3>
<p className="text-xs text-[#64748b] font-bold uppercase mb-4">{vendor.companyName}</p>
<div className="w-full pt-4 border-t border-[#f1f5f9] space-y-2">
<div className="flex justify-between text-[11px] font-bold uppercase tracking-wider text-[#94a3b8]">
<span>Orders</span>
<span className="text-[#1e293b]">{vendor.totalOrders || 0}</span>
</div>
<div className="flex justify-between text-[11px] font-bold uppercase tracking-wider text-[#94a3b8]">
<span>Volume</span>
<span className="text-[#1e293b]">{(vendor.totalAmount || 0).toLocaleString()}</span>
</div>
</div>
<button
onClick={() => handleEditClick(vendor)}
title="View and edit vendor profile"
className="w-full mt-6 py-2.5 bg-gray-50 border border-[#e2e8f0] text-[#1e293b] hover:bg-[#231651] hover:text-white rounded-xl text-sm font-bold transition-all"
>
Edit Details
</button>
</div>
))}
</div>
)}
<Pagination
currentPage={currentPage}
pageSize={pageSize}
totalElements={totalElements}
onPageChange={setCurrentPage}
onPageSizeChange={setPageSize}
/>
</div>
)}
</div>
</div>
{showModal && (
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
<div className="bg-white rounded-3xl w-full max-w-xl shadow-2xl overflow-hidden animate-in zoom-in duration-300">
<div className="px-8 py-6 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
<div className="flex items-center gap-4">
<div className="w-10 h-10 bg-[#231651] rounded-xl flex items-center justify-center text-white">
<Building2 size={20} />
</div>
<div>
<h2 className="text-xl font-bold text-[#1e293b]">{editingVendor ? 'Edit Vendor' : 'Add New Vendor'}</h2>
<p className="text-xs text-[#64748b]">Fill in the information below</p>
</div>
</div>
<button onClick={() => setShowModal(false)} title="Close" className="p-2 hover:bg-gray-200 rounded-full transition-colors">
<X size={20} className="text-[#64748b]" />
</button>
</div>
<form onSubmit={handleSubmit} className="p-8 space-y-6">
<div className="space-y-4">
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Vendor Name</label>
<input
required
type="text"
value={form.name}
onChange={(e) => setForm({...form, name: e.target.value})}
className="w-full px-4 py-3 bg-slate-50 border border-[#e2e8f0] rounded-xl text-sm font-bold focus:border-[#231651] outline-none transition-all"
placeholder="e.g. Fresh Foods Ltd"
/>
</div>
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Company Name</label>
<input
type="text"
value={form.companyName}
onChange={(e) => setForm({...form, companyName: e.target.value})}
className="w-full px-4 py-3 bg-slate-50 border border-[#e2e8f0] rounded-xl text-sm font-bold focus:border-[#231651] outline-none transition-all"
placeholder="Official company name"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Contact Number</label>
<input
required
type="text"
value={form.contactNumber}
onChange={(e) => setForm({...form, contactNumber: e.target.value})}
className="w-full px-4 py-3 bg-slate-50 border border-[#e2e8f0] rounded-xl text-sm font-bold focus:border-[#231651] outline-none transition-all"
placeholder="Phone number"
/>
</div>
<div>
<label className="block text-[10px] uppercase font-black text-[#64748b] mb-1.5 tracking-widest ml-1">Email Address</label>
<input
type="email"
value={form.email}
onChange={(e) => setForm({...form, email: e.target.value})}
className="w-full px-4 py-3 bg-slate-50 border border-[#e2e8f0] rounded-xl text-sm font-bold focus:border-[#231651] outline-none transition-all"
placeholder="vendor@email.com"
/>
</div>
</div>
</div>
<div className="flex gap-3 pt-4">
<button
type="button"
onClick={() => setShowModal(false)}
title="Discard changes"
className="flex-1 px-6 py-3 border border-[#e2e8f0] text-[#64748b] font-bold rounded-xl hover:bg-gray-50 transition-all text-sm"
>
Cancel
</button>
<button
type="submit"
disabled={isSaving}
title={editingVendor ? "Update vendor records" : "Save new vendor"}
className="flex-[1.5] px-6 py-3 bg-[#231651] text-white font-bold rounded-xl shadow-lg shadow-[#231651]/20 flex items-center justify-center gap-2 hover:scale-[1.02] transition-all text-sm"
>
{isSaving ? <Loader2 size={18} className="animate-spin" /> : editingVendor ? 'Update Vendor' : 'Create Vendor'}
</button>
</div>
</form>
</div>
</div>
)}
</>
);
};
export default Vendors;

View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "esnext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"module": "esnext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

17
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
host: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
secure: false,
}
}
}
})