Compare commits

...
162 Commits
Author SHA1 Message Date
efrilm bf0f4cfa38 Update Login 2025-09-26 13:47:50 +07:00
efrilm 82e79463b5 Report Sales Order 2025-09-26 13:47:04 +07:00
efrilm c3ad938a79 Report Sales Product Category 2025-09-26 13:39:18 +07:00
efrilm 69c49238d4 Report Sales Per Product 2025-09-26 13:29:17 +07:00
efrilm 191937e647 Export Excel Sales 2025-09-26 13:11:26 +07:00
efrilm ce9120e7e6 PDF Export Payment Method 2025-09-26 13:02:36 +07:00
efrilm 52879b58fe Excel Report Payment Method 2025-09-26 12:56:15 +07:00
efrilm a7b6e15818 login template 2025-09-26 12:47:43 +07:00
efrilm 8ac6ff6d14 Pdf Sales 2025-09-26 00:50:44 +07:00
efrilm 0dc6e967bb Sales Order Report 2025-09-26 00:04:35 +07:00
efrilm daa3c4e9a2 Payment Method Report 2025-09-25 23:45:49 +07:00
efrilm 27ddd137eb report sales product category 2025-09-25 23:11:49 +07:00
efrilm 073f3dd89c Sales Per Product Report 2025-09-25 23:05:26 +07:00
efrilm 07c0bdb3af Sales Report PDF 2025-09-25 22:52:09 +07:00
efrilm e6bcf287ea profit loss pdf 2025-09-25 19:35:22 +07:00
efrilm d317e8d06f update purchase order 2025-09-25 16:20:13 +07:00
efrilm dc32c8553b Report Profit Loss 2025-09-25 15:45:49 +07:00
efrilm 79cd4f9dcb Profit Loss Report 2025-09-25 14:59:08 +07:00
efrilm cfa3686de3 report margin 2025-09-25 13:08:31 +07:00
efrilm c7d29f4041 Shortcuts 2025-09-25 11:53:08 +07:00
efrilm 1b9908e882 update report 2025-09-23 22:27:58 +07:00
efrilm d245074904 no translate for payment method 2025-09-23 20:54:43 +07:00
efrilm 256f035997 fix: report page 2025-09-23 15:30:42 +07:00
efrilm 726d1f4984 base url 2025-09-21 20:36:36 +07:00
efrilm 9b92f4742f add printer type 2025-09-20 18:03:11 +07:00
efrilm 1bf2bad52c campaign detail 2025-09-19 17:38:48 +07:00
efrilm e55357e305 add campaign 2025-09-19 16:10:52 +07:00
efrilm 3bfd0b9e19 api 2025-09-18 16:31:58 +07:00
efrilm 97ed613cc6 api 2025-09-18 11:00:00 +07:00
efrilm fdcb0e12f4 api 2025-09-18 10:59:10 +07:00
efrilm 7570e973b8 update vertical menu 2025-09-18 10:55:37 +07:00
efrilm e82173c6e2 Campaign 2025-09-18 03:36:05 +07:00
efrilm 4640d14cb7 Reward 2025-09-18 03:04:06 +07:00
efrilm 3a56e56c69 Update Tier Drawer 2025-09-18 01:21:51 +07:00
efrilm 6d2e436b09 Game Prize 2025-09-18 01:07:39 +07:00
efrilm 7252c05569 Game Prize 2025-09-18 01:07:13 +07:00
efrilm 757d9f524a Game 2025-09-18 00:10:19 +07:00
efrilm a6f80bbd02 Games Page 2025-09-17 21:20:49 +07:00
efrilm 8ed2786bc2 tier 2025-09-17 20:54:54 +07:00
efrilm 4655411b24 tier page 2025-09-17 20:21:28 +07:00
efrilm 185edb94cb fix remove local 2025-09-17 18:43:14 +07:00
efrilm 2643963b49 Voucher 2025-09-17 02:21:02 +07:00
efrilm 18ee652731 Customer Royalti 2025-09-17 01:51:59 +07:00
efrilm 3d1b6eee39 Campaign 2025-09-17 01:45:05 +07:00
efrilm 966081214f Wheel Spin 2025-09-17 01:35:01 +07:00
efrilm 1c5740a85b reward 2025-09-17 00:56:56 +07:00
efrilm f527b6f004 Loyalty Page 2025-09-17 00:10:14 +07:00
Aditya Siregar 84454e66dc fix base url 2025-09-13 17:09:04 +07:00
aefril 54d8ff3444 Merge pull request 'base url' (#11) from efril into main
Reviewed-on: #11
2025-09-13 09:59:07 +00:00
efrilm ddbd5ba607 base url 2025-09-13 16:57:51 +07:00
Aditya Siregar 50a8f4a295 Fix 2025-09-13 16:53:25 +07:00
Aditya Siregar fb6e2571a5 WInners Voucher 2025-09-13 16:06:49 +07:00
aefril 5de78cb78f Merge pull request 'Update draw' (#10) from efril into main
Reviewed-on: #10
2025-09-13 08:21:07 +00:00
efrilm d85f081d3a Update draw 2025-09-13 15:06:46 +07:00
aefril f3358705b0 Merge pull request 'Order draw' (#9) from efril into main
Reviewed-on: #9
2025-09-13 07:26:28 +00:00
efrilm 9959775c77 Order draw 2025-09-13 14:25:25 +07:00
aefril 14efada9bb Merge pull request 'Send Payment' (#8) from efril into main
Reviewed-on: #8
2025-09-13 05:32:15 +00:00
efrilm 7384b38df5 Send Payment 2025-09-13 12:30:24 +07:00
aefril 7f646b82a9 Merge pull request 'efril' (#7) from efril into main
Reviewed-on: #7
2025-09-12 21:12:52 +00:00
efrilm fab31f1540 Add Waste at Product Recipe 2025-09-13 04:08:49 +07:00
efrilm aa2946e627 menu 2025-09-13 03:52:11 +07:00
efrilm 2d3274d3bf Purchase Detail 2025-09-13 03:50:57 +07:00
efrilm e1084277e0 status color 2025-09-13 03:05:45 +07:00
efrilm 222beb5043 Purchase create 2025-09-13 03:03:08 +07:00
efrilm 98d6446b0c Purchase Order table 2025-09-13 02:42:39 +07:00
efrilm d54d623d4c Create Purchase 2025-09-13 01:34:43 +07:00
efrilm 140822763e Ingredient in purchase 2025-09-12 22:15:16 +07:00
efrilm 0b51b29474 Vendor at Purchase Form 2025-09-12 21:54:27 +07:00
efrilm 20203942d2 Cash Bank List 2025-09-12 21:03:38 +07:00
efrilm b2840ca27c Create And Update Account 2025-09-12 20:35:49 +07:00
efrilm ce344e4a98 Get Account 2025-09-12 19:52:46 +07:00
efrilm 2d69a024c1 Get Account 2025-09-12 19:51:35 +07:00
efrilm 27fe48e99e integrate chart of account to sub akun dari 2025-09-12 19:30:14 +07:00
efrilm 5a0d96ee43 feat: update 2025-09-12 19:19:43 +07:00
efrilm 9cbb41c2ad Get Chart of Account Types 2025-09-12 19:18:43 +07:00
efrilm 76ee71e7fe Get Unit Converter 2025-09-12 18:57:23 +07:00
efrilm 54c7598e7a Create Unit Conventer 2025-09-12 18:49:01 +07:00
efrilm 40c417ec72 Delete and Edit Vendor 2025-09-12 15:23:19 +07:00
efrilm c91be1812b Vendor Slice 2025-09-12 14:02:57 +07:00
efrilm 3a74e32e64 Create Vendor 2025-09-12 13:52:11 +07:00
efrilm 8026004630 Update Vendor drawer 2025-09-12 03:27:11 +07:00
efrilm 0e8216b0c9 Vendor Api 2025-09-12 03:11:01 +07:00
aefril e8c1d02843 Merge pull request 'efril' (#6) from efril into main
Reviewed-on: #6
2025-09-11 18:58:34 +00:00
efrilm a019a4bdbc Update Expanse Detail Send Payment 2025-09-11 23:06:20 +07:00
efrilm 5def10dc64 Account 2025-09-11 23:01:01 +07:00
efrilm 5723d49090 Reconciliation and Cash Bank Detail Transaction 2025-09-11 21:47:52 +07:00
efrilm 1a9015563f Report 2025-09-11 20:43:15 +07:00
efrilm 34442740e2 Report Cash FLow 2025-09-11 18:38:27 +07:00
efrilm e13fbab564 Report Neraca 2025-09-11 18:29:17 +07:00
efrilm f2eb142dec Report Profit Loss 2025-09-11 18:20:40 +07:00
efrilm a1d23cad9e Report Cash Flow 2025-09-11 17:57:00 +07:00
efrilm b3a41fe0e0 Ingredient Detail Stock Adjustment Drawer 2025-09-11 16:55:18 +07:00
efrilm 5a77d3c2ea Ingredient Detail 2025-09-11 16:22:05 +07:00
efrilm 29defb68c8 Ingredient Detail Unit 2025-09-11 16:02:31 +07:00
efrilm c9e260860c Report Page 2025-09-11 15:32:26 +07:00
efrilm 9c1b1fc1db Fixed Asset Add 2025-09-11 14:47:57 +07:00
efrilm 42b95bb212 Fixed Asset Table 2025-09-11 13:37:52 +07:00
efrilm 63eea38d48 update 2025-09-11 00:44:07 +07:00
efrilm 630d9c0e65 Account Page 2025-09-11 00:16:00 +07:00
efrilm e267a50946 Cash Bank Detail Table 2025-09-10 19:42:26 +07:00
efrilm 2c754d96fd refator menu 2025-09-10 17:51:24 +07:00
efrilm 66589abdd4 Cash Bank List 2025-09-10 17:41:07 +07:00
efrilm 00620026e4 Detail expense 2025-09-10 16:55:19 +07:00
efrilm afa4cfad0d Expense Add 2025-09-10 15:45:34 +07:00
efrilm 420df71452 Sales Bill List table Update 2025-09-10 14:31:16 +07:00
efrilm 7077bf8d87 Expense List Table 2025-09-10 14:24:18 +07:00
efrilm c32d08666e Purchase Detail 2025-09-10 03:23:54 +07:00
efrilm 8461e1f4b7 Sales Quote List Table 2025-09-10 00:47:15 +07:00
efrilm 8ec6ba62f3 Sales Order List table 2025-09-10 00:40:54 +07:00
efrilm ce9f845fe4 Sales Delivery Page 2025-09-10 00:28:23 +07:00
efrilm cc3a0c07a9 Sales Invoice Page 2025-09-10 00:19:11 +07:00
efrilm f585f23c54 purchase quote list and add 2025-09-09 23:55:38 +07:00
efrilm 9b787e65d4 purchase delivery table page 2025-09-09 23:41:04 +07:00
efrilm d0d5d066a1 purchase bill add page 2025-09-09 23:28:17 +07:00
efrilm b20e672ea1 purchase bills table page 2025-09-09 23:23:59 +07:00
efrilm 49ed3386be feat: purchase form 2025-09-09 23:05:23 +07:00
efrilm 4c4579f009 feat: Purchase Order Add 2025-09-09 22:47:05 +07:00
efrilm dfa8218017 feat: purchase order page 2025-09-09 17:42:49 +07:00
efrilm 849013a08a Purchase Overview Page 2025-09-09 16:17:25 +07:00
efrilm 5dc62b8390 Sales Overview Page 2025-09-09 15:42:05 +07:00
efrilm dfa6b4be75 Vendor Detail 2025-09-09 14:28:35 +07:00
efrilm 59f2d45854 update add vendor 2025-09-09 01:25:50 +07:00
efrilm 105d75c820 feat: vendor create and vendor list 2025-09-09 01:17:01 +07:00
efrilm 789dd823b6 add indonesian lang 2025-09-08 23:19:41 +07:00
efrilm d58bf1983c Merge remote-tracking branch 'origin/main' into efril 2025-09-08 23:13:10 +07:00
efrilm 9f934ce5c7 fix local storage 2025-09-08 23:12:11 +07:00
aefril 0528cfa053 Merge pull request 'fix: reset product' (#5) from efril into main
Reviewed-on: #5
2025-09-03 06:05:58 +00:00
efrilm d3417fae9a fix: reset product 2025-09-03 13:01:48 +07:00
aefril 17f059f09d Merge pull request 'efril' (#4) from efril into main
Reviewed-on: #4
2025-09-03 05:38:04 +00:00
efrilm 1fc2b41d36 feat: routing add product 2025-09-03 12:36:44 +07:00
efrilm ad48cdebe7 fix: to date change 2025-09-03 12:34:18 +07:00
efrilm eb38bd7f5c Merge remote-tracking branch 'origin/main' into efril 2025-09-03 12:26:38 +07:00
Aditya Siregar b8de65bdcf fix api url 2025-09-02 16:25:13 +07:00
Aditya Siregar 4f65b9bbb6 fixed 2025-09-01 21:03:56 +07:00
Aditya Siregar bfdcb123d0 Fixed 2025-09-01 21:03:31 +07:00
Aditya Siregar 4ff01920e7 fix 2025-09-01 19:46:48 +07:00
Aditya Siregar 38e1bb5027 fix 2025-09-01 19:07:22 +07:00
Aditya Siregar c71529b11d fix 2025-09-01 18:33:38 +07:00
Aditya Siregar c6f2d67baf Fix deployment 2025-09-01 18:20:25 +07:00
Aditya Siregar 22374dbee1 add deployment 2025-09-01 18:09:54 +07:00
efrilm 7803eaa13e Merge remote-tracking branch 'origin/main' into efril 2025-08-14 03:25:38 +07:00
ferdiansyah783 6d2fe8d6f7 fix: typography 2025-08-14 03:21:58 +07:00
aefril 3700ce6228 Merge pull request 'efril' (#3) from efril into main
Reviewed-on: #3
2025-08-13 20:19:50 +00:00
efrilm 2c370b4c15 Merge remote-tracking branch 'origin/main' into efril 2025-08-14 03:19:02 +07:00
efrilm 16ad569297 feat: report inventory 2025-08-14 03:17:17 +07:00
ferdiansyah783 6549773c13 fix: typography 2025-08-14 03:15:47 +07:00
ferdiansyah783 274cecd1cb fix: re stock 2025-08-14 03:09:00 +07:00
efrilm e2f18ac9bb Merge remote-tracking branch 'origin/main' into efril 2025-08-14 02:08:24 +07:00
efrilm 7a8bd59bb4 feat: add categories at daily report 2025-08-14 02:07:55 +07:00
ferdiansyah783 1d5ff78fc2 fix: filter date 2025-08-14 01:29:40 +07:00
aefril 165c211c5b Merge pull request 'efril' (#2) from efril into main
Reviewed-on: #2
2025-08-13 18:26:55 +00:00
efrilm a13597725b Merge remote-tracking branch 'origin/main' into efril 2025-08-14 01:26:12 +07:00
efrilm 3aba6c3df5 refactor: change name 2025-08-14 01:24:34 +07:00
ferdiansyah783 1cd8adc1e2 fix: guest route 2025-08-14 00:29:19 +07:00
aefril c01db516b1 Merge pull request 'efril' (#1) from efril into main
Reviewed-on: #1
2025-08-13 17:12:17 +00:00
efrilm 054ca015fd Merge remote-tracking branch 'origin/main' into efril 2025-08-14 00:11:27 +07:00
ferdiansyah783 d34d5a92cd fix: organization input 2025-08-13 23:58:37 +07:00
ferdiansyah783 ba7911d04b fix: product and inventory 2025-08-13 23:53:03 +07:00
efrilm 3514e7dc46 Merge remote-tracking branch 'origin/main' into efril 2025-08-13 15:05:14 +07:00
ferdiansyah783 ea6205cfa7 feat: ingredient product 2025-08-12 21:34:50 +07:00
ferdiansyah783 f3dfad4cb3 feat: ingredient product 2025-08-12 21:29:24 +07:00
ferdiansyah783 c3780af341 feat: product recipes 2025-08-11 13:48:24 +07:00
385 changed files with 51431 additions and 1646 deletions
+2
View File
@@ -39,3 +39,5 @@ next-env.d.ts
# icon generated file
src/assets/iconify-icons/generated-icons.js
src/assets/iconify-icons/generated-icons.css
*.backup
+5
View File
@@ -0,0 +1,5 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
+7
View File
@@ -0,0 +1,7 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="Stylelint" enabled="true" level="ERROR" enabled_by_default="true" />
</profile>
</component>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/pos-dashboard-v2.iml" filepath="$PROJECT_DIR$/.idea/pos-dashboard-v2.iml" />
</modules>
</component>
</project>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+52
View File
@@ -0,0 +1,52 @@
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
# Build arguments for environment variables
ARG NEXT_PUBLIC_APP_URL
ARG NEXT_PUBLIC_DOCS_URL
ARG NEXT_PUBLIC_API_URL
ARG API_URL
ARG BASEPATH
ARG MAPBOX_ACCESS_TOKEN
# Set environment variables for build
ENV API_URL=$API_URL
ENV BASEPATH=$BASEPATH
ENV MAPBOX_ACCESS_TOKEN=$MAPBOX_ACCESS_TOKEN
ENV NEXT_PUBLIC_APP_URL=$NEXT_PUBLIC_APP_URL
ENV NEXT_PUBLIC_DOCS_URL=$NEXT_PUBLIC_DOCS_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
# Copy all files first
COPY . .
# Install dependencies
RUN npm ci
# Build icons
RUN npm run build:icons
# Build the application without linting
RUN npm run build:no-lint
# Production stage
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 8080
ENV PORT=8080
CMD ["node", "server.js"]
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
APP_NAME="apskel-frontend"
PORT="8080"
echo "🔄 Pulling latest code..."
git pull
echo "🐳 Building Docker image..."
docker build -t apskel-frontend .
docker stop $APP_NAME 2>/dev/null
docker rm $APP_NAME 2>/dev/null
docker run -d --name $APP_NAME \
-p 8080:$PORT \
$APP_NAME:latest
echo "✅ Deployment complete."
+27 -22
View File
@@ -1,29 +1,34 @@
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
output: 'standalone',
basePath: process.env.BASEPATH,
redirects: async () => {
return [
{
source: '/',
destination: '/en/dashboards/overview',
permanent: true,
locale: false
},
{
source: '/:lang(en|fr|ar)',
destination: '/:lang/dashboards/overview',
permanent: true,
locale: false
},
{
source: '/((?!(?:en|fr|ar|front-pages|favicon.ico)\\b)):path',
destination: '/en/:path',
permanent: true,
locale: false
}
]
}
eslint: {
ignoreDuringBuilds: true,
},
typescript: {
ignoreBuildErrors: true,
},
redirects: async () => [
{
source: '/',
destination: '/en/dashboards/overview',
permanent: true,
locale: false,
},
{
source: '/:lang(en|fr|ar)',
destination: '/:lang/dashboards/overview',
permanent: true,
locale: false,
},
{
source: '/((?!(?:en|fr|ar|front-pages|favicon.ico)\\b)):path',
destination: '/en/:path',
permanent: true,
locale: false,
}
],
}
export default nextConfig
+195 -33
View File
@@ -25,6 +25,7 @@
"@fullcalendar/react": "6.1.15",
"@fullcalendar/timegrid": "6.1.15",
"@hookform/resolvers": "3.9.1",
"@iconify/react": "^6.0.1",
"@mui/lab": "6.0.0-beta.19",
"@mui/material": "6.2.1",
"@mui/material-nextjs": "6.2.1",
@@ -51,9 +52,12 @@
"emoji-mart": "5.6.0",
"fs-extra": "11.2.0",
"html2canvas": "^1.4.1",
"html2pdf.js": "^0.12.1",
"input-otp": "1.4.1",
"jspdf": "^3.0.1",
"jspdf": "^3.0.3",
"jspdf-autotable": "^5.0.2",
"keen-slider": "6.8.6",
"lucide-react": "^0.544.0",
"mapbox-gl": "3.9.0",
"negotiator": "1.0.0",
"next": "15.1.2",
@@ -72,7 +76,8 @@
"react-use": "17.6.0",
"recharts": "2.15.0",
"use-debounce": "^10.0.5",
"valibot": "0.42.1"
"valibot": "0.42.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@iconify/json": "2.2.286",
@@ -80,6 +85,7 @@
"@iconify/types": "2.0.0",
"@iconify/utils": "2.2.1",
"@types/fs-extra": "^11.0.4",
"@types/jspdf": "^1.3.3",
"@types/mapbox-gl": "^3.4.1",
"@types/negotiator": "^0.6.3",
"@types/node": "^22.10.2",
@@ -1308,6 +1314,21 @@
"pathe": "^1.1.2"
}
},
"node_modules/@iconify/react": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/@iconify/react/-/react-6.0.1.tgz",
"integrity": "sha512-fCocnAfiGXjrA0u7KkS3W/OQHNp9LRFICudvOtxmS3Mf7U92aDhP50wyzRbobZli51zYt9ksZ9g0J7H586XvOQ==",
"license": "MIT",
"dependencies": {
"@iconify/types": "^2.0.0"
},
"funding": {
"url": "https://github.com/sponsors/cyberalien"
},
"peerDependencies": {
"react": ">=16"
}
},
"node_modules/@iconify/tools": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/@iconify/tools/-/tools-4.1.1.tgz",
@@ -1332,7 +1353,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz",
"integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==",
"dev": true,
"license": "MIT"
},
"node_modules/@iconify/utils": {
@@ -3491,6 +3511,13 @@
"@types/node": "*"
}
},
"node_modules/@types/jspdf": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@types/jspdf/-/jspdf-1.3.3.tgz",
"integrity": "sha512-DqwyAKpVuv+7DniCp2Deq1xGvfdnKSNgl9Agun2w6dFvR5UKamiv4VfYUgcypd8S9ojUyARFIlZqBrYrBMQlew==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/linkify-it": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz",
@@ -3556,6 +3583,12 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/pako": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz",
"integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==",
"license": "MIT"
},
"node_modules/@types/parse-json": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz",
@@ -3920,6 +3953,15 @@
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/ajv": {
"version": "6.12.6",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
@@ -4255,18 +4297,6 @@
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT"
},
"node_modules/atob": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz",
"integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==",
"license": "(MIT OR Apache-2.0)",
"bin": {
"atob": "bin/atob.js"
},
"engines": {
"node": ">= 4.5.0"
}
},
"node_modules/attr-accept": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",
@@ -4484,18 +4514,6 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/btoa": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/btoa/-/btoa-1.2.1.tgz",
"integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g==",
"license": "(MIT OR Apache-2.0)",
"bin": {
"btoa": "bin/btoa.js"
},
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/buffer-crc32": {
"version": "0.2.13",
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
@@ -4644,6 +4662,19 @@
"node": ">=10.0.0"
}
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -4796,6 +4827,15 @@
"react-dom": "^18 || ^19 || ^19.0.0-rc"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/color": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
@@ -4937,6 +4977,18 @@
"node": ">=10"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/crelt": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",
@@ -6582,6 +6634,17 @@
"dev": true,
"license": "MIT"
},
"node_modules/fast-png": {
"version": "6.4.0",
"resolved": "https://registry.npmjs.org/fast-png/-/fast-png-6.4.0.tgz",
"integrity": "sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==",
"license": "MIT",
"dependencies": {
"@types/pako": "^2.0.3",
"iobuffer": "^5.3.2",
"pako": "^2.1.0"
}
},
"node_modules/fast-shallow-equal": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fast-shallow-equal/-/fast-shallow-equal-1.0.0.tgz",
@@ -6861,6 +6924,15 @@
"node": ">= 6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/fraction.js": {
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz",
@@ -7440,6 +7512,16 @@
"node": ">=8.0.0"
}
},
"node_modules/html2pdf.js": {
"version": "0.12.1",
"resolved": "https://registry.npmjs.org/html2pdf.js/-/html2pdf.js-0.12.1.tgz",
"integrity": "sha512-3rBWQ96H5oOU9jtoz3MnE/epGi27ig9h8aonBk4JTpvUERM3lMRxhIRckhJZEi4wE0YfRINoYOIDY0hLY0CHgQ==",
"license": "MIT",
"dependencies": {
"html2canvas": "^1.0.0",
"jspdf": "^3.0.0"
}
},
"node_modules/htmlparser2": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
@@ -7614,6 +7696,12 @@
"node": ">=12"
}
},
"node_modules/iobuffer": {
"version": "5.4.0",
"resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz",
"integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==",
"license": "MIT"
},
"node_modules/is-array-buffer": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
@@ -8235,14 +8323,13 @@
}
},
"node_modules/jspdf": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.1.tgz",
"integrity": "sha512-qaGIxqxetdoNnFQQXxTKUD9/Z7AloLaw94fFsOiJMxbfYdBbrBuhWmbzI8TVjrw7s3jBY1PFHofBKMV/wZPapg==",
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-3.0.3.tgz",
"integrity": "sha512-eURjAyz5iX1H8BOYAfzvdPfIKK53V7mCpBTe7Kb16PaM8JSXEcUQNBQaiWMI8wY5RvNOPj4GccMjTlfwRBd+oQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.7",
"atob": "^2.1.2",
"btoa": "^1.2.1",
"@babel/runtime": "^7.26.9",
"fast-png": "^6.2.0",
"fflate": "^0.8.1"
},
"optionalDependencies": {
@@ -8252,6 +8339,15 @@
"html2canvas": "^1.0.0-rc.5"
}
},
"node_modules/jspdf-autotable": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/jspdf-autotable/-/jspdf-autotable-5.0.2.tgz",
"integrity": "sha512-YNKeB7qmx3pxOLcNeoqAv3qTS7KuvVwkFe5AduCawpop3NOkBUtqDToxNc225MlNecxT4kP2Zy3z/y/yvGdXUQ==",
"license": "MIT",
"peerDependencies": {
"jspdf": "^2 || ^3"
}
},
"node_modules/jsx-ast-utils": {
"version": "3.3.5",
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
@@ -8447,6 +8543,15 @@
"loose-envify": "cli.js"
}
},
"node_modules/lucide-react": {
"version": "0.544.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.544.0.tgz",
"integrity": "sha512-t5tS44bqd825zAW45UQxpG2CvcC4urOwn2TrwSH8u+MjeE+1NnWl6QqeQ/6NdjMqdOygyiT9p3Ev0p1NJykxjw==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/mapbox-gl": {
"version": "3.9.0",
"resolved": "https://registry.npmjs.org/mapbox-gl/-/mapbox-gl-3.9.0.tgz",
@@ -9118,6 +9223,12 @@
"quansync": "^0.2.7"
}
},
"node_modules/pako": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
"integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==",
"license": "(MIT AND Zlib)"
},
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@@ -11068,6 +11179,18 @@
"node": ">=0.10.0"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/stable-hash": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.4.tgz",
@@ -13020,6 +13143,24 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
@@ -13152,6 +13293,27 @@
"node": "^14.17.0 || ^16.13.0 || >=18.0.0"
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
+10 -3
View File
@@ -11,7 +11,8 @@
"lint:fix": "next lint --fix",
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\"",
"build:icons": "tsx src/assets/iconify-icons/bundle-icons-css.ts",
"removeI18n": "tsx src/remove-translation-scripts/index.ts"
"removeI18n": "tsx src/remove-translation-scripts/index.ts",
"build:no-lint": "NEXT_DISABLE_ESLINT=true NEXT_DISABLE_TYPECHECK=true next build"
},
"dependencies": {
"@emoji-mart/data": "1.2.1",
@@ -30,6 +31,7 @@
"@fullcalendar/react": "6.1.15",
"@fullcalendar/timegrid": "6.1.15",
"@hookform/resolvers": "3.9.1",
"@iconify/react": "^6.0.1",
"@mui/lab": "6.0.0-beta.19",
"@mui/material": "6.2.1",
"@mui/material-nextjs": "6.2.1",
@@ -56,9 +58,12 @@
"emoji-mart": "5.6.0",
"fs-extra": "11.2.0",
"html2canvas": "^1.4.1",
"html2pdf.js": "^0.12.1",
"input-otp": "1.4.1",
"jspdf": "^3.0.1",
"jspdf": "^3.0.3",
"jspdf-autotable": "^5.0.2",
"keen-slider": "6.8.6",
"lucide-react": "^0.544.0",
"mapbox-gl": "3.9.0",
"negotiator": "1.0.0",
"next": "15.1.2",
@@ -77,7 +82,8 @@
"react-use": "17.6.0",
"recharts": "2.15.0",
"use-debounce": "^10.0.5",
"valibot": "0.42.1"
"valibot": "0.42.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@iconify/json": "2.2.286",
@@ -85,6 +91,7 @@
"@iconify/types": "2.0.0",
"@iconify/utils": "2.2.1",
"@types/fs-extra": "^11.0.4",
"@types/jspdf": "^1.3.3",
"@types/mapbox-gl": "^3.4.1",
"@types/negotiator": "^0.6.3",
"@types/node": "^22.10.2",
@@ -1,16 +1,13 @@
// Type Imports
import type { ChildrenType } from '@core/types'
import type { Locale } from '@configs/i18n'
// HOC Imports
import GuestOnlyRoute from '@/hocs/GuestOnlyRoute'
const Layout = async (props: ChildrenType & { params: Promise<{ lang: Locale }> }) => {
const params = await props.params
const Layout = async (props: ChildrenType) => {
const { children } = props
return <GuestOnlyRoute lang={params.lang}>{children}</GuestOnlyRoute>
return <GuestOnlyRoute>{children}</GuestOnlyRoute>
}
export default Layout
@@ -13,10 +13,11 @@ export const metadata: Metadata = {
}
const LoginPage = async () => {
// Vars
const mode = await getServerMode()
return <Login mode={mode} />
return (
<div className='flex flex-col justify-center items-center min-bs-[100dvh] p-6'>
<Login />
</div>
)
}
export default LoginPage
@@ -0,0 +1,584 @@
'use client'
// React Imports
import type { ChangeEvent } from 'react'
import { useState, useEffect } from 'react'
// MUI Imports
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Grid from '@mui/material/Grid2'
import MenuItem from '@mui/material/MenuItem'
import Avatar from '@mui/material/Avatar'
import Divider from '@mui/material/Divider'
import Chip from '@mui/material/Chip'
import Alert from '@mui/material/Alert'
import CircularProgress from '@mui/material/CircularProgress'
// Third-party Imports
import classnames from 'classnames'
// Type Imports
import type { CustomInputHorizontalData } from '@core/components/custom-inputs/types'
// Component Imports
import CustomInputHorizontal from '@core/components/custom-inputs/Horizontal'
import DirectionalIcon from '@components/DirectionalIcon'
import { useSettings } from '@core/hooks/useSettings'
import CustomTextField from '@core/components/mui/TextField'
// Styles Imports
import frontCommonStyles from '@views/front-pages/styles.module.css'
import { useOrganizationsMutation } from '../../../../../services/mutations/organization'
import { useRouter } from 'next/navigation'
// Types
export interface OrganizationRequest {
organization_name: string
organization_email?: string | null
organization_phone_number?: string | null
plan_type: 'basic' | 'premium' | 'enterprise'
admin_name: string
admin_email: string
admin_password: string
outlet_name: string
outlet_address?: string | null
outlet_timezone?: string | null
outlet_currency: string
}
// Data
const planData: CustomInputHorizontalData[] = [
{
title: (
<div className='flex items-center gap-4'>
<Avatar
variant='rounded'
className='is-[58px] bs-[34px]'
sx={theme => ({
backgroundColor: 'var(--mui-palette-primary-light)',
color: 'var(--mui-palette-primary-main)'
})}
>
<i className='tabler-rocket text-2xl' />
</Avatar>
<div className='flex flex-col'>
<Typography color='text.primary' className='font-medium'>
Basic Plan
</Typography>
<Typography variant='body2' color='text.secondary'>
Perfect for small businesses
</Typography>
</div>
</div>
),
value: 'basic',
isSelected: true
},
{
title: (
<div className='flex items-center gap-4'>
<Avatar
variant='rounded'
className='is-[58px] bs-[34px]'
sx={theme => ({
backgroundColor: 'var(--mui-palette-success-light)',
color: 'var(--mui-palette-success-main)'
})}
>
<i className='tabler-crown text-2xl' />
</Avatar>
<div className='flex flex-col'>
<Typography color='text.primary' className='font-medium'>
Premium Plan
</Typography>
<Typography variant='body2' color='text.secondary'>
Most popular choice
</Typography>
</div>
</div>
),
value: 'premium'
},
{
title: (
<div className='flex items-center gap-4'>
<Avatar
variant='rounded'
className='is-[58px] bs-[34px]'
sx={theme => ({
backgroundColor: 'var(--mui-palette-warning-light)',
color: 'var(--mui-palette-warning-main)'
})}
>
<i className='tabler-building text-2xl' />
</Avatar>
<div className='flex flex-col'>
<Typography color='text.primary' className='font-medium'>
Enterprise Plan
</Typography>
<Typography variant='body2' color='text.secondary'>
Advanced features for large teams
</Typography>
</div>
</div>
),
value: 'enterprise'
}
]
const currencies = [
{ code: 'USD', name: 'US Dollar' },
{ code: 'EUR', name: 'Euro' },
{ code: 'GBP', name: 'British Pound' },
{ code: 'JPY', name: 'Japanese Yen' },
{ code: 'AUD', name: 'Australian Dollar' },
{ code: 'CAD', name: 'Canadian Dollar' },
{ code: 'CHF', name: 'Swiss Franc' },
{ code: 'CNY', name: 'Chinese Yuan' },
{ code: 'IDR', name: 'Indonesian Rupiah' }
]
const timezones = [
'UTC',
'America/New_York',
'America/Los_Angeles',
'Europe/London',
'Europe/Paris',
'Asia/Tokyo',
'Asia/Shanghai',
'Asia/Jakarta',
'Australia/Sydney'
]
const planPricing = {
basic: { price: 29.99, features: ['Up to 5 users', 'Basic reporting', '24/7 support', 'Mobile app'] },
premium: {
price: 59.99,
features: ['Up to 25 users', 'Advanced reporting', 'Priority support', 'API access', 'Custom integrations']
},
enterprise: {
price: 129.99,
features: [
'Unlimited users',
'Enterprise reporting',
'Dedicated support',
'White-label solution',
'Custom development'
]
}
}
const CreateOrganization = () => {
const initialSelected: string = planData.filter(item => item.isSelected)[
planData.filter(item => item.isSelected).length - 1
].value
const router = useRouter()
// States
const [formData, setFormData] = useState<OrganizationRequest>({
organization_name: '',
organization_email: null,
organization_phone_number: null,
plan_type: initialSelected as 'basic' | 'premium' | 'enterprise',
admin_name: '',
admin_email: '',
admin_password: '',
outlet_name: '',
outlet_address: null,
outlet_timezone: null,
outlet_currency: 'USD'
})
const [errors, setErrors] = useState<Partial<Record<keyof OrganizationRequest, string>>>({})
const [submitError, setSubmitError] = useState<string | null>(null)
// Hooks
const { updatePageSettings } = useSettings()
const { createOrganization } = useOrganizationsMutation()
const handleInputChange = (field: keyof OrganizationRequest) => (event: ChangeEvent<HTMLInputElement>) => {
const value = event.target.value
setFormData(prev => ({
...prev,
[field]: value || null
}))
// Clear error when user starts typing
if (errors[field]) {
setErrors(prev => ({
...prev,
[field]: undefined
}))
}
}
const handlePlanChange = (prop: string | ChangeEvent<HTMLInputElement>) => {
const planType = typeof prop === 'string' ? prop : prop.target.value
setFormData(prev => ({
...prev,
plan_type: planType as 'basic' | 'premium' | 'enterprise'
}))
}
const validateForm = (): boolean => {
const newErrors: Partial<Record<keyof OrganizationRequest, string>> = {}
// Required fields validation
if (!formData.organization_name.trim()) {
newErrors.organization_name = 'Organization name is required'
} else if (formData.organization_name.length > 255) {
newErrors.organization_name = 'Organization name must be 255 characters or less'
}
if (!formData.admin_name.trim()) {
newErrors.admin_name = 'Admin name is required'
} else if (formData.admin_name.length > 255) {
newErrors.admin_name = 'Admin name must be 255 characters or less'
}
if (!formData.admin_email.trim()) {
newErrors.admin_email = 'Admin email is required'
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.admin_email)) {
newErrors.admin_email = 'Please enter a valid email address'
}
if (!formData.admin_password) {
newErrors.admin_password = 'Password is required'
} else if (formData.admin_password.length < 6) {
newErrors.admin_password = 'Password must be at least 6 characters long'
}
if (!formData.outlet_name.trim()) {
newErrors.outlet_name = 'Outlet name is required'
} else if (formData.outlet_name.length > 255) {
newErrors.outlet_name = 'Outlet name must be 255 characters or less'
}
if (!formData.outlet_currency) {
newErrors.outlet_currency = 'Currency is required'
} else if (formData.outlet_currency.length !== 3) {
newErrors.outlet_currency = 'Currency must be a 3-character ISO code'
}
// Optional email validation
if (formData.organization_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.organization_email)) {
newErrors.organization_email = 'Please enter a valid email address'
}
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
const handleSubmit = async () => {
if (!validateForm()) return
setSubmitError(null)
createOrganization.mutate(formData, {
onSuccess: () => {
router.push('/login')
}
})
}
// For Page specific settings
useEffect(() => {
return updatePageSettings({
skin: 'default'
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const selectedPlan = planPricing[formData.plan_type]
return (
<section className={classnames('md:plb-[100px] plb-6', frontCommonStyles.layoutSpacing)}>
<Card>
<Grid container>
<Grid size={{ md: 12, lg: 8 }}>
<CardContent className='flex flex-col max-sm:gap-y-5 gap-y-8 sm:p-8 border-be lg:border-be-0 lg:border-e bs-full'>
<div className='flex flex-col gap-2'>
<Typography variant='h4' className='flex items-center gap-2'>
<i className='tabler-building text-primary' />
Create Organization
</Typography>
<Typography>
Set up your organization with admin account and primary outlet. Choose the plan that best fits your
needs.
</Typography>
</div>
{submitError && (
<Alert severity='error' className='mb-4'>
{submitError}
</Alert>
)}
{/* Plan Selection */}
<div>
<Typography variant='h5' className='mbe-4 flex items-center gap-2'>
<i className='tabler-crown text-warning' />
Choose Your Plan
</Typography>
<Grid container spacing={4}>
{planData.map((item, index) => (
<CustomInputHorizontal
key={index}
type='radio'
name='plan-type'
data={item}
selected={formData.plan_type}
handleChange={handlePlanChange}
gridProps={{ size: { xs: 12, md: 4 } }}
/>
))}
</Grid>
</div>
{/* Organization Details */}
<div>
<Typography variant='h5' className='mbe-6 flex items-center gap-2'>
<i className='tabler-building text-info' />
Organization Details
</Typography>
<Grid container spacing={5}>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
required
label='Organization Name'
placeholder='My Company Ltd.'
value={formData.organization_name || ''}
onChange={handleInputChange('organization_name')}
error={!!errors.organization_name}
helperText={errors.organization_name}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
label='Organization Email'
placeholder='contact@mycompany.com'
type='email'
value={formData.organization_email || ''}
onChange={handleInputChange('organization_email')}
error={!!errors.organization_email}
helperText={errors.organization_email}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
label='Phone Number'
placeholder='+1 (555) 123-4567'
value={formData.organization_phone_number || ''}
onChange={handleInputChange('organization_phone_number')}
/>
</Grid>
</Grid>
</div>
{/* Admin Account */}
<div>
<Typography variant='h5' className='mbe-6 flex items-center gap-2'>
<i className='tabler-user-shield text-success' />
Admin Account
</Typography>
<Grid container spacing={5}>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
required
label='Admin Name'
placeholder='John Doe'
value={formData.admin_name || ''}
onChange={handleInputChange('admin_name')}
error={!!errors.admin_name}
helperText={errors.admin_name}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
required
label='Admin Email'
placeholder='admin@mycompany.com'
type='email'
value={formData.admin_email || ''}
onChange={handleInputChange('admin_email')}
error={!!errors.admin_email}
helperText={errors.admin_email}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
required
type='password'
label='Admin Password'
placeholder='Minimum 6 characters'
value={formData.admin_password || ''}
onChange={handleInputChange('admin_password')}
error={!!errors.admin_password}
helperText={errors.admin_password}
/>
</Grid>
</Grid>
</div>
{/* Outlet Information */}
<div>
<Typography variant='h5' className='mbe-6 flex items-center gap-2'>
<i className='tabler-store text-warning' />
Primary Outlet
</Typography>
<Grid container spacing={5}>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
fullWidth
required
label='Outlet Name'
placeholder='Main Store'
value={formData.outlet_name || ''}
onChange={handleInputChange('outlet_name')}
error={!!errors.outlet_name}
helperText={errors.outlet_name}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
select
fullWidth
required
label='Currency'
value={formData.outlet_currency}
onChange={handleInputChange('outlet_currency')}
error={!!errors.outlet_currency}
helperText={errors.outlet_currency}
>
{currencies.map(currency => (
<MenuItem key={currency.code} value={currency.code}>
{currency.code} - {currency.name}
</MenuItem>
))}
</CustomTextField>
</Grid>
<Grid size={{ xs: 12 }}>
<CustomTextField
fullWidth
label='Outlet Address'
placeholder='123 Main Street, City, State, Country'
value={formData.outlet_address || ''}
onChange={handleInputChange('outlet_address')}
/>
</Grid>
<Grid size={{ xs: 12, sm: 6 }}>
<CustomTextField
select
fullWidth
label='Timezone'
value={formData.outlet_timezone || ''}
onChange={handleInputChange('outlet_timezone')}
>
{timezones.map(tz => (
<MenuItem key={tz} value={tz}>
{tz}
</MenuItem>
))}
</CustomTextField>
</Grid>
</Grid>
</div>
</CardContent>
</Grid>
<Grid size={{ md: 12, lg: 4 }}>
<CardContent className='flex flex-col gap-8 sm:p-8'>
<div className='flex flex-col gap-2'>
<Typography variant='h4' className='flex items-center gap-2'>
<i className='tabler-receipt text-primary' />
Plan Summary
</Typography>
<Typography>Review your selected plan and get started with your organization.</Typography>
</div>
<div className='flex flex-col gap-5'>
<div className='flex flex-col gap-4 p-6 bg-actionHover rounded'>
<div className='flex items-center justify-between'>
<Typography className='font-medium capitalize'>{formData.plan_type} Plan</Typography>
<Chip
label={formData.plan_type === 'premium' ? 'Most Popular' : 'Selected'}
color={formData.plan_type === 'premium' ? 'success' : 'primary'}
size='small'
/>
</div>
<div className='flex items-baseline'>
<Typography variant='h1'>${selectedPlan.price}</Typography>
<Typography component='sub'>/month</Typography>
</div>
<div className='flex flex-col gap-2'>
{selectedPlan.features.map((feature, index) => (
<div key={index} className='flex items-center gap-2'>
<i className='tabler-check text-success text-sm' />
<Typography variant='body2'>{feature}</Typography>
</div>
))}
</div>
</div>
<div>
<div className='flex gap-2 items-center justify-between mbe-2'>
<Typography>Plan Cost</Typography>
<Typography color='text.primary' className='font-medium'>
${selectedPlan.price}
</Typography>
</div>
<div className='flex gap-2 items-center justify-between'>
<Typography>Setup Fee</Typography>
<Typography color='text.primary' className='font-medium'>
Free
</Typography>
</div>
<Divider className='mlb-4' />
<div className='flex gap-2 items-center justify-between'>
<Typography className='font-medium'>Total</Typography>
<Typography color='text.primary' className='font-medium'>
${selectedPlan.price}
</Typography>
</div>
</div>
<Button
variant='contained'
size='large'
onClick={handleSubmit}
disabled={createOrganization.isPending}
endIcon={
createOrganization.isPending ? (
<CircularProgress size={20} color='inherit' />
) : (
<DirectionalIcon ltrIconClass='tabler-arrow-right' rtlIconClass='tabler-arrow-left' />
)
}
>
{createOrganization.isPending ? 'Creating Organization...' : 'Create Organization'}
</Button>
</div>
<Typography variant='body2' className='text-center'>
By creating an organization, you agree to our Terms of Service and Privacy Policy. You can change your
plan anytime.
</Typography>
</CardContent>
</Grid>
</Grid>
</Card>
</section>
)
}
export default CreateOrganization
@@ -0,0 +1,976 @@
'use client';
import React, { useState, useEffect, useRef } from 'react';
import { RotateCw, Trophy, Trash2, RefreshCw, Shuffle, Sparkles, Gift } from 'lucide-react';
import { useVoucherRows } from '@/services/queries/vouchers';
import { Voucher, VoucherRow } from '@/types/services/voucher';
import { toast } from 'react-toastify';
interface SpinRow {
id: string;
rowNumber: number;
vouchers: Voucher[];
displayVouchers: Voucher[];
isSpinning: boolean;
isShuffling: boolean;
winner: Voucher | null;
wheelRef: React.RefObject<HTMLDivElement>;
selectedWinner: Voucher | null;
}
interface WinnerHistory {
rowNumber: number;
winner: Voucher;
timestamp: Date;
}
const RandomDrawApp: React.FC = () => {
const [spinRows, setSpinRows] = useState<SpinRow[]>([]);
const [numberOfRows, setNumberOfRows] = useState<number>(5);
const [winnersHistory, setWinnersHistory] = useState<WinnerHistory[]>([]);
const [isRevealingWinners, setIsRevealingWinners] = useState<boolean>(false);
const [revealedWinners, setRevealedWinners] = useState<Set<number>>(new Set());
const [isSequentialSpinning, setIsSequentialSpinning] = useState<boolean>(false);
const [currentSpinningRow, setCurrentSpinningRow] = useState<number | null>(null);
const [selectedPrize, setSelectedPrize] = useState<number>(1); // 1 for Emas 0.25 Gram, 2 for Emas 3 Gram
const audioContextRef = useRef<AudioContext | null>(null);
const tickIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
const shuffleIntervalRefs = useRef<Map<string, NodeJS.Timeout>>(new Map());
// Use React Query hook for fetching voucher data - disabled by default
const { data: voucherData, isLoading: isLoadingData, refetch: refetchVouchers, error: fetchError } = useVoucherRows({
rows: numberOfRows,
winner_number: selectedPrize
}, {
enabled: false // Disable automatic fetching - only fetch when Load Data is clicked
});
// Initialize Audio Context
useEffect(() => {
const initAudio = () => {
if (!audioContextRef.current) {
audioContextRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();
}
};
document.addEventListener('click', initAudio, { once: true });
return () => {
document.removeEventListener('click', initAudio);
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
};
}, []);
// Create tick sound effect
const playTickSound = () => {
if (!audioContextRef.current) return;
const ctx = audioContextRef.current;
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
oscillator.frequency.setValueAtTime(800, ctx.currentTime);
oscillator.frequency.exponentialRampToValueAtTime(200, ctx.currentTime + 0.05);
gainNode.gain.setValueAtTime(0, ctx.currentTime);
gainNode.gain.linearRampToValueAtTime(0.1, ctx.currentTime + 0.01);
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.05);
oscillator.start(ctx.currentTime);
oscillator.stop(ctx.currentTime + 0.05);
};
// Create drum roll sound
const playDrumRoll = () => {
if (!audioContextRef.current) return;
const ctx = audioContextRef.current;
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
const noiseNode = ctx.createBufferSource();
// Create noise buffer for snare-like sound
const bufferSize = ctx.sampleRate * 0.05;
const buffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1;
}
noiseNode.buffer = buffer;
oscillator.connect(gainNode);
noiseNode.connect(gainNode);
gainNode.connect(ctx.destination);
oscillator.frequency.setValueAtTime(200, ctx.currentTime);
gainNode.gain.setValueAtTime(0.05, ctx.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.1);
oscillator.start(ctx.currentTime);
oscillator.stop(ctx.currentTime + 0.1);
noiseNode.start(ctx.currentTime);
};
// Create winner sound
const playWinnerSound = () => {
if (!audioContextRef.current) return;
const ctx = audioContextRef.current;
const notes = [523.25, 659.25, 783.99, 1046.5]; // C, E, G, C (higher octave)
notes.forEach((freq, index) => {
const oscillator = ctx.createOscillator();
const gainNode = ctx.createGain();
oscillator.connect(gainNode);
gainNode.connect(ctx.destination);
oscillator.frequency.setValueAtTime(freq, ctx.currentTime + index * 0.1);
gainNode.gain.setValueAtTime(0, ctx.currentTime + index * 0.1);
gainNode.gain.linearRampToValueAtTime(0.2, ctx.currentTime + index * 0.1 + 0.05);
gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + index * 0.1 + 0.5);
oscillator.start(ctx.currentTime + index * 0.1);
oscillator.stop(ctx.currentTime + index * 0.1 + 0.5);
});
};
// Start tick sound during spinning
const startTickSound = (rowId: string, duration: number) => {
const existingInterval = tickIntervalRefs.current.get(rowId);
if (existingInterval) {
clearTimeout(existingInterval);
}
let tickInterval = 50;
const maxInterval = 200;
const intervalIncrement = (maxInterval - tickInterval) / (duration / 100);
const tick = () => {
playTickSound();
tickInterval += intervalIncrement;
if (tickInterval < maxInterval) {
const timeoutId = setTimeout(tick, Math.min(tickInterval, maxInterval));
tickIntervalRefs.current.set(rowId, timeoutId);
}
};
tick();
setTimeout(() => {
const interval = tickIntervalRefs.current.get(rowId);
if (interval) {
clearTimeout(interval);
tickIntervalRefs.current.delete(rowId);
}
}, duration + 100);
};
// Shuffle array
const shuffleArray = <T,>(array: T[]): T[] => {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
};
// Process voucher data when it changes
useEffect(() => {
if (voucherData && voucherData.rows) {
const newSpinRows: SpinRow[] = voucherData.rows.map(row => ({
id: `row-${row.row_number}-${Date.now()}`,
rowNumber: row.row_number,
vouchers: row.vouchers,
displayVouchers: [...row.vouchers],
isSpinning: false,
isShuffling: false,
winner: null,
wheelRef: React.createRef<HTMLDivElement>(),
selectedWinner: null,
}));
setSpinRows(newSpinRows);
setRevealedWinners(new Set());
}
}, [voucherData]);
// Show error if fetch failed
useEffect(() => {
if (fetchError) {
toast.error('Failed to load voucher data. Please check your connection and try again.');
}
}, [fetchError]);
// Remove auto-refetch - data will only load when Load Data button is clicked
// Shuffle all rows (Acak functionality)
const shuffleAllRows = () => {
setSpinRows(prev => prev.map(row => ({
...row,
isShuffling: true
})));
// Animate shuffling for each row
spinRows.forEach((row, index) => {
let shuffleCount = 0;
const maxShuffles = 20;
const shuffleInterval = setInterval(() => {
shuffleCount++;
setSpinRows(prev => prev.map(r => {
if (r.id === row.id) {
return {
...r,
displayVouchers: shuffleArray(r.vouchers)
};
}
return r;
}));
playTickSound();
if (shuffleCount >= maxShuffles) {
clearInterval(shuffleInterval);
setTimeout(() => {
setSpinRows(prev => prev.map(r => {
if (r.id === row.id) {
return {
...r,
isShuffling: false
};
}
return r;
}));
}, index * 100);
}
}, 100);
shuffleIntervalRefs.current.set(row.id, shuffleInterval as any);
});
};
// Reveal winners dramatically
const revealWinnersDramatically = async () => {
setIsRevealingWinners(true);
setRevealedWinners(new Set());
// First, arrange winners to be in the winner zone for each row
const arrangedRows = spinRows.map(row => {
const winner = row.vouchers.find(v => v.is_winner);
if (!winner) return row;
// Create a new display order with winner at position 3 or 4 (will be in winner zone)
const otherVouchers = row.vouchers.filter(v => v.voucher_code !== winner.voucher_code);
const shuffledOthers = shuffleArray(otherVouchers);
// Place winner at index 3 (4th position) which will be in the winner zone
const newDisplayVouchers = [
...shuffledOthers.slice(0, 3),
winner,
...shuffledOthers.slice(3)
];
return {
...row,
displayVouchers: newDisplayVouchers
};
});
// Update display to show arranged vouchers
setSpinRows(arrangedRows);
// Start drum roll effect
const drumRollInterval = setInterval(() => {
playDrumRoll();
}, 100);
// Create a scrolling/spinning effect for all wheels simultaneously
let scrollSpeed = 50;
let currentScroll = 0;
const maxScroll = 2000;
const deceleration = 0.95;
const spinInterval = setInterval(() => {
currentScroll += scrollSpeed;
scrollSpeed *= deceleration;
// Apply scrolling to all wheels
arrangedRows.forEach(row => {
const wheelElement = row.wheelRef.current;
if (wheelElement) {
wheelElement.style.transition = 'none';
wheelElement.style.transform = `translateY(${-currentScroll}px)`;
}
});
// Stop when speed is very slow
if (scrollSpeed < 0.5 || currentScroll >= maxScroll) {
clearInterval(spinInterval);
clearInterval(drumRollInterval);
// Final positioning - snap to winner position
arrangedRows.forEach(row => {
const wheelElement = row.wheelRef.current;
if (wheelElement) {
const CARD_HEIGHT = 80;
const WINNER_ZONE_TOP = 260; // Top position of winner zone
// Position 4th card (index 3) exactly at the winner zone
const finalPosition = -(3 * CARD_HEIGHT - WINNER_ZONE_TOP);
wheelElement.style.transition = 'transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
wheelElement.style.transform = `translateY(${finalPosition}px)`;
}
});
}
}, 20);
// Wait for scrolling to complete
await new Promise(resolve => setTimeout(resolve, 3000));
// Play winner sound
playWinnerSound();
// Collect all winners
const winnersToReveal: { row: SpinRow, winner: Voucher }[] = [];
arrangedRows.forEach(row => {
const winner = row.vouchers.find(v => v.is_winner);
if (winner) {
winnersToReveal.push({ row, winner });
}
});
// Update all winners at once with highlighting
const allWinnerNumbers = new Set<number>();
const historyEntries: WinnerHistory[] = [];
winnersToReveal.forEach(({ row, winner }) => {
allWinnerNumbers.add(row.rowNumber);
historyEntries.push({
rowNumber: row.rowNumber,
winner: winner,
timestamp: new Date()
});
});
// Update state to highlight winners
setRevealedWinners(allWinnerNumbers);
setSpinRows(prev => prev.map(r => {
const winnerInfo = winnersToReveal.find(w => w.row.id === r.id);
if (winnerInfo) {
return {
...r,
winner: winnerInfo.winner,
selectedWinner: winnerInfo.winner
};
}
return r;
}));
setWinnersHistory(prev => [...prev, ...historyEntries]);
setIsRevealingWinners(false);
};
const performDramaticSpin = (row: SpinRow, isSequential: boolean = false) => {
const wheelElement = row.wheelRef.current;
if (!wheelElement) return;
const winner = row.vouchers.find(v => v.is_winner);
if (!winner) {
console.error('No winner found in vouchers');
return;
}
const CARD_HEIGHT = 80;
const WINNER_ZONE_TOP = 260; // Top position of winner zone
// Shuffle the display vouchers to create more dramatic effect
const shuffledVouchers = shuffleArray([...row.vouchers]);
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
// Update display vouchers with shuffled order
setSpinRows(prev => prev.map(r =>
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
));
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
setTimeout(() => {
// More dramatic spinning with multiple phases
const minSpins = 15;
const maxSpins = 25;
const spins = minSpins + Math.random() * (maxSpins - minSpins);
const totalItems = shuffledVouchers.length;
const totalRotations = Math.floor(spins);
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
const winnerScrollPosition = winnerIndex * CARD_HEIGHT;
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
const distance = Math.abs(finalPosition);
const baseDuration = 4000; // Longer base duration
const maxDuration = 7000; // Longer max duration
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
// Phase 1: Fast initial spin
const phase1Duration = duration * 0.3;
const phase1Distance = finalPosition * 0.7;
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
// Phase 2: Slower approach to final position
setTimeout(() => {
wheelElement.style.transform = `translateY(${finalPosition}px)`;
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
}, phase1Duration);
startTickSound(row.id, duration);
setTimeout(() => {
const interval = tickIntervalRefs.current.get(row.id);
if (interval) {
clearTimeout(interval);
tickIntervalRefs.current.delete(row.id);
}
playWinnerSound();
setSpinRows(prev => prev.map(r =>
r.id === row.id
? { ...r, isSpinning: false, winner: winner, selectedWinner: winner }
: r
));
setWinnersHistory(prev => [...prev, {
rowNumber: row.rowNumber,
winner: winner,
timestamp: new Date()
}]);
// If this is sequential spinning, trigger next row
if (isSequential) {
const nextRowIndex = spinRows.findIndex(r => r.id === row.id) + 1;
if (nextRowIndex < spinRows.length) {
setTimeout(() => {
spinSequentialRow(nextRowIndex);
}, 2000); // Wait 2 seconds before next spin
} else {
// All rows completed
setIsSequentialSpinning(false);
setCurrentSpinningRow(null);
}
}
// Keep the winner in the winner zone - don't reset position
// The winning card will stay exactly where it landed in the winner zone
}, duration);
}, 100);
};
const performSpin = (row: SpinRow) => {
const wheelElement = row.wheelRef.current;
if (!wheelElement) return;
const winner = row.vouchers.find(v => v.is_winner);
if (!winner) {
console.error('No winner found in vouchers');
return;
}
const CARD_HEIGHT = 80;
const WINNER_ZONE_TOP = 260; // Top position of winner zone
// Shuffle the display vouchers to create more dramatic effect
const shuffledVouchers = shuffleArray([...row.vouchers]);
const winnerIndex = shuffledVouchers.findIndex(v => v.voucher_code === winner.voucher_code);
// Update display vouchers with shuffled order
setSpinRows(prev => prev.map(r =>
r.id === row.id ? { ...r, displayVouchers: shuffledVouchers } : r
));
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
setTimeout(() => {
// More dramatic spinning with multiple phases
const minSpins = 15;
const maxSpins = 25;
const spins = minSpins + Math.random() * (maxSpins - minSpins);
const totalItems = shuffledVouchers.length;
const totalRotations = Math.floor(spins);
const baseScrollDistance = totalRotations * totalItems * CARD_HEIGHT;
const winnerScrollPosition = winnerIndex * CARD_HEIGHT;
const finalPosition = -(baseScrollDistance + winnerScrollPosition) + WINNER_ZONE_TOP;
const distance = Math.abs(finalPosition);
const baseDuration = 4000; // Longer base duration
const maxDuration = 7000; // Longer max duration
const duration = Math.min(baseDuration + (distance / 8000) * 2000, maxDuration);
// Phase 1: Fast initial spin
const phase1Duration = duration * 0.3;
const phase1Distance = finalPosition * 0.7;
wheelElement.style.transform = `translateY(${phase1Distance}px)`;
wheelElement.style.transition = `transform ${phase1Duration}ms cubic-bezier(0.25, 0.46, 0.45, 0.94)`;
// Phase 2: Slower approach to final position
setTimeout(() => {
wheelElement.style.transform = `translateY(${finalPosition}px)`;
wheelElement.style.transition = `transform ${duration - phase1Duration}ms cubic-bezier(0.17, 0.67, 0.12, 0.99)`;
}, phase1Duration);
startTickSound(row.id, duration);
setTimeout(() => {
const interval = tickIntervalRefs.current.get(row.id);
if (interval) {
clearTimeout(interval);
tickIntervalRefs.current.delete(row.id);
}
playWinnerSound();
setSpinRows(prev => prev.map(r =>
r.id === row.id
? { ...r, isSpinning: false, winner: winner, selectedWinner: winner }
: r
));
setWinnersHistory(prev => [...prev, {
rowNumber: row.rowNumber,
winner: winner,
timestamp: new Date()
}]);
// Keep the winner in the winner zone - don't reset position
// The winning card will stay exactly where it landed in the winner zone
}, duration);
}, 100);
};
const spinSequentialRow = (rowIndex: number) => {
if (rowIndex >= spinRows.length) {
setIsSequentialSpinning(false);
setCurrentSpinningRow(null);
return;
}
const row = spinRows[rowIndex];
if (!row || row.isSpinning || row.winner) {
// Skip this row and go to next
spinSequentialRow(rowIndex + 1);
return;
}
setCurrentSpinningRow(row.rowNumber);
setSpinRows(prev => prev.map(r =>
r.id === row.id ? { ...r, isSpinning: true, selectedWinner: null } : r
));
const wheelElement = row.wheelRef.current;
if (wheelElement) {
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
}
performDramaticSpin(row, true);
};
const startSequentialSpinning = () => {
if (spinRows.length === 0) return;
// Clear any existing results
setWinnersHistory([]);
setRevealedWinners(new Set());
setSpinRows(prev => prev.map(row => ({
...row,
isSpinning: false,
isShuffling: false,
winner: null,
selectedWinner: null,
displayVouchers: [...row.vouchers]
})));
// Reset all wheel positions
spinRows.forEach(row => {
const wheelElement = row.wheelRef.current;
if (wheelElement) {
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
}
});
setIsSequentialSpinning(true);
setCurrentSpinningRow(null);
// Start with first row after a short delay
setTimeout(() => {
spinSequentialRow(0);
}, 500);
};
const spinWheel = (rowId: string) => {
const row = spinRows.find(r => r.id === rowId);
if (!row || row.isSpinning || row.winner) return;
setSpinRows(prev => prev.map(r =>
r.id === rowId ? { ...r, isSpinning: true, selectedWinner: null } : r
));
const wheelElement = row.wheelRef.current;
if (wheelElement) {
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
wheelElement.offsetHeight;
}
performSpin(row);
};
const clearResults = () => {
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
tickIntervalRefs.current.clear();
shuffleIntervalRefs.current.clear();
setWinnersHistory([]);
setRevealedWinners(new Set());
setIsSequentialSpinning(false);
setCurrentSpinningRow(null);
setSpinRows(prev => prev.map(row => ({
...row,
isSpinning: false,
isShuffling: false,
winner: null,
selectedWinner: null,
displayVouchers: [...row.vouchers]
})));
spinRows.forEach(row => {
const wheelElement = row.wheelRef.current;
if (wheelElement) {
wheelElement.style.transition = 'none';
wheelElement.style.transform = 'translateY(0px)';
}
});
};
const refreshData = async () => {
tickIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
shuffleIntervalRefs.current.forEach(timeout => clearTimeout(timeout));
tickIntervalRefs.current.clear();
shuffleIntervalRefs.current.clear();
try {
await refetchVouchers();
toast.success('Data refreshed successfully');
} catch (error) {
toast.error('Failed to refresh data');
}
};
const formatPhoneNumber = (phone: string) => {
return phone.substring(0, 5) + '****' + phone.substring(phone.length - 2);
};
return (
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 text-gray-900 p-6">
<style jsx>{`
@keyframes bounce-in {
0% {
transform: scale(0.3);
opacity: 0;
}
50% {
transform: scale(1.05);
}
70% {
transform: scale(0.9);
}
100% {
transform: scale(1);
opacity: 1;
}
}
.animate-bounce-in {
animation: bounce-in 0.6s ease-out;
}
`}</style>
<div className="max-w-full px-4 mx-auto">
{/* Header */}
<div className="text-center mb-8">
<h1 className="text-5xl font-bold bg-gradient-to-r from-primary to-purple-600 bg-clip-text text-transparent mb-2">
Voucher Lucky Draw
</h1>
</div>
<div className="space-y-4">
{/* Controls Section - Compact Layout */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-3">
{/* Configuration Card */}
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-3 text-gray-900">
Configuration
</h2>
<div className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<div>
<label className="block text-xs font-medium text-gray-700 mb-1">
Number of Rows
</label>
<input
type="number"
min="1"
max="10"
value={numberOfRows}
onChange={(e) => setNumberOfRows(parseInt(e.target.value) || 1)}
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
disabled={isLoadingData}
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-700 mb-1">
Prize Selection
</label>
<select
value={selectedPrize}
onChange={(e) => setSelectedPrize(parseInt(e.target.value))}
className="w-full bg-white border border-gray-300 rounded p-1.5 text-sm text-gray-900 focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20"
disabled={isLoadingData}
>
<option value={1}>🥇 Emas 0.25 Gram</option>
<option value={2}>🥇 Emas 3 Gram</option>
</select>
</div>
</div>
<button
onClick={refreshData}
disabled={isLoadingData}
className="w-full px-3 py-1.5 bg-primary hover:bg-primary/90 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
>
<RefreshCw size={14} className={isLoadingData ? 'animate-spin' : ''} />
{isLoadingData ? 'Loading...' : 'Load Data'}
</button>
</div>
{spinRows.length > 0 && (
<div className="mt-3 p-2 bg-gray-50 rounded text-xs text-gray-600">
<div>Rows: {spinRows.length} | Vouchers: {spinRows.reduce((acc, row) => acc + row.vouchers.length, 0)}</div>
</div>
)}
</div>
{/* Actions Card */}
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-3 text-gray-900">
Actions
</h2>
<div className="space-y-2">
<button
onClick={shuffleAllRows}
disabled={isLoadingData || spinRows.some(r => r.isShuffling) || spinRows.length === 0}
className="w-full px-3 py-1.5 bg-purple-600 hover:bg-purple-700 disabled:bg-gray-400 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
>
<Shuffle size={14} className={spinRows.some(r => r.isShuffling) ? 'animate-pulse' : ''} />
Shuffle All
</button>
<button
onClick={startSequentialSpinning}
disabled={isSequentialSpinning || spinRows.length === 0}
className="w-full px-3 py-1.5 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 disabled:from-gray-400 disabled:to-gray-500 text-white text-sm font-bold rounded flex items-center justify-center gap-1 transition-all"
>
<Trophy size={14} className={isSequentialSpinning ? 'animate-spin' : ''} />
{isSequentialSpinning ? 'Spinning...' : 'Spin for Winner'}
</button>
{winnersHistory.length > 0 && (
<button
onClick={clearResults}
className="w-full px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white text-sm font-semibold rounded flex items-center justify-center gap-1 transition-colors"
>
<Trash2 size={14} />
Clear Results
</button>
)}
</div>
</div>
{/* Winners Summary Card */}
<div className="bg-white rounded-lg p-4 border border-gray-200 shadow-sm">
<h2 className="text-lg font-semibold mb-3 text-gray-900 flex items-center gap-2">
<Trophy className="text-yellow-500" size={18} />
Winners
</h2>
{winnersHistory.length > 0 ? (
<div className="space-y-1 max-h-32 overflow-y-auto">
{winnersHistory.map((history) => (
<div
key={`${history.rowNumber}-${history.timestamp.getTime()}`}
className="p-1.5 bg-yellow-50 border border-yellow-200 rounded text-xs"
>
<div className="font-semibold text-yellow-700">
Row {history.rowNumber}: {history.winner.name}
</div>
<div className="text-xs text-yellow-600">
{history.winner.voucher_code}
</div>
</div>
))}
</div>
) : (
<div className="text-center py-2">
<Trophy className="mx-auto text-gray-300 mb-1" size={20} />
<p className="text-gray-500 text-xs">No winners yet</p>
</div>
)}
</div>
</div>
{/* Spin Rows - Display in grid */}
<div className={`grid gap-4 ${
spinRows.length === 1 ? 'grid-cols-1' :
spinRows.length === 2 ? 'grid-cols-1 lg:grid-cols-2' :
spinRows.length === 3 ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3' :
spinRows.length === 4 ? 'grid-cols-1 md:grid-cols-2 xl:grid-cols-4' :
spinRows.length === 5 ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5' :
'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
}`}>
{spinRows.map((row) => (
<div key={row.id} className={`bg-white rounded-lg border-2 shadow-sm transition-all ${
row.isShuffling ? 'border-purple-400 animate-pulse' : 'border-gray-200'
}`}>
<div className="p-4 border-b border-gray-200">
{row.winner && (
<div className="mt-2 p-2 bg-yellow-50 border border-yellow-200 rounded-lg animate-bounce-in">
<div className="flex items-center gap-1 text-sm">
<Trophy className="text-yellow-500" size={16} />
<span className="font-semibold text-yellow-700 truncate">
{row.winner.name}
</span>
</div>
<div className="text-xs text-yellow-600 mt-1">
{row.winner.voucher_code}
</div>
</div>
)}
</div>
{/* Wheel Container */}
<div
className="relative bg-gray-50 overflow-hidden"
style={{ height: '600px' }}
>
{/* Subtle Winner Zone Indicator */}
<div
className="absolute left-0 right-0 z-10 pointer-events-none"
style={{
top: '260px',
height: '80px',
background: 'linear-gradient(90deg, transparent 0%, rgba(34, 197, 94, 0.1) 20%, rgba(34, 197, 94, 0.2) 50%, rgba(34, 197, 94, 0.1) 80%, transparent 100%)',
borderTop: '2px dashed rgba(34, 197, 94, 0.3)',
borderBottom: '2px dashed rgba(34, 197, 94, 0.3)'
}}
>
<div className="absolute right-2 top-1/2 transform -translate-y-1/2">
<div className="bg-green-500 text-white px-2 py-1 rounded text-xs font-bold shadow-lg">
🏆 WINNER
</div>
</div>
</div>
{/* Scrolling Cards */}
<div
ref={row.wheelRef}
className="absolute inset-0"
style={{ transform: 'translateY(0px)' }}
>
{Array.from({ length: 50 }, (_, repeatIndex) =>
row.displayVouchers.map((voucher, voucherIndex) => {
const isSelectedWinner = row.selectedWinner?.voucher_code === voucher.voucher_code;
return (
<div
key={`${repeatIndex}-${voucherIndex}`}
className={`flex items-center px-4 border-b border-gray-300 transition-all duration-300 ${
isSelectedWinner
? 'bg-gradient-to-r from-yellow-100 to-yellow-200 border-yellow-300 shadow-lg'
: voucherIndex % 2 === 0
? 'bg-white hover:bg-gray-50'
: 'bg-gray-50 hover:bg-gray-100'
}`}
style={{
height: '80px',
minHeight: '80px',
maxHeight: '80px',
boxSizing: 'border-box'
}}
>
<div className="flex-1">
<div className={`font-bold text-lg mb-1 ${
isSelectedWinner ? 'text-yellow-600' : 'text-gray-900'
}`}>
{voucher.voucher_code}
</div>
<div className={`text-sm ${
isSelectedWinner ? 'text-yellow-700' : 'text-gray-600'
}`}>
{voucher.name}
</div>
</div>
<div className="text-right">
<div className="text-gray-500 text-xs">
{formatPhoneNumber(voucher.phone_number)}
</div>
{isSelectedWinner && (
<Trophy className="inline ml-2 text-yellow-500" size={16} />
)}
</div>
</div>
);
})
)}
</div>
{/* Gradient Overlays */}
<div className="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-gray-50 via-gray-50/70 to-transparent pointer-events-none z-40"></div>
<div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-gray-50 via-gray-50/70 to-transparent pointer-events-none z-40"></div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
);
};
export default RandomDrawApp;
@@ -0,0 +1,7 @@
import AccountList from '@/views/apps/account'
const AccountPage = () => {
return <AccountList />
}
export default AccountPage
@@ -0,0 +1,7 @@
import CashBankDetail from '@/views/apps/cash-bank/detail'
const CashBankDetailPage = () => {
return <CashBankDetail />
}
export default CashBankDetailPage
@@ -0,0 +1,18 @@
import CashBankDetailTransactionContent from '@/views/apps/cash-bank/detail/transaction/CashBankDetailTransactionContent'
import CashBankDetailTransactionHeader from '@/views/apps/cash-bank/detail/transaction/CashBankDetailTransactionHeader'
import Grid from '@mui/material/Grid2'
const TransactionPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<CashBankDetailTransactionHeader title='Giro 1-10003' transaction='Terima Pembayaran Tagihan' />
</Grid>
<Grid size={{ xs: 12 }}>
<CashBankDetailTransactionContent />
</Grid>
</Grid>
)
}
export default TransactionPage
@@ -0,0 +1,7 @@
import CashBankList from '@/views/apps/cash-bank/CashBankList'
const CashBankPage = () => {
return <CashBankList />
}
export default CashBankPage
@@ -0,0 +1,18 @@
import ExpenseDetailContent from '@/views/apps/expense/detail/ExpenseDetailContent'
import ExpenseDetailHeader from '@/views/apps/expense/detail/ExpenseDetailHeader'
import Grid from '@mui/material/Grid2'
const ExpenseDetailPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ExpenseDetailHeader />
</Grid>
<Grid size={{ xs: 12 }}>
<ExpenseDetailContent />
</Grid>
</Grid>
)
}
export default ExpenseDetailPage
@@ -0,0 +1,18 @@
import ExpenseAddForm from '@/views/apps/expense/add/ExpenseAddForm'
import ExpenseAddHeader from '@/views/apps/expense/add/ExpenseAddHeader'
import Grid from '@mui/material/Grid2'
const ExpenseAddPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ExpenseAddHeader />
</Grid>
<Grid size={{ xs: 12 }}>
<ExpenseAddForm />
</Grid>
</Grid>
)
}
export default ExpenseAddPage
@@ -0,0 +1,7 @@
import ExpenseList from '@/views/apps/expense/list'
const ExpensePage = () => {
return <ExpenseList />
}
export default ExpensePage
@@ -0,0 +1,18 @@
import FixedAssetAddForm from '@/views/apps/fixed-assets/add/FixedAssetAddForm'
import FixedAssetAddHeader from '@/views/apps/fixed-assets/add/FixedAssetAddHeader'
import Grid from '@mui/material/Grid2'
const FixedAssetPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<FixedAssetAddHeader />
</Grid>
<Grid size={{ xs: 12 }}>
<FixedAssetAddForm />
</Grid>
</Grid>
)
}
export default FixedAssetPage
@@ -0,0 +1,7 @@
import FixedAssetList from '@/views/apps/fixed-assets'
const FixedAssetPage = () => {
return <FixedAssetList />
}
export default FixedAssetPage
@@ -3,12 +3,11 @@ import Grid from '@mui/material/Grid2'
// Component Imports
import ProductAddHeader from '@views/apps/ecommerce/products/add/ProductAddHeader'
import ProductInformation from '@views/apps/ecommerce/products/add/ProductInformation'
import ProductImage from '@views/apps/ecommerce/products/add/ProductImage'
import ProductVariants from '@views/apps/ecommerce/products/add/ProductVariants'
import ProductInventory from '@views/apps/ecommerce/products/add/ProductInventory'
import ProductPricing from '@views/apps/ecommerce/products/add/ProductPricing'
import ProductInformation from '@views/apps/ecommerce/products/add/ProductInformation'
import ProductOrganize from '@views/apps/ecommerce/products/add/ProductOrganize'
import ProductPricing from '@views/apps/ecommerce/products/add/ProductPricing'
import ProductVariants from '@views/apps/ecommerce/products/add/ProductVariants'
const eCommerceProductsEdit = () => {
return (
@@ -27,9 +26,6 @@ const eCommerceProductsEdit = () => {
<Grid size={{ xs: 12 }}>
<ProductVariants />
</Grid>
<Grid size={{ xs: 12 }}>
<ProductInventory />
</Grid>
</Grid>
</Grid>
<Grid size={{ xs: 12, md: 4 }}>
@@ -0,0 +1,7 @@
import IngredientDetail from '@/views/apps/ecommerce/products/ingredient/detail'
const IngredientDetailPage = () => {
return <IngredientDetail />
}
export default IngredientDetailPage
@@ -0,0 +1,317 @@
'use client'
import { useInventoryAnalytics } from '@/services/queries/analytics'
import { useOutletById } from '@/services/queries/outlets'
import { formatDateDDMMYYYY } from '@/utils/transform'
import ReportGeneratorComponent from '@/views/dashboards/daily-report/report-generator'
import ReportHeader from '@/views/dashboards/daily-report/report-header'
import { useRef, useState } from 'react'
const ExportInventoryPage = () => {
const reportRef = useRef<HTMLDivElement | null>(null)
const [now, setNow] = useState(new Date())
const [selectedDate, setSelectedDate] = useState(new Date())
const [dateRange, setDateRange] = useState({
startDate: new Date(),
endDate: new Date()
})
const [filterType, setFilterType] = useState<'single' | 'range'>('single') // 'single' or 'range'
const getDateParams = () => {
if (filterType === 'single') {
return {
date_from: formatDateDDMMYYYY(selectedDate),
date_to: formatDateDDMMYYYY(selectedDate)
}
} else {
return {
date_from: formatDateDDMMYYYY(dateRange.startDate),
date_to: formatDateDDMMYYYY(dateRange.endDate)
}
}
}
const dateParams = getDateParams()
const { data: outlet } = useOutletById()
const { data: inventory } = useInventoryAnalytics(dateParams)
const handleGeneratePDF = async () => {
const reportElement = reportRef.current
try {
// Import jsPDF dan html2canvas
const jsPDF = (await import('jspdf')).default
const html2canvas = (await import('html2canvas')).default
// Optimized canvas capture dengan scale lebih rendah
const canvas = await html2canvas(reportElement!, {
scale: 1.5, // Reduced from 2 to 1.5
useCORS: true,
allowTaint: true,
backgroundColor: '#ffffff',
logging: false, // Disable logging for performance
removeContainer: true, // Clean up after capture
imageTimeout: 0, // No timeout for image loading
height: reportElement!.scrollHeight,
width: reportElement!.scrollWidth
})
// Compress canvas using JPEG with quality setting
const imgData = canvas.toDataURL('image/jpeg', 0.85) // JPEG with 85% quality instead of PNG
// Create PDF with compression
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4',
compress: true // Enable built-in compression
})
const imgWidth = 210
const pageHeight = 295
const imgHeight = (canvas.height * imgWidth) / canvas.width
let heightLeft = imgHeight
let position = 0
// Add first page with compressed image
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST') // Use FAST compression
heightLeft -= pageHeight
// Handle multiple pages if needed
while (heightLeft >= 0) {
position = heightLeft - imgHeight
pdf.addPage()
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
heightLeft -= pageHeight
}
// Additional compression options
pdf.setProperties({
title: `Laporan Inventori`,
subject: 'Laporan Inventori',
author: 'Apskel POS System',
creator: 'Apskel'
})
// Save with optimized settings
const fileName =
filterType === 'single'
? `laporan-inventory-${formatDateForInput(selectedDate)}.pdf`
: `laporan-inventory-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
pdf.save(fileName, {
returnPromise: true
})
// Clean up canvas to free memory
canvas.width = canvas.height = 0
} catch (error) {
console.error('Error generating PDF:', error)
alert('Terjadi kesalahan saat membuat PDF. Pastikan jsPDF dan html2canvas sudah terinstall.')
}
}
const formatDateForInput = (date: Date) => {
return date.toISOString().split('T')[0]
}
const getReportPeriodText = () => {
if (filterType === 'single') {
return `${formatDateDDMMYYYY(selectedDate)} - ${formatDateDDMMYYYY(selectedDate)}`
} else {
return `${formatDateDDMMYYYY(dateRange.startDate)} - ${formatDateDDMMYYYY(dateRange.endDate)}`
}
}
const productSummary = {
totalQuantity: inventory?.products?.reduce((sum, item) => sum + (item?.quantity || 0), 0) || 0,
totalIn: inventory?.products?.reduce((sum, item) => sum + (item?.total_in || 0), 0) || 0,
totalOut: inventory?.products?.reduce((sum, item) => sum + (item?.total_out || 0), 0) || 0
}
const ingredientSummary = {
totalQuantity: inventory?.ingredients?.reduce((sum, item) => sum + (item?.quantity || 0), 0) || 0,
totalIn: inventory?.ingredients?.reduce((sum, item) => sum + (item?.total_in || 0), 0) || 0,
totalOut: inventory?.ingredients?.reduce((sum, item) => sum + (item?.total_out || 0), 0) || 0
}
return (
<div className='min-h-screen'>
{/* Control Panel */}
<ReportGeneratorComponent
// Props wajib
reportTitle='Laporan Inventori'
filterType={filterType}
selectedDate={selectedDate}
dateRange={dateRange}
onFilterTypeChange={setFilterType}
onSingleDateChange={setSelectedDate}
onDateRangeChange={setDateRange}
onGeneratePDF={handleGeneratePDF}
// Props opsional
// isGenerating={isGenerating}
// customQuickActions={customQuickActions}
// labels={customLabels}
/>
<div ref={reportRef} className='max-w-4xl mx-auto bg-white min-h-[297mm]' style={{ width: '210mm' }}>
{/* Header */}
<ReportHeader
outlet={outlet}
reportTitle='Laporan Inventori'
reportSubtitle='Laporan'
brandName='Apskel'
brandColor='#36175e'
periode={getReportPeriodText()}
/>
{/* Ringkasan */}
<div className='p-8'>
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
1. Ringkasan
</h3>
<div className='grid grid-cols-2 gap-6'>
<div className='space-y-4'>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Item</span>
<span className='font-semibold text-gray-800'>{inventory?.summary.total_products}</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Item Masuk</span>
<span className='font-semibold text-gray-800'>{inventory?.summary.low_stock_products}</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Item Keluar</span>
<span className='font-semibold text-gray-800'>{inventory?.summary.zero_stock_products}</span>
</div>
</div>
<div className='space-y-4'>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Ingredient</span>
<span className='font-semibold text-gray-800'>{inventory?.summary.total_ingredients}</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Ingredient Masuk</span>
<span className='font-semibold text-gray-800'>{inventory?.summary.low_stock_ingredients}</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Ingredient Keluar</span>
<span className='font-semibold text-gray-800'>{inventory?.summary.zero_stock_ingredients}</span>
</div>
</div>
</div>
</div>
{/* Item */}
<div className='px-8 pb-8'>
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
2. Item
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<th className='text-left p-3 font-semibold'>Nama</th>
<th className='text-center p-3 font-semibold'>Kategori</th>
<th className='text-center p-3 font-semibold'>Stock</th>
<th className='text-center p-3 font-semibold'>Masuk</th>
<th className='text-center p-3 font-semibold'>Keluar</th>
</tr>
</thead>
<tbody>
{inventory?.products?.map((product, index) => {
let rowClass = index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
if (product.is_zero_stock) {
rowClass = 'bg-red-300' // Merah untuk stok habis
} else if (product.is_low_stock) {
rowClass = 'bg-yellow-300' // Kuning untuk stok sedikit
}
return (
<tr key={index} className={rowClass}>
<td className='p-3 font-medium text-gray-800'>{product.product_name}</td>
<td className='p-3 font-medium text-gray-800'>{product.category_name}</td>
<td className='p-3 text-center text-gray-700'>{product.quantity}</td>
<td className='p-3 text-center text-gray-700'>{product.total_in}</td>
<td className='p-3 text-center text-gray-700'>{product.total_out}</td>
</tr>
)
}) || []}
</tbody>
<tfoot>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<td className='p-3 font-bold'>TOTAL</td>
<td className='p-3'></td>
<td className='p-3 text-center font-bold'>{productSummary.totalQuantity ?? 0}</td>
<td className='p-3 text-center font-bold'>{productSummary.totalIn ?? 0}</td>
<td className='p-3 text-center font-bold'>{productSummary.totalOut ?? 0}</td>
</tr>
</tfoot>
</table>
</div>
</div>
{/* Ingredient */}
<div className='px-8 pb-8'>
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
3. Ingredient
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<th className='text-left p-3 font-semibold'>Nama</th>
<th className='text-center p-3 font-semibold'>Stock</th>
<th className='text-center p-3 font-semibold'>Masuk</th>
<th className='text-center p-3 font-semibold'>Keluar</th>
</tr>
</thead>
<tbody>
{inventory?.ingredients?.map((ingredient, index) => {
let rowClass = index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
if (ingredient.is_zero_stock) {
rowClass = 'bg-red-300' // Merah untuk stok habis
} else if (ingredient.is_low_stock) {
rowClass = 'bg-yellow-300' // Kuning untuk stok sedikit
}
return (
<tr key={index} className={rowClass}>
<td className='p-3 font-medium text-gray-800'>{ingredient.ingredient_name}</td>
<td className='p-3 text-center text-gray-700'>{ingredient.quantity}</td>
<td className='p-3 text-center text-gray-700'>{ingredient.total_in}</td>
<td className='p-3 text-center text-gray-700'>{ingredient.total_out}</td>
</tr>
)
}) || []}
</tbody>
<tfoot>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<td className='p-3 font-bold'>TOTAL</td>
<td className='p-3 text-center font-bold'>{ingredientSummary.totalQuantity ?? 0}</td>
<td className='p-3 text-center font-bold'>{ingredientSummary.totalIn ?? 0}</td>
<td className='p-3 text-center font-bold'>{ingredientSummary.totalOut ?? 0}</td>
</tr>
</tfoot>
</table>
</div>
</div>
{/* Footer */}
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
<div className='flex justify-between items-center text-sm text-gray-600'>
<p>© 2025 Apskel - Sistem POS Terpadu</p>
<p></p>
<p>Dicetak pada: {now.toLocaleDateString('id-ID')}</p>
</div>
</div>
</div>
</div>
)
}
export default ExportInventoryPage
@@ -0,0 +1,7 @@
import CampaignDetailContent from '@/views/apps/marketing/campaign/detail'
const CampaignDetailPage = () => {
return <CampaignDetailContent />
}
export default CampaignDetailPage
@@ -0,0 +1,7 @@
import CampaignListTable from '@/views/apps/marketing/campaign/CampaignListTable'
const CampaignPage = () => {
return <CampaignListTable />
}
export default CampaignPage
@@ -0,0 +1,7 @@
import CustomerAnalyticList from '@/views/apps/marketing/customer-analytics'
const CustomerAnalyticsPage = () => {
return <CustomerAnalyticList />
}
export default CustomerAnalyticsPage
@@ -0,0 +1,7 @@
import GamePrizeList from '@/views/apps/marketing/games/game-prizes'
const GamePrizePage = () => {
return <GamePrizeList />
}
export default GamePrizePage
@@ -0,0 +1,7 @@
import GamesList from '@/views/apps/marketing/games/list'
const GamePage = () => {
return <GamesList />
}
export default GamePage
@@ -0,0 +1,7 @@
import WheelSpinList from '@/views/apps/marketing/gamification/wheel-spin'
const WheelSpinPage = () => {
return <WheelSpinList />
}
export default WheelSpinPage
@@ -0,0 +1,7 @@
import LoyaltyList from '@/views/apps/marketing/loyalty'
const LoyaltiPage = () => {
return <LoyaltyList />
}
export default LoyaltiPage
@@ -0,0 +1,7 @@
import RewardList from '@/views/apps/marketing/reward'
const RewardPage = () => {
return <RewardList />
}
export default RewardPage
@@ -0,0 +1,7 @@
import TierList from '@/views/apps/marketing/tier'
const TierPage = () => {
return <TierList />
}
export default TierPage
@@ -0,0 +1,7 @@
import VoucherList from '@/views/apps/marketing/voucher'
const VoucherPage = () => {
return <VoucherList />
}
export default VoucherPage
@@ -0,0 +1,86 @@
'use client'
import Grid from '@mui/material/Grid2'
import { TextField, Typography, useTheme } from '@mui/material'
import { useState } from 'react'
import { formatDateDDMMYYYY, formatForInputDate } from '@/utils/transform'
import PurchaseOverviewLeft from '@/views/apps/purchase/overview/overview-left'
import PurchaseOverviewRight from '@/views/apps/purchase/overview/overview-right'
const PurchaseOverviewPage = () => {
const theme = useTheme()
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const [filter, setFilter] = useState({
date_from: formatDateDDMMYYYY(monthAgo),
date_to: formatDateDDMMYYYY(today)
})
return (
<>
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<div className='flex gap-4 items-center justify-between'>
<Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
Overview Pembelian
</Typography>
<div className='flex items-center gap-4'>
<TextField
type='date'
value={formatForInputDate(today || new Date())}
onChange={e => {
setFilter({
...filter,
date_from: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
<Typography>-</Typography>
<TextField
type='date'
value={today}
onChange={e => {}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
</div>
</div>
</Grid>
</Grid>
<Grid container spacing={6} className='mt-5'>
<Grid size={{ xs: 12, lg: 8, md: 7 }}>
<PurchaseOverviewRight />
</Grid>
<Grid size={{ xs: 12, lg: 4, md: 5 }}>
<PurchaseOverviewLeft />
</Grid>
</Grid>
</>
)
}
export default PurchaseOverviewPage
@@ -0,0 +1,18 @@
import PurchaseDetailContent from '@/views/apps/purchase/purchase-detail/PurchaseDetailContent'
import PurchaseDetailHeader from '@/views/apps/purchase/purchase-detail/PurchaseDetailHeader'
import Grid from '@mui/material/Grid2'
const PurchaseBillDetailPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<PurchaseDetailHeader title='Detail Pesanan Pembelian' />
</Grid>
<Grid size={{ xs: 12 }}>
<PurchaseDetailContent />
</Grid>
</Grid>
)
}
export default PurchaseBillDetailPage
@@ -0,0 +1,19 @@
import Grid from '@mui/material/Grid2'
import PurchaseAddForm from '@/views/apps/purchase/purchase-form/PurchaseAddForm'
import PurchaseBillAddHeader from '@/views/apps/purchase/purchase-bills/add/PurchaseBillAddHeader'
const PurchaseBillAddPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<PurchaseBillAddHeader />
</Grid>
<Grid size={{ xs: 12 }}>
<PurchaseAddForm />
</Grid>
</Grid>
)
}
export default PurchaseBillAddPage
@@ -0,0 +1,7 @@
import PurchaseBillList from '@/views/apps/purchase/purchase-bills/list'
const PurchaseBillsPage = () => {
return <PurchaseBillList />
}
export default PurchaseBillsPage
@@ -0,0 +1,7 @@
import PurchaseDeliveryListTable from '@/views/apps/purchase/purchase-deliveries/list/PurchaseDeliveryListTable'
const PurchaseDeliveryPage = () => {
return <PurchaseDeliveryListTable />
}
export default PurchaseDeliveryPage
@@ -0,0 +1,18 @@
import PurchaseDetailContent from '@/views/apps/purchase/purchase-detail/PurchaseDetailContent'
import PurchaseDetailHeader from '@/views/apps/purchase/purchase-detail/PurchaseDetailHeader'
import Grid from '@mui/material/Grid2'
const PurchaseOrderDetailPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<PurchaseDetailHeader title='Detail Pesanan Pembelian' />
</Grid>
<Grid size={{ xs: 12 }}>
<PurchaseDetailContent />
</Grid>
</Grid>
)
}
export default PurchaseOrderDetailPage
@@ -0,0 +1,19 @@
import Grid from '@mui/material/Grid2'
import PurchaseOrderAddHeader from '@/views/apps/purchase/purchase-orders/add/PurchaseOrderAddHeader'
import PurchaseAddForm from '@/views/apps/purchase/purchase-form/PurchaseAddForm'
const PurchaseOrderAddPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<PurchaseOrderAddHeader />
</Grid>
<Grid size={{ xs: 12 }}>
<PurchaseAddForm />
</Grid>
</Grid>
)
}
export default PurchaseOrderAddPage
@@ -0,0 +1,7 @@
import PurchaseOrderList from '@/views/apps/purchase/purchase-orders/list'
const PurchaseOrdersPage = () => {
return <PurchaseOrderList />
}
export default PurchaseOrdersPage
@@ -0,0 +1,19 @@
import Grid from '@mui/material/Grid2'
import PurchaseAddForm from '@/views/apps/purchase/purchase-form/PurchaseAddForm'
import PurchaseQuoteAddHeader from '@/views/apps/purchase/purchase-quote/add/PurchaseQuoteAddHeader'
const PurchaseQuoteAddPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<PurchaseQuoteAddHeader />
</Grid>
<Grid size={{ xs: 12 }}>
<PurchaseAddForm />
</Grid>
</Grid>
)
}
export default PurchaseQuoteAddPage
@@ -0,0 +1,7 @@
import PurchaseQuoteList from '@/views/apps/purchase/purchase-quote/list'
const PurchaseQuotePage = () => {
return <PurchaseQuoteList />
}
export default PurchaseQuotePage
@@ -0,0 +1,22 @@
import ReportTitle from '@/components/report/ReportTitle'
import ReportCashFlowCard from '@/views/apps/report/cash-flow/ReportCashFlowCard'
import ReportCashFlowContent from '@/views/apps/report/cash-flow/ReportCashFlowContent'
import Grid from '@mui/material/Grid2'
const CashFlowPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Arus Kas' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportCashFlowCard />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportCashFlowContent />
</Grid>
</Grid>
)
}
export default CashFlowPage
@@ -0,0 +1,18 @@
import ReportTitle from '@/components/report/ReportTitle'
import ReportPaymentMethodContent from '@/views/apps/report/financial/payment-method-report/ReportPaymentMethodContent'
import Grid from '@mui/material/Grid2'
const SalesProductReportPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Laporan Metode Pembayaran' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportPaymentMethodContent />
</Grid>
</Grid>
)
}
export default SalesProductReportPage
@@ -0,0 +1,22 @@
import ReportTitle from '@/components/report/ReportTitle'
import ReportNeracaCard from '@/views/apps/report/neraca/ReportNeracaCard'
import ReportNeracaContent from '@/views/apps/report/neraca/ReportNeracaContent'
import Grid from '@mui/material/Grid2'
const NeracaPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Neraca' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportNeracaCard />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportNeracaContent />
</Grid>
</Grid>
)
}
export default NeracaPage
@@ -0,0 +1,7 @@
import ReportList from '@/views/apps/report'
const ReportPage = () => {
return <ReportList />
}
export default ReportPage
@@ -0,0 +1,72 @@
'use client'
import ReportTitle from '@/components/report/ReportTitle'
import ReportProfitLossCard from '@/views/apps/report/profit-loss/ReportProfitLossCard'
import ReportProfitLossContent from '@/views/apps/report/profit-loss/ReportProfitLossContent'
import Grid from '@mui/material/Grid2'
import { CircularProgress, Box } from '@mui/material'
import { useState } from 'react'
import { useProfitLossAnalytics } from '@/services/queries/analytics'
import { formatDateDDMMYYYY } from '@/utils/transform'
import Loading from '@/components/layout/shared/Loading'
const ProfitLossPage = () => {
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const [startDate, setStartDate] = useState<Date | null>(monthAgo)
const [endDate, setEndDate] = useState<Date | null>(today)
// Single API call at parent level
const {
data: profitData,
isLoading,
error
} = useProfitLossAnalytics({
date_from: formatDateDDMMYYYY(startDate!),
date_to: formatDateDDMMYYYY(endDate!)
})
// Handle loading state
if (isLoading) {
return <Loading />
}
// Handle error state
if (error) {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Laba Rugi' />
</Grid>
<Grid size={{ xs: 12 }}>
<Box display='flex' justifyContent='center' alignItems='center' minHeight={400}>
<span>Error loading data: {error.message}</span>
</Box>
</Grid>
</Grid>
)
}
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Laba Rugi' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportProfitLossCard profitData={profitData} />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportProfitLossContent
profitData={profitData}
startDate={startDate}
endDate={endDate}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
/>
</Grid>
</Grid>
)
}
export default ProfitLossPage
@@ -0,0 +1,19 @@
import ReportTitle from '@/components/report/ReportTitle'
import ReportSalesOrderContent from '@/views/apps/report/sales/sales-order/ReportSalesOrderContent'
import Grid from '@mui/material/Grid2'
const SalesOrderReportPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Laporan Penjualan Pesanan' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportSalesOrderContent />
</Grid>
z
</Grid>
)
}
export default SalesOrderReportPage
@@ -0,0 +1,18 @@
import ReportTitle from '@/components/report/ReportTitle'
import ReportSalesProductCategoryContent from '@/views/apps/report/sales/sales-product-category/ReportSalesProductCategoryReport'
import Grid from '@mui/material/Grid2'
const SalesProductCategoryReportPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Laporan Penjualan per Kategori Produk' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportSalesProductCategoryContent />
</Grid>
</Grid>
)
}
export default SalesProductCategoryReportPage
@@ -0,0 +1,18 @@
import ReportTitle from '@/components/report/ReportTitle'
import ReportSalesPerProductContent from '@/views/apps/report/sales/sales-per-product/ReportSalesPerProductContent'
import Grid from '@mui/material/Grid2'
const SalesProductReportPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Laporan Penjualan per Produk' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportSalesPerProductContent />
</Grid>
</Grid>
)
}
export default SalesProductReportPage
@@ -0,0 +1,18 @@
import ReportTitle from '@/components/report/ReportTitle'
import ReportSalesContent from '@/views/apps/report/sales/sales-report/ReportSalesContent'
import Grid from '@mui/material/Grid2'
const SalesReportPage = () => {
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<ReportTitle title='Laporan Penjualan' />
</Grid>
<Grid size={{ xs: 12 }}>
<ReportSalesContent />
</Grid>
</Grid>
)
}
export default SalesReportPage
@@ -0,0 +1,86 @@
'use client'
import Grid from '@mui/material/Grid2'
import { TextField, Typography, useTheme } from '@mui/material'
import { useState } from 'react'
import { formatDateDDMMYYYY, formatForInputDate } from '@/utils/transform'
import SalesOverviewRight from '@/views/apps/sales/overview/overview-right'
import SalesOverviewLeft from '@/views/apps/sales/overview/overview-left'
const SalesOverviewPage = () => {
const theme = useTheme()
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const [filter, setFilter] = useState({
date_from: formatDateDDMMYYYY(monthAgo),
date_to: formatDateDDMMYYYY(today)
})
return (
<>
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<div className='flex gap-4 items-center justify-between'>
<Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
Overview Penjualan
</Typography>
<div className='flex items-center gap-4'>
<TextField
type='date'
value={formatForInputDate(today || new Date())}
onChange={e => {
setFilter({
...filter,
date_from: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
<Typography>-</Typography>
<TextField
type='date'
value={today}
onChange={e => {}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
</div>
</div>
</Grid>
</Grid>
<Grid container spacing={6} className='mt-5'>
<Grid size={{ xs: 12, lg: 8, md: 7 }}>
<SalesOverviewRight />
</Grid>
<Grid size={{ xs: 12, lg: 4, md: 5 }}>
<SalesOverviewLeft />
</Grid>
</Grid>
</>
)
}
export default SalesOverviewPage
@@ -0,0 +1,7 @@
import SalesBillList from '@/views/apps/sales/sales-bill/list'
const SalesBillPage = () => {
return <SalesBillList />
}
export default SalesBillPage
@@ -0,0 +1,7 @@
import SalesDeliveryListTable from '@/views/apps/sales/sales-deliveries/list/SalesDeliveryListTable'
const SalesDeliveryPage = () => {
return <SalesDeliveryListTable />
}
export default SalesDeliveryPage
@@ -0,0 +1,7 @@
import SalesOrderList from '@/views/apps/sales/sales-orders/list'
const SalesOrdersPage = () => {
return <SalesOrderList />
}
export default SalesOrdersPage
@@ -0,0 +1,7 @@
import SalesQuoteList from '@/views/apps/sales/sales-quote/list'
const SalesQuotePage = () => {
return <SalesQuoteList />
}
export default SalesQuotePage
@@ -0,0 +1,7 @@
import VendorView from '@/views/apps/vendor/detail'
const VendorViewPage = async () => {
return <VendorView />
}
export default VendorViewPage
@@ -0,0 +1,8 @@
import { vendorDummyData } from '@/data/dummy/vendor'
import VendorList from '@/views/apps/vendor/list'
const VendorListTablePage = async () => {
return <VendorList vendorData={vendorDummyData} />
}
export default VendorListTablePage
@@ -4,7 +4,8 @@ import {
useProductSalesAnalytics,
useProfitLossAnalytics,
useSalesAnalytics,
usePaymentAnalytics
usePaymentAnalytics,
useCategoryAnalytics
} from '@/services/queries/analytics'
import { useOutletById } from '@/services/queries/outlets'
import { formatCurrency, formatDate, formatDateDDMMYYYY, formatDatetime } from '@/utils/transform'
@@ -13,7 +14,7 @@ import ReportHeader from '@/views/dashboards/daily-report/report-header'
import React, { useEffect, useRef, useState } from 'react'
const DailyPOSReport = () => {
const reportRef = useRef<HTMLElement | null>(null)
const reportRef = useRef<HTMLDivElement | null>(null)
const [now, setNow] = useState(new Date())
const [selectedDate, setSelectedDate] = useState(new Date())
@@ -21,7 +22,8 @@ const DailyPOSReport = () => {
startDate: new Date(),
endDate: new Date()
})
const [filterType, setFilterType] = useState('single') // 'single' or 'range'
const [filterType, setFilterType] = useState<'single' | 'range'>('single') // 'single' or 'range'
const [isGeneratingPDF, setIsGeneratingPDF] = useState(false)
// Use selectedDate for single date filter, or dateRange for range filter
const getDateParams = () => {
@@ -45,6 +47,7 @@ const DailyPOSReport = () => {
const { data: profitLoss } = useProfitLossAnalytics(dateParams)
const { data: products } = useProductSalesAnalytics(dateParams)
const { data: paymentAnalytics } = usePaymentAnalytics(dateParams)
const { data: category } = useCategoryAnalytics(dateParams)
const productSummary = {
totalQuantitySold: products?.data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0,
@@ -52,12 +55,11 @@ const DailyPOSReport = () => {
totalOrders: products?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0
}
// Calculate profit loss product summary
const profitLossProductSummary = {
totalRevenue: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.revenue || 0), 0) || 0,
totalCost: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.cost || 0), 0) || 0,
totalGrossProfit: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.gross_profit || 0), 0) || 0,
totalQuantity: profitLoss?.product_data?.reduce((sum, item) => sum + (item?.quantity_sold || 0), 0) || 0
const categorySummary = {
totalRevenue: category?.data?.reduce((sum, item) => sum + (item?.total_revenue || 0), 0) || 0,
orderCount: category?.data?.reduce((sum, item) => sum + (item?.order_count || 0), 0) || 0,
productCount: category?.data?.reduce((sum, item) => sum + (item?.product_count || 0), 0) || 0,
totalQuantity: category?.data?.reduce((sum, item) => sum + (item?.total_quantity || 0), 0) || 0
}
useEffect(() => {
@@ -92,84 +94,216 @@ const DailyPOSReport = () => {
const handleGeneratePDF = async () => {
const reportElement = reportRef.current
if (!reportElement) {
alert('Report element tidak ditemukan')
return
}
// Set loading state
setIsGeneratingPDF(true)
try {
// Import jsPDF dan html2canvas
const jsPDF = (await import('jspdf')).default
const html2canvas = (await import('html2canvas')).default
// Optimized canvas capture dengan scale lebih rendah
const canvas = await html2canvas(reportElement!, {
scale: 1.5, // Reduced from 2 to 1.5
// Pastikan element terlihat penuh
const originalOverflow = reportElement.style.overflow
reportElement.style.overflow = 'visible'
// Wait untuk memastikan rendering selesai
await new Promise(resolve => setTimeout(resolve, 300))
console.log('Starting PDF generation...')
// Update loading message
console.log('Capturing content...')
// Capture canvas dengan setting yang optimal
const canvas = await html2canvas(reportElement, {
scale: 1.5,
useCORS: true,
allowTaint: true,
backgroundColor: '#ffffff',
logging: false, // Disable logging for performance
removeContainer: true, // Clean up after capture
imageTimeout: 0, // No timeout for image loading
height: reportElement!.scrollHeight,
width: reportElement!.scrollWidth
logging: false,
removeContainer: true,
imageTimeout: 0,
height: reportElement.scrollHeight,
width: reportElement.scrollWidth,
scrollX: 0,
scrollY: 0,
// Pastikan capture semua content
windowWidth: Math.max(reportElement.scrollWidth, window.innerWidth),
windowHeight: Math.max(reportElement.scrollHeight, window.innerHeight)
})
// Compress canvas using JPEG with quality setting
const imgData = canvas.toDataURL('image/jpeg', 0.85) // JPEG with 85% quality instead of PNG
console.log('Canvas captured:', canvas.width, 'x', canvas.height)
console.log('Generating PDF pages...')
// Create PDF with compression
// Restore overflow
reportElement.style.overflow = originalOverflow
// Create PDF
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4',
compress: true // Enable built-in compression
compress: true
})
const imgWidth = 210
const pageHeight = 295
const imgHeight = (canvas.height * imgWidth) / canvas.width
let heightLeft = imgHeight
let position = 0
// A4 dimensions
const pdfWidth = 210
const pdfHeight = 297
const margin = 5 // Small margin to prevent cutoff
// Add first page with compressed image
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST') // Use FAST compression
heightLeft -= pageHeight
// Calculate scaling
const availableWidth = pdfWidth - 2 * margin
const availableHeight = pdfHeight - 2 * margin
// Handle multiple pages if needed
while (heightLeft >= 0) {
position = heightLeft - imgHeight
pdf.addPage()
pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, '', 'FAST')
heightLeft -= pageHeight
const imgWidth = availableWidth
const imgHeight = (canvas.height * availableWidth) / canvas.width
console.log('PDF dimensions - Canvas:', canvas.width, 'x', canvas.height)
console.log('PDF dimensions - Image:', imgWidth, 'x', imgHeight)
console.log('Available height per page:', availableHeight)
// Split content across pages
let yPosition = margin
let sourceY = 0
let pageCount = 1
let remainingHeight = imgHeight
while (remainingHeight > 0) {
console.log(`Processing page ${pageCount}, remaining height: ${remainingHeight}`)
if (pageCount > 1) {
pdf.addPage()
yPosition = margin
}
// Calculate how much content fits on this page
const heightForThisPage = Math.min(remainingHeight, availableHeight)
// Calculate source dimensions for cropping
const sourceHeight = (heightForThisPage * canvas.height) / imgHeight
// Create temporary canvas for this page portion
const tempCanvas = document.createElement('canvas')
const tempCtx = tempCanvas.getContext('2d')
if (!tempCtx) {
throw new Error('Unable to get 2D context from canvas')
}
tempCanvas.width = canvas.width
tempCanvas.height = sourceHeight
// Draw the portion we need
tempCtx.drawImage(
canvas,
0,
sourceY,
canvas.width,
sourceHeight, // Source rectangle
0,
0,
canvas.width,
sourceHeight // Destination rectangle
)
// Convert to image data
const pageImageData = tempCanvas.toDataURL('image/jpeg', 0.9)
// Add to PDF
pdf.addImage(pageImageData, 'JPEG', margin, yPosition, imgWidth, heightForThisPage)
// Update for next page
sourceY += sourceHeight
remainingHeight -= heightForThisPage
pageCount++
// Safety check to prevent infinite loop
if (pageCount > 20) {
console.warn('Too many pages, breaking loop')
break
}
}
// Additional compression options
console.log(`Generated ${pageCount - 1} pages`)
console.log('Finalizing PDF...')
// Add metadata
pdf.setProperties({
title: `${getReportTitle()}`,
subject: 'Daily Transaction Report',
title: getReportTitle(),
subject: 'Transaction Report',
author: 'Apskel POS System',
creator: 'Apskel'
})
// Save with optimized settings
// Generate filename
const fileName =
filterType === 'single'
? `laporan-transaksi-${formatDateForInput(selectedDate)}.pdf`
: `laporan-transaksi-${formatDateForInput(dateRange.startDate)}-to-${formatDateForInput(dateRange.endDate)}.pdf`
pdf.save(fileName, {
returnPromise: true
})
console.log('Saving PDF:', fileName)
// Clean up canvas to free memory
canvas.width = canvas.height = 0
// Save PDF
pdf.save(fileName)
console.log('PDF generated successfully!')
} catch (error) {
console.error('Error generating PDF:', error)
alert('Terjadi kesalahan saat membuat PDF. Pastikan jsPDF dan html2canvas sudah terinstall.')
alert(`Terjadi kesalahan saat membuat PDF: ${error}`)
} finally {
// Reset loading state
setIsGeneratingPDF(false)
}
}
const LoadingOverlay = ({ isVisible, message = 'Generating PDF...' }: { isVisible: boolean; message?: string }) => {
if (!isVisible) return null
return (
<div className='fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm'>
<div className='bg-white rounded-lg shadow-xl p-8 max-w-sm w-full mx-4'>
<div className='text-center'>
{/* Animated Spinner */}
<div className='inline-block animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-purple-600 mb-4'></div>
{/* Loading Message */}
<h3 className='text-lg font-semibold text-gray-800 mb-2'>{message}</h3>
<p className='text-sm text-gray-600'>Mohon tunggu, proses ini mungkin membutuhkan beberapa detik...</p>
{/* Progress Steps */}
<div className='mt-6 space-y-2'>
<div className='flex items-center text-xs text-gray-500'>
<div className='w-2 h-2 bg-green-500 rounded-full mr-2 flex-shrink-0'></div>
<span>Capturing report content</span>
</div>
<div className='flex items-center text-xs text-gray-500'>
<div className='w-2 h-2 bg-blue-500 rounded-full mr-2 flex-shrink-0 animate-pulse'></div>
<span>Processing pages</span>
</div>
<div className='flex items-center text-xs text-gray-500'>
<div className='w-2 h-2 bg-gray-300 rounded-full mr-2 flex-shrink-0'></div>
<span>Finalizing PDF</span>
</div>
</div>
</div>
</div>
</div>
)
}
return (
<div className='min-h-screen'>
<LoadingOverlay isVisible={isGeneratingPDF} message='Membuat PDF Laporan...' />
{/* Control Panel */}
<ReportGeneratorComponent
// Props wajib
className='min-w-full'
reportTitle='Laporan Penjualan'
filterType={filterType}
selectedDate={selectedDate}
@@ -199,126 +333,62 @@ const DailyPOSReport = () => {
{/* Performance Summary */}
<div className='p-8'>
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
1. Ringkasan Kinerja
Ringkasan
</h3>
<div className='grid grid-cols-2 gap-6'>
<div className='space-y-4'>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>TOTAL PENJUALAN (termasuk rasik)</span>
<span className='font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Terjual</span>
<span className='font-semibold text-gray-800'>{productSummary.totalQuantitySold}</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>HPP</span>
<span className='font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_cost ?? 0)} |{' '}
{(((profitLoss?.summary.total_cost ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(
0
)}
%
</span>
</div>
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
<span className='text-lg font-semibold text-green-800'>Laba Kotor</span>
<span className='text-lg font-bold text-green-800'>
{formatCurrency(profitLoss?.summary.gross_profit ?? 0)} |{' '}
{(profitLoss?.summary.gross_profit_margin ?? 0).toFixed(0)}%
</span>
</div>
<div className='space-y-4'>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Penjualan</span>
<span className='font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}
</span>
</div>
<div className='space-y-4'>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Biaya lain²</span>
<span className='font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_tax ?? 0)} |{' '}
{(((profitLoss?.summary.total_tax ?? 0) / (profitLoss?.summary.total_revenue || 1)) * 100).toFixed(0)}
%
</span>
</div>
<div className='flex justify-between items-center py-2 border-b-2 border-gray-300'>
<span className='text-lg font-bold text-blue-800'>Laba/Rugi</span>
<span className='text-lg font-bold text-blue-800'>
{formatCurrency(profitLoss?.summary.net_profit ?? 0)} |{' '}
{(profitLoss?.summary.net_profit_margin ?? 0).toFixed(0)}%
</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Diskon</span>
<span className='font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.total_discount ?? 0)}
</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Pajak</span>
<span className='font-semibold text-gray-800'>{formatCurrency(profitLoss?.summary.total_tax ?? 0)}</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700 font-bold'>Total</span>
<span className='font-bold text-gray-800'>{formatCurrency(profitLoss?.summary.total_revenue ?? 0)}</span>
</div>
</div>
</div>
{/* Profit Loss Product Table */}
<div className='px-8 pb-8'>
<h3 className='text-lg font-medium mb-6' style={{ color: '#36175e' }}>
Laba Rugi Per Produk
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
Invoice
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<th className='text-left p-3 font-semibold'>Produk</th>
<th className='text-center p-3 font-semibold'>Qty</th>
<th className='text-right p-3 font-semibold'>Pendapatan</th>
<th className='text-right p-3 font-semibold'>HPP</th>
<th className='text-right p-3 font-semibold'>Laba Kotor</th>
<th className='text-center p-3 font-semibold'>Margin (%)</th>
</tr>
</thead>
<tbody>
{profitLoss?.product_data?.map((item, index) => (
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
<td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
<td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
<td className='p-3 text-right font-semibold text-red-600'>{formatCurrency(item.cost)}</td>
<td className='p-3 text-right font-semibold text-green-600'>{formatCurrency(item.gross_profit)}</td>
<td className='p-3 text-center font-semibold' style={{ color: '#36175e' }}>
{(item.gross_profit_margin ?? 0).toFixed(1)}%
</td>
</tr>
)) || []}
</tbody>
<tfoot>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<td className='p-3 font-bold'>TOTAL</td>
<td className='p-3 text-center font-bold'>{profitLossProductSummary.totalQuantity}</td>
<td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalRevenue)}</td>
<td className='p-3 text-right font-bold'>{formatCurrency(profitLossProductSummary.totalCost)}</td>
<td className='p-3 text-right font-bold'>
{formatCurrency(profitLossProductSummary.totalGrossProfit)}
</td>
<td className='p-3 text-center font-bold'>
{profitLossProductSummary.totalRevenue > 0
? (
(profitLossProductSummary.totalGrossProfit / profitLossProductSummary.totalRevenue) *
100
).toFixed(1)
: 0}
%
</td>
</tr>
</tfoot>
</table>
<div className='space-y-4'>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Total Invoice</span>
<span className='font-semibold text-gray-800'>{profitLoss?.summary.total_orders ?? 0}</span>
</div>
<div className='flex justify-between items-center py-2 border-b border-gray-200'>
<span className='text-gray-700'>Rata-rata Tagihan Per Invoice </span>
<span className='font-semibold text-gray-800'>
{formatCurrency(profitLoss?.summary.average_profit ?? 0)}
</span>
</div>
</div>
</div>
{/* Payment Method Summary */}
<div className='px-8 pb-8'>
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
2. Ringkasan Metode Pembayaran
Ringkasan Metode Pembayaran
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<tr className='text-gray-800 border-b-2 border-gray-300'>
<th className='text-left p-3 font-semibold'>Metode Pembayaran</th>
<th className='text-center p-3 font-semibold'>Tipe</th>
<th className='text-center p-3 font-semibold'>Jumlah Order</th>
@@ -352,14 +422,54 @@ const DailyPOSReport = () => {
)) || []}
</tbody>
<tfoot>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<tr className='text-gray-800 border-t-2 border-gray-300'>
<td className='p-3 font-bold'>TOTAL</td>
<td className='p-3'></td>
<td className='p-3 text-center font-bold'>{paymentAnalytics?.summary.total_orders ?? 0}</td>
<td className='p-3 text-right font-bold'>
{formatCurrency(paymentAnalytics?.summary.total_amount ?? 0)}
</td>
<td className='p-3 text-center font-bold'>100.0%</td>
<td className='p-3 text-center font-bold'></td>
</tr>
</tfoot>
</table>
</div>
</div>
{/* Category Summary */}
<div className='px-8 pb-8'>
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
Ringkasan Kategori
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr className='text-gray-800 border-b-2 border-gray-300'>
<th className='text-left p-3 font-semibold'>Nama</th>
<th className='text-center p-3 font-semibold'>Total Produk</th>
<th className='text-center p-3 font-semibold'>Qty</th>
<th className='text-right p-3 font-semibold'>Pendapatan</th>
</tr>
</thead>
<tbody>
{category?.data?.map((c, index) => (
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className='p-3 font-medium text-gray-800'>{c.category_name}</td>
<td className='p-3 text-center text-gray-700'>{c.product_count}</td>
<td className='p-3 text-center text-gray-700'>{c.total_quantity}</td>
<td className='p-3 text-right font-semibold' style={{ color: '#36175e' }}>
{formatCurrency(c.total_revenue)}
</td>
</tr>
)) || []}
</tbody>
<tfoot>
<tr className='text-gray-800 border-t-2 border-gray-300'>
<td className='p-3 font-bold'>TOTAL</td>
<td className='p-3 text-center font-bold'>{categorySummary?.productCount ?? 0}</td>
<td className='p-3 text-center font-bold'>{categorySummary?.totalQuantity ?? 0}</td>
<td className='p-3 text-right font-bold'>{formatCurrency(categorySummary?.totalRevenue ?? 0)}</td>
</tr>
</tfoot>
</table>
@@ -369,49 +479,164 @@ const DailyPOSReport = () => {
{/* Transaction Summary */}
<div className='px-8 pb-8'>
<h3 className='text-xl font-bold mb-6' style={{ color: '#36175e' }}>
3. Ringkasan Transaksi
Ringkasan Item
</h3>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-hidden'>
<table className='w-full'>
<thead>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<th className='text-left p-3 font-semibold'>Produk</th>
<th className='text-left p-3 font-semibold'>Kategori</th>
<th className='text-center p-3 font-semibold'>Qty</th>
<th className='text-right p-3 font-semibold'>Order</th>
<th className='text-right p-3 font-semibold'>Pendapatan</th>
<th className='text-right p-3 font-semibold'>Rata Rata</th>
</tr>
</thead>
<tbody>
{products?.data?.map((item, index) => (
<tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
<td className='p-3 font-medium text-gray-800'>{item.product_name}</td>
<td className='p-3 font-medium text-gray-800'>{item.category_name}</td>
<td className='p-3 text-center text-gray-700'>{item.quantity_sold}</td>
<td className='p-3 text-center text-gray-700'>{item.order_count ?? 0}</td>
<td className='p-3 text-right font-semibold text-gray-800'>{formatCurrency(item.revenue)}</td>
<td className='p-3 text-right font-medium text-gray-800'>{formatCurrency(item.average_price)}</td>
<div className='bg-gray-50 rounded-lg border border-gray-200 overflow-visible'>
<div className='overflow-x-auto'>
<table className='w-full table-fixed' style={{ minWidth: '100%' }}>
<colgroup>
<col style={{ width: '40%' }} />
<col style={{ width: '15%' }} />
<col style={{ width: '15%' }} />
<col style={{ width: '15%' }} />
<col style={{ width: '15%' }} />
</colgroup>
<thead>
<tr className='text-gray-800 border-b-2 border-gray-300'>
<th className='text-left p-3 font-semibold border-r border-gray-300'>Produk</th>
<th className='text-center p-3 font-semibold border-r border-gray-300'>Qty</th>
<th className='text-center p-3 font-semibold border-r border-gray-300'>Order</th>
<th className='text-right p-3 font-semibold border-r border-gray-300'>Pendapatan</th>
<th className='text-right p-3 font-semibold'>Rata Rata</th>
</tr>
)) || []}
</tbody>
<tfoot>
<tr style={{ backgroundColor: '#36175e' }} className='text-white'>
<td className='p-3 font-bold'>TOTAL</td>
<td className='p-3 text-center'></td>
<td className='p-3 text-center font-bold'>{productSummary.totalQuantitySold ?? 0}</td>
<td className='p-3 text-right font-bold'>{productSummary.totalOrders ?? 0}</td>
<td className='p-3 text-right font-bold'>{formatCurrency(productSummary.totalRevenue ?? 0)}</td>
<td className='p-3 text-right font-bold'></td>
</tr>
</tfoot>
</table>
</thead>
<tbody>
{(() => {
// Group products by category
const groupedProducts =
products?.data?.reduce(
(acc, item) => {
const categoryName = item.category_name || 'Tidak Berkategori'
if (!acc[categoryName]) {
acc[categoryName] = []
}
acc[categoryName].push(item)
return acc
},
{} as Record<string, any[]>
) || {}
const rows: JSX.Element[] = []
let globalIndex = 0
// Sort categories alphabetically
Object.keys(groupedProducts)
.sort()
.forEach(categoryName => {
const categoryProducts = groupedProducts[categoryName]
// Category header row
rows.push(
<tr
key={`category-${categoryName}`}
className='bg-gray-100 border-b border-gray-300'
style={{ pageBreakInside: 'avoid' }}
>
<td
className='p-3 font-bold text-gray-900 border-r border-gray-300'
style={{ color: '#36175e' }}
>
{categoryName.toUpperCase()}
</td>
<td className='p-3 border-r border-gray-300'></td>
<td className='p-3 border-r border-gray-300'></td>
<td className='p-3 border-r border-gray-300'></td>
<td className='p-3'></td>
</tr>
)
// Product rows for this category
categoryProducts.forEach((item, index) => {
globalIndex++
rows.push(
<tr
key={`product-${item.product_name}-${index}`}
className={`${globalIndex % 2 === 0 ? 'bg-white' : 'bg-gray-50'} border-b border-gray-200`}
style={{ pageBreakInside: 'avoid' }}
>
<td
className='p-3 pl-6 font-medium text-gray-800 border-r border-gray-200'
style={{ wordWrap: 'break-word' }}
>
{item.product_name}
</td>
<td className='p-3 text-center text-gray-700 border-r border-gray-200'>
{item.quantity_sold}
</td>
<td className='p-3 text-center text-gray-700 border-r border-gray-200'>
{item.order_count ?? 0}
</td>
<td className='p-3 text-right font-semibold text-gray-800 border-r border-gray-200'>
{formatCurrency(item.revenue)}
</td>
<td className='p-3 text-right font-medium text-gray-800'>
{formatCurrency(item.average_price)}
</td>
</tr>
)
})
// Category subtotal row
const categoryTotalQty = categoryProducts.reduce(
(sum, item) => sum + (item.quantity_sold || 0),
0
)
const categoryTotalOrders = categoryProducts.reduce(
(sum, item) => sum + (item.order_count || 0),
0
)
const categoryTotalRevenue = categoryProducts.reduce(
(sum, item) => sum + (item.revenue || 0),
0
)
rows.push(
<tr
key={`subtotal-${categoryName}`}
className='bg-gray-200 border-b-2 border-gray-400'
style={{ pageBreakInside: 'avoid' }}
>
<td className='p-3 pl-6 font-semibold text-gray-800 border-r border-gray-400'>
Subtotal {categoryName}
</td>
<td className='p-3 text-center font-semibold text-gray-800 border-r border-gray-400'>
{categoryTotalQty}
</td>
<td className='p-3 text-center font-semibold text-gray-800 border-r border-gray-400'>
{categoryTotalOrders}
</td>
<td className='p-3 text-right font-semibold text-gray-800 border-r border-gray-400'>
{formatCurrency(categoryTotalRevenue)}
</td>
<td className='p-3'></td>
</tr>
)
})
return rows
})()}
</tbody>
<tfoot>
<tr className='text-gray-800 border-t-2 border-gray-300' style={{ pageBreakInside: 'avoid' }}>
<td className='p-3 font-bold border-r border-gray-300'>TOTAL KESELURUHAN</td>
<td className='p-3 text-center font-bold border-r border-gray-300'>
{productSummary.totalQuantitySold ?? 0}
</td>
<td className='p-3 text-center font-bold border-r border-gray-300'>
{productSummary.totalOrders ?? 0}
</td>
<td className='p-3 text-right font-bold border-r border-gray-300'>
{formatCurrency(productSummary.totalRevenue ?? 0)}
</td>
<td className='p-3'></td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
{/* Profit Loss Product Table */}
{/* Footer */}
<div className='px-8 py-6 border-t-2 border-gray-200 mt-8'>
<div className='flex justify-between items-center text-sm text-gray-600'>
@@ -7,22 +7,92 @@ import Grid from '@mui/material/Grid2'
import DistributedBarChartOrder from '@views/dashboards/crm/DistributedBarChartOrder'
// Server Action Imports
import { TextField, Typography, useTheme } from '@mui/material'
import { useState } from 'react'
import Loading from '../../../../../../components/layout/shared/Loading'
import { useSalesAnalytics } from '../../../../../../services/queries/analytics'
import { RecentSale } from '../../../../../../types/services/analytic'
import { formatDateDDMMYYYY, formatForInputDate } from '../../../../../../utils/transform'
import OrdersReport from '../../../../../../views/dashboards/orders/OrdersReport'
const DashboardOrder = () => {
const { data, isLoading } = useSalesAnalytics()
const theme = useTheme()
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const [filter, setFilter] = useState({
date_from: formatDateDDMMYYYY(monthAgo),
date_to: formatDateDDMMYYYY(today)
})
const { data, isLoading } = useSalesAnalytics({
date_from: filter.date_from,
date_to: filter.date_to
})
if (isLoading) return <Loading />
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<div className='flex gap-4 items-center justify-between'>
<Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
Orders Analysis Dashboard
</Typography>
<div className='flex items-center gap-4'>
<TextField
type='date'
value={formatForInputDate(data?.date_from || new Date())}
onChange={e => {
setFilter({
...filter,
date_from: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
<Typography>-</Typography>
<TextField
type='date'
value={
data?.date_to
? new Date(data?.date_to).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0]
}
onChange={e => {}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
</div>
</div>
</Grid>
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Items'
isCurrency={false}
value={data?.summary.total_items as number}
avatarIcon={'tabler-package'}
avatarColor='primary'
@@ -33,6 +103,7 @@ const DashboardOrder = () => {
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Orders'
isCurrency={false}
value={data?.summary.total_orders as number}
avatarIcon={'tabler-shopping-cart'}
avatarColor='info'
@@ -43,6 +114,7 @@ const DashboardOrder = () => {
<DistributedBarChartOrder
isLoading={isLoading}
title='Average Orders'
isCurrency={true}
value={data?.summary.average_order_value as number}
avatarIcon={'tabler-trending-up'}
avatarColor='warning'
@@ -53,6 +125,7 @@ const DashboardOrder = () => {
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Sales'
isCurrency={true}
value={data?.summary.total_sales as number}
avatarIcon={'tabler-currency-dollar'}
avatarColor='success'
@@ -1,114 +1,154 @@
'use client'
import React from 'react'
import { useDashboardAnalytics } from '../../../../../../services/queries/analytics'
import { TextField, Typography, useTheme } from '@mui/material'
import { useState } from 'react'
import Loading from '../../../../../../components/layout/shared/Loading'
import { formatCurrency, formatDate } from '../../../../../../utils/transform'
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
import { useDashboardAnalytics } from '../../../../../../services/queries/analytics'
import { formatDateDDMMYYYY, formatForInputDate, formatShortCurrency } from '../../../../../../utils/transform'
import OrdersReport from '../../../../../../views/dashboards/orders/OrdersReport'
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'
const DashboardOverview = () => {
const theme = useTheme()
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const [filter, setFilter] = useState({
date_from: formatDateDDMMYYYY(monthAgo),
date_to: formatDateDDMMYYYY(today)
})
// Sample data - replace with your actual data
const { data: salesData, isLoading } = useDashboardAnalytics()
const { data: salesData, isLoading } = useDashboardAnalytics({
date_from: filter.date_from,
date_to: filter.date_to
})
if (isLoading) return <Loading />
const MetricCard = ({ iconClass, title, value, subtitle, bgColor = 'bg-blue-500' }: any) => (
const MetricCard = ({ iconClass, title, value, subtitle, bgColor = 'bg-blue-500', isCurrency = false }: any) => (
<div className='bg-white rounded-lg shadow-md hover:shadow-xl transition-shadow duration-300 p-6'>
<div className='flex items-center justify-between'>
<div className='flex-1'>
<h3 className='text-sm font-medium text-gray-600 mb-2'>{title}</h3>
<p className='text-2xl font-bold text-gray-900 mb-1'>{value}</p>
<p className='text-2xl font-bold text-gray-900 mb-1'>{isCurrency ? 'Rp ' + value : value}</p>
{subtitle && <p className='text-sm text-gray-500'>{subtitle}</p>}
</div>
<div className={`p-3 rounded-full ${bgColor} bg-opacity-10`}>
<div className={`px-4 py-3 rounded-full ${bgColor} bg-opacity-10`}>
<i className={`${iconClass} text-[32px] ${bgColor.replace('bg-', 'text-')}`}></i>
</div>
</div>
</div>
)
const ProgressBar = ({ percentage, color = 'bg-blue-500' }: any) => (
<div className='w-full bg-gray-200 rounded-full h-2'>
<div
className={`${color} h-2 rounded-full transition-all duration-300`}
style={{ width: `${percentage}%` }}
></div>
</div>
)
return (
<>
{salesData && (
<div>
{/* Header */}
{/* <div className="mb-8">
<h1 className="text-3xl font-bold text-gray-900 mb-2">Sales Dashboard</h1>
<p className="text-gray-600">
{formatDate(salesData.date_from)} - {formatDate(salesData.date_to)}
</p>
</div> */}
{/* Overview Metrics */}
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8'>
<MetricCard
iconClass='tabler-cash'
title='Total Sales'
value={formatCurrency(salesData.overview.total_sales)}
bgColor='bg-green-500'
<div>
{/* Header */}
<div className='mb-8 flex gap-4 items-center justify-between'>
<Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
Analysis Dashboard
</Typography>
<div className='flex items-center gap-4'>
<TextField
type='date'
value={formatForInputDate(salesData?.date_from || new Date())}
onChange={e => {
setFilter({
...filter,
date_from: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
<MetricCard
iconClass='tabler-shopping-cart'
title='Total Orders'
value={salesData.overview.total_orders.toLocaleString()}
subtitle={`${salesData.overview.voided_orders} voided, ${salesData.overview.refunded_orders} refunded`}
bgColor='bg-blue-500'
/>
<MetricCard
iconClass='tabler-trending-up'
title='Average Order Value'
value={formatCurrency(salesData.overview.average_order_value)}
bgColor='bg-purple-500'
/>
<MetricCard
iconClass='tabler-users'
title='Total Customers'
value={salesData.overview.total_customers || 'N/A'}
bgColor='bg-orange-500'
<Typography>-</Typography>
<TextField
type='date'
value={
salesData?.date_to
? new Date(salesData?.date_to).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0]
}
onChange={e => {
setFilter({
...filter,
date_to: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
</div>
{/* Additional Metrics */}
<div className='grid grid-cols-1 md:grid-cols-2 gap-6 mb-8'>
<div className='bg-white rounded-lg shadow-md p-6'>
<div className='flex items-center mb-4'>
<i className='tabler-x text-[24px] text-red-500 mr-2'></i>
<h3 className='text-lg font-semibold text-gray-900'>Voided Orders</h3>
</div>
<p className='text-3xl font-bold text-red-600'>{salesData.overview.voided_orders}</p>
</div>
<div className='bg-white rounded-lg shadow-md p-6'>
<div className='flex items-center mb-4'>
<i className='tabler-refresh text-[24px] text-yellow-500 mr-2'></i>
<h3 className='text-lg font-semibold text-gray-900'>Refunded Orders</h3>
</div>
<p className='text-3xl font-bold text-yellow-600'>{salesData.overview.refunded_orders}</p>
</div>
</div>
<div className='grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8'>
{/* Top Products */}
<ProductSales title='Top Products' productData={salesData.top_products} />
{/* Payment Methods */}
<PaymentMethodReport payments={salesData.payment_methods} />
</div>
{/* Recent Sales */}
<OrdersReport title='Recent Sales' orderData={salesData.recent_sales} />
</div>
)}
{salesData ? (
<>
{/* Overview Metrics */}
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8'>
<MetricCard
iconClass='tabler-shopping-cart'
title='Total Orders'
value={salesData.overview.total_orders.toLocaleString()}
subtitle={`${salesData.overview.voided_orders} voided, ${salesData.overview.refunded_orders} refunded`}
bgColor='bg-blue-500'
/>
<MetricCard
iconClass='tabler-cash'
title='Total Sales'
value={formatShortCurrency(salesData.overview.total_sales)}
bgColor='bg-green-500'
isCurrency={true}
/>
<MetricCard
iconClass='tabler-trending-up'
title='Average Order Value'
value={formatShortCurrency(salesData.overview.average_order_value)}
bgColor='bg-purple-500'
isCurrency={true}
/>
<MetricCard
iconClass='tabler-users'
title='Total Customers'
value={salesData.overview.total_customers || 'N/A'}
bgColor='bg-orange-500'
/>
</div>
<div className='grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8'>
{/* Top Products */}
<ProductSales title='Top Products' productData={salesData.top_products} />
{/* Payment Methods */}
<PaymentMethodReport payments={salesData.payment_methods} />
</div>
{/* Recent Sales */}
<OrdersReport title='Recent Sales' orderData={salesData.recent_sales} />
</>
) : (
<Loading />
)}
</div>
</>
)
}
@@ -11,18 +11,87 @@ import Loading from '../../../../../../components/layout/shared/Loading'
import { usePaymentAnalytics } from '../../../../../../services/queries/analytics'
import { PaymentDataItem } from '../../../../../../types/services/analytic'
import PaymentMethodReport from '../../../../../../views/dashboards/payment-methods/PaymentMethodReport'
import { Typography, TextField, useTheme } from '@mui/material'
import { useState } from 'react'
import { formatDateDDMMYYYY, formatForInputDate } from '../../../../../../utils/transform'
const DashboardPayment = () => {
const { data, isLoading } = usePaymentAnalytics()
const theme = useTheme()
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const [filter, setFilter] = useState({
date_from: formatDateDDMMYYYY(monthAgo),
date_to: formatDateDDMMYYYY(today)
})
const { data, isLoading } = usePaymentAnalytics({
date_from: filter.date_from,
date_to: filter.date_to
})
if (isLoading) return <Loading />
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12 }}>
<div className='flex gap-4 items-center justify-between'>
<Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
Payments Analysis Dashboard
</Typography>
<div className='flex items-center gap-4'>
<TextField
type='date'
value={formatForInputDate(data?.date_from || new Date())}
onChange={e => {
setFilter({
...filter,
date_from: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
<Typography>-</Typography>
<TextField
type='date'
value={
data?.date_to
? new Date(data?.date_to).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0]
}
onChange={e => {}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
</div>
</div>
</Grid>
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Orders'
isCurrency={false}
value={data?.summary.total_orders as number}
avatarIcon={'tabler-shopping-cart'}
avatarColor='primary'
@@ -33,6 +102,7 @@ const DashboardPayment = () => {
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Payment'
isCurrency={false}
value={data?.summary.total_payments as number}
avatarIcon={'tabler-package'}
avatarColor='info'
@@ -43,6 +113,7 @@ const DashboardPayment = () => {
<DistributedBarChartOrder
isLoading={isLoading}
title='Average Orders'
isCurrency={true}
value={data?.summary.average_order_value as number}
avatarIcon={'tabler-trending-up'}
avatarColor='warning'
@@ -53,6 +124,7 @@ const DashboardPayment = () => {
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Amount'
isCurrency={true}
value={data?.summary.total_amount as number}
avatarIcon={'tabler-currency-dollar'}
avatarColor='success'
@@ -4,51 +4,90 @@
import Grid from '@mui/material/Grid2'
// Component Imports
import DistributedBarChartOrder from '@views/dashboards/crm/DistributedBarChartOrder'
import EarningReportsWithTabs from '@views/dashboards/crm/EarningReportsWithTabs'
// Server Action Imports
import { TextField, Typography, useTheme } from '@mui/material'
import { useState } from 'react'
import Loading from '../../../../../../components/layout/shared/Loading'
import { useProductSalesAnalytics } from '../../../../../../services/queries/analytics'
import { formatDateDDMMYYYY, formatForInputDate } from '../../../../../../utils/transform'
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'
const DashboardProduct = () => {
const { data, isLoading } = useProductSalesAnalytics()
const theme = useTheme()
const summary = {
totalProducts: data?.data.length,
totalQuantitySold: data?.data.reduce((sum, item) => sum + item.quantity_sold, 0),
totalRevenue: data?.data.reduce((sum, item) => sum + item.revenue, 0),
totalOrders: data?.data.reduce((sum, item) => sum + item.order_count, 0),
averageOrderValue: data?.data
? data!.data.reduce((sum, item) => sum + item.revenue, 0) /
data!.data.reduce((sum, item) => sum + item.order_count, 0)
: 0
}
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const formatDate = (dateString: any) => {
return new Date(dateString).toLocaleDateString('id-ID', {
month: 'short',
day: 'numeric'
})
}
const [filter, setFilter] = useState({
date_from: formatDateDDMMYYYY(monthAgo),
date_to: formatDateDDMMYYYY(today)
})
const transformSalesData = (data: any) => {
return [
{
type: 'products',
avatarIcon: 'tabler-package',
date: data.map((d: any) => d.product_name),
series: [{ data: data.map((d: any) => d.revenue) }]
}
]
}
const { data, isLoading } = useProductSalesAnalytics({
date_from: filter.date_from,
date_to: filter.date_to
})
if (isLoading) return <Loading />
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12, lg: 12 }}>{data?.data && <ProductSales title='Product Sales' productData={data.data} />}</Grid>
<Grid size={{ xs: 12, lg: 12 }}>
<div className='flex gap-4 items-center justify-between'>
<Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
Products Analysis Dashboard
</Typography>
<div className='flex items-center gap-4'>
<TextField
type='date'
value={formatForInputDate(data?.date_from || new Date())}
onChange={e => {
setFilter({
...filter,
date_from: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
<Typography>-</Typography>
<TextField
type='date'
value={
data?.date_to
? new Date(data?.date_to).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0]
}
onChange={e => {}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
</div>
</div>
</Grid>
<Grid size={{ xs: 12, lg: 12 }}>
{data?.data ? <ProductSales title='Product Sales' productData={data.data} /> : <Loading />}
</Grid>
</Grid>
)
}
@@ -1,66 +1,68 @@
'use client'
// MUI Imports
import Grid from '@mui/material/Grid2'
// Component Imports
import DistributedBarChartOrder from '@views/dashboards/crm/DistributedBarChartOrder'
// Server Action Imports
import Loading from '../../../../../../components/layout/shared/Loading'
import React, { useState } from 'react'
import { useProfitLossAnalytics } from '../../../../../../services/queries/analytics'
import { DailyData, ProductDataReport, ProfitLossReport } from '../../../../../../types/services/analytic'
import EarningReportsWithTabs from '../../../../../../views/dashboards/crm/EarningReportsWithTabs'
import { formatDateDDMMYYYY, formatForInputDate, formatShortCurrency } from '../../../../../../utils/transform'
import MultipleSeries from '../../../../../../views/dashboards/profit-loss/EarningReportWithTabs'
import { DailyData, ProfitLossReport } from '../../../../../../types/services/analytic'
import { TextField, Typography, useTheme } from '@mui/material'
import Loading from '../../../../../../components/layout/shared/Loading'
function formatMetricName(metric: string): string {
const nameMap: { [key: string]: string } = {
revenue: 'Revenue',
cost: 'Cost',
gross_profit: 'Gross Profit',
gross_profit_margin: 'Gross Profit Margin (%)',
tax: 'Tax',
discount: 'Discount',
net_profit: 'Net Profit',
net_profit_margin: 'Net Profit Margin (%)',
orders: 'Orders'
const DashboardProfitloss = () => {
const theme = useTheme()
const today = new Date()
const monthAgo = new Date()
monthAgo.setDate(today.getDate() - 30)
const [filter, setFilter] = useState({
date_from: formatDateDDMMYYYY(monthAgo),
date_to: formatDateDDMMYYYY(today)
})
// Sample data - replace with your actual data
const { data: profitData, isLoading } = useProfitLossAnalytics({
date_from: filter.date_from,
date_to: filter.date_to
})
const formatCurrency = (amount: any) => {
return new Intl.NumberFormat('id-ID', {
style: 'currency',
currency: 'IDR',
minimumFractionDigits: 0
}).format(amount)
}
return nameMap[metric] || metric.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}
const DashboardProfitLoss = () => {
const { data, isLoading } = useProfitLossAnalytics()
const formatPercentage = (value: any) => {
return `${value.toFixed(2)}%`
}
const formatDate = (dateString: any) => {
return new Date(dateString).toLocaleDateString('id-ID', {
day: 'numeric',
month: 'short',
day: 'numeric'
year: 'numeric'
})
}
const metrics = ['cost', 'revenue', 'gross_profit', 'net_profit']
const transformSalesData = (data: ProfitLossReport) => {
return [
{
type: 'products',
avatarIcon: 'tabler-package',
date: data.product_data.map((d: ProductDataReport) => d.product_name),
series: [{ data: data.product_data.map((d: ProductDataReport) => d.revenue) }]
}
// {
// type: 'profits',
// avatarIcon: 'tabler-currency-dollar',
// date: data.data.map((d: DailyData) => formatDate(d.date)),
// series: metrics.map(metric => ({
// name: formatMetricName(metric as string),
// data: data.data.map((item: any) => item[metric] as number)
// }))
// }
]
const getProfitabilityColor = (margin: any) => {
if (margin > 50) return 'text-green-600 bg-green-100'
if (margin > 0) return 'text-yellow-600 bg-yellow-100'
return 'text-red-600 bg-red-100'
}
function formatMetricName(metric: string): string {
const nameMap: { [key: string]: string } = {
revenue: 'Revenue',
net_profit: 'Net Profit'
}
return nameMap[metric] || metric.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}
const metrics = ['revenue', 'net_profit']
const transformMultipleData = (data: ProfitLossReport) => {
return [
{
@@ -75,58 +77,348 @@ const DashboardProfitLoss = () => {
]
}
if (isLoading) return <Loading />
const MetricCard = ({
iconClass,
title,
value,
subtitle,
bgColor = 'bg-blue-500',
isNegative = false,
isCurrency = false
}: any) => (
<div className='bg-white rounded-lg shadow-md hover:shadow-xl transition-shadow duration-300 p-6'>
<div className='flex items-center justify-between'>
<div className='flex-1'>
<h3 className='text-sm font-medium text-gray-600 mb-2'>{title}</h3>
<p className={`text-2xl font-bold mb-1 ${isNegative ? 'text-red-600' : 'text-gray-900'}`}>
{isCurrency ? 'Rp ' + value : value}
</p>
{subtitle && <p className='text-sm text-gray-500'>{subtitle}</p>}
</div>
<div className={`px-4 py-3 rounded-full ${bgColor} bg-opacity-10`}>
<i className={`${iconClass} text-[32px] ${bgColor.replace('bg-', 'text-')}`}></i>
</div>
</div>
</div>
)
return (
<Grid container spacing={6}>
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Cost'
value={data?.summary.total_cost as number}
avatarIcon={'tabler-currency-dollar'}
avatarColor='primary'
avatarSkin='light'
/>
</Grid>
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
<DistributedBarChartOrder
isLoading={isLoading}
title='Total Rvenue'
value={data?.summary.total_revenue as number}
avatarIcon={'tabler-currency-dollar'}
avatarColor='info'
avatarSkin='light'
/>
</Grid>
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
<DistributedBarChartOrder
isLoading={isLoading}
title='Gross Profit'
value={data?.summary.gross_profit as number}
avatarIcon={'tabler-trending-up'}
avatarColor='warning'
avatarSkin='light'
/>
</Grid>
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
<DistributedBarChartOrder
isLoading={isLoading}
title='Net Profit'
value={data?.summary.net_profit as number}
avatarIcon={'tabler-currency-dollar'}
avatarColor='success'
avatarSkin='light'
/>
</Grid>
<Grid size={{ xs: 12, lg: 12 }}>
<EarningReportsWithTabs data={transformSalesData(data!)} />
</Grid>
<Grid size={{ xs: 12, lg: 12 }}>
<MultipleSeries data={transformMultipleData(data!)} />
</Grid>
</Grid>
<>
<div>
{/* Header */}
<div className='mb-8 flex gap-4 items-center justify-between'>
<Typography variant='h1' className='text-3xl font-bold text-gray-900 mb-2'>
Profit Analysis Dashboard
</Typography>
<div className='flex items-center gap-4'>
<TextField
type='date'
value={formatForInputDate(profitData?.date_from || new Date())}
onChange={e => {
setFilter({
...filter,
date_from: formatDateDDMMYYYY(new Date(e.target.value))
})
}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
<Typography>-</Typography>
<TextField
type='date'
value={
profitData?.date_to
? new Date(profitData?.date_to).toISOString().split('T')[0]
: new Date().toISOString().split('T')[0]
}
onChange={e => {}}
size='small'
sx={{
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}}
/>
</div>
</div>
{profitData ? (
<>
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8'>
<MetricCard
iconClass='tabler-currency-dollar'
title='Total Revenue'
value={formatShortCurrency(profitData.summary.total_revenue)}
bgColor='bg-green-500'
isCurrency={true}
/>
<MetricCard
iconClass='tabler-receipt'
title='Total Cost'
value={formatShortCurrency(profitData.summary.total_cost)}
bgColor='bg-red-500'
isCurrency={true}
/>
<MetricCard
iconClass='tabler-trending-up'
title='Gross Profit'
value={formatShortCurrency(profitData.summary.gross_profit)}
subtitle={`Margin: ${formatPercentage(profitData.summary.gross_profit_margin)}`}
bgColor='bg-blue-500'
isNegative={profitData.summary.gross_profit < 0}
isCurrency={true}
/>
<MetricCard
iconClass='tabler-percentage'
title='Profitability Ratio'
value={formatPercentage(profitData.summary.profitability_ratio)}
subtitle={`Avg Profit: ${formatShortCurrency(profitData.summary.average_profit)}`}
bgColor='bg-purple-500'
/>
</div>
{/* Additional Summary Metrics */}
<div className='grid grid-cols-1 md:grid-cols-3 gap-6 mb-8'>
<div className='bg-white rounded-lg shadow-md p-6'>
<div className='flex items-center mb-4'>
<i className='tabler-wallet text-[24px] text-green-600 mr-2'></i>
<h3 className='text-lg font-semibold text-gray-900'>Net Profit</h3>
</div>
<p className='text-3xl font-bold text-green-600 mb-2'>
Rp {formatShortCurrency(profitData.summary.net_profit)}
</p>
<p className='text-sm text-gray-600'>
Margin: {formatPercentage(profitData.summary.net_profit_margin)}
</p>
</div>
<div className='bg-white rounded-lg shadow-md p-6'>
<div className='flex items-center mb-4'>
<i className='tabler-shopping-cart text-[24px] text-blue-600 mr-2'></i>
<h3 className='text-lg font-semibold text-gray-900'>Total Orders</h3>
</div>
<p className='text-3xl font-bold text-blue-600'>{profitData.summary.total_orders}</p>
</div>
<div className='bg-white rounded-lg shadow-md p-6'>
<div className='flex items-center mb-4'>
<i className='tabler-discount text-[24px] text-orange-600 mr-2'></i>
<h3 className='text-lg font-semibold text-gray-900'>Tax & Discount</h3>
</div>
<p className='text-xl font-bold text-orange-600 mb-1'>
Rp {formatShortCurrency(profitData.summary.total_tax + profitData.summary.total_discount)}
</p>
<p className='text-sm text-gray-600'>
Tax: {formatShortCurrency(profitData.summary.total_tax)} | Discount:{' '}
{formatShortCurrency(profitData.summary.total_discount)}
</p>
</div>
</div>
{/* Profit Chart */}
<div className='mb-8'>
<MultipleSeries data={transformMultipleData(profitData)} />
</div>
<div className='grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8'>
{/* Daily Breakdown */}
<div className='bg-white rounded-lg shadow-md'>
<div className='p-6'>
<div className='flex items-center mb-6'>
<i className='tabler-calendar text-[24px] text-purple-500 mr-2'></i>
<h2 className='text-xl font-semibold text-gray-900'>Daily Breakdown</h2>
</div>
<div className='overflow-x-auto'>
<table className='min-w-full'>
<thead>
<tr className='bg-gray-50'>
<th className='px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase'>Date</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Revenue</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Cost</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Profit</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Margin</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Orders</th>
</tr>
</thead>
<tbody className='bg-white divide-y divide-gray-200'>
{profitData.data.map((day, index) => (
<tr key={index} className='hover:bg-gray-50'>
<td className='px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-900'>
{formatDate(day.date)}
</td>
<td className='px-4 py-4 whitespace-nowrap text-right text-sm text-gray-900'>
{formatCurrency(day.revenue)}
</td>
<td className='px-4 py-4 whitespace-nowrap text-right text-sm text-red-600'>
{formatCurrency(day.cost)}
</td>
<td
className={`px-4 py-4 whitespace-nowrap text-right text-sm font-medium ${
day.gross_profit >= 0 ? 'text-green-600' : 'text-red-600'
}`}
>
{formatCurrency(day.gross_profit)}
</td>
<td className='px-4 py-4 whitespace-nowrap text-right'>
<span
className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getProfitabilityColor(
day.gross_profit_margin
)}`}
>
{formatPercentage(day.gross_profit_margin)}
</span>
</td>
<td className='px-4 py-4 whitespace-nowrap text-right text-sm text-gray-900'>
{day.orders}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
{/* Top Performing Products */}
<div className='bg-white rounded-lg shadow-md'>
<div className='p-6'>
<div className='flex items-center mb-6'>
<i className='tabler-trophy text-[24px] text-gold-500 mr-2'></i>
<h2 className='text-xl font-semibold text-gray-900'>Top Performers</h2>
</div>
<div className='space-y-4'>
{profitData.product_data
.sort((a, b) => b.gross_profit - a.gross_profit)
.slice(0, 5)
.map((product, index) => (
<div
key={product.product_id}
className='flex items-center justify-between p-4 bg-gray-50 rounded-lg'
>
<div className='flex items-center'>
<span
className={`w-8 h-8 rounded-full flex items-center justify-center text-white text-sm font-bold mr-3 ${
index === 0
? 'bg-yellow-500'
: index === 1
? 'bg-gray-400'
: index === 2
? 'bg-orange-500'
: 'bg-blue-500'
}`}
>
{index + 1}
</span>
<div>
<h3 className='font-medium text-gray-900'>{product.product_name}</h3>
<p className='text-sm text-gray-600'>{product.category_name}</p>
</div>
</div>
<div className='text-right'>
<p className={`font-bold ${product.gross_profit >= 0 ? 'text-green-600' : 'text-red-600'}`}>
{formatCurrency(product.gross_profit)}
</p>
<p className='text-xs text-gray-500'>{formatPercentage(product.gross_profit_margin)}</p>
</div>
</div>
))}
</div>
</div>
</div>
</div>
{/* Product Analysis Table */}
<div className='bg-white rounded-lg shadow-md'>
<div className='p-6'>
<div className='flex items-center mb-6'>
<i className='tabler-package text-[24px] text-green-500 mr-2'></i>
<h2 className='text-xl font-semibold text-gray-900'>Product Analysis</h2>
</div>
<div className='overflow-x-auto'>
<table className='min-w-full'>
<thead>
<tr className='bg-gray-50'>
<th className='px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase'>Product</th>
<th className='px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase'>Category</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Qty</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Revenue</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Cost</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Profit</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Margin</th>
<th className='px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase'>Per Unit</th>
</tr>
</thead>
<tbody className='bg-white divide-y divide-gray-200'>
{profitData.product_data
.sort((a, b) => b.gross_profit - a.gross_profit)
.map(product => (
<tr key={product.product_id} className='hover:bg-gray-50'>
<td className='px-4 py-4 whitespace-nowrap'>
<div className='text-sm font-medium text-gray-900'>{product.product_name}</div>
</td>
<td className='px-4 py-4 whitespace-nowrap'>
<span className='inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800'>
{product.category_name}
</span>
</td>
<td className='px-4 py-4 whitespace-nowrap text-right text-sm text-gray-900'>
{product.quantity_sold}
</td>
<td className='px-4 py-4 whitespace-nowrap text-right text-sm text-gray-900'>
{formatCurrency(product.revenue)}
</td>
<td className='px-4 py-4 whitespace-nowrap text-right text-sm text-red-600'>
{formatCurrency(product.cost)}
</td>
<td
className={`px-4 py-4 whitespace-nowrap text-right text-sm font-medium ${
product.gross_profit >= 0 ? 'text-green-600' : 'text-red-600'
}`}
>
{formatCurrency(product.gross_profit)}
</td>
<td className='px-4 py-4 whitespace-nowrap text-right'>
<span
className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getProfitabilityColor(
product.gross_profit_margin
)}`}
>
{formatPercentage(product.gross_profit_margin)}
</span>
</td>
<td
className={`px-4 py-4 whitespace-nowrap text-right text-sm ${
product.profit_per_unit >= 0 ? 'text-green-600' : 'text-red-600'
}`}
>
{formatCurrency(product.profit_per_unit)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
</>
) : (
<Loading />
)}
</div>
</>
)
}
export default DashboardProfitLoss
export default DashboardProfitloss
@@ -2,24 +2,23 @@
import Button from '@mui/material/Button'
// Type Imports
import type { ChildrenType } from '@core/types'
import type { Locale } from '@configs/i18n'
import type { ChildrenType } from '@core/types'
// Layout Imports
import HorizontalLayout from '@layouts/HorizontalLayout'
import LayoutWrapper from '@layouts/LayoutWrapper'
import VerticalLayout from '@layouts/VerticalLayout'
import HorizontalLayout from '@layouts/HorizontalLayout'
// Component Imports
import Providers from '@components/Providers'
import Navigation from '@components/layout/vertical/Navigation'
import Header from '@components/layout/horizontal/Header'
import Navbar from '@components/layout/vertical/Navbar'
import VerticalFooter from '@components/layout/vertical/Footer'
import HorizontalFooter from '@components/layout/horizontal/Footer'
import Customizer from '@core/components/customizer'
import ScrollToTop from '@core/components/scroll-to-top'
import AuthGuard from '@/hocs/AuthGuard'
import Providers from '@components/Providers'
import HorizontalFooter from '@components/layout/horizontal/Footer'
import Header from '@components/layout/horizontal/Header'
import VerticalFooter from '@components/layout/vertical/Footer'
import Navbar from '@components/layout/vertical/Navbar'
import Navigation from '@components/layout/vertical/Navigation'
import ScrollToTop from '@core/components/scroll-to-top'
// Config Imports
import { i18n } from '@configs/i18n'
+75
View File
@@ -0,0 +1,75 @@
// MUI Imports
import Button from '@mui/material/Button'
// Type Imports
import type { Locale } from '@configs/i18n'
import type { ChildrenType } from '@core/types'
// Layout Imports
import HorizontalLayout from '@layouts/HorizontalLayout'
import LayoutWrapper from '@layouts/LayoutWrapper'
import VerticalLayout from '@layouts/VerticalLayout'
// Component Imports
import Providers from '@components/Providers'
import HorizontalFooter from '@components/layout/horizontal/Footer'
import Header from '@components/layout/horizontal/Header'
import VerticalFooter from '@components/layout/vertical/Footer'
import Navbar from '@components/layout/vertical/Navbar'
import Navigation from '@components/layout/vertical/Navigation'
import ScrollToTop from '@core/components/scroll-to-top'
// Config Imports
import { i18n } from '@configs/i18n'
// Util Imports
import { getDictionary } from '@/utils/getDictionary'
import { getMode, getSystemMode } from '@core/utils/serverHelpers'
import RolesGuard from '../../../../hocs/RolesGuard'
const Layout = async (props: ChildrenType & { params: Promise<{ lang: Locale }> }) => {
const params = await props.params
const { children } = props
// Vars
const direction = i18n.langDirection[params.lang]
const dictionary = await getDictionary(params.lang)
const mode = await getMode()
const systemMode = await getSystemMode()
return (
<Providers direction={direction}>
<RolesGuard locale={params.lang}>
<LayoutWrapper
systemMode={systemMode}
verticalLayout={
<VerticalLayout
navigation={<Navigation dictionary={dictionary} mode={mode} />}
navbar={<Navbar />}
footer={<VerticalFooter />}
>
{children}
</VerticalLayout>
}
horizontalLayout={
<HorizontalLayout header={<Header dictionary={dictionary} />} footer={<HorizontalFooter />}>
{children}
</HorizontalLayout>
}
/>
<ScrollToTop className='mui-fixed'>
<Button
variant='contained'
className='is-10 bs-10 rounded-full p-0 min-is-0 flex items-center justify-center'
>
<i className='tabler-arrow-up' />
</Button>
</ScrollToTop>
{/* <Customizer dir={direction} /> */}
</RolesGuard>
</Providers>
)
}
export default Layout
@@ -0,0 +1,25 @@
import OrganizationListTable from '../../../../../../../views/sa/organizations/list/OrganizationListTable'
/**
* ! If you need data using an API call, uncomment the below API code, update the `process.env.API_URL` variable in the
* ! `.env` file found at root of your project and also update the API endpoints like `/apps/ecommerce` in below example.
* ! Also, remove the above server action import and the action itself from the `src/app/server/actions.ts` file to clean up unused code
* ! because we've used the server action for getting our static data.
*/
/* const getEcommerceData = async () => {
// Vars
const res = await fetch(`${process.env.API_URL}/apps/ecommerce`)
if (!res.ok) {
throw new Error('Failed to fetch ecommerce data')
}
return res.json()
} */
const OrganizationsListTablePage = async () => {
return <OrganizationListTable />
}
export default OrganizationsListTablePage
+291
View File
@@ -0,0 +1,291 @@
'use client'
// React Imports
import { useEffect, useState } from 'react'
// MUI Imports
import type { BoxProps } from '@mui/material/Box'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import Typography from '@mui/material/Typography'
import { styled } from '@mui/material/styles'
// Third-party Imports
import { useDropzone } from 'react-dropzone'
// Component Imports
import Link from '@components/Link'
import CustomAvatar from '@core/components/mui/Avatar'
// Styled Component Imports
import AppReactDropzone from '@/libs/styles/AppReactDropzone'
type FileProp = {
name: string
type: string
size: number
}
interface ImageUploadProps {
// Required props
onUpload: (file: File) => Promise<string> | string // Returns image URL
// Optional customization props
title?: string | null // Made nullable
currentImageUrl?: string
onImageRemove?: () => void
onImageChange?: (url: string) => void
// Upload state
isUploading?: boolean
// UI customization
maxFileSize?: number // in bytes
acceptedFileTypes?: string[]
showUrlOption?: boolean
uploadButtonText?: string
browseButtonText?: string
dragDropText?: string
replaceText?: string
// Style customization
className?: string
disabled?: boolean
}
// Styled Dropzone Component
const Dropzone = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
'& .dropzone': {
minHeight: 'unset',
padding: theme.spacing(12),
[theme.breakpoints.down('sm')]: {
paddingInline: theme.spacing(5)
},
'&+.MuiList-root .MuiListItem-root .file-name': {
fontWeight: theme.typography.body1.fontWeight
}
}
}))
const ImageUpload: React.FC<ImageUploadProps> = ({
onUpload,
title = null, // Default to null
currentImageUrl = '',
onImageRemove,
onImageChange,
isUploading = false,
maxFileSize = 5 * 1024 * 1024, // 5MB default
acceptedFileTypes = ['image/*'],
showUrlOption = true,
uploadButtonText = 'Upload',
browseButtonText = 'Browse Image',
dragDropText = 'Drag and Drop Your Image Here.',
replaceText = 'Drop New Image to Replace',
className = '',
disabled = false
}) => {
// States
const [files, setFiles] = useState<File[]>([])
const [error, setError] = useState<string>('')
const handleUpload = async () => {
if (!files.length) return
try {
setError('')
const imageUrl = await onUpload(files[0])
if (typeof imageUrl === 'string') {
onImageChange?.(imageUrl)
setFiles([]) // Clear files after successful upload
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
}
}
// Hooks
const { getRootProps, getInputProps } = useDropzone({
onDrop: (acceptedFiles: File[]) => {
setError('')
if (acceptedFiles.length === 0) return
const file = acceptedFiles[0]
// Validate file size
if (file.size > maxFileSize) {
setError(`File size should be less than ${formatFileSize(maxFileSize)}`)
return
}
// Replace files instead of adding to them
setFiles([file])
},
accept: acceptedFileTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),
disabled: disabled || isUploading
})
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const renderFilePreview = (file: FileProp) => {
if (file.type.startsWith('image')) {
return <img width={38} height={38} alt={file.name} src={URL.createObjectURL(file as any)} />
} else {
return <i className='tabler-file-description' />
}
}
const handleRemoveFile = (file: FileProp) => {
const filtered = files.filter((i: FileProp) => i.name !== file.name)
setFiles(filtered)
setError('')
}
const handleRemoveCurrentImage = () => {
onImageRemove?.()
}
const handleRemoveAllFiles = () => {
setFiles([])
setError('')
}
const fileList = files.map((file: FileProp) => (
<ListItem key={file.name} className='pis-4 plb-3'>
<div className='file-details'>
<div className='file-preview'>{renderFilePreview(file)}</div>
<div>
<Typography className='file-name font-medium' color='text.primary'>
{file.name}
</Typography>
<Typography className='file-size' variant='body2'>
{formatFileSize(file.size)}
</Typography>
</div>
</div>
<IconButton onClick={() => handleRemoveFile(file)} disabled={isUploading}>
<i className='tabler-x text-xl' />
</IconButton>
</ListItem>
))
return (
<Dropzone className={className}>
{/* Conditional title and URL option header */}
{title && (
<div className='flex justify-between items-center mb-4'>
<Typography variant='h6' component='h2'>
{title}
</Typography>
{showUrlOption && (
<Typography component={Link} color='primary.main' className='font-medium'>
Add media from URL
</Typography>
)}
</div>
)}
<div {...getRootProps({ className: 'dropzone' })}>
<input {...getInputProps()} />
<div className='flex items-center flex-col gap-2 text-center'>
<CustomAvatar variant='rounded' skin='light' color='secondary'>
<i className='tabler-upload' />
</CustomAvatar>
<Typography variant='h4'>{currentImageUrl && !files.length ? replaceText : dragDropText}</Typography>
<Typography color='text.disabled'>or</Typography>
<Button variant='tonal' size='small' disabled={disabled || isUploading}>
{browseButtonText}
</Button>
</div>
</div>
{/* Error Message */}
{error && (
<Typography color='error' variant='body2' className='mt-2 text-center'>
{error}
</Typography>
)}
{/* Show current image if it exists */}
{currentImageUrl && !files.length && (
<div className='current-image mb-4'>
<Typography variant='subtitle2' className='mb-2'>
Current Image:
</Typography>
<div className='flex items-center justify-between p-3 border border-gray-200 rounded'>
<div className='flex items-center gap-3'>
<img width={60} height={60} alt='Current image' src={currentImageUrl} className='rounded object-cover' />
<div>
<Typography className='font-medium' color='text.primary'>
Current image
</Typography>
<Typography variant='body2' color='text.secondary'>
Uploaded image
</Typography>
</div>
</div>
{onImageRemove && (
<IconButton onClick={handleRemoveCurrentImage} color='error' disabled={isUploading}>
<i className='tabler-x text-xl' />
</IconButton>
)}
</div>
</div>
)}
{/* File list and upload buttons */}
{files.length > 0 && (
<>
<List>{fileList}</List>
<div className='buttons'>
<Button color='error' variant='tonal' onClick={handleRemoveAllFiles} disabled={isUploading}>
Remove All
</Button>
<Button variant='contained' onClick={handleUpload} disabled={isUploading}>
{isUploading ? 'Uploading...' : uploadButtonText}
</Button>
</div>
</>
)}
</Dropzone>
)
}
export default ImageUpload
// ===== USAGE EXAMPLES =====
// 1. Without title
// <ImageUpload
// onUpload={handleUpload}
// currentImageUrl={imageUrl}
// onImageChange={setImageUrl}
// onImageRemove={() => setImageUrl('')}
// />
// 2. With title
// <ImageUpload
// title="Product Image"
// onUpload={handleUpload}
// currentImageUrl={imageUrl}
// onImageChange={setImageUrl}
// onImageRemove={() => setImageUrl('')}
// />
// 3. Explicitly set title to null
// <ImageUpload
// title={null}
// onUpload={handleUpload}
// currentImageUrl={imageUrl}
// onImageChange={setImageUrl}
// onImageRemove={() => setImageUrl('')}
// />
+465
View File
@@ -0,0 +1,465 @@
'use client'
// React Imports
import { useEffect, useState } from 'react'
// MUI Imports
import type { BoxProps } from '@mui/material/Box'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import Typography from '@mui/material/Typography'
import Chip from '@mui/material/Chip'
import LinearProgress from '@mui/material/LinearProgress'
import { styled } from '@mui/material/styles'
// Third-party Imports
import { useDropzone } from 'react-dropzone'
// Component Imports
import Link from '@components/Link'
import CustomAvatar from '@core/components/mui/Avatar'
// Styled Component Imports
import AppReactDropzone from '@/libs/styles/AppReactDropzone'
type FileProp = {
name: string
type: string
size: number
}
type UploadedImage = {
id: string
url: string
name: string
size: number
}
type UploadProgress = {
[fileId: string]: number
}
interface MultipleImageUploadProps {
// Required props
onUpload: (files: File[]) => Promise<string[]> | string[] // Returns array of image URLs
onSingleUpload?: (file: File) => Promise<string> | string // For individual file upload
// Optional customization props
title?: string | null
currentImages?: UploadedImage[]
onImagesChange?: (images: UploadedImage[]) => void
onImageRemove?: (imageId: string) => void
// Upload state
isUploading?: boolean
uploadProgress?: UploadProgress
// Limits
maxFiles?: number
maxFileSize?: number // in bytes
acceptedFileTypes?: string[]
// UI customization
showUrlOption?: boolean
uploadButtonText?: string
browseButtonText?: string
dragDropText?: string
replaceText?: string
maxFilesText?: string
// Style customization
className?: string
disabled?: boolean
// Upload modes
uploadMode?: 'batch' | 'individual' // batch: upload all at once, individual: upload one by one
}
// Styled Dropzone Component
const Dropzone = styled(AppReactDropzone)<BoxProps>(({ theme }) => ({
'& .dropzone': {
minHeight: 'unset',
padding: theme.spacing(12),
[theme.breakpoints.down('sm')]: {
paddingInline: theme.spacing(5)
},
'&+.MuiList-root .MuiListItem-root .file-name': {
fontWeight: theme.typography.body1.fontWeight
}
}
}))
const MultipleImageUpload: React.FC<MultipleImageUploadProps> = ({
onUpload,
onSingleUpload,
title = null,
currentImages = [],
onImagesChange,
onImageRemove,
isUploading = false,
uploadProgress = {},
maxFiles = 10,
maxFileSize = 5 * 1024 * 1024, // 5MB default
acceptedFileTypes = ['image/*'],
showUrlOption = true,
uploadButtonText = 'Upload All',
browseButtonText = 'Browse Images',
dragDropText = 'Drag and Drop Your Images Here.',
replaceText = 'Drop Images to Add More',
maxFilesText = 'Maximum {max} files allowed',
className = '',
disabled = false,
uploadMode = 'batch'
}) => {
// States
const [files, setFiles] = useState<File[]>([])
const [error, setError] = useState<string>('')
const [individualUploading, setIndividualUploading] = useState<Set<string>>(new Set())
const handleBatchUpload = async () => {
if (!files.length) return
try {
setError('')
const imageUrls = await onUpload(files)
if (Array.isArray(imageUrls)) {
const newImages: UploadedImage[] = files.map((file, index) => ({
id: `${Date.now()}-${index}`,
url: imageUrls[index],
name: file.name,
size: file.size
}))
const updatedImages = [...currentImages, ...newImages]
onImagesChange?.(updatedImages)
setFiles([]) // Clear files after successful upload
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
}
}
const handleIndividualUpload = async (file: File, fileIndex: number) => {
if (!onSingleUpload) return
const fileId = `${file.name}-${fileIndex}`
setIndividualUploading(prev => new Set(prev).add(fileId))
try {
setError('')
const imageUrl = await onSingleUpload(file)
if (typeof imageUrl === 'string') {
const newImage: UploadedImage = {
id: `${Date.now()}-${fileIndex}`,
url: imageUrl,
name: file.name,
size: file.size
}
const updatedImages = [...currentImages, newImage]
onImagesChange?.(updatedImages)
// Remove uploaded file from pending files
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
} finally {
setIndividualUploading(prev => {
const newSet = new Set(prev)
newSet.delete(fileId)
return newSet
})
}
}
// Hooks
const { getRootProps, getInputProps } = useDropzone({
onDrop: (acceptedFiles: File[]) => {
setError('')
if (acceptedFiles.length === 0) return
const totalFiles = currentImages.length + files.length + acceptedFiles.length
if (totalFiles > maxFiles) {
setError(`Cannot upload more than ${maxFiles} files. Current: ${currentImages.length + files.length}`)
return
}
// Validate file sizes
const invalidFiles = acceptedFiles.filter(file => file.size > maxFileSize)
if (invalidFiles.length > 0) {
setError(`Some files exceed ${formatFileSize(maxFileSize)} limit`)
return
}
// Add to existing files
setFiles(prev => [...prev, ...acceptedFiles])
},
accept: acceptedFileTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),
disabled: disabled || isUploading,
multiple: true
})
const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const renderFilePreview = (file: FileProp) => {
if (file.type.startsWith('image')) {
return (
<img
width={38}
height={38}
alt={file.name}
src={URL.createObjectURL(file as any)}
className='rounded object-cover'
/>
)
} else {
return <i className='tabler-file-description' />
}
}
const handleRemoveFile = (fileIndex: number) => {
setFiles(prev => prev.filter((_, index) => index !== fileIndex))
setError('')
}
const handleRemoveCurrentImage = (imageId: string) => {
onImageRemove?.(imageId)
}
const handleRemoveAllFiles = () => {
setFiles([])
setError('')
}
const isIndividualUploading = (file: File, index: number) => {
const fileId = `${file.name}-${index}`
return individualUploading.has(fileId)
}
const fileList = files.map((file: File, index: number) => {
const isFileUploading = isIndividualUploading(file, index)
const progress = uploadProgress[`${file.name}-${index}`] || 0
return (
<ListItem key={`${file.name}-${index}`} className='pis-4 plb-3'>
<div className='file-details flex-1'>
<div className='file-preview'>{renderFilePreview(file)}</div>
<div className='flex-1'>
<Typography className='file-name font-medium' color='text.primary'>
{file.name}
</Typography>
<Typography className='file-size' variant='body2'>
{formatFileSize(file.size)}
</Typography>
{isFileUploading && progress > 0 && (
<LinearProgress variant='determinate' value={progress} className='mt-1' />
)}
</div>
</div>
<div className='flex items-center gap-2'>
{uploadMode === 'individual' && onSingleUpload && (
<Button
variant='outlined'
size='small'
onClick={() => handleIndividualUpload(file, index)}
disabled={isUploading || isFileUploading}
>
{isFileUploading ? 'Uploading...' : 'Upload'}
</Button>
)}
<IconButton onClick={() => handleRemoveFile(index)} disabled={isUploading || isFileUploading}>
<i className='tabler-x text-xl' />
</IconButton>
</div>
</ListItem>
)
})
const currentImagesList = currentImages.map(image => (
<ListItem key={image.id} className='pis-4 plb-3'>
<div className='file-details flex-1'>
<div className='file-preview'>
<img width={38} height={38} alt={image.name} src={image.url} className='rounded object-cover' />
</div>
<div className='flex-1'>
<Typography className='file-name font-medium' color='text.primary'>
{image.name}
</Typography>
<Typography className='file-size' variant='body2'>
{formatFileSize(image.size)}
</Typography>
</div>
</div>
<div className='flex items-center gap-2'>
<Chip label='Uploaded' color='success' size='small' />
{onImageRemove && (
<IconButton onClick={() => handleRemoveCurrentImage(image.id)} color='error' disabled={isUploading}>
<i className='tabler-x text-xl' />
</IconButton>
)}
</div>
</ListItem>
))
return (
<Dropzone className={className}>
{/* Conditional title and URL option header */}
{title && (
<div className='flex justify-between items-center mb-4'>
<Typography variant='h6' component='h2'>
{title}
</Typography>
{showUrlOption && (
<Typography component={Link} color='primary.main' className='font-medium'>
Add media from URL
</Typography>
)}
</div>
)}
{/* File limits info */}
<div className='flex justify-between items-center mb-4'>
<Typography variant='body2' color='text.secondary'>
{maxFilesText.replace('{max}', maxFiles.toString())}
</Typography>
<Typography variant='body2' color='text.secondary'>
{currentImages.length + files.length} / {maxFiles} files
</Typography>
</div>
<div {...getRootProps({ className: 'dropzone' })}>
<input {...getInputProps()} />
<div className='flex items-center flex-col gap-2 text-center'>
<CustomAvatar variant='rounded' skin='light' color='secondary'>
<i className='tabler-upload' />
</CustomAvatar>
<Typography variant='h4'>
{currentImages.length > 0 || files.length > 0 ? replaceText : dragDropText}
</Typography>
<Typography color='text.disabled'>or</Typography>
<Button variant='tonal' size='small' disabled={disabled || isUploading}>
{browseButtonText}
</Button>
</div>
</div>
{/* Error Message */}
{error && (
<Typography color='error' variant='body2' className='mt-2 text-center'>
{error}
</Typography>
)}
{/* Current uploaded images */}
{currentImages.length > 0 && (
<div className='mt-4'>
<Typography variant='subtitle2' className='mb-2'>
Uploaded Images ({currentImages.length}):
</Typography>
<List>{currentImagesList}</List>
</div>
)}
{/* Pending files list and upload buttons */}
{files.length > 0 && (
<div className='mt-4'>
<Typography variant='subtitle2' className='mb-2'>
Pending Files ({files.length}):
</Typography>
<List>{fileList}</List>
<div className='buttons flex gap-2 mt-3'>
<Button color='error' variant='tonal' onClick={handleRemoveAllFiles} disabled={isUploading}>
Remove All
</Button>
{uploadMode === 'batch' && (
<Button variant='contained' onClick={handleBatchUpload} disabled={isUploading || files.length === 0}>
{isUploading ? 'Uploading...' : `${uploadButtonText} (${files.length})`}
</Button>
)}
</div>
</div>
)}
</Dropzone>
)
}
export default MultipleImageUpload
// ===== USAGE EXAMPLES =====
// 1. Batch upload mode (upload all files at once)
// const [images, setImages] = useState<UploadedImage[]>([])
//
// <MultipleImageUpload
// title="Product Images"
// onUpload={handleBatchUpload}
// currentImages={images}
// onImagesChange={setImages}
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
// maxFiles={5}
// uploadMode="batch"
// />
// 2. Individual upload mode (upload files one by one)
// <MultipleImageUpload
// title="Gallery Images"
// onUpload={handleBatchUpload}
// onSingleUpload={handleSingleUpload}
// currentImages={images}
// onImagesChange={setImages}
// onImageRemove={(id) => setImages(prev => prev.filter(img => img.id !== id))}
// maxFiles={10}
// uploadMode="individual"
// uploadProgress={uploadProgress}
// />
// 3. Without title, custom limits
// <MultipleImageUpload
// title={null}
// onUpload={handleBatchUpload}
// currentImages={images}
// onImagesChange={setImages}
// maxFiles={3}
// maxFileSize={2 * 1024 * 1024} // 2MB
// acceptedFileTypes={['image/jpeg', 'image/png']}
// />
// 4. Example upload handlers
// const handleBatchUpload = async (files: File[]): Promise<string[]> => {
// const formData = new FormData()
// files.forEach(file => formData.append('images', file))
//
// const response = await fetch('/api/upload-multiple', {
// method: 'POST',
// body: formData
// })
//
// const result = await response.json()
// return result.urls // Array of uploaded image URLs
// }
//
// const handleSingleUpload = async (file: File): Promise<string> => {
// const formData = new FormData()
// formData.append('image', file)
//
// const response = await fetch('/api/upload-single', {
// method: 'POST',
// body: formData
// })
//
// const result = await response.json()
// return result.url // Single uploaded image URL
// }
+276
View File
@@ -0,0 +1,276 @@
// React Imports
import React from 'react'
// MUI Imports
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import { useTheme } from '@mui/material/styles'
import type { TextFieldProps } from '@mui/material/TextField'
interface DateRangePickerProps {
/**
* Start date value (Date object or date string)
*/
startDate: Date | string | null
/**
* End date value (Date object or date string)
*/
endDate: Date | string | null
/**
* Callback when start date changes
*/
onStartDateChange: (date: Date | null) => void
/**
* Callback when end date changes
*/
onEndDateChange: (date: Date | null) => void
/**
* Label for start date field
*/
startLabel?: string
/**
* Label for end date field
*/
endLabel?: string
/**
* Placeholder for start date field
*/
startPlaceholder?: string
/**
* Placeholder for end date field
*/
endPlaceholder?: string
/**
* Size of the text fields
*/
size?: 'small' | 'medium'
/**
* Whether the fields are disabled
*/
disabled?: boolean
/**
* Whether the fields are required
*/
required?: boolean
/**
* Custom className for the container
*/
className?: string
/**
* Custom styles for the container
*/
containerStyle?: React.CSSProperties
/**
* Separator between date fields
*/
separator?: string
/**
* Custom props for start date TextField
*/
startTextFieldProps?: Omit<TextFieldProps, 'type' | 'value' | 'onChange'>
/**
* Custom props for end date TextField
*/
endTextFieldProps?: Omit<TextFieldProps, 'type' | 'value' | 'onChange'>
/**
* Error state for start date
*/
startError?: boolean
/**
* Error state for end date
*/
endError?: boolean
/**
* Helper text for start date
*/
startHelperText?: string
/**
* Helper text for end date
*/
endHelperText?: string
}
// Utility functions
const formatDateForInput = (date: Date | string | null): string => {
if (!date) return ''
const dateObj = typeof date === 'string' ? new Date(date) : date
if (isNaN(dateObj.getTime())) return ''
return dateObj.toISOString().split('T')[0]
}
const parseDateFromInput = (dateString: string): Date | null => {
if (!dateString) return null
const date = new Date(dateString)
return isNaN(date.getTime()) ? null : date
}
const DateRangePicker: React.FC<DateRangePickerProps> = ({
startDate,
endDate,
onStartDateChange,
onEndDateChange,
startLabel,
endLabel,
startPlaceholder,
endPlaceholder,
size = 'small',
disabled = false,
required = false,
className = '',
containerStyle = {},
separator = '-',
startTextFieldProps = {},
endTextFieldProps = {},
startError = false,
endError = false,
startHelperText,
endHelperText
}) => {
const theme = useTheme()
const defaultTextFieldSx = {
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: 'primary.main'
},
'& fieldset': {
borderColor: theme.palette.mode === 'dark' ? 'rgba(231, 227, 252, 0.22)' : theme.palette.divider
}
}
}
const handleStartDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const date = parseDateFromInput(event.target.value)
onStartDateChange(date)
}
const handleEndDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const date = parseDateFromInput(event.target.value)
onEndDateChange(date)
}
return (
<div className={`flex items-center gap-4 ${className}`} style={containerStyle}>
<TextField
type='date'
label={startLabel}
placeholder={startPlaceholder}
value={formatDateForInput(startDate)}
onChange={handleStartDateChange}
size={size}
disabled={disabled}
required={required}
error={startError}
helperText={startHelperText}
sx={{
...defaultTextFieldSx,
...startTextFieldProps.sx
}}
{...startTextFieldProps}
/>
<Typography
color='text.secondary'
sx={{
userSelect: 'none',
fontSize: size === 'small' ? '14px' : '16px'
}}
>
{separator}
</Typography>
<TextField
type='date'
label={endLabel}
placeholder={endPlaceholder}
value={formatDateForInput(endDate)}
onChange={handleEndDateChange}
size={size}
disabled={disabled}
required={required}
error={endError}
helperText={endHelperText}
sx={{
...defaultTextFieldSx,
...endTextFieldProps.sx
}}
{...endTextFieldProps}
/>
</div>
)
}
export default DateRangePicker
// Export utility functions for external use
export { formatDateForInput, parseDateFromInput }
// Example usage:
/*
import DateRangePicker from '@/components/DateRangePicker'
// In your component:
const [startDate, setStartDate] = useState<Date | null>(new Date())
const [endDate, setEndDate] = useState<Date | null>(new Date())
// Basic usage
<DateRangePicker
startDate={startDate}
endDate={endDate}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
/>
// With labels and validation
<DateRangePicker
startDate={startDate}
endDate={endDate}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
startLabel="Tanggal Mulai"
endLabel="Tanggal Selesai"
required
startError={startDate && endDate && startDate > endDate}
endError={startDate && endDate && startDate > endDate}
startHelperText={startDate && endDate && startDate > endDate ? "Tanggal mulai tidak boleh lebih besar dari tanggal selesai" : ""}
/>
// Custom styling
<DateRangePicker
startDate={startDate}
endDate={endDate}
onStartDateChange={setStartDate}
onEndDateChange={setEndDate}
separator="sampai"
size="medium"
className="my-custom-class"
startTextFieldProps={{
variant: "filled",
sx: { minWidth: '150px' }
}}
endTextFieldProps={{
variant: "filled",
sx: { minWidth: '150px' }
}}
/>
// Integration with your existing filter logic
const handleDateRangeChange = (start: Date | null, end: Date | null) => {
setFilter({
...filter,
date_from: start ? formatDateDDMMYYYY(start) : null,
date_to: end ? formatDateDDMMYYYY(end) : null
})
}
<DateRangePicker
startDate={filter.date_from ? new Date(filter.date_from) : null}
endDate={filter.date_to ? new Date(filter.date_to) : null}
onStartDateChange={(date) => handleDateRangeChange(date, filter.date_to ? new Date(filter.date_to) : null)}
onEndDateChange={(date) => handleDateRangeChange(filter.date_from ? new Date(filter.date_from) : null, date)}
/>
*/
+257
View File
@@ -0,0 +1,257 @@
// React Imports
import React, { useState } from 'react'
// MUI Imports
import Button from '@mui/material/Button'
import Menu from '@mui/material/Menu'
import MenuItem from '@mui/material/MenuItem'
import { styled } from '@mui/material/styles'
function toTitleCase(str: string): string {
return str
.toLowerCase()
.split(/\s+/) // split by spaces
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}
const DropdownButton = styled(Button)(({ theme }) => ({
textTransform: 'none',
fontWeight: 400,
borderRadius: '8px',
borderColor: '#e0e0e0',
color: '#666',
'&:hover': {
borderColor: '#ccc',
backgroundColor: 'rgba(0, 0, 0, 0.04)'
}
}))
interface StatusFilterTabsProps {
/**
* Array of status options to display as filter tabs
*/
statusOptions: string[]
/**
* Currently selected status filter
*/
selectedStatus: string
/**
* Callback function when a status is selected
*/
onStatusChange: (status: string) => void
/**
* Custom className for the container
*/
className?: string
/**
* Custom styles for the container
*/
containerStyle?: React.CSSProperties
/**
* Size of the buttons
*/
buttonSize?: 'small' | 'medium' | 'large'
/**
* Maximum number of status options to show as buttons before switching to dropdown
*/
maxButtonsBeforeDropdown?: number
/**
* Label for the dropdown when there are many options
*/
dropdownLabel?: string
}
const StatusFilterTabs: React.FC<StatusFilterTabsProps> = ({
statusOptions,
selectedStatus,
onStatusChange,
className = '',
containerStyle = {},
buttonSize = 'small',
maxButtonsBeforeDropdown = 5,
dropdownLabel = 'Lainnya'
}) => {
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
const open = Boolean(anchorEl)
const handleDropdownClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget)
}
const handleDropdownClose = () => {
setAnchorEl(null)
}
const handleDropdownItemClick = (status: string) => {
onStatusChange(status)
handleDropdownClose()
}
// If status options are <= maxButtonsBeforeDropdown, show all as buttons
if (statusOptions.length <= maxButtonsBeforeDropdown) {
return (
<div className='flex flex-wrap gap-2'>
{statusOptions.map(status => (
<Button
key={status}
variant={selectedStatus === status ? 'contained' : 'outlined'}
color={selectedStatus === status ? 'primary' : 'inherit'}
onClick={() => onStatusChange(status)}
size={buttonSize}
className='rounded-lg'
sx={{
textTransform: 'none',
fontWeight: selectedStatus === status ? 600 : 400,
borderRadius: '8px',
...(selectedStatus !== status && {
borderColor: '#e0e0e0',
color: '#666'
})
}}
>
{toTitleCase(status)}
</Button>
))}
</div>
)
}
// If more than maxButtonsBeforeDropdown, show first few as buttons and rest in dropdown
const buttonStatuses = statusOptions.slice(0, maxButtonsBeforeDropdown - 1)
const dropdownStatuses = statusOptions.slice(maxButtonsBeforeDropdown - 1)
const isDropdownItemSelected = dropdownStatuses.includes(selectedStatus)
return (
<div className='flex flex-wrap gap-2'>
{/* Regular buttons for first few statuses */}
{buttonStatuses.map(status => (
<Button
key={status}
variant={selectedStatus === status ? 'contained' : 'outlined'}
color={selectedStatus === status ? 'primary' : 'inherit'}
onClick={() => onStatusChange(status)}
size={buttonSize}
className='rounded-lg'
sx={{
textTransform: 'none',
fontWeight: selectedStatus === status ? 600 : 400,
borderRadius: '8px',
...(selectedStatus !== status && {
borderColor: '#e0e0e0',
color: '#666'
})
}}
>
{toTitleCase(status)}
</Button>
))}
{/* Dropdown button for remaining statuses */}
<DropdownButton
variant='outlined'
onClick={handleDropdownClick}
size={buttonSize}
endIcon={<i className='tabler-chevron-down' />}
sx={{
...(isDropdownItemSelected && {
backgroundColor: 'primary.main',
color: 'primary.contrastText',
borderColor: 'primary.main',
fontWeight: 600,
'&:hover': {
backgroundColor: 'primary.dark',
borderColor: 'primary.dark'
}
})
}}
>
{isDropdownItemSelected ? toTitleCase(selectedStatus) : dropdownLabel}
</DropdownButton>
<Menu
anchorEl={anchorEl}
open={open}
onClose={handleDropdownClose}
PaperProps={{
elevation: 3,
sx: {
mt: 1,
borderRadius: '8px',
minWidth: '160px'
}
}}
transformOrigin={{ horizontal: 'left', vertical: 'top' }}
anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}
>
{dropdownStatuses.map(status => (
<MenuItem
key={status}
onClick={() => handleDropdownItemClick(status)}
selected={selectedStatus === status}
sx={{
fontSize: '14px',
fontWeight: selectedStatus === status ? 600 : 400,
color: selectedStatus === status ? 'primary.main' : 'text.primary'
}}
>
{toTitleCase(status)}
</MenuItem>
))}
</Menu>
</div>
)
}
export default StatusFilterTabs
// Example usage:
/*
import StatusFilterTabs from '@/components/StatusFilterTabs'
// In your component:
const [statusFilter, setStatusFilter] = useState('Semua')
// For few statuses (will show all as buttons)
const expenseStatusOptions = ['Semua', 'Belum Dibayar', 'Dibayar Sebagian', 'Lunas']
// For many statuses (will show some buttons + dropdown)
const manyStatusOptions = [
'Semua',
'Belum Dibayar',
'Dibayar Sebagian',
'Lunas',
'Void',
'Retur',
'Jatuh Tempo',
'Transaksi Berulang',
'Ditangguhkan',
'Dibatalkan'
]
<StatusFilterTabs
statusOptions={expenseStatusOptions}
selectedStatus={statusFilter}
onStatusChange={setStatusFilter}
/>
// With many options (will automatically use dropdown)
<StatusFilterTabs
statusOptions={manyStatusOptions}
selectedStatus={statusFilter}
onStatusChange={setStatusFilter}
maxButtonsBeforeDropdown={4} // Show 3 buttons + dropdown
dropdownLabel="Status Lain"
/>
// Custom configuration
<StatusFilterTabs
statusOptions={manyStatusOptions}
selectedStatus={statusFilter}
onStatusChange={setStatusFilter}
maxButtonsBeforeDropdown={3}
dropdownLabel="Lainnya"
buttonSize="medium"
showBorder={false}
/>
*/
@@ -32,7 +32,7 @@ const HorizontalWithSubtitle = (props: UserDataType) => {
<div className='flex flex-col gap-1 flex-grow'>
<Typography color='text.primary'>{title}</Typography>
<div className='flex items-center gap-2 flex-wrap'>
<Typography variant='h4'>{stats}</Typography>
<Typography variant='h5'>{stats}</Typography>
<Typography color={trend === 'negative' ? 'error.main' : 'success.main'}>
{`(${trend === 'negative' ? '-' : '+'}${trendNumber})`}
</Typography>
@@ -97,8 +97,8 @@ const HorizontalMenu = ({ dictionary }: { dictionary: Awaited<ReturnType<typeof
<MenuItem href={`/${locale}/dashboards/analytics`} icon={<i className='tabler-trending-up' />}>
{dictionary['navigation'].analytics}
</MenuItem>
<MenuItem href={`/${locale}/dashboards/ecommerce`} icon={<i className='tabler-shopping-cart' />}>
{dictionary['navigation'].eCommerce}
<MenuItem href={`/${locale}/dashboards/inventory`} icon={<i className='tabler-shopping-cart' />}>
{dictionary['navigation'].inventory}
</MenuItem>
<MenuItem href={`/${locale}/dashboards/academy`} icon={<i className='tabler-school' />}>
{dictionary['navigation'].academy}
@@ -31,27 +31,27 @@ import { getLocalizedUrl } from '@/utils/i18n'
const shortcuts: ShortcutsType[] = [
{
url: '/apps/calendar',
icon: 'tabler-calendar',
title: 'Calendar',
subtitle: 'Appointments'
icon: 'tabler-box',
title: 'Produk',
subtitle: 'Kelola Produk'
},
{
url: '/apps/invoice/list',
icon: 'tabler-file-dollar',
title: 'Invoice App',
subtitle: 'Manage Accounts'
title: 'Pembelian',
subtitle: 'Kelola Pembelian'
},
{
url: '/apps/user/list',
icon: 'tabler-user',
title: 'Users',
subtitle: 'Manage Users'
title: 'Pengguna',
subtitle: 'Kelola Pengguna'
},
{
url: '/apps/roles',
url: '/apps/vendor',
icon: 'tabler-users-group',
title: 'Role Management',
subtitle: 'Permissions'
title: 'Vendor',
subtitle: 'Kelola Vendor'
},
{
url: '/',
@@ -60,10 +60,10 @@ const shortcuts: ShortcutsType[] = [
subtitle: 'User Dashboard'
},
{
url: '/pages/account-settings',
url: '/apps/reports',
icon: 'tabler-settings',
title: 'Settings',
subtitle: 'Account Settings'
title: 'Laporan',
subtitle: 'Lihat Laporan'
}
]
@@ -43,12 +43,8 @@ const languageData: LanguageDataType[] = [
langName: 'English'
},
{
langCode: 'fr',
langName: 'French'
},
{
langCode: 'ar',
langName: 'Arabic'
langCode: 'id',
langName: 'Indonesian'
}
]
+1 -1
View File
@@ -2,7 +2,7 @@ import { CircularProgress } from '@mui/material'
export default function Loading({ size = 60 }: { size?: number }) {
return (
<div className='fixed inset-0 z-50 flex items-center justify-center bg-white/70'>
<div className='absolute inset-0 z-50 flex items-center justify-center bg-white/70'>
<CircularProgress size={size} />
</div>
)
@@ -31,6 +31,7 @@ import { useSettings } from '@core/hooks/useSettings'
import { getLocalizedUrl } from '@/utils/i18n'
import { useAuthMutation } from '../../../services/mutations/auth'
import { useAuth } from '../../../contexts/authContext'
import { CircularProgress } from '@mui/material'
// Styled component for badge content
const BadgeContentSpan = styled('span')({
@@ -162,8 +163,9 @@ const UserDropdown = () => {
endIcon={<i className='tabler-logout' />}
onClick={handleUserLogout}
sx={{ '& .MuiButton-endIcon': { marginInlineStart: 1.5 } }}
disabled={logout.isPending}
>
Logout
Logout {logout.isPending && <CircularProgress size={16} />}
</Button>
</div>
</MenuList>
@@ -20,28 +20,28 @@ import { verticalLayoutClasses } from '@layouts/utils/layoutClasses'
// Vars
const shortcuts: ShortcutsType[] = [
{
url: '/apps/calendar',
icon: 'tabler-calendar',
title: 'Calendar',
subtitle: 'Appointments'
url: '/apps/inventory/products/list',
icon: 'tabler-box',
title: 'Produk',
subtitle: 'Kelola Produk'
},
{
url: '/apps/invoice/list',
url: '/apps/purchase/purchase-orders',
icon: 'tabler-file-dollar',
title: 'Invoice App',
subtitle: 'Manage Accounts'
title: 'Pembelian',
subtitle: 'Kelola Pembelian'
},
{
url: '/apps/user/list',
icon: 'tabler-user',
title: 'Users',
subtitle: 'Manage Users'
title: 'Pengguna',
subtitle: 'Kelola Pengguna'
},
{
url: '/apps/roles',
url: '/apps/vendor/list',
icon: 'tabler-users-group',
title: 'Role Management',
subtitle: 'Permissions'
title: 'Vendor',
subtitle: 'Kelola Vendor'
},
{
url: '/',
@@ -50,10 +50,10 @@ const shortcuts: ShortcutsType[] = [
subtitle: 'User Dashboard'
},
{
url: '/pages/account-settings',
url: '/apps/report',
icon: 'tabler-settings',
title: 'Settings',
subtitle: 'Account Settings'
title: 'Laporan',
subtitle: 'Lihat Laporan'
}
]
+10 -1
View File
@@ -29,6 +29,8 @@ import { getLocalizedUrl } from '@/utils/i18n'
// Style Imports
import navigationCustomStyles from '@core/styles/vertical/navigationCustomStyles'
import { useAuth } from '../../../contexts/authContext'
import SuperAdminVerticalMenu from './SuperAdminVerticalMenu'
type Props = {
dictionary: Awaited<ReturnType<typeof getDictionary>>
@@ -64,6 +66,8 @@ const Navigation = (props: Props) => {
const { mode: muiMode, systemMode: muiSystemMode } = useColorScheme()
const theme = useTheme()
const { currentUser } = useAuth()
// Refs
const shadowRef = useRef(null)
@@ -129,7 +133,12 @@ const Navigation = (props: Props) => {
)}
</NavHeader>
<StyledBoxForShadow ref={shadowRef} />
<VerticalMenu dictionary={dictionary} scrollMenu={scrollMenu} />
{currentUser?.role === 'superadmin' ? (
<SuperAdminVerticalMenu dictionary={dictionary} scrollMenu={scrollMenu} />
) : (
<VerticalMenu dictionary={dictionary} scrollMenu={scrollMenu} />
)}
</VerticalNav>
)
}
@@ -0,0 +1,91 @@
// Next Imports
import { useParams } from 'next/navigation'
// MUI Imports
import { useTheme } from '@mui/material/styles'
// Third-party Imports
import PerfectScrollbar from 'react-perfect-scrollbar'
// Type Imports
import type { getDictionary } from '@/utils/getDictionary'
import type { VerticalMenuContextProps } from '@menu/components/vertical-menu/Menu'
// Component Imports
import { Menu, MenuItem, MenuSection, SubMenu } from '@menu/vertical-menu'
// import { GenerateVerticalMenu } from '@components/GenerateMenu'
// Hook Imports
import useVerticalNav from '@menu/hooks/useVerticalNav'
// Styled Component Imports
import StyledVerticalNavExpandIcon from '@menu/styles/vertical/StyledVerticalNavExpandIcon'
// Style Imports
import menuItemStyles from '@core/styles/vertical/menuItemStyles'
import menuSectionStyles from '@core/styles/vertical/menuSectionStyles'
// Menu Data Imports
// import menuData from '@/data/navigation/verticalMenuData'
type RenderExpandIconProps = {
open?: boolean
transitionDuration?: VerticalMenuContextProps['transitionDuration']
}
type Props = {
dictionary: Awaited<ReturnType<typeof getDictionary>>
scrollMenu: (container: any, isPerfectScrollbar: boolean) => void
}
const RenderExpandIcon = ({ open, transitionDuration }: RenderExpandIconProps) => (
<StyledVerticalNavExpandIcon open={open} transitionDuration={transitionDuration}>
<i className='tabler-chevron-right' />
</StyledVerticalNavExpandIcon>
)
const SuperAdminVerticalMenu = ({ dictionary, scrollMenu }: Props) => {
// Hooks
const theme = useTheme()
const verticalNavOptions = useVerticalNav()
const params = useParams()
// Vars
const { isBreakpointReached, transitionDuration } = verticalNavOptions
const { lang: locale } = params
const ScrollWrapper = isBreakpointReached ? 'div' : PerfectScrollbar
return (
// eslint-disable-next-line lines-around-comment
/* Custom scrollbar instead of browser scroll, remove if you want browser scroll only */
<ScrollWrapper
{...(isBreakpointReached
? {
className: 'bs-full overflow-y-auto overflow-x-hidden',
onScroll: container => scrollMenu(container, false)
}
: {
options: { wheelPropagation: false, suppressScrollX: true },
onScrollY: container => scrollMenu(container, true)
})}
>
{/* Incase you also want to scroll NavHeader to scroll with Vertical Menu, remove NavHeader from above and paste it below this comment */}
{/* Vertical Menu */}
<Menu
popoutMenuOffset={{ mainAxis: 23 }}
menuItemStyles={menuItemStyles(verticalNavOptions, theme)}
renderExpandIcon={({ open }) => <RenderExpandIcon open={open} transitionDuration={transitionDuration} />}
renderExpandedMenuItemIcon={{ icon: <i className='tabler-circle text-xs' /> }}
menuSectionStyles={menuSectionStyles(verticalNavOptions, theme)}
>
<SubMenu label={dictionary['navigation'].organization} icon={<i className='tabler-smart-home' />}>
<MenuItem href={`/${locale}/sa/organizations/list`}>{dictionary['navigation'].list}</MenuItem>
</SubMenu>
</Menu>
</ScrollWrapper>
)
}
export default SuperAdminVerticalMenu
+116 -21
View File
@@ -91,41 +91,121 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
<MenuItem href={`/${locale}/dashboards/daily-report`}>{dictionary['navigation'].dailyReport}</MenuItem>
</SubMenu>
<MenuSection label={dictionary['navigation'].appsPages}>
<SubMenu label={dictionary['navigation'].eCommerce} icon={<i className='tabler-shopping-cart' />}>
<MenuItem href={`/${locale}/apps/ecommerce/dashboard`}>{dictionary['navigation'].dashboard}</MenuItem>
{/* <SubMenu label={dictionary['navigation'].sales} icon={<i className='tabler-receipt-2' />}>
<MenuItem href={`/${locale}/apps/sales/overview`}>{dictionary['navigation'].overview}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-bills`}>{dictionary['navigation'].invoices}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-deliveries`}>{dictionary['navigation'].deliveries}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-orders`}>{dictionary['navigation'].sales_orders}</MenuItem>
<MenuItem href={`/${locale}/apps/sales/sales-quotes`}>{dictionary['navigation'].quotes}</MenuItem>
</SubMenu> */}
<SubMenu label={dictionary['navigation'].purchase_text} icon={<i className='tabler-shopping-cart' />}>
<MenuItem href={`/${locale}/apps/purchase/overview`}>{dictionary['navigation'].overview}</MenuItem>
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-bills`}>
{dictionary['navigation'].purchase_bills}
</MenuItem>
<MenuItem href={`/${locale}/apps/purchase/purchase-deliveries`}>
{dictionary['navigation'].purchase_delivery}
</MenuItem> */}
<MenuItem href={`/${locale}/apps/purchase/purchase-orders`}>
{dictionary['navigation'].purchase_orders}
</MenuItem>
{/* <MenuItem href={`/${locale}/apps/purchase/purchase-quotes`}>
{dictionary['navigation'].purchase_quotes}
</MenuItem> */}
</SubMenu>
<MenuItem
href={`/${locale}/apps/expense`}
icon={<i className='tabler-cash' />}
exactMatch={false}
activeUrl='/apps/expense'
>
{dictionary['navigation'].expenses}
</MenuItem>
<MenuItem
href={`/${locale}/apps/cash-bank`}
icon={<i className='tabler-building-bank' />}
exactMatch={false}
activeUrl='/apps/cash-bank'
>
{dictionary['navigation'].cash_and_bank}
</MenuItem>
<MenuItem
href={`/${locale}/apps/account`}
icon={<i className='tabler-align-box-left-stretch' />}
exactMatch={false}
activeUrl='/apps/account'
>
{dictionary['navigation'].account}
</MenuItem>
<MenuItem
href={`/${locale}/apps/fixed-assets`}
icon={<i className='tabler-apps' />}
exactMatch={false}
activeUrl='/apps/fixed-assets'
>
{dictionary['navigation'].fixed_assets}
</MenuItem>
<MenuItem
href={`/${locale}/apps/report`}
icon={<i className='tabler-file-analytics' />}
exactMatch={false}
activeUrl='/apps/report'
>
{dictionary['navigation'].reports}
</MenuItem>
<SubMenu label={dictionary['navigation'].marketing} icon={<i className='tabler-shopping-cart' />}>
{/* <MenuItem href={`/${locale}/apps/marketing/loyalty`}>{dictionary['navigation'].loyalty}</MenuItem> */}
<MenuItem href={`/${locale}/apps/marketing/reward`}>{dictionary['navigation'].reward}</MenuItem>
{/* <SubMenu label={dictionary['navigation'].gamification}>
<MenuItem href={`/${locale}/apps/marketing/gamification/wheel-spin`}>
{dictionary['navigation'].wheel_spin}
</MenuItem>
</SubMenu> */}
<SubMenu label={dictionary['navigation'].games}>
<MenuItem href={`/${locale}/apps/marketing/games/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem href={`/${locale}/apps/marketing/games/game-prizes`}>
{dictionary['navigation'].game_prizes}
</MenuItem>
</SubMenu>
<MenuItem href={`/${locale}/apps/marketing/campaign`}>{dictionary['navigation'].campaign}</MenuItem>
{/* <MenuItem href={`/${locale}/apps/marketing/customer-analytics`}>
{dictionary['navigation'].customer_analytics}
</MenuItem> */}
{/* <MenuItem href={`/${locale}/apps/marketing/voucher`}>{dictionary['navigation'].voucher}</MenuItem> */}
<MenuItem href={`/${locale}/apps/marketing/tier`}>{dictionary['navigation'].tiers_text}</MenuItem>
</SubMenu>
<SubMenu label={dictionary['navigation'].inventory} icon={<i className='tabler-salad' />}>
<SubMenu label={dictionary['navigation'].products}>
<MenuItem href={`/${locale}/apps/ecommerce/products/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem className='hidden' href={`/${locale}/apps/ecommerce/products/${params.id}/detail`}>
<MenuItem href={`/${locale}/apps/inventory/products/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem className='hidden' href={`/${locale}/apps/inventory/products/${params.id}/detail`}>
{dictionary['navigation'].details}
</MenuItem>
<MenuItem className='hidden' href={`/${locale}/apps/ecommerce/products/${params.id}/edit`}>
<MenuItem className='hidden' href={`/${locale}/apps/inventory/products/${params.id}/edit`}>
{dictionary['navigation'].edit}
</MenuItem>
<MenuItem href={`/${locale}/apps/ecommerce/products/add`}>{dictionary['navigation'].add}</MenuItem>
<MenuItem href={`/${locale}/apps/ecommerce/products/category`}>
<MenuItem href={`/${locale}/apps/inventory/products/add`}>{dictionary['navigation'].add}</MenuItem>
<MenuItem href={`/${locale}/apps/inventory/products/category`}>
{dictionary['navigation'].category}
</MenuItem>
<MenuItem href={`/${locale}/apps/ecommerce/products/units`}>{dictionary['navigation'].units}</MenuItem>
<MenuItem href={`/${locale}/apps/ecommerce/products/ingredients`}>
<MenuItem href={`/${locale}/apps/inventory/products/units`}>{dictionary['navigation'].units}</MenuItem>
<MenuItem href={`/${locale}/apps/inventory/products/ingredients`}>
{dictionary['navigation'].ingredients}
</MenuItem>
</SubMenu>
<SubMenu label={dictionary['navigation'].orders}>
<MenuItem href={`/${locale}/apps/ecommerce/orders/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem className='hidden' href={`/${locale}/apps/ecommerce/orders/${params.id}/details`}>
<MenuItem href={`/${locale}/apps/inventory/orders/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem className='hidden' href={`/${locale}/apps/inventory/orders/${params.id}/details`}>
{dictionary['navigation'].details}
</MenuItem>
</SubMenu>
<SubMenu label={dictionary['navigation'].customers}>
<MenuItem href={`/${locale}/apps/ecommerce/customers/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem href={`/${locale}/apps/inventory/customers/list`}>{dictionary['navigation'].list}</MenuItem>
</SubMenu>
<SubMenu label={dictionary['navigation'].stock}>
<MenuItem href={`/${locale}/apps/ecommerce/inventory/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem href={`/${locale}/apps/ecommerce/inventory/adjustment`}>
{dictionary['navigation'].adjustment}
</MenuItem>
<MenuItem href={`/${locale}/apps/inventory/stock/list`}>{dictionary['navigation'].list}</MenuItem>
<MenuItem href={`/${locale}/apps/inventory/stock/restock`}>{dictionary['navigation'].restock}</MenuItem>
</SubMenu>
<MenuItem href={`/${locale}/apps/ecommerce/settings`}>{dictionary['navigation'].settings}</MenuItem>
{/* <MenuItem href={`/${locale}/apps/inventory/settings`}>{dictionary['navigation'].settings}</MenuItem> */}
</SubMenu>
<SubMenu label={dictionary['navigation'].organization} icon={<i className='tabler-sitemap' />}>
<SubMenu label={dictionary['navigation'].outlet}>
@@ -137,10 +217,25 @@ const VerticalMenu = ({ dictionary, scrollMenu }: Props) => {
<MenuItem href={`/${locale}/apps/finance/payment-methods/list`}>{dictionary['navigation'].list}</MenuItem>
</SubMenu>
</SubMenu>
<SubMenu label={dictionary['navigation'].user} icon={<i className='tabler-user' />}>
<MenuItem href={`/${locale}/apps/user/list`}>{dictionary['navigation'].list}</MenuItem>
{/* <MenuItem href={`/${locale}/apps/user/view`}>{dictionary['navigation'].view}</MenuItem> */}
</SubMenu>
<MenuItem
href={`/${locale}/apps/user/list`}
icon={<i className='tabler-user' />}
exactMatch={false}
activeUrl='/apps/user/list'
>
{dictionary['navigation'].user}
</MenuItem>
<MenuItem
href={`/${locale}/apps/vendor/list`}
icon={<i className='tabler-building' />}
exactMatch={false}
activeUrl='/apps/vendor/list'
>
{dictionary['navigation'].vendor}
</MenuItem>
<MenuItem href={`/${locale}/draw`} icon={<i className='tabler-building' />} target='_blank'>
Random Draw
</MenuItem>
</MenuSection>
</Menu>
</ScrollWrapper>
+102
View File
@@ -0,0 +1,102 @@
import React from 'react'
import { Box, Typography, Paper } from '@mui/material'
// Types
type ReportItemHeaderProps = {
title: string
date?: string
amount?: number
}
type ReportItemSubheaderProps = {
title: string
}
type ReportItemProps = {
accountCode: string
accountName: string
amount: number
onClick?: () => void
isSubtitle?: boolean
}
type ReportItemFooterProps = {
title: string
amount: number
children?: React.ReactNode
}
// Helper function to format currency
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('id-ID', {
minimumFractionDigits: 0,
maximumFractionDigits: 0
}).format(amount)
}
// ReportItemHeader Component
export const ReportItemHeader: React.FC<ReportItemHeaderProps> = ({ title, date, amount }) => {
return (
<Box className='bg-slate-200 px-6 py-4 flex justify-between items-center'>
<Typography variant='h6' className='text-primary font-semibold'>
{title}
</Typography>
<Typography variant='body1' className='text-primary font-medium'>
{amount ? formatCurrency(amount) : date}
</Typography>
</Box>
)
}
// ReportItemSubheader Component
export const ReportItemSubheader: React.FC<ReportItemSubheaderProps> = ({ title }) => {
return (
<Box className='px-6 py-3 bg-white border-b border-gray-300 hover:bg-gray-50 transition-colors'>
<Typography variant='subtitle1' className='font-semibold text-gray-900'>
{title}
</Typography>
</Box>
)
}
// ReportItem Component
export const ReportItem: React.FC<ReportItemProps> = ({
accountCode,
accountName,
amount,
onClick,
isSubtitle = true
}) => {
return (
<Box
onClick={onClick}
className={`px-6 py-3 flex justify-between items-center bg-white border-b border-gray-300 transition-all duration-200 ease-in-out ${
onClick ? 'cursor-pointer hover:bg-gray-50' : 'cursor-default'
}`}
>
<Typography variant='body1' className={`text-gray-900 font-normal ${isSubtitle ? 'ml-4' : ''}`}>
{accountCode} {accountName}
</Typography>
<Typography variant='body1' className='text-primary font-medium text-right'>
{formatCurrency(amount)}
</Typography>
</Box>
)
}
// ReportItemFooter Component
export const ReportItemFooter: React.FC<ReportItemFooterProps> = ({ title, amount, children }) => {
return (
<Box className='px-6 py-4 border-b border-gray-300 hover:bg-gray-50 transition-colors'>
<Box className='flex justify-between items-center'>
<Typography variant='subtitle1' className='font-bold text-gray-900'>
{title}
</Typography>
<Typography variant='subtitle1' className='text-primary font-bold text-right'>
{formatCurrency(amount)}
</Typography>
</Box>
{children && <Box className='mt-2'>{children}</Box>}
</Box>
)
}

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