Release Sytem ERP v3.0 (Multi-PT, SN Excel, RMA, RBAC, Laporan

Keuangan)
This commit is contained in:
Yoga Pratama committed 2026-11-27 13:45:46 +07:00
1 parent cd1a77ba75
commit 62cb3a4ce2
61 files changed
+13060 -4024

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
node_modules
.next
.git
.env
.env.*
prisma/*.db
prisma/*.db-journal
prisma/*.db-wal
prisma/*.db-shm
*.log
tsconfig.tsbuildinfo
+6 -2
View File
@@ -4,7 +4,11 @@ out/
build/
dist/
.env
.env.*
*.log
.DS_Store
prisma/dev.db
prisma/dev.db-journal
tsconfig.tsbuildinfo
prisma/*.db
prisma/*.db-journal
prisma/*.db-wal
prisma/*.db-shm
+22 -8
View File
@@ -1,18 +1,32 @@
FROM node:22-alpine
FROM node:22-alpine AS builder
WORKDIR /app
# Install openssl for Prisma
RUN apk add --no-cache openssl libc6-compat
COPY package.json ./
RUN npm install
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npx prisma generate
RUN npm run build
RUN chmod +x ./entrypoint.sh
FROM node:22-alpine AS runner
EXPOSE 3000
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3005
RUN apk add --no-cache openssl libc6-compat
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/next.config.ts ./next.config.ts
COPY --from=builder /app/entrypoint.sh ./entrypoint.sh
RUN chmod +x ./entrypoint.sh && mkdir -p /app/data
EXPOSE 3005
ENTRYPOINT ["./entrypoint.sh"]
Binary file not shown.
+13 -32
View File
@@ -1,43 +1,24 @@
services:
db:
image: postgres:16-alpine
container_name: erp_postgres
restart: always
environment:
POSTGRES_USER: erp
POSTGRES_PASSWORD: erppassword
POSTGRES_DB: erp_db
ports:
- "5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U erp -d erp_db"]
interval: 5s
timeout: 5s
retries: 5
app:
erp:
build:
context: .
dockerfile: Dockerfile
container_name: erp_app
restart: always
image: enterprisecore-erp:latest
container_name: enterprisecore_erp
restart: unless-stopped
ports:
- "3000:3000"
- "3005:3005"
environment:
DATABASE_URL: "postgresql://erp:erppassword@db:5432/erp_db?schema=public"
JWT_SECRET: "enterprisecore-secret-jwt-key-2026-production-ready"
NODE_ENV: "production"
PORT: "3005"
DATABASE_URL: "file:/app/data/live.db"
LIVE_DATABASE_URL: "file:/app/data/live.db"
JWT_SECRET: "${JWT_SECRET:-ganti-dengan-random-secret-minimal-32-karakter}"
NEXT_PUBLIC_APP_NAME: "EnterpriseCore ERP"
PORT: "3000"
depends_on:
db:
condition: service_healthy
TZ: "Asia/Jakarta"
volumes:
- ./:/app
- /app/node_modules
- /app/.next
- erp_data:/app/data
volumes:
pgdata:
erp_data:
driver: local
+5 -6
View File
@@ -1,12 +1,11 @@
#!/bin/sh
set -e
echo "==> Waiting for database to be ready..."
npx prisma generate
echo "==> Syncing SQLite schema..."
npx prisma db push --skip-generate
echo "==> Seeding database if not seeded..."
node prisma/seed.js || true
echo "==> Initializing default accounts & roles if database is empty..."
node prisma/seed.js
echo "==> Starting application..."
exec npm run dev
echo "==> Starting EnterpriseCore ERP on port ${PORT:-3005}..."
exec npx next start -H 0.0.0.0 -p "${PORT:-3005}"
+313 -3
View File
@@ -9,18 +9,23 @@
"version": "1.0.0",
"dependencies": {
"@prisma/client": "^6.2.1",
"@types/pdfkit": "^0.17.7",
"bcryptjs": "^2.4.3",
"clsx": "^2.1.1",
"jose": "^5.9.6",
"lucide-react": "^0.473.0",
"next": "^15.1.5",
"nodemailer": "^10.6.1",
"pdfkit": "^0.20.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^2.6.0"
"tailwind-merge": "^2.6.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^22.10.7",
"@types/nodemailer": "^8.0.2",
"@types/react": "^19.0.7",
"@types/react-dom": "^19.0.3",
"autoprefixer": "^10.6.2",
@@ -727,6 +732,30 @@
"node": ">= 10"
}
},
"node_modules/@noble/ciphers": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz",
"integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
"integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==",
"license": "MIT",
"engines": {
"node": "^14.21.3 || >=16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -877,12 +906,30 @@
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/nodemailer": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz",
"integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/pdfkit": {
"version": "0.17.7",
"resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.7.tgz",
"integrity": "sha512-VMOZDWw7HtNtLbjIuHIhVArm9PlV0gxpz32jAl1IuXWlIgbr1lKFoTsrtvEzY8a9BIpQJEE5DwNPKD50otTs6g==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
@@ -903,6 +950,15 @@
"@types/react": "^19.3.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/any-promise": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
@@ -968,6 +1024,26 @@
"postcss": "^8.1.0"
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.34",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz",
@@ -1013,6 +1089,15 @@
"node": ">=8"
}
},
"node_modules/brotli": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz",
"integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.1.2"
}
},
"node_modules/browserslist": {
"version": "4.29.5",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz",
@@ -1106,6 +1191,19 @@
],
"license": "CC-BY-4.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/chokidar": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
@@ -1138,6 +1236,15 @@
"integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
"license": "MIT"
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/clsx": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -1147,6 +1254,15 @@
"node": ">=6"
}
},
"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/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@@ -1174,6 +1290,18 @@
"node": "^14.18.0 || >=16.10.0"
}
},
"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/cssesc": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz",
@@ -1228,6 +1356,12 @@
"node": ">=8"
}
},
"node_modules/dfa": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz",
"integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==",
"license": "MIT"
},
"node_modules/didyoumean": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz",
@@ -1333,6 +1467,12 @@
"node": ">=8.0.0"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
"node_modules/fast-glob": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
@@ -1373,6 +1513,12 @@
"reusify": "^1.0.4"
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -1386,6 +1532,32 @@
"node": ">=8"
}
},
"node_modules/fontkit": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz",
"integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==",
"license": "MIT",
"dependencies": {
"@swc/helpers": "^0.5.12",
"brotli": "^1.3.2",
"clone": "^2.1.2",
"dfa": "^1.2.0",
"fast-deep-equal": "^3.1.3",
"restructure": "^3.0.0",
"tiny-inflate": "^1.0.3",
"unicode-properties": "^1.4.0",
"unicode-trie": "^2.0.0"
}
},
"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": "5.3.4",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
@@ -1563,6 +1735,25 @@
"url": "https://github.com/sponsors/antonk52"
}
},
"node_modules/linebreak": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz",
"integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==",
"license": "MIT",
"dependencies": {
"base64-js": "0.0.8",
"unicode-trie": "^2.0.0"
}
},
"node_modules/linebreak/node_modules/base64-js": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz",
"integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/lines-and-columns": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
@@ -1730,6 +1921,15 @@
"node": ">=18"
}
},
"node_modules/nodemailer": {
"version": "10.6.1",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz",
"integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==",
"license": "MIT-0",
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/normalize-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
@@ -1792,6 +1992,12 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/pako": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz",
"integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==",
"license": "MIT"
},
"node_modules/path-parse": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
@@ -1806,6 +2012,20 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/pdfkit": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz",
"integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==",
"license": "MIT",
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@noble/hashes": "^1.8.0",
"fflate": "^0.8.3",
"fontkit": "^2.0.4",
"linebreak": "^1.1.0",
"png-js": "^2.0.0"
}
},
"node_modules/perfect-debounce": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
@@ -1861,6 +2081,14 @@
"devOptional": true,
"license": "MIT"
},
"node_modules/png-js": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz",
"integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==",
"dependencies": {
"fflate": "^0.8.2"
}
},
"node_modules/postcss": {
"version": "8.5.32",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
@@ -2163,6 +2391,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/restructure": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz",
"integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==",
"license": "MIT"
},
"node_modules/reusify": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
@@ -2276,6 +2510,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/styled-jsx": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz",
@@ -2467,6 +2713,12 @@
"node": ">=0.8"
}
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinyexec": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
@@ -2569,9 +2821,28 @@
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/unicode-properties": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz",
"integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0",
"unicode-trie": "^2.0.0"
}
},
"node_modules/unicode-trie": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz",
"integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==",
"license": "MIT",
"dependencies": {
"pako": "^0.2.5",
"tiny-inflate": "^1.0.0"
}
},
"node_modules/update-browserslist-db": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz",
@@ -2609,6 +2880,45 @@
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"dev": true,
"license": "MIT"
},
"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/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"
}
}
}
}
+6 -1
View File
@@ -16,18 +16,23 @@
},
"dependencies": {
"@prisma/client": "^6.2.1",
"@types/pdfkit": "^0.17.7",
"bcryptjs": "^2.4.3",
"clsx": "^2.1.1",
"jose": "^5.9.6",
"lucide-react": "^0.473.0",
"next": "^15.1.5",
"nodemailer": "^10.6.1",
"pdfkit": "^0.20.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^2.6.0"
"tailwind-merge": "^2.6.0",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^22.10.7",
"@types/nodemailer": "^8.0.2",
"@types/react": "^19.0.7",
"@types/react-dom": "^19.0.3",
"autoprefixer": "^10.6.2",
BIN
View File
Binary file not shown.
+63 -4
View File
@@ -1,6 +1,6 @@
datasource db {
provider = "sqlite"
url = "file:./dev.db"
url = env("DATABASE_URL")
}
generator client {
@@ -13,6 +13,7 @@ model User {
name String
password String
role String @default("SALES")
isActive Boolean @default(true) // Status aktif akses login akun
telegramChatId String?
notifyEmail Boolean @default(true)
notifyTelegram Boolean @default(false)
@@ -22,6 +23,7 @@ model User {
notifStockOut Boolean @default(true)
notifMoneyIn Boolean @default(true)
notifMoneyOut Boolean @default(true)
notifRma Boolean @default(true) // Notifikasi RMA, Service & Garansi
// Multi-Factor Authentication (MFA / 2FA)
mfaEnabled Boolean @default(false)
@@ -107,6 +109,7 @@ model Product {
requisitionItems PurchaseRequisitionItem[]
batches PurchaseBatch[]
customerPrices CustomerProductPrice[]
deviceRecords DeviceRecord[]
}
model StockItem {
@@ -131,6 +134,7 @@ model StockMovement {
quantity Int
referenceType String? // SALES_ORDER, PURCHASE_ORDER, MANUAL_ADJUSTMENT
referenceId String?
serialNumbers String? // Daftar Serial Number (SN) device yang masuk/keluar gudang
notes String?
companyName String @default("PT EnterpriseCore Utama")
createdAt DateTime @default(now())
@@ -152,6 +156,7 @@ model Customer {
salesOrders SalesOrder[]
purchaseRequisitions PurchaseRequisition[]
specialPrices CustomerProductPrice[]
deviceRecords DeviceRecord[]
}
model SalesOrder {
@@ -167,6 +172,13 @@ model SalesOrder {
status String @default("DRAFT") // DRAFT, CONFIRMED, SHIPPED, COMPLETED, CANCELLED
paymentStatus String @default("UNPAID") // UNPAID, PARTIAL, PAID
paidAmount Float @default(0) // Jumlah nominal yang telah dibayarkan oleh pelanggan
shippingCost Float @default(0) // Ongkos kirim manual yang dibebankan ke customer (terutama timbangan berat)
courierName String? // Nama ekspedisi / kurir pengiriman (misal: Baraka, JNE Trucking, Deliveree)
trackingNumber String? // Nomor resi pengiriman yang diinput pihak gudang
shippingNotes String? // Keterangan tambahan ekspedisi pengiriman / kargo
taxRate Float @default(0) // Tarif PPN (%) misal 11%
taxAmount Float @default(0) // Nominal PPN (Rp)
includeTax Boolean @default(false) // Toggle penerapan PPN ke customer
totalAmount Float @default(0)
totalHpp Float @default(0)
notes String?
@@ -185,13 +197,22 @@ model SalesOrderItem {
costPrice Float @default(0)
unitPrice Float
subtotal Float
serialNumbers String? // Daftar Serial Number (SN) unit yang dikirim ke pelanggan
batchAllocationNotes String? // Rincian FIFO: "50 pcs (PO-2026/001) + 10 pcs (PO-2026/002)"
warrantyExpiry DateTime? // Tanggal kedaluwarsa garansi
serviceStatus String? // NORMAL, NEED_SERVICE, IN_SERVICE, SERVICED_RETURNED, REPLACED
serviceType String? // FREE_WARRANTY, PAID_SERVICE, WARRANTY_REPLACEMENT
serviceNotes String? // Catatan kerusakan / kendala teknis
damagedSerialNumbers String? // Serial Number (SN) unit yang rusak / bermasalah
serviceFee Float @default(0) // Uang jasa perbaikan / biaya service yang dibebankan
returnShippingCost Float @default(0) // Biaya kirim balik service / tukar unit (ditanggung user/customer)
returnCourierName String? // Nama kurir pengiriman balik ke customer
returnTrackingNumber String? // No. resi pengiriman balik ke customer
servicePaymentStatus String? // FREE, UNPAID, PAID
replacedQty Int @default(0) // Jumlah unit yang telah diganti baru
replacedAt DateTime? // Waktu unit diganti baru
replacementNotes String? // Catatan pergantian unit garansi
replacementSerialNumbers String? // Serial Number (SN) unit baru pengganti garansi
salesOrder SalesOrder @relation(fields: [salesOrderId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
@@ -261,10 +282,13 @@ model PurchaseOrder {
subtotalProducts Float @default(0) // Total harga beli barang
shippingCost Float @default(0) // Biaya Ongkos Kirim / Freight / Ekspedisi
exportCost Float @default(0) // Biaya Ekspor / Bea Cukai / Penanganan Dokumen (atau Biaya All-In Ongkir + Pajak Masuk)
taxRate Float @default(0) // Tarif PPN Masukan (%) misal 11%
taxAmount Float @default(0) // Nominal PPN Masukan (Rp)
includeTax Boolean @default(false) // Toggle penerapan PPN ke vendor
shippingCostUsd Float? // Ongkir dalam USD jika currency USD
exportCostUsd Float? // Biaya Ekspor dalam USD jika currency USD
totalAmountUsd Float?
totalAmount Float @default(0) // Grand Total (Barang + Ongkir + Ekspor)
totalAmount Float @default(0) // Grand Total (Barang + Ongkir + Ekspor + PPN)
notes String?
// Approval dari Finance (Approve / Hold / Reject)
@@ -272,8 +296,9 @@ model PurchaseOrder {
financeApprovedBy String?
financeNotes String?
// Status & Konfirmasi Pembayaran PO oleh Finance (PAID / UNPAID)
paymentStatus String @default("UNPAID") // UNPAID, PAID
// Status & Konfirmasi Pembayaran PO oleh Finance (UNPAID / PARTIAL (DP) / PAID)
paymentStatus String @default("UNPAID") // UNPAID, PARTIAL (DP / Cicilan), PAID
paidAmount Float @default(0) // Nominal yang telah dibayarkan oleh Finance ke Vendor (mendukung DP / Termin)
paidAt DateTime?
paidBy String?
paymentNotes String?
@@ -300,6 +325,7 @@ model PurchaseOrderItem {
unitCostUsd Float?
unitCost Float
subtotal Float
serialNumbers String? // Daftar Serial Number (SN) barang yang dipesan / diterima dari vendor
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
@@ -387,6 +413,7 @@ model PurchaseBatch {
initialQty Int
remainingQty Int
unitCost Float // HPP Landed Cost per unit (harga beli + proporsi ongkir & biaya ekspor)
serialNumbers String? // Daftar Serial Number (SN) barang dalam batch ini
receivedAt DateTime @default(now())
createdAt DateTime @default(now())
@@ -427,3 +454,35 @@ model CustomerProductPrice {
@@unique([customerId, productId])
}
// -----------------------------------------------------------------------------
// PENCATATAN RIWAYAT DEVICE: PERNAH DISERVIS, RUSAK TOTAL (AFKIR), & KANIBALAN
// -----------------------------------------------------------------------------
model DeviceRecord {
id String @id @default(uuid())
recordNumber String @unique
serialNumber String
productId String
customerId String?
salesOrderId String?
salesOrderNumber String?
companyName String @default("PT EnterpriseCore Utama")
condition String @default("IN_SERVICE") // IN_SERVICE, SERVICED_OK, DAMAGED_UNUSABLE, CANNIBALIZED, REPLACED_WARRANTY
serviceOrigin String @default("WAREHOUSE_DEFECT") // WARRANTY_FREE, WARRANTY_REPLACE, PAID_SERVICE, WAREHOUSE_DEFECT
warrantyStatus String? // IN_WARRANTY, OUT_OF_WARRANTY, INTERNAL
serviceFee Float @default(0)
returnShippingCost Float @default(0) // Biaya kirim balik ke customer (ditanggung user)
returnCourierName String? // Nama kurir pengiriman balik
returnTrackingNumber String? // No. resi pengiriman balik
servicePaymentStatus String @default("FREE") // FREE, UNPAID, PAID
damageDescription String
actionTaken String? // Tindakan perbaikan teknisi / alasan afkir
salvagedParts String? // Daftar komponen/sparepart untuk kanibalan (masih bagus / sudah diambil)
stockAdjusted Boolean @default(false) // true jika sudah memotong stok gudang saat dicatat rusak/kanibalan
recordedBy String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
customer Customer? @relation(fields: [customerId], references: [id], onDelete: SetNull)
}
-100
View File
@@ -1,100 +0,0 @@
const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcryptjs');
const prisma = new PrismaClient({
datasources: {
db: {
url: process.env.LIVE_DATABASE_URL || 'file:./live.db',
},
},
});
async function main() {
console.log('🚀 Initializing PRODUCTION (LIVE) ERP Database...');
// Bersihkan seluruh data simulasi/dummy terlebih dahulu
await prisma.journalLine.deleteMany({});
await prisma.journalEntry.deleteMany({});
await prisma.salesOrderItem.deleteMany({});
await prisma.salesOrder.deleteMany({});
await prisma.purchaseOrderItem.deleteMany({});
await prisma.purchaseOrder.deleteMany({});
await prisma.stockMovement.deleteMany({});
await prisma.stockItem.deleteMany({});
await prisma.product.deleteMany({});
await prisma.category.deleteMany({});
await prisma.warehouse.deleteMany({});
await prisma.customer.deleteMany({});
await prisma.supplier.deleteMany({});
await prisma.account.deleteMany({});
await prisma.notificationLog.deleteMany({});
await prisma.auditLog.deleteMany({});
await prisma.user.deleteMany({});
const passwordHash = await bcrypt.hash('admin123', 10);
// 1. Production Super Admin
const admin = await prisma.user.create({
data: {
name: 'Super Admin',
email: 'admin@erp.local',
password: passwordHash,
role: 'ADMIN',
notifyEmail: true,
notifyTelegram: true,
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
},
});
// 2. Master Kategori Dasar
await prisma.category.create({
data: {
name: 'Umum / Reguler',
description: 'Kategori produk operasional utama',
},
});
// Master Customer, Supplier, & Gudang dibiarkan kosong agar diinput mandiri oleh pengguna.
// 5. Chart of Accounts (COA) Standar dengan Saldo Awal Rp 0 (Clean Production)
const accountsData = [
{ code: '1001', name: 'Kas Kantor Operasional', type: 'ASSET', balance: 0 },
{ code: '1002', name: 'Bank Operasional Utama', type: 'ASSET', balance: 0 },
{ code: '1101', name: 'Piutang Dagang (AR)', type: 'ASSET', balance: 0 },
{ code: '1201', name: 'Persediaan Barang Dagang', type: 'ASSET', balance: 0 },
{ code: '2001', name: 'Hutang Dagang (AP)', type: 'LIABILITY', balance: 0 },
{ code: '3001', name: 'Modal Disetor', type: 'EQUITY', balance: 0 },
{ code: '4001', name: 'Pendapatan Penjualan Barang', type: 'REVENUE', balance: 0 },
{ code: '5001', name: 'Beban Pokok Penjualan (HPP)', type: 'EXPENSE', balance: 0 },
{ code: '6001', name: 'Beban Gaji & Operasional', type: 'EXPENSE', balance: 0 },
];
for (const acc of accountsData) {
await prisma.account.create({ data: acc });
}
// 6. Audit Log Inisialisasi Production
await prisma.auditLog.create({
data: {
userId: admin.id,
userName: admin.name,
action: 'PRODUCTION_INIT',
module: 'AUTH',
description: 'Database Production (LIVE) siap digunakan untuk operasional nyata (Tanpa data dummy)',
},
});
console.log('✅ Production (LIVE) database initialized cleanly!');
}
main()
.catch((e) => {
console.error('Error initializing live db:', e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+206 -323
View File
@@ -1,346 +1,229 @@
const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcryptjs');
const { PrismaClient } = require("@prisma/client");
const bcrypt = require("bcryptjs");
const path = require("path");
const prisma = new PrismaClient();
const dbPath = path.resolve(__dirname, "live.db");
const dbUrl = process.env.LIVE_DATABASE_URL || process.env.DATABASE_URL || `file:${dbPath}`;
const prisma = new PrismaClient({
datasources: { db: { url: dbUrl } },
});
const DEFAULT_COMPANY = "PT EnterpriseCore Utama";
const DEFAULT_ACCOUNTS = [
{ code: "1001", name: "Kas Kantor Operasional", type: "ASSET" },
{ code: "1002", name: "Bank Operasional Utama", type: "ASSET" },
{ code: "1101", name: "Piutang Dagang (AR)", type: "ASSET" },
{ code: "1201", name: "Persediaan Barang Dagang", type: "ASSET" },
{ code: "1301", name: "PPN Masukan (Pajak Pembelian)", type: "ASSET" },
{ code: "2001", name: "Hutang Dagang (AP)", type: "LIABILITY" },
{ code: "2101", name: "PPN Keluaran (Hutang Pajak Penjualan)", type: "LIABILITY" },
{ code: "3001", name: "Modal Disetor", type: "EQUITY" },
{ code: "4001", name: "Pendapatan Penjualan Barang", type: "REVENUE" },
{ code: "5001", name: "Beban Pokok Penjualan (HPP)", type: "EXPENSE" },
{ code: "6001", name: "Beban Gaji & Operasional", type: "EXPENSE" },
];
const DUMMY_USERS = [
{
name: "Super Admin",
email: "admin@erp.local",
password: "Admin123!",
role: "ADMIN",
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: true,
},
{
name: "Manager Operasional",
email: "manager@erp.local",
password: "Manager123!",
role: "MANAGER",
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: true,
},
{
name: "Staf Keuangan",
email: "finance@erp.local",
password: "Finance123!",
role: "ACCOUNTANT",
notifStockIn: false,
notifStockOut: false,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: false,
},
{
name: "Staf Sales",
email: "sales@erp.local",
password: "Sales123!",
role: "SALES",
notifStockIn: false,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: false,
notifRma: true,
},
{
name: "Staf Purchasing",
email: "purchasing@erp.local",
password: "Purchasing123!",
role: "PURCHASING",
notifStockIn: true,
notifStockOut: false,
notifMoneyIn: false,
notifMoneyOut: true,
notifRma: false,
},
{
name: "Staf Gudang & Teknisi",
email: "gudang@erp.local",
password: "Gudang123!",
role: "INVENTORY",
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: false,
notifMoneyOut: false,
notifRma: true,
},
];
async function main() {
console.log('Seeding initial ERP data...');
const isReset = process.argv.includes("--reset");
const existingUsers = await prisma.user.count();
const passwordHash = await bcrypt.hash('admin123', 10);
const staffHash = await bcrypt.hash('staff123', 10);
// 1. Users & RBAC
const admin = await prisma.user.upsert({
where: { email: 'admin@erp.local' },
update: {},
create: {
name: 'Super Admin',
email: 'admin@erp.local',
password: passwordHash,
role: 'ADMIN',
},
});
await prisma.user.upsert({
where: { email: 'inventory@erp.local' },
update: {},
create: {
name: 'Rudi Gudang',
email: 'inventory@erp.local',
password: staffHash,
role: 'INVENTORY',
},
});
await prisma.user.upsert({
where: { email: 'sales@erp.local' },
update: {},
create: {
name: 'Maya Sales Rep',
email: 'sales@erp.local',
password: staffHash,
role: 'SALES',
},
});
await prisma.user.upsert({
where: { email: 'purchasing@erp.local' },
update: {},
create: {
name: 'Doni Pengadaan',
email: 'purchasing@erp.local',
password: staffHash,
role: 'PURCHASING',
},
});
await prisma.user.upsert({
where: { email: 'accountant@erp.local' },
update: {},
create: {
name: 'Linda Akuntan',
email: 'accountant@erp.local',
password: staffHash,
role: 'ACCOUNTANT',
},
});
// 2. Warehouses
const whJkt = await prisma.warehouse.upsert({
where: { code: 'WH-JKT' },
update: {},
create: {
code: 'WH-JKT',
name: 'Gudang Pusat Jakarta',
address: 'Kawasan Industri Pulo Gadung, Jakarta Timur',
},
});
const whSby = await prisma.warehouse.upsert({
where: { code: 'WH-SBY' },
update: {},
create: {
code: 'WH-SBY',
name: 'Gudang Cabang Surabaya',
address: 'Kawasan Industri Rungkut, Surabaya',
},
});
// 3. Categories
const catNetwork = await prisma.category.upsert({
where: { name: 'Jaringan & Server' },
update: {},
create: {
name: 'Jaringan & Server',
description: 'Perangkat jaringan enterprise, router, switch, server',
},
});
const catPower = await prisma.category.upsert({
where: { name: 'Power & UPS' },
update: {},
create: {
name: 'Power & UPS',
description: 'Sistem backup daya listrik dan baterai industri',
},
});
const catKabel = await prisma.category.upsert({
where: { name: 'Kabel & Aksesoris' },
update: {},
create: {
name: 'Kabel & Aksesoris',
description: 'Kabel UTP, fiber optik, dan konektor patchcord',
},
});
// 4. Products
const productsData = [
{
sku: 'PRD-SRV-01',
name: 'Server Rackmount 2U Dell PowerEdge',
description: 'Dual Intel Xeon Silver, 64GB DDR4 ECC, 2x 960GB Enterprise SSD',
unit: 'UNIT',
purchasePrice: 28500000,
sellingPrice: 36000000,
minStock: 3,
categoryId: catNetwork.id,
stockJkt: 8,
stockSby: 2,
},
{
sku: 'PRD-SWT-02',
name: 'Switch Gigabit Managed 48-Port Cisco Catalyst',
description: '48 port PoE+ 370W, 4x 10G SFP+ Uplinks, Layer 3 Lite',
unit: 'UNIT',
purchasePrice: 11000000,
sellingPrice: 14500000,
minStock: 5,
categoryId: catNetwork.id,
stockJkt: 18,
stockSby: 7,
},
{
sku: 'PRD-RTR-03',
name: 'Enterprise SD-WAN Gateway Router',
description: 'Multi-WAN Gigabit router with hardware IPSec acceleration',
unit: 'UNIT',
purchasePrice: 6500000,
sellingPrice: 8900000,
minStock: 4,
categoryId: catNetwork.id,
stockJkt: 12,
stockSby: 4,
},
{
sku: 'PRD-UPS-04',
name: 'UPS Online Double Conversion 3000VA APC',
description: 'Tower/Rackmount 2U, Smart-UPS RT, LCD interface',
unit: 'UNIT',
purchasePrice: 9800000,
sellingPrice: 13200000,
minStock: 5,
categoryId: catPower.id,
stockJkt: 2, // Low stock on purpose for testing alerts
stockSby: 1,
},
{
sku: 'PRD-CAB-05',
name: 'Kabel UTP Cat6 High Grade 305 Meter',
description: 'Pure copper 24AWG, CMR rated blue jacket roll',
unit: 'ROLL',
purchasePrice: 1650000,
sellingPrice: 2250000,
minStock: 10,
categoryId: catKabel.id,
stockJkt: 35,
stockSby: 15,
},
];
for (const item of productsData) {
const p = await prisma.product.upsert({
where: { sku: item.sku },
update: {},
create: {
sku: item.sku,
name: item.name,
description: item.description,
unit: item.unit,
purchasePrice: item.purchasePrice,
sellingPrice: item.sellingPrice,
minStock: item.minStock,
categoryId: item.categoryId,
},
});
await prisma.stockItem.upsert({
where: {
productId_warehouseId: { productId: p.id, warehouseId: whJkt.id },
},
update: { quantity: item.stockJkt },
create: {
productId: p.id,
warehouseId: whJkt.id,
quantity: item.stockJkt,
},
});
await prisma.stockItem.upsert({
where: {
productId_warehouseId: { productId: p.id, warehouseId: whSby.id },
},
update: { quantity: item.stockSby },
create: {
productId: p.id,
warehouseId: whSby.id,
quantity: item.stockSby,
},
});
if (!isReset && existingUsers > 0) {
console.log(`Database sudah berisi ${existingUsers} pengguna. Skip seed (gunakan --reset untuk mengosongkan total).`);
return;
}
// 5. Customers
const cust1 = await prisma.customer.upsert({
where: { code: 'CUST-001' },
update: {},
create: {
code: 'CUST-001',
name: 'Budi Santoso',
company: 'PT Data Prima Mandiri',
email: 'budi@dataprimamandiri.co.id',
phone: '081298765432',
address: 'Sudirman Central Business District Lt. 12, Jakarta Selatan',
},
});
const cust2 = await prisma.customer.upsert({
where: { code: 'CUST-002' },
update: {},
create: {
code: 'CUST-002',
name: 'Ahmad Fauzi',
company: 'PT Solusi Informatika Nusantara',
email: 'ahmad@solusinusantara.com',
phone: '081377889900',
address: 'Ruko Golden Boulevard Blok A No. 5, BSD Tangerang',
},
});
// 6. Suppliers
const sup1 = await prisma.supplier.upsert({
where: { code: 'SUP-001' },
update: {},
create: {
code: 'SUP-001',
name: 'PT Distribusi Teknologi Global',
contactPerson: 'Hendra Setiawan',
email: 'sales@distribusiglobal.co.id',
phone: '021-5890123',
address: 'Kawasan Niaga Puri Kencana, Jakarta Barat',
},
});
const sup2 = await prisma.supplier.upsert({
where: { code: 'SUP-002' },
update: {},
create: {
code: 'SUP-002',
name: 'CV Sentra Komputindo',
contactPerson: 'Sari Wulandari',
email: 'order@sentrakomputindo.com',
phone: '031-8976543',
address: 'Jl. Ngagel Tama No. 88, Surabaya',
},
});
// 7. Chart of Accounts (COA)
const accountsData = [
{ code: '1001', name: 'Kas Kantor Operasional', type: 'ASSET', balance: 35000000 },
{ code: '1002', name: 'Bank BCA Utama', type: 'ASSET', balance: 245000000 },
{ code: '1101', name: 'Piutang Dagang (AR)', type: 'ASSET', balance: 54000000 },
{ code: '1201', name: 'Persediaan Barang Dagang', type: 'ASSET', balance: 780000000 },
{ code: '2001', name: 'Hutang Dagang (AP)', type: 'LIABILITY', balance: 95000000 },
{ code: '3001', name: 'Modal Disetor', type: 'EQUITY', balance: 800000000 },
{ code: '4001', name: 'Pendapatan Penjualan Barang', type: 'REVENUE', balance: 320000000 },
{ code: '5001', name: 'Beban Pokok Penjualan (HPP)', type: 'EXPENSE', balance: 185000000 },
{ code: '6001', name: 'Beban Gaji & Operasional', type: 'EXPENSE', balance: 45000000 },
];
for (const acc of accountsData) {
await prisma.account.upsert({
where: { code: acc.code },
update: { balance: acc.balance },
create: acc,
});
if (isReset) {
console.log("Mengosongkan seluruh data transaksi & master...");
await prisma.deviceRecord.deleteMany();
await prisma.salesItemBatchAllocation.deleteMany();
await prisma.salesOrderItem.deleteMany();
await prisma.salesOrder.deleteMany();
await prisma.purchaseBatch.deleteMany();
await prisma.purchaseOrderItem.deleteMany();
await prisma.purchaseOrder.deleteMany();
await prisma.purchaseRequisitionItem.deleteMany();
await prisma.purchaseRequisition.deleteMany();
await prisma.stockMovement.deleteMany();
await prisma.stockItem.deleteMany();
await prisma.customerProductPrice.deleteMany();
await prisma.product.deleteMany();
await prisma.category.deleteMany();
await prisma.customer.deleteMany();
await prisma.supplier.deleteMany();
await prisma.warehouse.deleteMany();
await prisma.journalLine.deleteMany();
await prisma.journalEntry.deleteMany();
await prisma.payrollRecord.deleteMany();
await prisma.payrollEmployee.deleteMany();
await prisma.account.deleteMany();
await prisma.notificationLog.deleteMany();
await prisma.auditLog.deleteMany();
await prisma.systemSetting.deleteMany();
await prisma.user.deleteMany();
}
// 8. Sample Sales Order
const prd1 = await prisma.product.findUnique({ where: { sku: 'PRD-SWT-02' } });
if (prd1) {
const existingOrder = await prisma.salesOrder.findFirst({
where: { orderNumber: 'SO-2026-001' },
// 1. Default Warehouse (Gudang Utama)
await prisma.warehouse.upsert({
where: { code: "WH-01" },
update: {},
create: {
code: "WH-01",
name: "Gudang Utama",
address: "Kantor Pusat Operasional",
companyName: DEFAULT_COMPANY,
},
});
// 2. Clean Zero-Balance Standard COA for Default Company
for (const acc of DEFAULT_ACCOUNTS) {
const exists = await prisma.account.findFirst({
where: { code: acc.code, companyName: DEFAULT_COMPANY },
});
if (!existingOrder) {
await prisma.salesOrder.create({
if (!exists) {
await prisma.account.create({
data: {
orderNumber: 'SO-2026-001',
customerId: cust1.id,
status: 'CONFIRMED',
paymentStatus: 'PAID',
totalAmount: 29000000,
notes: 'Pengiriman via ekspedisi khusus express',
items: {
create: [
{
productId: prd1.id,
quantity: 2,
unitPrice: 14500000,
subtotal: 29000000,
},
],
},
code: acc.code,
name: acc.name,
type: acc.type,
companyName: DEFAULT_COMPANY,
balance: 0,
},
});
}
}
// 9. Initial Audit Log
await prisma.auditLog.create({
data: {
userId: admin.id,
userName: admin.name,
action: 'SYSTEM_INIT',
module: 'AUTH',
description: 'Sistem ERP berhasil diinisialisasi beserta data master awal',
},
});
// 3. Clean Default System Settings
const defaultSettings = [
{ key: "PAYROLL_COMPANIES", value: JSON.stringify([DEFAULT_COMPANY]), category: "FINANCE" },
{ key: "EMAIL_ENABLED", value: "false", category: "EMAIL" },
{ key: "TELEGRAM_ENABLED", value: "false", category: "TELEGRAM" },
{ key: "NOTIF_STOCK_IN_ENABLED", value: "true", category: "NOTIFICATION" },
{ key: "NOTIF_STOCK_OUT_ENABLED", value: "true", category: "NOTIFICATION" },
{ key: "NOTIF_MONEY_IN_ENABLED", value: "true", category: "NOTIFICATION" },
{ key: "NOTIF_MONEY_OUT_ENABLED", value: "true", category: "NOTIFICATION" },
{ key: "NOTIF_RMA_ENABLED", value: "true", category: "NOTIFICATION" },
];
for (const s of defaultSettings) {
await prisma.systemSetting.upsert({
where: { key: s.key },
update: { value: s.value },
create: s,
});
}
console.log('✅ Seeding completed successfully!');
// 4. Create 1 Dummy User for Each of the 6 RBAC Roles
for (const u of DUMMY_USERS) {
const hashedPassword = await bcrypt.hash(u.password, 10);
await prisma.user.upsert({
where: { email: u.email },
update: {
name: u.name,
password: hashedPassword,
role: u.role,
isActive: true,
notifyEmail: true,
notifyTelegram: false,
notifStockIn: u.notifStockIn,
notifStockOut: u.notifStockOut,
notifMoneyIn: u.notifMoneyIn,
notifMoneyOut: u.notifMoneyOut,
notifRma: u.notifRma,
},
create: {
name: u.name,
email: u.email,
password: hashedPassword,
role: u.role,
isActive: true,
notifyEmail: true,
notifyTelegram: false,
notifStockIn: u.notifStockIn,
notifStockOut: u.notifStockOut,
notifMoneyIn: u.notifMoneyIn,
notifMoneyOut: u.notifMoneyOut,
notifRma: u.notifRma,
mfaEnabled: false,
},
});
}
console.log("✓ Database bersih siap pakai dengan 6 akun dummy untuk semua role RBAC!");
}
main()
.catch((e) => {
console.error('Error during seeding:', e);
console.error("Seed error:", e);
process.exit(1);
})
.finally(async () => {
+411 -257
View File
@@ -1,330 +1,484 @@
const fs = require('fs');
const path = require('path');
const PDFDocument = require('pdfkit');
const fs = require("fs");
const path = require("path");
const PDFDocument = require("pdfkit");
function generateERPGuidePDF() {
const outputPath = path.join(__dirname, '..', 'public', 'Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf');
const rootOutputPath = path.join(__dirname, '..', 'Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf');
const publicDir = path.join(__dirname, "..", "public");
const outputPath = path.join(publicDir, "Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf");
const rootOutputPath = path.join(__dirname, "..", "Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf");
// Pastikan folder public ada
if (!fs.existsSync(path.join(__dirname, '..', 'public'))) {
fs.mkdirSync(path.join(__dirname, '..', 'public'), { recursive: true });
if (!fs.existsSync(publicDir)) {
fs.mkdirSync(publicDir, { recursive: true });
}
const MARGIN_X = 48;
const MARGIN_TOP = 48;
const FOOTER_ZONE = 56;
const doc = new PDFDocument({
size: 'A4',
margins: { top: 50, bottom: 50, left: 50, right: 50 },
size: "A4",
margins: { top: MARGIN_TOP, bottom: 48, left: MARGIN_X, right: MARGIN_X },
bufferPages: true,
autoFirstPage: true,
});
const stream = fs.createWriteStream(outputPath);
doc.pipe(stream);
// Palet Warna Brand
const PRIMARY = '#1e293b'; // Slate 800
const SECONDARY = '#2563eb'; // Blue 600
const ACCENT = '#059669'; // Emerald 600
const TEXT_DARK = '#0f172a'; // Slate 900
const TEXT_MUTED = '#64748b'; // Slate 500
const BORDER_COLOR = '#cbd5e1'; // Slate 300
const BG_LIGHT = '#f8fafc'; // Slate 50
const PAGE_W = doc.page.width;
const PAGE_H = doc.page.height;
const CONTENT_W = PAGE_W - MARGIN_X * 2;
const MAX_Y = PAGE_H - FOOTER_ZONE;
// =========================================================================
// COVER PAGE
// =========================================================================
doc.rect(0, 0, doc.page.width, 180).fill('#0f172a');
const DARK = "#0f172a";
const SLATE = "#1e293b";
const BODY = "#334155";
const ACCENT = "#1d4ed8";
const EMERALD = "#047857";
const BORDER = "#cbd5e1";
const BG_SOFT = "#f8fafc";
const BG_BADGE = "#eff6ff";
doc.fillColor('#ffffff').fontSize(24).font('Helvetica-Bold')
.text('EnterpriseCore ERP', 50, 45);
let cursorY = MARGIN_TOP;
doc.fontSize(12).font('Helvetica')
.fillColor('#94a3b8')
.text('PANDUAN ALUR OPERASIONAL & STANDAR PENGGUNAAN SISTEM', 50, 75);
function startNewPage() {
doc.addPage();
cursorY = MARGIN_TOP;
}
doc.fontSize(10).font('Helvetica')
.fillColor('#38bdf8')
.text('Petunjuk Terpadu Berbasis Peran Divisi (RBAC) & Tata Kelola Keuangan', 50, 95);
function ensureSpace(neededHeight) {
if (cursorY + neededHeight > MAX_Y) {
startNewPage();
}
}
doc.rect(50, 125, 120, 24).fill('#2563eb');
doc.fillColor('#ffffff').fontSize(10).font('Helvetica-Bold')
.text('VERSI SISTEM 2.4', 60, 132);
function measureText(text, font, size, width, lineGap = 2) {
doc.font(font).fontSize(size);
return doc.heightOfString(text, { width, lineGap });
}
doc.y = 210;
doc.fillColor(TEXT_DARK).fontSize(16).font('Helvetica-Bold')
.text('Ringkasan Eksekutif Sistem');
function drawText(text, x, y, font, size, color, width, lineGap = 2) {
doc.font(font).fontSize(size).fillColor(color);
doc.text(text, x, y, { width, lineGap });
return doc.heightOfString(text, { width, lineGap });
}
doc.moveDown(0.5);
doc.fillColor(TEXT_MUTED).fontSize(9.5).font('Helvetica').lineGap(4)
.text(
'EnterpriseCore ERP dirancang khusus untuk mengintegrasikan seluruh siklus bisnis perdagangan dan pengadaan: ' +
'mulai dari pengajuan pembelian barang oleh Sales, penerbitan PO ke Vendor/Distributor, multi-tier approval oleh ' +
'Finance dan Gudang, pencatatan HPP FIFO bertahap, alokasi stok multi-PO saat penjualan, penerbitan Surat Jalan ' +
'dan Invoice dengan dukungan pembayaran parsial (kurang bayar), hingga layanan purna jual / klaim garansi RMA.'
);
function drawSectionHeader(tag, title, introText) {
const introH = introText ? measureText(introText, "Helvetica", 9, CONTENT_W, 2.5) + 12 : 0;
ensureSpace(52 + introH);
doc.moveDown(1.5);
doc.fillColor(PRIMARY).fontSize(12).font('Helvetica-Bold')
.text('Tujuan & Manfaat Penerapan SOP Ini:');
drawText(tag, MARGIN_X, cursorY, "Helvetica-Bold", 8.5, ACCENT, CONTENT_W, 1);
cursorY += 13;
const titleH = drawText(title, MARGIN_X, cursorY, "Helvetica-Bold", 15, DARK, CONTENT_W, 2);
cursorY += titleH + 6;
const bullets = [
'Pemisahan Kapasitas & Hak Akses Divisi: Setiap pengguna hanya mengakses modul yang sesuai dengan tugas pokoknya.',
'Proteksi Nominal Keuangan: Menjaga kerahasiaan nominal uang (HPP modal, kas bank, dan laba perusahaan) dari staf yang tidak berwenang.',
'Akurasi Stok Fisik & Akuntansi: Sinkronisasi otomatis antara pergerakan fisik barang di gudang dengan jurnal buku besar.',
'Transparansi Alokasi Batch PO: Mengetahui secara presisi dari PO nomor berapa setiap unit produk terjual dan berapa sisa stoknya.',
];
doc
.moveTo(MARGIN_X, cursorY)
.lineTo(PAGE_W - MARGIN_X, cursorY)
.strokeColor(BORDER)
.lineWidth(0.8)
.stroke();
cursorY += 12;
doc.moveDown(0.5);
bullets.forEach((b) => {
doc.fillColor(SECONDARY).font('Helvetica-Bold').text('• ', { continued: true });
doc.fillColor(TEXT_DARK).font('Helvetica').fontSize(9).text(b);
doc.moveDown(0.3);
});
if (introText) {
const h = drawText(introText, MARGIN_X, cursorY, "Helvetica", 9, BODY, CONTENT_W, 2.5);
cursorY += h + 14;
}
}
// =========================================================================
// BAB 1: KAPASITAS LOGIN & HAK AKSES MELIHAT UANG PER DIVISI
// =========================================================================
doc.addPage();
doc.fillColor(SECONDARY).fontSize(10).font('Helvetica-Bold')
.text('BAB 1: TATA KELOLA AKSES PENGGUNA', 50, 50);
doc.fillColor(TEXT_DARK).fontSize(16).font('Helvetica-Bold')
.text('Kapasitas Login & Hak Melihat Nominal Uang per Divisi');
function drawInfoCard(title, rows) {
const padX = 11;
const padY = 7;
const innerW = CONTENT_W - padX * 2;
const titleH = measureText(title, "Helvetica-Bold", 9.2, innerW, 1.5);
doc.moveDown(0.5);
doc.fillColor(TEXT_MUTED).fontSize(9).font('Helvetica').lineGap(3)
.text(
'Sistem menerapkan kontrol akses berbasis peran (Role-Based Access Control / RBAC) yang sangat ketat. ' +
'Setiap divisi memiliki ruang lingkup wewenang dan batasan tampilan nominal uang yang telah disesuaikan secara proporsional.'
);
let rowsH = 0;
const measuredRows = rows.map((r) => {
const labelW = r.labelWidth || 82;
const valW = innerW - labelW - 8;
const lh = measureText(r.label, "Helvetica-Bold", 7.9, labelW, 1.5);
const vh = measureText(r.value, r.bold ? "Helvetica-Bold" : "Helvetica", 7.9, valW, 1.5);
const h = Math.max(lh, vh);
rowsH += h + 3.5;
return { ...r, labelW, valW, h };
});
doc.moveDown(1);
const totalH = padY + titleH + 6 + rowsH + padY - 2;
ensureSpace(totalH + 6);
// Tabel Matriks RBAC
const roles = [
{
role: 'Super Admin (ADMIN)',
divisi: 'Direksi / IT Admin',
menu: 'Seluruh Menu (Dashboard, Inventaris, Penjualan, Pembelian, Keuangan, RBAC, Settings)',
uang: 'FULL AKSES: Melihat seluruh nominal uang (Omzet, Saldo Kas Bank, HPP Modal, Margin Laba, Nilai Aset, Payroll).',
},
{
role: 'Manager (MANAGER)',
divisi: 'General Manager / Operasional',
menu: 'Seluruh Menu Operasional (Dashboard, Inventaris, Penjualan, Pembelian, Keuangan)',
uang: 'MELIHAT NOMINAL UANG: Melihat omzet penjualan, laba kotor per PO, HPP modal, dan persetujuan pengadaan.',
},
{
role: 'Staf Gudang (INVENTORY)',
divisi: 'Logistik & Pergudangan',
menu: 'Inventaris & Stok, Riwayat Mutasi, Penerimaan Fisik Barang PO',
uang: 'UANG DISEMBUNYIKAN 100%: Hanya melihat jumlah unit fisik (PCS/Unit), lokasi gudang, dan mutasi. Harga Beli (HPP), Harga Jual, Kas Bank, dan Margin Laba disembunyikan.',
},
{
role: 'Purchasing (PURCHASING)',
divisi: 'Pengadaan & Pemasok',
menu: 'Pembelian PO, Pengajuan PR, Pelacakan Batch PO Vendor, Data Pemasok',
uang: 'HARGA BELI VENDOR: Melihat harga beli PO ke supplier dan biaya logistik ekspor. TIDAK BISA melihat harga jual customer, margin laba penjualan, ataupun kas/gaji.',
},
{
role: 'Sales Rep (SALES)',
divisi: 'Penjualan & Pemasaran',
menu: 'Penjualan SO, Surat Jalan, Invoice, Garansi/RMA, Buat Pengajuan PR',
uang: 'HARGA JUAL & OMZET: Melihat harga jual resmi produk ke customer dan total tagihan invoice. TIDAK BISA melihat HPP modal vendor, kas bank, ataupun laba bersih.',
},
{
role: 'Akuntan (ACCOUNTANT)',
divisi: 'Keuangan & Akuntansi (Finance)',
menu: 'Keuangan, Jurnal, COA Bank, Entitas PT, Slip Gaji Payroll, Review Anggaran PO & Verifikasi Pelunasan Invoice',
uang: 'FULL FINANSIAL: Melihat seluruh arus kas, buku besar jurnal, saldo rekening bank, hutang vendor, piutang customer, dan pembukuan payroll.',
},
];
const topY = cursorY;
doc.roundedRect(MARGIN_X, topY, CONTENT_W, totalH, 5).fill(BG_SOFT);
doc.roundedRect(MARGIN_X, topY, CONTENT_W, totalH, 5).strokeColor(BORDER).lineWidth(0.6).stroke();
roles.forEach((r, idx) => {
doc.fillColor(BG_LIGHT).rect(50, doc.y, doc.page.width - 100, 48).fill();
doc.rect(50, doc.y - 48, doc.page.width - 100, 48).strokeColor(BORDER_COLOR).stroke();
let y = topY + padY;
drawText(title, MARGIN_X + padX, y, "Helvetica-Bold", 9.2, DARK, innerW, 1.5);
y += titleH + 4;
const currentY = doc.y - 42;
doc.fillColor(SECONDARY).font('Helvetica-Bold').fontSize(10)
.text(`${idx + 1}. ${r.role}`, 60, currentY);
doc.fillColor(TEXT_MUTED).font('Helvetica-Bold').fontSize(8.5)
.text(`Divisi: ${r.divisi}`, 240, currentY);
doc
.moveTo(MARGIN_X + padX, y)
.lineTo(MARGIN_X + CONTENT_W - padX, y)
.strokeColor("#e2e8f0")
.lineWidth(0.5)
.stroke();
y += 4.5;
doc.fillColor(TEXT_DARK).font('Helvetica').fontSize(8)
.text(`• Menu Akses: ${r.menu}`, 60, currentY + 14, { width: doc.page.width - 120 });
doc.fillColor(ACCENT).font('Helvetica-Bold').fontSize(8)
.text(`• Kebijakan Uang: ${r.uang}`, 60, currentY + 25, { width: doc.page.width - 120 });
measuredRows.forEach((r) => {
drawText(r.label, MARGIN_X + padX, y, "Helvetica-Bold", 7.9, r.labelColor || SLATE, r.labelW, 1.5);
drawText(
r.value,
MARGIN_X + padX + r.labelW + 8,
y,
r.bold ? "Helvetica-Bold" : "Helvetica",
7.9,
r.valueColor || BODY,
r.valW,
1.5
);
y += r.h + 3.5;
});
doc.y = currentY + 44;
doc.moveDown(0.2);
});
cursorY = topY + totalH + 6.5;
}
// =========================================================================
// BAB 2: ALUR OPERASIONAL TERPADU (END-TO-END WORKFLOW)
// =========================================================================
doc.addPage();
doc.fillColor(SECONDARY).fontSize(10).font('Helvetica-Bold')
.text('BAB 2: SIKLUS ALUR OPERASIONAL LENGKAP', 50, 50);
doc.fillColor(TEXT_DARK).fontSize(16).font('Helvetica-Bold')
.text('Alur Kerja 8 Tahap: Pengadaan hingga Penjualan & Finance');
function drawTopicBlock(heading, subtitle, paragraphs) {
const innerW = CONTENT_W;
const hHead = measureText(heading, "Helvetica-Bold", 10, innerW, 2);
const hSub = subtitle ? measureText(subtitle, "Helvetica-Bold", 8.2, innerW, 1.5) + 4 : 0;
const paraHeights = paragraphs.map((p) => measureText(p, "Helvetica", 8.7, innerW - (p.startsWith("• ") ? 8 : 0), 2.5));
const totalH = hHead + hSub + paraHeights.reduce((a, b) => a + b + 5, 0) + 12;
doc.moveDown(0.6);
ensureSpace(totalH);
const steps = [
{
step: 'TAHAP 1',
title: 'Pengajuan Kebutuhan Barang (Requisition)',
actor: 'Divisi Sales Rep / Staf Gudang',
desc: 'Ketika ada pesanan pelanggan atau stok fisik di gudang menipis, Sales atau Gudang membuat formulir Pengajuan (PR) di modul Pembelian. Data mencakup SKU produk, jumlah unit yang diminta, keperluan proyek, dan nama PT Customer pemesan.',
},
{
step: 'TAHAP 2',
title: 'Penerbitan Purchase Order (PO) ke Vendor',
actor: 'Divisi Purchasing / Pengadaan',
desc: 'Purchasing mengonversi Pengajuan Sales menjadi dokumen PO Vendor. Memilih supplier resmi, menentukan mata uang (IDR atau USD kurs berjalan), mode logistik (Forwarder All-in atau Breakdown Bea Cukai), dan menerbitkan PO berstatus "Menunggu Finance".',
},
{
step: 'TAHAP 3',
title: 'Persetujuan Anggaran (Approval Finance)',
actor: 'Divisi Finance & Akuntan',
desc: 'Finance memeriksa kesesuaian anggaran pengadaan. Finance berwenang memberikan keputusan: Approve (disetujui untuk dipesan ke vendor), Hold (ditunda sementara dengan catatan), atau Reject (dibatalkan).',
},
{
step: 'TAHAP 4',
title: 'Penerimaan Fisik Barang di Gudang',
actor: 'Divisi Staf Gudang (Inventory)',
desc: 'Ketika barang fisik tiba dari distributor, Staf Gudang memeriksa jumlah dan kondisi fisik. Mengklik "Approve Gudang (Barang Tiba)". Sistem secara otomatis menambah stok fisik di Gudang Utama, mencatat riwayat mutasi masuk, dan mencatat landed cost.',
},
{
step: 'TAHAP 5',
title: 'Pelacakan Batch FIFO & Alokasi Multi-PO',
actor: 'Divisi Purchasing & Sales',
desc: 'Setiap penerimaan barang otomatis membentuk "Batch PO FIFO". Sistem mencatat nomor PO sumber, kuantitas awal, modal HPP landed cost per unit, dan sisa unit yang belum terjual.',
},
{
step: 'TAHAP 6',
title: 'Pembuatan Sales Order (SO) & Cetak Surat Jalan',
actor: 'Divisi Sales Representative',
desc: 'Sales membuat Sales Order untuk pelanggan. Sales dapat memilih mengambil barang dari PO Vendor ke-1 atau ke-2 secara transparan jika unit pada satu PO kurang. Sales mencetak Surat Jalan pengiriman dan Invoice resmi.',
},
{
step: 'TAHAP 7',
title: 'Penagihan, Pembayaran Parsial & Penjurnalan',
actor: 'Divisi Finance & Akuntan',
desc: 'Finance mencatat pembayaran pelanggan. Sistem mendukung pembayaran bertahap (Kurang Bayar / Partial Payment), di mana dana yang masuk langsung tercatat di kas, dan sisa nominal otomatis menjadi Piutang Belum Lunas. Transaksi otomatis terjurnal di buku besar.',
},
{
step: 'TAHAP 8',
title: 'Layanan Purna Jual, Garansi & RMA Jual Putus',
actor: 'Divisi Sales & Customer Support',
desc: 'Untuk barang dengan skema Jual Putus yang mengalami kerusakan saat masa garansi, staf membuka modul Pelacakan Garansi. Sistem menyediakan fitur Service Perbaikan atau Ganti Unit Baru dengan pemotongan stok otomatis dan pencatatan serial number baru.',
},
];
drawText(heading, MARGIN_X, cursorY, "Helvetica-Bold", 10, DARK, innerW, 2);
cursorY += hHead + 2;
steps.forEach((s) => {
// Cek batas halaman
if (doc.y > doc.page.height - 95) {
doc.addPage();
if (subtitle) {
const sh = drawText(subtitle, MARGIN_X, cursorY, "Helvetica-Bold", 8.2, EMERALD, innerW, 1.5);
cursorY += sh + 4;
}
doc.fillColor(SECONDARY).font('Helvetica-Bold').fontSize(8.5)
.text(`[${s.step}] `, 50, doc.y, { continued: true });
doc.fillColor(TEXT_DARK).font('Helvetica-Bold').fontSize(9.5)
.text(`${s.title} `);
paragraphs.forEach((p, idx) => {
const isBullet = p.startsWith("• ");
const x = isBullet ? MARGIN_X + 8 : MARGIN_X;
const w = isBullet ? innerW - 8 : innerW;
const h = drawText(p, x, cursorY, "Helvetica", 8.7, BODY, w, 2.5);
cursorY += h + (idx === paragraphs.length - 1 ? 12 : 4);
});
}
doc.fillColor(ACCENT).font('Helvetica-Bold').fontSize(8)
.text(`Pelaksana: ${s.actor}`);
// =========================================================================
// HALAMAN 1: SAMPUL & STRUKTUR MENU APLIKASI
// =========================================================================
doc.rect(0, 0, PAGE_W, 178).fill(DARK);
doc.fillColor(TEXT_MUTED).font('Helvetica').fontSize(8.5).lineGap(2)
.text(s.desc);
drawText("EnterpriseCore ERP", MARGIN_X, 40, "Helvetica-Bold", 24, "#ffffff", CONTENT_W, 1);
drawText(
"PANDUAN ALUR OPERASIONAL, KEAMANAN & STANDAR PENGGUNAAN SISTEM",
MARGIN_X,
72,
"Helvetica",
10.5,
"#e2e8f0",
CONTENT_W,
2
);
drawText(
"Multi-PT • Inventaris & Serial Number (SN) • Service & RMA • Keuangan • Notifikasi Email • RBAC",
MARGIN_X,
94,
"Helvetica",
9,
"#7dd3fc",
CONTENT_W,
2
);
doc.moveDown(0.6);
doc.roundedRect(MARGIN_X, 124, 185, 24, 4).fill(ACCENT);
drawText("VERSI SISTEM 3.0 • SOP RESMI", MARGIN_X + 12, 131, "Helvetica-Bold", 9, "#ffffff", 170, 1);
cursorY = 204;
const hIntroTitle = drawText("Ringkasan Sistem", MARGIN_X, cursorY, "Helvetica-Bold", 13.5, DARK, CONTENT_W, 2);
cursorY += hIntroTitle + 6;
const hIntro = drawText(
"EnterpriseCore ERP menyatukan seluruh operasional perusahaan dalam satu platform multi-PT yang aman dan terintegrasi: Dashboard terpersonalisasi per divisi, Inventaris (Katalog & SN, Mutasi Stok, Service & RMA), Penjualan (Sales Order, Surat Jalan, Invoice, Garansi), Pembelian (Purchase Order, Pengajuan, Batch & Alokasi FIFO), Keuangan (Payroll, Daftar Akun/COA, Jurnal, Perusahaan), Portal RMA Customer tanpa login berbasis verifikasi SN, notifikasi Email SMTP & Telegram sesuai kapasitas role, serta Mode Gelap (default) dan Mode Terang.",
MARGIN_X,
cursorY,
"Helvetica",
9,
BODY,
CONTENT_W,
3
);
cursorY += hIntro + 18;
const hMenuTitle = drawText("Struktur Menu Aplikasi", MARGIN_X, cursorY, "Helvetica-Bold", 11.5, DARK, CONTENT_W, 2);
cursorY += hMenuTitle + 8;
const menuRows = [
["Dashboard", "Ringkasan KPI, posisi Kas & Bank per PT, stok gudang, transaksi terbaru, dan peringatan sesuai role."],
["Inventaris", "Dropdown 3 sub-menu: Katalog & SN, Mutasi Stok, dan Service & RMA (Device Service, Rusak, Kanibalan)."],
["Penjualan", "Pembuatan Sales Order, Invoice, Surat Jalan, SN keluar, & klaim garansi (tampil 'Pengiriman' bagi Gudang)."],
["Pembelian", "Dropdown 3 sub-menu: Purchase Order, Pengajuan dari Sales/Gudang, dan Batch & Alokasi FIFO."],
["Keuangan", "Dropdown 5 sub-menu: Laporan (Laba Rugi, Neraca, AR/AP), Payroll, Daftar Akun (COA), Jurnal, dan Perusahaan."],
["Pengguna", "Manajemen akun karyawan, kunci aktif/nonaktif, role RBAC, MFA (2FA), preferensi email, dan Audit Log."],
["Pengaturan", "Konfigurasi Email SMTP, Telegram per divisi, tombol Tes Email, log alert, dan Backup Database (Admin)."],
["Portal RMA (/rma)", "Halaman publik tanpa login khusus customer untuk pengajuan & pelacakan service berbasis SN terdaftar."],
];
// Tabel Menu Rapi dengan Kalkulasi Tinggi Otomatis
const col1W = 112;
const col2W = CONTENT_W - col1W - 20;
menuRows.forEach(([name, desc], idx) => {
const h1 = measureText(name, "Helvetica-Bold", 8.6, col1W, 2);
const h2 = measureText(desc, "Helvetica", 8.6, col2W, 2);
const rowH = Math.max(h1, h2) + 12;
ensureSpace(rowH);
if (idx % 2 === 0) {
doc.rect(MARGIN_X, cursorY, CONTENT_W, rowH).fill(BG_SOFT);
}
doc.rect(MARGIN_X, cursorY, CONTENT_W, rowH).strokeColor("#e2e8f0").lineWidth(0.5).stroke();
drawText(name, MARGIN_X + 8, cursorY + 6, "Helvetica-Bold", 8.6, ACCENT, col1W, 2);
drawText(desc, MARGIN_X + col1W + 12, cursorY + 6, "Helvetica", 8.6, BODY, col2W, 2);
cursorY += rowH;
});
// =========================================================================
// BAB 3: FITUR KHUSUS & PANDUAN TEKNIS APLIKASI
// HALAMAN 2: BAB 1 - MATRIKS HAK AKSES, KEBIJAKAN UANG & EMAIL
// =========================================================================
doc.addPage();
doc.fillColor(SECONDARY).fontSize(10).font('Helvetica-Bold')
.text('BAB 3: FITUR KHUSUS & PETUNJUK PRAKTIS', 50, 50);
doc.fillColor(TEXT_DARK).fontSize(16).font('Helvetica-Bold')
.text('Panduan Fitur-Fitur Khusus Sistem');
startNewPage();
drawSectionHeader(
"BAB 1 • KONTROL AKSES & NOTIFIKASI",
"Matriks Role Login, Kebijakan Uang & Kapasitas Email",
"Seluruh rute halaman dan API divalidasi di tingkat server (Middleware & API RBAC). Semua role dapat melihat Dashboard yang otomatis disesuaikan kapasitas loginnya, sementara akses modul di luar wewenang diblokir dan dialihkan."
);
doc.moveDown(0.6);
const tips = [
const roles = [
{
title: '1. Pendaftaran Master Produk Cepat & Efisien',
content:
'Saat menambahkan produk baru ke katalog, form disederhanakan hanya untuk data pokok: Jenis Item (Fisik / Layanan), Kode SKU, Nama Produk, Satuan Ukuran, dan Kategori. Kolom HPP modal, harga jual, dan stok gudang ditiadakan dari form ini karena HPP modal dan stok fisik otomatis terbentuk secara akurat saat ada PO Vendor masuk, sedangkan harga jual dapat disesuaikan kemudian melalui tombol Edit.',
title: "1. Super Admin (ADMIN)",
rows: [
{ label: "Modul Akses", value: "Semua modul termasuk Pengguna (tambah/edit/kunci akun) & Pengaturan (SMTP, Telegram, Backup Database)." },
{ label: "Kebijakan Uang", value: "AKSES PENUH: Omzet, Laba Kotor, HPP, Saldo Kas & Bank per PT, Piutang, Hutang, dan Payroll.", valueColor: EMERALD, bold: true },
{ label: "Kapasitas Email", value: "Barang Masuk, Barang Keluar, Uang Masuk, Uang Keluar / Approval PO, RMA & Service.", valueColor: ACCENT },
],
},
{
title: '2. Pemisahan "Stok Menipis" vs "Stok Kosong (0 Unit)"',
content:
'Sistem membedakan secara tegas kondisi stok barang. Jika barang baru ditambahkan dan stok fisiknya masih 0, status yang muncul adalah "0 PCS (Stok Kosong)" berlabel netral, bukan "Stok Menipis". Status "Stok Menipis" hanya aktif jika barang memiliki stok fisik (> 0 unit) tetapi jumlahnya berada di bawah batas minimum aman yang ditentukan.',
title: "2. Manajemen (MANAGER)",
rows: [
{ label: "Modul Akses", value: "Dashboard (View-Only), Inventaris, Penjualan, Pembelian, Keuangan, Pengguna (profil/audit), Pengaturan (View-Only)." },
{ label: "Kebijakan Uang", value: "AKSES PANTAUAN PENUH: Seluruh ringkasan keuangan, posisi kas per PT, laba, dan persetujuan anggaran.", valueColor: EMERALD, bold: true },
{ label: "Kapasitas Email", value: "Barang Masuk, Barang Keluar, Uang Masuk, Uang Keluar / Approval PO, RMA & Service.", valueColor: ACCENT },
],
},
{
title: '2. Paginasi Angka Bersih (Tanpa Embel-Embel /hal)',
content:
'Seluruh tabel pada modul Penjualan, Pembelian, dan Inventaris menggunakan navigasi paginasi dengan pilihan ukuran halaman berupa angka murni: 5, 10, 25, dan 50 data per halaman. Pengguna dapat berpindah halaman dengan tombol Sebelumnya / Selanjutnya atau nomor halaman langsung.',
title: "3. Keuangan (ACCOUNTANT)",
rows: [
{ label: "Modul Akses", value: "Dashboard Keuangan, Keuangan (Laporan Laba Rugi/Neraca/AR-AP, Payroll, Daftar Akun, Jurnal, Perusahaan), Approval & Bayar PO/SO." },
{ label: "Kebijakan Uang", value: "FULL FINANSIAL: Arus kas per PT, buku besar, COA, piutang customer, hutang vendor, PPN, dan verifikasi biaya service.", valueColor: EMERALD, bold: true },
{ label: "Kapasitas Email", value: "Uang Masuk & Uang Keluar / Approval PO (bebas dari notifikasi mutasi gudang/RMA teknis).", valueColor: ACCENT },
],
},
{
title: '3. Tombol Hapus Aman & Modal Dialog Interaktif',
content:
'Penghapusan data (Produk di Inventaris, PO di Pembelian, SO di Penjualan) tidak lagi menggunakan alert bawaan browser yang rawan diblokir. Sistem menyediakan Modal Konfirmasi khusus dengan tombol merah "Ya, Hapus Sekarang" yang secara otomatis membersihkan seluruh dependensi data terkait tanpa merusak integritas database.',
title: "4. Sales (SALES)",
rows: [
{ label: "Modul Akses", value: "Dashboard Penjualan, Penjualan (SO, Invoice, Surat Jalan, Klaim Garansi/RMA), Pengajuan Pembelian (PR), Cek Stok Inventaris." },
{ label: "Kebijakan Uang", value: "HARGA JUAL & TAGIHAN: Melihat omzet, piutang customer, biaya service & ongkir balik. Tidak mengakses Kas Bank, COA, atau PPN PO.", valueColor: EMERALD, bold: true },
{ label: "Kapasitas Email", value: "Barang Keluar, Uang Masuk (pelunasan customer), dan RMA & Service.", valueColor: ACCENT },
],
},
{
title: '4. Gabung Produk Duplikat (Merge SKU)',
content:
'Jika terdapat produk ganda dengan penulisan SKU berbeda (misalnya TIMBANGAN dan TMBG), Super Admin dapat menggunakan fitur "Gabung Duplikat" di modul Inventaris. Sistem secara otomatis menyatukan riwayat mutasi stok, harga khusus customer, dan alokasi batch ke SKU target.',
title: "5. Purchasing (PURCHASING)",
rows: [
{ label: "Modul Akses", value: "Dashboard Pengadaan, Pembelian (Purchase Order, Pengajuan, Batch & Alokasi), dan Cek Stok Inventaris." },
{ label: "Kebijakan Uang", value: "HARGA BELI VENDOR: Melihat nilai belanja PO dan hutang vendor. Tidak melihat omzet penjualan, laba, atau saldo Kas Bank.", valueColor: EMERALD, bold: true },
{ label: "Kapasitas Email", value: "Barang Masuk (penerimaan PO) dan Uang Keluar / Approval PO.", valueColor: ACCENT },
],
},
{
title: '5. Multi-Entitas Perusahaan (Multi-PT)',
content:
'Aplikasi mendukung pengelolaan transaksi multi-perusahaan. Di bagian atas navbar, pengguna berwenang dapat memfilter data atau beralih antara PT EnterpriseCore Utama dan entitas PT lainnya.',
title: "6. Gudang & Teknisi (INVENTORY)",
rows: [
{ label: "Modul Akses", value: "Dashboard Gudang, Inventaris (Katalog & SN, Mutasi Stok, Service & RMA), Pengiriman (resi/Surat Jalan), Penerimaan PO & Input SN." },
{ label: "Kebijakan Uang", value: "NOMINAL UANG DISEMBUNYIKAN 100%: Hanya melihat unit fisik, SN, gudang, dan status device. Nominal Rp di email otomatis disensor.", valueColor: EMERALD, bold: true },
{ label: "Kapasitas Email", value: "Barang Masuk, Barang Keluar, dan RMA & Service (dengan sensor nominal uang otomatis).", valueColor: ACCENT },
],
},
];
tips.forEach((t) => {
doc.fillColor(PRIMARY).font('Helvetica-Bold').fontSize(10)
.text(t.title);
doc.moveDown(0.2);
doc.fillColor(TEXT_MUTED).font('Helvetica').fontSize(8.5).lineGap(3)
.text(t.content);
doc.moveDown(0.8);
});
roles.forEach((r) => drawInfoCard(r.title, r.rows));
// Footer & Penomoran Halaman di semua halaman
// =========================================================================
// BAB 2: SIKLUS OPERASIONAL, SN EXCEL & AKUNTANSI MULTI-PT
// =========================================================================
startNewPage();
drawSectionHeader(
"BAB 2 • ALUR KERJA OPERASIONAL",
"Pengadaan, Pencatatan SN (Excel), Penjualan & Multi-PT",
"Alur kerja berikut menjaga sinkronisasi otomatis antara pengajuan barang, persetujuan anggaran, stok fisik per PT, Serial Number (SN), hingga buku besar keuangan."
);
const workflows = [
{
title: "Tahap 1 — Pengajuan Barang (PR) & Penerbitan PO",
actor: "Pelaksana: Sales / Gudang -> Purchasing",
paras: [
"Sales atau Gudang membuat pengajuan kebutuhan barang di menu Pembelian > Pengajuan. Purchasing kemudian mengonversi pengajuan menjadi Purchase Order (PO) dengan memilih entitas PT pembeli, vendor, mata uang (IDR/USD), dan jumlah unit. Status awal PO masuk ke antrean Review Finance.",
],
},
{
title: "Tahap 2 — Approval Anggaran, Logistik/Pajak & Pembayaran PO",
actor: "Pelaksana: Keuangan (Accountant) / Manager",
paras: [
"Finance memeriksa dan memberi keputusan Approve, Hold, atau Reject atas anggaran PO, menginput biaya pengiriman/forwarder dan PPN, serta mencatat pembayaran DP (Sebagian) maupun Pelunasan (Lunas).",
"Isolasi Akuntansi Multi-PT: Sistem otomatis memastikan setiap PT memiliki Bagan Akun (COA) terpisah sehingga pengeluaran kas, persediaan, dan hutang PO selalu tercatat pada rekening PT yang bertransaksi dan tidak pernah bercampur ke PT lain.",
],
},
{
title: "Tahap 3 — Penerimaan Barang Gudang & Upload Excel Serial Number (SN)",
actor: "Pelaksana: Gudang (Inventory)",
paras: [
"Saat barang fisik tiba, staf Gudang klik Terima Barang pada PO terkait. Gudang dapat mencatat Serial Number (SN) secara manual atau melalui fitur Upload Excel (.xlsx/.csv) menggunakan tombol Unduh Template Excel.",
"Apabila pencatatan SN dilakukan menyusul setelah barang diterima, staf Gudang/Admin tetap dapat menambahkan atau memperbarui daftar SN melalui tombol Edit / Upload SN Barang Masuk pada PO yang sudah diterima.",
],
},
{
title: "Tahap 4 — Stok Akurat per PT & Pelacakan Batch FIFO",
actor: "Pelaksana: Sistem Otomatis • Inventaris & Pembelian",
paras: [
"Walaupun Gudang Utama digunakan bersama beberapa perusahaan, stok fisik pada Katalog Produk dan Dashboard dihitung akurat per entitas PT berdasarkan Batch PO dan riwayat mutasi masing-masing PT. Dropdown pilihan Perusahaan di navbar langsung memfilter stok, saldo kas, dan seluruh transaksi PT yang dipilih.",
],
},
{
title: "Tahap 5 — Sales Order (SO), Upload SN Keluar & Pengiriman",
actor: "Pelaksana: Sales -> Gudang (Pengiriman)",
paras: [
"Sales membuat Sales Order dengan memilih produk, harga jual, durasi garansi, serta mencatat/upload Excel SN barang keluar. Staf Gudang memproses pengiriman pada menu Pengiriman dengan mencetak Surat Jalan dan mengisi 3 informasi ringkas: Nama Kurir, Nomor Resi, dan Ongkos Kirim.",
],
},
{
title: "Tahap 6 — Penagihan, Pembayaran Parsial & Penjurnalan Otomatis",
actor: "Pelaksana: Keuangan (Accountant)",
paras: [
"Finance memverifikasi pelunasan customer (mendukung pembayaran DP/parsial maupun lunas) serta konfirmasi pembayaran jasa service berbayar dan ongkir kirim balik. Jurnal piutang, pendapatan, HPP, dan kas otomatis tercatat pada buku besar PT terkait.",
],
},
];
workflows.forEach((w) => drawTopicBlock(w.title, w.actor, w.paras));
// =========================================================================
// BAB 3: SERVICE, GARANSI, DEVICE RUSAK/KANIBALAN & PORTAL RMA PUBLIK
// =========================================================================
startNewPage();
drawSectionHeader(
"BAB 3 • PURNA JUAL & RMA",
"Garansi, Device Service/Rusak/Kanibalan & Portal RMA",
"Modul purna jual mencatat seluruh siklus hidup perangkat bernomor seri (SN), mulai dari pengajuan mandiri customer hingga perbaikan, tukar unit, pencatatan rusak/kanibalan, dan pengiriman balik."
);
drawTopicBlock("1. Skema Garansi Aktif vs Garansi Habis", null, [
"• Masa Garansi Aktif: Customer berhak memilih Service Gratis (Rp 0) atau Tukar Unit Baru. Saat memilih Tukar Unit Baru, kondisi unit lama wajib dicatat sebagai Rusak Total (Tidak Bisa Dipakai) atau Kanibalan (beserta daftar sparepart yang diambil) agar histori aset tercatat rapi.",
"• Masa Garansi Habis: Sistem otomatis membuka skema Jasa Service Berbayar dengan pengisian biaya service, pencetakan Invoice Service resmi, dan verifikasi pembayaran oleh Finance.",
]);
drawTopicBlock("2. Ongkos Kirim Balik (Ditanggung User)", null, [
"Setelah perbaikan selesai atau unit pengganti siap dikirim, tim Teknisi/Gudang maupun Sales dapat memperbarui status perangkat (misalnya menjadi Selesai Service) sekaligus menginput Biaya Ongkir Kirim Balik, Nama Kurir, dan Nomor Resi.",
"Kebijakan ongkir ditanggung user berlaku untuk service gratis, service berbayar, maupun ganti unit, dan data otomatis tersinkronisasi 2 arah antara Inventaris > Service & RMA dengan Sales Order terkait.",
]);
drawTopicBlock("3. Portal RMA Customer Tanpa Login (/rma)", null, [
"Customer dapat mengajukan RMA/Service atau melacak status tiket secara mandiri tanpa akun ERP melalui halaman publik /rma (tautan juga tersedia di halaman Login):",
"• Verifikasi Ketat via SN Database: Customer wajib memasukkan Serial Number (SN) fisik unit. SN yang tidak terdaftar resmi pada database transaksi perusahaan otomatis ditolak untuk mencegah pengajuan fiktif atau spam.",
"• Deteksi Garansi Otomatis: Setelah SN valid, sistem langsung menampilkan nama produk, tanggal pembelian, status masa garansi, dan pilihan layanan yang berhak diajukan.",
"• Notifikasi Otomatis: Setiap pengajuan RMA dari portal publik langsung memicu notifikasi Email kepada tim Sales, Gudang/Teknisi, Manager, dan Admin.",
]);
drawTopicBlock("4. Pencatatan Terpusat Device Service, Rusak & Kanibalan", null, [
"Seluruh riwayat perangkat yang pernah di-service, dinyatakan rusak total, atau dijadikan kanibalan dikelola di menu Inventaris > Service & RMA lengkap dengan nomor tiket, SN otomatis, keluhan, tindakan teknisi, daftar sparepart kanibalan, serta status ongkir balik.",
]);
// =========================================================================
// BAB 4: NOTIFIKASI EMAIL SMTP, KEAMANAN SISTEM & BACKUP DATABASE
// =========================================================================
startNewPage();
drawSectionHeader(
"BAB 4 • KEAMANAN & ADMINISTRASI SISTEM",
"Notifikasi Email SMTP, Perlindungan Akun & Backup Database",
"Bagian ini merangkum konfigurasi notifikasi otomatis agar tim tidak perlu terus memantau dashboard, beserta standar keamanan operasional sistem."
);
drawTopicBlock("1. Konfigurasi Email SMTP & Notifikasi per Kapasitas Role", null, [
"• Buka menu Pengaturan (khusus Super Admin), aktifkan sakelar Notifikasi Email, dan pilih topik yang diinginkan (Barang Masuk, Barang Keluar, Uang Masuk, Uang Keluar/PO, serta RMA & Service).",
"• Isi SMTP Host (misalnya smtp.gmail.com), Port (587 atau 465), SMTP User, App Password, dan Alamat Pengirim (From), lalu klik Simpan Konfigurasi.",
"• Klik tombol Tes Kirim Email untuk memastikan email masuk ke kotak masuk. Pastikan email aktif setiap karyawan sudah diisi dengan benar di menu Pengguna.",
]);
drawTopicBlock("2. Lapisan Keamanan Akun, Sesi & API", null, [
"• Kunci Akun Aktif / Nonaktif (isActive): Admin dapat menonaktifkan akun karyawan kapan saja di menu Pengguna. Sesi yang sedang aktif langsung terputus seketika dan percobaan login baru ditolak.",
"• Kebijakan Password Kuat: Pembuatan maupun penggantian password mewajibkan minimal 8 karakter dengan kombinasi huruf dan angka, tersimpan terenkripsi (bcrypt).",
"• Verifikasi 2-Langkah (MFA / 2FA): Mendukung aplikasi Google Authenticator (TOTP) maupun OTP melalui Telegram.",
"• Auto-Logout Otomatis (30 Menit Idle): Sesi pengguna otomatis berakhir setelah 30 menit tanpa aktivitas demi melindungi komputer kantor yang ditinggalkan.",
"• Proteksi Brute-Force & Masking Kredensial: Login, verifikasi MFA, dan pencarian SN pada Portal RMA dilengkapi Rate Limiting. Password SMTP dan Token Bot Telegram selalu disamarkan dan tidak pernah dikirim dalam bentuk teks polos ke browser.",
]);
drawTopicBlock("3. Backup Database Atomik (Khusus Super Admin)", null, [
"Pada menu Pengaturan > Keamanan Sistem & Backup Database, Super Admin dapat mengklik tombol Unduh Backup (.db) untuk mengunduh snapshot database secara aman dan atomik (menggunakan SQLite VACUUM INTO tanpa mengganggu transaksi yang sedang berjalan). Setiap aktivitas backup otomatis tercatat di Audit Log.",
"Disarankan melakukan backup berkala minimal setiap akhir minggu dan menyimpan salinannya pada media penyimpanan eksternal atau cloud terenkripsi.",
]);
drawTopicBlock("4. Mode Tampilan Gelap (Default) & Mode Terang + Cetak Dokumen", null, [
"Aplikasi aktif dalam Mode Gelap secara default dengan teks terang kontras tinggi agar nyaman digunakan sepanjang hari. Pengguna dapat beralih ke Mode Terang kapan saja melalui tombol Terang / Gelap di pojok kanan atas navbar.",
"Saat mencetak Invoice, Surat Jalan, Purchase Order, atau Slip Gaji, sistem otomatis menyesuaikan ke format cetak hitam-putih bersih di atas kertas putih.",
]);
// =========================================================================
// FOOTER TANPA MEMICU HALAMAN KOSONG (lineBreak: false!)
// =========================================================================
const range = doc.bufferedPageRange();
for (let i = range.start; i < range.start + range.count; i++) {
const totalPages = range.count;
for (let i = range.start; i < range.start + totalPages; i++) {
doc.switchToPage(i);
// Garis pemisah footer
doc.rect(50, doc.page.height - 35, doc.page.width - 100, 0.5).fill('#e2e8f0');
const footerLineY = PAGE_H - 36;
const footerTextY = PAGE_H - 28;
doc.fillColor('#94a3b8').fontSize(7.5).font('Helvetica')
.text(
'EnterpriseCore ERP System • Dokumen Resmi Panduan Operasional Perusahaan',
50,
doc.page.height - 28
);
doc
.moveTo(MARGIN_X, footerLineY)
.lineTo(PAGE_W - MARGIN_X, footerLineY)
.strokeColor(BORDER)
.lineWidth(0.5)
.stroke();
doc.fillColor('#94a3b8').fontSize(7.5).font('Helvetica')
.text(
`Halaman ${i + 1} dari ${range.count}`,
doc.page.width - 120,
doc.page.height - 28,
{ align: 'right' }
);
doc
.font("Helvetica")
.fontSize(7.5)
.fillColor("#475569")
.text(
"EnterpriseCore ERP v3.0 • Panduan Resmi Operasional & Keamanan Sistem",
MARGIN_X,
footerTextY,
{ lineBreak: false }
);
const pageLabel = `Halaman ${i + 1} dari ${totalPages}`;
const labelW = doc.widthOfString(pageLabel);
doc
.font("Helvetica")
.fontSize(7.5)
.fillColor("#475569")
.text(pageLabel, PAGE_W - MARGIN_X - labelW, footerTextY, { lineBreak: false });
}
doc.end();
stream.on('finish', () => {
console.log(`PDF berhasil dibuat di: ${outputPath}`);
// Salin ke root folder juga
stream.on("finish", () => {
console.log(`PDF v3.0 rapi berhasil dibuat (${totalPages} halaman) di: ${outputPath}`);
try {
fs.copyFileSync(outputPath, rootOutputPath);
console.log(`Salinan PDF dibuat di root: ${rootOutputPath}`);
console.log(`Salinan PDF disinkronkan ke: ${rootOutputPath}`);
} catch (e) {
console.error(e);
console.error("Gagal menyalin ke root:", e);
}
});
}
+27 -10
View File
@@ -1,3 +1,4 @@
import crypto from "crypto";
import { NextResponse } from "next/server";
import { getPrismaByMode, type EnvMode } from "@/lib/db";
import {
@@ -6,6 +7,7 @@ import {
checkRateLimit,
recordFailedAttempt,
clearRateLimit,
getAuthCookieOptions,
} from "@/lib/auth";
import {
generateMfaSecret,
@@ -14,11 +16,12 @@ import {
hashDynamicOtp,
} from "@/lib/mfa";
import { sendTelegramMessage, getAllSettings } from "@/lib/notifier";
import { getDefaultLandingRoute } from "@/lib/permissions";
export async function POST(req: Request) {
try {
const { email, password, envMode } = await req.json();
const mode: EnvMode = envMode === "LIVE" ? "LIVE" : "DEMO";
const { email, password } = await req.json();
const mode: EnvMode = "LIVE";
if (!email || !password) {
return NextResponse.json(
@@ -58,6 +61,25 @@ export async function POST(req: Request) {
);
}
if (user.isActive === false) {
await db.auditLog.create({
data: {
userId: user.id,
userName: user.name,
action: "LOGIN_BLOCKED",
module: "AUTH",
description: `Percobaan login ditolak karena akun ${user.email} (${user.role}) berstatus NONAKTIF`,
},
});
return NextResponse.json(
{
error:
"Akses login ditolak: Akun Anda sedang dinonaktifkan oleh Administrator. Hubungi Super Admin untuk mengaktifkan kembali.",
},
{ status: 403 }
);
}
const isMatch = await comparePassword(String(password), user.password);
if (!isMatch) {
recordFailedAttempt(rateKey);
@@ -87,7 +109,7 @@ export async function POST(req: Request) {
// Send OTP via Telegram if method is TELEGRAM (never store plaintext OTP inside JWT!)
if (user.mfaMethod === "TELEGRAM") {
const dynamicOtp = Math.floor(100000 + Math.random() * 900000).toString();
const dynamicOtp = crypto.randomInt(100000, 1000000).toString();
otpHash = hashDynamicOtp(dynamicOtp);
try {
const settings = await getAllSettings();
@@ -161,15 +183,10 @@ export async function POST(req: Request) {
const response = NextResponse.json({
success: true,
user: sessionUser,
defaultRoute: getDefaultLandingRoute(user.role),
});
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
maxAge: 60 * 60 * 24, // 24 hours
};
const cookieOptions = getAuthCookieOptions(req);
response.cookies.set("erp_session", token, cookieOptions);
response.cookies.set("erp_env", mode, cookieOptions);
+7 -94
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { getCurrentUser, signToken } from "@/lib/auth";
import { prisma, getPrismaByMode, type EnvMode } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { ensureCompanyAccounts, getSavedCompanies } from "@/lib/companies";
export async function GET() {
@@ -128,96 +128,9 @@ export async function POST(req: Request) {
}
}
export async function PUT(req: Request) {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
const { envMode } = await req.json();
const targetMode: EnvMode = envMode === "LIVE" ? "LIVE" : "DEMO";
// Saat sudah berada di mode LIVE (Production), tidak bisa kembali ke mode DEMO
if (currentUser.envMode === "LIVE" && targetMode === "DEMO") {
return NextResponse.json(
{
error:
"Anda sudah berada di Mode Production (Live). Beralih kembali ke Mode Demo dinonaktifkan.",
},
{ status: 403 }
);
}
// Pemisahan Kredensial: Saat beralih dari Mode DEMO ke LIVE (Production), wajib login ulang dengan akun Production
if (currentUser.envMode === "DEMO" && targetMode === "LIVE") {
const response = NextResponse.json(
{
requireLogin: true,
error:
"Beralih ke Mode Production memerlukan autentikasi login ulang menggunakan akun kredensial Production.",
},
{ status: 401 }
);
response.cookies.delete("erp_session");
return response;
}
const db = getPrismaByMode(targetMode);
const targetUser = await db.user.findUnique({
where: { email: currentUser.email.toLowerCase().trim() },
});
if (!targetUser) {
return NextResponse.json(
{
requireLogin: true,
error: `Akun ${currentUser.email} belum terdaftar di lingkungan ${targetMode}. Silakan login dengan akun ${targetMode}.`,
},
{ status: 404 }
);
}
// Keamanan: Jangan izinkan bypass MFA jika akun di mode LIVE mewajibkan verifikasi 2-langkah
if (targetMode === "LIVE" && targetUser.mfaEnabled) {
return NextResponse.json(
{
requireLogin: true,
error: `Akun ${targetUser.email} di mode Production mewajibkan verifikasi 2-langkah (MFA). Silakan login terlebih dahulu.`,
},
{ status: 401 }
);
}
const newSessionUser = {
id: targetUser.id,
email: targetUser.email,
name: targetUser.name,
role: targetUser.role,
envMode: targetMode,
};
const token = await signToken(newSessionUser);
const response = NextResponse.json({
success: true,
user: newSessionUser,
});
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
maxAge: 60 * 60 * 24,
};
response.cookies.set("erp_session", token, cookieOptions);
response.cookies.set("erp_env", targetMode, cookieOptions);
return response;
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
export async function PUT() {
return NextResponse.json(
{ error: "Mode Demo telah dinonaktifkan. Sistem berjalan penuh pada lingkungan Production." },
{ status: 400 }
);
}
+7 -10
View File
@@ -6,6 +6,7 @@ import {
checkRateLimit,
recordFailedAttempt,
clearRateLimit,
getAuthCookieOptions,
} from "@/lib/auth";
import {
generateMfaSecret,
@@ -14,6 +15,7 @@ import {
verifyTOTP,
verifyDynamicOtpHash,
} from "@/lib/mfa";
import { getDefaultLandingRoute } from "@/lib/permissions";
// GET: Fetch or reset MFA setup details for a user
export async function GET(req: Request) {
@@ -109,10 +111,10 @@ export async function POST(req: Request) {
where: { id: challenge.userId },
});
if (!user) {
if (!user || user.isActive === false) {
return NextResponse.json(
{ error: "Pengguna tidak ditemukan" },
{ status: 401 }
{ error: "Akun tidak ditemukan atau sedang dinonaktifkan oleh Administrator." },
{ status: 403 }
);
}
@@ -164,15 +166,10 @@ export async function POST(req: Request) {
const response = NextResponse.json({
success: true,
user: sessionUser,
defaultRoute: getDefaultLandingRoute(user.role),
});
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
maxAge: 60 * 60 * 24,
};
const cookieOptions = getAuthCookieOptions(req);
response.cookies.set("erp_session", token, cookieOptions);
response.cookies.set("erp_env", challenge.envMode, cookieOptions);
+229 -159
View File
@@ -3,33 +3,42 @@ import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { canViewPriceAndHpp } from "@/lib/permissions";
export async function GET() {
export async function GET(req: Request) {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
const { searchParams } = new URL(req.url);
const companyFilter = (searchParams.get("company") || "ALL").trim();
const isFilteredByCompany = companyFilter !== "" && companyFilter !== "ALL";
const canSeeFinance = ["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role);
const canSeeSalesMoney = ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT"].includes(user.role);
const canSeePurchaseMoney = ["ADMIN", "MANAGER", "PURCHASING", "ACCOUNTANT"].includes(user.role);
const canSeePrices = canViewPriceAndHpp(user.role);
const companyWhere = isFilteredByCompany ? { companyName: companyFilter } : {};
const [
products,
stockMovements,
salesOrders,
allSalesItems,
allPurchaseItems,
totalSalesAgg,
totalPurchasesAgg,
allSalesOrders,
allPurchaseOrders,
cashAccounts,
arAccount,
apAccount,
recentAudits,
deviceRecords,
allBatches,
] = await Promise.all([
prisma.product.findMany({
include: { stockItems: true },
include: {
stockItems: {
include: { warehouse: true },
},
},
}),
prisma.stockMovement.findMany({
where: companyWhere,
orderBy: { createdAt: "desc" },
include: {
product: true,
@@ -37,54 +46,100 @@ export async function GET() {
},
}),
prisma.salesOrder.findMany({
take: 5,
orderBy: { createdAt: "desc" },
where: {
status: { not: "CANCELLED" },
...companyWhere,
},
include: { customer: true },
orderBy: { createdAt: "desc" },
}),
prisma.salesOrderItem.findMany({
include: { salesOrder: true, product: true },
}),
prisma.purchaseOrderItem.findMany({
include: { purchaseOrder: true, product: true },
}),
prisma.salesOrder.aggregate({
_sum: { totalAmount: true },
_count: { id: true },
where: { status: { not: "CANCELLED" } },
}),
prisma.purchaseOrder.aggregate({
_sum: { totalAmount: true },
_count: { id: true },
where: { status: { not: "CANCELLED" } },
prisma.purchaseOrder.findMany({
where: {
status: { notIn: ["CANCELLED", "REJECTED"] },
...companyWhere,
},
include: { supplier: true },
orderBy: { createdAt: "desc" },
}),
prisma.account.findMany({
where: { type: "ASSET", code: { startsWith: "10" } },
where: {
type: "ASSET",
code: { startsWith: "10" },
...companyWhere,
},
}),
prisma.account.findFirst({ where: { code: "1101" } }),
prisma.account.findFirst({ where: { code: "2001" } }),
prisma.auditLog.findMany({
take: 6,
orderBy: { createdAt: "desc" },
...(user.role !== "ADMIN"
? {
where: {
NOT: [
{ action: { in: ["LOGIN", "LOGIN_MFA", "CREATE_USER", "UPDATE_USER"] } },
{ module: "AUTH" },
],
},
}
: {}),
prisma.deviceRecord.findMany({
where: companyWhere,
select: { condition: true },
}),
prisma.purchaseBatch.findMany({
select: {
productId: true,
remainingQty: true,
purchaseOrder: { select: { companyName: true, status: true } },
},
}),
]);
// Peta stok per PT dari Batch PO & mutasi manual (Gudang Utama dipakai bersama beberapa PT)
const batchByProdComp = new Map<string, Record<string, number>>();
for (const b of allBatches) {
if (b.purchaseOrder?.status !== "CANCELLED" && b.purchaseOrder?.status !== "REJECTED" && (b.remainingQty || 0) > 0) {
const comp = b.purchaseOrder?.companyName || "PT EnterpriseCore Utama";
if (!batchByProdComp.has(b.productId)) batchByProdComp.set(b.productId, {});
const map = batchByProdComp.get(b.productId)!;
map[comp] = (map[comp] || 0) + (b.remainingQty || 0);
}
}
const manualByProdComp = new Map<string, Record<string, number>>();
for (const m of stockMovements) {
if (m.referenceType !== "PURCHASE_ORDER" && m.referenceType !== "SALES_ORDER") {
const comp = m.companyName || "PT EnterpriseCore Utama";
if (!manualByProdComp.has(m.productId)) manualByProdComp.set(m.productId, {});
const map = manualByProdComp.get(m.productId)!;
const delta =
m.type === "IN"
? Math.abs(m.quantity)
: m.type === "OUT"
? -Math.abs(m.quantity)
: m.quantity;
map[comp] = (map[comp] || 0) + delta;
}
}
// 1. Ringkasan Stok & Peringatan Stok Menipis
let totalInventoryValue = 0;
let totalStockUnits = 0;
const lowStockAlerts: any[] = [];
const lowStockAlerts: {
id: string;
sku: string;
name: string;
currentStock: number;
minStock: number;
unit: string;
}[] = [];
products.forEach((p) => {
if (p.isService) return; // Layanan / Non-Fisik tidak dihitung stok fisik gudang
const units = p.stockItems.reduce((acc, curr) => acc + curr.quantity, 0);
if (p.isService) return;
let units = 0;
if (!isFilteredByCompany) {
units = p.stockItems.reduce((acc, curr) => acc + curr.quantity, 0);
} else {
const bMap = batchByProdComp.get(p.id) || {};
const mMap = manualByProdComp.get(p.id) || {};
const hasTracked = Object.keys(bMap).length > 0 || Object.keys(mMap).length > 0;
if (hasTracked) {
units = Math.max(0, (bMap[companyFilter] || 0) + (mMap[companyFilter] || 0));
} else {
units = p.stockItems
.filter(
(s) =>
(s.warehouse?.companyName || "PT EnterpriseCore Utama") === companyFilter
)
.reduce((acc, curr) => acc + curr.quantity, 0);
}
}
totalStockUnits += units;
totalInventoryValue += units * p.purchasePrice;
@@ -100,7 +155,7 @@ export async function GET() {
}
});
// Hitung total keluar masuk barang dari StockMovement + PO/SO
// 2. Keluar-Masuk Barang
let stockInUnits = 0;
let stockInCount = 0;
let stockOutUnits = 0;
@@ -116,28 +171,71 @@ export async function GET() {
}
});
// Jika belum ada StockMovement tetapi ada SO/PO (misal dari data seed awal), tambahkan ke hitungan
if (stockOutUnits === 0 && allSalesItems.length > 0) {
allSalesItems.forEach((item) => {
if (item.salesOrder.status !== "CANCELLED") {
stockOutUnits += item.quantity;
stockOutCount += 1;
}
});
}
// 3. Ringkasan Keuangan Real dari Transaksi SO & PO
const totalRevenue = allSalesOrders.reduce((s, o) => s + (o.totalAmount || 0), 0);
const totalHpp = allSalesOrders.reduce((s, o) => s + (o.totalHpp || 0), 0);
const grossProfit = totalRevenue - totalHpp;
const grossMarginPct = totalRevenue > 0 ? Math.round((grossProfit / totalRevenue) * 100) : 0;
if (stockInUnits === 0 && allPurchaseItems.length > 0) {
allPurchaseItems.forEach((item) => {
if (item.purchaseOrder.status === "RECEIVED") {
stockInUnits += item.quantity;
stockInCount += 1;
let receivables = 0;
let unpaidSalesCount = 0;
let pendingShipmentsCount = 0;
allSalesOrders.forEach((o) => {
if (o.paymentStatus !== "PAID") {
const paid = o.paidAmount || 0;
const remaining = Math.max(0, (o.totalAmount || 0) - paid);
if (remaining > 0) {
receivables += remaining;
unpaidSalesCount += 1;
}
});
}
}
if (o.status === "CONFIRMED") {
pendingShipmentsCount += 1;
}
});
const totalPurchases = allPurchaseOrders.reduce((s, p) => s + (p.totalAmount || 0), 0);
let payables = 0;
let unpaidPoCount = 0;
let pendingFinancePoCount = 0;
allPurchaseOrders.forEach((p) => {
if (p.status === "PENDING_FINANCE" || p.status === "ON_HOLD") {
pendingFinancePoCount += 1;
}
if (p.paymentStatus !== "PAID") {
const paid = p.paidAmount || 0;
const remaining = Math.max(0, (p.totalAmount || 0) - paid);
if (remaining > 0) {
payables += remaining;
unpaidPoCount += 1;
}
}
});
const totalCashBank = cashAccounts.reduce((acc, curr) => acc + curr.balance, 0);
// 1. Agregasi Tren Bulanan (Financial & Stock Trends 6 Bulan Terakhir)
// Rincian saldo Kas & Bank per PT agar Management/Finance bisa melihat saldo tiap PT secara akurat
const cashByCompanyMap = new Map<string, number>();
for (const acc of cashAccounts) {
const comp = acc.companyName || "PT EnterpriseCore Utama";
cashByCompanyMap.set(comp, (cashByCompanyMap.get(comp) || 0) + (acc.balance || 0));
}
const cashByCompany = Array.from(cashByCompanyMap.entries())
.map(([companyName, balance]) => ({ companyName, balance }))
.sort((a, b) => a.companyName.localeCompare(b.companyName));
// 4. Ringkasan Kondisi Device (Service, Kanibalan, Rusak Total)
const deviceSummary = {
inService: deviceRecords.filter((d) => d.condition === "IN_SERVICE").length,
servicedOk: deviceRecords.filter((d) => d.condition === "SERVICED_OK").length,
cannibalized: deviceRecords.filter((d) => d.condition === "CANNIBALIZED").length,
damaged: deviceRecords.filter((d) => d.condition === "DAMAGED_UNUSABLE").length,
total: deviceRecords.length,
};
// 5. Tren 6 Bulan Terakhir (untuk Grafik)
const monthNames = ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des"];
const now = new Date();
const trendMonths: { year: number; month: number; key: string; label: string }[] = [];
@@ -153,16 +251,6 @@ export async function GET() {
});
}
const allSalesList = await prisma.salesOrder.findMany({
where: { status: { not: "CANCELLED" } },
select: { createdAt: true, totalAmount: true, totalHpp: true },
});
const allPurchasesList = await prisma.purchaseOrder.findMany({
where: { status: { not: "CANCELLED" } },
select: { createdAt: true, totalAmount: true },
});
const monthlyTrends = trendMonths.map((tm) => {
let sales = 0;
let hpp = 0;
@@ -170,7 +258,7 @@ export async function GET() {
let sIn = 0;
let sOut = 0;
allSalesList.forEach((s) => {
allSalesOrders.forEach((s) => {
const d = new Date(s.createdAt);
if (d.getFullYear() === tm.year && d.getMonth() === tm.month) {
sales += s.totalAmount || 0;
@@ -178,7 +266,7 @@ export async function GET() {
}
});
allPurchasesList.forEach((p) => {
allPurchaseOrders.forEach((p) => {
const d = new Date(p.createdAt);
if (d.getFullYear() === tm.year && d.getMonth() === tm.month) {
purchases += p.totalAmount || 0;
@@ -196,112 +284,94 @@ export async function GET() {
}
});
const effectiveHpp = hpp > 0 ? hpp : (sales > 0 && purchases > 0 ? Math.min(sales * 0.7, purchases) : 0);
const grossProfit = sales - effectiveHpp;
const effectiveHpp = hpp > 0 ? hpp : 0;
return {
key: tm.key,
label: tm.label,
sales: canSeePrices ? sales : 0,
purchases: canSeePrices ? purchases : 0,
hpp: canSeePrices ? effectiveHpp : 0,
grossProfit: canSeePrices ? grossProfit : 0,
sales: canSeeSalesMoney ? sales : 0,
purchases: canSeePurchaseMoney ? purchases : 0,
hpp: canSeeSalesMoney ? effectiveHpp : 0,
grossProfit: canSeeSalesMoney ? sales - effectiveHpp : 0,
stockInUnits: sIn,
stockOutUnits: sOut,
};
});
// 2. Alur Transparansi Barang (Beli -> Masuk Gudang -> Jual & PO Customer -> Margin HPP)
const productFlowTransparency = products.map((p) => {
const units = p.stockItems.reduce((acc, curr) => acc + curr.quantity, 0);
const profitPerUnit = p.sellingPrice - p.purchasePrice;
const marginPct = p.purchasePrice > 0 ? Math.round((profitPerUnit / p.purchasePrice) * 100) : 100;
// Filter pembelian produk ini
const prodPurchases = allPurchaseItems.filter((item) => item.productId === p.id);
const totalInUnits = prodPurchases.reduce((acc, curr) => acc + curr.quantity, 0);
// Filter penjualan produk ini
const prodSales = allSalesItems.filter((item) => item.productId === p.id);
const totalOutUnits = prodSales.reduce((acc, curr) => acc + curr.quantity, 0);
// Cari No. PO Customer terbaru yang membeli barang ini
const latestSaleWithCustPo = prodSales
.filter((item) => item.salesOrder?.customerPoNumber)
.sort((a, b) => new Date(b.salesOrder.createdAt).getTime() - new Date(a.salesOrder.createdAt).getTime())[0];
// Cari No. PO Pemasok terbaru
const latestPoPurchase = prodPurchases
.sort((a, b) => new Date(b.purchaseOrder.createdAt).getTime() - new Date(a.purchaseOrder.createdAt).getTime())[0];
return {
id: p.id,
sku: p.sku,
name: p.name,
unit: p.unit,
purchasePrice: canSeePrices ? p.purchasePrice : 0,
sellingPrice: canSeePrices ? p.sellingPrice : 0,
profitPerUnit: canSeePrices ? profitPerUnit : 0,
marginPct,
currentStock: units,
stockValue: canSeePrices ? units * p.purchasePrice : 0,
totalInUnits,
totalOutUnits,
lastCustomerPo: latestSaleWithCustPo?.salesOrder?.customerPoNumber || null,
lastSoNumber: latestSaleWithCustPo?.salesOrder?.orderNumber || (prodSales[0]?.salesOrder?.orderNumber || null),
lastSupplierPo: latestPoPurchase?.purchaseOrder?.poNumber || null,
};
});
// 3. Mutasi Stok terbaru dengan informasi referensi No. PO Customer
const soRefIds = stockMovements
.slice(0, 10)
.filter((m) => m.referenceType === "SALES_ORDER" && m.referenceId)
.map((m) => m.referenceId as string);
const relatedSOs = soRefIds.length > 0
? await prisma.salesOrder.findMany({
where: { orderNumber: { in: soRefIds } },
select: { orderNumber: true, customerPoNumber: true, invoiceNumber: true },
})
const recentSalesOrders = canSeeSalesMoney
? allSalesOrders.slice(0, 5).map((o) => ({
id: o.id,
orderNumber: o.orderNumber,
customerPoNumber: o.customerPoNumber,
customerName: o.customer?.company || o.customer?.name || "-",
companyName: o.companyName || "-",
status: o.status,
paymentStatus: o.paymentStatus,
totalAmount: o.totalAmount,
createdAt: o.createdAt,
}))
: [];
const soMap = new Map(relatedSOs.map((so) => [so.orderNumber, so]));
const recentPurchaseOrders = canSeePurchaseMoney
? allPurchaseOrders.slice(0, 5).map((p) => ({
id: p.id,
poNumber: p.poNumber,
supplierName: p.supplier?.name || "-",
companyName: p.companyName || "-",
status: p.status,
paymentStatus: p.paymentStatus,
totalAmount: p.totalAmount,
createdAt: p.createdAt,
}))
: [];
const enrichedRecentMovements = stockMovements.slice(0, 10).map((m) => {
const so = m.referenceId ? soMap.get(m.referenceId) : null;
return {
...m,
customerPoNumber: so?.customerPoNumber || null,
invoiceNumber: so?.invoiceNumber || null,
};
});
const recentMovements = stockMovements.slice(0, 5).map((m) => ({
id: m.id,
type: m.type,
outboundCategory: m.outboundCategory,
quantity: m.quantity,
referenceId: m.referenceId,
createdAt: m.createdAt,
productName: m.product?.name || "-",
productUnit: m.product?.unit || "UNIT",
warehouseName: m.warehouse?.name || "Gudang Utama",
}));
return NextResponse.json({
metrics: {
totalRevenue: canSeePrices ? totalSalesAgg._sum.totalAmount || 0 : 0,
totalSalesCount: totalSalesAgg._count.id || 0,
totalPurchases: canSeePrices ? totalPurchasesAgg._sum.totalAmount || 0 : 0,
totalPurchasesCount: totalPurchasesAgg._count.id || 0,
inventoryValue: canSeePrices ? totalInventoryValue : 0,
totalRevenue: canSeeSalesMoney ? totalRevenue : 0,
totalSalesCount: canSeeSalesMoney || user.role === "INVENTORY" ? allSalesOrders.length : 0,
totalHpp: canSeeSalesMoney ? totalHpp : 0,
grossProfit: canSeeSalesMoney ? grossProfit : 0,
grossMarginPct: canSeeSalesMoney ? grossMarginPct : 0,
totalPurchases: canSeePurchaseMoney ? totalPurchases : 0,
totalPurchasesCount: canSeePurchaseMoney || user.role === "INVENTORY" ? allPurchaseOrders.length : 0,
inventoryValue: canSeeFinance ? totalInventoryValue : 0,
totalStockUnits,
totalProductsCount: products.length,
totalProductsCount: products.filter((p) => !p.isService).length,
stockInUnits,
stockInCount,
stockOutUnits,
stockOutCount,
totalCashBank: canSeeFinance ? totalCashBank : 0,
receivables: canSeeFinance ? arAccount?.balance || 0 : 0,
payables: canSeeFinance ? apAccount?.balance || 0 : 0,
receivables: canSeeSalesMoney ? receivables : 0,
unpaidSalesCount: canSeeSalesMoney ? unpaidSalesCount : 0,
payables: canSeeFinance || user.role === "PURCHASING" ? payables : 0,
unpaidPoCount: canSeeFinance || user.role === "PURCHASING" ? unpaidPoCount : 0,
pendingFinancePoCount: canSeeFinance || user.role === "PURCHASING" ? pendingFinancePoCount : 0,
pendingShipmentsCount: canSeeSalesMoney || user.role === "INVENTORY" ? pendingShipmentsCount : 0,
},
lowStockAlerts,
monthlyTrends: canSeePrices ? monthlyTrends : [],
productFlowTransparency,
recentSalesOrders: canSeePrices ? salesOrders : [],
recentMovements: enrichedRecentMovements,
recentAudits: ["ADMIN", "MANAGER"].includes(user.role) ? recentAudits : [],
cashByCompany: canSeeFinance ? cashByCompany : [],
deviceSummary,
lowStockAlerts: lowStockAlerts.slice(0, 6),
lowStockTotal: lowStockAlerts.length,
monthlyTrends: canSeeSalesMoney || canSeePurchaseMoney ? monthlyTrends : [],
recentSalesOrders,
recentPurchaseOrders,
recentMovements,
canSeePrices,
canSeeFinance,
canSeeSalesMoney,
canSeePurchaseMoney,
});
} catch (error: any) {
console.error("Dashboard API error:", error);
+547
View File
@@ -0,0 +1,547 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { logAudit } from "@/lib/audit";
import { dispatchNotification } from "@/lib/notifier";
const VALID_CONDITIONS = new Set([
"IN_SERVICE",
"SERVICED_OK",
"DAMAGED_UNUSABLE",
"CANNIBALIZED",
"REPLACED_WARRANTY",
]);
const VALID_ORIGINS = new Set([
"WARRANTY_FREE",
"WARRANTY_REPLACE",
"PAID_SERVICE",
"WAREHOUSE_DEFECT",
]);
function splitSerialNumbers(raw: string): string[] {
if (!raw) return [];
return Array.from(
new Set(
String(raw)
.split(/[\n,;]+/)
.map((s) => s.trim())
.filter(Boolean)
)
);
}
export async function GET() {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
if (
!["ADMIN", "MANAGER", "INVENTORY", "SALES", "PURCHASING", "ACCOUNTANT"].includes(
user.role
)
) {
return NextResponse.json(
{ error: `Akses ditolak: Peran ${user.role} tidak memiliki izin melihat catatan device.` },
{ status: 403 }
);
}
const canSeeMoney = ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT"].includes(user.role);
const [records, customers] = await Promise.all([
prisma.deviceRecord.findMany({
include: {
product: {
select: {
id: true,
sku: true,
name: true,
unit: true,
isService: true,
},
},
customer: {
select: {
id: true,
code: true,
name: true,
company: true,
},
},
},
orderBy: { updatedAt: "desc" },
}),
prisma.customer.findMany({
select: { id: true, code: true, name: true, company: true },
orderBy: { name: "asc" },
}),
]);
const sanitizedRecords = canSeeMoney
? records
: records.map((r) => ({
...r,
serviceFee: 0,
}));
return NextResponse.json({
records: sanitizedRecords,
customers,
canSeeMoney,
});
} catch (error: any) {
console.error("Devices GET error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
export async function POST(req: Request) {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
if (!["ADMIN", "MANAGER", "INVENTORY", "SALES"].includes(user.role)) {
return NextResponse.json(
{
error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang mencatat kondisi device.`,
},
{ status: 403 }
);
}
const body = await req.json();
const {
serialNumbers,
serialNumber,
productId,
customerId,
salesOrderNumber,
companyName,
condition = "IN_SERVICE",
serviceOrigin = "WAREHOUSE_DEFECT",
warrantyStatus,
serviceFee,
returnShippingCost,
returnCourierName,
returnTrackingNumber,
damageDescription,
actionTaken,
salvagedParts,
deductWarehouseStock = false,
warehouseId,
} = body;
if (!productId) {
return NextResponse.json({ error: "Produk / perangkat wajib dipilih" }, { status: 400 });
}
const snList = splitSerialNumbers(serialNumbers || serialNumber || "");
if (snList.length === 0) {
return NextResponse.json(
{ error: "Minimal 1 Serial Number (SN) perangkat wajib diisi (ketik manual atau upload Excel)" },
{ status: 400 }
);
}
if (!damageDescription || !String(damageDescription).trim()) {
return NextResponse.json(
{ error: "Deskripsi kerusakan / kondisi device wajib diisi" },
{ status: 400 }
);
}
const finalOrigin = VALID_ORIGINS.has(serviceOrigin) ? serviceOrigin : "WAREHOUSE_DEFECT";
const finalCondition = VALID_CONDITIONS.has(condition) ? condition : "IN_SERVICE";
// Aturan bisnis: Saat pilih Ganti Unit (WARRANTY_REPLACE), kondisi unit lama HANYA boleh Rusak Total atau Kanibalan!
if (
finalOrigin === "WARRANTY_REPLACE" &&
!["DAMAGED_UNUSABLE", "CANNIBALIZED"].includes(finalCondition)
) {
return NextResponse.json(
{
error:
"Untuk kategori Ganti Unit (Tukar Unit Garansi), kondisi device lama hanya boleh Rusak Total (Tidak Bisa Dipakai) atau Unit Kanibalan.",
},
{ status: 400 }
);
}
const product = await prisma.product.findUnique({ where: { id: productId } });
if (!product) {
return NextResponse.json({ error: "Produk tidak ditemukan" }, { status: 404 });
}
const cleanCompany = (companyName || "").trim() || "PT EnterpriseCore Utama";
const canSetFee = ["ADMIN", "MANAGER", "SALES"].includes(user.role);
const cleanFee =
canSetFee && finalOrigin === "PAID_SERVICE"
? Math.max(0, parseFloat(serviceFee) || 0)
: 0;
const cleanReturnShipping = Math.max(0, parseFloat(returnShippingCost) || 0);
const cleanReturnCourier = returnCourierName ? String(returnCourierName).trim() : null;
const cleanReturnTracking = returnTrackingNumber ? String(returnTrackingNumber).trim() : null;
const finalPayStatus = cleanFee + cleanReturnShipping > 0 ? "UNPAID" : "FREE";
const finalWarrantyStatus =
warrantyStatus ||
(finalOrigin === "WARRANTY_FREE" || finalOrigin === "WARRANTY_REPLACE"
? "IN_WARRANTY"
: finalOrigin === "PAID_SERVICE"
? "OUT_OF_WARRANTY"
: "INTERNAL");
// Jika diminta memotong stok fisik gudang (khusus Gudang/Admin/Manager untuk barang rusak/kanibalan internal)
const shouldDeductStock =
Boolean(deductWarehouseStock) &&
!product.isService &&
["ADMIN", "MANAGER", "INVENTORY"].includes(user.role) &&
(finalCondition === "DAMAGED_UNUSABLE" || finalCondition === "CANNIBALIZED");
if (shouldDeductStock) {
const defaultWh = await prisma.warehouse.findFirst();
const targetWhId = warehouseId || defaultWh?.id;
if (!targetWhId) {
return NextResponse.json({ error: "Gudang tidak ditemukan" }, { status: 400 });
}
const stockItem = await prisma.stockItem.findUnique({
where: { productId_warehouseId: { productId: product.id, warehouseId: targetWhId } },
});
if (!stockItem || stockItem.quantity < snList.length) {
return NextResponse.json(
{
error: `Stok gudang untuk ${product.name} tidak mencukupi untuk dipotong (Tersedia: ${
stockItem?.quantity || 0
}, SN dicatat: ${snList.length}). Hilangkan centang potong stok jika barang sudah keluar/bukan dari stok aktif.`,
},
{ status: 400 }
);
}
await prisma.stockItem.update({
where: { id: stockItem.id },
data: { quantity: stockItem.quantity - snList.length },
});
const outCat = finalCondition === "CANNIBALIZED" ? "KANIBALAN" : "RUSAK_AFKIR";
await prisma.stockMovement.create({
data: {
productId: product.id,
warehouseId: targetWhId,
type: "OUT",
outboundCategory: outCat,
quantity: snList.length,
referenceType: "DEVICE_RECORD",
referenceId: salesOrderNumber ? String(salesOrderNumber).trim() : outCat,
companyName: cleanCompany,
serialNumbers: snList.join(", "),
notes: `[${
finalCondition === "CANNIBALIZED"
? "Unit Kanibalan / Sparepart"
: "Barang Rusak Total / Tidak Bisa Dipakai"
}] ${snList.length} ${product.unit} ${product.name}. Kerusakan: ${String(
damageDescription
).trim()}${salvagedParts ? ` | Sparepart Kanibalan: ${String(salvagedParts).trim()}` : ""}`,
},
});
}
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const baseCount = await prisma.deviceRecord.count();
const createdRecords = [];
for (let idx = 0; idx < snList.length; idx++) {
const sn = snList[idx];
const recNo = `DEV-${dateStr}-${String(baseCount + idx + 1).padStart(4, "0")}-${Math.floor(
10 + Math.random() * 89
)}`;
const rec = await prisma.deviceRecord.create({
data: {
recordNumber: recNo,
serialNumber: sn,
productId: product.id,
customerId: customerId || null,
salesOrderNumber: salesOrderNumber ? String(salesOrderNumber).trim() : null,
companyName: cleanCompany,
condition: finalCondition,
serviceOrigin: finalOrigin,
warrantyStatus: finalWarrantyStatus,
serviceFee: cleanFee,
returnShippingCost: cleanReturnShipping,
returnCourierName: cleanReturnCourier,
returnTrackingNumber: cleanReturnTracking,
servicePaymentStatus: finalPayStatus,
damageDescription: String(damageDescription).trim(),
actionTaken: actionTaken ? String(actionTaken).trim() : null,
salvagedParts: salvagedParts ? String(salvagedParts).trim() : null,
stockAdjusted: shouldDeductStock,
recordedBy: user.name,
},
include: { product: true, customer: true },
});
createdRecords.push(rec);
}
await logAudit({
userId: user.id,
userName: user.name,
action: "CREATE_DEVICE_RECORD",
module: "INVENTORY",
description: `[${user.role}] Mencatat ${createdRecords.length} unit device (${product.name}) status ${finalCondition} | SN: ${snList
.slice(0, 5)
.join(", ")}${snList.length > 5 ? ` (+${snList.length - 5} lainnya)` : ""}${
shouldDeductStock ? " [Stok Gudang Dipotong]" : ""
}`,
metadata: {
productId: product.id,
condition: finalCondition,
serviceOrigin: finalOrigin,
count: createdRecords.length,
stockAdjusted: shouldDeductStock,
},
});
return NextResponse.json({
success: true,
count: createdRecords.length,
records: createdRecords,
});
} catch (error: any) {
console.error("Devices POST error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
export async function PUT(req: Request) {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
if (!["ADMIN", "MANAGER", "INVENTORY", "SALES", "ACCOUNTANT"].includes(user.role)) {
return NextResponse.json(
{
error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang memperbarui catatan device.`,
},
{ status: 403 }
);
}
const body = await req.json();
const {
id,
condition,
damageDescription,
actionTaken,
salvagedParts,
serviceOrigin,
serviceFee,
returnShippingCost,
returnCourierName,
returnTrackingNumber,
servicePaymentStatus,
} = body;
if (!id) {
return NextResponse.json({ error: "ID catatan device wajib disertakan" }, { status: 400 });
}
const existing = await prisma.deviceRecord.findUnique({
where: { id },
include: { product: true },
});
if (!existing) {
return NextResponse.json({ error: "Catatan device tidak ditemukan" }, { status: 404 });
}
const canEditMoney = ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT"].includes(user.role);
const canConfirmPay = ["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role);
const effectiveOrigin =
serviceOrigin && VALID_ORIGINS.has(serviceOrigin) ? serviceOrigin : existing.serviceOrigin;
if (
effectiveOrigin === "WARRANTY_REPLACE" &&
condition &&
!["DAMAGED_UNUSABLE", "CANNIBALIZED"].includes(condition)
) {
return NextResponse.json(
{
error:
"Untuk kategori Ganti Unit (Tukar Unit Garansi), kondisi device lama hanya boleh Rusak Total (Tidak Bisa Dipakai) atau Unit Kanibalan.",
},
{ status: 400 }
);
}
const updateData: any = {};
if (condition && VALID_CONDITIONS.has(condition)) {
updateData.condition = condition;
}
if (serviceOrigin && VALID_ORIGINS.has(serviceOrigin)) {
updateData.serviceOrigin = serviceOrigin;
}
if (damageDescription !== undefined) {
updateData.damageDescription = String(damageDescription).trim() || existing.damageDescription;
}
if (actionTaken !== undefined) {
updateData.actionTaken = String(actionTaken).trim() || null;
}
if (salvagedParts !== undefined) {
updateData.salvagedParts = String(salvagedParts).trim() || null;
}
if (canEditMoney && serviceFee !== undefined) {
updateData.serviceFee = Math.max(0, parseFloat(serviceFee) || 0);
}
if (returnShippingCost !== undefined) {
updateData.returnShippingCost = Math.max(0, parseFloat(returnShippingCost) || 0);
}
if (returnCourierName !== undefined) {
updateData.returnCourierName = String(returnCourierName).trim() || null;
}
if (returnTrackingNumber !== undefined) {
updateData.returnTrackingNumber = String(returnTrackingNumber).trim() || null;
}
const nextFee = updateData.serviceFee !== undefined ? updateData.serviceFee : existing.serviceFee || 0;
const nextReturnShip =
updateData.returnShippingCost !== undefined
? updateData.returnShippingCost
: existing.returnShippingCost || 0;
const prevTotal = (existing.serviceFee || 0) + (existing.returnShippingCost || 0);
const nextTotal = nextFee + nextReturnShip;
if (canConfirmPay && servicePaymentStatus && ["FREE", "UNPAID", "PAID"].includes(servicePaymentStatus)) {
updateData.servicePaymentStatus = servicePaymentStatus;
} else if (nextTotal !== prevTotal) {
updateData.servicePaymentStatus = nextTotal > 0 ? "UNPAID" : "FREE";
}
const updated = await prisma.deviceRecord.update({
where: { id },
data: updateData,
include: { product: true, customer: true },
});
// Sinkronkan balik ke SalesOrderItem jika device ini berasal dari Sales Order (termasuk status selesai & ongkir balik ditanggung user)
if (existing.salesOrderId) {
const mappedSoStatus =
updated.condition === "SERVICED_OK"
? "SERVICED_RETURNED"
: updated.condition === "IN_SERVICE"
? "IN_SERVICE"
: updated.condition === "DAMAGED_UNUSABLE"
? "DAMAGED_UNUSABLE"
: updated.condition === "CANNIBALIZED"
? "CANNIBALIZED"
: undefined;
await prisma.salesOrderItem.updateMany({
where: {
salesOrderId: existing.salesOrderId,
productId: existing.productId,
},
data: {
...(mappedSoStatus && existing.serviceOrigin !== "WARRANTY_REPLACE"
? { serviceStatus: mappedSoStatus }
: {}),
returnShippingCost: updated.returnShippingCost,
returnCourierName: updated.returnCourierName,
returnTrackingNumber: updated.returnTrackingNumber,
servicePaymentStatus: updated.servicePaymentStatus,
},
});
}
await logAudit({
userId: user.id,
userName: user.name,
action: "UPDATE_DEVICE_RECORD",
module: "INVENTORY",
description: `[${user.role}] Memperbarui status device ${existing.recordNumber} (SN: ${existing.serialNumber} - ${existing.product.name}) menjadi ${updated.condition}${updated.returnShippingCost > 0 ? ` | Ongkir Balik (Ditanggung User): Rp ${updated.returnShippingCost.toLocaleString("id-ID")}` : ""}`,
metadata: {
id,
serialNumber: existing.serialNumber,
condition: updated.condition,
returnShippingCost: updated.returnShippingCost,
returnCourierName: updated.returnCourierName,
returnTrackingNumber: updated.returnTrackingNumber,
},
});
await dispatchNotification({
type: "RMA_SERVICE",
title: `Update Status Device (${updated.condition}): ${existing.serialNumber}`,
message: `${user.name} (${user.role}) memperbarui status perangkat ${existing.product.name} (SN: ${existing.serialNumber}, Ref: ${existing.recordNumber}) menjadi ${updated.condition}.${updated.actionTaken ? `\nTindakan: ${updated.actionTaken}` : ""}${updated.returnShippingCost > 0 ? `\nOngkir Kirim Balik (Ditanggung User): Rp ${updated.returnShippingCost.toLocaleString("id-ID")}${updated.returnCourierName ? ` via ${updated.returnCourierName}` : ""}${updated.returnTrackingNumber ? ` [Resi: ${updated.returnTrackingNumber}]` : ""}` : ""}`,
targetRoles: ["ADMIN", "MANAGER", "SALES", "INVENTORY"],
});
if (updated.returnShippingCost > 0 && updated.servicePaymentStatus === "UNPAID") {
await dispatchNotification({
type: "MONEY_IN",
title: `Tagihan Ongkir Balik Service: ${existing.recordNumber}`,
message: `Perangkat ${existing.product.name} (SN: ${existing.serialNumber}) memiliki tagihan ongkir kirim balik Rp ${updated.returnShippingCost.toLocaleString("id-ID")} (ditanggung user). Menunggu konfirmasi pembayaran Finance.`,
targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "SALES"],
});
}
return NextResponse.json({ success: true, record: updated });
} catch (error: any) {
console.error("Devices PUT error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
export async function DELETE(req: Request) {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
if (!["ADMIN", "MANAGER", "INVENTORY"].includes(user.role)) {
return NextResponse.json(
{
error:
"Akses ditolak: Hanya Admin, Manager, atau Gudang (Inventory) yang dapat menghapus catatan device.",
},
{ status: 403 }
);
}
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) {
return NextResponse.json({ error: "ID catatan device wajib disertakan" }, { status: 400 });
}
const existing = await prisma.deviceRecord.findUnique({
where: { id },
include: { product: true },
});
if (!existing) {
return NextResponse.json({ error: "Catatan device tidak ditemukan" }, { status: 404 });
}
await prisma.deviceRecord.delete({ where: { id } });
await logAudit({
userId: user.id,
userName: user.name,
action: "DELETE_DEVICE_RECORD",
module: "INVENTORY",
description: `[${user.role}] Menghapus catatan device ${existing.recordNumber} (SN: ${existing.serialNumber} - ${existing.product.name})`,
});
return NextResponse.json({ success: true, message: `Catatan device ${existing.serialNumber} berhasil dihapus.` });
} catch (error: any) {
console.error("Devices DELETE error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
+65 -3
View File
@@ -25,6 +25,8 @@ export async function GET() {
savedEmployees,
posSetting,
compSetting,
openSalesOrders,
openPurchaseOrders,
] = await Promise.all([
prisma.account.findMany({
orderBy: { code: "asc" },
@@ -52,6 +54,16 @@ export async function GET() {
prisma.systemSetting.findUnique({
where: { key: "PAYROLL_COMPANIES" },
}),
prisma.salesOrder.findMany({
where: { status: { not: "CANCELLED" }, paymentStatus: { not: "PAID" } },
include: { customer: true },
orderBy: { orderDate: "asc" },
}),
prisma.purchaseOrder.findMany({
where: { status: { notIn: ["CANCELLED", "REJECTED"] }, paymentStatus: { not: "PAID" } },
include: { supplier: true },
orderBy: { orderDate: "asc" },
}),
]);
// Gabungkan daftar karyawan dari PayrollEmployee dan riwayat PayrollRecord (terpisah dari user login RBAC)
@@ -126,6 +138,51 @@ export async function GET() {
payrollRecords.forEach((r) => r.companyName && compSet.add(r.companyName));
const companies = Array.from(compSet);
const nowMs = Date.now();
const arList = openSalesOrders
.map((so) => {
const remaining = Math.max(0, (so.totalAmount || 0) - (so.paidAmount || 0));
const ageDays = Math.max(
0,
Math.floor((nowMs - new Date(so.orderDate || so.createdAt).getTime()) / (1000 * 60 * 60 * 24))
);
return {
id: so.id,
number: so.orderNumber,
counterparty: so.customer?.company || so.customer?.name || "-",
companyName: so.companyName || "PT EnterpriseCore Utama",
orderDate: so.orderDate || so.createdAt,
totalAmount: so.totalAmount || 0,
paidAmount: so.paidAmount || 0,
remaining,
paymentStatus: so.paymentStatus,
ageDays,
};
})
.filter((x) => x.remaining > 0);
const apList = openPurchaseOrders
.map((po) => {
const remaining = Math.max(0, (po.totalAmount || 0) - (po.paidAmount || 0));
const ageDays = Math.max(
0,
Math.floor((nowMs - new Date(po.orderDate || po.createdAt).getTime()) / (1000 * 60 * 60 * 24))
);
return {
id: po.id,
number: po.poNumber,
counterparty: po.supplier?.name || "-",
companyName: po.companyName || "PT EnterpriseCore Utama",
orderDate: po.orderDate || po.createdAt,
totalAmount: po.totalAmount || 0,
paidAmount: po.paidAmount || 0,
remaining,
paymentStatus: po.paymentStatus,
ageDays,
};
})
.filter((x) => x.remaining > 0);
return NextResponse.json({
accounts,
journalEntries,
@@ -133,6 +190,8 @@ export async function GET() {
payrollEmployees,
positions,
companies,
arList,
apList,
});
} catch (error: any) {
console.error("Finance GET error:", error);
@@ -336,6 +395,7 @@ export async function POST(req: Request) {
const duplicate = await prisma.account.findFirst({
where: {
code,
companyName,
NOT: { id },
},
});
@@ -402,7 +462,9 @@ export async function POST(req: Request) {
"1002",
"1101",
"1201",
"1301",
"2001",
"2101",
"3001",
"4001",
"5001",
@@ -720,7 +782,7 @@ export async function POST(req: Request) {
const expenseAcc = await prisma.account.findFirst({ where: { code: "6001", companyName: cleanCompany } });
if (expenseAcc && cashAcc) {
const jCount = await prisma.journalEntry.count();
const entryNumber = `JV-PAY-${String(jCount + 1).padStart(4, "0")}`;
const entryNumber = `JV-PAY-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`;
const desc = `[${cleanCompany}] Pembayaran Payroll & Uang Makan ${cleanName} [${cleanRole}] (${
period || existing.period
}) — Hadir: ${wDays} hr, Absen: ${aDays} hr`;
@@ -1038,7 +1100,7 @@ export async function POST(req: Request) {
if (expenseAcc && cashAcc) {
const jCount = await prisma.journalEntry.count();
const entryNumber = `JV-PAY-${String(jCount + 1).padStart(4, "0")}`;
const entryNumber = `JV-PAY-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`;
const desc = `[${cleanCompany}] Pembayaran Payroll & Uang Makan ${cleanName} [${cleanPosition}] (${period}) — Hadir: ${wDays} hr, Absen: ${aDays} hr`;
await prisma.journalEntry.create({
@@ -1124,7 +1186,7 @@ export async function POST(req: Request) {
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const count = await prisma.journalEntry.count();
const entryNumber = `JV-${dateStr}-${String(count + 1).padStart(4, "0")}`;
const entryNumber = `JV-${dateStr}-${Date.now().toString().slice(-4)}-${String(count + 1).padStart(3, "0")}`;
const journal = await prisma.journalEntry.create({
data: {
+168 -30
View File
@@ -6,6 +6,18 @@ import { dispatchNotification } from "@/lib/notifier";
import { canViewPriceAndHpp } from "@/lib/permissions";
import { getSavedCompanies } from "@/lib/companies";
function parseSnTokens(raw?: string | null): string[] {
if (!raw) return [];
return Array.from(
new Set(
String(raw)
.split(/[\n,;]+/)
.map((s) => s.trim())
.filter(Boolean)
)
);
}
export async function GET() {
try {
const user = await getCurrentUser();
@@ -15,34 +27,115 @@ export async function GET() {
const canSeePrices = canViewPriceAndHpp(user.role);
const products = await prisma.product.findMany({
include: {
category: true,
stockItems: {
const [products, warehouses, categories, rawMovements, allMovementsForCalc, allBatches] =
await Promise.all([
prisma.product.findMany({
include: {
category: true,
stockItems: {
include: {
warehouse: true,
},
},
},
orderBy: { createdAt: "desc" },
}),
prisma.warehouse.findMany({
orderBy: { name: "asc" },
}),
prisma.category.findMany({
orderBy: { name: "asc" },
}),
prisma.stockMovement.findMany({
take: 100,
orderBy: { createdAt: "desc" },
include: {
product: true,
warehouse: true,
},
},
},
orderBy: { createdAt: "desc" },
});
}),
prisma.stockMovement.findMany({
select: {
productId: true,
type: true,
quantity: true,
referenceType: true,
companyName: true,
serialNumbers: true,
createdAt: true,
},
orderBy: { createdAt: "asc" },
}),
prisma.purchaseBatch.findMany({
select: {
productId: true,
remainingQty: true,
serialNumbers: true,
poNumber: true,
purchaseOrder: {
select: { companyName: true, status: true },
},
},
}),
]);
const warehouses = await prisma.warehouse.findMany({
orderBy: { name: "asc" },
});
// Bangun peta SN & stok per PT (karena Gudang Utama dipakai bersama oleh beberapa PT)
const inSnByProduct = new Map<string, Set<string>>();
const outSnByProduct = new Map<string, Set<string>>();
const batchStockByProdCompany = new Map<string, Record<string, number>>();
const manualStockByProdCompany = new Map<string, Record<string, number>>();
const categories = await prisma.category.findMany({
orderBy: { name: "asc" },
});
for (const b of allBatches) {
if (b.serialNumbers) {
if (!inSnByProduct.has(b.productId)) inSnByProduct.set(b.productId, new Set());
const target = inSnByProduct.get(b.productId)!;
for (const sn of parseSnTokens(b.serialNumbers)) {
target.add(sn);
}
}
const poStatus = b.purchaseOrder?.status;
if (poStatus !== "CANCELLED" && poStatus !== "REJECTED" && (b.remainingQty || 0) > 0) {
const comp = b.purchaseOrder?.companyName || "PT EnterpriseCore Utama";
if (!batchStockByProdCompany.has(b.productId)) batchStockByProdCompany.set(b.productId, {});
const map = batchStockByProdCompany.get(b.productId)!;
map[comp] = (map[comp] || 0) + (b.remainingQty || 0);
}
}
const rawMovements = await prisma.stockMovement.findMany({
take: 50,
orderBy: { createdAt: "desc" },
include: {
product: true,
warehouse: true,
},
});
for (const m of allMovementsForCalc) {
const tokens = parseSnTokens(m.serialNumbers);
if (tokens.length > 0) {
if (m.type === "IN") {
if (!inSnByProduct.has(m.productId)) inSnByProduct.set(m.productId, new Set());
const inSet = inSnByProduct.get(m.productId)!;
const outSet = outSnByProduct.get(m.productId);
for (const sn of tokens) {
inSet.add(sn);
outSet?.delete(sn);
}
} else if (m.type === "OUT") {
if (!outSnByProduct.has(m.productId)) outSnByProduct.set(m.productId, new Set());
const outSet = outSnByProduct.get(m.productId)!;
for (const sn of tokens) {
outSet.add(sn);
}
}
}
// Hitung mutasi manual / stok awal / afkir yang tidak melewati batch PO/SO
if (m.referenceType !== "PURCHASE_ORDER" && m.referenceType !== "SALES_ORDER") {
const comp = m.companyName || "PT EnterpriseCore Utama";
if (!manualStockByProdCompany.has(m.productId)) manualStockByProdCompany.set(m.productId, {});
const map = manualStockByProdCompany.get(m.productId)!;
const delta =
m.type === "IN"
? Math.abs(m.quantity)
: m.type === "OUT"
? -Math.abs(m.quantity)
: m.quantity;
map[comp] = (map[comp] || 0) + delta;
}
}
// Cari referensi SO untuk melampirkan No. PO Customer jika mutasi berasal dari penjualan
const soRefIds = rawMovements
@@ -62,6 +155,13 @@ export async function GET() {
const so = m.referenceId ? soMap.get(m.referenceId) : null;
return {
...m,
product: m.product
? {
...m.product,
purchasePrice: canSeePrices ? m.product.purchasePrice : 0,
sellingPrice: canSeePrices ? m.product.sellingPrice : 0,
}
: m.product,
customerPoNumber: so?.customerPoNumber || null,
invoiceNumber: so?.invoiceNumber || null,
saleType: so?.saleType || m.outboundCategory || null,
@@ -70,11 +170,41 @@ export async function GET() {
const formattedProducts = products.map((p) => {
const totalStock = p.stockItems.reduce((acc, curr) => acc + curr.quantity, 0);
const inSet = inSnByProduct.get(p.id) || new Set<string>();
const outSet = outSnByProduct.get(p.id) || new Set<string>();
const availableSerialNumbers = Array.from(inSet).filter((sn) => !outSet.has(sn));
const allRecordedSerialNumbers = Array.from(new Set([...Array.from(inSet), ...Array.from(outSet)]));
// Gabungkan stok per PT dari Batch PO + mutasi manual; fallback ke warehouse.companyName jika data seed lama
const stockByCompany: Record<string, number> = {};
const batchMap = batchStockByProdCompany.get(p.id) || {};
const manualMap = manualStockByProdCompany.get(p.id) || {};
const allComps = new Set([...Object.keys(batchMap), ...Object.keys(manualMap)]);
let allocatedTotal = 0;
for (const comp of allComps) {
const val = Math.max(0, (batchMap[comp] || 0) + (manualMap[comp] || 0));
if (val > 0) {
stockByCompany[comp] = val;
allocatedTotal += val;
}
}
if (allocatedTotal === 0 && totalStock > 0) {
for (const s of p.stockItems) {
const whComp = s.warehouse?.companyName || "PT EnterpriseCore Utama";
stockByCompany[whComp] = (stockByCompany[whComp] || 0) + (s.quantity || 0);
}
}
return {
...p,
purchasePrice: canSeePrices ? p.purchasePrice : 0,
sellingPrice: canSeePrices ? p.sellingPrice : 0,
totalStock,
stockByCompany,
availableSerialNumbers,
allRecordedSerialNumbers,
};
});
@@ -153,6 +283,7 @@ export async function POST(req: Request) {
categoryId,
warehouseId: rawWhId,
initialQuantity,
initialSerialNumbers,
} = body;
const defaultWh = await prisma.warehouse.findFirst();
@@ -190,6 +321,7 @@ export async function POST(req: Request) {
if (!isService && warehouseId && initialQuantity && parseInt(initialQuantity) > 0) {
const qty = parseInt(initialQuantity);
const cleanInitialSn = initialSerialNumbers ? String(initialSerialNumbers).trim() : null;
await prisma.stockItem.create({
data: {
productId: product.id,
@@ -205,7 +337,8 @@ export async function POST(req: Request) {
type: "IN",
quantity: qty,
referenceType: "INITIAL_STOCK",
notes: "Inisialisasi stok awal produk baru",
serialNumbers: cleanInitialSn,
notes: `Inisialisasi stok awal produk baru${cleanInitialSn ? ` (SN: ${cleanInitialSn})` : ""}`,
},
});
}
@@ -274,6 +407,8 @@ export async function PUT(req: Request) {
}
}
const allowPriceUpdate = canViewPriceAndHpp(user.role);
const updated = await prisma.product.update({
where: { id: productId },
data: {
@@ -281,9 +416,9 @@ export async function PUT(req: Request) {
...(sku && { sku: sku.trim().toUpperCase() }),
...(categoryId !== undefined && { categoryId: categoryId || null }),
...(unit && { unit: unit.trim().toUpperCase() }),
...(minStock !== undefined && { minStock: parseInt(minStock) || 0 }),
...(purchasePrice !== undefined && { purchasePrice: Math.max(0, parseFloat(purchasePrice) || 0) }),
...(sellingPrice !== undefined && { sellingPrice: Math.max(0, parseFloat(sellingPrice) || 0) }),
...(minStock !== undefined && { minStock: Math.max(0, parseInt(minStock) || 0) }),
...(allowPriceUpdate && purchasePrice !== undefined && { purchasePrice: Math.max(0, parseFloat(purchasePrice) || 0) }),
...(allowPriceUpdate && sellingPrice !== undefined && { sellingPrice: Math.max(0, parseFloat(sellingPrice) || 0) }),
...(description !== undefined && { description: description ? description.trim() : null }),
},
});
@@ -415,7 +550,7 @@ export async function PUT(req: Request) {
});
}
const { productId, warehouseId: rawWhId, type, quantity, notes, outboundCategory } = body;
const { productId, warehouseId: rawWhId, type, quantity, notes, outboundCategory, serialNumbers } = body;
const defaultWh = await prisma.warehouse.findFirst();
const warehouseId = rawWhId || defaultWh?.id;
@@ -488,6 +623,8 @@ export async function PUT(req: Request) {
? "Jual Putus"
: "";
const cleanSn = serialNumbers ? String(serialNumbers).trim() : null;
await prisma.stockMovement.create({
data: {
productId,
@@ -496,11 +633,12 @@ export async function PUT(req: Request) {
outboundCategory: outCat,
quantity: qty,
referenceType: "MANUAL_ADJUSTMENT",
companyName: warehouse?.companyName || "PT EnterpriseCore Utama",
companyName: (body.companyName || "").trim() || warehouse?.companyName || "PT EnterpriseCore Utama",
serialNumbers: cleanSn,
notes:
type === "OUT"
? `[${outCatLabel}] ${notes || "Pengeluaran barang manual oleh staf gudang"}`
: notes || "Penyesuaian stok manual oleh staf gudang",
? `[${outCatLabel}] ${notes || "Pengeluaran barang manual oleh staf gudang"}${cleanSn ? ` (SN: ${cleanSn})` : ""}`
: `${notes || "Penyesuaian stok manual oleh staf gudang"}${cleanSn ? ` (SN: ${cleanSn})` : ""}`,
},
});
+543
View File
@@ -0,0 +1,543 @@
import { NextResponse } from "next/server";
import type { PrismaClient } from "@prisma/client";
import { prismaLive, type EnvMode } from "@/lib/db";
import { dispatchNotification } from "@/lib/notifier";
// In-memory rate limiter per IP (maks 30 request / menit) untuk mencegah spam & brute-force SN
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
function checkRateLimit(req: Request): boolean {
const ip =
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
req.headers.get("x-real-ip") ||
"local";
const now = Date.now();
const entry = rateLimitMap.get(ip);
if (!entry || now > entry.resetAt) {
rateLimitMap.set(ip, { count: 1, resetAt: now + 60_000 });
return true;
}
if (entry.count >= 30) {
return false;
}
entry.count += 1;
return true;
}
function splitSnTokens(raw?: string | null): string[] {
if (!raw) return [];
return String(raw)
.split(/[\n,;]+/)
.map((s) => s.trim())
.filter(Boolean);
}
function findExactSnToken(raw: string | null | undefined, targetLower: string): string | null {
const tokens = splitSnTokens(raw);
const found = tokens.find((t) => t.toLowerCase() === targetLower);
return found || null;
}
interface VerifiedSnMatch {
mode: EnvMode;
client: PrismaClient;
canonicalSn: string;
productId: string;
productName: string;
productSku: string;
companyName: string;
customerId: string | null;
salesOrderId: string | null;
salesOrderNumber: string | null;
salesOrderItemId: string | null;
purchaseDate: Date;
warrantyExpiry: Date;
isWarrantyActive: boolean;
source: "SALES_ORDER" | "STOCK_MOVEMENT" | "PURCHASE_BATCH";
}
async function searchSnInClient(
client: PrismaClient,
mode: EnvMode,
rawSn: string
): Promise<VerifiedSnMatch | null> {
const targetLower = rawSn.trim().toLowerCase();
if (!targetLower) return null;
// 1. Prioritas utama: cari di SalesOrderItem (serialNumbers / replacementSerialNumbers)
const soItems = await client.salesOrderItem.findMany({
where: {
salesOrder: { status: { not: "CANCELLED" } },
product: { isService: false },
OR: [
{ serialNumbers: { not: null } },
{ replacementSerialNumbers: { not: null } },
],
},
include: {
salesOrder: true,
product: true,
},
orderBy: { salesOrder: { createdAt: "desc" } },
});
for (const it of soItems) {
const matched =
findExactSnToken(it.replacementSerialNumbers, targetLower) ||
findExactSnToken(it.serialNumbers, targetLower);
if (matched) {
const purchaseDate = new Date(it.salesOrder.orderDate || it.salesOrder.createdAt);
const warrantyExpiry = it.warrantyExpiry
? new Date(it.warrantyExpiry)
: (() => {
const d = new Date(purchaseDate);
d.setMonth(d.getMonth() + (it.salesOrder.warrantyMonths || 12));
return d;
})();
const isWarrantyActive = new Date() <= warrantyExpiry;
return {
mode,
client,
canonicalSn: matched,
productId: it.productId,
productName: it.product.name,
productSku: it.product.sku,
companyName: it.salesOrder.companyName || "PT EnterpriseCore Utama",
customerId: it.salesOrder.customerId,
salesOrderId: it.salesOrderId,
salesOrderNumber: it.salesOrder.orderNumber,
salesOrderItemId: it.id,
purchaseDate,
warrantyExpiry,
isWarrantyActive,
source: "SALES_ORDER",
};
}
}
// 2. Sekunder: cari di StockMovement (unit yang keluar/masuk dengan SN tercatat)
const movements = await client.stockMovement.findMany({
where: {
serialNumbers: { not: null },
product: { isService: false },
},
include: { product: true },
orderBy: { createdAt: "desc" },
});
for (const m of movements) {
const matched = findExactSnToken(m.serialNumbers, targetLower);
if (matched) {
let linkedSo: any = null;
if (m.referenceType === "SALES_ORDER" && m.referenceId) {
linkedSo = await client.salesOrder.findUnique({
where: { orderNumber: m.referenceId },
});
}
const purchaseDate = new Date(linkedSo?.orderDate || m.createdAt);
const warrantyExpiry = new Date(purchaseDate);
warrantyExpiry.setMonth(warrantyExpiry.getMonth() + (linkedSo?.warrantyMonths || 12));
const isWarrantyActive = new Date() <= warrantyExpiry;
return {
mode,
client,
canonicalSn: matched,
productId: m.productId,
productName: m.product.name,
productSku: m.product.sku,
companyName: linkedSo?.companyName || m.companyName || "PT EnterpriseCore Utama",
customerId: linkedSo?.customerId || null,
salesOrderId: linkedSo?.id || null,
salesOrderNumber: linkedSo?.orderNumber || (m.referenceType === "SALES_ORDER" ? m.referenceId : null),
salesOrderItemId: null,
purchaseDate,
warrantyExpiry,
isWarrantyActive,
source: "STOCK_MOVEMENT",
};
}
}
// 3. Tersier: cari di PurchaseBatch (unit resmi yang tercatat di penerimaan gudang)
const batches = await client.purchaseBatch.findMany({
where: {
serialNumbers: { not: null },
product: { isService: false },
},
include: {
product: true,
purchaseOrder: { select: { companyName: true } },
},
orderBy: { receivedAt: "desc" },
});
for (const b of batches) {
const matched = findExactSnToken(b.serialNumbers, targetLower);
if (matched) {
const purchaseDate = new Date(b.receivedAt);
const warrantyExpiry = new Date(purchaseDate);
warrantyExpiry.setMonth(warrantyExpiry.getMonth() + 12);
const isWarrantyActive = new Date() <= warrantyExpiry;
return {
mode,
client,
canonicalSn: matched,
productId: b.productId,
productName: b.product.name,
productSku: b.product.sku,
companyName: b.purchaseOrder?.companyName || "PT EnterpriseCore Utama",
customerId: null,
salesOrderId: null,
salesOrderNumber: null,
salesOrderItemId: null,
purchaseDate,
warrantyExpiry,
isWarrantyActive,
source: "PURCHASE_BATCH",
};
}
}
return null;
}
async function findVerifiedSn(rawSn: string): Promise<VerifiedSnMatch | null> {
return searchSnInClient(prismaLive, "LIVE", rawSn);
}
function serializePublicTicket(rec: any) {
return {
recordNumber: rec.recordNumber,
serialNumber: rec.serialNumber,
productName: rec.product?.name || "-",
productSku: rec.product?.sku || "-",
companyName: rec.companyName || "PT EnterpriseCore Utama",
condition: rec.condition,
serviceOrigin: rec.serviceOrigin,
warrantyStatus: rec.warrantyStatus,
damageDescription: rec.damageDescription,
actionTaken: rec.actionTaken,
serviceFee: rec.serviceFee || 0,
returnShippingCost: rec.returnShippingCost || 0,
returnCourierName: rec.returnCourierName || null,
returnTrackingNumber: rec.returnTrackingNumber || null,
servicePaymentStatus: rec.servicePaymentStatus || "FREE",
createdAt: rec.createdAt,
updatedAt: rec.updatedAt,
};
}
export async function GET(req: Request) {
try {
if (!checkRateLimit(req)) {
return NextResponse.json(
{ error: "Terlalu banyak permintaan. Mohon tunggu 1 menit lalu coba kembali." },
{ status: 429 }
);
}
const { searchParams } = new URL(req.url);
const snParam = (searchParams.get("sn") || "").trim();
const ticketParam = (searchParams.get("ticket") || "").trim();
// MODE A: Lacak Status Tiket RMA (by Nomor Tiket atau SN)
if (ticketParam) {
if (ticketParam.length < 3) {
return NextResponse.json(
{ error: "Masukkan minimal 3 karakter Nomor Tiket RMA atau Serial Number." },
{ status: 400 }
);
}
const queryTickets = async (client: PrismaClient) => {
const all = await client.deviceRecord.findMany({
where: {
OR: [
{ recordNumber: ticketParam },
{ serialNumber: ticketParam },
],
},
include: { product: { select: { name: true, sku: true } } },
orderBy: { updatedAt: "desc" },
});
if (all.length > 0) return all;
// Case-insensitive fallback (SQLite exact match sensitif terhadap huruf besar/kecil)
const recent = await client.deviceRecord.findMany({
include: { product: { select: { name: true, sku: true } } },
orderBy: { updatedAt: "desc" },
take: 500,
});
const qLower = ticketParam.toLowerCase();
return recent.filter(
(r) =>
r.recordNumber.toLowerCase() === qLower ||
r.serialNumber.toLowerCase() === qLower
);
};
const found = await queryTickets(prismaLive);
if (found.length === 0) {
return NextResponse.json(
{
error: `Tiket RMA atau Serial Number "${ticketParam}" tidak ditemukan. Pastikan nomor yang dimasukkan sudah benar.`,
},
{ status: 404 }
);
}
return NextResponse.json({
success: true,
tickets: found.map(serializePublicTicket),
});
}
// MODE B: Verifikasi SN & Cek Garansi (Wajib SN terdaftar di database)
if (!snParam || snParam.length < 3) {
return NextResponse.json(
{ error: "Masukkan Serial Number (SN) perangkat minimal 3 karakter." },
{ status: 400 }
);
}
const match = await findVerifiedSn(snParam);
if (!match) {
return NextResponse.json(
{
verified: false,
error:
"Serial Number (SN) tidak terdaftar di database kami. Pengajuan RMA / Service hanya berlaku untuk perangkat resmi yang SN-nya tercatat di sistem kami.",
},
{ status: 404 }
);
}
// Ambil riwayat tiket yang sudah ada untuk SN ini
const existingRecords = await match.client.deviceRecord.findMany({
where: { productId: match.productId },
include: { product: { select: { name: true, sku: true } } },
orderBy: { updatedAt: "desc" },
});
const matchedTickets = existingRecords
.filter((r) => r.serialNumber.toLowerCase() === match.canonicalSn.toLowerCase())
.map(serializePublicTicket);
return NextResponse.json({
verified: true,
device: {
serialNumber: match.canonicalSn,
productName: match.productName,
productSku: match.productSku,
companyName: match.companyName,
purchaseDate: match.purchaseDate,
warrantyExpiry: match.warrantyExpiry,
isWarrantyActive: match.isWarrantyActive,
eligibleModes: match.isWarrantyActive
? ["WARRANTY_FREE", "WARRANTY_REPLACE"]
: ["PAID_SERVICE"],
},
existingTickets: matchedTickets,
});
} catch (error: any) {
console.error("Public RMA GET error:", error);
return NextResponse.json(
{ error: "Terjadi kesalahan saat memverifikasi Serial Number." },
{ status: 500 }
);
}
}
export async function POST(req: Request) {
try {
if (!checkRateLimit(req)) {
return NextResponse.json(
{ error: "Terlalu banyak permintaan. Mohon tunggu 1 menit lalu coba kembali." },
{ status: 429 }
);
}
const body = await req.json();
const {
serialNumber,
requestType, // "WARRANTY_FREE" | "WARRANTY_REPLACE" | "PAID_SERVICE"
contactName,
contactPhone,
returnAddress,
damageDescription,
} = body;
const cleanSn = String(serialNumber || "").trim();
if (!cleanSn || cleanSn.length < 3) {
return NextResponse.json(
{ error: "Serial Number (SN) wajib diisi." },
{ status: 400 }
);
}
// VERIFIKASI KETAT SERVER-SIDE: Di luar SN yang ada di database, user TIDAK BISA mengajukan service!
const match = await findVerifiedSn(cleanSn);
if (!match) {
return NextResponse.json(
{
error:
"Pengajuan ditolak: Serial Number (SN) tidak terdaftar di database kami. Hanya perangkat dengan SN terdaftar yang dapat mengajukan RMA / Service.",
},
{ status: 403 }
);
}
const cleanName = String(contactName || "").trim();
const cleanPhone = String(contactPhone || "").trim();
const cleanAddress = String(returnAddress || "").trim();
const cleanDamage = String(damageDescription || "").trim();
if (!cleanName || !cleanPhone || !cleanAddress || !cleanDamage) {
return NextResponse.json(
{
error:
"Nama pemohon, nomor WhatsApp/HP, alamat kirim balik, dan deskripsi kerusakan wajib diisi lengkap.",
},
{ status: 400 }
);
}
// Cek apakah sudah ada tiket aktif (IN_SERVICE) untuk SN yang sama agar tidak dobel spam
const activeDuplicates = await match.client.deviceRecord.findMany({
where: {
productId: match.productId,
condition: "IN_SERVICE",
},
});
const activeTicket = activeDuplicates.find(
(r) => r.serialNumber.toLowerCase() === match.canonicalSn.toLowerCase()
);
if (activeTicket) {
return NextResponse.json(
{
error: `Perangkat dengan SN ${match.canonicalSn} sudah memiliki tiket aktif (${activeTicket.recordNumber}) yang sedang diproses. Silakan cek progres pada tab Lacak Status RMA.`,
existingTicketNumber: activeTicket.recordNumber,
},
{ status: 409 }
);
}
// Tentukan skema layanan sesuai masa garansi (server-enforced)
let finalOrigin: "WARRANTY_FREE" | "WARRANTY_REPLACE" | "PAID_SERVICE" = "PAID_SERVICE";
if (match.isWarrantyActive) {
finalOrigin = requestType === "WARRANTY_REPLACE" ? "WARRANTY_REPLACE" : "WARRANTY_FREE";
} else {
finalOrigin = "PAID_SERVICE";
}
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const count = await match.client.deviceRecord.count();
const ticketNumber = `RMA-${dateStr}-${String(count + 1).padStart(4, "0")}-${Math.floor(
10 + Math.random() * 89
)}`;
const fullDamageDesc = `${cleanDamage} | PIC: ${cleanName} (${cleanPhone}) | Alamat Kirim Balik: ${cleanAddress}`;
const originLabel =
finalOrigin === "WARRANTY_REPLACE"
? "Pengajuan Ganti Unit (Garansi Aktif)"
: finalOrigin === "WARRANTY_FREE"
? "Service Gratis (Garansi Aktif)"
: "Jasa Service Berbayar (Garansi Habis)";
const created = await match.client.deviceRecord.create({
data: {
recordNumber: ticketNumber,
serialNumber: match.canonicalSn,
productId: match.productId,
customerId: match.customerId,
salesOrderId: match.salesOrderId,
salesOrderNumber: match.salesOrderNumber,
companyName: match.companyName,
condition: "IN_SERVICE",
serviceOrigin: finalOrigin,
warrantyStatus: match.isWarrantyActive ? "IN_WARRANTY" : "OUT_OF_WARRANTY",
serviceFee: 0,
returnShippingCost: 0,
servicePaymentStatus: "FREE",
damageDescription: fullDamageDesc,
actionTaken: `Tiket diajukan online oleh customer (${originLabel}) — menunggu unit tiba & pengecekan teknisi`,
recordedBy: `Portal Customer (${cleanName})`,
},
include: { product: { select: { name: true, sku: true } } },
});
// Sinkronkan ke SalesOrderItem jika terhubung ke SO
if (match.salesOrderItemId) {
const existingSoItem = await match.client.salesOrderItem.findUnique({
where: { id: match.salesOrderItemId },
});
if (existingSoItem) {
const existingDamaged = splitSnTokens(existingSoItem.damagedSerialNumbers);
if (!existingDamaged.some((s) => s.toLowerCase() === match.canonicalSn.toLowerCase())) {
existingDamaged.push(match.canonicalSn);
}
await match.client.salesOrderItem.update({
where: { id: match.salesOrderItemId },
data: {
serviceStatus:
!existingSoItem.serviceStatus || existingSoItem.serviceStatus === "NORMAL"
? "NEED_SERVICE"
: existingSoItem.serviceStatus,
serviceType:
finalOrigin === "PAID_SERVICE"
? "PAID_SERVICE"
: finalOrigin === "WARRANTY_REPLACE"
? "WARRANTY_REPLACEMENT"
: "FREE_WARRANTY",
damagedSerialNumbers: existingDamaged.join(", "),
serviceNotes: existingSoItem.serviceNotes
? `${existingSoItem.serviceNotes} | [${ticketNumber}] ${cleanDamage}`
: `[${ticketNumber}] ${cleanDamage} (PIC: ${cleanName} - ${cleanPhone})`,
},
});
}
}
// Catat AuditLog di database yang sama
await match.client.auditLog.create({
data: {
userName: `Customer: ${cleanName}`,
action: "PUBLIC_RMA_SUBMIT",
module: "INVENTORY",
description: `[PORTAL RMA] Pengajuan ${ticketNumber} untuk SN ${match.canonicalSn} (${match.productName}) — ${originLabel}. PIC: ${cleanName} (${cleanPhone})`,
metadata: JSON.stringify({
ticketNumber,
serialNumber: match.canonicalSn,
productId: match.productId,
serviceOrigin: finalOrigin,
contactName: cleanName,
contactPhone: cleanPhone,
}),
},
});
// Kirim notifikasi Email & Telegram otomatis ke divisi terkait (Sales, Gudang/Teknis, Manager, Admin) sesuai kapasitas masing-masing
await dispatchNotification({
type: "RMA_SERVICE",
title: `Pengajuan RMA Customer Baru: ${ticketNumber}`,
message: `Customer ${cleanName} (${cleanPhone}) mengajukan ${originLabel} untuk ${match.productName} (SN: ${match.canonicalSn}).\nKeluhan: ${cleanDamage}\nAlamat Kirim Balik: ${cleanAddress}`,
targetRoles: ["ADMIN", "MANAGER", "SALES", "INVENTORY"],
dbClient: match.client,
});
return NextResponse.json({
success: true,
ticketNumber: created.recordNumber,
ticket: serializePublicTicket(created),
});
} catch (error: any) {
console.error("Public RMA POST error:", error);
return NextResponse.json(
{ error: "Terjadi kesalahan saat mengirim pengajuan RMA." },
{ status: 500 }
);
}
}
+646 -101
View File
@@ -104,14 +104,115 @@ export async function GET() {
getSavedCompanies(),
]);
const canSeePurchasesMoney = ["ADMIN", "MANAGER", "PURCHASING", "ACCOUNTANT"].includes(user.role);
const canSeeSellingPrice = ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT"].includes(user.role);
const canSeeHpp = ["ADMIN", "MANAGER", "PURCHASING", "ACCOUNTANT", "SALES"].includes(user.role);
const sanitizedOrders = canSeePurchasesMoney
? orders.map((po) => ({
...po,
items: po.items.map((item) => ({
...item,
product: item.product
? {
...item.product,
purchasePrice: canSeeHpp ? item.product.purchasePrice : 0,
sellingPrice: canSeeSellingPrice ? item.product.sellingPrice : 0,
}
: item.product,
})),
}))
: orders.map((po) => ({
...po,
subtotalProducts: 0,
shippingCost: 0,
exportCost: 0,
shippingCostUsd: 0,
exportCostUsd: 0,
taxRate: 0,
taxAmount: 0,
totalAmount: 0,
totalAmountUsd: 0,
paidAmount: 0,
items: po.items.map((item) => ({
...item,
unitCost: 0,
unitCostUsd: 0,
subtotal: 0,
product: item.product
? {
...item.product,
purchasePrice: canSeeHpp ? item.product.purchasePrice : 0,
sellingPrice: canSeeSellingPrice ? item.product.sellingPrice : 0,
}
: item.product,
})),
}));
const sanitizedProducts = products.map((p) => ({
...p,
purchasePrice: canSeeHpp ? p.purchasePrice : 0,
sellingPrice: canSeeSellingPrice ? p.sellingPrice : 0,
}));
const sanitizedRequisitions = requisitions.map((reqItem) => ({
...reqItem,
items: reqItem.items.map((it) => ({
...it,
product: it.product
? {
...it.product,
purchasePrice: canSeeHpp ? it.product.purchasePrice : 0,
sellingPrice: canSeeSellingPrice ? it.product.sellingPrice : 0,
}
: it.product,
})),
}));
const sanitizedBatches = batches.map((b) => ({
...b,
unitCost: canSeePurchasesMoney ? b.unitCost : 0,
product: b.product
? {
...b.product,
purchasePrice: canSeeHpp ? b.product.purchasePrice : 0,
sellingPrice: canSeeSellingPrice ? b.product.sellingPrice : 0,
}
: b.product,
purchaseOrder: b.purchaseOrder
? {
...b.purchaseOrder,
totalAmount: canSeePurchasesMoney ? b.purchaseOrder.totalAmount : 0,
paidAmount: canSeePurchasesMoney ? b.purchaseOrder.paidAmount : 0,
}
: b.purchaseOrder,
allocations: b.allocations.map((al) => ({
...al,
salesOrderItem: al.salesOrderItem
? {
...al.salesOrderItem,
unitPrice: canSeeSellingPrice ? al.salesOrderItem.unitPrice : 0,
subtotal: canSeeSellingPrice ? al.salesOrderItem.subtotal : 0,
salesOrder: al.salesOrderItem.salesOrder
? {
...al.salesOrderItem.salesOrder,
totalAmount: canSeeSellingPrice ? al.salesOrderItem.salesOrder.totalAmount : 0,
totalHpp: canSeeSellingPrice ? al.salesOrderItem.salesOrder.totalHpp : 0,
}
: al.salesOrderItem.salesOrder,
}
: al.salesOrderItem,
})),
}));
return NextResponse.json({
orders,
orders: sanitizedOrders,
suppliers,
requisitions,
products,
requisitions: sanitizedRequisitions,
products: sanitizedProducts,
warehouses,
customers,
batches,
batches: sanitizedBatches,
companies,
});
} catch (error: any) {
@@ -133,6 +234,12 @@ export async function POST(req: Request) {
// 0. ACTION: CREATE_CUSTOMER (Tambah PT / Pelanggan Baru dari Sales)
// =========================================================================
if (body.action === "CREATE_CUSTOMER") {
if (!["ADMIN", "MANAGER", "SALES", "PURCHASING"].includes(user.role)) {
return NextResponse.json(
{ error: `Akses ditolak: Peran ${user.role} tidak berwenang menambahkan pelanggan baru.` },
{ status: 403 }
);
}
const { name, company, phone, email, address } = body;
const ptName = (company || name || "").trim();
if (!ptName) {
@@ -583,10 +690,15 @@ export async function POST(req: Request) {
});
}
// Detail Biaya Ongkir & Ekspor (Mandiri Terpisah vs Dibantu Perusahaan Lain / All-In)
const logisticsMode = inputLogisticsMode === "ASSISTED_ALL_IN" ? "ASSISTED_ALL_IN" : "DETAILED";
// Detail Biaya Ongkir, Ekspor & PPN Masukan: HANYA Finance (ACCOUNTANT), Manager, atau Admin yang berwenang mengisi!
const canSetPoLogisticsAndTax = ["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role);
const logisticsMode =
canSetPoLogisticsAndTax && inputLogisticsMode === "ASSISTED_ALL_IN"
? "ASSISTED_ALL_IN"
: "DETAILED";
const forwardingCompany =
logisticsMode === "ASSISTED_ALL_IN" && inputForwardingCompany
canSetPoLogisticsAndTax && logisticsMode === "ASSISTED_ALL_IN" && inputForwardingCompany
? String(inputForwardingCompany).trim()
: null;
@@ -594,29 +706,35 @@ export async function POST(req: Request) {
let shippingCostUsd: number | null = null;
let exportCost = 0;
if (logisticsMode === "ASSISTED_ALL_IN") {
// Mode Dibantu Perusahaan Lain (All-In: Gabungan Ongkir + Pajak Masuk dijadikan satu tagihan Rupiah)
shippingCost = 0;
shippingCostUsd = null;
exportCost = Math.max(
0,
parseFloat(inputAllInCost !== undefined ? inputAllInCost : inputExportCost) || 0
);
} else {
// Mode Rincian Terpisah (Mandiri)
exportCost = Math.max(0, parseFloat(inputExportCost) || 0);
if (currency === "USD") {
shippingCostUsd = Math.max(
if (canSetPoLogisticsAndTax) {
if (logisticsMode === "ASSISTED_ALL_IN") {
// Mode Dibantu Perusahaan Lain (All-In: Gabungan Ongkir + Pajak Masuk dijadikan satu tagihan Rupiah)
shippingCost = 0;
shippingCostUsd = null;
exportCost = Math.max(
0,
parseFloat(inputShippingCostUsd !== undefined ? inputShippingCostUsd : inputShippingCost) || 0
parseFloat(inputAllInCost !== undefined ? inputAllInCost : inputExportCost) || 0
);
shippingCost = Math.round(shippingCostUsd * exchangeRate);
} else {
shippingCost = Math.max(0, parseFloat(inputShippingCost) || 0);
// Mode Rincian Terpisah (Mandiri)
exportCost = Math.max(0, parseFloat(inputExportCost) || 0);
if (currency === "USD") {
shippingCostUsd = Math.max(
0,
parseFloat(inputShippingCostUsd !== undefined ? inputShippingCostUsd : inputShippingCost) || 0
);
shippingCost = Math.round(shippingCostUsd * exchangeRate);
} else {
shippingCost = Math.max(0, parseFloat(inputShippingCost) || 0);
}
}
}
const totalAmount = subtotalProducts + shippingCost + exportCost;
const includeTax = canSetPoLogisticsAndTax && Boolean(body.includeTax);
const taxRate = includeTax ? Math.max(0, parseFloat(body.taxRate) || 11) : 0;
const taxAmount = includeTax ? Math.round((subtotalProducts * taxRate) / 100) : 0;
const totalAmount = subtotalProducts + shippingCost + exportCost + taxAmount;
// Nilai tagihan vendor luar negeri dalam USD: Barang + Ongkir International (jika tidak All-In lokal)
const totalAmountUsd =
currency === "USD" ? subtotalProductsUsd + (shippingCostUsd || 0) : null;
@@ -647,6 +765,9 @@ export async function POST(req: Request) {
exportCost,
shippingCostUsd,
exportCostUsd: null,
taxRate,
taxAmount,
includeTax,
totalAmountUsd,
totalAmount,
notes,
@@ -762,14 +883,30 @@ export async function POST(req: Request) {
});
}
await prisma.account.updateMany({
where: { code: "1201" },
data: { balance: { increment: totalAmount } },
});
await prisma.account.updateMany({
where: { code: "2001" },
data: { balance: { increment: totalAmount } },
});
const autoPoCompany = po.companyName || "PT EnterpriseCore Utama";
const autoInvAcc = await getCompanyAccount("1201", autoPoCompany);
const autoTaxAcc = await getCompanyAccount("1301", autoPoCompany);
const autoApAcc = await getCompanyAccount("2001", autoPoCompany);
const autoInvValue = Math.max(0, totalAmount - taxAmount);
if (autoInvAcc && autoInvValue > 0) {
await prisma.account.update({
where: { id: autoInvAcc.id },
data: { balance: { increment: autoInvValue } },
});
}
if (autoTaxAcc && taxAmount > 0) {
await prisma.account.update({
where: { id: autoTaxAcc.id },
data: { balance: { increment: taxAmount } },
});
}
if (autoApAcc && totalAmount > 0) {
await prisma.account.update({
where: { id: autoApAcc.id },
data: { balance: { increment: totalAmount } },
});
}
}
const usdInfo = currency === "USD" && totalAmountUsd !== null ? ` ($${totalAmountUsd.toLocaleString("en-US", { minimumFractionDigits: 2 })} @ Kurs Rp ${exchangeRate.toLocaleString("id-ID")})` : "";
@@ -874,7 +1011,7 @@ export async function PUT(req: Request) {
);
}
const { orderId, warehouseId, warehouseNotes } = body;
const { orderId, warehouseId, warehouseNotes, itemSerialNumbers, serialNumbers } = body;
const po = await prisma.purchaseOrder.findUnique({
where: { id: orderId },
@@ -949,6 +1086,16 @@ export async function PUT(req: Request) {
});
}
const sn = (itemSerialNumbers && itemSerialNumbers[item.id]) || serialNumbers || null;
const cleanSn = sn ? String(sn).trim() : null;
if (cleanSn) {
await prisma.purchaseOrderItem.update({
where: { id: item.id },
data: { serialNumbers: cleanSn },
});
}
// 2. Buat Record Batch PO (FIFO) untuk pelacakan penjualan
await prisma.purchaseBatch.create({
data: {
@@ -959,6 +1106,7 @@ export async function PUT(req: Request) {
initialQty: item.quantity,
remainingQty: item.quantity,
unitCost: landedUnitCost,
serialNumbers: cleanSn,
receivedAt: new Date(),
},
});
@@ -995,7 +1143,8 @@ export async function PUT(req: Request) {
referenceType: "PURCHASE_ORDER",
referenceId: po.poNumber,
companyName: po.companyName || "PT EnterpriseCore Utama",
notes: `Penerimaan & Verifikasi Gudang PO ${po.poNumber} (${po.companyName || "PT Utama"}) [Batch FIFO: ${item.quantity} pcs @ HPP Rp ${landedUnitCost.toLocaleString("id-ID")}${additionalCost > 0 ? ` (Inc. Ongkir & Ekspor)` : ""}]`,
serialNumbers: cleanSn,
notes: `Penerimaan & Verifikasi Gudang PO ${po.poNumber} (${po.companyName || "PT Utama"}) [Batch FIFO: ${item.quantity} pcs @ HPP Rp ${landedUnitCost.toLocaleString("id-ID")}${additionalCost > 0 ? ` (Inc. Ongkir & Ekspor)` : ""}]${cleanSn ? ` (SN: ${cleanSn})` : ""}`,
},
});
}
@@ -1011,18 +1160,28 @@ export async function PUT(req: Request) {
},
});
// 4. Pembukuan otomatis: Tambah Persediaan (1201) dan Hutang (2001) untuk PT terkait
// 4. Pembukuan otomatis: Tambah Persediaan (1201), PPN Masukan (1301), dan Hutang (2001) untuk PT terkait
const poCompany = po.companyName || "PT EnterpriseCore Utama";
const invAcc = await getCompanyAccount("1201", poCompany);
const taxInAcc = await getCompanyAccount("1301", poCompany);
const apAcc = await getCompanyAccount("2001", poCompany);
if (invAcc) {
const poTaxVal = po.includeTax && po.taxAmount > 0 ? po.taxAmount : 0;
const poInvVal = Math.max(0, po.totalAmount - poTaxVal);
if (invAcc && poInvVal > 0) {
await prisma.account.update({
where: { id: invAcc.id },
data: { balance: { increment: po.totalAmount } },
data: { balance: { increment: poInvVal } },
});
}
if (apAcc) {
if (taxInAcc && poTaxVal > 0) {
await prisma.account.update({
where: { id: taxInAcc.id },
data: { balance: { increment: poTaxVal } },
});
}
if (apAcc && po.totalAmount > 0) {
await prisma.account.update({
where: { id: apAcc.id },
data: { balance: { increment: po.totalAmount } },
@@ -1031,17 +1190,26 @@ export async function PUT(req: Request) {
if (invAcc && apAcc && po.totalAmount > 0) {
const jCount = await prisma.journalEntry.count();
const journalLines: { accountId: string; type: string; amount: number }[] = [];
if (poInvVal > 0) {
journalLines.push({ accountId: invAcc.id, type: "DEBIT", amount: poInvVal });
}
if (taxInAcc && poTaxVal > 0) {
journalLines.push({ accountId: taxInAcc.id, type: "DEBIT", amount: poTaxVal });
} else if (poTaxVal > 0) {
// Fallback jika akun 1301 belum ada
journalLines.push({ accountId: invAcc.id, type: "DEBIT", amount: poTaxVal });
}
journalLines.push({ accountId: apAcc.id, type: "CREDIT", amount: po.totalAmount });
await prisma.journalEntry.create({
data: {
entryNumber: `JV-PO-${String(jCount + 1).padStart(4, "0")}`,
description: `Penerimaan Barang PO ${po.poNumber} (${poCompany}) dari ${po.supplier.name}`,
entryNumber: `JV-PO-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`,
description: `Penerimaan Barang PO ${po.poNumber} (${poCompany}) dari ${po.supplier.name}${poTaxVal > 0 ? ` (Inc. PPN Masukan ${po.taxRate}%)` : ""}`,
reference: po.poNumber,
companyName: poCompany,
lines: {
create: [
{ accountId: invAcc.id, type: "DEBIT", amount: po.totalAmount },
{ accountId: apAcc.id, type: "CREDIT", amount: po.totalAmount },
],
create: journalLines,
},
},
});
@@ -1076,28 +1244,51 @@ export async function PUT(req: Request) {
);
}
const { orderId, paidAmount: inputPaidAmount, paymentNotes, paymentStatus: manualStatus } = body;
const po = await prisma.purchaseOrder.findUnique({
where: { id: body.orderId },
where: { id: orderId || body.orderId },
include: { supplier: true },
});
if (!po) {
return NextResponse.json({ error: "PO tidak ditemukan" }, { status: 404 });
}
const targetPaymentStatus =
String(body.paymentStatus || "PAID").toUpperCase() === "UNPAID" ? "UNPAID" : "PAID";
const wasAlreadyPaid = po.paymentStatus === "PAID";
const totalPO = po.totalAmount;
const prevPaid = po.paidAmount || (po.paymentStatus === "PAID" ? totalPO : 0);
let finalPaid = prevPaid;
if (inputPaidAmount !== undefined && inputPaidAmount !== "") {
finalPaid = Math.max(0, parseFloat(inputPaidAmount) || 0);
} else if (manualStatus === "PAID") {
finalPaid = totalPO;
} else if (manualStatus === "UNPAID") {
finalPaid = 0;
}
let finalPaymentStatus = "UNPAID";
if (finalPaid >= totalPO && totalPO > 0) {
finalPaid = totalPO;
finalPaymentStatus = "PAID";
} else if (finalPaid > 0) {
finalPaymentStatus = "PARTIAL"; // DP / Pembayaran Termin
} else {
finalPaid = 0;
finalPaymentStatus = "UNPAID";
}
const delta = finalPaid - prevPaid;
const updated = await prisma.purchaseOrder.update({
where: { id: po.id },
data: {
paymentStatus: targetPaymentStatus,
paidAt: targetPaymentStatus === "PAID" ? new Date() : null,
paidAmount: finalPaid,
paymentStatus: finalPaymentStatus,
paidAt: finalPaid > 0 ? (po.paidAt || new Date()) : null,
paidBy: user.name,
paymentNotes: body.paymentNotes || null,
...(targetPaymentStatus === "PAID" && po.status === "RECEIVED"
paymentNotes: paymentNotes !== undefined ? String(paymentNotes).trim() : po.paymentNotes,
...(finalPaymentStatus === "PAID" && po.status === "RECEIVED"
? { status: "COMPLETED" }
: targetPaymentStatus === "UNPAID" && po.status === "COMPLETED"
: finalPaymentStatus !== "PAID" && po.status === "COMPLETED"
? { status: "RECEIVED" }
: {}),
},
@@ -1107,73 +1298,427 @@ export async function PUT(req: Request) {
const apAcc = await getCompanyAccount("2001", poCompany);
const bankAcc = await getCompanyAccount("1002", poCompany);
// Jika dikonfirmasi PAID dari UNPAID -> bukukan pelunasan utang usaha
if (targetPaymentStatus === "PAID" && !wasAlreadyPaid) {
if (apAcc) {
await prisma.account.update({
where: { id: apAcc.id },
data: { balance: { decrement: po.totalAmount } },
});
}
if (bankAcc) {
await prisma.account.update({
where: { id: bankAcc.id },
data: { balance: { decrement: po.totalAmount } },
});
}
if (apAcc && bankAcc && po.totalAmount > 0) {
const jCount = await prisma.journalEntry.count();
await prisma.journalEntry.create({
data: {
entryNumber: `JV-OUT-${String(jCount + 1).padStart(4, "0")}`,
description: `Konfirmasi Pelunasan (PAID) Tagihan PO ${po.poNumber} (${poCompany}) kepada ${po.supplier.name}`,
reference: po.poNumber,
companyName: poCompany,
lines: {
create: [
{ accountId: apAcc.id, type: "DEBIT", amount: po.totalAmount },
{ accountId: bankAcc.id, type: "CREDIT", amount: po.totalAmount },
],
if (delta !== 0) {
if (delta > 0) {
// Bayar uang muka (DP) atau pelunasan: kurangi utang AP & kurangi kas bank
if (apAcc) {
await prisma.account.update({
where: { id: apAcc.id },
data: { balance: { decrement: delta } },
});
}
if (bankAcc) {
await prisma.account.update({
where: { id: bankAcc.id },
data: { balance: { decrement: delta } },
});
}
if (apAcc && bankAcc) {
const jCount = await prisma.journalEntry.count();
await prisma.journalEntry.create({
data: {
entryNumber: `JV-PAY-PO-${String(jCount + 1).padStart(4, "0")}`,
description: `${finalPaymentStatus === "PARTIAL" ? "Pembayaran Uang Muka (DP) / Termin" : "Pelunasan"} PO ${po.poNumber} (${poCompany}) kepada ${po.supplier.name}`,
reference: po.poNumber,
companyName: poCompany,
lines: {
create: [
{ accountId: apAcc.id, type: "DEBIT", amount: delta },
{ accountId: bankAcc.id, type: "CREDIT", amount: delta },
],
},
},
},
});
}
} else if (targetPaymentStatus === "UNPAID" && wasAlreadyPaid) {
// Jika dikembalikan ke UNPAID dari PAID -> kembalikan saldo utang & kas
if (apAcc) {
await prisma.account.update({
where: { id: apAcc.id },
data: { balance: { increment: po.totalAmount } },
});
}
if (bankAcc) {
await prisma.account.update({
where: { id: bankAcc.id },
data: { balance: { increment: po.totalAmount } },
});
});
}
} else {
// Pengembalian / koreksi penurunan nominal bayar
const absDelta = Math.abs(delta);
if (apAcc) {
await prisma.account.update({
where: { id: apAcc.id },
data: { balance: { increment: absDelta } },
});
}
if (bankAcc) {
await prisma.account.update({
where: { id: bankAcc.id },
data: { balance: { increment: absDelta } },
});
}
}
}
const remainingDebt = Math.max(0, totalPO - finalPaid);
await logAudit({
userId: user.id,
userName: user.name,
action: "CONFIRM_PAYMENT",
module: "PURCHASING",
description: `[${user.role}] Mengonfirmasi status payment PO ${po.poNumber} menjadi ${targetPaymentStatus}. Catatan: ${body.paymentNotes || "-"}`,
metadata: { poNumber: po.poNumber, paymentStatus: targetPaymentStatus, paymentNotes: body.paymentNotes },
description: `[${user.role}] Pembayaran PO ${po.poNumber} (${finalPaymentStatus}): Bayar Rp ${finalPaid.toLocaleString("id-ID")} (Sisa Hutang: Rp ${remainingDebt.toLocaleString("id-ID")}). Catatan: ${paymentNotes || "-"}`,
metadata: {
poNumber: po.poNumber,
paymentStatus: finalPaymentStatus,
paidAmount: finalPaid,
remainingDebt,
paymentNotes: paymentNotes || body.paymentNotes,
},
});
await dispatchNotification({
type: "MONEY_OUT",
title: `Konfirmasi Payment PO (${targetPaymentStatus}): ${po.poNumber}`,
message: `Status pembayaran PO ${po.poNumber} (${po.supplier.name}) sebesar Rp ${po.totalAmount.toLocaleString("id-ID")} telah dikonfirmasi oleh Finance (${user.name}) sebagai ${targetPaymentStatus}.`,
title: `Pembayaran PO (${finalPaymentStatus === "PARTIAL" ? "DP" : finalPaymentStatus}): ${po.poNumber}`,
message: `Pembayaran PO ${po.poNumber} (${po.supplier.name}) sebesar Rp ${finalPaid.toLocaleString("id-ID")} (${finalPaymentStatus === "PARTIAL" ? `DP / Kurang Bayar, Sisa Hutang: Rp ${remainingDebt.toLocaleString("id-ID")}` : "Lunas"}) telah dikonfirmasi oleh Finance (${user.name}).`,
targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "PURCHASING"],
});
return NextResponse.json({ success: true, order: updated });
}
// =========================================================================
// 4. UPDATE BIAYA FORWARDER, PAJAK MASUK & ONGKIR PO BELAKANGAN (KHUSUS FINANCE)
// =========================================================================
if (body.action === "UPDATE_PO_LOGISTICS") {
if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) {
return NextResponse.json(
{ error: `Akses ditolak: Hanya Finance (Akuntan), Manager, atau Admin yang berwenang menginput biaya ongkir, forwarder, dan pajak PO.` },
{ status: 403 }
);
}
const {
orderId,
logisticsMode: inputMode,
forwardingCompany,
allInCost,
shippingCost: inputShippingCost,
shippingCostUsd: inputShippingCostUsd,
exportCost: inputExportCost,
includeTax: inputIncludeTax,
taxRate: inputTaxRate,
notes: inputNotes,
} = body;
if (!orderId) {
return NextResponse.json({ error: "ID Purchase Order wajib disertakan" }, { status: 400 });
}
const po = await prisma.purchaseOrder.findUnique({
where: { id: orderId },
include: {
supplier: true,
items: true,
batches: true,
},
});
if (!po) {
return NextResponse.json({ error: "Purchase Order tidak ditemukan" }, { status: 404 });
}
const mode = inputMode === "ASSISTED_ALL_IN" ? "ASSISTED_ALL_IN" : "DETAILED";
const cleanForwarder =
mode === "ASSISTED_ALL_IN" && forwardingCompany
? String(forwardingCompany).trim()
: mode === "ASSISTED_ALL_IN"
? po.forwardingCompany
: null;
let newShippingCost = 0;
let newExportCost = 0;
let newShippingCostUsd: number | null = null;
if (mode === "ASSISTED_ALL_IN") {
const cleanAllIn = Math.max(0, parseFloat(allInCost) || 0);
newShippingCost = 0;
newExportCost = cleanAllIn;
newShippingCostUsd = null;
} else {
if (po.currency === "USD" && inputShippingCostUsd !== undefined && inputShippingCostUsd !== null && inputShippingCostUsd !== "") {
newShippingCostUsd = Math.max(0, parseFloat(inputShippingCostUsd) || 0);
newShippingCost = Math.round(newShippingCostUsd * (po.exchangeRate || 1));
} else {
newShippingCost = Math.max(0, parseFloat(inputShippingCost) || 0);
newShippingCostUsd = po.currency === "USD" && po.exchangeRate > 0 ? Number((newShippingCost / po.exchangeRate).toFixed(2)) : null;
}
newExportCost = Math.max(0, parseFloat(inputExportCost) || 0);
}
const itemsSubtotal = po.subtotalProducts > 0
? po.subtotalProducts
: po.items.reduce((sum, it) => sum + it.subtotal, 0);
const oldAdditionalCost = (po.shippingCost || 0) + (po.exportCost || 0);
const newAdditionalCost = newShippingCost + newExportCost;
const deltaLogisticsCost = newAdditionalCost - oldAdditionalCost;
const oldTaxVal = po.includeTax ? (po.taxAmount || 0) : 0;
const newIncludeTax = inputIncludeTax !== undefined ? Boolean(inputIncludeTax) : po.includeTax;
const newTaxRate = newIncludeTax
? Math.max(0, parseFloat(inputTaxRate !== undefined ? inputTaxRate : String(po.taxRate || 11)) || 11)
: 0;
const newTaxVal = newIncludeTax ? Math.round((itemsSubtotal * newTaxRate) / 100) : 0;
const deltaTax = newTaxVal - oldTaxVal;
const newTotalAmount = itemsSubtotal + newAdditionalCost + newTaxVal;
const deltaCost = newTotalAmount - po.totalAmount;
// Hitung ulang total USD bila mata uang USD
let newTotalAmountUsd = po.totalAmountUsd;
if (po.currency === "USD") {
const itemsSubtotalUsd = po.items.reduce(
(sum, it) => sum + (it.unitCostUsd || 0) * it.quantity,
0
);
newTotalAmountUsd =
mode === "ASSISTED_ALL_IN"
? itemsSubtotalUsd
: itemsSubtotalUsd + (newShippingCostUsd || 0);
}
// Sesuaikan status pembayaran jika total PO berubah setelah sebelumnya sudah dibayar/DP
const currentPaid = po.paidAmount || (po.paymentStatus === "PAID" ? po.totalAmount : 0);
let nextPaymentStatus = po.paymentStatus;
if (currentPaid >= newTotalAmount && newTotalAmount > 0) {
nextPaymentStatus = "PAID";
} else if (currentPaid > 0 && currentPaid < newTotalAmount) {
nextPaymentStatus = "PARTIAL";
} else {
nextPaymentStatus = "UNPAID";
}
const updatedPo = await prisma.purchaseOrder.update({
where: { id: orderId },
data: {
logisticsMode: mode,
forwardingCompany: cleanForwarder,
shippingCost: newShippingCost,
exportCost: newExportCost,
shippingCostUsd: newShippingCostUsd,
includeTax: newIncludeTax,
taxRate: newTaxRate,
taxAmount: newTaxVal,
totalAmountUsd: newTotalAmountUsd,
totalAmount: newTotalAmount,
paymentStatus: nextPaymentStatus,
...(inputNotes !== undefined && { notes: String(inputNotes).trim() || null }),
},
include: { supplier: true, items: { include: { product: true } }, batches: true },
});
// Jika PO sudah RECEIVED / sudah masuk batch gudang, perbarui Landed Cost (HPP) Batch & Produk + Jurnal Akuntansi!
if ((po.status === "RECEIVED" || po.batches.length > 0) && (deltaLogisticsCost !== 0 || deltaTax !== 0)) {
if (deltaLogisticsCost !== 0) {
for (const item of po.items) {
const itemRatio = itemsSubtotal > 0 ? item.subtotal / itemsSubtotal : 1 / Math.max(1, po.items.length);
const oldItemExtra = Math.round(oldAdditionalCost * itemRatio);
const newItemExtra = Math.round(newAdditionalCost * itemRatio);
const oldUnitCost = Math.round((item.subtotal + oldItemExtra) / Math.max(1, item.quantity));
const newUnitCost = Math.round((item.subtotal + newItemExtra) / Math.max(1, item.quantity));
const unitCostDelta = newUnitCost - oldUnitCost;
// Update unitCost di PurchaseBatch untuk PO & produk ini
await prisma.purchaseBatch.updateMany({
where: { purchaseOrderId: po.id, productId: item.productId },
data: { unitCost: newUnitCost },
});
// Sesuaikan rata-rata HPP produk secara proporsional
if (unitCostDelta !== 0) {
const prod = await prisma.product.findUnique({
where: { id: item.productId },
include: { stockItems: true },
});
if (prod) {
const totalStock = prod.stockItems.reduce((acc, s) => acc + s.quantity, 0);
const batchForItem = po.batches.find((b) => b.productId === item.productId);
const remainingBatchQty = batchForItem ? batchForItem.remainingQty : item.quantity;
const weight = totalStock > 0 ? Math.min(1, remainingBatchQty / totalStock) : 1;
const adjustedHpp = Math.max(0, Math.round((prod.purchasePrice || 0) + unitCostDelta * weight));
await prisma.product.update({
where: { id: prod.id },
data: { purchasePrice: adjustedHpp },
});
}
}
}
}
// Update Akuntansi: Persediaan (1201), PPN Masukan (1301) & Hutang Usaha (2001)
const poCompany = po.companyName || "PT EnterpriseCore Utama";
const invAcc = await getCompanyAccount("1201", poCompany);
const taxInAcc = await getCompanyAccount("1301", poCompany);
const apAcc = await getCompanyAccount("2001", poCompany);
if (invAcc && deltaLogisticsCost !== 0) {
await prisma.account.update({
where: { id: invAcc.id },
data: { balance: { increment: deltaLogisticsCost } },
});
}
if (taxInAcc && deltaTax !== 0) {
await prisma.account.update({
where: { id: taxInAcc.id },
data: { balance: { increment: deltaTax } },
});
}
if (apAcc && deltaCost !== 0) {
await prisma.account.update({
where: { id: apAcc.id },
data: { balance: { increment: deltaCost } },
});
}
if (apAcc && (deltaLogisticsCost !== 0 || deltaTax !== 0)) {
const lines: { accountId: string; type: string; amount: number }[] = [];
if (invAcc && deltaLogisticsCost !== 0) {
lines.push({
accountId: invAcc.id,
type: deltaLogisticsCost > 0 ? "DEBIT" : "CREDIT",
amount: Math.abs(deltaLogisticsCost),
});
}
if (taxInAcc && deltaTax !== 0) {
lines.push({
accountId: taxInAcc.id,
type: deltaTax > 0 ? "DEBIT" : "CREDIT",
amount: Math.abs(deltaTax),
});
}
if (deltaCost !== 0) {
lines.push({
accountId: apAcc.id,
type: deltaCost > 0 ? "CREDIT" : "DEBIT",
amount: Math.abs(deltaCost),
});
}
if (lines.length >= 2) {
const jCount = await prisma.journalEntry.count();
await prisma.journalEntry.create({
data: {
entryNumber: `JV-LOG-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`,
description: `Penyesuaian Biaya ${mode === "ASSISTED_ALL_IN" ? `Forwarder${cleanForwarder ? ` (${cleanForwarder})` : ""}` : "Ongkir & Pajak"} PO ${po.poNumber} (${poCompany})${newIncludeTax ? ` [PPN ${newTaxRate}%]` : ""}`,
reference: po.poNumber,
companyName: poCompany,
lines: { create: lines },
},
});
}
}
}
const modeLabel =
mode === "ASSISTED_ALL_IN"
? `Via Forwarder${cleanForwarder ? ` (${cleanForwarder})` : ""}: Rp ${newExportCost.toLocaleString("id-ID")}`
: `Ongkir: Rp ${newShippingCost.toLocaleString("id-ID")}, Bea Cukai/Pajak: Rp ${newExportCost.toLocaleString("id-ID")}`;
await logAudit({
userId: user.id,
userName: user.name,
action: "UPDATE_PO_LOGISTICS",
module: "PURCHASING",
description: `[${user.role}] Memperbarui biaya logistik/forwarder PO ${po.poNumber} (${modeLabel}). Total PO baru: Rp ${newTotalAmount.toLocaleString("id-ID")}.`,
metadata: {
orderId,
poNumber: po.poNumber,
logisticsMode: mode,
forwardingCompany: cleanForwarder,
shippingCost: newShippingCost,
exportCost: newExportCost,
deltaCost,
newTotalAmount,
},
});
await dispatchNotification({
type: "MONEY_OUT",
title: `Update Biaya Forwarder / Pajak PO: ${po.poNumber}`,
message: `${user.name} (${user.role}) memperbarui biaya logistik PO ${po.poNumber} (${modeLabel}). Total nilai PO kini Rp ${newTotalAmount.toLocaleString("id-ID")}${po.status === "RECEIVED" ? " & HPP (Landed Cost) telah disesuaikan otomatis." : "."}`,
targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "PURCHASING"],
});
return NextResponse.json({ success: true, order: updatedPo });
}
// =========================================================================
// 5. UPDATE / CATAT SERIAL NUMBER (SN) BARANG MASUK OLEH GUDANG (MANUAL / EXCEL)
// =========================================================================
if (body.action === "UPDATE_PO_SERIALS") {
if (!["ADMIN", "MANAGER", "INVENTORY", "PURCHASING"].includes(user.role)) {
return NextResponse.json(
{
error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang mencatat Serial Number barang masuk.`,
},
{ status: 403 }
);
}
const { orderId, itemSerialNumbers } = body;
if (!orderId || !itemSerialNumbers || typeof itemSerialNumbers !== "object") {
return NextResponse.json(
{ error: "ID Purchase Order dan daftar Serial Number wajib disertakan" },
{ status: 400 }
);
}
const po = await prisma.purchaseOrder.findUnique({
where: { id: orderId },
include: { items: { include: { product: true } } },
});
if (!po) {
return NextResponse.json({ error: "Purchase Order tidak ditemukan" }, { status: 404 });
}
let updatedCount = 0;
const summaryParts: string[] = [];
for (const item of po.items) {
if (item.product?.isService) continue;
if (!(item.id in itemSerialNumbers)) continue;
const rawSn = itemSerialNumbers[item.id];
const cleanSn = rawSn ? String(rawSn).trim() : null;
await prisma.purchaseOrderItem.update({
where: { id: item.id },
data: { serialNumbers: cleanSn },
});
await prisma.purchaseBatch.updateMany({
where: { purchaseOrderId: po.id, productId: item.productId },
data: { serialNumbers: cleanSn },
});
await prisma.stockMovement.updateMany({
where: {
referenceType: "PURCHASE_ORDER",
referenceId: po.poNumber,
productId: item.productId,
type: "IN",
},
data: { serialNumbers: cleanSn },
});
const snTotal = cleanSn
? Array.from(new Set(cleanSn.split(/[\n,;]+/).map((s) => s.trim()).filter(Boolean))).length
: 0;
summaryParts.push(`${item.product?.name || "Produk"} (${snTotal} SN)`);
updatedCount++;
}
await logAudit({
userId: user.id,
userName: user.name,
action: "UPDATE_PO_SERIALS",
module: "PURCHASING",
description: `[${user.role}] Memperbarui pencatatan Serial Number (SN) barang masuk PO ${po.poNumber}: ${summaryParts.join(", ") || "-"}`,
metadata: { orderId, poNumber: po.poNumber, updatedCount },
});
return NextResponse.json({ success: true, updatedCount });
}
return NextResponse.json({ error: "Tindakan tidak dikenal" }, { status: 400 });
} catch (error: any) {
console.error("Purchases PUT error:", error);
+848 -242
View File
File diff suppressed because it is too large. Load diff
+77
View File
@@ -0,0 +1,77 @@
import { NextResponse } from "next/server";
import fs from "fs/promises";
import os from "os";
import path from "path";
import crypto from "crypto";
import { getCurrentUser } from "@/lib/auth";
import { getPrismaByMode } from "@/lib/db";
import { logAudit } from "@/lib/audit";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET() {
let tmpBackupPath = "";
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
if (user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Akses ditolak: Hanya Super Admin yang berwenang mengunduh backup database." },
{ status: 403 }
);
}
const mode = "LIVE";
const db = getPrismaByMode(mode);
const now = new Date();
const pad = (n: number) => String(n).padStart(2, "0");
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(
now.getHours()
)}${pad(now.getMinutes())}`;
const randomId = crypto.randomBytes(6).toString("hex");
tmpBackupPath = path.join(os.tmpdir(), `erp-backup-${mode.toLowerCase()}-${stamp}-${randomId}.db`);
// SQLite VACUUM INTO menghasilkan salinan snapshot konsisten secara atomik meski database sedang aktif
const escapedPath = tmpBackupPath.replace(/'/g, "''");
await db.$executeRawUnsafe(`VACUUM INTO '${escapedPath}'`);
const buffer = await fs.readFile(tmpBackupPath);
await logAudit({
userId: user.id,
userName: user.name,
action: "DATABASE_BACKUP",
module: "SYSTEM",
description: `Admin ${user.name} mengunduh snapshot backup database mode ${mode} (${Math.round(
buffer.length / 1024
)} KB)`,
});
const filename = `EnterpriseCore-${mode}-Backup-${stamp}.db`;
return new NextResponse(buffer, {
status: 200,
headers: {
"Content-Type": "application/octet-stream",
"Content-Disposition": `attachment; filename="${filename}"`,
"Content-Length": String(buffer.length),
"Cache-Control": "no-store, no-cache, must-revalidate",
"X-Content-Type-Options": "nosniff",
},
});
} catch (error: any) {
console.error("Database backup error:", error);
return NextResponse.json(
{ error: "Gagal membuat backup database: " + (error?.message || "Kesalahan internal") },
{ status: 500 }
);
} finally {
if (tmpBackupPath) {
await fs.unlink(tmpBackupPath).catch(() => {});
}
}
}
+68 -6
View File
@@ -1,19 +1,34 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { getAllSettings, sendTelegramMessage, dispatchNotification } from "@/lib/notifier";
import {
getAllSettings,
sendTelegramMessage,
sendEmailNotification,
dispatchNotification,
} from "@/lib/notifier";
import { logAudit } from "@/lib/audit";
const ALLOWED_SETTING_KEYS = new Set([
"TELEGRAM_ENABLED",
"TELEGRAM_BOT_TOKEN",
"TELEGRAM_CHAT_ID",
"TELEGRAM_CHAT_ID_MANAGEMENT",
"TELEGRAM_CHAT_ID_INVENTORY",
"TELEGRAM_CHAT_ID_SALES",
"TELEGRAM_CHAT_ID_PURCHASING",
"TELEGRAM_CHAT_ID_FINANCE",
"EMAIL_ENABLED",
"SMTP_HOST",
"SMTP_PORT",
"SMTP_USER",
"SMTP_PASS",
"SMTP_FROM",
"NOTIF_STOCK_IN_ENABLED",
"NOTIF_STOCK_OUT_ENABLED",
"NOTIF_MONEY_IN_ENABLED",
"NOTIF_MONEY_OUT_ENABLED",
"NOTIF_RMA_ENABLED",
"ALERT_ON_STOCK_IN",
"ALERT_ON_STOCK_OUT",
"ALERT_ON_LOW_STOCK",
@@ -39,11 +54,8 @@ export async function GET() {
const settings: Record<string, string> = {};
for (const [key, val] of Object.entries(rawSettings)) {
if (!ALLOWED_SETTING_KEYS.has(key)) continue;
if (
user.role !== "ADMIN" &&
(key === "SMTP_PASS" || key === "TELEGRAM_BOT_TOKEN") &&
val
) {
// Selalu samarkan kredensial sensitif saat dikirim ke browser (termasuk untuk Admin)
if ((key === "SMTP_PASS" || key === "TELEGRAM_BOT_TOKEN") && val) {
settings[key] = "••••••••";
} else {
settings[key] = val;
@@ -157,6 +169,56 @@ export async function PUT(req: Request) {
}
return NextResponse.json({ success: true, message: "Pesan tes berhasil dikirim ke Telegram!" });
} else if (channel === "EMAIL") {
const savedSettings = await getAllSettings();
const mergedSettings = {
...savedSettings,
...(body.smtpHost ? { SMTP_HOST: String(body.smtpHost) } : {}),
...(body.smtpPort ? { SMTP_PORT: String(body.smtpPort) } : {}),
...(body.smtpUser ? { SMTP_USER: String(body.smtpUser) } : {}),
...(body.smtpPass && body.smtpPass !== "••••••••" ? { SMTP_PASS: String(body.smtpPass) } : {}),
...(body.smtpFrom ? { SMTP_FROM: String(body.smtpFrom) } : {}),
};
const targetEmail = String(body.testEmail || user.email || "").trim();
if (!targetEmail) {
return NextResponse.json({ error: "Alamat email tujuan uji coba wajib diisi." }, { status: 400 });
}
const mailRes = await sendEmailNotification(mergedSettings, {
to: targetEmail,
recipientName: user.name,
recipientRole: user.role,
type: "SYSTEM",
title: "Uji Coba Pengiriman Email SMTP — EnterpriseCore ERP",
message: `Halo ${user.name}, ini adalah email uji coba dari sistem notifikasi EnterpriseCore ERP. Jika Anda menerima pesan ini, konfigurasi SMTP sudah aktif dan notifikasi otomatis per divisi siap berjalan ke email masing-masing staf.`,
});
await prisma.notificationLog.create({
data: {
recipient: `${user.name} [${user.role}] <${targetEmail}>`,
channel: "EMAIL",
type: "SYSTEM",
title: "Uji Coba Email SMTP",
message: mailRes.error || `Email uji coba berhasil dikirim ke ${targetEmail}`,
status: mailRes.status,
},
});
if (mailRes.status === "FAILED") {
return NextResponse.json(
{ error: `Gagal mengirim email SMTP: ${mailRes.error}` },
{ status: 400 }
);
}
return NextResponse.json({
success: true,
status: mailRes.status,
message:
mailRes.status === "SIMULATED"
? "SMTP User/Password belum diisi — notifikasi dicatat sebagai SIMULATED. Isi SMTP Host, Port, User & App Password untuk pengiriman email asli."
: `Email uji coba berhasil dikirim ke ${targetEmail}! Silakan periksa kotak masuk / folder Spam.`,
});
} else {
// Test broadcast
await dispatchNotification({
+108 -18
View File
@@ -3,6 +3,7 @@ import { prisma } from "@/lib/db";
import { getCurrentUser, hashPassword } from "@/lib/auth";
import { logAudit } from "@/lib/audit";
import { generateMfaSecret } from "@/lib/mfa";
import { getRoleDefaultNotifications, isRoleAllowedNotifType } from "@/lib/permissions";
const VALID_ROLES = new Set([
"ADMIN",
@@ -11,14 +12,29 @@ const VALID_ROLES = new Set([
"SALES",
"PURCHASING",
"INVENTORY",
"STAFF",
]);
function validateStrongPassword(pw: string): string | null {
const clean = String(pw || "").trim();
if (clean.length < 8) {
return "Password minimal harus 8 karakter demi keamanan akun.";
}
if (!/[a-zA-Z]/.test(clean) || !/[0-9]/.test(clean)) {
return "Password harus mengandung kombinasi huruf dan angka.";
}
return null;
}
function isValidEmailFormat(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(email || "").trim());
}
const USER_SELECT = {
id: true,
name: true,
email: true,
role: true,
isActive: true,
telegramChatId: true,
notifyEmail: true,
notifyTelegram: true,
@@ -26,6 +42,7 @@ const USER_SELECT = {
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: true,
mfaEnabled: true,
mfaMethod: true,
createdAt: true,
@@ -57,8 +74,16 @@ export async function GET() {
} else {
// Non-Superadmin:
// 1. Pengguna hanya melihat profil akun dirinya sendiri
// 2. History Operasional: semua user bisa melihat riwayat terkait PO, stok, pembelian, penjualan & keuangan
// Hanya menyembunyikan riwayat akses login serta add/edit akun user
// 2. History Operasional disesuaikan dengan divisi & hak akses data keuangan
const allowedModules =
currentUser.role === "MANAGER" || currentUser.role === "ACCOUNTANT"
? undefined
: currentUser.role === "SALES"
? ["SALES", "INVENTORY"]
: currentUser.role === "PURCHASING"
? ["PURCHASING", "INVENTORY"]
: ["INVENTORY"];
const [selfUser, operationalLogs] = await Promise.all([
prisma.user.findUnique({
where: { id: currentUser.id },
@@ -66,6 +91,7 @@ export async function GET() {
}),
prisma.auditLog.findMany({
where: {
...(allowedModules ? { module: { in: allowedModules } } : {}),
NOT: [
{ action: { in: ["LOGIN", "LOGIN_MFA", "CREATE_USER", "UPDATE_USER"] } },
{ module: "AUTH" },
@@ -117,6 +143,8 @@ export async function POST(req: Request) {
notifStockOut,
notifMoneyIn,
notifMoneyOut,
notifRma,
isActive,
mfaEnabled,
mfaMethod,
} = body;
@@ -135,13 +163,18 @@ export async function POST(req: Request) {
);
}
if (String(password).trim().length < 6) {
if (!isValidEmailFormat(email)) {
return NextResponse.json(
{ error: "Password minimal harus 6 karakter" },
{ error: "Format alamat email tidak valid" },
{ status: 400 }
);
}
const pwError = validateStrongPassword(password);
if (pwError) {
return NextResponse.json({ error: pwError }, { status: 400 });
}
const existing = await prisma.user.findUnique({
where: { email: email.toLowerCase().trim() },
});
@@ -154,6 +187,7 @@ export async function POST(req: Request) {
}
const hashedPassword = await hashPassword(password);
const roleDefaults = getRoleDefaultNotifications(role);
const user = await prisma.user.create({
data: {
@@ -161,13 +195,25 @@ export async function POST(req: Request) {
email: email.toLowerCase().trim(),
password: hashedPassword,
role,
isActive: isActive !== undefined ? Boolean(isActive) : true,
telegramChatId: telegramChatId ? telegramChatId.trim() : null,
notifyEmail: notifyEmail !== undefined ? Boolean(notifyEmail) : true,
notifyTelegram: notifyTelegram !== undefined ? Boolean(notifyTelegram) : false,
notifStockIn: notifStockIn !== undefined ? Boolean(notifStockIn) : true,
notifStockOut: notifStockOut !== undefined ? Boolean(notifStockOut) : true,
notifMoneyIn: notifMoneyIn !== undefined ? Boolean(notifMoneyIn) : true,
notifMoneyOut: notifMoneyOut !== undefined ? Boolean(notifMoneyOut) : true,
notifStockIn:
isRoleAllowedNotifType(role, "STOCK_IN") &&
(notifStockIn !== undefined ? Boolean(notifStockIn) : roleDefaults.notifStockIn),
notifStockOut:
isRoleAllowedNotifType(role, "STOCK_OUT") &&
(notifStockOut !== undefined ? Boolean(notifStockOut) : roleDefaults.notifStockOut),
notifMoneyIn:
isRoleAllowedNotifType(role, "MONEY_IN") &&
(notifMoneyIn !== undefined ? Boolean(notifMoneyIn) : roleDefaults.notifMoneyIn),
notifMoneyOut:
isRoleAllowedNotifType(role, "MONEY_OUT") &&
(notifMoneyOut !== undefined ? Boolean(notifMoneyOut) : roleDefaults.notifMoneyOut),
notifRma:
isRoleAllowedNotifType(role, "RMA_SERVICE") &&
(notifRma !== undefined ? Boolean(notifRma) : roleDefaults.notifRma),
mfaEnabled: Boolean(mfaEnabled),
mfaMethod: mfaMethod || "TOTP",
mfaSecret: `PENDING:${generateMfaSecret()}`,
@@ -211,6 +257,8 @@ export async function PUT(req: Request) {
notifStockOut,
notifMoneyIn,
notifMoneyOut,
notifRma,
isActive,
mfaEnabled,
mfaMethod,
} = body;
@@ -246,6 +294,12 @@ export async function PUT(req: Request) {
// 2. Alamat Email (Bisa diubah oleh pengguna itu sendiri maupun Super Admin)
if (email !== undefined && email.trim() !== "") {
if (!isValidEmailFormat(email)) {
return NextResponse.json(
{ error: "Format alamat email tidak valid" },
{ status: 400 }
);
}
const cleanEmail = email.toLowerCase().trim();
const duplicate = await prisma.user.findUnique({
where: { email: cleanEmail },
@@ -261,11 +315,9 @@ export async function PUT(req: Request) {
// 3. Password (Bisa diubah oleh pengguna itu sendiri maupun Super Admin)
if (password && password.trim().length > 0) {
if (password.trim().length < 6) {
return NextResponse.json(
{ error: "Password baru minimal harus 6 karakter" },
{ status: 400 }
);
const pwError = validateStrongPassword(password);
if (pwError) {
return NextResponse.json({ error: pwError }, { status: 400 });
}
updateData.password = await hashPassword(password.trim());
}
@@ -287,13 +339,51 @@ export async function PUT(req: Request) {
updateData.role = role;
}
// 4B. Status Aktif / Nonaktif Akses Login (KHUSUS SUPER ADMIN)
if (isAdmin && isActive !== undefined) {
if (isSelf && !Boolean(isActive)) {
return NextResponse.json(
{ error: "Anda tidak dapat menonaktifkan akun Super Admin milik Anda sendiri" },
{ status: 400 }
);
}
updateData.isActive = Boolean(isActive);
}
const targetRecord = await prisma.user.findUnique({
where: { id: userId },
select: { role: true },
});
const effectiveRole = updateData.role || targetRecord?.role || "SALES";
if (telegramChatId !== undefined) updateData.telegramChatId = telegramChatId ? telegramChatId.trim() : null;
if (notifyEmail !== undefined) updateData.notifyEmail = Boolean(notifyEmail);
if (notifyTelegram !== undefined) updateData.notifyTelegram = Boolean(notifyTelegram);
if (notifStockIn !== undefined) updateData.notifStockIn = Boolean(notifStockIn);
if (notifStockOut !== undefined) updateData.notifStockOut = Boolean(notifStockOut);
if (notifMoneyIn !== undefined) updateData.notifMoneyIn = Boolean(notifMoneyIn);
if (notifMoneyOut !== undefined) updateData.notifMoneyOut = Boolean(notifMoneyOut);
if (notifStockIn !== undefined || updateData.role) {
updateData.notifStockIn =
isRoleAllowedNotifType(effectiveRole, "STOCK_IN") &&
(notifStockIn !== undefined ? Boolean(notifStockIn) : getRoleDefaultNotifications(effectiveRole).notifStockIn);
}
if (notifStockOut !== undefined || updateData.role) {
updateData.notifStockOut =
isRoleAllowedNotifType(effectiveRole, "STOCK_OUT") &&
(notifStockOut !== undefined ? Boolean(notifStockOut) : getRoleDefaultNotifications(effectiveRole).notifStockOut);
}
if (notifMoneyIn !== undefined || updateData.role) {
updateData.notifMoneyIn =
isRoleAllowedNotifType(effectiveRole, "MONEY_IN") &&
(notifMoneyIn !== undefined ? Boolean(notifMoneyIn) : getRoleDefaultNotifications(effectiveRole).notifMoneyIn);
}
if (notifMoneyOut !== undefined || updateData.role) {
updateData.notifMoneyOut =
isRoleAllowedNotifType(effectiveRole, "MONEY_OUT") &&
(notifMoneyOut !== undefined ? Boolean(notifMoneyOut) : getRoleDefaultNotifications(effectiveRole).notifMoneyOut);
}
if (notifRma !== undefined || updateData.role) {
updateData.notifRma =
isRoleAllowedNotifType(effectiveRole, "RMA_SERVICE") &&
(notifRma !== undefined ? Boolean(notifRma) : getRoleDefaultNotifications(effectiveRole).notifRma);
}
if (mfaEnabled !== undefined) {
updateData.mfaEnabled = Boolean(mfaEnabled);
+430 -52
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { Modal } from "@/components/Modal";
import { CurrencyInput } from "@/components/CurrencyInput";
import { formatRupiah, formatDateTime, exportToCSV, escapeHtml } from "@/lib/utils";
import {
Plus,
@@ -62,15 +63,17 @@ export default function FinancePage() {
const [journalEntries, setJournalEntries] = useState<any[]>([]);
const [payrollRecords, setPayrollRecords] = useState<any[]>([]);
const [payrollEmployees, setPayrollEmployees] = useState<any[]>([]);
const [arList, setArList] = useState<any[]>([]);
const [apList, setApList] = useState<any[]>([]);
const [positions, setPositions] = useState<string[]>(DEFAULT_POSITIONS);
const [companies, setCompanies] = useState<string[]>(DEFAULT_COMPANIES);
const [selectedCompanyFilter, setSelectedCompanyFilter] = useState<string>("ALL");
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<
"payroll" | "coa" | "journal" | "companies"
>("payroll");
"reports" | "payroll" | "coa" | "journal" | "companies"
>("reports");
const switchFinanceTab = (tab: "payroll" | "coa" | "journal" | "companies") => {
const switchFinanceTab = (tab: "reports" | "payroll" | "coa" | "journal" | "companies") => {
setActiveTab(tab);
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_finance_tab", tab);
@@ -164,6 +167,8 @@ export default function FinancePage() {
setAccounts(json.accounts || []);
setJournalEntries(json.journalEntries || []);
setPayrollRecords(json.payrollRecords || []);
setArList(json.arList || []);
setApList(json.apList || []);
const savedEmps = json.payrollEmployees || [];
setPayrollEmployees(savedEmps);
@@ -224,6 +229,7 @@ export default function FinancePage() {
}
const savedTab = sessionStorage.getItem("erp_finance_tab");
if (
savedTab === "reports" ||
savedTab === "payroll" ||
savedTab === "coa" ||
savedTab === "journal" ||
@@ -237,6 +243,7 @@ export default function FinancePage() {
const handleSidebarTabChange = (e: any) => {
const t = e?.detail?.tab;
if (
t === "reports" ||
t === "payroll" ||
t === "coa" ||
t === "journal" ||
@@ -304,15 +311,86 @@ export default function FinancePage() {
.filter((a) => a.type === "ASSET")
.reduce((sum, a) => sum + a.balance, 0);
const totalLiabilities = filteredAccounts
.filter((a) => a.type === "LIABILITY")
.reduce((sum, a) => sum + a.balance, 0);
const totalEquity = filteredAccounts
.filter((a) => a.type === "EQUITY")
.reduce((sum, a) => sum + a.balance, 0);
const totalRevenue = filteredAccounts
.filter((a) => a.type === "REVENUE")
.reduce((sum, a) => sum + a.balance, 0);
const totalExpenses = filteredAccounts
.filter((a) => a.type === "EXPENSE")
const totalCogs = filteredAccounts
.filter((a) => a.type === "EXPENSE" && String(a.code || "").startsWith("5"))
.reduce((sum, a) => sum + a.balance, 0);
const totalOpex = filteredAccounts
.filter((a) => a.type === "EXPENSE" && !String(a.code || "").startsWith("5"))
.reduce((sum, a) => sum + a.balance, 0);
const totalExpenses = totalCogs + totalOpex;
const grossProfit = totalRevenue - totalCogs;
const netProfit = totalRevenue - totalExpenses;
const totalLiabAndEquity = totalLiabilities + totalEquity + netProfit;
const isBalanceSheetBalanced = Math.abs(totalAssets - totalLiabAndEquity) < 1;
const filteredArList =
selectedCompanyFilter === "ALL"
? arList
: arList.filter((x) => (x.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter);
const filteredApList =
selectedCompanyFilter === "ALL"
? apList
: apList.filter((x) => (x.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter);
const totalArRemaining = filteredArList.reduce((s, x) => s + (x.remaining || 0), 0);
const totalApRemaining = filteredApList.reduce((s, x) => s + (x.remaining || 0), 0);
const handleExportFinancialReport = () => {
const labelPt = selectedCompanyFilter === "ALL" ? "Semua_PT" : selectedCompanyFilter.replace(/\s+/g, "_");
const headers = ["Bagian", "Kode / Referensi", "Akun / Keterangan", "Entitas PT", "Nominal (Rp)"];
const rows: (string | number)[][] = [
["LABA RUGI", "-", "Total Pendapatan", selectedCompanyFilter, totalRevenue],
["LABA RUGI", "5xxx", "Beban Pokok Penjualan (HPP)", selectedCompanyFilter, -totalCogs],
["LABA RUGI", "-", "LABA KOTOR", selectedCompanyFilter, grossProfit],
["LABA RUGI", "6xxx", "Beban Operasional & Gaji", selectedCompanyFilter, -totalOpex],
["LABA RUGI", "-", "LABA / RUGI BERSIH BERJALAN", selectedCompanyFilter, netProfit],
...filteredAccounts
.filter((a) => ["ASSET", "LIABILITY", "EQUITY"].includes(a.type))
.map((a) => [
`NERACA - ${a.type}`,
a.code,
a.name,
a.companyName || "PT EnterpriseCore Utama",
a.balance,
]),
["NERACA - TOTAL", "-", "TOTAL ASET", selectedCompanyFilter, totalAssets],
["NERACA - TOTAL", "-", "TOTAL KEWAJIBAN + EKUITAS + LABA BERJALAN", selectedCompanyFilter, totalLiabAndEquity],
...filteredArList.map((r) => [
"PIUTANG CUSTOMER (AR)",
r.number,
`${r.counterparty} (${r.ageDays} hari)`,
r.companyName,
r.remaining,
]),
...filteredApList.map((p) => [
"HUTANG VENDOR (AP)",
p.number,
`${p.counterparty} (${p.ageDays} hari)`,
p.companyName,
p.remaining,
]),
];
exportToCSV(
`Laporan_Keuangan_${labelPt}_${new Date().toISOString().slice(0, 10)}.csv`,
headers,
rows
);
};
// Live Payroll Calculator Values
const calculatedMealTotal = (Number(workDays) || 0) * (Number(dailyMealRate) || 0);
@@ -1017,8 +1095,8 @@ export default function FinancePage() {
return (
<AppShell
title="Keuangan, Multi-PT Payroll, Slip Gaji & Bagan Akun (COA)"
subtitle="Kelola penggajian terpisah per PT, cetak slip gaji, tambah/edit rekening bank (COA), serta jurnal umum"
title="Keuangan"
subtitle="Laporan Laba Rugi & Neraca, piutang/hutang, payroll per perusahaan, daftar akun (COA), dan jurnal"
>
{/* Financial Summary KPIs */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-8">
@@ -1081,7 +1159,9 @@ export default function FinancePage() {
<div className="flex items-center gap-2.5">
<div className="h-2.5 w-2.5 rounded-full bg-blue-600" />
<span className="text-sm font-bold text-slate-800">
{activeTab === "payroll"
{activeTab === "reports"
? `Laporan Keuangan: Laba Rugi, Neraca & Piutang/Hutang`
: activeTab === "payroll"
? `Payroll & Slip Gaji (${filteredPayrollRecords.length})`
: activeTab === "coa"
? `Kode Akun & Bank / COA (${filteredAccounts.length})`
@@ -1205,6 +1285,314 @@ export default function FinancePage() {
</div>
)}
{/* TAB 0: LAPORAN KEUANGAN (LABA RUGI, NERACA & AR/AP AGING) */}
{activeTab === "reports" && (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3 bg-white rounded-xl border border-slate-200 p-4 shadow-xs">
<div>
<h3 className="text-sm font-bold text-slate-900">
Laporan Keuangan Terkonsolidasi —{" "}
{selectedCompanyFilter === "ALL" ? "Semua Perusahaan" : selectedCompanyFilter}
</h3>
<p className="text-xs text-slate-500 mt-0.5">
Dihitung otomatis dari Buku Besar (COA), Jurnal, Sales Order, dan Purchase Order aktif
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={handleExportFinancialReport}
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg bg-white hover:bg-slate-50 text-slate-800 border border-slate-200 text-xs font-semibold transition-colors"
>
<Download className="h-3.5 w-3.5" />
<span>Export Excel / CSV</span>
</button>
<button
type="button"
onClick={handlePrintFinancialReport}
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg bg-slate-900 hover:bg-slate-800 text-white text-xs font-semibold transition-colors"
>
<Printer className="h-3.5 w-3.5" />
<span>Cetak Laporan</span>
</button>
</div>
</div>
{/* Laba Rugi & Neraca Side-by-Side */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Laporan Laba Rugi (Profit & Loss) */}
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
<div className="px-5 py-3.5 border-b border-slate-100 bg-slate-50/70 flex items-center justify-between">
<h4 className="text-sm font-bold text-slate-900">Laporan Laba Rugi (Profit &amp; Loss)</h4>
<span className="text-[11px] font-medium text-slate-500">Periode Berjalan</span>
</div>
<div className="p-5 space-y-4 text-xs">
<div className="space-y-1.5">
<div className="text-[11px] font-bold uppercase tracking-wider text-slate-500">
Pendapatan Usaha
</div>
{filteredAccounts.filter((a) => a.type === "REVENUE").length === 0 ? (
<div className="text-slate-400">Belum ada akun pendapatan.</div>
) : (
filteredAccounts
.filter((a) => a.type === "REVENUE")
.map((a) => (
<div key={a.id} className="flex items-center justify-between py-1 border-b border-slate-100">
<span className="text-slate-700">
<span className="font-mono text-slate-500 mr-2">{a.code}</span>
{a.name}
</span>
<span className="font-semibold text-slate-900 tabular-nums">{formatRupiah(a.balance)}</span>
</div>
))
)}
<div className="flex items-center justify-between pt-1 font-bold text-slate-900">
<span>Total Pendapatan</span>
<span className="tabular-nums">{formatRupiah(totalRevenue)}</span>
</div>
</div>
<div className="space-y-1.5">
<div className="text-[11px] font-bold uppercase tracking-wider text-slate-500">
Beban Pokok Penjualan (HPP)
</div>
{filteredAccounts
.filter((a) => a.type === "EXPENSE" && String(a.code || "").startsWith("5"))
.map((a) => (
<div key={a.id} className="flex items-center justify-between py-1 border-b border-slate-100">
<span className="text-slate-700">
<span className="font-mono text-slate-500 mr-2">{a.code}</span>
{a.name}
</span>
<span className="font-semibold text-slate-900 tabular-nums">{formatRupiah(a.balance)}</span>
</div>
))}
<div className="flex items-center justify-between pt-1.5 px-3 py-2 rounded-lg bg-slate-50 border border-slate-200 font-bold text-slate-900">
<span>Laba Kotor (Gross Profit)</span>
<span className="tabular-nums">{formatRupiah(grossProfit)}</span>
</div>
</div>
<div className="space-y-1.5">
<div className="text-[11px] font-bold uppercase tracking-wider text-slate-500">
Beban Operasional &amp; Gaji
</div>
{filteredAccounts
.filter((a) => a.type === "EXPENSE" && !String(a.code || "").startsWith("5"))
.map((a) => (
<div key={a.id} className="flex items-center justify-between py-1 border-b border-slate-100">
<span className="text-slate-700">
<span className="font-mono text-slate-500 mr-2">{a.code}</span>
{a.name}
</span>
<span className="font-semibold text-slate-900 tabular-nums">{formatRupiah(a.balance)}</span>
</div>
))}
</div>
<div className="flex items-center justify-between px-4 py-3 rounded-lg bg-slate-100 border border-slate-200 font-bold text-sm">
<span className="text-slate-900">Laba / Rugi Bersih</span>
<span className={`tabular-nums ${netProfit >= 0 ? "text-emerald-600" : "text-rose-600"}`}>
{formatRupiah(netProfit)}
</span>
</div>
</div>
</div>
{/* Laporan Neraca (Balance Sheet) */}
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
<div className="px-5 py-3.5 border-b border-slate-100 bg-slate-50/70 flex items-center justify-between gap-2">
<h4 className="text-sm font-bold text-slate-900">Neraca (Balance Sheet)</h4>
<span
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10.5px] font-semibold border ${
isBalanceSheetBalanced
? "bg-emerald-50 text-emerald-700 border-emerald-200"
: "bg-amber-50 text-amber-700 border-amber-200"
}`}
>
<CheckCircle2 className="h-3 w-3" />
{isBalanceSheetBalanced ? "Seimbang (Balance)" : "Cek Penyesuaian"}
</span>
</div>
<div className="p-5 space-y-4 text-xs">
<div className="space-y-1.5">
<div className="text-[11px] font-bold uppercase tracking-wider text-slate-500">
Aset (Aktiva)
</div>
{filteredAccounts
.filter((a) => a.type === "ASSET")
.map((a) => (
<div key={a.id} className="flex items-center justify-between py-1 border-b border-slate-100">
<span className="text-slate-700 truncate pr-2">
<span className="font-mono text-slate-500 mr-2">{a.code}</span>
{a.name}
</span>
<span className={`font-semibold tabular-nums whitespace-nowrap ${a.balance < 0 ? "text-rose-600" : "text-slate-900"}`}>
{formatRupiah(a.balance)}
</span>
</div>
))}
<div className="flex items-center justify-between pt-1.5 px-3 py-2 rounded-lg bg-slate-50 border border-slate-200 font-bold text-slate-900">
<span>Total Aset</span>
<span className="tabular-nums">{formatRupiah(totalAssets)}</span>
</div>
</div>
<div className="space-y-1.5">
<div className="text-[11px] font-bold uppercase tracking-wider text-slate-500">
Kewajiban (Liabilitas) &amp; Ekuitas
</div>
{filteredAccounts
.filter((a) => a.type === "LIABILITY" || a.type === "EQUITY")
.map((a) => (
<div key={a.id} className="flex items-center justify-between py-1 border-b border-slate-100">
<span className="text-slate-700 truncate pr-2">
<span className="font-mono text-slate-500 mr-2">{a.code}</span>
{a.name}
</span>
<span className="font-semibold text-slate-900 tabular-nums whitespace-nowrap">
{formatRupiah(a.balance)}
</span>
</div>
))}
<div className="flex items-center justify-between py-1 border-b border-slate-100">
<span className="text-slate-700 italic">Laba / Rugi Tahun Berjalan</span>
<span className={`font-semibold tabular-nums ${netProfit >= 0 ? "text-emerald-600" : "text-rose-600"}`}>
{formatRupiah(netProfit)}
</span>
</div>
<div className="flex items-center justify-between px-4 py-3 rounded-lg bg-slate-100 border border-slate-200 font-bold text-sm text-slate-900">
<span>Total Kewajiban &amp; Ekuitas</span>
<span className="tabular-nums">{formatRupiah(totalLiabAndEquity)}</span>
</div>
</div>
</div>
</div>
</div>
{/* Piutang Customer (AR) & Hutang Vendor (AP) Aging */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
<div className="px-5 py-3.5 border-b border-slate-100 bg-slate-50/70 flex items-center justify-between">
<div>
<h4 className="text-sm font-bold text-slate-900">Piutang Customer Belum Lunas (AR)</h4>
<p className="text-[11px] text-slate-500">{filteredArList.length} invoice menunggu pembayaran</p>
</div>
<span className="text-xs font-bold text-slate-900 tabular-nums">
{formatRupiah(totalArRemaining)}
</span>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse text-xs">
<thead>
<tr className="bg-slate-50 text-slate-500 font-semibold border-b border-slate-100">
<th className="py-2.5 px-4">No. SO &amp; Customer</th>
<th className="py-2.5 px-3 text-center">Umur</th>
<th className="py-2.5 px-4 text-right">Sisa Tagihan</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{filteredArList.length === 0 ? (
<tr>
<td colSpan={3} className="py-6 text-center text-slate-400">
Tidak ada piutang belum lunas.
</td>
</tr>
) : (
filteredArList.map((r) => (
<tr key={r.id} className="hover:bg-slate-50/60">
<td className="py-2.5 px-4">
<div className="font-mono font-semibold text-slate-900">{r.number}</div>
<div className="text-[11px] text-slate-500 truncate max-w-[210px]">
{r.counterparty} • {r.companyName}
</div>
</td>
<td className="py-2.5 px-3 text-center whitespace-nowrap">
<span
className={`px-2 py-0.5 rounded-full text-[10px] font-semibold border ${
r.ageDays > 60
? "bg-rose-50 text-rose-700 border-rose-200"
: r.ageDays > 30
? "bg-amber-50 text-amber-700 border-amber-200"
: "bg-slate-50 text-slate-700 border-slate-200"
}`}
>
{r.ageDays} hari
</span>
</td>
<td className="py-2.5 px-4 text-right font-bold text-slate-900 tabular-nums whitespace-nowrap">
{formatRupiah(r.remaining)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
<div className="px-5 py-3.5 border-b border-slate-100 bg-slate-50/70 flex items-center justify-between">
<div>
<h4 className="text-sm font-bold text-slate-900">Hutang Vendor Belum Lunas (AP)</h4>
<p className="text-[11px] text-slate-500">{filteredApList.length} PO belum lunas</p>
</div>
<span className="text-xs font-bold text-slate-900 tabular-nums">
{formatRupiah(totalApRemaining)}
</span>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse text-xs">
<thead>
<tr className="bg-slate-50 text-slate-500 font-semibold border-b border-slate-100">
<th className="py-2.5 px-4">No. PO &amp; Vendor</th>
<th className="py-2.5 px-3 text-center">Umur</th>
<th className="py-2.5 px-4 text-right">Sisa Hutang</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{filteredApList.length === 0 ? (
<tr>
<td colSpan={3} className="py-6 text-center text-slate-400">
Tidak ada hutang vendor belum lunas.
</td>
</tr>
) : (
filteredApList.map((p) => (
<tr key={p.id} className="hover:bg-slate-50/60">
<td className="py-2.5 px-4">
<div className="font-mono font-semibold text-slate-900">{p.number}</div>
<div className="text-[11px] text-slate-500 truncate max-w-[210px]">
{p.counterparty} • {p.companyName}
</div>
</td>
<td className="py-2.5 px-3 text-center whitespace-nowrap">
<span
className={`px-2 py-0.5 rounded-full text-[10px] font-semibold border ${
p.ageDays > 60
? "bg-rose-50 text-rose-700 border-rose-200"
: p.ageDays > 30
? "bg-amber-50 text-amber-700 border-amber-200"
: "bg-slate-50 text-slate-700 border-slate-200"
}`}
>
{p.ageDays} hari
</span>
</td>
<td className="py-2.5 px-4 text-right font-bold text-slate-900 tabular-nums whitespace-nowrap">
{formatRupiah(p.remaining)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
</div>
</div>
)}
{/* TAB 1: PAYROLL, SLIP GAJI, UANG MAKAN & ABSENSI (TERPISAH PER PT) */}
{activeTab === "payroll" && (
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
@@ -1945,7 +2333,7 @@ export default function FinancePage() {
<CalendarCheck className="h-4 w-4 text-blue-600" />
<span>Rekap Kehadiran & Absensi ({periodMonth} {periodYear}):</span>
</div>
<div className="grid grid-cols-3 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Hari Hadir (Masuk) *
@@ -1989,58 +2377,54 @@ export default function FinancePage() {
</div>
{/* Komponen Gaji, Uang Makan & Potongan */}
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Gaji Pokok Bulanan (Rp) *
Gaji Pokok Bulanan *
</label>
<input
type="number"
min="0"
<CurrencyInput
currency="IDR"
min={0}
required
value={baseSalary}
onChange={(e) => setBaseSalary(Number(e.target.value))}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-bold"
onChange={(val) => setBaseSalary(Number(val) || 0)}
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
Tarif Uang Makan / Hari Hadir (Rp) *
Tarif Uang Makan / Hari Hadir *
</label>
<input
type="number"
min="0"
<CurrencyInput
currency="IDR"
min={0}
required
value={dailyMealRate}
onChange={(e) => setDailyMealRate(Number(e.target.value))}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-bold text-emerald-700"
onChange={(val) => setDailyMealRate(Number(val) || 0)}
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
Tunjangan Transport / Lembur (Rp)
Tunjangan Transport / Lembur
</label>
<input
type="number"
min="0"
<CurrencyInput
currency="IDR"
min={0}
value={transportAllowance}
onChange={(e) => setTransportAllowance(Number(e.target.value))}
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
onChange={(val) => setTransportAllowance(Number(val) || 0)}
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
Potongan per Hari Absen (Rp)
Potongan per Hari Absen
</label>
<input
type="number"
min="0"
<CurrencyInput
currency="IDR"
min={0}
value={deductionPerAbsent}
onChange={(e) => setDeductionPerAbsent(Number(e.target.value))}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-rose-600"
onChange={(val) => setDeductionPerAbsent(Number(val) || 0)}
/>
</div>
</div>
@@ -2234,15 +2618,12 @@ export default function FinancePage() {
<div>
<label className="block font-semibold text-slate-700 mb-1">
Saldo Saat Ini / Saldo Awal (Rp)
Saldo Saat Ini / Saldo Awal *
</label>
<input
type="number"
<CurrencyInput
currency="IDR"
value={accBalance}
onChange={(e) =>
setAccBalance(e.target.value === "" ? "" : parseFloat(e.target.value))
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-bold text-slate-800"
onChange={(val) => setAccBalance(val)}
/>
</div>
@@ -2306,7 +2687,7 @@ export default function FinancePage() {
</div>
{/* Info Karyawan & Absensi */}
<div className="grid grid-cols-2 gap-3 p-3.5 rounded-xl bg-slate-50 border border-slate-200">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 p-3.5 rounded-xl bg-slate-50 border border-slate-200">
<div className="space-y-1">
<div className="text-slate-400 text-[10px] uppercase font-bold">
Data Karyawan & PT
@@ -2503,7 +2884,7 @@ export default function FinancePage() {
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Akun Debit (Bertambah) *
@@ -2541,21 +2922,18 @@ export default function FinancePage() {
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Nominal Transaksi (Rp) *
Nominal Transaksi *
</label>
<input
type="number"
min="1"
<CurrencyInput
currency="IDR"
min={1}
required
placeholder="1000000"
value={amount}
onChange={(e) =>
setAmount(e.target.value === "" ? "" : parseFloat(e.target.value))
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-bold text-slate-800"
onChange={(val) => setAmount(val)}
/>
</div>
<div>
+573 -8
View File
@@ -3,14 +3,14 @@
@tailwind utilities;
:root {
--foreground-rgb: 15, 23, 42;
--background-start-rgb: 248, 250, 252;
--background-end-rgb: 241, 245, 249;
color-scheme: light;
}
html.dark {
color-scheme: dark;
}
body {
color: rgb(var(--foreground-rgb));
background-color: #f8fafc;
font-feature-settings: "rlig" 1, "calt" 1;
}
@@ -25,10 +25,575 @@ body {
}
::-webkit-scrollbar-thumb {
background: #cbd5e1;
background: #64748b;
border-radius: 9999px;
}
::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
html.dark ::-webkit-scrollbar-thumb {
background: #334155;
}
/* ============================================================================
LIGHT MODE: ZERO WASHED-OUT GRAY FONTS (Tajam, Jelas, Kontras Tinggi)
============================================================================ */
html:not(.dark) body {
background-color: #f8fafc;
color: #090d16;
}
html:not(.dark) .text-slate-300,
html:not(.dark) .text-slate-400,
html:not(.dark) .text-slate-500,
html:not(.dark) .text-gray-300,
html:not(.dark) .text-gray-400,
html:not(.dark) .text-gray-500 {
color: #1e293b !important;
}
html:not(.dark) .text-slate-600,
html:not(.dark) .text-slate-700,
html:not(.dark) .text-slate-800,
html:not(.dark) .text-gray-600,
html:not(.dark) .text-gray-700,
html:not(.dark) .text-gray-800 {
color: #0f172a !important;
}
/* Keep bright readable text inside intentionally dark surfaces even in Light Mode */
html:not(.dark) .bg-slate-950 .text-slate-300,
html:not(.dark) .bg-slate-950 .text-slate-400,
html:not(.dark) .bg-slate-950 .text-slate-500,
html:not(.dark) .bg-slate-900 .text-slate-300,
html:not(.dark) .bg-slate-900 .text-slate-400,
html:not(.dark) .bg-slate-900 .text-slate-500 {
color: #f1f5f9 !important;
}
html:not(.dark) ::placeholder {
color: #334155 !important;
opacity: 0.85;
}
/* ============================================================================
DARK MODE (DEFAULT): OBSIDIAN SURFACES + ZERO GRAY / ZERO INVISIBLE HOVER
============================================================================ */
html.dark body {
background-color: #090d16;
color: #ffffff;
}
/* --- 1. Neutral Surfaces --- */
html.dark .bg-slate-50,
html.dark .bg-slate-50\/50,
html.dark .bg-slate-50\/60,
html.dark .bg-slate-50\/70,
html.dark .bg-slate-50\/80,
html.dark .bg-gray-50 {
background-color: #0b1120 !important;
}
html.dark .bg-white,
html.dark .bg-white\/95,
html.dark .bg-white\/90,
html.dark .bg-white\/80 {
background-color: #111827 !important;
}
/* Active tab buttons inside dark pill switchers stand out clearly */
html.dark .bg-slate-100 button.bg-white,
html.dark .bg-slate-200\/80 button.bg-white {
background-color: #0b1120 !important;
color: #ffffff !important;
border: 1px solid #475569 !important;
}
/* Nested subtle blocks inside dark cards (table headers, callouts, inner boxes) */
html.dark .bg-white .bg-slate-50,
html.dark .bg-white .bg-slate-50\/50,
html.dark .bg-white .bg-slate-50\/60,
html.dark .bg-white .bg-slate-50\/70,
html.dark .bg-white .bg-slate-50\/80 {
background-color: #162033 !important;
}
html.dark .bg-slate-100,
html.dark .bg-slate-100\/70,
html.dark .bg-slate-100\/80,
html.dark .bg-slate-100\/90,
html.dark .bg-slate-200\/80,
html.dark .bg-gray-100 {
background-color: #1b263b !important;
}
html.dark .bg-slate-200 {
background-color: #26354d !important;
}
html.dark .bg-slate-300 {
background-color: #334155 !important;
}
/* --- 2. All Pastel Surfaces (50, 100, 200 & opacity variants) -> Rich Dark Tints --- */
html.dark .bg-blue-50,
html.dark .bg-blue-50\/60,
html.dark .bg-blue-50\/70,
html.dark .bg-blue-50\/80 {
background-color: rgba(59, 130, 246, 0.16) !important;
}
html.dark .bg-blue-100,
html.dark .bg-blue-100\/70,
html.dark .bg-blue-100\/80 {
background-color: rgba(59, 130, 246, 0.24) !important;
}
html.dark .bg-indigo-50,
html.dark .bg-indigo-50\/60,
html.dark .bg-indigo-50\/70,
html.dark .bg-indigo-50\/80 {
background-color: rgba(99, 102, 241, 0.16) !important;
}
html.dark .bg-indigo-100,
html.dark .bg-indigo-100\/70 {
background-color: rgba(99, 102, 241, 0.24) !important;
}
html.dark .bg-sky-50,
html.dark .bg-sky-50\/40,
html.dark .bg-sky-50\/80 {
background-color: rgba(14, 165, 233, 0.16) !important;
}
html.dark .bg-sky-100 {
background-color: rgba(14, 165, 233, 0.24) !important;
}
html.dark .bg-teal-50,
html.dark .bg-teal-50\/40 {
background-color: rgba(20, 184, 166, 0.16) !important;
}
html.dark .bg-teal-100,
html.dark .bg-teal-100\/70 {
background-color: rgba(20, 184, 166, 0.24) !important;
}
html.dark .bg-emerald-50,
html.dark .bg-emerald-50\/40,
html.dark .bg-emerald-50\/50,
html.dark .bg-emerald-50\/60,
html.dark .bg-emerald-50\/70,
html.dark .bg-emerald-50\/80 {
background-color: rgba(16, 185, 129, 0.16) !important;
}
html.dark .bg-emerald-100,
html.dark .bg-emerald-100\/70,
html.dark .bg-emerald-200 {
background-color: rgba(16, 185, 129, 0.24) !important;
}
html.dark .bg-amber-50,
html.dark .bg-amber-50\/50,
html.dark .bg-amber-50\/60,
html.dark .bg-amber-50\/70,
html.dark .bg-amber-50\/80 {
background-color: rgba(245, 158, 11, 0.16) !important;
}
html.dark .bg-amber-100,
html.dark .bg-amber-100\/50,
html.dark .bg-amber-100\/60,
html.dark .bg-amber-200 {
background-color: rgba(245, 158, 11, 0.25) !important;
}
html.dark .bg-rose-50,
html.dark .bg-rose-50\/40,
html.dark .bg-rose-50\/50,
html.dark .bg-rose-50\/60,
html.dark .bg-rose-50\/80,
html.dark .bg-rose-50\/90,
html.dark .bg-red-50 {
background-color: rgba(244, 63, 94, 0.16) !important;
}
html.dark .bg-rose-100,
html.dark .bg-red-100 {
background-color: rgba(244, 63, 94, 0.25) !important;
}
html.dark .bg-purple-50,
html.dark .bg-purple-50\/60,
html.dark .bg-purple-50\/70 {
background-color: rgba(168, 85, 247, 0.16) !important;
}
html.dark .bg-purple-100 {
background-color: rgba(168, 85, 247, 0.25) !important;
}
/* Pastel Gradients -> Dark Tinted Gradients */
html.dark .from-emerald-50 {
--tw-gradient-from: rgba(16, 185, 129, 0.16) var(--tw-gradient-from-position) !important;
--tw-gradient-to: rgba(16, 185, 129, 0) var(--tw-gradient-to-position) !important;
--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to) !important;
}
html.dark .via-teal-50 {
--tw-gradient-to: rgba(20, 184, 166, 0) var(--tw-gradient-to-position) !important;
--tw-gradient-stops: var(--tw-gradient-from), rgba(20, 184, 166, 0.14) var(--tw-gradient-via-position), var(--tw-gradient-to) !important;
}
html.dark .to-blue-50 {
--tw-gradient-to: rgba(59, 130, 246, 0.16) var(--tw-gradient-to-position) !important;
}
/* --- 3. ALL Borders & Dividers in Dark Mode --- */
html.dark .border-slate-100,
html.dark .border-slate-200,
html.dark .border-slate-200\/60,
html.dark .border-slate-200\/70,
html.dark .border-slate-200\/80,
html.dark .border-slate-200\/90,
html.dark .border-slate-300,
html.dark .border-slate-300\/90,
html.dark .border-gray-200,
html.dark .border-gray-300 {
border-color: #29384f !important;
}
html.dark .hover\:border-slate-300\/90:hover {
border-color: #475569 !important;
}
html.dark .divide-slate-100 > :not([hidden]) ~ :not([hidden]),
html.dark .divide-slate-200 > :not([hidden]) ~ :not([hidden]) {
border-color: #223044 !important;
}
html.dark .border-blue-100,
html.dark .border-blue-200,
html.dark .border-blue-200\/80,
html.dark .border-blue-300 {
border-color: rgba(96, 165, 250, 0.4) !important;
}
html.dark .border-indigo-200,
html.dark .border-indigo-200\/80,
html.dark .border-indigo-300 {
border-color: rgba(129, 140, 248, 0.4) !important;
}
html.dark .border-sky-200,
html.dark .border-sky-300 {
border-color: rgba(56, 189, 248, 0.4) !important;
}
html.dark .border-teal-200,
html.dark .border-teal-300 {
border-color: rgba(45, 212, 191, 0.4) !important;
}
html.dark .border-emerald-100,
html.dark .border-emerald-200,
html.dark .border-emerald-200\/80,
html.dark .border-emerald-300 {
border-color: rgba(52, 211, 153, 0.4) !important;
}
html.dark .border-amber-100,
html.dark .border-amber-200,
html.dark .border-amber-200\/70,
html.dark .border-amber-200\/80,
html.dark .border-amber-300 {
border-color: rgba(251, 191, 36, 0.42) !important;
}
html.dark .border-rose-100,
html.dark .border-rose-200,
html.dark .border-rose-200\/70,
html.dark .border-rose-300,
html.dark .border-red-200 {
border-color: rgba(251, 113, 133, 0.42) !important;
}
html.dark .border-purple-100,
html.dark .border-purple-200,
html.dark .border-purple-200\/60,
html.dark .border-purple-200\/80,
html.dark .border-purple-300 {
border-color: rgba(192, 132, 252, 0.4) !important;
}
/* --- 4. BRIGHT HIGH-CONTRAST FONTS IN DARK MODE (ZERO GRAY, ZERO DARK-ON-DARK!) --- */
html.dark .text-slate-950,
html.dark .text-slate-900,
html.dark .text-slate-800,
html.dark .text-gray-900,
html.dark .text-gray-800,
html.dark .text-black {
color: #ffffff !important;
}
html.dark .text-slate-700,
html.dark .text-slate-600,
html.dark .text-gray-700,
html.dark .text-gray-600 {
color: #f8fafc !important;
}
html.dark .text-slate-500,
html.dark .text-slate-400,
html.dark .text-slate-300,
html.dark .text-gray-500,
html.dark .text-gray-400 {
color: #e2e8f0 !important;
}
/* Luminous semantic text (including 500..950 shades) */
html.dark .text-blue-500,
html.dark .text-blue-600,
html.dark .text-blue-700,
html.dark .text-blue-800,
html.dark .text-blue-800\/90,
html.dark .text-blue-900,
html.dark .text-blue-950 {
color: #93c5fd !important;
}
html.dark .text-indigo-500,
html.dark .text-indigo-600,
html.dark .text-indigo-700,
html.dark .text-indigo-800,
html.dark .text-indigo-900,
html.dark .text-indigo-950 {
color: #a5b4fc !important;
}
html.dark .text-sky-500,
html.dark .text-sky-600,
html.dark .text-sky-700,
html.dark .text-sky-800,
html.dark .text-sky-900,
html.dark .text-sky-950 {
color: #7dd3fc !important;
}
html.dark .text-teal-500,
html.dark .text-teal-600,
html.dark .text-teal-700,
html.dark .text-teal-800,
html.dark .text-teal-900,
html.dark .text-teal-950 {
color: #5eead4 !important;
}
html.dark .text-emerald-500,
html.dark .text-emerald-600,
html.dark .text-emerald-700,
html.dark .text-emerald-800,
html.dark .text-emerald-900,
html.dark .text-emerald-950 {
color: #6ee7b7 !important;
}
html.dark .text-amber-500,
html.dark .text-amber-600,
html.dark .text-amber-700,
html.dark .text-amber-800,
html.dark .text-amber-850,
html.dark .text-amber-900,
html.dark .text-amber-950 {
color: #fde68a !important;
}
html.dark .text-rose-500,
html.dark .text-rose-600,
html.dark .text-rose-700,
html.dark .text-rose-800,
html.dark .text-rose-900,
html.dark .text-red-500,
html.dark .text-red-600,
html.dark .text-red-700,
html.dark .text-red-800 {
color: #fda4af !important;
}
html.dark .text-purple-500,
html.dark .text-purple-600,
html.dark .text-purple-700,
html.dark .text-purple-800,
html.dark .text-purple-900,
html.dark .text-purple-950 {
color: #d8b4fe !important;
}
/* --- 5. ALL HOVER BACKGROUNDS & HOVER TEXTS IN DARK MODE (ALWAYS CLEAR!) --- */
/* Neutral hovers -> Clean elevated dark slate (NEVER white/light gray!) */
html.dark .hover\:bg-white:hover,
html.dark .hover\:bg-slate-50:hover,
html.dark .hover\:bg-slate-50\/50:hover,
html.dark .hover\:bg-slate-50\/60:hover,
html.dark .hover\:bg-slate-50\/70:hover,
html.dark .hover\:bg-slate-100:hover,
html.dark .hover\:bg-slate-200:hover {
background-color: #24344d !important;
}
/* Tinted pastel hovers -> Deeper luminous dark tint (NEVER light pastel!) */
html.dark .hover\:bg-blue-50:hover,
html.dark .hover\:bg-blue-100:hover {
background-color: rgba(59, 130, 246, 0.32) !important;
}
html.dark .hover\:bg-indigo-100:hover {
background-color: rgba(99, 102, 241, 0.32) !important;
}
html.dark .hover\:bg-sky-50:hover,
html.dark .hover\:bg-sky-100:hover {
background-color: rgba(14, 165, 233, 0.32) !important;
}
html.dark .hover\:bg-teal-100:hover {
background-color: rgba(20, 184, 166, 0.32) !important;
}
html.dark .hover\:bg-emerald-50:hover,
html.dark .hover\:bg-emerald-100:hover,
html.dark .hover\:bg-emerald-200:hover {
background-color: rgba(16, 185, 129, 0.32) !important;
}
html.dark .hover\:bg-amber-50:hover,
html.dark .hover\:bg-amber-100:hover,
html.dark .hover\:bg-amber-200:hover {
background-color: rgba(245, 158, 11, 0.32) !important;
}
html.dark .hover\:bg-rose-50:hover,
html.dark .hover\:bg-rose-100:hover {
background-color: rgba(244, 63, 94, 0.32) !important;
}
html.dark .hover\:bg-purple-50:hover,
html.dark .hover\:bg-purple-100:hover {
background-color: rgba(168, 85, 247, 0.32) !important;
}
/* Hover text colors -> ALWAYS bright & luminous (NEVER dark/black/gray!) */
html.dark .hover\:text-slate-900:hover,
html.dark .hover\:text-slate-600:hover,
html.dark .hover\:text-slate-200:hover,
html.dark .hover\:text-white:hover,
html.dark .group:hover .group-hover\:text-slate-900 {
color: #ffffff !important;
}
html.dark .hover\:text-blue-600:hover,
html.dark .hover\:text-blue-700:hover,
html.dark .hover\:text-blue-800:hover,
html.dark .hover\:text-blue-900:hover {
color: #bfdbfe !important;
}
html.dark .hover\:text-emerald-700:hover,
html.dark .hover\:text-emerald-900:hover {
color: #a7f3d0 !important;
}
html.dark .hover\:text-amber-800:hover {
color: #fef08a !important;
}
html.dark .hover\:text-purple-900:hover {
color: #e9d5ff !important;
}
html.dark .hover\:text-rose-700:hover {
color: #fecdd3 !important;
}
/* --- 6. Active Primary Dark Buttons (bg-slate-900) -> Crisp High-Contrast Bright Pill --- */
html.dark button.bg-slate-900,
html.dark a.bg-slate-900 {
background-color: #f8fafc !important;
color: #090d16 !important;
border-color: #f8fafc !important;
}
html.dark button.bg-slate-900 *,
html.dark a.bg-slate-900 * {
color: #090d16 !important;
}
html.dark button.bg-slate-900:hover,
html.dark a.bg-slate-900:hover {
background-color: #e2e8f0 !important;
color: #090d16 !important;
}
html.dark button.bg-slate-900:hover *,
html.dark a.bg-slate-900:hover * {
color: #090d16 !important;
}
/* Dark brand icon box inside Sidebar / Login */
html.dark .dark\:bg-white {
background-color: #ffffff !important;
}
html.dark .dark\:text-slate-950,
html.dark .dark\:text-slate-950 * {
color: #090d16 !important;
}
/* --- 7. Native Form Controls in Dark Mode --- */
html.dark input:not([type="checkbox"]):not([type="radio"]),
html.dark select,
html.dark textarea {
background-color: #0f172a;
color: #ffffff;
border-color: #334155;
}
html.dark input:not([type="checkbox"]):not([type="radio"]):focus,
html.dark select:focus,
html.dark textarea:focus {
border-color: #60a5fa;
background-color: #0f172a;
color: #ffffff;
}
html.dark select option {
background-color: #0f172a;
color: #ffffff;
}
html.dark ::placeholder {
color: #cbd5e1 !important;
opacity: 0.8;
}
/* --- 8. Bright Chart Bars in Dark Mode --- */
html.dark .chart-bar-primary {
background-color: #f8fafc !important;
}
html.dark .chart-bar-secondary {
background-color: #60a5fa !important;
}
html.dark .chart-bar-profit {
background-color: #34d399 !important;
}
/* ============================================================================
PRINT SAFETY: Selalu cetak hitam di atas kertas putih meski Dark Mode aktif
============================================================================ */
@media print {
html,
html.dark,
body,
html.dark body {
background-color: #ffffff !important;
color: #000000 !important;
color-scheme: light !important;
}
html.dark * {
background-color: transparent !important;
color: #000000 !important;
border-color: #cbd5e1 !important;
box-shadow: none !important;
}
}
+1496 -87
View File
File diff suppressed because it is too large. Load diff
+30 -3
View File
@@ -1,4 +1,4 @@
import type { Metadata } from "next";
import type { Metadata, Viewport } from "next";
import "./globals.css";
export const metadata: Metadata = {
@@ -6,14 +6,41 @@ export const metadata: Metadata = {
description: "Sistem ERP Modular: Inventaris, Penjualan, Pembelian, Keuangan & RBAC",
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
maximumScale: 5,
};
const themeInitScript = `
(function() {
try {
var saved = localStorage.getItem('erp_theme');
var root = document.documentElement;
if (saved === 'light') {
root.classList.remove('dark');
root.setAttribute('data-theme', 'light');
} else {
root.classList.add('dark');
root.setAttribute('data-theme', 'dark');
}
} catch (e) {
document.documentElement.classList.add('dark');
}
})();
`;
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="id">
<body className="min-h-screen bg-slate-50 text-slate-900 antialiased font-sans">
<html lang="id" className="dark" data-theme="dark" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />
</head>
<body className="min-h-screen bg-slate-50 dark:bg-[#090d16] text-slate-900 dark:text-white antialiased font-sans overflow-x-hidden transition-colors duration-150">
{children}
</body>
</html>
+28 -210
View File
@@ -3,15 +3,16 @@
export const dynamic = "force-dynamic";
import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { getDefaultLandingRoute } from "@/lib/permissions";
import { ThemeToggle } from "@/components/ThemeToggle";
import {
Building2,
Lock,
Mail,
ArrowRight,
ShieldCheck,
Rocket,
FlaskConical,
KeyRound,
ArrowLeft,
QrCode,
@@ -20,7 +21,6 @@ import {
export default function LoginPage() {
const router = useRouter();
const [envMode, setEnvMode] = useState<"DEMO" | "LIVE">("LIVE");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
@@ -39,40 +39,15 @@ export default function LoginPage() {
useEffect(() => {
if (typeof window !== "undefined") {
const params = new URLSearchParams(window.location.search);
const m = params.get("mode");
const reason = params.get("reason");
if (reason === "switch_live") {
if (reason === "idle_timeout") {
setInfoNotice(
"🔒 Anda beralih dari Mode Demo ke Mode Production (Live). Untuk keamanan data operasional, silakan login ulang menggunakan akun kredensial Production Anda."
"Sesi Anda ditutup otomatis karena tidak ada aktivitas selama 30 menit demi keamanan data. Silakan login kembali."
);
}
if (m === "DEMO") {
setEnvMode("DEMO");
setEmail("admin@erp.local");
setPassword("admin123");
} else if (m === "LIVE") {
setEnvMode("LIVE");
setEmail("");
setPassword("");
}
}
}, []);
const switchMode = (target: "DEMO" | "LIVE") => {
setEnvMode(target);
setError(null);
setMfaRequired(false);
setIsFirstTimeSetup(false);
setMfaCode("");
if (target === "LIVE") {
setEmail("");
setPassword("");
} else {
setEmail("admin@erp.local");
setPassword("admin123");
}
};
const applyMfaResponse = (data: any) => {
setMfaRequired(true);
setIsFirstTimeSetup(Boolean(data.isFirstTimeSetup));
@@ -92,7 +67,7 @@ export default function LoginPage() {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, envMode }),
body: JSON.stringify({ email, password }),
});
const data = await res.json();
@@ -109,7 +84,7 @@ export default function LoginPage() {
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
}
router.push("/");
router.push(data.defaultRoute || getDefaultLandingRoute(data.user?.role));
} catch (err: any) {
setError(err.message);
} finally {
@@ -138,47 +113,7 @@ export default function LoginPage() {
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
}
router.push("/");
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleQuickLogin = async (
targetEmail: string,
targetPass: string,
targetMode: "DEMO" | "LIVE"
) => {
setEnvMode(targetMode);
setEmail(targetEmail);
setPassword(targetPass);
setLoading(true);
setError(null);
try {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: targetEmail,
password: targetPass,
envMode: targetMode,
}),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "Gagal login");
}
if (data.requireMfa) {
applyMfaResponse(data);
return;
}
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
}
router.push("/");
router.push(data.defaultRoute || getDefaultLandingRoute(data.user?.role));
} catch (err: any) {
setError(err.message);
} finally {
@@ -187,15 +122,18 @@ export default function LoginPage() {
};
return (
<div className="min-h-screen bg-slate-950 flex flex-col justify-center items-center px-4 sm:px-6 lg:px-8 py-8">
<div className="min-h-screen bg-slate-50 dark:bg-[#090d16] flex flex-col justify-center items-center px-4 sm:px-6 lg:px-8 py-8 relative">
<div className="absolute top-4 right-4">
<ThemeToggle />
</div>
<div className="sm:mx-auto sm:w-full sm:max-w-md text-center">
<div className="inline-flex h-12 w-12 rounded-xl bg-blue-600 items-center justify-center text-white shadow-lg shadow-blue-500/30 mb-3">
<div className="inline-flex h-12 w-12 rounded-xl bg-slate-900 dark:bg-white items-center justify-center text-white dark:text-slate-950 shadow-md mb-3">
<Building2 className="h-6 w-6" />
</div>
<h2 className="text-2xl font-bold tracking-tight text-white">
<h2 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">
EnterpriseCore ERP
</h2>
<p className="mt-1 text-xs text-slate-400">
<p className="mt-1 text-xs text-slate-700 dark:text-slate-100">
Masuk untuk mengakses sistem informasi bisnis terintegrasi
</p>
</div>
@@ -204,55 +142,6 @@ export default function LoginPage() {
<div className="bg-slate-900 border border-slate-800 py-6 px-6 shadow-xl rounded-2xl sm:px-8">
{!mfaRequired ? (
<>
{/* Environment Mode Selector: PRODUCTION vs DEMO */}
<div className="mb-5">
<div className="grid grid-cols-2 gap-2.5 p-1 bg-slate-950 rounded-xl border border-slate-800">
<button
type="button"
onClick={() => switchMode("LIVE")}
className={`flex flex-col items-center justify-center py-2.5 px-3 rounded-lg text-xs font-bold transition-all ${
envMode === "LIVE"
? "bg-emerald-600 text-white shadow-md shadow-emerald-600/25"
: "text-slate-400 hover:text-slate-200 hover:bg-slate-900"
}`}
>
<div className="flex items-center gap-1.5">
<Rocket className="h-3.5 w-3.5" />
<span>PRODUCTION</span>
</div>
<span
className={`text-[10px] font-normal mt-0.5 ${
envMode === "LIVE" ? "text-emerald-100" : "text-slate-500"
}`}
>
Sistem Utama
</span>
</button>
<button
type="button"
onClick={() => switchMode("DEMO")}
className={`flex flex-col items-center justify-center py-2.5 px-3 rounded-lg text-xs font-bold transition-all ${
envMode === "DEMO"
? "bg-amber-600 text-white shadow-md shadow-amber-600/25"
: "text-slate-400 hover:text-slate-200 hover:bg-slate-900"
}`}
>
<div className="flex items-center gap-1.5">
<FlaskConical className="h-3.5 w-3.5" />
<span>MODE DEMO</span>
</div>
<span
className={`text-[10px] font-normal mt-0.5 ${
envMode === "DEMO" ? "text-amber-100" : "text-slate-500"
}`}
>
Simulasi & Uji Coba
</span>
</button>
</div>
</div>
{infoNotice && (
<div className="mb-4 p-3 rounded-lg bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs">
{infoNotice}
@@ -307,92 +196,12 @@ export default function LoginPage() {
<button
type="submit"
disabled={loading}
className={`w-full flex items-center justify-center gap-2 py-2.5 px-4 rounded-lg text-sm font-semibold text-white transition-colors disabled:opacity-50 ${
envMode === "LIVE"
? "bg-emerald-600 hover:bg-emerald-500"
: "bg-blue-600 hover:bg-blue-500"
}`}
className="w-full flex items-center justify-center gap-2 py-2.5 px-4 rounded-lg text-sm font-semibold text-white bg-emerald-600 hover:bg-emerald-500 transition-colors disabled:opacity-50"
>
<span>{loading ? "Memproses..." : "Masuk ke Dashboard"}</span>
<ArrowRight className="h-4 w-4" />
</button>
</form>
{/* Quick Logins ONLY for DEMO mode */}
{envMode === "DEMO" && (
<div className="mt-5 pt-4 border-t border-slate-800">
<p className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider mb-2.5 text-center">
Akses Cepat Mode Demo (Multi-Role RBAC):
</p>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2 text-xs">
<button
type="button"
onClick={() => handleQuickLogin("admin@erp.local", "admin123", "DEMO")}
className="p-2 rounded bg-slate-800/80 hover:bg-slate-700 text-slate-200 border border-slate-700 text-left transition-colors"
title="Kapasitas: Akses Penuh ke Semua Menu & Melihat Seluruh Nominal Uang"
>
<div className="font-semibold text-blue-400">Super Admin</div>
<div className="text-[10px] text-slate-400">admin@erp.local</div>
<div className="text-[9px] text-emerald-400 font-mono mt-0.5">Semua Nominal Uang</div>
</button>
<button
type="button"
onClick={() => handleQuickLogin("yoga@erp.local", "manager123", "DEMO")}
className="p-2 rounded bg-slate-800/80 hover:bg-slate-700 text-slate-200 border border-slate-700 text-left transition-colors"
title="Kapasitas: Pengawasan Operasional & Melihat Nominal Uang / HPP"
>
<div className="font-semibold text-cyan-400">Manager</div>
<div className="text-[10px] text-slate-400">yoga@erp.local</div>
<div className="text-[9px] text-emerald-400 font-mono mt-0.5">Approval & Nominal</div>
</button>
<button
type="button"
onClick={() => handleQuickLogin("purchasing@erp.local", "staff123", "DEMO")}
className="p-2 rounded bg-slate-800/80 hover:bg-slate-700 text-slate-200 border border-slate-700 text-left transition-colors"
title="Kapasitas: Pengadaan PO Vendor (Hanya Harga Beli PO, Tidak Lihat Laba)"
>
<div className="font-semibold text-indigo-400">Purchasing</div>
<div className="text-[10px] text-slate-400">purchasing@erp.local</div>
<div className="text-[9px] text-indigo-300 font-mono mt-0.5">Harga Beli Vendor</div>
</button>
<button
type="button"
onClick={() => handleQuickLogin("sales@erp.local", "staff123", "DEMO")}
className="p-2 rounded bg-slate-800/80 hover:bg-slate-700 text-slate-200 border border-slate-700 text-left transition-colors"
title="Kapasitas: Sales Order & Invoice (Hanya Harga Jual Customer)"
>
<div className="font-semibold text-amber-400">Sales Rep</div>
<div className="text-[10px] text-slate-400">sales@erp.local</div>
<div className="text-[9px] text-amber-300 font-mono mt-0.5">Harga Jual & Omzet</div>
</button>
<button
type="button"
onClick={() => handleQuickLogin("inventory@erp.local", "staff123", "DEMO")}
className="p-2 rounded bg-slate-800/80 hover:bg-slate-700 text-slate-200 border border-slate-700 text-left transition-colors"
title="Kapasitas: Fisik Barang & Mutasi (UANG DISEMBUNYIKAN)"
>
<div className="font-semibold text-emerald-400">Staf Gudang</div>
<div className="text-[10px] text-slate-400">inventory@erp.local</div>
<div className="text-[9px] text-rose-300 font-mono mt-0.5">Fisik (Uang Disembunyikan)</div>
</button>
<button
type="button"
onClick={() => handleQuickLogin("accountant@erp.local", "staff123", "DEMO")}
className="p-2 rounded bg-slate-800/80 hover:bg-slate-700 text-slate-200 border border-slate-700 text-left transition-colors"
title="Kapasitas: Keuangan, Jurnal, Payroll & Seluruh Arus Kas"
>
<div className="font-semibold text-purple-400">Akuntan</div>
<div className="text-[10px] text-slate-400">accountant@erp.local</div>
<div className="text-[9px] text-purple-300 font-mono mt-0.5">Arus Kas & Jurnal</div>
</button>
</div>
</div>
)}
</>
) : (
/* MFA / 2FA Step: Either First-Time Authenticator Enrollment OR Regular OTP Verify */
@@ -508,9 +317,18 @@ export default function LoginPage() {
)}
</div>
<div className="mt-4 flex items-center justify-center gap-1.5 text-xs text-slate-500">
<ShieldCheck className="h-3.5 w-3.5 text-blue-500" />
<span>Sistem diamankan dengan Enkripsi JWT, Bcrypt & MFA (2FA)</span>
<div className="mt-4 flex flex-col items-center gap-2.5">
<Link
href="/rma"
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl bg-slate-900/90 hover:bg-slate-800 text-amber-300 border border-amber-500/30 text-xs font-semibold transition-colors"
>
<span>🔧 Portal Pengajuan RMA / Service Customer (Tanpa Login)</span>
<ArrowRight className="h-3.5 w-3.5" />
</Link>
<div className="flex items-center justify-center gap-1.5 text-xs text-slate-500">
<ShieldCheck className="h-3.5 w-3.5 text-blue-500" />
<span>Sistem diamankan dengan Enkripsi JWT, Bcrypt &amp; MFA (2FA)</span>
</div>
</div>
</div>
</div>
+583 -709
View File
File diff suppressed because it is too large. Load diff
+1050 -236
View File
File diff suppressed because it is too large. Load diff
+782
View File
@@ -0,0 +1,782 @@
"use client";
import React, { useState } from "react";
import Link from "next/link";
import { formatRupiah, formatDateTime } from "@/lib/utils";
import { ThemeToggle } from "@/components/ThemeToggle";
import {
ShieldCheck,
Wrench,
Search,
CheckCircle2,
AlertCircle,
Truck,
RotateCcw,
Copy,
Check,
Building2,
ArrowRight,
Clock,
FileSearch,
} from "lucide-react";
interface VerifiedDevice {
serialNumber: string;
productName: string;
productSku: string;
companyName: string;
purchaseDate: string;
warrantyExpiry: string;
isWarrantyActive: boolean;
eligibleModes: string[];
}
interface PublicTicket {
recordNumber: string;
serialNumber: string;
productName: string;
productSku: string;
companyName: string;
condition: string;
serviceOrigin: string;
warrantyStatus: string;
damageDescription: string;
actionTaken: string | null;
serviceFee: number;
returnShippingCost: number;
returnCourierName: string | null;
returnTrackingNumber: string | null;
servicePaymentStatus: string;
createdAt: string;
updatedAt: string;
}
function getConditionDisplay(condition: string, origin: string) {
switch (condition) {
case "IN_SERVICE":
return {
label: origin === "WARRANTY_REPLACE" ? "🔄 Pengajuan Tukar Unit Diproses" : "⚙️ Dalam Antrean / Proses Service",
cls: "bg-blue-50 text-blue-800 border-blue-200",
};
case "SERVICED_OK":
return {
label: "✅ Service Selesai (Siap / Sudah Dikirim Balik)",
cls: "bg-emerald-50 text-emerald-800 border-emerald-200",
};
case "CANNIBALIZED":
return {
label: origin === "WARRANTY_REPLACE" ? "🔄 Tukar Unit Disetujui (Unit Lama Kanibalan)" : "🛠️ Tidak Dapat Diperbaiki (Kanibalan)",
cls: "bg-purple-50 text-purple-800 border-purple-200",
};
case "DAMAGED_UNUSABLE":
return {
label: origin === "WARRANTY_REPLACE" ? "🔄 Tukar Unit Disetujui (Unit Lama Rusak Total)" : "🚫 Rusak Total (Tidak Bisa Diperbaiki)",
cls: "bg-rose-50 text-rose-800 border-rose-200",
};
case "REPLACED_WARRANTY":
return {
label: "🔄 Unit Diganti Baru (Garansi)",
cls: "bg-amber-50 text-amber-800 border-amber-200",
};
default:
return { label: condition, cls: "bg-slate-100 text-slate-700 border-slate-200" };
}
}
function getOriginDisplay(origin: string) {
switch (origin) {
case "WARRANTY_FREE":
return "Service Gratis (Masa Garansi Aktif)";
case "WARRANTY_REPLACE":
return "Tukar Unit Baru (Masa Garansi Aktif)";
case "PAID_SERVICE":
return "Jasa Service Berbayar (Garansi Habis)";
default:
return "Layanan Purna Jual";
}
}
export default function PublicRmaPortalPage() {
const [activeTab, setActiveTab] = useState<"submit" | "track">("submit");
// Step 1: Verifikasi SN
const [snInput, setSnInput] = useState("");
const [verifying, setVerifying] = useState(false);
const [verifyError, setVerifyError] = useState<string | null>(null);
const [verifiedDevice, setVerifiedDevice] = useState<VerifiedDevice | null>(null);
const [snHistoryTickets, setSnHistoryTickets] = useState<PublicTicket[]>([]);
// Step 2: Form Pengajuan RMA
const [requestType, setRequestType] = useState<"WARRANTY_FREE" | "WARRANTY_REPLACE" | "PAID_SERVICE">("WARRANTY_FREE");
const [contactName, setContactName] = useState("");
const [contactPhone, setContactPhone] = useState("");
const [returnAddress, setReturnAddress] = useState("");
const [damageDescription, setDamageDescription] = useState("");
const [submitting, setSubmitting] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const [createdTicket, setCreatedTicket] = useState<PublicTicket | null>(null);
const [copiedTicket, setCopiedTicket] = useState(false);
// Tab 2: Lacak Status Tiket
const [trackQuery, setTrackQuery] = useState("");
const [tracking, setTracking] = useState(false);
const [trackError, setTrackError] = useState<string | null>(null);
const [trackedTickets, setTrackedTickets] = useState<PublicTicket[]>([]);
const handleVerifySn = async (e: React.FormEvent) => {
e.preventDefault();
const clean = snInput.trim();
if (!clean) return;
setVerifying(true);
setVerifyError(null);
setVerifiedDevice(null);
setSnHistoryTickets([]);
setCreatedTicket(null);
setSubmitError(null);
try {
const res = await fetch(`/api/public/rma?sn=${encodeURIComponent(clean)}`);
const data = await res.json();
if (!res.ok || !data.verified) {
setVerifyError(
data.error ||
"Serial Number (SN) tidak terdaftar di database kami. Pengajuan service hanya untuk perangkat resmi yang tercatat."
);
return;
}
setVerifiedDevice(data.device);
setSnHistoryTickets(data.existingTickets || []);
setRequestType(data.device.isWarrantyActive ? "WARRANTY_FREE" : "PAID_SERVICE");
} catch {
setVerifyError("Gagal menghubungi server. Periksa koneksi internet Anda lalu coba lagi.");
} finally {
setVerifying(false);
}
};
const handleSubmitRma = async (e: React.FormEvent) => {
e.preventDefault();
if (!verifiedDevice) return;
setSubmitting(true);
setSubmitError(null);
try {
const res = await fetch("/api/public/rma", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
serialNumber: verifiedDevice.serialNumber,
requestType: verifiedDevice.isWarrantyActive ? requestType : "PAID_SERVICE",
contactName,
contactPhone,
returnAddress,
damageDescription,
}),
});
const data = await res.json();
if (!res.ok) {
setSubmitError(data.error || "Gagal mengirim pengajuan RMA / Service.");
return;
}
setCreatedTicket(data.ticket);
setContactName("");
setContactPhone("");
setReturnAddress("");
setDamageDescription("");
} catch {
setSubmitError("Gagal mengirim pengajuan. Silakan coba kembali.");
} finally {
setSubmitting(false);
}
};
const handleTrackTicket = async (e?: React.FormEvent, overrideQuery?: string) => {
if (e) e.preventDefault();
const q = (overrideQuery ?? trackQuery).trim();
if (!q) return;
setTracking(true);
setTrackError(null);
setTrackedTickets([]);
try {
const res = await fetch(`/api/public/rma?ticket=${encodeURIComponent(q)}`);
const data = await res.json();
if (!res.ok) {
setTrackError(data.error || "Tiket RMA atau Serial Number tidak ditemukan.");
return;
}
setTrackedTickets(data.tickets || []);
} catch {
setTrackError("Gagal memuat status tiket. Silakan coba kembali.");
} finally {
setTracking(false);
}
};
const handleCopyTicket = (ticketNo: string) => {
navigator.clipboard?.writeText(ticketNo);
setCopiedTicket(true);
setTimeout(() => setCopiedTicket(false), 2500);
};
return (
<div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 text-slate-100 flex flex-col">
{/* Top Bar */}
<header className="border-b border-slate-800/80 bg-slate-950/70 backdrop-blur-sm">
<div className="max-w-3xl mx-auto px-4 py-3.5 flex items-center justify-between gap-3">
<div className="flex items-center gap-2.5 min-w-0">
<div className="h-9 w-9 rounded-lg bg-blue-600 flex items-center justify-center text-white shrink-0 shadow-md shadow-blue-600/20">
<Building2 className="h-5 w-5" />
</div>
<div className="min-w-0">
<div className="font-bold text-sm sm:text-base text-white truncate">
Portal RMA &amp; Service Customer
</div>
<div className="text-[11px] text-slate-400 truncate">
Pengajuan Garansi, Tukar Unit &amp; Service Tanpa Login
</div>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<ThemeToggle compact />
<Link
href="/login"
className="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-white border border-slate-700 text-xs font-semibold shrink-0 transition-colors"
>
<span>Login Staff</span>
<ArrowRight className="h-3.5 w-3.5" />
</Link>
</div>
</div>
</header>
{/* Main Content */}
<main className="flex-1 max-w-3xl w-full mx-auto px-4 py-6 sm:py-8">
{/* Switcher Tabs */}
<div className="grid grid-cols-2 gap-2 p-1.5 bg-slate-900 border border-slate-800 rounded-xl mb-6">
<button
type="button"
onClick={() => setActiveTab("submit")}
className={`py-2.5 px-3 rounded-lg text-xs sm:text-sm font-bold flex items-center justify-center gap-2 transition-all ${
activeTab === "submit"
? "bg-blue-600 text-white shadow-md shadow-blue-600/20"
: "text-slate-400 hover:text-white"
}`}
>
<Wrench className="h-4 w-4 shrink-0" />
<span>Ajukan RMA / Service</span>
</button>
<button
type="button"
onClick={() => setActiveTab("track")}
className={`py-2.5 px-3 rounded-lg text-xs sm:text-sm font-bold flex items-center justify-center gap-2 transition-all ${
activeTab === "track"
? "bg-blue-600 text-white shadow-md shadow-blue-600/20"
: "text-slate-400 hover:text-white"
}`}
>
<FileSearch className="h-4 w-4 shrink-0" />
<span>Lacak Status Tiket</span>
</button>
</div>
{/* ================================================================= */}
{/* TAB 1: AJUKAN RMA / SERVICE (VERIFIKASI WAJIB VIA SN DATABASE) */}
{/* ================================================================= */}
{activeTab === "submit" && (
<div className="space-y-5">
{/* Step 1: Verifikasi SN */}
<div className="bg-white text-slate-900 rounded-2xl shadow-xl border border-slate-200 p-5 sm:p-6">
<div className="flex items-start gap-3 mb-4">
<div className="h-8 w-8 rounded-full bg-blue-100 text-blue-700 font-bold text-sm flex items-center justify-center shrink-0">
1
</div>
<div>
<h2 className="font-bold text-slate-900 text-sm sm:text-base">
Verifikasi Serial Number (SN) Perangkat
</h2>
<p className="text-xs text-slate-500 mt-0.5">
Masukkan Serial Number fisik pada unit Anda. Pengajuan service hanya dapat dilakukan untuk perangkat yang SN-nya terdaftar resmi di database kami.
</p>
</div>
</div>
<form onSubmit={handleVerifySn} className="flex flex-col sm:flex-row gap-2.5">
<div className="relative flex-1">
<Search className="h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
<input
type="text"
required
placeholder="Contoh: SN-DEV-0001"
value={snInput}
onChange={(e) => setSnInput(e.target.value)}
className="w-full h-11 pl-9 pr-3 border border-slate-300 rounded-xl font-mono text-sm font-bold text-slate-900 placeholder:font-sans placeholder:font-normal focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<button
type="submit"
disabled={verifying || !snInput.trim()}
className="h-11 px-5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-bold text-xs sm:text-sm shadow-sm disabled:opacity-50 transition-colors shrink-0 inline-flex items-center justify-center gap-2"
>
<ShieldCheck className="h-4 w-4" />
<span>{verifying ? "Memverifikasi..." : "Verifikasi SN"}</span>
</button>
</form>
{verifyError && (
<div className="mt-4 p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs flex items-start gap-2.5">
<AlertCircle className="h-4 w-4 text-rose-600 shrink-0 mt-0.5" />
<div>
<div className="font-bold">Verifikasi SN Gagal</div>
<p className="mt-0.5 leading-relaxed">{verifyError}</p>
</div>
</div>
)}
</div>
{/* Kartu Sukses setelah Tiket Dibuat */}
{createdTicket && (
<div className="bg-emerald-50 text-emerald-950 rounded-2xl border-2 border-emerald-300 p-5 sm:p-6 shadow-xl space-y-4">
<div className="flex items-start gap-3">
<CheckCircle2 className="h-7 w-7 text-emerald-600 shrink-0" />
<div>
<h3 className="font-bold text-base text-emerald-900">
Pengajuan RMA / Service Berhasil Dikirim!
</h3>
<p className="text-xs text-emerald-800 mt-0.5">
Simpan Nomor Tiket RMA di bawah ini untuk memantau status perbaikan, biaya kirim, dan nomor resi pengiriman balik.
</p>
</div>
</div>
<div className="p-4 rounded-xl bg-white border border-emerald-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div>
<span className="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">
Nomor Tiket RMA Anda
</span>
<div className="font-mono font-extrabold text-lg sm:text-xl text-blue-700">
{createdTicket.recordNumber}
</div>
<div className="text-xs text-slate-600 mt-0.5">
{createdTicket.productName} • SN: <strong className="font-mono">{createdTicket.serialNumber}</strong>
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
<button
type="button"
onClick={() => handleCopyTicket(createdTicket.recordNumber)}
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-800 text-xs font-bold"
>
{copiedTicket ? (
<>
<Check className="h-3.5 w-3.5 text-emerald-600" />
<span>Disalin</span>
</>
) : (
<>
<Copy className="h-3.5 w-3.5" />
<span>Salin Tiket</span>
</>
)}
</button>
<button
type="button"
onClick={() => {
setTrackQuery(createdTicket.recordNumber);
setActiveTab("track");
handleTrackTicket(undefined, createdTicket.recordNumber);
}}
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold"
>
<span>Lacak Status</span>
<ArrowRight className="h-3.5 w-3.5" />
</button>
</div>
</div>
<div className="text-[11px] text-emerald-900 bg-emerald-100/70 rounded-lg p-3 leading-relaxed">
<strong>Catatan Pengiriman:</strong> Cantumkan nomor tiket <strong className="font-mono">{createdTicket.recordNumber}</strong> pada paket saat mengirimkan unit ke kantor/gudang kami. Biaya pengiriman ke kami dan pengiriman balik ditanggung oleh customer.
</div>
</div>
)}
{/* Step 2: Detail Perangkat Terverifikasi + Form Pengajuan (HANYA muncul jika SN terverifikasi!) */}
{verifiedDevice && !createdTicket && (
<div className="bg-white text-slate-900 rounded-2xl shadow-xl border border-slate-200 p-5 sm:p-6 space-y-5">
{/* Banner Info Perangkat & Status Garansi */}
<div
className={`p-4 rounded-xl border ${
verifiedDevice.isWarrantyActive
? "bg-emerald-50 border-emerald-200"
: "bg-amber-50 border-amber-300"
}`}
>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<div>
<div className="inline-flex items-center gap-1.5 text-[11px] font-bold text-emerald-700 uppercase tracking-wider">
<CheckCircle2 className="h-3.5 w-3.5" />
<span>Perangkat Terverifikasi Resmi</span>
</div>
<h3 className="font-bold text-slate-900 text-sm sm:text-base mt-0.5">
{verifiedDevice.productName}
</h3>
<div className="text-xs text-slate-600 mt-0.5">
SN: <strong className="font-mono text-slate-900">{verifiedDevice.serialNumber}</strong> • SKU: <span className="font-mono">{verifiedDevice.productSku}</span>
</div>
</div>
<div className="sm:text-right">
{verifiedDevice.isWarrantyActive ? (
<span className="inline-block px-3 py-1 rounded-lg bg-emerald-600 text-white text-xs font-bold">
🛡️ Garansi Aktif s/d{" "}
{new Date(verifiedDevice.warrantyExpiry).toLocaleDateString("id-ID", {
day: "numeric",
month: "short",
year: "numeric",
})}
</span>
) : (
<span className="inline-block px-3 py-1 rounded-lg bg-amber-600 text-white text-xs font-bold">
⚠️ Garansi Habis (
{new Date(verifiedDevice.warrantyExpiry).toLocaleDateString("id-ID", {
day: "numeric",
month: "short",
year: "numeric",
})}
)
</span>
)}
</div>
</div>
</div>
{/* Jika sudah ada riwayat tiket sebelumnya */}
{snHistoryTickets.length > 0 && (
<div className="p-3 rounded-xl bg-slate-50 border border-slate-200 text-xs space-y-1.5">
<div className="font-bold text-slate-700 flex items-center gap-1.5">
<Clock className="h-3.5 w-3.5 text-slate-500" />
<span>Riwayat Service / RMA Sebelumnya untuk SN ini ({snHistoryTickets.length}):</span>
</div>
{snHistoryTickets.slice(0, 3).map((t) => (
<div key={t.recordNumber} className="flex flex-wrap items-center justify-between gap-2 bg-white px-2.5 py-1.5 rounded-lg border border-slate-200">
<div>
<span className="font-mono font-bold text-blue-700">{t.recordNumber}</span>
<span className="text-slate-500 ml-2">{getConditionDisplay(t.condition, t.serviceOrigin).label}</span>
</div>
<button
type="button"
onClick={() => {
setTrackQuery(t.recordNumber);
setActiveTab("track");
handleTrackTicket(undefined, t.recordNumber);
}}
className="text-blue-600 hover:underline font-semibold text-[11px]"
>
Lihat Detail →
</button>
</div>
))}
</div>
)}
{/* Form Step 2 */}
<form onSubmit={handleSubmitRma} className="space-y-4 text-xs">
<div className="flex items-start gap-3">
<div className="h-8 w-8 rounded-full bg-blue-100 text-blue-700 font-bold text-sm flex items-center justify-center shrink-0">
2
</div>
<div>
<h2 className="font-bold text-slate-900 text-sm sm:text-base">
Lengkapi Formulir Pengajuan RMA / Service
</h2>
<p className="text-xs text-slate-500 mt-0.5">
Biaya kirim pengiriman unit ke kami &amp; kirim balik ke alamat Anda ditanggung oleh customer.
</p>
</div>
</div>
{submitError && (
<div className="p-3 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 font-semibold flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-rose-600 shrink-0 mt-0.5" />
<span>{submitError}</span>
</div>
)}
{/* Pilihan Layanan Otomatis Sesuai Garansi */}
<div>
<label className="block font-bold text-slate-700 mb-1.5">
Jenis Layanan yang Diajukan *
</label>
{verifiedDevice.isWarrantyActive ? (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
<button
type="button"
onClick={() => setRequestType("WARRANTY_FREE")}
className={`p-3 rounded-xl border text-left transition-all ${
requestType === "WARRANTY_FREE"
? "bg-emerald-50 border-emerald-400 text-emerald-950 shadow-xs"
: "bg-white border-slate-200 text-slate-600 hover:bg-slate-50"
}`}
>
<div className="font-bold text-xs flex items-center gap-1.5">
<Wrench className="h-3.5 w-3.5 text-emerald-600" />
<span>Service Gratis (Garansi)</span>
</div>
<p className="text-[10.5px] text-slate-500 mt-1">
Perbaikan unit gratis (Rp 0) selama masa garansi aktif. Ongkir ditanggung customer.
</p>
</button>
<button
type="button"
onClick={() => setRequestType("WARRANTY_REPLACE")}
className={`p-3 rounded-xl border text-left transition-all ${
requestType === "WARRANTY_REPLACE"
? "bg-amber-50 border-amber-400 text-amber-950 shadow-xs"
: "bg-white border-slate-200 text-slate-600 hover:bg-slate-50"
}`}
>
<div className="font-bold text-xs flex items-center gap-1.5">
<RotateCcw className="h-3.5 w-3.5 text-amber-600" />
<span>Ajukan Tukar Unit Baru (Garansi)</span>
</div>
<p className="text-[10.5px] text-slate-500 mt-1">
Tukar unit pengganti gratis bila kerusakan memenuhi syarat garansi. Ongkir ditanggung customer.
</p>
</button>
</div>
) : (
<div className="p-3.5 rounded-xl bg-amber-50 border border-amber-300 text-amber-950">
<div className="font-bold text-xs">
💰 Jasa Service Berbayar (Masa Garansi Habis)
</div>
<p className="text-[11px] text-amber-900 mt-0.5">
Karena masa garansi telah berakhir, pengajuan akan diproses sebagai <strong>Jasa Service Berbayar</strong>. Estimasi biaya jasa &amp; ongkir kirim balik akan diinformasikan setelah unit diperiksa teknisi.
</p>
</div>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Nama Pemohon / PIC <span className="text-rose-500">*</span>
</label>
<input
type="text"
required
placeholder="Nama lengkap Anda / PIC perusahaan"
value={contactName}
onChange={(e) => setContactName(e.target.value)}
className="w-full h-10 px-3 border border-slate-300 rounded-lg text-xs"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
No. WhatsApp / Telepon Aktif <span className="text-rose-500">*</span>
</label>
<input
type="text"
required
placeholder="08xxxxxxxxxx"
value={contactPhone}
onChange={(e) => setContactPhone(e.target.value)}
className="w-full h-10 px-3 border border-slate-300 rounded-lg text-xs"
/>
</div>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
Alamat Pengiriman Balik <span className="text-rose-500">*</span>
</label>
<textarea
rows={2}
required
placeholder="Masukkan alamat lengkap tujuan pengiriman balik setelah service / ganti unit selesai..."
value={returnAddress}
onChange={(e) => setReturnAddress(e.target.value)}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-xs"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
Deskripsi Kerusakan / Kendala Perangkat <span className="text-rose-500">*</span>
</label>
<textarea
rows={3}
required
placeholder="Jelaskan gejala kerusakan secara detail (misal: layar tidak menyala, port error, daya tidak masuk, dll)..."
value={damageDescription}
onChange={(e) => setDamageDescription(e.target.value)}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-xs"
/>
</div>
<div className="pt-2 flex justify-end">
<button
type="submit"
disabled={submitting}
className="w-full sm:w-auto px-6 py-2.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-bold text-xs sm:text-sm shadow-sm disabled:opacity-50 inline-flex items-center justify-center gap-2"
>
<CheckCircle2 className="h-4 w-4" />
<span>{submitting ? "Mengirim Pengajuan..." : "Kirim Pengajuan RMA / Service"}</span>
</button>
</div>
</form>
</div>
)}
</div>
)}
{/* ================================================================= */}
{/* TAB 2: LACAK STATUS TIKET RMA / SERVICE (TANPA LOGIN) */}
{/* ================================================================= */}
{activeTab === "track" && (
<div className="space-y-5">
<div className="bg-white text-slate-900 rounded-2xl shadow-xl border border-slate-200 p-5 sm:p-6">
<h2 className="font-bold text-slate-900 text-sm sm:text-base mb-1">
Lacak Status RMA / Service Anda
</h2>
<p className="text-xs text-slate-500 mb-4">
Masukkan <strong>Nomor Tiket RMA</strong> (contoh: <span className="font-mono">RMA-...</span>) atau <strong>Serial Number (SN)</strong> perangkat Anda.
</p>
<form onSubmit={(e) => handleTrackTicket(e)} className="flex flex-col sm:flex-row gap-2.5">
<div className="relative flex-1">
<Search className="h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
<input
type="text"
required
placeholder="Nomor Tiket RMA atau Serial Number (SN)"
value={trackQuery}
onChange={(e) => setTrackQuery(e.target.value)}
className="w-full h-11 pl-9 pr-3 border border-slate-300 rounded-xl font-mono text-sm font-bold text-slate-900 placeholder:font-sans placeholder:font-normal focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<button
type="submit"
disabled={tracking || !trackQuery.trim()}
className="h-11 px-5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-bold text-xs sm:text-sm shadow-sm disabled:opacity-50 shrink-0"
>
{tracking ? "Mencari..." : "Lacak Status"}
</button>
</form>
{trackError && (
<div className="mt-4 p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-rose-600 shrink-0 mt-0.5" />
<span>{trackError}</span>
</div>
)}
</div>
{trackedTickets.length > 0 && (
<div className="space-y-4">
{trackedTickets.map((t) => {
const badge = getConditionDisplay(t.condition, t.serviceOrigin);
const totalCost = (t.serviceFee || 0) + (t.returnShippingCost || 0);
return (
<div
key={t.recordNumber}
className="bg-white text-slate-900 rounded-2xl shadow-xl border border-slate-200 p-5 space-y-3.5 text-xs"
>
<div className="flex flex-wrap items-start justify-between gap-2 pb-3 border-b border-slate-100">
<div>
<div className="font-mono font-extrabold text-blue-700 text-sm">
{t.recordNumber}
</div>
<div className="font-bold text-slate-800 mt-0.5">{t.productName}</div>
<div className="text-[11px] text-slate-500">
SN: <strong className="font-mono text-slate-800">{t.serialNumber}</strong> • {getOriginDisplay(t.serviceOrigin)}
</div>
</div>
<span className={`px-2.5 py-1 rounded-lg border font-bold text-[11px] ${badge.cls}`}>
{badge.label}
</span>
</div>
<div className="space-y-2">
<div>
<span className="text-slate-400 font-semibold block text-[10.5px] uppercase">
Keluhan / Kerusakan
</span>
<p className="text-slate-700 mt-0.5">{t.damageDescription}</p>
</div>
{t.actionTaken && (
<div className="p-2.5 rounded-lg bg-blue-50 border border-blue-100 text-blue-900">
<span className="font-bold block text-[10.5px] uppercase text-blue-700">
Update Progres Teknisi
</span>
<p className="mt-0.5">{t.actionTaken}</p>
</div>
)}
</div>
{/* Rincian Biaya & Pengiriman Balik */}
<div className="p-3 rounded-xl bg-slate-50 border border-slate-200 space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-slate-600">Biaya Jasa Service:</span>
<strong className="font-mono text-slate-900">
{t.serviceFee > 0 ? formatRupiah(t.serviceFee) : "Rp 0 (FREE)"}
</strong>
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Biaya Kirim Balik (Ditanggung User):</span>
<strong className="font-mono text-slate-900">
{formatRupiah(t.returnShippingCost || 0)}
</strong>
</div>
{totalCost > 0 && (
<div className="flex items-center justify-between pt-1.5 border-t border-slate-200">
<span className="font-bold text-slate-800">Total Tagihan:</span>
<div className="flex items-center gap-2">
<strong className="font-mono text-sm text-blue-800">
{formatRupiah(totalCost)}
</strong>
<span
className={`px-2 py-0.5 rounded text-[10px] font-bold ${
t.servicePaymentStatus === "PAID"
? "bg-emerald-600 text-white"
: "bg-amber-100 text-amber-900 border border-amber-300"
}`}
>
{t.servicePaymentStatus === "PAID" ? "LUNAS" : "BELUM BAYAR"}
</span>
</div>
</div>
)}
{(t.returnCourierName || t.returnTrackingNumber) && (
<div className="pt-1.5 border-t border-slate-200 flex items-center gap-2 text-sky-900 font-semibold">
<Truck className="h-4 w-4 text-sky-600 shrink-0" />
<span>
Pengiriman Balik: {t.returnCourierName || "Kurir"}
{t.returnTrackingNumber && (
<span className="ml-1.5 px-1.5 py-0.5 rounded bg-sky-100 font-mono font-bold">
Resi: {t.returnTrackingNumber}
</span>
)}
</span>
</div>
)}
</div>
<div className="text-[10.5px] text-slate-400 flex items-center justify-between">
<span>Diajukan: {formatDateTime(t.createdAt)}</span>
<span>Diperbarui: {formatDateTime(t.updatedAt)}</span>
</div>
</div>
);
})}
</div>
)}
</div>
)}
</main>
<footer className="py-4 text-center text-[11px] text-slate-500 border-t border-slate-800/60">
Portal Layanan Purna Jual &amp; Garansi • Verifikasi Serial Number Otomatis
</footer>
</div>
);
}
+1742 -304
View File
File diff suppressed because it is too large. Load diff
+194 -22
View File
@@ -13,6 +13,9 @@ import {
Radio,
History,
Lock,
ShieldCheck,
Download,
Database,
} from "lucide-react";
const DIVISION_CHANNELS = [
@@ -153,6 +156,40 @@ export default function SettingsPage() {
}
};
const handleTestEmail = async () => {
setTesting(true);
setStatusMessage(null);
try {
const res = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
channel: "EMAIL",
smtpHost: settings.SMTP_HOST,
smtpPort: settings.SMTP_PORT,
smtpUser: settings.SMTP_USER,
smtpPass: settings.SMTP_PASS,
smtpFrom: settings.SMTP_FROM,
testEmail: currentUser?.email,
}),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || "Gagal mengirim email uji coba");
setStatusMessage({
type: "success",
text: data.message || "Email uji coba berhasil diproses!",
});
loadData();
} catch (err: any) {
setStatusMessage({
type: "error",
text: err.message || "Gagal menguji koneksi SMTP",
});
} finally {
setTesting(false);
}
};
const handleTestBroadcast = async () => {
setTesting(true);
setStatusMessage(null);
@@ -181,8 +218,8 @@ export default function SettingsPage() {
return (
<AppShell
title="Pengaturan Sistem & Saluran Notifikasi Divisi"
subtitle="Konfigurasi bot Telegram per divisi, email SMTP, serta aturan otomatisasi mutasi barang dan uang"
title="Pengaturan"
subtitle="Konfigurasi email SMTP, notifikasi Telegram, dan aturan pengiriman laporan per divisi"
>
{statusMessage && (
<div
@@ -351,23 +388,7 @@ export default function SettingsPage() {
</label>
</div>
<div className="grid grid-cols-2 gap-3 text-xs">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Alamat Pengirim (Sender Email)
</label>
<input
type="text"
disabled={!isAdmin}
placeholder="erp-system@nusantara.id"
value={settings.SMTP_FROM || ""}
onChange={(e) =>
setSettings({ ...settings, SMTP_FROM: e.target.value })
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg disabled:bg-slate-100"
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
<div>
<label className="block font-semibold text-slate-700 mb-1">
SMTP Host / Server
@@ -375,7 +396,7 @@ export default function SettingsPage() {
<input
type="text"
disabled={!isAdmin}
placeholder="smtp.gmail.com / smtp.mailtrap.io"
placeholder="misal: smtp.gmail.com / mail.perusahaan.id"
value={settings.SMTP_HOST || ""}
onChange={(e) =>
setSettings({ ...settings, SMTP_HOST: e.target.value })
@@ -383,7 +404,87 @@ export default function SettingsPage() {
className="w-full px-3 py-2 border border-slate-300 rounded-lg disabled:bg-slate-100"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
SMTP Port (587 TLS / 465 SSL)
</label>
<input
type="text"
disabled={!isAdmin}
placeholder="587"
value={settings.SMTP_PORT || "587"}
onChange={(e) =>
setSettings({ ...settings, SMTP_PORT: e.target.value })
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono disabled:bg-slate-100"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
SMTP Username / Email Login
</label>
<input
type="text"
disabled={!isAdmin}
placeholder="notifikasi@perusahaan.id"
value={settings.SMTP_USER || ""}
onChange={(e) =>
setSettings({ ...settings, SMTP_USER: e.target.value })
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg disabled:bg-slate-100"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
SMTP Password / App Password
</label>
<input
type="password"
disabled={!isAdmin}
placeholder="App Password SMTP"
value={settings.SMTP_PASS || ""}
onChange={(e) =>
setSettings({ ...settings, SMTP_PASS: e.target.value })
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg disabled:bg-slate-100"
/>
</div>
<div className="sm:col-span-2 flex flex-col sm:flex-row sm:items-end gap-2">
<div className="flex-1">
<label className="block font-semibold text-slate-700 mb-1">
Alamat Pengirim (Sender From)
</label>
<input
type="text"
disabled={!isAdmin}
placeholder="erp-system@perusahaan.id"
value={settings.SMTP_FROM || ""}
onChange={(e) =>
setSettings({ ...settings, SMTP_FROM: e.target.value })
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg disabled:bg-slate-100"
/>
</div>
{isAdmin && (
<button
type="button"
disabled={testing}
onClick={handleTestEmail}
className="shrink-0 h-9 px-3.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-semibold flex items-center justify-center gap-1.5 shadow-xs transition-colors disabled:opacity-50"
>
<Mail className="h-3.5 w-3.5" />
<span>{testing ? "Mengirim..." : "Tes Kirim Email"}</span>
</button>
)}
</div>
</div>
<p className="text-[10.5px] text-slate-500 mt-3 leading-relaxed">
ℹ️ Setiap staf menerima notifikasi otomatis ke alamat <strong>email terdaftar masing-masing</strong> sesuai <strong>kapasitas divisinya</strong> (Gudang tidak menerima nominal uang/keuangan, Finance fokus transaksi uang &amp; approval PO, Sales fokus order/RMA/pelunasan customer).
</p>
</div>
{/* 3. Event Trigger Toggles */}
@@ -480,9 +581,30 @@ export default function SettingsPage() {
className="mt-0.5 h-4 w-4 rounded text-blue-600"
/>
<div>
<div className="font-bold text-slate-900">💳 Uang Keluar</div>
<div className="font-bold text-slate-900">💳 Uang Keluar &amp; Approval PO</div>
<div className="text-[11px] text-slate-500 mt-0.5">
Rute: Divisi Keuangan (Akuntan), Purchasing & Admin
Rute: Finance (Akuntan), Purchasing, Manager &amp; Admin
</div>
</div>
</label>
<label className="p-3 rounded-lg border border-slate-200 bg-slate-50 flex items-start gap-3 cursor-pointer sm:col-span-2">
<input
type="checkbox"
disabled={!isAdmin}
checked={settings.NOTIF_RMA_ENABLED !== "false"}
onChange={(e) =>
setSettings({
...settings,
NOTIF_RMA_ENABLED: e.target.checked ? "true" : "false",
})
}
className="mt-0.5 h-4 w-4 rounded text-blue-600"
/>
<div>
<div className="font-bold text-slate-900">🔧 RMA, Service Garansi, Rusak &amp; Kanibalan</div>
<div className="text-[11px] text-slate-500 mt-0.5">
Rute: Divisi Sales, Gudang/Teknisi (Inventory), Manager &amp; Admin (termasuk tiket RMA customer tanpa login)
</div>
</div>
</label>
@@ -515,6 +637,56 @@ export default function SettingsPage() {
</div>
)}
</form>
{/* Kartu Keamanan Sistem & Backup Database */}
<div className="bg-white rounded-xl border border-slate-200 shadow-xs p-6 space-y-4">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-slate-100 pb-4">
<div className="flex items-center gap-3">
<div className="h-10 w-10 rounded-xl bg-slate-100 text-slate-700 flex items-center justify-center border border-slate-200 shrink-0">
<ShieldCheck className="h-5 w-5" />
</div>
<div>
<h3 className="font-bold text-slate-900 text-sm">
Keamanan Sistem &amp; Backup Database
</h3>
<p className="text-xs text-slate-500">
Proteksi sesi aktif, enkripsi akun, dan unduh salinan snapshot database secara aman
</p>
</div>
</div>
{isAdmin && (
<a
href="/api/settings/backup"
className="inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-slate-900 hover:bg-slate-800 text-white text-xs font-semibold transition-colors shrink-0"
>
<Download className="h-3.5 w-3.5" />
<span>Unduh Backup (.db)</span>
</a>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-xs">
<div className="p-3 rounded-lg bg-slate-50 border border-slate-200 space-y-1">
<div className="font-semibold text-slate-900 flex items-center gap-1.5">
<Database className="h-3.5 w-3.5 text-emerald-600" />
<span>Snapshot Online Atomik (SQLite)</span>
</div>
<p className="text-[11px] text-slate-600">
Backup otomatis mengambil snapshot database produksi tanpa mengganggu transaksi berjalan dan tercatat di Audit Log.
</p>
</div>
<div className="p-3 rounded-lg bg-slate-50 border border-slate-200 space-y-1">
<div className="font-semibold text-slate-900 flex items-center gap-1.5">
<ShieldCheck className="h-3.5 w-3.5 text-blue-600" />
<span>Kontrol Keamanan Aktif</span>
</div>
<p className="text-[11px] text-slate-600">
RBAC Middleware, Auto-Logout Idle 30 menit, Password min. 8 karakter (huruf &amp; angka), Rate-Limit Login/MFA/RMA, Masking Secret SMTP/Bot, &amp; Kunci Akun Aktif.
</p>
</div>
</div>
</div>
</div>
{/* Live Notification Logs Stream */}
+150 -65
View File
@@ -4,6 +4,12 @@ import { useEffect, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { Modal } from "@/components/Modal";
import { formatDateTime } from "@/lib/utils";
import {
ROLE_PERMISSIONS,
getRoleDefaultNotifications,
isRoleAllowedNotifType,
type Role,
} from "@/lib/permissions";
import {
Users,
Plus,
@@ -20,12 +26,12 @@ import {
} from "lucide-react";
const roleDescriptions: Record<string, string> = {
ADMIN: "Akses penuh tanpa batas ke semua modul sistem dan konfigurasi",
MANAGER: "Melihat laporan eksekutif dan menyetujui transaksi operasional",
INVENTORY: "Mengelola katalog barang, penerimaan fisik, dan mutasi stok",
SALES: "Menerbitkan penawaran, pesanan penjualan, dan invoice pelanggan",
PURCHASING: "Mengelola pengadaan barang, vendor supplier, dan PO",
ACCOUNTANT: "Mengelola pembukuan jurnal, bagan akun (COA), dan laporan keuangan",
ADMIN: ROLE_PERMISSIONS.ADMIN.accessSummary,
MANAGER: ROLE_PERMISSIONS.MANAGER.accessSummary,
INVENTORY: ROLE_PERMISSIONS.INVENTORY.accessSummary,
SALES: ROLE_PERMISSIONS.SALES.accessSummary,
PURCHASING: ROLE_PERMISSIONS.PURCHASING.accessSummary,
ACCOUNTANT: ROLE_PERMISSIONS.ACCOUNTANT.accessSummary,
};
const EMPTY_FORM = {
@@ -33,22 +39,25 @@ const EMPTY_FORM = {
email: "",
password: "",
role: "SALES",
isActive: true,
telegramChatId: "",
notifyEmail: true,
notifyTelegram: false,
notifStockIn: true,
notifStockIn: false,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifMoneyOut: false,
notifRma: true,
mfaEnabled: false,
mfaMethod: "TOTP",
};
const NOTIF_TOPICS = [
{ key: "notifStockIn", label: "📦 Barang Masuk", desc: "Penerimaan stok dari PO supplier" },
{ key: "notifStockOut", label: "🚚 Barang Keluar", desc: "Pengeluaran stok dari SO penjualan" },
{ key: "notifMoneyIn", label: "💵 Uang Masuk", desc: "Pelunasan invoice / kas masuk" },
{ key: "notifMoneyOut", label: "💳 Uang Keluar", desc: "Pembayaran vendor / biaya operasional" },
{ key: "notifStockIn", type: "STOCK_IN" as const, label: "📦 Barang Masuk", desc: "Penerimaan stok dari PO supplier & restock" },
{ key: "notifStockOut", type: "STOCK_OUT" as const, label: "🚚 Barang Keluar", desc: "Pengeluaran stok SO, pengiriman & resi" },
{ key: "notifMoneyIn", type: "MONEY_IN" as const, label: "💵 Uang Masuk", desc: "Pelunasan invoice, kurang bayar & jasa service" },
{ key: "notifMoneyOut", type: "MONEY_OUT" as const, label: "💳 Uang Keluar & Approval PO", desc: "Approval anggaran PO & pembayaran/DP vendor" },
{ key: "notifRma", type: "RMA_SERVICE" as const, label: "🔧 RMA, Service & Garansi", desc: "Pengajuan RMA customer, perbaikan, rusak & kanibalan" },
] as const;
export default function UsersPage() {
@@ -72,13 +81,15 @@ export default function UsersPage() {
email: "",
password: "",
role: "SALES",
isActive: true,
telegramChatId: "",
notifyEmail: true,
notifyTelegram: false,
notifStockIn: true,
notifStockIn: false,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifMoneyOut: false,
notifRma: true,
mfaEnabled: false,
mfaMethod: "TOTP",
});
@@ -171,13 +182,15 @@ export default function UsersPage() {
email: u.email || "",
password: "",
role: u.role || "SALES",
isActive: u.isActive ?? true,
telegramChatId: u.telegramChatId || "",
notifyEmail: u.notifyEmail ?? true,
notifyTelegram: u.notifyTelegram ?? false,
notifStockIn: u.notifStockIn ?? true,
notifStockOut: u.notifStockOut ?? true,
notifMoneyIn: u.notifMoneyIn ?? true,
notifMoneyOut: u.notifMoneyOut ?? true,
notifStockIn: u.notifStockIn ?? false,
notifStockOut: u.notifStockOut ?? false,
notifMoneyIn: u.notifMoneyIn ?? false,
notifMoneyOut: u.notifMoneyOut ?? false,
notifRma: u.notifRma ?? false,
mfaEnabled: u.mfaEnabled ?? false,
mfaMethod: u.mfaMethod || "TOTP",
});
@@ -213,11 +226,11 @@ export default function UsersPage() {
return (
<AppShell
title={isAdmin ? "Manajemen Pengguna, RBAC & Keamanan MFA" : "Profil & Pengaturan Akun Saya"}
title={isAdmin ? "Pengguna" : "Profil Saya"}
subtitle={
isAdmin
? "Kelola akun karyawan, ubah nama/email/password, verifikasi 2-langkah (MFA), serta konfigurasi notifikasi"
: "Lihat dan ubah nama, email, password, verifikasi 2-langkah (MFA), serta preferensi notifikasi Anda"
? "Kelola akun karyawan, hak akses role, keamanan MFA, dan preferensi notifikasi"
: "Kelola profil, password, keamanan MFA, dan preferensi notifikasi akun Anda"
}
>
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
@@ -286,10 +299,21 @@ export default function UsersPage() {
<tr key={u.id} className="hover:bg-slate-50/60 transition-colors">
<td className="py-3.5 px-6 font-bold text-slate-900">
<div className="flex items-center gap-2.5">
<div className="h-7 w-7 rounded-full bg-slate-800 text-white flex items-center justify-center text-[10px] font-bold">
<div className={`h-7 w-7 rounded-full text-white flex items-center justify-center text-[10px] font-bold ${u.isActive === false ? "bg-slate-400" : "bg-slate-800"}`}>
{u.name.slice(0, 2).toUpperCase()}
</div>
<span>{u.name}</span>
<div>
<div className={u.isActive === false ? "line-through text-slate-400" : ""}>{u.name}</div>
{u.isActive === false ? (
<span className="inline-block px-1.5 py-0.2 rounded bg-rose-100 text-rose-700 text-[9px] font-bold">
LOGIN NONAKTIF
</span>
) : (
<span className="inline-block text-[9.5px] font-medium text-emerald-600">
● Akses Aktif
</span>
)}
</div>
</div>
</td>
<td className="py-3.5 px-4">
@@ -365,6 +389,11 @@ export default function UsersPage() {
💳
</span>
)}
{u.notifRma && (
<span title="RMA & Service" className="px-1 py-0.5 rounded bg-sky-50 border border-sky-200 text-[10px]">
🔧
</span>
)}
</div>
</td>
<td className="py-3.5 px-6 text-slate-600">
@@ -450,7 +479,7 @@ export default function UsersPage() {
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">Alamat Email Kerja *</label>
<input
@@ -474,7 +503,7 @@ export default function UsersPage() {
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">Kata Sandi Awal *</label>
<input
@@ -490,7 +519,11 @@ export default function UsersPage() {
<label className="block font-semibold text-slate-700 mb-1">Peran & Hak Akses (Role) *</label>
<select
value={form.role}
onChange={(e) => setForm({ ...form, role: e.target.value })}
onChange={(e) => {
const nextRole = e.target.value as Role;
const defs = getRoleDefaultNotifications(nextRole);
setForm({ ...form, role: nextRole, ...defs });
}}
className="w-full px-3 py-2 border border-slate-300 rounded-lg bg-white font-semibold text-slate-800"
>
<option value="ADMIN">ADMIN</option>
@@ -556,24 +589,37 @@ export default function UsersPage() {
</label>
</div>
<div className="border-t border-slate-200 pt-2">
<div className="grid grid-cols-2 gap-2">
{NOTIF_TOPICS.map(({ key, label, desc }) => (
<label
key={key}
className="flex items-start gap-2 cursor-pointer p-2 rounded-lg border border-slate-200 bg-white hover:bg-slate-50"
>
<input
type="checkbox"
checked={form[key as keyof typeof form] as boolean}
onChange={(e) => setForm({ ...form, [key]: e.target.checked })}
className="mt-0.5 rounded text-blue-600"
/>
<div>
<div className="font-semibold text-slate-800 text-[11px]">{label}</div>
<div className="text-[10px] text-slate-400">{desc}</div>
</div>
</label>
))}
<div className="text-[10.5px] text-slate-500 mb-2">
Topik notifikasi otomatis disesuaikan dengan kapasitas peran <strong>{form.role}</strong>:
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{NOTIF_TOPICS.map(({ key, type, label, desc }) => {
const allowed = isRoleAllowedNotifType(form.role, type);
return (
<label
key={key}
className={`flex items-start gap-2 p-2 rounded-lg border ${
allowed
? "cursor-pointer border-slate-200 bg-white hover:bg-slate-50"
: "cursor-not-allowed border-slate-100 bg-slate-100/70 opacity-60"
}`}
>
<input
type="checkbox"
disabled={!allowed}
checked={allowed && (form[key as keyof typeof form] as boolean)}
onChange={(e) => setForm({ ...form, [key]: e.target.checked })}
className="mt-0.5 rounded text-blue-600"
/>
<div>
<div className="font-semibold text-slate-800 text-[11px]">{label}</div>
<div className="text-[10px] text-slate-400">
{allowed ? desc : `Di luar kapasitas role ${form.role}`}
</div>
</div>
</label>
);
})}
</div>
</div>
</div>
@@ -610,7 +656,7 @@ export default function UsersPage() {
)}
<form onSubmit={handleEditUser} className="space-y-4 text-xs">
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Nama Lengkap Karyawan *
@@ -638,7 +684,7 @@ export default function UsersPage() {
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block font-semibold text-slate-700 mb-1 flex items-center gap-1">
<KeyRound className="h-3.5 w-3.5 text-amber-600" />
@@ -665,7 +711,11 @@ export default function UsersPage() {
{isAdmin ? (
<select
value={editForm.role}
onChange={(e) => setEditForm({ ...editForm, role: e.target.value })}
onChange={(e) => {
const nextRole = e.target.value as Role;
const defs = getRoleDefaultNotifications(nextRole);
setEditForm({ ...editForm, role: nextRole, ...defs });
}}
className="w-full px-3 py-2 border border-slate-300 rounded-lg bg-white font-semibold text-slate-800"
>
<option value="ADMIN">ADMIN - Super Admin</option>
@@ -781,28 +831,63 @@ export default function UsersPage() {
</div>
<div className="border-t border-slate-200 pt-2">
<div className="grid grid-cols-2 gap-2">
{NOTIF_TOPICS.map(({ key, label, desc }) => (
<label
key={key}
className="flex items-start gap-2 cursor-pointer p-2 rounded-lg border border-slate-200 bg-white hover:bg-slate-50"
>
<input
type="checkbox"
checked={editForm[key as keyof typeof editForm] as boolean}
onChange={(e) => setEditForm({ ...editForm, [key]: e.target.checked })}
className="mt-0.5 rounded text-blue-600"
/>
<div>
<div className="font-semibold text-slate-800 text-[11px]">{label}</div>
<div className="text-[10px] text-slate-400">{desc}</div>
</div>
</label>
))}
<div className="text-[10.5px] text-slate-500 mb-2">
Kapasitas notifikasi email/Telegram sesuai peran <strong>{editForm.role}</strong>:
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{NOTIF_TOPICS.map(({ key, type, label, desc }) => {
const allowed = isRoleAllowedNotifType(editForm.role, type);
return (
<label
key={key}
className={`flex items-start gap-2 p-2 rounded-lg border ${
allowed
? "cursor-pointer border-slate-200 bg-white hover:bg-slate-50"
: "cursor-not-allowed border-slate-100 bg-slate-100/70 opacity-60"
}`}
>
<input
type="checkbox"
disabled={!allowed}
checked={allowed && (editForm[key as keyof typeof editForm] as boolean)}
onChange={(e) => setEditForm({ ...editForm, [key]: e.target.checked })}
className="mt-0.5 rounded text-blue-600"
/>
<div>
<div className="font-semibold text-slate-800 text-[11px]">{label}</div>
<div className="text-[10px] text-slate-400">
{allowed ? desc : `Di luar kapasitas role ${editForm.role}`}
</div>
</div>
</label>
);
})}
</div>
</div>
</div>
{isAdmin && editUser?.id !== currentUser?.id && (
<div className="p-3 rounded-lg border border-rose-200 bg-rose-50/50 flex items-center justify-between">
<div>
<div className="font-bold text-slate-800 text-xs">Status Akses Login Akun</div>
<div className="text-[10.5px] text-slate-500">
Jika dinonaktifkan, akun ini langsung diblokir dari login &amp; berhenti menerima notifikasi email.
</div>
</div>
<label className="inline-flex items-center gap-2 cursor-pointer font-bold text-xs shrink-0 ml-3">
<input
type="checkbox"
checked={editForm.isActive}
onChange={(e) => setEditForm({ ...editForm, isActive: e.target.checked })}
className="h-4 w-4 rounded text-emerald-600"
/>
<span className={editForm.isActive ? "text-emerald-700" : "text-rose-700"}>
{editForm.isActive ? "Aktif" : "Nonaktif"}
</span>
</label>
</div>
)}
<div className="pt-2 flex items-center justify-end gap-2 border-t border-slate-200">
<button
type="button"
+47 -59
View File
@@ -4,7 +4,7 @@ import { ReactNode, useEffect, useState } from "react";
import { Sidebar } from "./Sidebar";
import { Navbar } from "./Navbar";
import { useRouter, usePathname } from "next/navigation";
import { canAccessRoute } from "@/lib/permissions";
import { canAccessRoute, getDefaultLandingRoute } from "@/lib/permissions";
import { ShieldAlert, ArrowLeft } from "lucide-react";
import Link from "next/link";
@@ -13,7 +13,6 @@ interface UserSession {
name: string;
role: string;
email: string;
envMode?: "DEMO" | "LIVE";
}
let memoryCachedUser: UserSession | null = null;
@@ -46,6 +45,7 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
});
const [companies, setCompanies] = useState<string[]>(memoryCachedCompanies);
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const [selectedCompany, setSelectedCompany] = useState<string>(() => {
if (typeof window !== "undefined") {
return localStorage.getItem("erp_selected_pt") || "ALL";
@@ -95,9 +95,42 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
}
};
window.addEventListener("erp:company-sync", handleExternalCompanyUpdate);
// Keamanan sesi: Auto-logout jika tidak ada aktivitas selama 30 menit
const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
let idleTimer: ReturnType<typeof setTimeout> | null = null;
let lastReset = 0;
const triggerIdleLogout = async () => {
try {
memoryCachedUser = null;
if (typeof window !== "undefined") {
sessionStorage.removeItem("erp_cached_user");
}
await fetch("/api/auth/logout", { method: "POST" });
} catch {
// ignore network errors during logout
}
window.location.href = "/login?reason=idle_timeout";
};
const resetIdleTimer = () => {
const now = Date.now();
if (now - lastReset < 10_000) return; // throttle 10 detik
lastReset = now;
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(triggerIdleLogout, IDLE_TIMEOUT_MS);
};
resetIdleTimer();
const activityEvents = ["mousemove", "keydown", "click", "scroll", "touchstart"] as const;
activityEvents.forEach((evt) => window.addEventListener(evt, resetIdleTimer, { passive: true }));
return () => {
mounted = false;
window.removeEventListener("erp:company-sync", handleExternalCompanyUpdate);
if (idleTimer) clearTimeout(idleTimer);
activityEvents.forEach((evt) => window.removeEventListener(evt, resetIdleTimer));
};
}, [router]);
@@ -185,70 +218,25 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
}
};
const handleSwitchEnv = async (targetMode: "DEMO" | "LIVE") => {
// Jika sudah berada di mode LIVE, tidak boleh kembali ke DEMO
if (user?.envMode === "LIVE" && targetMode === "DEMO") {
return;
}
// Pemisahan Kredensial: Dari DEMO ke LIVE wajib login ulang dengan akun Production
if (user?.envMode === "DEMO" && targetMode === "LIVE") {
try {
await fetch("/api/auth/logout", { method: "POST" });
} catch (err) {
console.error("Logout on switch error:", err);
}
memoryCachedUser = null;
if (typeof window !== "undefined") {
sessionStorage.removeItem("erp_cached_user");
sessionStorage.removeItem("erp_finance_tab");
window.location.href = "/login?mode=LIVE&reason=switch_live";
}
return;
}
try {
const res = await fetch("/api/auth/me", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ envMode: targetMode }),
});
const data = await res.json();
if (res.ok && data.user) {
memoryCachedUser = data.user;
setUser(data.user);
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
window.location.reload();
}
} else {
memoryCachedUser = null;
if (typeof window !== "undefined") {
sessionStorage.removeItem("erp_cached_user");
}
router.push(`/login?mode=${targetMode}`);
}
} catch (err) {
console.error("Switch env error:", err);
}
};
// Check if current user is allowed to access this route
const isAllowed = user ? canAccessRoute(user.role, pathname) : true;
return (
<div className="min-h-screen bg-slate-50 flex">
{/* Sidebar with role-filtered menus */}
<Sidebar user={user} />
{/* Sidebar with role-filtered menus (responsive drawer on mobile) */}
<Sidebar
user={user}
mobileOpen={mobileMenuOpen}
onCloseMobile={() => setMobileMenuOpen(false)}
/>
{/* Main Content Area */}
<div className="flex-1 ml-64 flex flex-col min-h-screen">
<div className="flex-1 lg:ml-64 flex flex-col min-h-screen min-w-0 w-full">
<Navbar
title={title}
subtitle={subtitle}
envMode={user?.envMode || "DEMO"}
onSwitchEnv={handleSwitchEnv}
userRole={user?.role}
onOpenMobileMenu={() => setMobileMenuOpen(true)}
showCompanySelector={["/finance", "/purchases", "/sales", "/inventory", "/"].includes(pathname)}
canDeleteCompany={user?.role === "ADMIN"}
companies={companies}
@@ -257,7 +245,7 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
onAddCompany={handleAddCompany}
onDeleteCompany={handleDeleteCompany}
/>
<main className="flex-1 p-8 max-w-7xl w-full mx-auto">
<main className="flex-1 p-3.5 sm:p-6 lg:p-8 max-w-7xl w-full mx-auto min-w-0">
{!isAllowed ? (
<div className="bg-white rounded-2xl border border-rose-200 p-10 text-center max-w-xl mx-auto mt-12 shadow-sm">
<div className="h-14 w-14 rounded-2xl bg-rose-50 text-rose-600 flex items-center justify-center mx-auto mb-4 border border-rose-100">
@@ -274,11 +262,11 @@ export function AppShell({ children, title, subtitle }: AppShellProps) {
. Peran ini tidak memiliki wewenang untuk membuka modul halaman ini.
</p>
<Link
href="/"
href={getDefaultLandingRoute(user?.role)}
className="inline-flex items-center gap-2 px-5 py-2.5 rounded-lg bg-slate-900 hover:bg-slate-800 text-white text-xs font-semibold shadow-xs transition-colors"
>
<ArrowLeft className="h-4 w-4" />
<span>Kembali ke Dashboard Utama</span>
<span>Kembali ke Halaman Utama</span>
</Link>
</div>
) : (
+22 -16
View File
@@ -6,19 +6,19 @@ interface BadgeProps {
}
const statusLabels: Record<string, string> = {
RECEIVED: "Diterima Gudang",
ORDERED: "Approved / Dipesan",
APPROVED: "Approved Finance",
ON_HOLD: "Hold Finance",
HOLD: "Hold Finance",
RECEIVED: "Diterima",
ORDERED: "Disetujui",
APPROVED: "Disetujui",
ON_HOLD: "Ditahan",
HOLD: "Ditahan",
WAITING_APPROVAL: "Menunggu Approval",
PENDING_FINANCE: "Review Finance",
PENDING_PURCHASING: "Menunggu Purchasing",
PROCESSED_PO: "Diproses ke PO",
REJECTED: "Rejected Finance",
PAID: "PAID (Lunas)",
UNPAID: "UNPAID (Belum Bayar)",
PARTIAL: "Sebagian",
PROCESSED_PO: "Diproses PO",
REJECTED: "Ditolak",
PAID: "Lunas",
UNPAID: "Belum Lunas",
PARTIAL: "Sebagian / DP",
CONFIRMED: "Dikonfirmasi",
SHIPPED: "Terkirim",
COMPLETED: "Selesai",
@@ -29,7 +29,8 @@ const statusLabels: Record<string, string> = {
};
export function StatusBadge({ status, className }: BadgeProps) {
let style = "bg-slate-100 text-slate-700 border-slate-200";
let dotColor = "bg-slate-400";
let style = "bg-slate-50 text-slate-700 border-slate-200/90";
switch (status.toUpperCase()) {
case "PAID":
@@ -38,13 +39,15 @@ export function StatusBadge({ status, className }: BadgeProps) {
case "RECEIVED_AND_PAID":
case "ACTIVE":
case "APPROVED":
style = "bg-emerald-50 text-emerald-700 border-emerald-200";
dotColor = "bg-emerald-500";
style = "bg-slate-50 text-slate-800 border-slate-200/90";
break;
case "CONFIRMED":
case "ORDERED":
case "SHIPPED":
case "PROCESSED_PO":
style = "bg-blue-50 text-blue-700 border-blue-200";
dotColor = "bg-slate-700";
style = "bg-slate-100/80 text-slate-800 border-slate-200";
break;
case "PARTIAL":
case "PENDING":
@@ -54,13 +57,15 @@ export function StatusBadge({ status, className }: BadgeProps) {
case "ON_HOLD":
case "HOLD":
case "DRAFT":
style = "bg-amber-50 text-amber-700 border-amber-200";
dotColor = "bg-amber-500";
style = "bg-amber-50/50 text-amber-900 border-amber-200/70";
break;
case "CANCELLED":
case "LOW_STOCK":
case "UNPAID":
case "REJECTED":
style = "bg-rose-50 text-rose-700 border-rose-200";
dotColor = "bg-rose-500";
style = "bg-rose-50/50 text-rose-800 border-rose-200/70";
break;
}
@@ -69,11 +74,12 @@ export function StatusBadge({ status, className }: BadgeProps) {
return (
<span
className={cn(
"inline-flex items-center px-2 py-0.5 rounded-md text-xs font-semibold border",
"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[11px] font-medium border whitespace-nowrap",
style,
className
)}
>
<span className={cn("h-1.5 w-1.5 rounded-full shrink-0", dotColor)} />
{label}
</span>
);
+75
View File
@@ -0,0 +1,75 @@
"use client";
import React from "react";
interface CurrencyInputProps {
value: number | string;
onChange: (val: number | "") => void;
currency?: string; // "IDR" | "USD"
placeholder?: string;
className?: string;
disabled?: boolean;
required?: boolean;
min?: number;
max?: number;
step?: string | number;
id?: string;
name?: string;
autoFocus?: boolean;
}
export function CurrencyInput({
value,
onChange,
currency = "IDR",
placeholder = "0",
className = "",
disabled = false,
required = false,
min = 0,
max,
step = "any",
id,
name,
autoFocus,
}: CurrencyInputProps) {
const symbol = currency === "USD" ? "$" : "Rp";
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const rawVal = e.target.value;
if (rawVal === "") {
onChange("");
return;
}
const parsed = parseFloat(rawVal);
if (!isNaN(parsed)) {
onChange(parsed);
}
};
return (
<div className="relative flex items-center w-full">
<span className="inline-flex items-center px-2.5 h-9 rounded-l-lg border border-r-0 border-slate-300 bg-slate-100 text-slate-600 font-bold text-xs select-none shrink-0">
{symbol}
</span>
<input
type="number"
id={id}
name={name}
min={min}
max={max}
step={step}
required={required}
disabled={disabled}
autoFocus={autoFocus}
placeholder={placeholder}
value={value === "" || value === undefined ? "" : value}
onChange={handleChange}
onWheel={(e) => (e.target as HTMLElement).blur()}
className={`w-full h-9 px-3 py-1.5 border border-slate-300 rounded-r-lg font-bold text-xs focus:ring-1 focus:ring-blue-500 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none ${
disabled ? "bg-slate-100 text-slate-400 cursor-not-allowed" : "bg-white text-slate-900"
} ${className}`}
/>
</div>
);
}
+302 -358
View File
@@ -2,17 +2,7 @@
import React, { useState } from "react";
import { formatRupiah } from "@/lib/utils";
import {
TrendingUp,
BarChart3,
PieChart,
ArrowDownLeft,
ArrowUpRight,
Wallet,
ShieldCheck,
Boxes,
HelpCircle,
} from "lucide-react";
import { TrendingUp, PieChart, Boxes } from "lucide-react";
interface MonthlyTrendItem {
key: string;
@@ -37,17 +27,30 @@ interface FinancialChartProps {
stockInUnits: number;
stockOutUnits: number;
};
canSeeFinance?: boolean;
canSeeSalesMoney?: boolean;
canSeePurchaseMoney?: boolean;
}
export function FinancialChart({ monthlyTrends = [], metrics }: FinancialChartProps) {
export function FinancialChart({
monthlyTrends = [],
metrics,
canSeeFinance = true,
canSeeSalesMoney = true,
canSeePurchaseMoney = true,
}: FinancialChartProps) {
const [activeTab, setActiveTab] = useState<"finance" | "liquidity" | "stock">("finance");
const [hoveredMonth, setHoveredMonth] = useState<MonthlyTrendItem | null>(null);
// Cari nilai maksimum omzet & belanja untuk normalisasi tinggi grafik
const maxFinancialVal = Math.max(
...monthlyTrends.map((t) => Math.max(t.sales, t.purchases, t.grossProfit)),
metrics.totalRevenue,
metrics.totalPurchases,
...monthlyTrends.map((t) =>
Math.max(
canSeeSalesMoney ? t.sales : 0,
canSeePurchaseMoney ? t.purchases : 0,
canSeeSalesMoney ? t.grossProfit : 0
)
),
canSeeSalesMoney ? metrics.totalRevenue : 0,
canSeePurchaseMoney ? metrics.totalPurchases : 0,
10000000
);
@@ -58,387 +61,164 @@ export function FinancialChart({ monthlyTrends = [], metrics }: FinancialChartPr
50
);
// Total aset lancar: Kas + Piutang + Nilai Stok
const totalPositiveAssets =
Math.max(0, metrics.totalCashBank || 0) +
Math.max(0, metrics.receivables || 0) +
Math.max(0, metrics.inventoryValue || 0);
const totalCurrentAssets =
(metrics.totalCashBank || 0) + (metrics.receivables || 0) + (metrics.inventoryValue || 0);
// Rasio Lancar (Current Ratio): Total Aset Lancar / Hutang Usaha
const currentRatio =
metrics.payables > 0 ? (totalCurrentAssets / metrics.payables).toFixed(2) : "Sangat Sehat (0 Hutang)";
return (
<div className="bg-white rounded-xl border border-slate-200 shadow-xs p-5 mb-8">
{/* Header & View Switcher */}
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-4 border-b border-slate-100">
<div className="bg-white rounded-xl border border-slate-200/80 shadow-[0_1px_2px_rgba(15,23,42,0.03)] p-5 mb-6">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 pb-4 border-b border-slate-100">
<div>
<div className="flex items-center gap-2">
<span className="p-1.5 rounded-lg bg-blue-50 text-blue-600">
<BarChart3 className="h-5 w-5" />
</span>
<h3 className="text-base font-bold text-slate-900">
Grafik Analisis Keuangan & Perputaran Bisnis
</h3>
</div>
<p className="text-xs text-slate-500 mt-1">
Visualisasi tren omzet penjualan, biaya pembelian (HPP), laba kotor, dan likuiditas aset
<h3 className="text-sm font-semibold text-slate-900">
Ringkasan Tren 6 Bulan
</h3>
<p className="text-xs text-slate-500 mt-0.5">
{canSeeFinance
? "Perbandingan penjualan, pembelian, posisi aset, dan volume stok"
: canSeeSalesMoney
? "Tren omzet penjualan, estimasi laba kotor, dan pergerakan stok"
: "Tren nilai pembelian (PO) dan pergerakan volume barang"}
</p>
</div>
{/* Tab Buttons */}
<div className="flex items-center gap-1 p-1 bg-slate-100 rounded-lg text-xs font-semibold self-stretch sm:self-auto overflow-x-auto">
<div className="flex items-center gap-1 p-1 bg-slate-100 rounded-lg text-xs font-medium self-stretch sm:self-auto overflow-x-auto">
<button
type="button"
onClick={() => setActiveTab("finance")}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-all whitespace-nowrap ${
activeTab === "finance"
? "bg-white text-blue-700 shadow-2xs font-bold"
: "text-slate-600 hover:text-slate-900"
? "bg-white text-slate-900 shadow-2xs font-semibold"
: "text-slate-500 hover:text-slate-900"
}`}
>
<TrendingUp className="h-3.5 w-3.5" />
<span>Omzet & Laba</span>
<span>Transaksi</span>
</button>
<button
type="button"
onClick={() => setActiveTab("liquidity")}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-all whitespace-nowrap ${
activeTab === "liquidity"
? "bg-white text-emerald-700 shadow-2xs font-bold"
: "text-slate-600 hover:text-slate-900"
}`}
>
<PieChart className="h-3.5 w-3.5" />
<span>Komposisi Likuiditas</span>
</button>
{canSeeFinance && (
<button
type="button"
onClick={() => setActiveTab("liquidity")}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-all whitespace-nowrap ${
activeTab === "liquidity"
? "bg-white text-slate-900 shadow-2xs font-semibold"
: "text-slate-500 hover:text-slate-900"
}`}
>
<PieChart className="h-3.5 w-3.5" />
<span>Posisi Aset</span>
</button>
)}
<button
type="button"
onClick={() => setActiveTab("stock")}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-all whitespace-nowrap ${
activeTab === "stock"
? "bg-white text-purple-700 shadow-2xs font-bold"
: "text-slate-600 hover:text-slate-900"
? "bg-white text-slate-900 shadow-2xs font-semibold"
: "text-slate-500 hover:text-slate-900"
}`}
>
<Boxes className="h-3.5 w-3.5" />
<span>Volume Keluar-Masuk</span>
<span>Volume Stok</span>
</button>
</div>
</div>
{/* ========================================================================= */}
{/* 1. VIEW TAB: OMZET, PEMBELIAN & LABA KOTOR BULANAN */}
{/* ========================================================================= */}
{activeTab === "finance" && (
<div className="pt-5">
{/* Legend and Summary */}
<div className="flex flex-wrap items-center justify-between gap-4 mb-6">
<div className="flex flex-wrap items-center gap-4 text-xs font-medium">
<span className="flex items-center gap-1.5">
<span className="h-3 w-3 rounded-xs bg-blue-600" />
<span className="text-slate-700 font-semibold">Penjualan (Sales)</span>
</span>
<span className="flex items-center gap-1.5">
<span className="h-3 w-3 rounded-xs bg-rose-500" />
<span className="text-slate-700 font-semibold">Pembelian & HPP</span>
</span>
<span className="flex items-center gap-1.5">
<span className="h-3 w-3 rounded-xs bg-emerald-500" />
<span className="text-slate-700 font-semibold">Laba Kotor (Gross Margin)</span>
</span>
</div>
<div className="text-xs text-slate-500 bg-slate-50 border border-slate-200/60 rounded-md px-2.5 py-1">
Arahkan kursor pada batang untuk melihat nominal detail
</div>
</div>
{/* Bar Chart Area */}
<div className="relative h-64 w-full flex items-end gap-3 sm:gap-6 pt-6 pb-2 px-2 border-b border-slate-200">
{monthlyTrends.length === 0 ? (
<div className="w-full h-full flex items-center justify-center text-xs text-slate-400">
Belum ada data transaksi bulanan yang terekam.
</div>
) : (
monthlyTrends.map((item) => {
const salesHeight = Math.max(4, Math.round((item.sales / maxFinancialVal) * 100));
const purchasesHeight = Math.max(4, Math.round((item.purchases / maxFinancialVal) * 100));
const profitHeight = Math.max(
item.grossProfit > 0 ? 4 : 0,
Math.round((Math.max(0, item.grossProfit) / maxFinancialVal) * 100)
);
return (
<div
key={item.key}
onMouseEnter={() => setHoveredMonth(item)}
onMouseLeave={() => setHoveredMonth(null)}
className="flex-1 flex flex-col items-center justify-end h-full group relative cursor-pointer"
>
{/* Hover Tooltip Box */}
<div className="opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none absolute -top-16 z-30 bg-slate-900 text-white rounded-lg p-2.5 shadow-xl text-[11px] whitespace-nowrap min-w-[170px] -translate-x-1/2 left-1/2">
<div className="font-bold border-b border-slate-700 pb-1 mb-1 text-slate-200">
{item.label}
</div>
<div className="flex justify-between gap-2 text-blue-300">
<span>Penjualan:</span>
<span className="font-bold">{formatRupiah(item.sales)}</span>
</div>
<div className="flex justify-between gap-2 text-rose-300">
<span>Pembelian/HPP:</span>
<span className="font-bold">{formatRupiah(item.purchases)}</span>
</div>
<div className="flex justify-between gap-2 text-emerald-400 font-semibold pt-0.5 border-t border-slate-800">
<span>Laba Kotor:</span>
<span>{formatRupiah(item.grossProfit)}</span>
</div>
</div>
{/* Bars Container */}
<div className="w-full flex items-end justify-center gap-1 sm:gap-2 h-full">
{/* Bar 1: Sales */}
<div
style={{ height: `${salesHeight}%` }}
className="w-3 sm:w-6 bg-gradient-to-t from-blue-700 to-blue-500 rounded-t-xs hover:brightness-110 transition-all shadow-2xs"
/>
{/* Bar 2: Purchases */}
<div
style={{ height: `${purchasesHeight}%` }}
className="w-3 sm:w-6 bg-gradient-to-t from-rose-600 to-rose-400 rounded-t-xs hover:brightness-110 transition-all shadow-2xs"
/>
{/* Bar 3: Gross Profit */}
<div
style={{ height: `${profitHeight}%` }}
className="w-3 sm:w-6 bg-gradient-to-t from-emerald-600 to-emerald-400 rounded-t-xs hover:brightness-110 transition-all shadow-2xs"
/>
</div>
{/* Month Label */}
<span className="text-[11px] font-semibold text-slate-600 group-hover:text-blue-600 mt-2 truncate max-w-full">
{item.label}
</span>
</div>
);
})
)}
</div>
{/* Quick Stats Footer */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 pt-4">
<div className="p-3 bg-blue-50/60 border border-blue-100 rounded-lg">
<span className="text-[10px] font-bold uppercase text-blue-700">Total Omzet Periode Ini</span>
<p className="text-base font-bold text-blue-900 mt-0.5">
{formatRupiah(metrics.totalRevenue)}
</p>
</div>
<div className="p-3 bg-rose-50/60 border border-rose-100 rounded-lg">
<span className="text-[10px] font-bold uppercase text-rose-700">Total Belanja Pengadaan (PO)</span>
<p className="text-base font-bold text-rose-900 mt-0.5">
{formatRupiah(metrics.totalPurchases)}
</p>
</div>
<div className="p-3 bg-emerald-50/60 border border-emerald-100 rounded-lg">
<span className="text-[10px] font-bold uppercase text-emerald-700">Estimasi Margin Keuntungan Bersih</span>
<p className="text-base font-bold text-emerald-900 mt-0.5">
+{formatRupiah(Math.max(0, metrics.totalRevenue - metrics.totalPurchases))}
</p>
</div>
</div>
</div>
)}
{/* ========================================================================= */}
{/* 2. VIEW TAB: KOMPOSISI LIKUIDITAS ASET & NERACA */}
{/* ========================================================================= */}
{activeTab === "liquidity" && (
<div className="pt-5 space-y-6">
<div className="flex flex-col md:flex-row items-center justify-between gap-6 p-4 rounded-xl bg-slate-50 border border-slate-200">
<div>
<span className="text-xs font-bold uppercase tracking-wider text-slate-500">
Struktur Posisi Keuangan Lancar
</span>
<h4 className="text-2xl font-bold text-slate-900 mt-1">
{formatRupiah(totalCurrentAssets)}
</h4>
<p className="text-xs text-slate-600 mt-0.5">
Total Aset Likuid (Kas + Piutang Dagang + Persediaan Gudang)
</p>
</div>
<div className="flex items-center gap-3 bg-white px-4 py-2.5 rounded-lg border border-slate-200 shadow-2xs">
<ShieldCheck className="h-6 w-6 text-emerald-600" />
<div>
<span className="text-[10px] font-bold uppercase tracking-wider text-slate-400">
Rasio Likuiditas Lancar
<div className="flex flex-wrap items-center justify-between gap-3 mb-5">
<div className="flex flex-wrap items-center gap-4 text-xs">
{canSeeSalesMoney && (
<span className="flex items-center gap-1.5 text-slate-800 dark:text-white font-medium">
<span className="h-2.5 w-2.5 rounded-xs bg-slate-900 chart-bar-primary" />
<span>Penjualan</span>
</span>
)}
{canSeePurchaseMoney && (
<span className="flex items-center gap-1.5 text-slate-800 dark:text-white font-medium">
<span className="h-2.5 w-2.5 rounded-xs bg-slate-400 chart-bar-secondary" />
<span>Pembelian (PO)</span>
</span>
)}
{canSeeSalesMoney && (
<span className="flex items-center gap-1.5 text-slate-800 dark:text-white font-medium">
<span className="h-2.5 w-2.5 rounded-xs bg-emerald-600 chart-bar-profit" />
<span>Laba Kotor</span>
</span>
<p className="text-sm font-bold text-emerald-700">
{typeof currentRatio === "number" ? `${currentRatio}x` : currentRatio}
</p>
</div>
</div>
</div>
{/* Visual Multi-Segment Bar */}
<div>
<div className="flex items-center justify-between text-xs text-slate-500 mb-2 font-medium">
<span>Distribusi Bobot Aset Lancar</span>
<span>100% Total Nilai Aset</span>
</div>
<div className="h-6 w-full rounded-lg overflow-hidden flex bg-slate-200 shadow-inner">
{totalCurrentAssets > 0 ? (
<>
<div
style={{
width: `${Math.round(((metrics.totalCashBank || 0) / totalCurrentAssets) * 100)}%`,
}}
title={`Kas & Bank: ${formatRupiah(metrics.totalCashBank)}`}
className="bg-emerald-500 hover:brightness-110 transition-all flex items-center justify-center text-[10px] text-white font-bold truncate px-1"
>
Kas {Math.round(((metrics.totalCashBank || 0) / totalCurrentAssets) * 100)}%
</div>
<div
style={{
width: `${Math.round(((metrics.receivables || 0) / totalCurrentAssets) * 100)}%`,
}}
title={`Piutang: ${formatRupiah(metrics.receivables)}`}
className="bg-blue-500 hover:brightness-110 transition-all flex items-center justify-center text-[10px] text-white font-bold truncate px-1"
>
Piutang {Math.round(((metrics.receivables || 0) / totalCurrentAssets) * 100)}%
</div>
<div
style={{
width: `${Math.round(((metrics.inventoryValue || 0) / totalCurrentAssets) * 100)}%`,
}}
title={`Persediaan: ${formatRupiah(metrics.inventoryValue)}`}
className="bg-purple-500 hover:brightness-110 transition-all flex items-center justify-center text-[10px] text-white font-bold truncate px-1"
>
Stok {Math.round(((metrics.inventoryValue || 0) / totalCurrentAssets) * 100)}%
</div>
</>
) : (
<div className="w-full flex items-center justify-center text-xs text-slate-400">
Belum ada nilai aset tercatat
</div>
)}
</div>
<span className="text-[11px] text-slate-400">
Arahkan kursor pada batang untuk detail
</span>
</div>
{/* Asset Breakdown Cards */}
<div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
<div className="p-3.5 bg-emerald-50/70 border border-emerald-100 rounded-xl">
<div className="flex items-center gap-2 mb-1">
<span className="h-2.5 w-2.5 rounded-full bg-emerald-500" />
<span className="text-xs font-bold text-emerald-900">Kas & Saldo Bank</span>
</div>
<p className="text-lg font-bold text-emerald-800">
{formatRupiah(metrics.totalCashBank)}
</p>
<span className="text-[11px] text-emerald-700">Dana likuid siap pakai</span>
</div>
<div className="p-3.5 bg-blue-50/70 border border-blue-100 rounded-xl">
<div className="flex items-center gap-2 mb-1">
<span className="h-2.5 w-2.5 rounded-full bg-blue-500" />
<span className="text-xs font-bold text-blue-900">Piutang Penjualan</span>
</div>
<p className="text-lg font-bold text-blue-800">
{formatRupiah(metrics.receivables)}
</p>
<span className="text-[11px] text-blue-700">Tagihan invoice aktif</span>
</div>
<div className="p-3.5 bg-purple-50/70 border border-purple-100 rounded-xl">
<div className="flex items-center gap-2 mb-1">
<span className="h-2.5 w-2.5 rounded-full bg-purple-500" />
<span className="text-xs font-bold text-purple-900">Nilai Stok Gudang</span>
</div>
<p className="text-lg font-bold text-purple-800">
{formatRupiah(metrics.inventoryValue)}
</p>
<span className="text-[11px] text-purple-700">Aset inventaris fisik</span>
</div>
<div className="p-3.5 bg-amber-50/70 border border-amber-200 rounded-xl">
<div className="flex items-center gap-2 mb-1">
<span className="h-2.5 w-2.5 rounded-full bg-amber-500" />
<span className="text-xs font-bold text-amber-900">Hutang Vendor (PO)</span>
</div>
<p className="text-lg font-bold text-amber-800">
{formatRupiah(metrics.payables)}
</p>
<span className="text-[11px] text-amber-700">Kewajiban pembayaran</span>
</div>
</div>
</div>
)}
{/* ========================================================================= */}
{/* 3. VIEW TAB: VOLUME KELUAR MASUK FISIK BARANG GUDANG */}
{/* ========================================================================= */}
{activeTab === "stock" && (
<div className="pt-5">
<div className="flex flex-wrap items-center justify-between gap-4 mb-6">
<div className="flex items-center gap-4 text-xs font-medium">
<span className="flex items-center gap-1.5">
<span className="h-3 w-3 rounded-xs bg-emerald-500" />
<span className="text-slate-700 font-semibold">Barang Masuk (Inbound PO)</span>
</span>
<span className="flex items-center gap-1.5">
<span className="h-3 w-3 rounded-xs bg-amber-500" />
<span className="text-slate-700 font-semibold">Barang Keluar (Outbound SO)</span>
</span>
</div>
<div className="text-xs text-slate-500">
Satuan kuantitas dalam unit fisik gudang
</div>
</div>
{/* Bar Chart Area */}
<div className="relative h-64 w-full flex items-end gap-3 sm:gap-6 pt-6 pb-2 px-2 border-b border-slate-200">
<div className="relative h-52 w-full flex items-end gap-3 sm:gap-6 pt-6 pb-2 px-2 border-b border-slate-200/80">
{monthlyTrends.length === 0 ? (
<div className="w-full h-full flex items-center justify-center text-xs text-slate-400">
Belum ada data keluar masuk barang.
Belum ada data transaksi bulanan.
</div>
) : (
monthlyTrends.map((item) => {
const inHeight = Math.max(4, Math.round((item.stockInUnits / maxStockUnitsVal) * 100));
const outHeight = Math.max(4, Math.round((item.stockOutUnits / maxStockUnitsVal) * 100));
const salesHeight = item.sales > 0 ? Math.max(4, Math.round((item.sales / maxFinancialVal) * 100)) : 2;
const purchasesHeight = item.purchases > 0 ? Math.max(4, Math.round((item.purchases / maxFinancialVal) * 100)) : 2;
const profitHeight = item.grossProfit > 0 ? Math.max(4, Math.round((item.grossProfit / maxFinancialVal) * 100)) : 2;
return (
<div
key={item.key}
className="flex-1 flex flex-col items-center justify-end h-full group relative cursor-pointer"
>
{/* Hover Tooltip Box */}
<div className="opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none absolute -top-14 z-30 bg-slate-900 text-white rounded-lg p-2 shadow-xl text-[11px] whitespace-nowrap min-w-[140px] -translate-x-1/2 left-1/2">
<div className="font-bold border-b border-slate-700 pb-1 mb-1 text-slate-200">
<div className="opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none absolute -top-16 z-30 bg-slate-900 text-white rounded-lg p-2.5 shadow-lg text-[11px] whitespace-nowrap min-w-[165px] -translate-x-1/2 left-1/2">
<div className="font-semibold border-b border-slate-700 pb-1 mb-1 text-slate-200">
{item.label}
</div>
<div className="flex justify-between gap-2 text-emerald-300">
<span>Masuk (PO):</span>
<span className="font-bold">+{item.stockInUnits} Unit</span>
</div>
<div className="flex justify-between gap-2 text-amber-300">
<span>Keluar (SO):</span>
<span className="font-bold">-{item.stockOutUnits} Unit</span>
</div>
{canSeeSalesMoney && (
<div className="flex justify-between gap-3 text-slate-200">
<span>Penjualan</span>
<span className="font-semibold tabular-nums">{formatRupiah(item.sales)}</span>
</div>
)}
{canSeePurchaseMoney && (
<div className="flex justify-between gap-3 text-slate-300">
<span>Pembelian</span>
<span className="font-semibold tabular-nums">{formatRupiah(item.purchases)}</span>
</div>
)}
{canSeeSalesMoney && (
<div className="flex justify-between gap-3 text-emerald-400 pt-0.5 border-t border-slate-800 mt-0.5">
<span>Laba Kotor</span>
<span className="font-semibold tabular-nums">{formatRupiah(item.grossProfit)}</span>
</div>
)}
</div>
{/* Bars Container */}
<div className="w-full flex items-end justify-center gap-1 sm:gap-2 h-full">
<div
style={{ height: `${inHeight}%` }}
className="w-4 sm:w-8 bg-gradient-to-t from-emerald-600 to-emerald-400 rounded-t-xs hover:brightness-110 transition-all shadow-2xs"
/>
<div
style={{ height: `${outHeight}%` }}
className="w-4 sm:w-8 bg-gradient-to-t from-amber-600 to-amber-400 rounded-t-xs hover:brightness-110 transition-all shadow-2xs"
/>
<div className="w-full flex items-end justify-center gap-1 sm:gap-1.5 h-full">
{canSeeSalesMoney && (
<div
style={{ height: `${salesHeight}%` }}
className="w-3 sm:w-5 bg-slate-900 chart-bar-primary rounded-t-xs transition-all"
/>
)}
{canSeePurchaseMoney && (
<div
style={{ height: `${purchasesHeight}%` }}
className="w-3 sm:w-5 bg-slate-400 chart-bar-secondary rounded-t-xs transition-all"
/>
)}
{canSeeSalesMoney && (
<div
style={{ height: `${profitHeight}%` }}
className="w-3 sm:w-5 bg-emerald-600 chart-bar-profit rounded-t-xs transition-all"
/>
)}
</div>
<span className="text-[11px] font-semibold text-slate-600 group-hover:text-emerald-700 mt-2 truncate max-w-full">
<span className="text-[11px] font-medium text-slate-500 group-hover:text-slate-900 mt-2 truncate max-w-full">
{item.label}
</span>
</div>
@@ -447,25 +227,189 @@ export function FinancialChart({ monthlyTrends = [], metrics }: FinancialChartPr
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-4">
<div className="p-3 bg-emerald-50/70 border border-emerald-100 rounded-lg flex items-center justify-between">
<div>
<span className="text-[10px] font-bold uppercase text-emerald-700">Total Unit Diterima (Inbound)</span>
<p className="text-xl font-bold text-emerald-900 mt-0.5">
+{metrics.stockInUnits.toLocaleString("id-ID")} Unit
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 pt-4">
{canSeeSalesMoney && (
<div className="p-3 bg-slate-50/80 border border-slate-200/70 rounded-lg">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-500">
Total Penjualan
</span>
<p className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums">
{formatRupiah(metrics.totalRevenue)}
</p>
</div>
<ArrowDownLeft className="h-6 w-6 text-emerald-600" />
</div>
)}
{canSeePurchaseMoney && (
<div className="p-3 bg-slate-50/80 border border-slate-200/70 rounded-lg">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-500">
Total Pembelian (PO)
</span>
<p className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums">
{formatRupiah(metrics.totalPurchases)}
</p>
</div>
)}
{canSeeSalesMoney && (
<div className="p-3 bg-slate-50/80 border border-slate-200/70 rounded-lg">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-500">
Selisih Arus Transaksi
</span>
<p className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums">
{formatRupiah(metrics.totalRevenue - metrics.totalPurchases)}
</p>
</div>
)}
</div>
</div>
)}
<div className="p-3 bg-amber-50/70 border border-amber-100 rounded-lg flex items-center justify-between">
<div>
<span className="text-[10px] font-bold uppercase text-amber-700">Total Unit Terkirim (Outbound)</span>
<p className="text-xl font-bold text-amber-900 mt-0.5">
-{metrics.stockOutUnits.toLocaleString("id-ID")} Unit
</p>
{activeTab === "liquidity" && canSeeFinance && (
<div className="pt-5 space-y-4">
<div className="p-4 rounded-lg bg-slate-50/80 border border-slate-200/70 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div>
<span className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">
Total Aset Lancar Bersih
</span>
<h4 className="text-xl font-bold text-slate-900 mt-0.5 tabular-nums">
{formatRupiah(totalCurrentAssets)}
</h4>
<p className="text-xs text-slate-500">Kas & Bank + Piutang + Nilai Persediaan</p>
</div>
<div className="text-left sm:text-right">
<span className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">
Hutang Vendor (PO)
</span>
<p className="text-base font-bold text-slate-900 mt-0.5 tabular-nums">
{formatRupiah(metrics.payables)}
</p>
</div>
</div>
<div className="h-3 w-full rounded-full overflow-hidden flex bg-slate-100">
{totalPositiveAssets > 0 ? (
<>
<div
style={{ width: `${Math.round((Math.max(0, metrics.totalCashBank) / totalPositiveAssets) * 100)}%` }}
className="bg-slate-900"
title={`Kas & Bank: ${formatRupiah(metrics.totalCashBank)}`}
/>
<div
style={{ width: `${Math.round((Math.max(0, metrics.receivables) / totalPositiveAssets) * 100)}%` }}
className="bg-slate-500"
title={`Piutang: ${formatRupiah(metrics.receivables)}`}
/>
<div
style={{ width: `${Math.round((Math.max(0, metrics.inventoryValue) / totalPositiveAssets) * 100)}%` }}
className="bg-slate-300"
title={`Persediaan: ${formatRupiah(metrics.inventoryValue)}`}
/>
</>
) : null}
</div>
<div className="grid grid-cols-1 sm:grid-cols-4 gap-3">
<div className="p-3.5 bg-white border border-slate-200/80 rounded-lg">
<span className="text-[11px] font-medium text-slate-500">Kas & Bank</span>
<p className={`text-sm font-bold mt-1 tabular-nums ${metrics.totalCashBank < 0 ? "text-rose-700" : "text-slate-900"}`}>
{formatRupiah(metrics.totalCashBank)}
</p>
</div>
<div className="p-3.5 bg-white border border-slate-200/80 rounded-lg">
<span className="text-[11px] font-medium text-slate-500">Piutang Customer</span>
<p className="text-sm font-bold text-slate-900 mt-1 tabular-nums">
{formatRupiah(metrics.receivables)}
</p>
</div>
<div className="p-3.5 bg-white border border-slate-200/80 rounded-lg">
<span className="text-[11px] font-medium text-slate-500">Nilai Stok Gudang</span>
<p className="text-sm font-bold text-slate-900 mt-1 tabular-nums">
{formatRupiah(metrics.inventoryValue)}
</p>
</div>
<div className="p-3.5 bg-white border border-slate-200/80 rounded-lg">
<span className="text-[11px] font-medium text-slate-500">Hutang Vendor</span>
<p className="text-sm font-bold text-slate-900 mt-1 tabular-nums">
{formatRupiah(metrics.payables)}
</p>
</div>
</div>
</div>
)}
{activeTab === "stock" && (
<div className="pt-5">
<div className="flex flex-wrap items-center justify-between gap-3 mb-5">
<div className="flex items-center gap-4 text-xs">
<span className="flex items-center gap-1.5 text-slate-600">
<span className="h-2.5 w-2.5 rounded-xs bg-slate-900" />
<span>Barang Masuk</span>
</span>
<span className="flex items-center gap-1.5 text-slate-600">
<span className="h-2.5 w-2.5 rounded-xs bg-slate-300" />
<span>Barang Keluar</span>
</span>
</div>
<span className="text-[11px] text-slate-400">Satuan unit fisik</span>
</div>
<div className="relative h-52 w-full flex items-end gap-3 sm:gap-6 pt-6 pb-2 px-2 border-b border-slate-200/80">
{monthlyTrends.length === 0 ? (
<div className="w-full h-full flex items-center justify-center text-xs text-slate-400">
Belum ada mutasi stok.
</div>
<ArrowUpRight className="h-6 w-6 text-amber-600" />
) : (
monthlyTrends.map((item) => {
const inHeight = item.stockInUnits > 0 ? Math.max(4, Math.round((item.stockInUnits / maxStockUnitsVal) * 100)) : 2;
const outHeight = item.stockOutUnits > 0 ? Math.max(4, Math.round((item.stockOutUnits / maxStockUnitsVal) * 100)) : 2;
return (
<div
key={item.key}
className="flex-1 flex flex-col items-center justify-end h-full group relative cursor-pointer"
>
<div className="opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none absolute -top-14 z-30 bg-slate-900 text-white rounded-lg p-2 shadow-lg text-[11px] whitespace-nowrap min-w-[130px] -translate-x-1/2 left-1/2">
<div className="font-semibold border-b border-slate-700 pb-1 mb-1 text-slate-200">
{item.label}
</div>
<div className="flex justify-between gap-2 text-slate-200">
<span>Masuk</span>
<span className="font-semibold">+{item.stockInUnits}</span>
</div>
<div className="flex justify-between gap-2 text-slate-300">
<span>Keluar</span>
<span className="font-semibold">-{item.stockOutUnits}</span>
</div>
</div>
<div className="w-full flex items-end justify-center gap-1.5 h-full">
<div style={{ height: `${inHeight}%` }} className="w-4 sm:w-6 bg-slate-900 chart-bar-primary rounded-t-xs" />
<div style={{ height: `${outHeight}%` }} className="w-4 sm:w-6 bg-slate-400 chart-bar-secondary rounded-t-xs" />
</div>
<span className="text-[11px] font-medium text-slate-500 mt-2 truncate max-w-full">
{item.label}
</span>
</div>
);
})
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-4">
<div className="p-3 bg-slate-50/80 border border-slate-200/70 rounded-lg">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-500">
Total Barang Masuk
</span>
<p className="text-base font-bold text-slate-900 mt-0.5 tabular-nums">
+{metrics.stockInUnits.toLocaleString("id-ID")} Unit
</p>
</div>
<div className="p-3 bg-slate-50/80 border border-slate-200/70 rounded-lg">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-500">
Total Barang Keluar
</span>
<p className="text-base font-bold text-slate-900 mt-0.5 tabular-nums">
-{metrics.stockOutUnits.toLocaleString("id-ID")} Unit
</p>
</div>
</div>
</div>
+21 -7
View File
@@ -1,6 +1,6 @@
"use client";
import { ReactNode } from "react";
import { ReactNode, useEffect } from "react";
import { X } from "lucide-react";
interface ModalProps {
@@ -20,25 +20,39 @@ export function Modal({
zIndex = "z-50",
maxWidth = "max-w-xl",
}: ModalProps) {
useEffect(() => {
if (!isOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [isOpen, onClose]);
if (!isOpen) return null;
return (
<div
className={`fixed inset-0 ${zIndex} overflow-y-auto bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4`}
className={`fixed inset-0 ${zIndex} overflow-y-auto bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-2 sm:p-4`}
onClick={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div
className={`bg-white rounded-xl shadow-2xl border border-slate-200 w-full ${maxWidth} overflow-hidden animate-in fade-in zoom-in-95 duration-150`}
className={`bg-white rounded-xl shadow-2xl border border-slate-200 w-full ${maxWidth} overflow-hidden animate-in fade-in zoom-in-95 duration-150 my-auto`}
>
<div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between bg-slate-50">
<h3 className="font-bold text-slate-800 text-base">{title}</h3>
<div className="px-4 sm:px-6 py-3 sm:py-4 border-b border-slate-200 flex items-center justify-between gap-2 bg-slate-50">
<h3 className="font-bold text-slate-800 text-sm sm:text-base truncate">{title}</h3>
<button
type="button"
onClick={onClose}
className="text-slate-400 hover:text-slate-600 p-1 rounded-md hover:bg-slate-200 transition-colors"
aria-label="Tutup"
className="text-slate-400 hover:text-slate-600 p-1.5 rounded-md hover:bg-slate-200 transition-colors shrink-0"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="p-6 max-h-[80vh] overflow-y-auto">{children}</div>
<div className="p-4 sm:p-6 max-h-[85vh] overflow-y-auto overflow-x-hidden">{children}</div>
</div>
</div>
);
+98 -97
View File
@@ -1,20 +1,19 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import {
Bell,
Rocket,
FlaskConical,
ArrowLeftRight,
Building2,
FileText,
Menu,
} from "lucide-react";
import { ThemeToggle } from "./ThemeToggle";
export function Navbar({
title,
subtitle,
envMode = "DEMO",
onSwitchEnv,
userRole,
onOpenMobileMenu,
showCompanySelector = false,
companies = ["PT EnterpriseCore Utama"],
selectedCompany = "ALL",
@@ -22,8 +21,8 @@ export function Navbar({
}: {
title: string;
subtitle?: string;
envMode?: "DEMO" | "LIVE";
onSwitchEnv?: (targetMode: "DEMO" | "LIVE") => void;
userRole?: string;
onOpenMobileMenu?: () => void;
showCompanySelector?: boolean;
canDeleteCompany?: boolean;
companies?: string[];
@@ -32,102 +31,104 @@ export function Navbar({
onAddCompany?: (newCompany: string) => Promise<void>;
onDeleteCompany?: (company: string) => Promise<void>;
}) {
const [switching, setSwitching] = useState(false);
const handleSwitchToLive = async () => {
if (!onSwitchEnv || switching || envMode === "LIVE") return;
const confirmSwitch = window.confirm(
"Apakah Anda yakin ingin beralih ke Mode Production (Live)? Akun Demo dan Production dipisahkan untuk keamanan data, sehingga Anda akan diarahkan untuk login ulang dengan akun Production Anda."
);
if (!confirmSwitch) return;
setSwitching(true);
try {
await onSwitchEnv("LIVE");
} finally {
setSwitching(false);
}
};
const notifHref = userRole === "ADMIN" || userRole === "MANAGER" ? "/settings" : "/users";
return (
<header className="h-16 bg-white border-b border-slate-200 px-8 flex items-center justify-between sticky top-0 z-30 shadow-xs">
<div>
<h1 className="text-xl font-bold text-slate-800">{title}</h1>
{subtitle && <p className="text-xs text-slate-500 mt-0.5">{subtitle}</p>}
</div>
<div className="flex items-center gap-2.5">
{/* Di bagian atas hanya Dropdown Nama PT saja (tanpa tombol Add / Edit / Hapus) */}
{showCompanySelector && (
<div className="flex items-center gap-2 bg-slate-100/90 border border-slate-200 rounded-lg px-3 py-1.5">
<Building2 className="h-3.5 w-3.5 text-blue-600 shrink-0" />
<span className="text-[11px] font-semibold text-slate-500 hidden sm:inline">
PT Aktif:
</span>
<select
value={selectedCompany}
onChange={(e) => onSelectCompany && onSelectCompany(e.target.value)}
className="bg-transparent text-xs font-bold text-slate-800 focus:outline-none cursor-pointer pr-1"
title="Pilih Entitas Perusahaan (PT)"
<header className="bg-white/95 backdrop-blur-xs border-b border-slate-200/80 sticky top-0 z-30">
<div className="min-h-15 px-4 sm:px-6 lg:px-8 py-2.5 flex items-center justify-between gap-3">
<div className="flex items-center gap-3 min-w-0 flex-1">
{onOpenMobileMenu && (
<button
type="button"
onClick={onOpenMobileMenu}
aria-label="Buka Menu"
className="lg:hidden p-2 -ml-1 rounded-lg text-slate-600 hover:text-slate-900 hover:bg-slate-100 border border-slate-200 shrink-0 transition-colors"
>
<option value="ALL">Semua PT ({companies.length})</option>
{companies.map((pt) => (
<option key={pt} value={pt}>
{pt}
</option>
))}
</select>
</div>
)}
{/* Status Lingkungan: Saat sudah LIVE tidak bisa klik ke DEMO, tapi dari DEMO bisa ke LIVE */}
{envMode === "LIVE" ? (
<div className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-emerald-50 text-emerald-800 border border-emerald-200 text-xs font-bold select-none">
<Rocket className="h-3.5 w-3.5 text-emerald-600" />
<span>PRODUCTION</span>
</div>
) : (
<>
<div className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-amber-50 text-amber-800 border border-amber-300 text-xs font-bold">
<FlaskConical className="h-3.5 w-3.5 text-amber-600" />
<span>MODE DEMO</span>
</div>
{onSwitchEnv && (
<button
type="button"
disabled={switching}
onClick={handleSwitchToLive}
title="Beralih dari Mode Demo ke Lingkungan Production (Live)"
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-emerald-600 hover:bg-emerald-700 text-white border border-emerald-600 shadow-2xs transition-colors disabled:opacity-50"
>
<ArrowLeftRight className="h-3.5 w-3.5" />
<span>{switching ? "Mengalihkan..." : "Buka Web Production"}</span>
</button>
<Menu className="h-4 w-4" />
</button>
)}
<div className="min-w-0">
<h1 className="text-base sm:text-lg font-semibold text-slate-900 tracking-tight truncate">
{title}
</h1>
{subtitle && (
<p className="text-xs text-slate-500 mt-0.5 truncate hidden sm:block">
{subtitle}
</p>
)}
</>
)}
</div>
</div>
{/* Tombol Unduh Buku Panduan PDF */}
<a
href="/Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf"
target="_blank"
download="Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf"
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-300 shadow-2xs transition-colors"
title="Unduh Panduan Alur Penggunaan Aplikasi ERP dalam format PDF"
>
<FileText className="h-3.5 w-3.5 text-blue-600" />
<span>Panduan PDF</span>
</a>
<div className="flex items-center gap-2 shrink-0">
{/* Pilihan Entitas PT */}
{showCompanySelector && (
<div className="hidden md:flex items-center gap-2 bg-slate-50 border border-slate-200 rounded-lg px-2.5 py-1.5">
<Building2 className="h-3.5 w-3.5 text-slate-400 shrink-0" />
<select
value={selectedCompany}
onChange={(e) => onSelectCompany && onSelectCompany(e.target.value)}
className="bg-transparent text-xs font-medium text-slate-800 focus:outline-none cursor-pointer pr-1 max-w-[190px] truncate"
title="Filter Entitas Perusahaan (PT)"
>
<option value="ALL">Semua Perusahaan ({companies.length})</option>
{companies.map((pt) => (
<option key={pt} value={pt}>
{pt}
</option>
))}
</select>
</div>
)}
{/* Notifications */}
<button
title="Notifikasi Sistem"
className="relative p-2 rounded-lg text-slate-500 hover:text-slate-700 hover:bg-slate-100 transition-colors"
>
<Bell className="h-5 w-5" />
<span className="absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-blue-600 ring-2 ring-white" />
</button>
{/* Panduan PDF (View di tab baru) */}
<a
href="/Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf?v=4"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium bg-white hover:bg-slate-50 text-slate-800 dark:text-white border border-slate-200 transition-colors"
title="Lihat Panduan ERP (PDF)"
>
<FileText className="h-3.5 w-3.5 shrink-0" />
<span className="hidden sm:inline">Panduan</span>
</a>
{/* Tombol Mode Gelap / Terang */}
<ThemeToggle />
{/* Notifikasi */}
<Link
href={notifHref}
title={
userRole === "ADMIN" || userRole === "MANAGER"
? "Pengaturan & Log Notifikasi"
: "Profil & Preferensi Akun"
}
className="relative p-2 rounded-lg text-slate-500 hover:text-slate-900 hover:bg-slate-100 transition-colors"
>
<Bell className="h-4 w-4" />
</Link>
</div>
</div>
{/* Baris Filter PT untuk Mobile */}
{showCompanySelector && (
<div className="md:hidden px-4 pb-2.5 pt-1 border-t border-slate-100 bg-slate-50/60 flex items-center gap-2">
<Building2 className="h-3.5 w-3.5 text-slate-400 shrink-0" />
<select
value={selectedCompany}
onChange={(e) => onSelectCompany && onSelectCompany(e.target.value)}
className="flex-1 min-w-0 bg-white border border-slate-200 rounded-md px-2.5 py-1 text-xs font-medium text-slate-800 focus:outline-none focus:ring-1 focus:ring-slate-400"
title="Filter Entitas Perusahaan (PT)"
>
<option value="ALL">Semua Perusahaan ({companies.length})</option>
{companies.map((pt) => (
<option key={pt} value={pt}>
{pt}
</option>
))}
</select>
</div>
)}
</header>
);
}
+12 -10
View File
@@ -43,14 +43,14 @@ export function Pagination({
};
return (
<div className="px-5 py-3.5 bg-slate-50 border-t border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-slate-600">
<div className="flex items-center gap-3">
<div className="px-3.5 sm:px-5 py-3 bg-slate-50 border-t border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-slate-600">
<div className="flex flex-wrap items-center justify-center sm:justify-start gap-2 sm:gap-3">
<span>
Menampilkan <strong className="text-slate-800">{startItem}</strong> -{" "}
<strong className="text-slate-800">{endItem}</strong> dari{" "}
<strong className="text-slate-800">{totalItems}</strong> data
</span>
<div className="flex items-center gap-1.5 pl-3 border-l border-slate-200">
<div className="flex items-center gap-1.5 pl-2 sm:pl-3 border-l border-slate-200">
<span className="text-[11px] text-slate-500">Tampilkan:</span>
<select
value={pageSize}
@@ -69,22 +69,23 @@ export function Pagination({
</div>
</div>
<div className="flex items-center gap-1">
<div className="flex flex-wrap items-center justify-center gap-1">
<button
type="button"
onClick={() => onPageChange(Math.max(1, safeCurrentPage - 1))}
disabled={safeCurrentPage <= 1}
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-slate-100 disabled:opacity-40 disabled:hover:bg-white text-xs font-medium transition-colors"
aria-label="Halaman Sebelumnya"
className="inline-flex items-center gap-1 px-2 sm:px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-slate-100 disabled:opacity-40 disabled:hover:bg-white text-xs font-medium transition-colors"
>
<ChevronLeft className="h-3.5 w-3.5" />
<span>Sebelumnya</span>
<span className="hidden sm:inline">Sebelumnya</span>
</button>
<div className="flex items-center gap-1 px-1">
<div className="flex items-center gap-1 px-0.5 sm:px-1">
{getPageNumbers().map((p, idx) => {
if (p === "...") {
return (
<span key={`ellipsis-${idx}`} className="px-2 text-slate-400 font-bold">
<span key={`ellipsis-${idx}`} className="px-1.5 text-slate-400 font-bold">
...
</span>
);
@@ -112,9 +113,10 @@ export function Pagination({
type="button"
onClick={() => onPageChange(Math.min(totalPages, safeCurrentPage + 1))}
disabled={safeCurrentPage >= totalPages}
className="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-slate-100 disabled:opacity-40 disabled:hover:bg-white text-xs font-medium transition-colors"
aria-label="Halaman Berikutnya"
className="inline-flex items-center gap-1 px-2 sm:px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-slate-100 disabled:opacity-40 disabled:hover:bg-white text-xs font-medium transition-colors"
>
<span>Berikutnya</span>
<span className="hidden sm:inline">Berikutnya</span>
<ChevronRight className="h-3.5 w-3.5" />
</button>
</div>
+306
View File
@@ -0,0 +1,306 @@
"use client";
import React, { useRef, useState } from "react";
import * as XLSX from "xlsx";
import { Download, Upload, X, CheckCircle2, AlertCircle, FileSpreadsheet } from "lucide-react";
interface SerialNumberInputProps {
value: string;
onChange: (val: string) => void;
label?: string;
placeholder?: string;
templateName?: string;
expectedQty?: number;
className?: string;
compact?: boolean;
}
const HEADER_KEYWORDS = new Set([
"no",
"no.",
"nomor",
"sn",
"serial",
"serial number",
"serial_number",
"serialnumber",
"no seri",
"no. seri",
"nomor seri",
"nomor_seri",
"kode sn",
"device sn",
]);
export function parseSerialList(raw: string): string[] {
if (!raw) return [];
const parts = raw
.split(/[\n,;]+/)
.map((s) => s.trim())
.filter(Boolean);
return Array.from(new Set(parts));
}
export function SerialNumberInput({
value,
onChange,
label = "Daftar Serial Number (SN)",
placeholder = "Contoh: SN-001, SN-002, SN-003 (ketik manual atau upload Excel)",
templateName = "Serial_Number",
expectedQty,
className = "",
compact = false,
}: SerialNumberInputProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [uploadStatus, setUploadStatus] = useState<{
type: "success" | "error";
text: string;
} | null>(null);
const parsedSnList = parseSerialList(value);
const snCount = parsedSnList.length;
const handleDownloadTemplate = () => {
const safeName = templateName
.replace(/[^a-zA-Z0-9_-]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 40) || "Serial_Number";
const qtyHint = expectedQty && expectedQty > 0 ? Math.min(expectedQty, 5) : 3;
const rows: (string | number)[][] = [["No", "Serial_Number"]];
for (let i = 1; i <= qtyHint; i++) {
rows.push([i, `SN-CONTOH-${String(i).padStart(4, "0")}`]);
}
const ws = XLSX.utils.aoa_to_sheet(rows);
ws["!cols"] = [{ wch: 8 }, { wch: 30 }];
const wsGuide = XLSX.utils.aoa_to_sheet([
["PETUNJUK PENGISIAN TEMPLATE SERIAL NUMBER (SN)"],
["1. Isi daftar Serial Number perangkat pada kolom B (Serial_Number) di sheet 'Daftar_SN'."],
["2. Hapus baris contoh (SN-CONTOH-...) lalu masukkan seluruh SN fisik perangkat Anda."],
["3. Mendukung ratusan hingga ribuan SN dalam 1 file (.xlsx, .xls, atau .csv)."],
["4. Simpan file lalu klik tombol 'Upload Excel' di aplikasi ERP."],
]);
wsGuide["!cols"] = [{ wch: 78 }];
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Daftar_SN");
XLSX.utils.book_append_sheet(wb, wsGuide, "Petunjuk");
XLSX.writeFile(wb, `Template_SN_${safeName}.xlsx`);
};
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploadStatus(null);
try {
const buffer = await file.arrayBuffer();
const workbook = XLSX.read(buffer, { type: "array" });
const firstSheetName = workbook.SheetNames[0];
if (!firstSheetName) {
throw new Error("File Excel kosong atau tidak memiliki sheet.");
}
const worksheet = workbook.Sheets[firstSheetName];
const rows = XLSX.utils.sheet_to_json<any[]>(worksheet, {
header: 1,
defval: "",
raw: false,
});
if (!rows || rows.length === 0) {
throw new Error("Tidak ada data di dalam file Excel.");
}
// Cari indeks kolom SN berdasarkan header baris pertama
const firstRow = (rows[0] || []).map((c) => String(c ?? "").trim().toLowerCase());
let snColIdx = firstRow.findIndex(
(h) =>
h === "serial_number" ||
h === "serial number" ||
h === "serialnumber" ||
h === "sn" ||
h === "no seri" ||
h === "no. seri" ||
h === "nomor seri" ||
h.includes("serial")
);
let startRow = 0;
if (snColIdx !== -1) {
startRow = 1; // Baris pertama adalah header
} else {
// Cek apakah baris pertama berupa header umum ("No", ...) atau langsung data
const hasHeaderLikeFirst = firstRow.some((h) => HEADER_KEYWORDS.has(h));
startRow = hasHeaderLikeFirst ? 1 : 0;
// Jika ada >= 2 kolom dan kolom 0 berisi nomor urut (1, 2, 3...), ambil kolom 1
const sampleRows = rows.slice(startRow, startRow + 5).filter((r) => r && r.length > 0);
const col0LooksLikeIndex =
sampleRows.length > 0 &&
sampleRows.every((r) => {
const c0 = String(r[0] ?? "").trim();
const c1 = String(r[1] ?? "").trim();
return /^\d+$/.test(c0) && c1.length > 0;
});
snColIdx = col0LooksLikeIndex ? 1 : 0;
}
const extracted: string[] = [];
for (let i = startRow; i < rows.length; i++) {
const row = rows[i];
if (!row) continue;
const cellVal = String(row[snColIdx] ?? "").trim();
if (!cellVal) continue;
if (HEADER_KEYWORDS.has(cellVal.toLowerCase())) continue;
// Dukung jika dalam 1 sel ada beberapa SN dipisah koma
const subParts = cellVal
.split(/[\n,;]+/)
.map((s) => s.trim())
.filter(Boolean);
extracted.push(...subParts);
}
const uniqueSns = Array.from(new Set(extracted));
if (uniqueSns.length === 0) {
throw new Error(
"Tidak ditemukan Serial Number yang valid. Pastikan SN diisi pada kolom 'Serial_Number'."
);
}
// Gabungkan jika sebelumnya sudah ada SN, atau langsung set
const existing = parseSerialList(value);
const merged = existing.length > 0 ? Array.from(new Set([...existing, ...uniqueSns])) : uniqueSns;
onChange(merged.join(", "));
setUploadStatus({
type: "success",
text: `Berhasil memuat ${uniqueSns.length} SN dari ${file.name}${
existing.length > 0 ? ` (Total: ${merged.length} SN)` : ""
}`,
});
} catch (err: any) {
setUploadStatus({
type: "error",
text: err?.message || "Gagal membaca file Excel. Gunakan template yang tersedia.",
});
} finally {
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}
};
return (
<div className={`space-y-1.5 ${className}`}>
<div className="flex flex-wrap items-center justify-between gap-1.5">
<div className="flex items-center gap-1.5 min-w-0">
<label className="text-[10.5px] font-bold text-slate-700 truncate">
{label}
</label>
{snCount > 0 && (
<span
className={`px-1.5 py-0.5 rounded text-[10px] font-bold border whitespace-nowrap ${
expectedQty && expectedQty > 0
? snCount === expectedQty
? "bg-emerald-50 text-emerald-700 border-emerald-200"
: "bg-amber-50 text-amber-800 border-amber-300"
: "bg-blue-50 text-blue-700 border-blue-200"
}`}
>
{expectedQty && expectedQty > 0
? `${snCount}/${expectedQty} SN`
: `${snCount} SN`}
</span>
)}
</div>
<div className="flex items-center gap-1.5 shrink-0 flex-wrap">
<button
type="button"
onClick={handleDownloadTemplate}
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-white hover:bg-emerald-50 text-emerald-700 border border-emerald-300 text-[10px] font-bold transition-colors shadow-2xs"
title="Unduh Template Excel (.xlsx) untuk pengisian banyak Serial Number"
>
<Download className="h-3 w-3 shrink-0" />
<span>Template Excel</span>
</button>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="inline-flex items-center gap-1 px-2 py-1 rounded bg-emerald-600 hover:bg-emerald-700 text-white text-[10px] font-bold transition-colors shadow-2xs"
title="Upload file Excel (.xlsx, .xls, .csv) berisi daftar Serial Number"
>
<Upload className="h-3 w-3 shrink-0" />
<span>Upload Excel</span>
</button>
{snCount > 0 && (
<button
type="button"
onClick={() => {
onChange("");
setUploadStatus(null);
}}
className="inline-flex items-center gap-0.5 px-1.5 py-1 rounded bg-white hover:bg-rose-50 text-rose-600 border border-rose-200 text-[10px] font-semibold transition-colors"
title="Kosongkan daftar SN"
>
<X className="h-3 w-3" />
</button>
)}
<input
ref={fileInputRef}
type="file"
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
onChange={handleFileUpload}
className="hidden"
/>
</div>
</div>
{compact ? (
<input
type="text"
placeholder={placeholder}
value={value}
onChange={(e) => onChange(e.target.value)}
className="w-full h-9 px-2.5 py-1.5 border border-slate-300 rounded-lg font-mono text-xs bg-white focus:ring-1 focus:ring-blue-500"
/>
) : (
<textarea
rows={snCount > 8 ? 3 : 2}
placeholder={placeholder}
value={value}
onChange={(e) => onChange(e.target.value)}
className="w-full px-2.5 py-1.5 border border-slate-300 rounded-lg font-mono text-xs bg-white focus:ring-1 focus:ring-blue-500 resize-y"
/>
)}
{uploadStatus && (
<div
className={`flex items-center gap-1.5 px-2 py-1 rounded text-[10.5px] font-medium ${
uploadStatus.type === "success"
? "bg-emerald-50 text-emerald-800 border border-emerald-200"
: "bg-rose-50 text-rose-700 border border-rose-200"
}`}
>
{uploadStatus.type === "success" ? (
<CheckCircle2 className="h-3.5 w-3.5 text-emerald-600 shrink-0" />
) : (
<AlertCircle className="h-3.5 w-3.5 text-rose-600 shrink-0" />
)}
<span>{uploadStatus.text}</span>
</div>
)}
{!uploadStatus && (
<div className="flex items-center gap-1 text-[9.5px] text-slate-500">
<FileSpreadsheet className="h-3 w-3 text-emerald-600 shrink-0" />
<span>Ketik dipisah koma, atau klik <strong>Template Excel</strong> &amp; <strong>Upload Excel</strong> untuk pengiriman banyak unit.</span>
</div>
)}
</div>
);
}
+283 -254
View File
@@ -19,101 +19,135 @@ import {
ArrowRightLeft,
ClipboardList,
Layers,
History,
Wrench,
FileSpreadsheet,
X,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { canAccessRoute } from "@/lib/permissions";
const allNavigation = [
{ name: "Dashboard", href: "/", icon: LayoutDashboard },
{ name: "Inventaris & Stok", href: "/inventory", icon: Boxes },
{ name: "Penjualan & Invoice", href: "/sales", icon: ShoppingCart },
{ name: "Pembelian & Pemasok", href: "/purchases", icon: Truck, isPurchases: true },
{ name: "Keuangan & Akuntansi", href: "/finance", icon: DollarSign, isFinance: true },
{ name: "Pengguna & RBAC", href: "/users", icon: Users },
{ name: "Notifikasi & Sistem", href: "/settings", icon: Settings },
{ name: "Inventaris", href: "/inventory", icon: Boxes, isInventory: true },
{ name: "Penjualan", href: "/sales", icon: ShoppingCart },
{ name: "Pembelian", href: "/purchases", icon: Truck, isPurchases: true },
{ name: "Keuangan", href: "/finance", icon: DollarSign, isFinance: true },
{ name: "Pengguna", href: "/users", icon: Users },
{ name: "Pengaturan", href: "/settings", icon: Settings },
];
const inventorySubMenus = [
{ id: "catalog", name: "Katalog & SN", icon: Boxes },
{ id: "movements", name: "Mutasi Stok", icon: History },
{ id: "devices", name: "Service & RMA", icon: Wrench },
];
const purchasesSubMenus = [
{ id: "po", name: "Daftar Purchase Order", icon: Truck },
{ id: "requisitions", name: "Pengajuan dari Sales", icon: ClipboardList },
{ id: "batches", name: "Pelacakan Batch PO & Kolaborasi Penjualan", icon: Layers },
{ id: "po", name: "Purchase Order", icon: Truck },
{ id: "requisitions", name: "Pengajuan", icon: ClipboardList },
{ id: "batches", name: "Batch & Alokasi", icon: Layers },
];
const financeSubMenus = [
{ id: "payroll", name: "Payroll & Slip Gaji", icon: Calculator },
{ id: "coa", name: "Kode Akun & Bank / COA", icon: BookOpen },
{ id: "journal", name: "Jurnal Transaksi", icon: ArrowRightLeft },
{ id: "companies", name: "Entitas PT", icon: Building2 },
{ id: "reports", name: "Laporan", icon: FileSpreadsheet },
{ id: "payroll", name: "Payroll", icon: Calculator },
{ id: "coa", name: "Daftar Akun", icon: BookOpen },
{ id: "journal", name: "Jurnal", icon: ArrowRightLeft },
{ id: "companies", name: "Perusahaan", icon: Building2 },
];
const roleLabelMap: Record<string, string> = {
ADMIN: "Administrator",
MANAGER: "Manajemen",
INVENTORY: "Gudang & Teknisi",
SALES: "Sales",
PURCHASING: "Purchasing",
ACCOUNTANT: "Keuangan",
};
export function Sidebar({
user,
mobileOpen = false,
onCloseMobile,
}: {
user?: { name: string; role: string; email: string; envMode?: "DEMO" | "LIVE" } | null;
user?: { name: string; role: string; email: string } | null;
mobileOpen?: boolean;
onCloseMobile?: () => void;
}) {
const pathname = usePathname();
const router = useRouter();
const [financeOpen, setFinanceOpen] = useState(pathname === "/finance");
const [activeFinanceTab, setActiveFinanceTab] = useState<string>("payroll");
const [activeFinanceTab, setActiveFinanceTab] = useState<string>("reports");
const [purchasesOpen, setPurchasesOpen] = useState(pathname === "/purchases");
const [activePurchasesTab, setActivePurchasesTab] = useState<string>("po");
const [inventoryOpen, setInventoryOpen] = useState(pathname === "/inventory");
const [activeInventoryTab, setActiveInventoryTab] = useState<string>("catalog");
useEffect(() => {
if (pathname === "/finance") {
setFinanceOpen(true);
}
if (pathname === "/purchases") {
setPurchasesOpen(true);
}
if (pathname === "/finance") setFinanceOpen(true);
if (pathname === "/purchases") setPurchasesOpen(true);
if (pathname === "/inventory") setInventoryOpen(true);
if (typeof window !== "undefined") {
const savedTab = sessionStorage.getItem("erp_finance_tab");
if (savedTab) setActiveFinanceTab(savedTab);
const savedPurchasesTab = sessionStorage.getItem("erp_purchases_tab");
if (savedPurchasesTab) setActivePurchasesTab(savedPurchasesTab);
const savedInventoryTab = sessionStorage.getItem("erp_inventory_tab");
if (savedInventoryTab) setActiveInventoryTab(savedInventoryTab);
}
const handleTabSync = (e: any) => {
if (e?.detail?.tab) {
setActiveFinanceTab(e.detail.tab);
}
if (e?.detail?.tab) setActiveFinanceTab(e.detail.tab);
};
const handlePurchasesTabSync = (e: any) => {
if (e?.detail?.tab) {
setActivePurchasesTab(e.detail.tab);
}
if (e?.detail?.tab) setActivePurchasesTab(e.detail.tab);
};
window.addEventListener("erp:finance-tab-sync", handleTabSync);
window.addEventListener("erp:purchases-tab-sync", handlePurchasesTabSync);
const handleInventoryTabSync = (e: any) => {
if (e?.detail?.tab) setActiveInventoryTab(e.detail.tab);
};
window.addEventListener("erp:finance-tab", handleTabSync);
window.addEventListener("erp:purchases-tab", handlePurchasesTabSync);
window.addEventListener("erp:inventory-tab", handleInventoryTabSync);
return () => {
window.removeEventListener("erp:finance-tab-sync", handleTabSync);
window.removeEventListener("erp:purchases-tab-sync", handlePurchasesTabSync);
window.removeEventListener("erp:finance-tab", handleTabSync);
window.removeEventListener("erp:purchases-tab", handlePurchasesTabSync);
window.removeEventListener("erp:inventory-tab", handleInventoryTabSync);
};
}, [pathname]);
const handleSelectInventorySub = (tabId: string) => {
setActiveInventoryTab(tabId);
setInventoryOpen(true);
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_inventory_tab", tabId);
window.dispatchEvent(new CustomEvent("erp:inventory-tab", { detail: { tab: tabId } }));
}
if (pathname !== "/inventory") router.push("/inventory");
onCloseMobile?.();
};
const handleSelectFinanceSub = (tabId: string) => {
setActiveFinanceTab(tabId);
setFinanceOpen(true);
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_finance_tab", tabId);
window.dispatchEvent(
new CustomEvent("erp:finance-tab", { detail: { tab: tabId } })
);
}
if (pathname !== "/finance") {
router.push("/finance");
window.dispatchEvent(new CustomEvent("erp:finance-tab", { detail: { tab: tabId } }));
}
if (pathname !== "/finance") router.push("/finance");
onCloseMobile?.();
};
const handleSelectPurchasesSub = (tabId: string) => {
setActivePurchasesTab(tabId);
setPurchasesOpen(true);
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_purchases_tab", tabId);
window.dispatchEvent(
new CustomEvent("erp:purchases-tab", { detail: { tab: tabId } })
);
}
if (pathname !== "/purchases") {
router.push("/purchases");
window.dispatchEvent(new CustomEvent("erp:purchases-tab", { detail: { tab: tabId } }));
}
if (pathname !== "/purchases") router.push("/purchases");
onCloseMobile?.();
};
const handleLogout = async () => {
@@ -128,226 +162,221 @@ export function Sidebar({
user?.role ? canAccessRoute(user.role, item.href) : true
);
const isLive = user?.envMode === "LIVE";
const renderGroup = (
item: (typeof allNavigation)[number],
isActive: boolean,
isOpen: boolean,
setOpen: (v: boolean) => void,
subMenus: { id: string; name: string; icon: any }[],
activeSub: string,
onSelectSub: (id: string) => void
) => {
const Icon = item.icon;
return (
<div key={item.name} className="space-y-0.5">
<button
type="button"
onClick={() => {
if (pathname !== item.href) {
setOpen(true);
router.push(item.href);
} else {
setOpen(!isOpen);
}
}}
className={cn(
"w-full flex items-center justify-between px-3 py-2 rounded-lg text-[13px] font-medium transition-colors",
isActive
? "bg-slate-900 text-white"
: "text-slate-800 dark:text-slate-100 hover:bg-slate-100 hover:text-slate-900"
)}
>
<div className="flex items-center gap-2.5">
<Icon className={cn("h-4 w-4", isActive ? "text-white" : "text-slate-700 dark:text-slate-200")} />
<span>{item.name}</span>
</div>
<ChevronDown
className={cn(
"h-3.5 w-3.5 transition-transform duration-150",
isActive ? "text-slate-200" : "text-slate-700 dark:text-slate-200",
isOpen ? "rotate-180" : ""
)}
/>
</button>
{isOpen && (
<div className="ml-4 pl-3 border-l border-slate-200 space-y-0.5 py-1">
{subMenus.map((sub) => {
const SubIcon = sub.icon;
const isSubActive = pathname === item.href && activeSub === sub.id;
return (
<button
key={sub.id}
type="button"
onClick={() => onSelectSub(sub.id)}
className={cn(
"w-full flex items-center gap-2 px-2.5 py-1.5 rounded-md text-xs transition-colors text-left",
isSubActive
? "bg-slate-100 text-slate-900 font-semibold border border-slate-200/80"
: "text-slate-700 dark:text-slate-100 hover:bg-slate-50 hover:text-slate-900"
)}
>
<SubIcon
className={cn(
"h-3.5 w-3.5 shrink-0",
isSubActive ? "text-slate-900" : "text-slate-700 dark:text-slate-200"
)}
/>
<span>{sub.name}</span>
</button>
);
})}
</div>
)}
</div>
);
};
return (
<aside className="fixed inset-y-0 left-0 z-40 w-64 bg-slate-900 text-slate-100 flex flex-col border-r border-slate-800">
{/* Brand Header */}
<div className="h-16 flex items-center px-6 gap-3 border-b border-slate-800 bg-slate-950">
<>
{mobileOpen && (
<div
className={`h-9 w-9 rounded-lg flex items-center justify-center text-white font-bold shadow-md ${
isLive
? "bg-emerald-600 shadow-emerald-500/20"
: "bg-blue-600 shadow-blue-500/20"
}`}
>
<Building2 className="h-5 w-5" />
</div>
<div>
<span className="font-bold text-base tracking-wide text-white">EnterpriseCore</span>
<span
className={`block text-[10px] font-bold tracking-wider uppercase ${
isLive ? "text-emerald-400" : "text-amber-400"
}`}
>
{isLive ? "● PRODUCTION" : "● DEMO SANDBOX"}
</span>
</div>
</div>
className="fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-[1px] lg:hidden"
onClick={onCloseMobile}
aria-hidden="true"
/>
)}
{/* Navigation Links */}
<div className="flex-1 py-6 px-3 space-y-1.5 overflow-y-auto">
<div className="px-3 pb-2 text-[11px] font-semibold tracking-wider text-slate-400 uppercase flex items-center justify-between">
<span>Menu Akses</span>
<span className="text-[10px] text-blue-400 font-mono">
{user?.role || "GUEST"}
</span>
</div>
{allowedNav.map((item) => {
const isActive = pathname === item.href;
const Icon = item.icon;
if (item.isPurchases) {
return (
<div key={item.name} className="space-y-1">
<button
type="button"
onClick={() => {
if (pathname !== "/purchases") {
setPurchasesOpen(true);
router.push("/purchases");
} else {
setPurchasesOpen(!purchasesOpen);
}
}}
className={cn(
"w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-150",
isActive
? "bg-blue-600 text-white shadow-sm shadow-blue-600/30 font-semibold"
: "text-slate-300 hover:bg-slate-800/80 hover:text-white"
)}
>
<div className="flex items-center gap-3">
<Icon
className={cn("h-4 w-4", isActive ? "text-white" : "text-slate-400")}
/>
<span>{item.name}</span>
</div>
<ChevronDown
className={cn(
"h-4 w-4 transition-transform duration-150",
purchasesOpen ? "rotate-180" : ""
)}
/>
</button>
{/* Sub-menu Menurun saat Klik Pembelian & Pemasok */}
{purchasesOpen && (
<div className="ml-4 pl-3 border-l border-slate-700/80 space-y-1 py-1">
{purchasesSubMenus.map((sub) => {
const SubIcon = sub.icon;
const isSubActive =
pathname === "/purchases" && activePurchasesTab === sub.id;
return (
<button
key={sub.id}
type="button"
onClick={() => handleSelectPurchasesSub(sub.id)}
className={cn(
"w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors text-left",
isSubActive
? "bg-slate-800 text-blue-400 font-bold border border-slate-700"
: "text-slate-400 hover:bg-slate-800/50 hover:text-slate-200"
)}
>
<SubIcon
className={cn(
"h-3.5 w-3.5 shrink-0",
isSubActive ? "text-blue-400" : "text-slate-500"
)}
/>
<span>{sub.name}</span>
</button>
);
})}
</div>
)}
</div>
);
}
if (item.isFinance) {
return (
<div key={item.name} className="space-y-1">
<button
type="button"
onClick={() => {
if (pathname !== "/finance") {
setFinanceOpen(true);
router.push("/finance");
} else {
setFinanceOpen(!financeOpen);
}
}}
className={cn(
"w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-150",
isActive
? "bg-blue-600 text-white shadow-sm shadow-blue-600/30 font-semibold"
: "text-slate-300 hover:bg-slate-800/80 hover:text-white"
)}
>
<div className="flex items-center gap-3">
<Icon
className={cn("h-4 w-4", isActive ? "text-white" : "text-slate-400")}
/>
<span>{item.name}</span>
</div>
<ChevronDown
className={cn(
"h-4 w-4 transition-transform duration-150",
financeOpen ? "rotate-180" : ""
)}
/>
</button>
{/* Sub-menu Menurun saat Klik Keuangan & Akuntansi */}
{financeOpen && (
<div className="ml-4 pl-3 border-l border-slate-700/80 space-y-1 py-1">
{financeSubMenus.map((sub) => {
const SubIcon = sub.icon;
const isSubActive =
pathname === "/finance" && activeFinanceTab === sub.id;
return (
<button
key={sub.id}
type="button"
onClick={() => handleSelectFinanceSub(sub.id)}
className={cn(
"w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors text-left",
isSubActive
? "bg-slate-800 text-emerald-400 font-bold border border-slate-700"
: "text-slate-400 hover:bg-slate-800/50 hover:text-slate-200"
)}
>
<SubIcon
className={cn(
"h-3.5 w-3.5 shrink-0",
isSubActive ? "text-emerald-400" : "text-slate-500"
)}
/>
<span>{sub.name}</span>
</button>
);
})}
</div>
)}
</div>
);
}
return (
<Link
key={item.name}
href={item.href}
prefetch={true}
className={cn(
"flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-150",
isActive
? "bg-blue-600 text-white shadow-sm shadow-blue-600/30 font-semibold"
: "text-slate-300 hover:bg-slate-800/80 hover:text-white"
)}
>
<Icon className={cn("h-4 w-4", isActive ? "text-white" : "text-slate-400")} />
<span>{item.name}</span>
</Link>
);
})}
</div>
{/* User Info & Logout */}
<div className="p-4 border-t border-slate-800 bg-slate-950/60">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-3 min-w-0">
<div className="h-8 w-8 rounded-full bg-slate-700 flex items-center justify-center font-bold text-xs text-white">
{user?.name ? user.name.slice(0, 2).toUpperCase() : "AD"}
<aside
className={cn(
"fixed inset-y-0 left-0 z-50 lg:z-40 w-64 bg-white text-slate-800 flex flex-col border-r border-slate-200/80 transition-transform duration-200 ease-in-out",
mobileOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
)}
>
{/* Brand Header */}
<div className="h-15 flex items-center justify-between px-4 gap-2 border-b border-slate-200/80">
<div className="flex items-center gap-2.5 min-w-0">
<div className="h-8 w-8 shrink-0 rounded-lg bg-slate-900 dark:bg-white flex items-center justify-center text-white dark:text-slate-950">
<Building2 className="h-4 w-4" />
</div>
<div className="min-w-0 truncate">
<p className="text-xs font-semibold text-white truncate">{user?.name || "Pengguna"}</p>
<span className="inline-block px-1.5 py-0.5 rounded text-[10px] font-medium bg-blue-900/60 text-blue-300 border border-blue-700/50 mt-0.5">
{user?.role || "USER"}
<div className="min-w-0">
<span className="font-semibold text-sm tracking-tight text-slate-900 dark:text-white block truncate">
EnterpriseCore
</span>
<span className="flex items-center gap-1.5 text-[10px] font-semibold text-slate-800 dark:text-slate-100">
<span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
Enterprise ERP
</span>
</div>
</div>
{onCloseMobile && (
<button
type="button"
onClick={onCloseMobile}
aria-label="Tutup Menu"
className="lg:hidden p-1.5 rounded-lg text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors"
>
<X className="h-4 w-4" />
</button>
)}
</div>
<button
onClick={handleLogout}
className="w-full flex items-center justify-center gap-2 px-3 py-2 text-xs font-medium text-slate-300 bg-slate-800/70 hover:bg-rose-950/50 hover:text-rose-300 hover:border-rose-800 rounded-md border border-slate-700/60 transition-colors"
>
<LogOut className="h-3.5 w-3.5" />
<span>Keluar / Ganti Mode</span>
</button>
</div>
</aside>
{/* Navigation Links */}
<div className="flex-1 py-4 px-3 space-y-1 overflow-y-auto">
<div className="px-3 pb-1.5 text-[10px] font-semibold tracking-wider text-slate-400 uppercase">
Navigasi
</div>
{allowedNav.map((item) => {
const isActive = pathname === item.href;
const Icon = item.icon;
if ((item as any).isInventory) {
return renderGroup(
item,
isActive,
inventoryOpen,
setInventoryOpen,
inventorySubMenus,
activeInventoryTab,
handleSelectInventorySub
);
}
if (item.isPurchases) {
return renderGroup(
item,
isActive,
purchasesOpen,
setPurchasesOpen,
purchasesSubMenus,
activePurchasesTab,
handleSelectPurchasesSub
);
}
if (item.isFinance) {
return renderGroup(
item,
isActive,
financeOpen,
setFinanceOpen,
financeSubMenus,
activeFinanceTab,
handleSelectFinanceSub
);
}
const displayName =
item.href === "/sales" && user?.role === "INVENTORY"
? "Pengiriman"
: item.name;
return (
<Link
key={item.name}
href={item.href}
prefetch={true}
onClick={() => onCloseMobile?.()}
className={cn(
"flex items-center gap-2.5 px-3 py-2 rounded-lg text-[13px] font-medium transition-colors",
isActive
? "bg-slate-900 text-white"
: "text-slate-800 dark:text-slate-100 hover:bg-slate-100 hover:text-slate-900"
)}
>
<Icon className={cn("h-4 w-4", isActive ? "text-white" : "text-slate-700 dark:text-slate-200")} />
<span>{displayName}</span>
</Link>
);
})}
</div>
{/* User Footer */}
<div className="p-3.5 border-t border-slate-200/80 bg-slate-50/60">
<div className="flex items-center gap-2.5 mb-2.5 min-w-0">
<div className="h-8 w-8 rounded-full bg-slate-200 text-slate-700 flex items-center justify-center font-semibold text-xs shrink-0">
{user?.name ? user.name.slice(0, 2).toUpperCase() : "US"}
</div>
<div className="min-w-0">
<p className="text-xs font-semibold text-slate-900 truncate">
{user?.name || "Pengguna"}
</p>
<p className="text-[11px] text-slate-500 truncate">
{roleLabelMap[user?.role || ""] || user?.role || "User"}
</p>
</div>
</div>
<button
onClick={handleLogout}
className="w-full flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-medium text-slate-600 bg-white hover:bg-slate-100 hover:text-slate-900 rounded-lg border border-slate-200 transition-colors"
>
<LogOut className="h-3.5 w-3.5" />
<span>Keluar</span>
</button>
</div>
</aside>
</>
);
}
+13 -18
View File
@@ -7,39 +7,34 @@ interface StatCardProps {
value: string;
description?: string;
icon: LucideIcon;
variant?: "blue" | "emerald" | "amber" | "rose" | "purple";
variant?: "blue" | "emerald" | "amber" | "rose" | "purple" | "neutral";
badge?: ReactNode;
}
const variantStyles = {
blue: "bg-blue-50 text-blue-600 border-blue-100",
emerald: "bg-emerald-50 text-emerald-600 border-emerald-100",
amber: "bg-amber-50 text-amber-600 border-amber-100",
rose: "bg-rose-50 text-rose-600 border-rose-100",
purple: "bg-purple-50 text-purple-600 border-purple-100",
};
export function StatCard({
title,
value,
description,
icon: Icon,
variant = "blue",
badge,
}: StatCardProps) {
return (
<div className="bg-white rounded-xl border border-slate-200/80 p-5 shadow-xs hover:shadow-sm transition-shadow">
<div className="flex items-center justify-between">
<span className="text-xs font-semibold uppercase tracking-wider text-slate-500">
<div className="bg-white rounded-xl border border-slate-200/80 p-4 sm:p-5 shadow-[0_1px_2px_rgba(15,23,42,0.03)] hover:border-slate-300/90 transition-colors">
<div className="flex items-center justify-between gap-2">
<span className="text-[11px] font-semibold uppercase tracking-wider text-slate-500 truncate">
{title}
</span>
<div className={cn("p-2.5 rounded-lg border", variantStyles[variant])}>
<Icon className="h-5 w-5" />
<div className={cn("p-2 rounded-lg bg-slate-100/80 text-slate-600 border border-slate-200/60 shrink-0")}>
<Icon className="h-4 w-4" />
</div>
</div>
<div className="mt-4">
<h3 className="text-2xl font-bold text-slate-800 tracking-tight">{value}</h3>
{description && <p className="text-xs text-slate-500 mt-1">{description}</p>}
<div className="mt-3">
<h3 className="text-xl sm:text-2xl font-bold text-slate-900 tracking-tight tabular-nums truncate">
{value}
</h3>
{description && (
<p className="text-xs text-slate-500 mt-1 truncate">{description}</p>
)}
{badge && <div className="mt-2">{badge}</div>}
</div>
</div>
+57
View File
@@ -0,0 +1,57 @@
"use client";
import { useEffect, useState } from "react";
import { Moon, Sun } from "lucide-react";
export function ThemeToggle({ compact = false }: { compact?: boolean }) {
const [theme, setTheme] = useState<"dark" | "light">("dark");
useEffect(() => {
const sync = () => {
const isDark = document.documentElement.classList.contains("dark");
setTheme(isDark ? "dark" : "light");
};
sync();
window.addEventListener("erp:theme-changed", sync);
return () => window.removeEventListener("erp:theme-changed", sync);
}, []);
const toggleTheme = () => {
const next = theme === "dark" ? "light" : "dark";
const root = document.documentElement;
if (next === "dark") {
root.classList.add("dark");
} else {
root.classList.remove("dark");
}
root.setAttribute("data-theme", next);
try {
localStorage.setItem("erp_theme", next);
} catch {
// ignore storage errors
}
setTheme(next);
window.dispatchEvent(new CustomEvent("erp:theme-changed", { detail: { theme: next } }));
};
return (
<button
type="button"
onClick={toggleTheme}
title={theme === "dark" ? "Beralih ke Mode Terang" : "Beralih ke Mode Gelap"}
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-semibold border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-white hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors shrink-0"
>
{theme === "dark" ? (
<>
<Sun className="h-3.5 w-3.5 text-amber-300 shrink-0" />
{!compact && <span className="hidden sm:inline">Terang</span>}
</>
) : (
<>
<Moon className="h-3.5 w-3.5 text-slate-900 shrink-0" />
{!compact && <span className="hidden sm:inline">Gelap</span>}
</>
)}
</button>
);
}
+43 -6
View File
@@ -1,7 +1,7 @@
import { SignJWT, jwtVerify } from "jose";
import bcrypt from "bcryptjs";
import { cookies } from "next/headers";
import type { EnvMode } from "./db";
import { getPrismaByMode, type EnvMode } from "./db";
const SECRET_KEY = new TextEncoder().encode(
process.env.JWT_SECRET || "enterprisecore-secret-jwt-key-2026-production-ready"
@@ -29,7 +29,7 @@ export async function signToken(user: SessionUser): Promise<string> {
email: user.email,
name: user.name,
role: user.role,
envMode: user.envMode || "DEMO",
envMode: "LIVE",
})
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
@@ -47,7 +47,7 @@ export async function verifyToken(token: string): Promise<SessionUser | null> {
email: payload.email as string,
name: payload.name as string,
role: payload.role as string,
envMode: (payload.envMode as EnvMode) || "DEMO",
envMode: "LIVE",
};
} catch {
return null;
@@ -61,10 +61,25 @@ export async function getCurrentUser(): Promise<SessionUser | null> {
if (!token) return null;
const user = await verifyToken(token);
if (!user) return null;
// Keamanan: envMode harus selalu bersumber dari payload JWT yang ditandatangani (bukan cookie erp_env mentah)
const envMode: EnvMode = "LIVE";
// Validasi status aktif & role terkini di database agar penonaktifan akun atau perubahan role berlaku seketika
const db = getPrismaByMode(envMode);
const dbUser = await db.user.findUnique({
where: { id: user.id },
select: { id: true, email: true, name: true, role: true, isActive: true },
});
if (!dbUser || dbUser.isActive === false) {
return null;
}
return {
...user,
envMode: user.envMode === "LIVE" ? "LIVE" : "DEMO",
id: dbUser.id,
email: dbUser.email,
name: dbUser.name,
role: dbUser.role,
envMode,
};
} catch {
return null;
@@ -106,6 +121,28 @@ export function recordFailedAttempt(key: string): void {
}
}
export function isHttpsRequest(req: Request): boolean {
const forwardedProto = req.headers.get("x-forwarded-proto");
if (forwardedProto) {
return forwardedProto.split(",")[0].trim().toLowerCase() === "https";
}
try {
return new URL(req.url).protocol === "https:";
} catch {
return false;
}
}
export function getAuthCookieOptions(req: Request) {
return {
httpOnly: true,
secure: isHttpsRequest(req),
sameSite: "lax" as const,
path: "/",
maxAge: 60 * 60 * 24, // 24 hours
};
}
export function clearRateLimit(key: string): void {
rateLimitStore.delete(key);
}
+24 -1
View File
@@ -7,7 +7,9 @@ export const DEFAULT_ACCOUNTS_TEMPLATE = [
{ code: "1002", name: "Bank BCA Utama", type: "ASSET" },
{ code: "1101", name: "Piutang Dagang (AR)", type: "ASSET" },
{ code: "1201", name: "Persediaan Barang Dagang", type: "ASSET" },
{ code: "1301", name: "PPN Masukan (Pajak Pembelian)", type: "ASSET" },
{ code: "2001", name: "Hutang Dagang (AP)", type: "LIABILITY" },
{ code: "2101", name: "PPN Keluaran (Hutang Pajak Penjualan)", type: "LIABILITY" },
{ code: "3001", name: "Modal Disetor", type: "EQUITY" },
{ code: "4001", name: "Pendapatan Penjualan Barang", type: "REVENUE" },
{ code: "5001", name: "Beban Pokok Penjualan (HPP)", type: "EXPENSE" },
@@ -65,8 +67,29 @@ export async function getCompanyAccount(code: string, companyName?: string) {
where: { code, companyName: cleanComp },
});
if (matched) return matched;
// Auto-provision seluruh template akun untuk PT ini agar transaksi TIDAK pernah bocor ke PT lain!
await ensureCompanyAccounts(cleanComp);
const provisioned = await prisma.account.findFirst({
where: { code, companyName: cleanComp },
});
if (provisioned) return provisioned;
// Jika kode custom di luar template, buat akun khusus untuk PT ini (bukan fallback ke PT lain)
const templateRef = await prisma.account.findFirst({ where: { code } });
return prisma.account.create({
data: {
code,
name: templateRef
? `${templateRef.name.replace(/\s*\([^)]+\)\s*$/, "")} (${cleanComp})`
: `Akun ${code} (${cleanComp})`,
type: templateRef?.type || (code.startsWith("2") ? "LIABILITY" : code.startsWith("3") ? "EQUITY" : code.startsWith("4") ? "REVENUE" : code.startsWith("5") || code.startsWith("6") ? "EXPENSE" : "ASSET"),
companyName: cleanComp,
balance: 0,
},
});
}
// Fallback to default or any account with that code
// Fallback hanya jika benar-benar tidak ada companyName yang dikirim
const fallback = await prisma.account.findFirst({
where: { code, companyName: "PT EnterpriseCore Utama" },
});
+6 -57
View File
@@ -1,27 +1,12 @@
import { PrismaClient } from "@prisma/client";
import { cookies } from "next/headers";
import { jwtVerify } from "jose";
export type EnvMode = "DEMO" | "LIVE";
const SECRET_KEY = new TextEncoder().encode(
process.env.JWT_SECRET || "enterprisecore-secret-jwt-key-2026-production-ready"
);
export type EnvMode = "LIVE";
const globalForPrisma = globalThis as unknown as {
prismaDemo: PrismaClient | undefined;
prismaLive: PrismaClient | undefined;
};
const demoDbUrl = process.env.DEMO_DATABASE_URL || "file:./dev.db";
const liveDbUrl = process.env.LIVE_DATABASE_URL || "file:./live.db";
export const prismaDemo =
globalForPrisma.prismaDemo ??
new PrismaClient({
datasources: { db: { url: demoDbUrl } },
log: ["error"],
});
const liveDbUrl = process.env.LIVE_DATABASE_URL || process.env.DATABASE_URL || "file:./live.db";
export const prismaLive =
globalForPrisma.prismaLive ??
@@ -31,51 +16,15 @@ export const prismaLive =
});
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prismaDemo = prismaDemo;
globalForPrisma.prismaLive = prismaLive;
}
export async function getEnvMode(): Promise<EnvMode> {
try {
const cookieStore = await cookies();
const token = cookieStore.get("erp_session")?.value;
if (token) {
try {
const { payload } = await jwtVerify(token, SECRET_KEY, {
algorithms: ["HS256"],
});
return payload.envMode === "LIVE" ? "LIVE" : "DEMO";
} catch {
// fallback if token invalid
}
}
const mode = cookieStore.get("erp_env")?.value;
return mode === "LIVE" ? "LIVE" : "DEMO";
} catch {
return "DEMO";
}
return "LIVE";
}
export function getPrismaByMode(mode: EnvMode): PrismaClient {
return mode === "LIVE" ? prismaLive : prismaDemo;
export function getPrismaByMode(_mode?: string): PrismaClient {
return prismaLive;
}
// Dynamic Proxy that automatically routes all Prisma queries to either DEMO (dev.db) or LIVE (live.db)
export const prisma = new Proxy({} as PrismaClient, {
get(_target, modelProp: string | symbol) {
if (typeof modelProp !== "string") return undefined;
return new Proxy(
{},
{
get(_modelTarget, methodProp: string | symbol) {
if (typeof methodProp !== "string") return undefined;
return async (...args: any[]) => {
const mode = await getEnvMode();
const client: any = mode === "LIVE" ? prismaLive : prismaDemo;
return client[modelProp][methodProp](...args);
};
},
}
);
},
});
export const prisma = prismaLive;
+3 -1
View File
@@ -57,8 +57,10 @@ export function verifyTOTP(secret: string, code: string): boolean {
const cleanCode = code.trim();
if (!/^\d{6}$/.test(cleanCode) || !secret) return false;
const providedBuf = Buffer.from(cleanCode, "utf8");
for (const offset of [-1, 0, 1]) {
if (generateTOTP(secret, offset) === cleanCode) {
const expectedBuf = Buffer.from(generateTOTP(secret, offset), "utf8");
if (expectedBuf.length === providedBuf.length && crypto.timingSafeEqual(expectedBuf, providedBuf)) {
return true;
}
}
+176 -29
View File
@@ -1,10 +1,14 @@
import nodemailer from "nodemailer";
import type { PrismaClient } from "@prisma/client";
import { prisma } from "./db";
import { isRoleAllowedNotifType } from "./permissions";
export type NotificationType =
| "STOCK_IN"
| "STOCK_OUT"
| "MONEY_IN"
| "MONEY_OUT"
| "RMA_SERVICE"
| "SYSTEM";
interface DispatchParams {
@@ -13,13 +17,14 @@ interface DispatchParams {
message: string;
details?: Record<string, any>;
targetRoles?: string[];
dbClient?: PrismaClient;
}
const DEFAULT_SETTINGS: Record<string, string> = {
TELEGRAM_BOT_TOKEN: "",
TELEGRAM_ENABLED: "false",
EMAIL_ENABLED: "true",
// Saluran Telegram per Divisi
TELEGRAM_CHAT_ID_MANAGEMENT: "", // Direksi & Admin
TELEGRAM_CHAT_ID_INVENTORY: "", // Divisi Gudang & Logistik
@@ -32,18 +37,20 @@ const DEFAULT_SETTINGS: Record<string, string> = {
NOTIF_STOCK_OUT_ENABLED: "true",
NOTIF_MONEY_IN_ENABLED: "true",
NOTIF_MONEY_OUT_ENABLED: "true",
NOTIF_RMA_ENABLED: "true",
// Email SMTP
SMTP_HOST: "smtp.mailtrap.io",
SMTP_HOST: "",
SMTP_PORT: "587",
SMTP_USER: "",
SMTP_PASS: "",
SMTP_FROM: "erp-system@nusantara.id",
};
export async function getAllSettings(): Promise<Record<string, string>> {
export async function getAllSettings(dbClient?: PrismaClient): Promise<Record<string, string>> {
try {
const list = await prisma.systemSetting.findMany();
const db = dbClient || prisma;
const list = await db.systemSetting.findMany();
const result = { ...DEFAULT_SETTINGS };
list.forEach((item) => {
result[item.key] = item.value;
@@ -88,68 +95,186 @@ export async function sendTelegramMessage(
}
}
function escapeHtmlBasic(str: string): string {
return String(str)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function maskMoneyForStockRoles(text: string): string {
// Sembunyikan nominal Rp / $ agar divisi Gudang tidak melihat harga jual atau total omset di email
return text
.replace(/Rp\s?[0-9.,]+/gi, "[Nominal Khusus Finance/Sales]")
.replace(/\$\s?[0-9.,]+(\s?USD)?/gi, "[Nominal Khusus Finance/Purchasing]");
}
export async function sendEmailNotification(
settings: Record<string, string>,
params: {
to: string;
recipientName: string;
recipientRole: string;
type: NotificationType;
title: string;
message: string;
}
): Promise<{ status: "SENT" | "SIMULATED" | "FAILED"; error?: string }> {
const host = (settings.SMTP_HOST || "").trim();
const port = parseInt(settings.SMTP_PORT || "587", 10) || 587;
const user = (settings.SMTP_USER || "").trim();
const pass = (settings.SMTP_PASS || "").trim();
const from = (settings.SMTP_FROM || user || "erp-system@nusantara.id").trim();
// Jika SMTP belum dikonfigurasi lengkap, catat sebagai SIMULATED agar tidak error
if (!host || !user || !pass) {
return {
status: "SIMULATED",
error: "SMTP Host/User/Password belum diisi di Pengaturan — notifikasi dicatat (SIMULATED).",
};
}
const typeLabelMap: Record<NotificationType, { label: string; color: string }> = {
STOCK_IN: { label: "BARANG MASUK", color: "#059669" },
STOCK_OUT: { label: "BARANG KELUAR", color: "#d97706" },
MONEY_IN: { label: "UANG MASUK", color: "#2563eb" },
MONEY_OUT: { label: "UANG KELUAR", color: "#7c3aed" },
RMA_SERVICE: { label: "RMA / SERVICE", color: "#0284c7" },
SYSTEM: { label: "SISTEM ERP", color: "#334155" },
};
const badge = typeLabelMap[params.type] || typeLabelMap.SYSTEM;
const timeStr = new Date().toLocaleString("id-ID", { timeZone: "Asia/Jakarta" });
const html = `
<div style="font-family:Arial,Helvetica,sans-serif;background:#f8fafc;padding:24px;color:#0f172a;">
<div style="max-width:580px;margin:0 auto;background:#ffffff;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;">
<div style="background:#0f172a;color:#ffffff;padding:16px 20px;display:flex;justify-content:space-between;align-items:center;">
<div style="font-size:15px;font-weight:bold;">EnterpriseCore ERP</div>
<span style="background:${badge.color};color:#ffffff;font-size:11px;font-weight:bold;padding:3px 10px;border-radius:999px;">
${badge.label}
</span>
</div>
<div style="padding:20px;">
<p style="margin:0 0 8px;font-size:12px;color:#64748b;">
Halo <strong>${escapeHtmlBasic(params.recipientName)}</strong> (${escapeHtmlBasic(params.recipientRole)}),
</p>
<h2 style="margin:0 0 12px;font-size:16px;color:#0f172a;">
${escapeHtmlBasic(params.title)}
</h2>
<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:14px;font-size:13px;line-height:1.6;color:#334155;">
${escapeHtmlBasic(params.message).replace(/\n/g, "<br/>")}
</div>
<p style="margin:16px 0 0;font-size:11px;color:#94a3b8;">
Dikirim otomatis sesuai kapasitas peran Anda (${escapeHtmlBasic(params.recipientRole)}) • ${timeStr} WIB
</p>
</div>
</div>
</div>
`;
try {
const transporter = nodemailer.createTransport({
host,
port,
secure: port === 465,
auth: { user, pass },
connectionTimeout: 8000,
greetingTimeout: 8000,
});
await transporter.sendMail({
from: `"EnterpriseCore ERP" <${from}>`,
to: params.to,
subject: `[${badge.label}] ${params.title}`,
text: `${params.title}\n\n${params.message}\n\n-- EnterpriseCore ERP (${timeStr})`,
html,
});
return { status: "SENT" };
} catch (err: any) {
console.error("SMTP sendEmailNotification error:", err?.message || err);
return { status: "FAILED", error: err?.message || "Gagal mengirim email SMTP" };
}
}
export async function dispatchNotification({
type,
title,
message,
targetRoles,
dbClient,
}: DispatchParams) {
try {
const settings = await getAllSettings();
const db = dbClient || prisma;
const settings = await getAllSettings(db);
// 1. Cek toggle global
if (type === "STOCK_IN" && settings.NOTIF_STOCK_IN_ENABLED !== "true") return;
if (type === "STOCK_OUT" && settings.NOTIF_STOCK_OUT_ENABLED !== "true") return;
if (type === "MONEY_IN" && settings.NOTIF_MONEY_IN_ENABLED !== "true") return;
if (type === "MONEY_OUT" && settings.NOTIF_MONEY_OUT_ENABLED !== "true") return;
if (type === "RMA_SERVICE" && settings.NOTIF_RMA_ENABLED === "false") return;
const botToken = settings.TELEGRAM_BOT_TOKEN;
const telegramEnabled = settings.TELEGRAM_ENABLED === "true";
const emailEnabled = settings.EMAIL_ENABLED === "true";
// 2. Pemetaan Divisi / Role yang berhak menerima event ini:
let allowedRoles: string[] = [];
// 2. Pemetaan Divisi / Role sesuai KAPASITAS masing-masing
let baseAllowedRoles: string[] = [];
const targetDivisionChannels: string[] = [];
switch (type) {
case "STOCK_IN":
// Divisi Gudang, Pengadaan, dan Manajemen
allowedRoles = ["INVENTORY", "PURCHASING", "ADMIN", "MANAGER"];
baseAllowedRoles = ["INVENTORY", "PURCHASING", "ADMIN", "MANAGER"];
if (settings.TELEGRAM_CHAT_ID_INVENTORY) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_INVENTORY);
if (settings.TELEGRAM_CHAT_ID_PURCHASING) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_PURCHASING);
if (settings.TELEGRAM_CHAT_ID_MANAGEMENT) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_MANAGEMENT);
break;
case "STOCK_OUT":
// Divisi Gudang, Penjualan, dan Manajemen
allowedRoles = ["INVENTORY", "SALES", "ADMIN", "MANAGER"];
baseAllowedRoles = ["INVENTORY", "SALES", "ADMIN", "MANAGER"];
if (settings.TELEGRAM_CHAT_ID_INVENTORY) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_INVENTORY);
if (settings.TELEGRAM_CHAT_ID_SALES) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_SALES);
if (settings.TELEGRAM_CHAT_ID_MANAGEMENT) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_MANAGEMENT);
break;
case "MONEY_IN":
// Divisi Keuangan, Penjualan, dan Manajemen
allowedRoles = ["ACCOUNTANT", "SALES", "ADMIN", "MANAGER"];
baseAllowedRoles = ["ACCOUNTANT", "SALES", "ADMIN", "MANAGER"];
if (settings.TELEGRAM_CHAT_ID_FINANCE) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_FINANCE);
if (settings.TELEGRAM_CHAT_ID_SALES) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_SALES);
if (settings.TELEGRAM_CHAT_ID_MANAGEMENT) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_MANAGEMENT);
break;
case "MONEY_OUT":
// Divisi Keuangan, Pengadaan, dan Manajemen
allowedRoles = ["ACCOUNTANT", "PURCHASING", "ADMIN", "MANAGER"];
baseAllowedRoles = ["ACCOUNTANT", "PURCHASING", "ADMIN", "MANAGER"];
if (settings.TELEGRAM_CHAT_ID_FINANCE) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_FINANCE);
if (settings.TELEGRAM_CHAT_ID_PURCHASING) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_PURCHASING);
if (settings.TELEGRAM_CHAT_ID_MANAGEMENT) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_MANAGEMENT);
break;
case "RMA_SERVICE":
baseAllowedRoles = ["INVENTORY", "SALES", "ADMIN", "MANAGER"];
if (settings.TELEGRAM_CHAT_ID_INVENTORY) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_INVENTORY);
if (settings.TELEGRAM_CHAT_ID_SALES) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_SALES);
if (settings.TELEGRAM_CHAT_ID_MANAGEMENT) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_MANAGEMENT);
break;
case "SYSTEM":
default:
allowedRoles = ["ADMIN", "MANAGER"];
baseAllowedRoles = ["ADMIN", "MANAGER"];
if (settings.TELEGRAM_CHAT_ID_MANAGEMENT) targetDivisionChannels.push(settings.TELEGRAM_CHAT_ID_MANAGEMENT);
break;
}
// Jika pemanggil menentukan targetRoles, lakukan IRISAN ketat dengan kapasitas role (mencegah kebocoran antar divisi)
const effectiveRoles =
targetRoles && targetRoles.length > 0
? targetRoles.filter((r) => baseAllowedRoles.includes(r) && isRoleAllowedNotifType(r, type))
: baseAllowedRoles;
if (effectiveRoles.length === 0) return;
const emoji =
type === "STOCK_IN"
? "📥 [BARANG MASUK]"
@@ -159,6 +284,8 @@ export async function dispatchNotification({
? "💰 [UANG MASUK]"
: type === "MONEY_OUT"
? "💸 [UANG KELUAR]"
: type === "RMA_SERVICE"
? "🔧 [RMA / SERVICE]"
: "ℹ️ [SISTEM]";
const formattedTelegramText = `<b>${emoji} ${title}</b>\n\n${message}\n\n<i>EnterpriseCore ERP • ${new Date().toLocaleString(
@@ -167,11 +294,10 @@ export async function dispatchNotification({
// 3. Kirim ke Saluran Grup/Channel Telegram Divisi yang Ditargetkan
if (telegramEnabled && botToken && targetDivisionChannels.length > 0) {
// Hilangkan duplikasi chat ID jika ada channel yang sama
const uniqueChannels = [...new Set(targetDivisionChannels)];
for (const chatId of uniqueChannels) {
const res = await sendTelegramMessage(botToken, chatId, formattedTelegramText);
await prisma.notificationLog.create({
await db.notificationLog.create({
data: {
recipient: `Grup Divisi TG (${chatId})`,
channel: "TELEGRAM",
@@ -184,49 +310,70 @@ export async function dispatchNotification({
}
}
// 4. Kirim ke Pengguna Spesifik di Divisi Terkait (Email & Telegram Pribadi)
const users = await prisma.user.findMany({
// 4. Kirim ke Pengguna Aktif di Divisi Terkait (Email & Telegram Pribadi sesuai kapasitas role)
const users = await db.user.findMany({
where: {
role: { in: allowedRoles },
isActive: true,
role: { in: effectiveRoles },
},
});
for (const u of users) {
// Cek preferensi topik per user
// Pastikan kapasitas role + preferensi topik user mengizinkan
if (!isRoleAllowedNotifType(u.role, type)) continue;
const isSubscribedToTopic =
(type === "STOCK_IN" && u.notifStockIn) ||
(type === "STOCK_OUT" && u.notifStockOut) ||
(type === "MONEY_IN" && u.notifMoneyIn) ||
(type === "MONEY_OUT" && u.notifMoneyOut) ||
(type === "RMA_SERVICE" && (u.notifRma ?? true)) ||
type === "SYSTEM";
if (!isSubscribedToTopic) continue;
// Masking nominal uang otomatis untuk peran Gudang (INVENTORY)
const safeMessageForRole =
u.role === "INVENTORY" ? maskMoneyForStockRoles(message) : message;
const userTelegramText = `<b>${emoji} ${title}</b>\n\n${safeMessageForRole}\n\n<i>EnterpriseCore ERP • ${new Date().toLocaleString(
"id-ID"
)}</i>`;
// Kirim via Telegram Pribadi staf jika aktif
if (telegramEnabled && botToken && u.notifyTelegram && u.telegramChatId) {
const res = await sendTelegramMessage(botToken, u.telegramChatId, formattedTelegramText);
await prisma.notificationLog.create({
const res = await sendTelegramMessage(botToken, u.telegramChatId, userTelegramText);
await db.notificationLog.create({
data: {
recipient: `${u.name} [${u.role}] (TG: ${u.telegramChatId})`,
channel: "TELEGRAM",
type,
title,
message,
message: safeMessageForRole,
status: res.success ? "SENT" : "FAILED",
},
});
}
// Kirim via Email staf jika aktif
// Kirim via Email SMTP staf jika aktif
if (emailEnabled && u.notifyEmail && u.email) {
await prisma.notificationLog.create({
const mailRes = await sendEmailNotification(settings, {
to: u.email,
recipientName: u.name,
recipientRole: u.role,
type,
title,
message: safeMessageForRole,
});
await db.notificationLog.create({
data: {
recipient: `${u.name} [${u.role}] <${u.email}>`,
channel: "EMAIL",
type,
title,
message,
status: "SENT",
message: safeMessageForRole,
status: mailRes.status,
},
});
}
+101 -1
View File
@@ -10,6 +10,16 @@ export const ROLE_PERMISSIONS: Record<
Role,
{
allowedRoutes: string[];
defaultRoute: string;
accessSummary: string;
allowedNotifTypes: ("STOCK_IN" | "STOCK_OUT" | "MONEY_IN" | "MONEY_OUT" | "RMA_SERVICE" | "SYSTEM")[];
defaultNotifPrefs: {
notifStockIn: boolean;
notifStockOut: boolean;
notifMoneyIn: boolean;
notifMoneyOut: boolean;
notifRma: boolean;
};
canAddUser: boolean;
canManageProducts: boolean;
canAdjustStock: boolean;
@@ -28,6 +38,16 @@ export const ROLE_PERMISSIONS: Record<
> = {
ADMIN: {
allowedRoutes: ["/", "/inventory", "/sales", "/purchases", "/finance", "/users", "/settings"],
defaultRoute: "/",
accessSummary: "Akses penuh seluruh modul, manajemen pengguna, dan konfigurasi notifikasi.",
allowedNotifTypes: ["STOCK_IN", "STOCK_OUT", "MONEY_IN", "MONEY_OUT", "RMA_SERVICE", "SYSTEM"],
defaultNotifPrefs: {
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: true,
},
canAddUser: true,
canManageProducts: true,
canAdjustStock: true,
@@ -45,6 +65,16 @@ export const ROLE_PERMISSIONS: Record<
},
MANAGER: {
allowedRoutes: ["/", "/inventory", "/sales", "/purchases", "/finance", "/users", "/settings"],
defaultRoute: "/",
accessSummary: "Dashboard eksekutif View-Only, approval anggaran, dan pantauan seluruh divisi (tidak bisa tambah user/ubah SMTP).",
allowedNotifTypes: ["STOCK_IN", "STOCK_OUT", "MONEY_IN", "MONEY_OUT", "RMA_SERVICE", "SYSTEM"],
defaultNotifPrefs: {
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: true,
},
canAddUser: false, // Hanya ADMIN yang boleh menambah user baru!
canManageProducts: true,
canAdjustStock: true,
@@ -61,7 +91,17 @@ export const ROLE_PERMISSIONS: Record<
canViewPriceAndHpp: true,
},
INVENTORY: {
allowedRoutes: ["/", "/inventory", "/purchases", "/users"],
allowedRoutes: ["/", "/inventory", "/sales", "/purchases", "/users"],
defaultRoute: "/",
accessSummary: "Khusus operasional gudang & teknisi: stok, SN, terima barang PO, input resi/ongkir kirim, dan device service/rusak/kanibalan (tanpa akses harga jual/HPP/keuangan).",
allowedNotifTypes: ["STOCK_IN", "STOCK_OUT", "RMA_SERVICE"],
defaultNotifPrefs: {
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: false,
notifMoneyOut: false,
notifRma: true,
},
canAddUser: false,
canManageProducts: true,
canAdjustStock: true,
@@ -79,6 +119,16 @@ export const ROLE_PERMISSIONS: Record<
},
SALES: {
allowedRoutes: ["/", "/sales", "/purchases", "/inventory", "/users"],
defaultRoute: "/",
accessSummary: "Khusus penjualan, pengajuan pembelian, dan layanan RMA/service customer (tanpa akses keuangan, PPN, ongkir PO, atau pelunasan).",
allowedNotifTypes: ["STOCK_OUT", "MONEY_IN", "RMA_SERVICE"],
defaultNotifPrefs: {
notifStockIn: false,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: false,
notifRma: true,
},
canAddUser: false,
canManageProducts: false, // Sales hanya melihat katalog & cek ketersediaan stok
canAdjustStock: false,
@@ -96,6 +146,16 @@ export const ROLE_PERMISSIONS: Record<
},
PURCHASING: {
allowedRoutes: ["/", "/purchases", "/inventory", "/users"],
defaultRoute: "/",
accessSummary: "Khusus pengadaan & PO ke vendor (tanpa akses penjualan, keuangan, biaya forwarder/pajak Finance, atau harga jual).",
allowedNotifTypes: ["STOCK_IN", "MONEY_OUT"],
defaultNotifPrefs: {
notifStockIn: true,
notifStockOut: false,
notifMoneyIn: false,
notifMoneyOut: true,
notifRma: false,
},
canAddUser: false,
canManageProducts: false,
canAdjustStock: false,
@@ -113,6 +173,16 @@ export const ROLE_PERMISSIONS: Record<
},
ACCOUNTANT: {
allowedRoutes: ["/", "/finance", "/sales", "/purchases", "/users"],
defaultRoute: "/",
accessSummary: "Khusus keuangan & akuntansi: approve anggaran PO, biaya forwarder/pajak/PPN, pembayaran/DP vendor, pelunasan customer, payroll & jurnal (tanpa akses mutasi stok/pengaturan sistem).",
allowedNotifTypes: ["MONEY_IN", "MONEY_OUT"],
defaultNotifPrefs: {
notifStockIn: false,
notifStockOut: false,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: false,
},
canAddUser: false,
canManageProducts: false,
canAdjustStock: false,
@@ -152,3 +222,33 @@ export function canViewPriceAndHpp(role: string | undefined): boolean {
const userRole = (role as Role) || "SALES";
return ROLE_PERMISSIONS[userRole]?.canViewPriceAndHpp ?? false;
}
export function getDefaultLandingRoute(role: string | undefined): string {
if (!role) return "/";
const userRole = (role as Role) || "SALES";
return ROLE_PERMISSIONS[userRole]?.defaultRoute || "/";
}
export function getRoleDefaultNotifications(role: string | undefined) {
const userRole = (role as Role) || "SALES";
return (
ROLE_PERMISSIONS[userRole]?.defaultNotifPrefs || {
notifStockIn: false,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: false,
notifRma: true,
}
);
}
export function isRoleAllowedNotifType(
role: string | undefined,
notifType: "STOCK_IN" | "STOCK_OUT" | "MONEY_IN" | "MONEY_OUT" | "RMA_SERVICE" | "SYSTEM"
): boolean {
if (!role) return false;
const userRole = (role as Role) || "SALES";
const allowed = ROLE_PERMISSIONS[userRole]?.allowedNotifTypes;
if (!allowed) return false;
return allowed.includes(notifType);
}
+1 -1
View File
@@ -51,7 +51,7 @@ export function exportToCSV(
const escapeCell = (val: string | number | null | undefined) => {
let str = String(val ?? "").replace(/"/g, '""');
// Prevent CSV Formula Injection when opened in Excel
if (/^[=+\-@]/.test(str)) {
if (/^[=+\-@\t\r]/.test(str)) {
str = `'${str}`;
}
return `"${str}"`;
+14 -3
View File
@@ -1,5 +1,6 @@
import { NextResponse, type NextRequest } from "next/server";
import { jwtVerify } from "jose";
import { canAccessRoute, getDefaultLandingRoute } from "@/lib/permissions";
const SECRET_KEY = new TextEncoder().encode(
process.env.JWT_SECRET || "enterprisecore-secret-jwt-key-2026-production-ready"
@@ -7,6 +8,8 @@ const SECRET_KEY = new TextEncoder().encode(
const PUBLIC_PATHS = [
"/login",
"/rma",
"/api/public/rma",
"/api/auth/login",
"/api/auth/mfa",
"/api/auth/logout",
@@ -31,11 +34,11 @@ function applySecurityHeaders(res: NextResponse): NextResponse {
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Skip static assets and Next.js internals
// Skip static assets and Next.js internals (never bypass /api/ routes)
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/favicon") ||
pathname.includes(".")
(!pathname.startsWith("/api/") && pathname.includes("."))
) {
return applySecurityHeaders(NextResponse.next());
}
@@ -61,7 +64,15 @@ export async function middleware(req: NextRequest) {
}
try {
await jwtVerify(token, SECRET_KEY, { algorithms: ["HS256"] });
const { payload } = await jwtVerify(token, SECRET_KEY, { algorithms: ["HS256"] });
const role = typeof payload.role === "string" ? payload.role : undefined;
// Penegakan batasan halaman (RBAC) di tingkat server untuk seluruh route halaman non-API
if (!pathname.startsWith("/api/") && role && !canAccessRoute(role, pathname)) {
const fallbackUrl = new URL(getDefaultLandingRoute(role), req.url);
return applySecurityHeaders(NextResponse.redirect(fallbackUrl));
}
return applySecurityHeaders(NextResponse.next());
} catch {
if (pathname.startsWith("/api/")) {
+1
View File
@@ -1,6 +1,7 @@
import type { Config } from "tailwindcss";
const config: Config = {
darkMode: "class",
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
+1 -1
View File
@@ -1 +1 @@
{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_modules/typescript/lib/lib.es2024.d.ts","./node_modules/typescript/lib/lib.esnext.d.ts","./node_modules/typescript/lib/lib.dom.d.ts","./node_modules/typescript/lib/lib.dom.iterable.d.ts","./node_modules/typescript/lib/lib.es2015.core.d.ts","./node_modules/typescript/lib/lib.es2015.collection.d.ts","./node_modules/typescript/lib/lib.es2015.generator.d.ts","./node_modules/typescript/lib/lib.es2015.iterable.d.ts","./node_modules/typescript/lib/lib.es2015.promise.d.ts","./node_modules/typescript/lib/lib.es2015.proxy.d.ts","./node_modules/typescript/lib/lib.es2015.reflect.d.ts","./node_modules/typescript/lib/lib.es2015.symbol.d.ts","./node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts","./node_modules/typescript/lib/lib.es2016.array.include.d.ts","./node_modules/typescript/lib/lib.es2016.intl.d.ts","./node_modules/typescript/lib/lib.es2017.arraybuffer.d.ts","./node_modules/typescript/lib/lib.es2017.date.d.ts","./node_modules/typescript/lib/lib.es2017.object.d.ts","./node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts","./node_modules/typescript/lib/lib.es2017.string.d.ts","./node_modules/typescript/lib/lib.es2017.intl.d.ts","./node_modules/typescript/lib/lib.es2017.typedarrays.d.ts","./node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts","./node_modules/typescript/lib/lib.es2018.asynciterable.d.ts","./node_modules/typescript/lib/lib.es2018.intl.d.ts","./node_modules/typescript/lib/lib.es2018.promise.d.ts","./node_modules/typescript/lib/lib.es2018.regexp.d.ts","./node_modules/typescript/lib/lib.es2019.array.d.ts","./node_modules/typescript/lib/lib.es2019.object.d.ts","./node_modules/typescript/lib/lib.es2019.string.d.ts","./node_modules/typescript/lib/lib.es2019.symbol.d.ts","./node_modules/typescript/lib/lib.es2019.intl.d.ts","./node_modules/typescript/lib/lib.es2020.bigint.d.ts","./node_modules/typescript/lib/lib.es2020.date.d.ts","./node_modules/typescript/lib/lib.es2020.promise.d.ts","./node_modules/typescript/lib/lib.es2020.sharedmemory.d.ts","./node_modules/typescript/lib/lib.es2020.string.d.ts","./node_modules/typescript/lib/lib.es2020.symbol.wellknown.d.ts","./node_modules/typescript/lib/lib.es2020.intl.d.ts","./node_modules/typescript/lib/lib.es2020.number.d.ts","./node_modules/typescript/lib/lib.es2021.promise.d.ts","./node_modules/typescript/lib/lib.es2021.string.d.ts","./node_modules/typescript/lib/lib.es2021.weakref.d.ts","./node_modules/typescript/lib/lib.es2021.intl.d.ts","./node_modules/typescript/lib/lib.es2022.array.d.ts","./node_modules/typescript/lib/lib.es2022.error.d.ts","./node_modules/typescript/lib/lib.es2022.intl.d.ts","./node_modules/typescript/lib/lib.es2022.object.d.ts","./node_modules/typescript/lib/lib.es2022.string.d.ts","./node_modules/typescript/lib/lib.es2022.regexp.d.ts","./node_modules/typescript/lib/lib.es2023.array.d.ts","./node_modules/typescript/lib/lib.es2023.collection.d.ts","./node_modules/typescript/lib/lib.es2023.intl.d.ts","./node_modules/typescript/lib/lib.es2024.arraybuffer.d.ts","./node_modules/typescript/lib/lib.es2024.collection.d.ts","./node_modules/typescript/lib/lib.es2024.object.d.ts","./node_modules/typescript/lib/lib.es2024.promise.d.ts","./node_modules/typescript/lib/lib.es2024.regexp.d.ts","./node_modules/typescript/lib/lib.es2024.sharedmemory.d.ts","./node_modules/typescript/lib/lib.es2024.string.d.ts","./node_modules/typescript/lib/lib.esnext.array.d.ts","./node_modules/typescript/lib/lib.esnext.collection.d.ts","./node_modules/typescript/lib/lib.esnext.intl.d.ts","./node_modules/typescript/lib/lib.esnext.disposable.d.ts","./node_modules/typescript/lib/lib.esnext.promise.d.ts","./node_modules/typescript/lib/lib.esnext.decorators.d.ts","./node_modules/typescript/lib/lib.esnext.iterator.d.ts","./node_modules/typescript/lib/lib.esnext.float16.d.ts","./node_modules/typescript/lib/lib.esnext.error.d.ts","./node_modules/typescript/lib/lib.esnext.sharedmemory.d.ts","./node_modules/typescript/lib/lib.decorators.d.ts","./node_modules/typescript/lib/lib.decorators.legacy.d.ts","./.next/types/routes.d.ts","./node_modules/@types/react/global.d.ts","./node_modules/csstype/index.d.ts","./node_modules/@types/react/index.d.ts","./node_modules/next/dist/styled-jsx/types/css.d.ts","./node_modules/next/dist/styled-jsx/types/macro.d.ts","./node_modules/next/dist/styled-jsx/types/style.d.ts","./node_modules/next/dist/styled-jsx/types/global.d.ts","./node_modules/next/dist/styled-jsx/types/index.d.ts","./node_modules/next/dist/shared/lib/amp.d.ts","./node_moduleLine truncated
{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_modules/typescript/lib/lib.es2024.d.ts","./node_modules/typescript/lib/lib.esnext.d.ts","./node_modules/typescript/lib/lib.dom.d.ts","./node_modules/typescript/lib/lib.dom.iterable.d.ts","./node_modules/typescript/lib/lib.es2015.core.d.ts","./node_modules/typescript/lib/lib.es2015.collection.d.ts","./node_modules/typescript/lib/lib.es2015.generator.d.ts","./node_modules/typescript/lib/lib.es2015.iterable.d.ts","./node_modules/typescript/lib/lib.es2015.promise.d.ts","./node_modules/typescript/lib/lib.es2015.proxy.d.ts","./node_modules/typescript/lib/lib.es2015.reflect.d.ts","./node_modules/typescript/lib/lib.es2015.symbol.d.ts","./node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts","./node_modules/typescript/lib/lib.es2016.array.include.d.ts","./node_modules/typescript/lib/lib.es2016.intl.d.ts","./node_modules/typescript/lib/lib.es2017.arraybuffer.d.ts","./node_modules/typescript/lib/lib.es2017.date.d.ts","./node_modules/typescript/lib/lib.es2017.object.d.ts","./node_modules/typescript/lib/lib.es2017.sharedmemory.d.ts","./node_modules/typescript/lib/lib.es2017.string.d.ts","./node_modules/typescript/lib/lib.es2017.intl.d.ts","./node_modules/typescript/lib/lib.es2017.typedarrays.d.ts","./node_modules/typescript/lib/lib.es2018.asyncgenerator.d.ts","./node_modules/typescript/lib/lib.es2018.asynciterable.d.ts","./node_modules/typescript/lib/lib.es2018.intl.d.ts","./node_modules/typescript/lib/lib.es2018.promise.d.ts","./node_modules/typescript/lib/lib.es2018.regexp.d.ts","./node_modules/typescript/lib/lib.es2019.array.d.ts","./node_modules/typescript/lib/lib.es2019.object.d.ts","./node_modules/typescript/lib/lib.es2019.string.d.ts","./node_modules/typescript/lib/lib.es2019.symbol.d.ts","./node_modules/typescript/lib/lib.es2019.intl.d.ts","./node_modules/typescript/lib/lib.es2020.bigint.d.ts","./node_modules/typescript/lib/lib.es2020.date.d.ts","./node_modules/typescript/lib/lib.es2020.promise.d.ts","./node_modules/typescript/lib/lib.es2020.sharedmemory.d.ts","./node_modules/typescript/lib/lib.es2020.string.d.ts","./node_modules/typescript/lib/lib.es2020.symbol.wellknown.d.ts","./node_modules/typescript/lib/lib.es2020.intl.d.ts","./node_modules/typescript/lib/lib.es2020.number.d.ts","./node_modules/typescript/lib/lib.es2021.promise.d.ts","./node_modules/typescript/lib/lib.es2021.string.d.ts","./node_modules/typescript/lib/lib.es2021.weakref.d.ts","./node_modules/typescript/lib/lib.es2021.intl.d.ts","./node_modules/typescript/lib/lib.es2022.array.d.ts","./node_modules/typescript/lib/lib.es2022.error.d.ts","./node_modules/typescript/lib/lib.es2022.intl.d.ts","./node_modules/typescript/lib/lib.es2022.object.d.ts","./node_modules/typescript/lib/lib.es2022.string.d.ts","./node_modules/typescript/lib/lib.es2022.regexp.d.ts","./node_modules/typescript/lib/lib.es2023.array.d.ts","./node_modules/typescript/lib/lib.es2023.collection.d.ts","./node_modules/typescript/lib/lib.es2023.intl.d.ts","./node_modules/typescript/lib/lib.es2024.arraybuffer.d.ts","./node_modules/typescript/lib/lib.es2024.collection.d.ts","./node_modules/typescript/lib/lib.es2024.object.d.ts","./node_modules/typescript/lib/lib.es2024.promise.d.ts","./node_modules/typescript/lib/lib.es2024.regexp.d.ts","./node_modules/typescript/lib/lib.es2024.sharedmemory.d.ts","./node_modules/typescript/lib/lib.es2024.string.d.ts","./node_modules/typescript/lib/lib.esnext.array.d.ts","./node_modules/typescript/lib/lib.esnext.collection.d.ts","./node_modules/typescript/lib/lib.esnext.intl.d.ts","./node_modules/typescript/lib/lib.esnext.disposable.d.ts","./node_modules/typescript/lib/lib.esnext.promise.d.ts","./node_modules/typescript/lib/lib.esnext.decorators.d.ts","./node_modules/typescript/lib/lib.esnext.iterator.d.ts","./node_modules/typescript/lib/lib.esnext.float16.d.ts","./node_modules/typescript/lib/lib.esnext.error.d.ts","./node_modules/typescript/lib/lib.esnext.sharedmemory.d.ts","./node_modules/typescript/lib/lib.decorators.d.ts","./node_modules/typescript/lib/lib.decorators.legacy.d.ts","./.next/types/routes.d.ts","./node_modules/@types/react/global.d.ts","./node_modules/csstype/index.d.ts","./node_modules/@types/react/index.d.ts","./node_modules/next/dist/styled-jsx/types/css.d.ts","./node_modules/next/dist/styled-jsx/types/macro.d.ts","./node_modules/next/dist/styled-jsx/types/style.d.ts","./node_modules/next/dist/styled-jsx/types/global.d.ts","./node_modules/next/dist/styled-jsx/types/index.d.ts","./node_modules/next/dist/shared/lib/amp.d.ts","./node_moduleLine truncated