Initial clean release EnterpriseCore ERP v3.0

This commit is contained in:
Yoga Pratama committed 2026-11-27 17:04:52 +07:00
commit 5c70b9713b
69 files changed
+35339

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
+4
View File
@@ -0,0 +1,4 @@
DATABASE_URL="postgresql://erp:erppassword@db:5432/erp_db?schema=public"
JWT_SECRET="your-super-secret-jwt-key"
NEXT_PUBLIC_APP_NAME="EnterpriseCore ERP"
PORT=3000
+14
View File
@@ -0,0 +1,14 @@
node_modules/
.next/
out/
build/
dist/
.env
.env.*
*.log
.DS_Store
tsconfig.tsbuildinfo
prisma/*.db
prisma/*.db-journal
prisma/*.db-wal
prisma/*.db-shm
+33
View File
@@ -0,0 +1,33 @@
FROM node:22-alpine AS builder
WORKDIR /app
RUN apk add --no-cache openssl libc6-compat
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ENV DATABASE_URL="file:/app/data/live.db"
RUN npx prisma generate
RUN npm run build
FROM node:22-alpine AS runner
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.
+109
View File
@@ -0,0 +1,109 @@
# EnterpriseCore ERP (v3.0)
Sistem **Enterprise Resource Planning (ERP)** terpadu berbasis web untuk operasional perdagangan, distribusi, pergudangan, keuangan multi-PT, dan layanan purna jual (Service & RMA).
Dibangun dengan **Next.js 15**, **TypeScript**, **Tailwind CSS**, **Prisma ORM**, dan **SQLite**.
---
## Fitur Utama
- **Dashboard Terpersonalisasi per Role**: Ringkasan KPI, grafik tren 6 bulan, posisi **Kas & Bank per PT**, stok gudang, dan peringatan otomatis sesuai hak akses login.
- **Inventaris & Serial Number (SN)**:
- Katalog Produk & SN (stok akurat per entitas PT meski berbagi Gudang Utama).
- Riwayat Mutasi Stok masuk/keluar.
- **Upload & Template Excel (.xlsx/.csv)** untuk pencatatan SN barang masuk (PO) dan barang keluar (SO).
- Manajemen **Service & RMA** (perangkat sedang di-service, rusak total, kanibalan + daftar sparepart, dan ongkir kirim balik ditanggung user).
- **Penjualan & Pengiriman**: Sales Order (SO), alokasi stok Multi-PO FIFO, Invoice, Surat Jalan, pelacakan garansi aktif/habis, jasa service berbayar + Invoice Service, dan input resi/ongkir.
- **Pembelian (Procure-to-Pay)**: Pengajuan Barang (PR), Purchase Order (PO IDR/USD, Forwarder/PPN), Approval Finance, Penerimaan Gudang + Input SN, dan Pelacakan Batch FIFO.
- **Keuangan Multi-PT**:
- **Laporan Keuangan**: Laba Rugi (Profit & Loss), Neraca (Balance Sheet), Daftar Piutang Customer (AR) & Hutang Vendor (AP) lengkap dengan umur hari, Export Excel/CSV, dan Cetak.
- Payroll & Slip Gaji per PT, Daftar Akun (COA) terisolasi otomatis per PT, Jurnal Transaksi, dan Manajemen Perusahaan.
- **Portal RMA Customer Tanpa Login (`/rma`)**: Pengajuan & pelacakan tiket service mandiri dengan verifikasi ketat **wajib SN terdaftar di database**.
- **Notifikasi Email SMTP & Telegram per Kapasitas Role**: Routing notifikasi sesuai divisi dan sensor nominal uang otomatis untuk peran Gudang (`INVENTORY`).
- **Keamanan & Tampilan**:
- Mode Gelap (default) & Mode Terang dengan tipografi kontras tinggi + print-safe hitam putih.
- Middleware & API RBAC, Kunci Akun Aktif/Nonaktif, MFA (Google Authenticator TOTP / Telegram OTP), Auto-Logout 30 menit idle, kebijakan password kuat (min. 8 karakter huruf & angka), Rate Limiting, Masking Secret SMTP/Bot, Audit Log, serta **Backup Database Atomik (.db)** khusus Super Admin.
---
## Akun Default (Dummy per Role RBAC)
Saat aplikasi pertama kali dijalankan pada database kosong, sistem otomatis membuat **1 Gudang Utama**, **11 Akun COA standar (saldo Rp 0)** untuk `PT EnterpriseCore Utama`, dan **6 akun default** berikut:
| Role | Nama Akun | Email Login | Kata Sandi Default | Ringkasan Hak Akses |
| :--- | :--- | :--- | :--- | :--- |
| **ADMIN** | Super Admin | `admin@erp.local` | `Admin123!` | Akses penuh semua modul, manajemen pengguna, pengaturan SMTP, & backup database |
| **MANAGER** | Manager Operasional | `manager@erp.local` | `Manager123!` | Dashboard eksekutif, pantauan seluruh divisi, & persetujuan anggaran |
| **ACCOUNTANT** | Staf Keuangan | `finance@erp.local` | `Finance123!` | Laporan Keuangan (Laba Rugi/Neraca/AR-AP), Payroll, COA, Jurnal, Approval & Bayar PO/SO |
| **SALES** | Staf Sales | `sales@erp.local` | `Sales123!` | Penjualan (SO, Invoice, Surat Jalan, Garansi/RMA), Pengajuan PR, & cek stok |
| **PURCHASING** | Staf Purchasing | `purchasing@erp.local` | `Purchasing123!` | Pengadaan PO Vendor, Pengajuan PR, Batch & Alokasi, & cek stok |
| **INVENTORY** | Staf Gudang & Teknisi | `gudang@erp.local` | `Gudang123!` | Katalog & SN, Mutasi Stok, Service & RMA, Pengiriman (resi), Penerimaan PO *(tanpa nominal uang)* |
> **Penting (Keamanan Produksi):** Segera ubah email dan kata sandi seluruh akun default di menu **Pengguna** setelah aplikasi aktif, dan aktifkan **MFA (2FA)** untuk akun Admin & Keuangan.
---
## Deploy ke Portainer (Otomatis dari Git Repository)
Anda **tidak perlu compile manual** sebelum deploy ke Portainer. `Dockerfile` sudah otomatis melakukan `npm ci`, `prisma generate`, dan `npm run build`, serta `entrypoint.sh` otomatis menjalankan sinkronisasi skema database dan inisialisasi akun default jika database masih kosong.
1. Buka **Portainer** → pilih Environment → **Stacks** → **Add stack**.
2. Isi **Name**, misalnya: `enterprisecore-erp`.
3. Pada **Build method**, pilih **Repository**.
4. Isi detail repository Git Anda:
- **Repository URL**: URL repository Git Anda (contoh: `https://git.domain-anda.com/username/system-erp.git`)
- **Authentication**: aktifkan jika repo Private (masukkan Username & Access Token).
- **Repository reference**: `refs/heads/main`
- **Compose path**: `docker-compose.yml`
5. Pada bagian **Environment variables**, tambahkan variabel berikut:
- `JWT_SECRET` = *(isi string acak minimal 32 karakter, contoh hasil `openssl rand -hex 32`)*
- `TZ` = `Asia/Jakarta`
6. Klik **Deploy the stack** dan tunggu proses build selesai.
7. Setelah container berstatus **running**, akses aplikasi di:
- Aplikasi ERP: `http://<IP-SERVER>:3005`
- Portal RMA Customer (tanpa login): `http://<IP-SERVER>:3005/rma`
> **Penyimpanan Data Permanen:** Database SQLite (`live.db`) tersimpan otomatis di Docker Volume `erp_data` (`/app/data/live.db`), sehingga data tetap aman saat container di-restart atau di-redeploy.
---
## Menjalankan Secara Lokal (Tanpa Docker)
```bash
# 1. Install dependencies
npm install
# 2. Siapkan file .env
cat << 'EOF' > .env
DATABASE_URL="file:./live.db"
LIVE_DATABASE_URL="file:./live.db"
JWT_SECRET="ganti-dengan-secret-acak-minimal-32-karakter"
NEXT_PUBLIC_APP_NAME="EnterpriseCore ERP"
PORT=3005
EOF
# 3. Sinkronisasi database & buat akun default
npx prisma generate
npx prisma db push
node prisma/seed.js
# 4. Build & jalankan server produksi
npm run build
npx next start -H 0.0.0.0 -p 3005
```
### Reset Database ke Kondisi Awal (Kosong + 6 Akun Default)
```bash
node prisma/seed.js --reset
```
---
## Konfigurasi Email Notifikasi (SMTP) & Backup
1. Login sebagai **Super Admin** (`admin@erp.local`).
2. Buka menu **Pengaturan**.
3. Isi konfigurasi **SMTP Host**, **Port** (`587`/`465`), **SMTP User**, **App Password**, dan **From Email**, lalu klik **Simpan Konfigurasi** dan uji dengan tombol **Tes Kirim Email**.
4. Untuk backup database rutin, klik tombol **Unduh Backup (.db)** pada kartu **Keamanan Sistem & Backup Database** di menu **Pengaturan**.
5. Panduan lengkap operasional (PDF 5 halaman) dapat langsung dilihat melalui tombol **Panduan** di pojok kanan atas aplikasi.
+28
View File
@@ -0,0 +1,28 @@
version: "3.8"
services:
erp:
image: <REGISTRY_ANDA>/ypratama/system-erp:latest
ports:
- "3005:3005"
environment:
NODE_ENV: "production"
PORT: "3005"
DATABASE_URL: "file:/app/data/live.db"
LIVE_DATABASE_URL: "file:/app/data/live.db"
JWT_SECRET: "<GANTI_DENGAN_SECRET_ACAK_MINIMAL_32_KARAKTER>"
NEXT_PUBLIC_APP_NAME: "EnterpriseCore ERP"
TZ: "Asia/Jakarta"
volumes:
- erp_data:/app/data
deploy:
replicas: 1
placement:
constraints:
- node.role == manager
restart_policy:
condition: any
volumes:
erp_data:
driver: local
Executable
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -e
echo "==> Syncing SQLite schema..."
npx prisma db push --skip-generate
echo "==> Initializing default accounts & roles if database is empty..."
node prisma/seed.js
echo "==> Starting EnterpriseCore ERP on port ${PORT:-3005}..."
exec npx next start -H 0.0.0.0 -p "${PORT:-3005}"
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+8
View File
@@ -0,0 +1,8 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
reactStrictMode: true,
poweredByHeader: false,
};
export default nextConfig;
+2924
View File
File diff suppressed because it is too large. Load diff
+44
View File
@@ -0,0 +1,44 @@
{
"name": "enterprisecore-erp",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "prisma generate && next build",
"start": "next start",
"lint": "next lint",
"prisma:generate": "prisma generate",
"prisma:push": "prisma db push",
"prisma:seed": "node prisma/seed.js",
"db:setup": "prisma generate && prisma db push && node prisma/seed.js",
"db:sqlite": "node scripts/switch-db.js sqlite",
"db:postgres": "node scripts/switch-db.js postgres"
},
"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",
"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",
"postcss": "^8.5.1",
"prisma": "^6.2.1",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.3"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+263
View File
@@ -0,0 +1,263 @@
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
enum Role {
ADMIN
MANAGER
INVENTORY
SALES
PURCHASING
ACCOUNTANT
}
enum MovementType {
IN
OUT
ADJUSTMENT
TRANSFER
}
enum OrderStatus {
DRAFT
CONFIRMED
SHIPPED
COMPLETED
CANCELLED
}
enum PaymentStatus {
UNPAID
PARTIAL
PAID
}
enum POStatus {
DRAFT
ORDERED
RECEIVED
CANCELLED
}
enum AccountType {
ASSET
LIABILITY
EQUITY
REVENUE
EXPENSE
}
enum EntryType {
DEBIT
CREDIT
}
model User {
id String @id @default(uuid())
email String @unique
name String
password String
role Role @default(SALES)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
auditLogs AuditLog[]
}
model AuditLog {
id String @id @default(uuid())
userId String?
userName String?
action String // CREATE, UPDATE, DELETE, LOGIN, APPROVE
module String // INVENTORY, SALES, PURCHASING, FINANCE, AUTH
description String
metadata String? // JSON string for extra payload
createdAt DateTime @default(now())
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
}
model Warehouse {
id String @id @default(uuid())
code String @unique
name String
address String?
createdAt DateTime @default(now())
stockItems StockItem[]
stockMovements StockMovement[]
}
model Category {
id String @id @default(uuid())
name String @unique
description String?
products Product[]
}
model Product {
id String @id @default(uuid())
sku String @unique
name String
description String?
unit String @default("PCS") // PCS, BOX, KG, LTR, MTR
purchasePrice Float @default(0)
sellingPrice Float @default(0)
minStock Int @default(5)
categoryId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
stockItems StockItem[]
stockMovements StockMovement[]
salesItems SalesOrderItem[]
purchaseItems PurchaseOrderItem[]
}
model StockItem {
id String @id @default(uuid())
productId String
warehouseId String
quantity Int @default(0)
updatedAt DateTime @updatedAt
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Cascade)
@@unique([productId, warehouseId])
}
model StockMovement {
id String @id @default(uuid())
productId String
warehouseId String
type MovementType
quantity Int
referenceType String? // SALES_ORDER, PURCHASE_ORDER, MANUAL_ADJUSTMENT
referenceId String?
notes String?
createdAt DateTime @default(now())
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Cascade)
}
model Customer {
id String @id @default(uuid())
code String @unique
name String
company String?
email String?
phone String?
address String?
createdAt DateTime @default(now())
salesOrders SalesOrder[]
}
model SalesOrder {
id String @id @default(uuid())
orderNumber String @unique
customerId String
orderDate DateTime @default(now())
status OrderStatus @default(DRAFT)
paymentStatus PaymentStatus @default(UNPAID)
totalAmount Float @default(0)
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
items SalesOrderItem[]
}
model SalesOrderItem {
id String @id @default(uuid())
salesOrderId String
productId String
quantity Int
unitPrice Float
subtotal Float
salesOrder SalesOrder @relation(fields: [salesOrderId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
}
model Supplier {
id String @id @default(uuid())
code String @unique
name String
contactPerson String?
email String?
phone String?
address String?
createdAt DateTime @default(now())
purchaseOrders PurchaseOrder[]
}
model PurchaseOrder {
id String @id @default(uuid())
poNumber String @unique
supplierId String
orderDate DateTime @default(now())
status POStatus @default(DRAFT)
totalAmount Float @default(0)
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
supplier Supplier @relation(fields: [supplierId], references: [id], onDelete: Restrict)
items PurchaseOrderItem[]
}
model PurchaseOrderItem {
id String @id @default(uuid())
purchaseOrderId String
productId String
quantity Int
unitCost Float
subtotal Float
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
}
model Account {
id String @id @default(uuid())
code String @unique
name String
type AccountType
balance Float @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
lines JournalLine[]
}
model JournalEntry {
id String @id @default(uuid())
entryNumber String @unique
date DateTime @default(now())
description String
reference String? // Invoice #, PO #, etc.
createdAt DateTime @default(now())
lines JournalLine[]
}
model JournalLine {
id String @id @default(uuid())
journalEntryId String
accountId String
type EntryType
amount Float
journalEntry JournalEntry @relation(fields: [journalEntryId], references: [id], onDelete: Cascade)
account Account @relation(fields: [accountId], references: [id], onDelete: Restrict)
}
+488
View File
@@ -0,0 +1,488 @@
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(uuid())
email String @unique
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)
// Divisional topic subscriptions
notifStockIn Boolean @default(true)
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)
mfaSecret String?
mfaMethod String @default("TOTP")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
auditLogs AuditLog[]
}
model SystemSetting {
id String @id @default(uuid())
key String @unique
value String
category String @default("GENERAL") // TELEGRAM, EMAIL, NOTIFICATION
updatedAt DateTime @updatedAt
}
model NotificationLog {
id String @id @default(uuid())
recipient String
channel String // EMAIL, TELEGRAM
type String // STOCK_IN, STOCK_OUT, MONEY_IN, MONEY_OUT, SYSTEM
title String
message String
status String @default("SENT") // SENT, FAILED, SIMULATED
createdAt DateTime @default(now())
}
model AuditLog {
id String @id @default(uuid())
userId String?
userName String?
action String // CREATE, UPDATE, DELETE, LOGIN, APPROVE
module String // INVENTORY, SALES, PURCHASING, FINANCE, AUTH
description String
metadata String? // JSON string
createdAt DateTime @default(now())
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
}
model Warehouse {
id String @id @default(uuid())
code String @unique
name String
address String?
companyName String @default("PT EnterpriseCore Utama")
createdAt DateTime @default(now())
stockItems StockItem[]
stockMovements StockMovement[]
batches PurchaseBatch[]
}
model Category {
id String @id @default(uuid())
name String @unique
description String?
products Product[]
}
model Product {
id String @id @default(uuid())
sku String @unique
name String
description String?
isService Boolean @default(false) // true jika Layanan / Non-Fisik (Akses Internet, Bandwidth, Lisensi, Jasa)
unit String @default("PCS")
purchasePrice Float @default(0)
sellingPrice Float @default(0)
minStock Int @default(5)
categoryId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
stockItems StockItem[]
stockMovements StockMovement[]
salesItems SalesOrderItem[]
purchaseItems PurchaseOrderItem[]
requisitionItems PurchaseRequisitionItem[]
batches PurchaseBatch[]
customerPrices CustomerProductPrice[]
deviceRecords DeviceRecord[]
}
model StockItem {
id String @id @default(uuid())
productId String
warehouseId String
quantity Int @default(0)
updatedAt DateTime @updatedAt
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Cascade)
@@unique([productId, warehouseId])
}
model StockMovement {
id String @id @default(uuid())
productId String
warehouseId String
type String // IN, OUT, ADJUSTMENT, TRANSFER
outboundCategory String? // JUAL_PUTUS, MANAGED_SERVICE, OPERASIONAL
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())
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Cascade)
}
model Customer {
id String @id @default(uuid())
code String @unique
name String
company String?
email String?
phone String?
address String?
createdAt DateTime @default(now())
salesOrders SalesOrder[]
purchaseRequisitions PurchaseRequisition[]
specialPrices CustomerProductPrice[]
deviceRecords DeviceRecord[]
}
model SalesOrder {
id String @id @default(uuid())
orderNumber String @unique
invoiceNumber String?
customerPoNumber String?
customerId String
companyName String @default("PT EnterpriseCore Utama")
saleType String @default("JUAL_PUTUS") // JUAL_PUTUS, MANAGED_SERVICE
warrantyMonths Int @default(12) // Default masa garansi 12 bulan (untuk Jual Putus)
orderDate DateTime @default(now())
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?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
items SalesOrderItem[]
}
model SalesOrderItem {
id String @id @default(uuid())
salesOrderId String
productId String
quantity Int
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)
batchAllocations SalesItemBatchAllocation[]
}
model Supplier {
id String @id @default(uuid())
code String @unique
name String
contactPerson String?
email String?
phone String?
address String?
createdAt DateTime @default(now())
purchaseOrders PurchaseOrder[]
}
model PurchaseRequisition {
id String @id @default(uuid())
reqNumber String @unique
salesUserId String?
salesUserName String?
customerId String?
customerCompany String? // Nama PT / Perusahaan Customer (tersimpan di database)
customerPoRef String? // Referensi PO Customer jika ada
purpose String // Kebutuhan / Alasan pengadaan
urgency String @default("NORMAL") // LOW, NORMAL, HIGH, URGENT
companyName String @default("PT EnterpriseCore Utama") // PT internal yang mengajukan
status String @default("PENDING_PURCHASING") // PENDING_PURCHASING, PROCESSED_PO, REJECTED
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
customer Customer? @relation(fields: [customerId], references: [id], onDelete: SetNull)
items PurchaseRequisitionItem[]
purchaseOrders PurchaseOrder[]
}
model PurchaseRequisitionItem {
id String @id @default(uuid())
requisitionId String
productId String
requestedQty Int
notes String?
requisition PurchaseRequisition @relation(fields: [requisitionId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
}
model PurchaseOrder {
id String @id @default(uuid())
poNumber String @unique
requisitionId String?
supplierId String
warehouseTargetId String? // Gudang tujuan penerimaan
companyName String @default("PT EnterpriseCore Utama") // PT internal pembeli
orderDate DateTime @default(now())
status String @default("PENDING_FINANCE") // DRAFT, PENDING_FINANCE, ORDERED, RECEIVED, CANCELLED
currency String @default("IDR") // IDR, USD
exchangeRate Float @default(1)
// Rincian Biaya Pengadaan & Ekspor
logisticsMode String @default("DETAILED") // DETAILED (Rincian Terpisah) | ASSISTED_ALL_IN (Dibantu Perusahaan Lain: Ongkir + Pajak Masuk Gabung)
forwardingCompany String? // Nama Perusahaan Lain / Forwarder / Undername yang membantu
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 + PPN)
notes String?
// Approval dari Finance (Approve / Hold / Reject)
financeApprovedAt DateTime?
financeApprovedBy String?
financeNotes String?
// 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?
// Approval dari Gudang / Admin saat barang datang dari distributor
warehouseReceivedAt DateTime?
warehouseReceivedBy String?
warehouseNotes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
requisition PurchaseRequisition? @relation(fields: [requisitionId], references: [id], onDelete: SetNull)
supplier Supplier @relation(fields: [supplierId], references: [id], onDelete: Restrict)
items PurchaseOrderItem[]
batches PurchaseBatch[]
}
model PurchaseOrderItem {
id String @id @default(uuid())
purchaseOrderId String
productId String
quantity Int
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)
}
model Account {
id String @id @default(uuid())
code String
name String
type String // ASSET, LIABILITY, EQUITY, REVENUE, EXPENSE
companyName String @default("PT EnterpriseCore Utama")
balance Float @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
lines JournalLine[]
@@unique([code, companyName])
}
model JournalEntry {
id String @id @default(uuid())
entryNumber String @unique
date DateTime @default(now())
description String
reference String?
companyName String @default("PT EnterpriseCore Utama")
createdAt DateTime @default(now())
lines JournalLine[]
}
model JournalLine {
id String @id @default(uuid())
journalEntryId String
accountId String
type String // DEBIT, CREDIT
amount Float
journalEntry JournalEntry @relation(fields: [journalEntryId], references: [id], onDelete: Cascade)
account Account @relation(fields: [accountId], references: [id], onDelete: Restrict)
}
model PayrollRecord {
id String @id @default(uuid())
payrollNumber String @unique
companyName String @default("PT EnterpriseCore Utama")
employeeName String
role String
period String
workDays Int @default(22)
absentDays Int @default(0)
lateCount Int @default(0)
baseSalary Float @default(0)
dailyMealRate Float @default(0)
totalMealAllowance Float @default(0)
transportAllowance Float @default(0)
absenceDeduction Float @default(0)
netSalary Float @default(0)
paymentAccountName String?
status String @default("PAID")
notes String?
createdAt DateTime @default(now())
}
model PayrollEmployee {
id String @id @default(uuid())
name String @unique
companyName String @default("PT EnterpriseCore Utama")
position String
baseSalary Float @default(0)
dailyMealRate Float @default(35000)
createdAt DateTime @default(now())
}
// -----------------------------------------------------------------------------
// PELACAKAN STOK BATCH PO (FIFO) UNTUK PENJUALAN
// -----------------------------------------------------------------------------
model PurchaseBatch {
id String @id @default(uuid())
purchaseOrderId String
poNumber String
productId String
warehouseId String
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())
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Restrict)
allocations SalesItemBatchAllocation[]
}
model SalesItemBatchAllocation {
id String @id @default(uuid())
salesOrderItemId String
purchaseBatchId String?
poNumber String // Nomor PO sumber barang (misal: PO-2026/001)
quantity Int // Jumlah unit yang diambil dari PO ini
unitCost Float // HPP Modal per unit dari PO ini
subtotalCost Float // quantity * unitCost
createdAt DateTime @default(now())
salesOrderItem SalesOrderItem @relation(fields: [salesOrderItemId], references: [id], onDelete: Cascade)
purchaseBatch PurchaseBatch? @relation(fields: [purchaseBatchId], references: [id], onDelete: SetNull)
}
// -----------------------------------------------------------------------------
// HARGA KHUSUS PER PELANGGAN (CUSTOMER-SPECIFIC PRICING)
// -----------------------------------------------------------------------------
model CustomerProductPrice {
id String @id @default(uuid())
customerId String
productId String
specialPrice Float // Harga jual khusus yang disepakati untuk customer ini
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
customer Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
@@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)
}
+288
View File
@@ -0,0 +1,288 @@
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(uuid())
email String @unique
name String
password String
role String @default("SALES")
telegramChatId String?
notifyEmail Boolean @default(true)
notifyTelegram Boolean @default(false)
// Divisional topic subscriptions
notifStockIn Boolean @default(true)
notifStockOut Boolean @default(true)
notifMoneyIn Boolean @default(true)
notifMoneyOut Boolean @default(true)
// Multi-Factor Authentication (MFA / 2FA)
mfaEnabled Boolean @default(false)
mfaSecret String?
mfaMethod String @default("TOTP")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
auditLogs AuditLog[]
}
model SystemSetting {
id String @id @default(uuid())
key String @unique
value String
category String @default("GENERAL") // TELEGRAM, EMAIL, NOTIFICATION
updatedAt DateTime @updatedAt
}
model NotificationLog {
id String @id @default(uuid())
recipient String
channel String // EMAIL, TELEGRAM
type String // STOCK_IN, STOCK_OUT, MONEY_IN, MONEY_OUT, SYSTEM
title String
message String
status String @default("SENT") // SENT, FAILED, SIMULATED
createdAt DateTime @default(now())
}
model AuditLog {
id String @id @default(uuid())
userId String?
userName String?
action String // CREATE, UPDATE, DELETE, LOGIN, APPROVE
module String // INVENTORY, SALES, PURCHASING, FINANCE, AUTH
description String
metadata String? // JSON string
createdAt DateTime @default(now())
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
}
model Warehouse {
id String @id @default(uuid())
code String @unique
name String
address String?
createdAt DateTime @default(now())
stockItems StockItem[]
stockMovements StockMovement[]
}
model Category {
id String @id @default(uuid())
name String @unique
description String?
products Product[]
}
model Product {
id String @id @default(uuid())
sku String @unique
name String
description String?
unit String @default("PCS")
purchasePrice Float @default(0)
sellingPrice Float @default(0)
minStock Int @default(5)
categoryId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
stockItems StockItem[]
stockMovements StockMovement[]
salesItems SalesOrderItem[]
purchaseItems PurchaseOrderItem[]
}
model StockItem {
id String @id @default(uuid())
productId String
warehouseId String
quantity Int @default(0)
updatedAt DateTime @updatedAt
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Cascade)
@@unique([productId, warehouseId])
}
model StockMovement {
id String @id @default(uuid())
productId String
warehouseId String
type String // IN, OUT, ADJUSTMENT, TRANSFER
quantity Int
referenceType String? // SALES_ORDER, PURCHASE_ORDER, MANUAL_ADJUSTMENT
referenceId String?
notes String?
createdAt DateTime @default(now())
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Cascade)
}
model Customer {
id String @id @default(uuid())
code String @unique
name String
company String?
email String?
phone String?
address String?
createdAt DateTime @default(now())
salesOrders SalesOrder[]
}
model SalesOrder {
id String @id @default(uuid())
orderNumber String @unique
invoiceNumber String?
customerPoNumber String?
customerId String
orderDate DateTime @default(now())
status String @default("DRAFT") // DRAFT, CONFIRMED, SHIPPED, COMPLETED, CANCELLED
paymentStatus String @default("UNPAID") // UNPAID, PARTIAL, PAID
totalAmount Float @default(0)
totalHpp Float @default(0)
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
items SalesOrderItem[]
}
model SalesOrderItem {
id String @id @default(uuid())
salesOrderId String
productId String
quantity Int
costPrice Float @default(0)
unitPrice Float
subtotal Float
salesOrder SalesOrder @relation(fields: [salesOrderId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
}
model Supplier {
id String @id @default(uuid())
code String @unique
name String
contactPerson String?
email String?
phone String?
address String?
createdAt DateTime @default(now())
purchaseOrders PurchaseOrder[]
}
model PurchaseOrder {
id String @id @default(uuid())
poNumber String @unique
supplierId String
orderDate DateTime @default(now())
status String @default("DRAFT") // DRAFT, ORDERED, RECEIVED, COMPLETED, CANCELLED
currency String @default("IDR") // IDR, USD
exchangeRate Float @default(1)
totalAmountUsd Float?
totalAmount Float @default(0)
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
supplier Supplier @relation(fields: [supplierId], references: [id], onDelete: Restrict)
items PurchaseOrderItem[]
}
model PurchaseOrderItem {
id String @id @default(uuid())
purchaseOrderId String
productId String
quantity Int
unitCostUsd Float?
unitCost Float
subtotal Float
purchaseOrder PurchaseOrder @relation(fields: [purchaseOrderId], references: [id], onDelete: Cascade)
product Product @relation(fields: [productId], references: [id], onDelete: Restrict)
}
model Account {
id String @id @default(uuid())
code String @unique
name String
type String // ASSET, LIABILITY, EQUITY, REVENUE, EXPENSE
companyName String @default("PT EnterpriseCore Utama")
balance Float @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
lines JournalLine[]
}
model JournalEntry {
id String @id @default(uuid())
entryNumber String @unique
date DateTime @default(now())
description String
reference String?
createdAt DateTime @default(now())
lines JournalLine[]
}
model JournalLine {
id String @id @default(uuid())
journalEntryId String
accountId String
type String // DEBIT, CREDIT
amount Float
journalEntry JournalEntry @relation(fields: [journalEntryId], references: [id], onDelete: Cascade)
account Account @relation(fields: [accountId], references: [id], onDelete: Restrict)
}
model PayrollRecord {
id String @id @default(uuid())
payrollNumber String @unique
companyName String @default("PT EnterpriseCore Utama")
employeeName String
role String
period String
workDays Int @default(22)
absentDays Int @default(0)
lateCount Int @default(0)
baseSalary Float @default(0)
dailyMealRate Float @default(0)
totalMealAllowance Float @default(0)
transportAllowance Float @default(0)
absenceDeduction Float @default(0)
netSalary Float @default(0)
paymentAccountName String?
status String @default("PAID")
notes String?
createdAt DateTime @default(now())
}
model PayrollEmployee {
id String @id @default(uuid())
name String @unique
companyName String @default("PT EnterpriseCore Utama")
position String
baseSalary Float @default(0)
dailyMealRate Float @default(35000)
createdAt DateTime @default(now())
}
+231
View File
@@ -0,0 +1,231 @@
const { PrismaClient } = require("@prisma/client");
const bcrypt = require("bcryptjs");
const path = require("path");
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() {
const isReset = process.argv.includes("--reset");
const existingUsers = await prisma.user.count();
if (!isReset && existingUsers > 0) {
console.log(`Database sudah berisi ${existingUsers} pengguna. Skip seed (gunakan --reset untuk mengosongkan total).`);
return;
}
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();
}
// 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 (!exists) {
await prisma.account.create({
data: {
code: acc.code,
name: acc.name,
type: acc.type,
companyName: DEFAULT_COMPANY,
balance: 0,
},
});
}
}
// 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,
});
}
// 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("Seed error:", e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
+486
View File
@@ -0,0 +1,486 @@
const fs = require("fs");
const path = require("path");
const PDFDocument = require("pdfkit");
function generateERPGuidePDF() {
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");
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: MARGIN_TOP, bottom: 48, left: MARGIN_X, right: MARGIN_X },
bufferPages: true,
autoFirstPage: true,
});
const stream = fs.createWriteStream(outputPath);
doc.pipe(stream);
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;
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";
let cursorY = MARGIN_TOP;
function startNewPage() {
doc.addPage();
cursorY = MARGIN_TOP;
}
function ensureSpace(neededHeight) {
if (cursorY + neededHeight > MAX_Y) {
startNewPage();
}
}
function measureText(text, font, size, width, lineGap = 2) {
doc.font(font).fontSize(size);
return doc.heightOfString(text, { width, lineGap });
}
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 });
}
function drawSectionHeader(tag, title, introText) {
const introH = introText ? measureText(introText, "Helvetica", 9, CONTENT_W, 2.5) + 12 : 0;
ensureSpace(52 + introH);
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;
doc
.moveTo(MARGIN_X, cursorY)
.lineTo(PAGE_W - MARGIN_X, cursorY)
.strokeColor(BORDER)
.lineWidth(0.8)
.stroke();
cursorY += 12;
if (introText) {
const h = drawText(introText, MARGIN_X, cursorY, "Helvetica", 9, BODY, CONTENT_W, 2.5);
cursorY += h + 14;
}
}
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);
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 };
});
const totalH = padY + titleH + 6 + rowsH + padY - 2;
ensureSpace(totalH + 6);
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();
let y = topY + padY;
drawText(title, MARGIN_X + padX, y, "Helvetica-Bold", 9.2, DARK, innerW, 1.5);
y += titleH + 4;
doc
.moveTo(MARGIN_X + padX, y)
.lineTo(MARGIN_X + CONTENT_W - padX, y)
.strokeColor("#e2e8f0")
.lineWidth(0.5)
.stroke();
y += 4.5;
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;
});
cursorY = topY + totalH + 6.5;
}
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;
ensureSpace(totalH);
drawText(heading, MARGIN_X, cursorY, "Helvetica-Bold", 10, DARK, innerW, 2);
cursorY += hHead + 2;
if (subtitle) {
const sh = drawText(subtitle, MARGIN_X, cursorY, "Helvetica-Bold", 8.2, EMERALD, innerW, 1.5);
cursorY += sh + 4;
}
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);
});
}
// =========================================================================
// HALAMAN 1: SAMPUL & STRUKTUR MENU APLIKASI
// =========================================================================
doc.rect(0, 0, PAGE_W, 178).fill(DARK);
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.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;
});
// =========================================================================
// HALAMAN 2: BAB 1 - MATRIKS HAK AKSES, KEBIJAKAN UANG & EMAIL
// =========================================================================
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."
);
const roles = [
{
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. 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: "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: "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: "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: "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 },
],
},
];
roles.forEach((r) => drawInfoCard(r.title, r.rows));
// =========================================================================
// 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();
const totalPages = range.count;
for (let i = range.start; i < range.start + totalPages; i++) {
doc.switchToPage(i);
const footerLineY = PAGE_H - 36;
const footerTextY = PAGE_H - 28;
doc
.moveTo(MARGIN_X, footerLineY)
.lineTo(PAGE_W - MARGIN_X, footerLineY)
.strokeColor(BORDER)
.lineWidth(0.5)
.stroke();
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 v3.0 rapi berhasil dibuat (${totalPages} halaman) di: ${outputPath}`);
try {
fs.copyFileSync(outputPath, rootOutputPath);
console.log(`Salinan PDF disinkronkan ke: ${rootOutputPath}`);
} catch (e) {
console.error("Gagal menyalin ke root:", e);
}
});
}
generateERPGuidePDF();
+53
View File
@@ -0,0 +1,53 @@
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const target = process.argv[2]?.toLowerCase() || 'sqlite';
const rootDir = path.resolve(__dirname, '..');
const prismaDir = path.join(rootDir, 'prisma');
const envPath = path.join(rootDir, '.env');
if (target === 'sqlite') {
console.log('🔄 Mengalihkan database ke SQLite (Zero-dependency local database)...');
fs.copyFileSync(
path.join(prismaDir, 'schema.sqlite.prisma'),
path.join(prismaDir, 'schema.prisma')
);
let envContent = fs.readFileSync(envPath, 'utf8');
envContent = envContent.replace(
/DATABASE_URL=.*/,
'DATABASE_URL="file:./dev.db"'
);
fs.writeFileSync(envPath, envContent);
console.log('📦 Menghasilkan Prisma Client & migrasi SQLite dev.db...');
execSync('npx prisma generate', { stdio: 'inherit', cwd: rootDir });
execSync('npx prisma db push --skip-generate', { stdio: 'inherit', cwd: rootDir });
console.log('🌱 Melakukan seeding data awal...');
execSync('node prisma/seed.js', { stdio: 'inherit', cwd: rootDir });
console.log('✅ Berhasil beralih ke SQLite! Database lokal dev.db siap dipakai.');
} else if (target === 'postgres') {
console.log('🔄 Mengalihkan database ke PostgreSQL...');
fs.copyFileSync(
path.join(prismaDir, 'schema.postgres.prisma'),
path.join(prismaDir, 'schema.prisma')
);
let envContent = fs.readFileSync(envPath, 'utf8');
envContent = envContent.replace(
/DATABASE_URL=.*/,
'DATABASE_URL="postgresql://erp:erppassword@localhost:5432/erp_db?schema=public"'
);
fs.writeFileSync(envPath, envContent);
console.log('📦 Menghasilkan Prisma Client untuk PostgreSQL...');
execSync('npx prisma generate', { stdio: 'inherit', cwd: rootDir });
console.log('✅ Skema siap untuk PostgreSQL. Pastikan container PostgreSQL aktif (docker compose up -d db).');
} else {
console.log('Pilihan tidak dikenal. Gunakan: node scripts/switch-db.js [sqlite|postgres]');
}
+202
View File
@@ -0,0 +1,202 @@
import crypto from "crypto";
import { NextResponse } from "next/server";
import { getPrismaByMode, type EnvMode } from "@/lib/db";
import {
comparePassword,
signToken,
checkRateLimit,
recordFailedAttempt,
clearRateLimit,
getAuthCookieOptions,
} from "@/lib/auth";
import {
generateMfaSecret,
getOtpAuthUri,
signMfaChallenge,
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 } = await req.json();
const mode: EnvMode = "LIVE";
if (!email || !password) {
return NextResponse.json(
{ error: "Email dan password wajib diisi" },
{ status: 400 }
);
}
const cleanEmail = String(email).toLowerCase().trim();
const ip =
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
req.headers.get("x-real-ip") ||
"local";
const rateKey = `login:${mode}:${ip}:${cleanEmail}`;
const rateStatus = checkRateLimit(rateKey);
if (!rateStatus.allowed) {
return NextResponse.json(
{
error: `Terlalu banyak percobaan login yang gagal. Silakan tunggu ${rateStatus.retryAfterSec} detik sebelum mencoba kembali.`,
},
{ status: 429 }
);
}
const db = getPrismaByMode(mode);
const user = await db.user.findUnique({
where: { email: cleanEmail },
});
if (!user) {
recordFailedAttempt(rateKey);
return NextResponse.json(
{ error: "Email atau kata sandi tidak valid" },
{ status: 401 }
);
}
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);
return NextResponse.json(
{ error: "Email atau kata sandi tidak valid" },
{ status: 401 }
);
}
clearRateLimit(rateKey);
// Check if MFA (2FA) is enabled for this user
if (user.mfaEnabled) {
let storedSecret = user.mfaSecret;
if (!storedSecret) {
storedSecret = `PENDING:${generateMfaSecret()}`;
await db.user.update({
where: { id: user.id },
data: { mfaSecret: storedSecret },
});
}
const isFirstTimeSetup = storedSecret.startsWith("PENDING:");
const rawSecret = storedSecret.replace(/^PENDING:/, "");
let otpHash: string | undefined;
// Send OTP via Telegram if method is TELEGRAM (never store plaintext OTP inside JWT!)
if (user.mfaMethod === "TELEGRAM") {
const dynamicOtp = crypto.randomInt(100000, 1000000).toString();
otpHash = hashDynamicOtp(dynamicOtp);
try {
const settings = await getAllSettings();
const botToken = settings.TELEGRAM_BOT_TOKEN;
const targetChatId = user.telegramChatId || settings.TELEGRAM_CHAT_ID;
if (botToken && targetChatId) {
await sendTelegramMessage(
botToken,
targetChatId,
`🔐 <b>KODE VERIFIKASI LOGIN MFA (ERP)</b>\n\nHalo <b>${user.name}</b>,\nKode OTP Login 2-Langkah Anda adalah:\n\n<code>${dynamicOtp}</code>\n\n<i>Kode ini berlaku selama 5 menit. Jangan berikan kode ini kepada siapa pun.</i>`
);
}
await db.notificationLog.create({
data: {
type: "SYSTEM",
channel: "TELEGRAM",
recipient: user.email,
title: "Kode Verifikasi Login MFA (2FA)",
message: `Kode OTP MFA dikirim ke Telegram untuk ${user.email}`,
status: "SENT",
},
});
} catch (e) {
console.error("Failed to dispatch MFA notification:", e);
}
}
const mfaToken = await signMfaChallenge({
userId: user.id,
email: user.email,
envMode: mode,
mfaMethod: user.mfaMethod || "TOTP",
otpHash,
});
return NextResponse.json({
requireMfa: true,
isFirstTimeSetup,
mfaToken,
mfaMethod: user.mfaMethod || "TOTP",
email: user.email,
...(isFirstTimeSetup
? {
mfaSecret: rawSecret,
otpAuthUri: getOtpAuthUri(user.email, rawSecret),
}
: {}),
});
}
const sessionUser = {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
envMode: mode,
};
const token = await signToken(sessionUser);
await db.auditLog.create({
data: {
userId: user.id,
userName: user.name,
action: "LOGIN",
module: "AUTH",
description: `Pengguna ${user.name} (${user.role}) berhasil login ke sistem`,
},
});
const response = NextResponse.json({
success: true,
user: sessionUser,
defaultRoute: getDefaultLandingRoute(user.role),
});
const cookieOptions = getAuthCookieOptions(req);
response.cookies.set("erp_session", token, cookieOptions);
response.cookies.set("erp_env", mode, cookieOptions);
return response;
} catch (error: any) {
console.error("Login API error:", error);
return NextResponse.json(
{ error: "Gagal memproses autentikasi: " + error.message },
{ status: 500 }
);
}
}
+8
View File
@@ -0,0 +1,8 @@
import { NextResponse } from "next/server";
export async function POST() {
const response = NextResponse.json({ success: true });
response.cookies.delete("erp_session");
response.cookies.delete("erp_env");
return response;
}
+136
View File
@@ -0,0 +1,136 @@
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { ensureCompanyAccounts, getSavedCompanies } from "@/lib/companies";
export async function GET() {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ user: null }, { status: 401 });
}
const companies = await getSavedCompanies();
return NextResponse.json({ user, companies });
}
export async function POST(req: Request) {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
const body = await req.json();
// User Finance, Manager, dan Admin di menu keuangan bisa View & Add PT
if (body.action === "ADD_COMPANY") {
if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(currentUser.role)) {
return NextResponse.json(
{ error: "Akses ditolak: Hanya Finance, Manager, dan Admin yang dapat menambah Entitas PT." },
{ status: 403 }
);
}
const cleanComp = (body.companyName || "").trim();
if (!cleanComp) {
return NextResponse.json({ error: "Nama PT wajib diisi" }, { status: 400 });
}
const list = await getSavedCompanies();
if (!list.includes(cleanComp)) {
list.push(cleanComp);
}
await prisma.systemSetting.upsert({
where: { key: "PAYROLL_COMPANIES" },
update: { value: JSON.stringify(list) },
create: {
key: "PAYROLL_COMPANIES",
value: JSON.stringify(list),
category: "FINANCE",
},
});
await ensureCompanyAccounts(cleanComp);
return NextResponse.json({ success: true, companies: list, added: cleanComp });
}
// HANYA SUPERADMIN (ADMIN) YANG BISA HAPUS PT
if (body.action === "DELETE_COMPANY") {
if (currentUser.role !== "ADMIN") {
return NextResponse.json(
{
error:
"Akses ditolak: Hanya Super Admin yang dapat menghapus Entitas PT. Selain Super Admin hanya dapat melihat (view) dan menambah (add) PT.",
},
{ status: 403 }
);
}
const targetComp = (body.companyName || "").trim();
if (!targetComp) {
return NextResponse.json(
{ error: "Nama PT yang akan dihapus wajib dipilih" },
{ status: 400 }
);
}
const currentList = await getSavedCompanies();
const updatedList = currentList.filter((c) => c !== targetComp);
if (updatedList.length === 0) {
return NextResponse.json(
{
error:
"Tidak dapat menghapus satu-satunya Entitas PT yang tersisa. Tambahkan PT lain terlebih dahulu sebelum menghapus PT ini.",
},
{ status: 400 }
);
}
const fallbackCompany = updatedList[0];
// Simpan daftar PT terbaru dan pindahkan referensi PT yang dihapus ke PT utama yang tersisa
await Promise.all([
prisma.systemSetting.upsert({
where: { key: "PAYROLL_COMPANIES" },
update: { value: JSON.stringify(updatedList) },
create: {
key: "PAYROLL_COMPANIES",
value: JSON.stringify(updatedList),
category: "FINANCE",
},
}),
prisma.account.updateMany({
where: { companyName: targetComp },
data: { companyName: fallbackCompany },
}),
prisma.payrollEmployee.updateMany({
where: { companyName: targetComp },
data: { companyName: fallbackCompany },
}),
prisma.payrollRecord.updateMany({
where: { companyName: targetComp },
data: { companyName: fallbackCompany },
}),
]);
return NextResponse.json({
success: true,
companies: updatedList,
deleted: targetComp,
fallbackCompany,
});
}
return NextResponse.json({ error: "Aksi tidak dikenali" }, { status: 400 });
} 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 }
);
}
+185
View File
@@ -0,0 +1,185 @@
import { NextResponse } from "next/server";
import { getPrismaByMode, prisma } from "@/lib/db";
import {
getCurrentUser,
signToken,
checkRateLimit,
recordFailedAttempt,
clearRateLimit,
getAuthCookieOptions,
} from "@/lib/auth";
import {
generateMfaSecret,
getOtpAuthUri,
verifyMfaChallenge,
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) {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
const { searchParams } = new URL(req.url);
const targetUserId = searchParams.get("userId") || currentUser.id;
const regenerate = searchParams.get("regenerate") === "true";
if (targetUserId !== currentUser.id && currentUser.role !== "ADMIN") {
return NextResponse.json({ error: "Akses ditolak" }, { status: 403 });
}
const user = await prisma.user.findUnique({
where: { id: targetUserId },
});
if (!user) {
return NextResponse.json({ error: "Pengguna tidak ditemukan" }, { status: 404 });
}
let storedSecret = user.mfaSecret;
if (!storedSecret || regenerate) {
storedSecret = `PENDING:${generateMfaSecret()}`;
await prisma.user.update({
where: { id: user.id },
data: { mfaSecret: storedSecret },
});
}
const isPending = storedSecret.startsWith("PENDING:");
const rawSecret = storedSecret.replace(/^PENDING:/, "");
const otpAuthUri = getOtpAuthUri(user.email, rawSecret);
// Keamanan: Hanya tampilkan secret key pada saat pendaftaran pertama (PENDING) atau saat reset/regenerate
return NextResponse.json({
mfaEnabled: user.mfaEnabled,
mfaMethod: user.mfaMethod || "TOTP",
isFirstTimeSetup: isPending,
...(isPending || regenerate
? {
mfaSecret: rawSecret,
otpAuthUri,
}
: {}),
});
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
// POST: Verify 6-digit MFA code during login (and complete first-time enrollment if PENDING)
export async function POST(req: Request) {
try {
const { mfaToken, code } = await req.json();
if (!mfaToken || !code) {
return NextResponse.json(
{ error: "Token sesi MFA dan kode 6-digit wajib diisi" },
{ status: 400 }
);
}
const challenge = await verifyMfaChallenge(mfaToken);
if (!challenge) {
return NextResponse.json(
{ error: "Sesi verifikasi MFA telah kedaluwarsa. Silakan login ulang." },
{ status: 401 }
);
}
const ip =
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
req.headers.get("x-real-ip") ||
"local";
const rateKey = `mfa:${challenge.envMode}:${ip}:${challenge.userId}`;
const rateStatus = checkRateLimit(rateKey);
if (!rateStatus.allowed) {
return NextResponse.json(
{
error: `Terlalu banyak percobaan OTP yang salah. Silakan tunggu ${rateStatus.retryAfterSec} detik sebelum mencoba kembali.`,
},
{ status: 429 }
);
}
const db = getPrismaByMode(challenge.envMode);
const user = await db.user.findUnique({
where: { id: challenge.userId },
});
if (!user || user.isActive === false) {
return NextResponse.json(
{ error: "Akun tidak ditemukan atau sedang dinonaktifkan oleh Administrator." },
{ status: 403 }
);
}
const rawSecret = (user.mfaSecret || "").replace(/^PENDING:/, "");
const cleanCode = String(code).trim();
const isTotpValid = rawSecret ? verifyTOTP(rawSecret, cleanCode) : false;
const isDynamicValid =
challenge.mfaMethod === "TELEGRAM" &&
verifyDynamicOtpHash(cleanCode, challenge.otpHash);
if (!isTotpValid && !isDynamicValid) {
recordFailedAttempt(rateKey);
return NextResponse.json(
{ error: "Kode verifikasi MFA (6-digit) tidak sesuai atau sudah kedaluwarsa" },
{ status: 401 }
);
}
clearRateLimit(rateKey);
// Jika ini adalah aktivasi MFA pertama kali (PENDING), tandai sudah terhubung (hapus prefix PENDING:)
if (user.mfaSecret && user.mfaSecret.startsWith("PENDING:")) {
await db.user.update({
where: { id: user.id },
data: { mfaSecret: rawSecret },
});
}
const sessionUser = {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
envMode: challenge.envMode,
};
const token = await signToken(sessionUser);
await db.auditLog.create({
data: {
userId: user.id,
userName: user.name,
action: "LOGIN_MFA",
module: "AUTH",
description: `Pengguna ${user.name} (${user.role}) berhasil login dengan verifikasi 2-langkah (MFA)`,
},
});
const response = NextResponse.json({
success: true,
user: sessionUser,
defaultRoute: getDefaultLandingRoute(user.role),
});
const cookieOptions = getAuthCookieOptions(req);
response.cookies.set("erp_session", token, cookieOptions);
response.cookies.set("erp_env", challenge.envMode, cookieOptions);
return response;
} catch (error: any) {
console.error("MFA Verify error:", error);
return NextResponse.json(
{ error: "Gagal memverifikasi MFA: " + error.message },
{ status: 500 }
);
}
}
+383
View File
@@ -0,0 +1,383 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
import { canViewPriceAndHpp } from "@/lib/permissions";
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,
allSalesOrders,
allPurchaseOrders,
cashAccounts,
deviceRecords,
allBatches,
] = await Promise.all([
prisma.product.findMany({
include: {
stockItems: {
include: { warehouse: true },
},
},
}),
prisma.stockMovement.findMany({
where: companyWhere,
orderBy: { createdAt: "desc" },
include: {
product: true,
warehouse: true,
},
}),
prisma.salesOrder.findMany({
where: {
status: { not: "CANCELLED" },
...companyWhere,
},
include: { customer: true },
orderBy: { createdAt: "desc" },
}),
prisma.purchaseOrder.findMany({
where: {
status: { notIn: ["CANCELLED", "REJECTED"] },
...companyWhere,
},
include: { supplier: true },
orderBy: { createdAt: "desc" },
}),
prisma.account.findMany({
where: {
type: "ASSET",
code: { startsWith: "10" },
...companyWhere,
},
}),
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: {
id: string;
sku: string;
name: string;
currentStock: number;
minStock: number;
unit: string;
}[] = [];
products.forEach((p) => {
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;
if (units <= p.minStock) {
lowStockAlerts.push({
id: p.id,
sku: p.sku,
name: p.name,
currentStock: units,
minStock: p.minStock,
unit: p.unit,
});
}
});
// 2. Keluar-Masuk Barang
let stockInUnits = 0;
let stockInCount = 0;
let stockOutUnits = 0;
let stockOutCount = 0;
stockMovements.forEach((m) => {
if (m.type === "IN" || (m.type === "ADJUSTMENT" && m.quantity > 0)) {
stockInUnits += Math.abs(m.quantity);
stockInCount += 1;
} else if (m.type === "OUT" || (m.type === "ADJUSTMENT" && m.quantity < 0)) {
stockOutUnits += Math.abs(m.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;
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);
// 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 }[] = [];
for (let i = 5; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
const m = d.getMonth();
const y = d.getFullYear();
trendMonths.push({
year: y,
month: m,
key: `${y}-${String(m + 1).padStart(2, "0")}`,
label: `${monthNames[m]} ${y}`,
});
}
const monthlyTrends = trendMonths.map((tm) => {
let sales = 0;
let hpp = 0;
let purchases = 0;
let sIn = 0;
let sOut = 0;
allSalesOrders.forEach((s) => {
const d = new Date(s.createdAt);
if (d.getFullYear() === tm.year && d.getMonth() === tm.month) {
sales += s.totalAmount || 0;
hpp += s.totalHpp || 0;
}
});
allPurchaseOrders.forEach((p) => {
const d = new Date(p.createdAt);
if (d.getFullYear() === tm.year && d.getMonth() === tm.month) {
purchases += p.totalAmount || 0;
}
});
stockMovements.forEach((m) => {
const d = new Date(m.createdAt);
if (d.getFullYear() === tm.year && d.getMonth() === tm.month) {
if (m.type === "IN" || (m.type === "ADJUSTMENT" && m.quantity > 0)) {
sIn += Math.abs(m.quantity);
} else if (m.type === "OUT" || (m.type === "ADJUSTMENT" && m.quantity < 0)) {
sOut += Math.abs(m.quantity);
}
}
});
const effectiveHpp = hpp > 0 ? hpp : 0;
return {
key: tm.key,
label: tm.label,
sales: canSeeSalesMoney ? sales : 0,
purchases: canSeePurchaseMoney ? purchases : 0,
hpp: canSeeSalesMoney ? effectiveHpp : 0,
grossProfit: canSeeSalesMoney ? sales - effectiveHpp : 0,
stockInUnits: sIn,
stockOutUnits: sOut,
};
});
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 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 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: 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.filter((p) => !p.isService).length,
stockInUnits,
stockInCount,
stockOutUnits,
stockOutCount,
totalCashBank: canSeeFinance ? totalCashBank : 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,
},
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);
return NextResponse.json(
{ error: "Gagal memuat data dashboard: " + error.message },
{ status: 500 }
);
}
}
+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 });
}
}
File diff suppressed because it is too large. Load diff
+742
View File
@@ -0,0 +1,742 @@
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";
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();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
const canSeePrices = canViewPriceAndHpp(user.role);
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,
},
}),
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 },
},
},
}),
]);
// 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>>();
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);
}
}
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
.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, saleType: true },
})
: [];
const soMap = new Map(relatedSOs.map((so) => [so.orderNumber, so]));
const movements = rawMovements.map((m) => {
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,
};
});
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,
};
});
const companies = await getSavedCompanies();
return NextResponse.json({
products: formattedProducts,
warehouses,
categories,
movements,
companies,
canSeePrices,
});
} catch (error: any) {
console.error("Inventory 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 });
}
// Role check: ADMIN, MANAGER, INVENTORY, SALES, PURCHASING can add products/services
if (!["ADMIN", "MANAGER", "INVENTORY", "SALES", "PURCHASING"].includes(user.role)) {
return NextResponse.json(
{
error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang untuk menambahkan produk/layanan baru.`,
},
{ status: 403 }
);
}
const body = await req.json();
if (body.action === "CREATE_WAREHOUSE") {
const name = (body.name || "").trim();
const address = (body.location || body.address || "Pusat").trim();
const companyName = (body.companyName || "").trim() || "PT EnterpriseCore Utama";
if (!name) {
return NextResponse.json({ error: "Nama gudang wajib diisi" }, { status: 400 });
}
const wCount = await prisma.warehouse.count();
const code = `WH-${String(wCount + 1).padStart(2, "0")}`;
const warehouse = await prisma.warehouse.create({
data: { code, name, address, companyName },
});
return NextResponse.json({ success: true, warehouse });
}
if (body.action === "CREATE_CATEGORY") {
const name = (body.name || "").trim();
if (!name) {
return NextResponse.json({ error: "Nama kategori wajib diisi" }, { status: 400 });
}
const category = await prisma.category.upsert({
where: { name },
update: {},
create: { name, description: body.description || null },
});
return NextResponse.json({ success: true, category });
}
const {
sku,
name,
description,
isService: rawIsService,
unit,
purchasePrice,
sellingPrice,
minStock,
categoryId,
warehouseId: rawWhId,
initialQuantity,
initialSerialNumbers,
} = body;
const defaultWh = await prisma.warehouse.findFirst();
const warehouseId = rawWhId || defaultWh?.id;
const isService = Boolean(rawIsService);
if (!sku || !name) {
return NextResponse.json(
{ error: "SKU dan Nama Produk/Layanan wajib diisi" },
{ status: 400 }
);
}
const existing = await prisma.product.findUnique({ where: { sku } });
if (existing) {
return NextResponse.json(
{ error: `Item dengan SKU ${sku} sudah terdaftar` },
{ status: 400 }
);
}
const product = await prisma.product.create({
data: {
sku: sku.toUpperCase().trim(),
name: name.trim(),
description: description ? String(description).trim() : null,
isService,
unit: unit || (isService ? "PAKET" : "PCS"),
purchasePrice: Math.max(0, parseFloat(purchasePrice) || 0),
sellingPrice: Math.max(0, parseFloat(sellingPrice) || 0),
minStock: isService ? 0 : Math.max(0, isNaN(parseInt(minStock)) ? 0 : parseInt(minStock)),
categoryId: categoryId || null,
},
});
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,
warehouseId,
quantity: qty,
},
});
await prisma.stockMovement.create({
data: {
productId: product.id,
warehouseId,
type: "IN",
quantity: qty,
referenceType: "INITIAL_STOCK",
serialNumbers: cleanInitialSn,
notes: `Inisialisasi stok awal produk baru${cleanInitialSn ? ` (SN: ${cleanInitialSn})` : ""}`,
},
});
}
await logAudit({
userId: user.id,
userName: user.name,
action: "CREATE_PRODUCT",
module: "INVENTORY",
description: `[${user.role}] Menambahkan produk baru: ${product.name} (SKU: ${product.sku})`,
metadata: { sku: product.sku, initialQty: initialQuantity },
});
return NextResponse.json({ success: true, product });
} catch (error: any) {
console.error("Inventory 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 });
}
// Role check: Only ADMIN, MANAGER, INVENTORY can adjust stock
if (!["ADMIN", "MANAGER", "INVENTORY"].includes(user.role)) {
return NextResponse.json(
{
error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang untuk mengubah stok barang secara manual.`,
},
{ status: 403 }
);
}
const body = await req.json();
if (body.action === "UPDATE_PRODUCT") {
const {
productId,
name,
sku,
categoryId,
unit,
minStock,
purchasePrice,
sellingPrice,
description,
} = body;
if (!productId) {
return NextResponse.json({ error: "ID Produk wajib ada" }, { status: 400 });
}
const existing = await prisma.product.findUnique({ where: { id: productId } });
if (!existing) {
return NextResponse.json({ error: "Produk tidak ditemukan" }, { status: 404 });
}
if (sku && sku !== existing.sku) {
const skuTaken = await prisma.product.findUnique({ where: { sku: sku.trim().toUpperCase() } });
if (skuTaken) {
return NextResponse.json({ error: `SKU ${sku} sudah digunakan oleh produk lain` }, { status: 400 });
}
}
const allowPriceUpdate = canViewPriceAndHpp(user.role);
const updated = await prisma.product.update({
where: { id: productId },
data: {
...(name && { name: name.trim() }),
...(sku && { sku: sku.trim().toUpperCase() }),
...(categoryId !== undefined && { categoryId: categoryId || null }),
...(unit && { unit: unit.trim().toUpperCase() }),
...(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 }),
},
});
await logAudit({
userId: user.id,
userName: user.name,
action: "UPDATE",
module: "INVENTORY",
description: `[${user.role}] Memperbarui data produk ${updated.name} (${updated.sku}): Harga Jual=${updated.sellingPrice}, HPP=${updated.purchasePrice}`,
metadata: { productId, updated },
});
return NextResponse.json({ success: true, product: updated });
}
if (body.action === "MERGE_PRODUCTS") {
const { sourceProductId, targetProductId } = body;
if (!sourceProductId || !targetProductId) {
return NextResponse.json({ error: "Pilih produk sumber dan target untuk digabungkan" }, { status: 400 });
}
if (sourceProductId === targetProductId) {
return NextResponse.json({ error: "Produk sumber dan target tidak boleh sama" }, { status: 400 });
}
const [source, target] = await Promise.all([
prisma.product.findUnique({ where: { id: sourceProductId }, include: { stockItems: true } }),
prisma.product.findUnique({ where: { id: targetProductId }, include: { stockItems: true } }),
]);
if (!source || !target) {
return NextResponse.json({ error: "Salah satu produk tidak ditemukan" }, { status: 404 });
}
// 1. Pindahkan stok fisik ke target
for (const sStock of source.stockItems) {
if (sStock.quantity > 0) {
await prisma.stockItem.upsert({
where: { productId_warehouseId: { productId: target.id, warehouseId: sStock.warehouseId } },
update: { quantity: { increment: sStock.quantity } },
create: { productId: target.id, warehouseId: sStock.warehouseId, quantity: sStock.quantity },
});
}
}
await prisma.stockItem.deleteMany({ where: { productId: source.id } });
// 2. Pindahkan relasi batch, mutasi, purchase order, dan sales order
await prisma.purchaseBatch.updateMany({
where: { productId: source.id },
data: { productId: target.id },
});
await prisma.stockMovement.updateMany({
where: { productId: source.id },
data: { productId: target.id },
});
await prisma.purchaseOrderItem.updateMany({
where: { productId: source.id },
data: { productId: target.id },
});
await prisma.purchaseRequisitionItem.updateMany({
where: { productId: source.id },
data: { productId: target.id },
});
await prisma.salesOrderItem.updateMany({
where: { productId: source.id },
data: { productId: target.id },
});
// Pindahkan harga khusus pelanggan (customerProductPrice) dengan aman tanpa melanggar unique constraint
const sourcePrices = await prisma.customerProductPrice.findMany({
where: { productId: source.id },
});
for (const sp of sourcePrices) {
const existingTargetPrice = await prisma.customerProductPrice.findUnique({
where: {
customerId_productId: {
customerId: sp.customerId,
productId: target.id,
},
},
});
if (existingTargetPrice) {
// Jika target sudah punya harga khusus untuk customer ini, hapus data lama dari source
await prisma.customerProductPrice.delete({ where: { id: sp.id } });
} else {
// Pindahkan harga khusus source ke target
await prisma.customerProductPrice.update({
where: { id: sp.id },
data: { productId: target.id },
});
}
}
// 3. Catat mutasi penggabungan
const defaultWh = await prisma.warehouse.findFirst();
const transferredQty = source.stockItems.reduce((acc, s) => acc + s.quantity, 0);
if (transferredQty > 0) {
await prisma.stockMovement.create({
data: {
productId: target.id,
warehouseId: defaultWh?.id || "",
type: "IN",
quantity: transferredQty,
referenceType: "PRODUCT_MERGE",
referenceId: source.sku,
notes: `Penggabungan produk duplikat: Memindahkan ${transferredQty} ${source.unit} dari ${source.name} (${source.sku}) ke ${target.name} (${target.sku})`,
},
});
}
// 4. Hapus produk duplikat
await prisma.product.delete({ where: { id: source.id } });
await logAudit({
userId: user.id,
userName: user.name,
action: "MERGE_PRODUCTS",
module: "INVENTORY",
description: `[${user.role}] Menggabungkan produk duplikat ${source.name} (${source.sku}) ke ${target.name} (${target.sku})`,
});
return NextResponse.json({
success: true,
message: `Produk ${source.name} (${source.sku}) berhasil digabungkan ke ${target.name} (${target.sku})`,
});
}
const { productId, warehouseId: rawWhId, type, quantity, notes, outboundCategory, serialNumbers } = body;
const defaultWh = await prisma.warehouse.findFirst();
const warehouseId = rawWhId || defaultWh?.id;
if (!productId || !warehouseId || !quantity || quantity <= 0) {
return NextResponse.json(
{ error: "Parameter penyesuaian stok tidak valid" },
{ status: 400 }
);
}
const qty = parseInt(quantity);
if (isNaN(qty) || qty <= 0) {
return NextResponse.json(
{ error: "Jumlah kuantitas harus berupa bilangan bulat positif" },
{ status: 400 }
);
}
let stockItem = await prisma.stockItem.findUnique({
where: {
productId_warehouseId: { productId, warehouseId },
},
});
if (!stockItem) {
stockItem = await prisma.stockItem.create({
data: {
productId,
warehouseId,
quantity: 0,
},
});
}
let newQuantity = stockItem.quantity;
if (type === "IN") {
newQuantity += qty;
} else if (type === "OUT") {
if (stockItem.quantity < qty) {
return NextResponse.json(
{ error: `Stok tidak mencukupi. Stok saat ini: ${stockItem.quantity}` },
{ status: 400 }
);
}
newQuantity -= qty;
} else if (type === "ADJUSTMENT") {
newQuantity = qty;
}
await prisma.stockItem.update({
where: { id: stockItem.id },
data: { quantity: newQuantity },
});
const warehouse = await prisma.warehouse.findUnique({ where: { id: warehouseId } });
const outCat =
type === "OUT"
? outboundCategory === "MANAGED_SERVICE"
? "MANAGED_SERVICE"
: outboundCategory === "OPERASIONAL"
? "OPERASIONAL"
: "JUAL_PUTUS"
: null;
const outCatLabel =
outCat === "MANAGED_SERVICE"
? "Jual Manage Service"
: outCat === "OPERASIONAL"
? "Operasional / Lainnya"
: outCat === "JUAL_PUTUS"
? "Jual Putus"
: "";
const cleanSn = serialNumbers ? String(serialNumbers).trim() : null;
await prisma.stockMovement.create({
data: {
productId,
warehouseId,
type,
outboundCategory: outCat,
quantity: qty,
referenceType: "MANUAL_ADJUSTMENT",
companyName: (body.companyName || "").trim() || warehouse?.companyName || "PT EnterpriseCore Utama",
serialNumbers: cleanSn,
notes:
type === "OUT"
? `[${outCatLabel}] ${notes || "Pengeluaran barang manual oleh staf gudang"}${cleanSn ? ` (SN: ${cleanSn})` : ""}`
: `${notes || "Penyesuaian stok manual oleh staf gudang"}${cleanSn ? ` (SN: ${cleanSn})` : ""}`,
},
});
const product = await prisma.product.findUnique({ where: { id: productId } });
await logAudit({
userId: user.id,
userName: user.name,
action: "STOCK_ADJUSTMENT",
module: "INVENTORY",
description: `[${user.role}] Penyesuaian stok ${product?.name}: tipe ${type}, jumlah ${qty}, total baru ${newQuantity}`,
});
// Kirim notifikasi keluar/masuk barang
if (type === "IN") {
await dispatchNotification({
type: "STOCK_IN",
title: `Barang Masuk: ${product?.name}`,
message: `Stok bertambah +${qty} ${product?.unit || "Unit"}. Total stok saat ini: ${newQuantity}. (Ref: ${notes || "Penyesuaian stok masuk"})`,
targetRoles: ["ADMIN", "MANAGER", "INVENTORY", "PURCHASING"],
});
} else if (type === "OUT") {
await dispatchNotification({
type: "STOCK_OUT",
title: `Barang Keluar: ${product?.name}`,
message: `Stok berkurang -${qty} ${product?.unit || "Unit"}. Sisa stok saat ini: ${newQuantity}. (Ref: ${notes || "Penyesuaian stok keluar"})`,
targetRoles: ["ADMIN", "MANAGER", "INVENTORY", "SALES"],
});
}
return NextResponse.json({ success: true, newQuantity });
} catch (error: any) {
console.error("Inventory 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 Superadmin (ADMIN), Manager, atau Staf Gudang yang dapat menghapus produk." },
{ status: 403 }
);
}
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) {
return NextResponse.json({ error: "ID produk wajib disertakan" }, { status: 400 });
}
const product = await prisma.product.findUnique({ where: { id } });
if (!product) {
return NextResponse.json({ error: "Produk tidak ditemukan" }, { status: 404 });
}
// Bersihkan seluruh dependensi data produk secara terstruktur agar tidak melanggar foreign key
await prisma.stockItem.deleteMany({ where: { productId: id } });
await prisma.stockMovement.deleteMany({ where: { productId: id } });
// Hapus alokasi batch yang terkait dengan produk ini
await prisma.salesItemBatchAllocation.deleteMany({
where: {
OR: [
{ purchaseBatch: { productId: id } },
{ salesOrderItem: { productId: id } },
],
},
});
await prisma.purchaseBatch.deleteMany({ where: { productId: id } });
await prisma.purchaseOrderItem.deleteMany({ where: { productId: id } });
await prisma.purchaseRequisitionItem.deleteMany({ where: { productId: id } });
await prisma.salesOrderItem.deleteMany({ where: { productId: id } });
await prisma.customerProductPrice.deleteMany({ where: { productId: id } });
await prisma.product.delete({ where: { id } });
await logAudit({
userId: user.id,
userName: user.name,
action: "DELETE",
module: "INVENTORY",
description: `[${user.role}] Menghapus produk ${product.name} (${product.sku}) secara permanen`,
metadata: { productId: id, name: product.name, sku: product.sku },
});
return NextResponse.json({
success: true,
message: `Produk ${product.name} (${product.sku}) berhasil dihapus.`,
});
} catch (error: any) {
console.error("Inventory DELETE error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
+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 }
);
}
}
File diff suppressed because it is too large. Load diff
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(() => {});
}
}
}
+236
View File
@@ -0,0 +1,236 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth";
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",
"ALERT_ON_MONEY_IN",
"ALERT_ON_MONEY_OUT",
]);
export async function GET() {
try {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
if (!["ADMIN", "MANAGER"].includes(user.role)) {
return NextResponse.json(
{ error: "Akses ditolak: Hanya Admin dan Manager yang dapat mengakses pengaturan sistem" },
{ status: 403 }
);
}
const rawSettings = await getAllSettings();
const settings: Record<string, string> = {};
for (const [key, val] of Object.entries(rawSettings)) {
if (!ALLOWED_SETTING_KEYS.has(key)) continue;
// 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;
}
}
const logs = await prisma.notificationLog.findMany({
take: 40,
orderBy: { createdAt: "desc" },
});
return NextResponse.json({ settings, logs });
} catch (error: any) {
console.error("Settings 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 });
}
// Only ADMIN can save system settings
if (user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Akses ditolak: Hanya ADMIN yang berhak mengubah konfigurasi sistem" },
{ status: 403 }
);
}
const body = await req.json();
const { settings } = body;
if (!settings || typeof settings !== "object") {
return NextResponse.json({ error: "Payload settings tidak valid" }, { status: 400 });
}
// Save only allowlisted key-value pairs
for (const [key, value] of Object.entries(settings)) {
if (!ALLOWED_SETTING_KEYS.has(key)) continue;
if (value === "••••••••") continue;
await prisma.systemSetting.upsert({
where: { key },
update: { value: String(value) },
create: {
key,
value: String(value),
category: key.startsWith("TELEGRAM")
? "TELEGRAM"
: key.startsWith("SMTP")
? "EMAIL"
: "NOTIFICATION",
},
});
}
await logAudit({
userId: user.id,
userName: user.name,
action: "UPDATE_SYSTEM_SETTINGS",
module: "SYSTEM",
description: `Admin ${user.name} memperbarui pengaturan notifikasi sistem (Telegram & Email)`,
});
return NextResponse.json({ success: true });
} catch (error: any) {
console.error("Settings 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 (user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Akses ditolak: Hanya ADMIN yang dapat menguji notifikasi" },
{ status: 403 }
);
}
const body = await req.json();
const { channel, token, chatId } = body;
if (channel === "TELEGRAM") {
const testMsg = `🔔 <b>Tes Notifikasi EnterpriseCore ERP</b>\n\nKoneksi bot Telegram berhasil terhubung! Sistem notifikasi siap memantau keluar masuk barang dan transaksi keuangan.\n\nPenguji: ${user.name} (${user.role})\nWaktu: ${new Date().toLocaleString("id-ID")}`;
const res = await sendTelegramMessage(token, chatId, testMsg);
await prisma.notificationLog.create({
data: {
recipient: `Telegram (${chatId})`,
channel: "TELEGRAM",
type: "SYSTEM",
title: "Uji Coba Notifikasi Telegram",
message: testMsg,
status: res.success ? "SENT" : "FAILED",
},
});
if (!res.success) {
return NextResponse.json({ error: res.error }, { status: 400 });
}
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({
type: "SYSTEM",
title: "Uji Coba Sistem Notifikasi",
message: `Sistem notifikasi ERP berfungsi dengan normal. Pengujian diinisiasi oleh ${user.name}.`,
});
return NextResponse.json({ success: true, message: "Pesan tes broadcast berhasil dicatat dan disiarkan!" });
}
} catch (error: any) {
console.error("Settings PUT test error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
+420
View File
@@ -0,0 +1,420 @@
import { NextResponse } from "next/server";
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",
"MANAGER",
"ACCOUNTANT",
"SALES",
"PURCHASING",
"INVENTORY",
]);
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,
notifStockIn: true,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: true,
notifRma: true,
mfaEnabled: true,
mfaMethod: true,
createdAt: true,
};
export async function GET() {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
const isAdmin = currentUser.role === "ADMIN";
if (isAdmin) {
// Super Admin: Melihat seluruh pengguna dan audit log sistem
const [users, auditLogs] = await Promise.all([
prisma.user.findMany({
select: USER_SELECT,
orderBy: { createdAt: "desc" },
}),
prisma.auditLog.findMany({
take: 40,
orderBy: { createdAt: "desc" },
}),
]);
return NextResponse.json({ users, auditLogs, isSuperAdmin: true });
} else {
// Non-Superadmin:
// 1. Pengguna hanya melihat profil akun dirinya sendiri
// 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 },
select: USER_SELECT,
}),
prisma.auditLog.findMany({
where: {
...(allowedModules ? { module: { in: allowedModules } } : {}),
NOT: [
{ action: { in: ["LOGIN", "LOGIN_MFA", "CREATE_USER", "UPDATE_USER"] } },
{ module: "AUTH" },
],
},
take: 60,
orderBy: { createdAt: "desc" },
}),
]);
return NextResponse.json({
users: selfUser ? [selfUser] : [],
auditLogs: operationalLogs,
isSuperAdmin: false,
});
}
} catch (error: any) {
console.error("Users GET error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
export async function POST(req: Request) {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
if (currentUser.role !== "ADMIN") {
return NextResponse.json(
{
error: `Akses ditolak: Peran Anda (${currentUser.role}) tidak memiliki wewenang untuk mendaftarkan pengguna baru. Hanya ADMIN yang diizinkan.`,
},
{ status: 403 }
);
}
const body = await req.json();
const {
name,
email,
password,
role,
telegramChatId,
notifyEmail,
notifyTelegram,
notifStockIn,
notifStockOut,
notifMoneyIn,
notifMoneyOut,
notifRma,
isActive,
mfaEnabled,
mfaMethod,
} = body;
if (!name || !email || !password || !role) {
return NextResponse.json(
{ error: "Nama, email, password, dan peran (role) wajib diisi" },
{ status: 400 }
);
}
if (!VALID_ROLES.has(role)) {
return NextResponse.json(
{ error: "Peran (role) tidak valid" },
{ status: 400 }
);
}
if (!isValidEmailFormat(email)) {
return NextResponse.json(
{ 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() },
});
if (existing) {
return NextResponse.json(
{ error: "Email sudah digunakan oleh akun lain" },
{ status: 400 }
);
}
const hashedPassword = await hashPassword(password);
const roleDefaults = getRoleDefaultNotifications(role);
const user = await prisma.user.create({
data: {
name: name.trim(),
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:
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()}`,
},
select: USER_SELECT,
});
await logAudit({
userId: currentUser.id,
userName: currentUser.name,
action: "CREATE_USER",
module: "AUTH",
description: `Admin ${currentUser.name} mendaftarkan pengguna baru: ${user.name} (${user.email}) [Role: ${user.role}]`,
});
return NextResponse.json({ success: true, user });
} catch (error: any) {
console.error("Users POST error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
export async function PUT(req: Request) {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 });
}
const body = await req.json();
const {
userId,
name,
email,
password,
role,
telegramChatId,
notifyEmail,
notifyTelegram,
notifStockIn,
notifStockOut,
notifMoneyIn,
notifMoneyOut,
notifRma,
isActive,
mfaEnabled,
mfaMethod,
} = body;
if (!userId) {
return NextResponse.json({ error: "User ID wajib disertakan" }, { status: 400 });
}
const isSelf = currentUser.id === userId;
const isAdmin = currentUser.role === "ADMIN";
if (!isSelf && !isAdmin) {
return NextResponse.json(
{ error: "Akses ditolak: Pengguna hanya dapat melihat dan mengedit profil dirinya sendiri." },
{ status: 403 }
);
}
// Role hanya boleh diubah oleh Super Admin
if (role && role !== currentUser.role && !isAdmin) {
return NextResponse.json(
{ error: "Akses ditolak: Hanya Super Admin yang berwenang mengubah peran (role) akun." },
{ status: 403 }
);
}
const updateData: any = {};
// 1. Nama (Bisa diubah oleh pengguna itu sendiri maupun Super Admin)
if (name !== undefined && name.trim() !== "") {
updateData.name = name.trim();
}
// 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 },
});
if (duplicate && duplicate.id !== userId) {
return NextResponse.json(
{ error: "Alamat email tersebut sudah dipakai oleh pengguna lain" },
{ status: 400 }
);
}
updateData.email = cleanEmail;
}
// 3. Password (Bisa diubah oleh pengguna itu sendiri maupun Super Admin)
if (password && password.trim().length > 0) {
const pwError = validateStrongPassword(password);
if (pwError) {
return NextResponse.json({ error: pwError }, { status: 400 });
}
updateData.password = await hashPassword(password.trim());
}
// 4. Role (KHUSUS SUPER ADMIN)
if (isAdmin && role) {
if (!VALID_ROLES.has(role)) {
return NextResponse.json(
{ error: "Peran (role) tidak valid" },
{ status: 400 }
);
}
if (isSelf && role !== "ADMIN") {
return NextResponse.json(
{ error: "Anda tidak dapat menurunkan peran Super Admin milik akun Anda sendiri" },
{ status: 400 }
);
}
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.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);
if (mfaEnabled) {
const existingUser = await prisma.user.findUnique({ where: { id: userId } });
if (!existingUser?.mfaSecret || !existingUser.mfaEnabled) {
updateData.mfaSecret = `PENDING:${generateMfaSecret()}`;
}
}
}
if (mfaMethod !== undefined) {
updateData.mfaMethod = mfaMethod;
}
const updated = await prisma.user.update({
where: { id: userId },
data: updateData,
select: USER_SELECT,
});
await logAudit({
userId: currentUser.id,
userName: currentUser.name,
action: "UPDATE_USER",
module: "AUTH",
description: `Data akun ${updated.name} (${updated.email}) [Role: ${updated.role}, MFA: ${updated.mfaEnabled ? "ON" : "OFF"}] diperbarui oleh ${currentUser.name}`,
});
return NextResponse.json({ success: true, user: updated });
} catch (error: any) {
console.error("Users PUT error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
File diff suppressed because it is too large. Load diff
+599
View File
@@ -0,0 +1,599 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
color-scheme: light;
}
html.dark {
color-scheme: dark;
}
body {
font-feature-settings: "rlig" 1, "calt" 1;
}
/* Custom modern scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: #64748b;
border-radius: 9999px;
}
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;
}
}
File diff suppressed because it is too large. Load diff
+48
View File
@@ -0,0 +1,48 @@
import type { Metadata, Viewport } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "EnterpriseCore ERP - Platform Pengelolaan Bisnis Terpadu",
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" 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>
);
}
+336
View File
@@ -0,0 +1,336 @@
"use client";
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,
KeyRound,
ArrowLeft,
QrCode,
Smartphone,
} from "lucide-react";
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [infoNotice, setInfoNotice] = useState<string | null>(null);
// MFA Step State
const [mfaRequired, setMfaRequired] = useState(false);
const [isFirstTimeSetup, setIsFirstTimeSetup] = useState(false);
const [mfaSecret, setMfaSecret] = useState("");
const [otpAuthUri, setOtpAuthUri] = useState("");
const [mfaToken, setMfaToken] = useState("");
const [mfaMethod, setMfaMethod] = useState("TOTP");
const [mfaCode, setMfaCode] = useState("");
useEffect(() => {
if (typeof window !== "undefined") {
const params = new URLSearchParams(window.location.search);
const reason = params.get("reason");
if (reason === "idle_timeout") {
setInfoNotice(
"Sesi Anda ditutup otomatis karena tidak ada aktivitas selama 30 menit demi keamanan data. Silakan login kembali."
);
}
}
}, []);
const applyMfaResponse = (data: any) => {
setMfaRequired(true);
setIsFirstTimeSetup(Boolean(data.isFirstTimeSetup));
setMfaSecret(data.mfaSecret || "");
setOtpAuthUri(data.otpAuthUri || "");
setMfaToken(data.mfaToken);
setMfaMethod(data.mfaMethod || "TOTP");
setMfaCode("");
};
const handleLogin = async (e?: React.FormEvent) => {
if (e) e.preventDefault();
setLoading(true);
setError(null);
try {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "Gagal login ke sistem");
}
if (data.requireMfa) {
applyMfaResponse(data);
return;
}
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
}
router.push(data.defaultRoute || getDefaultLandingRoute(data.user?.role));
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleVerifyMfa = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
const res = await fetch("/api/auth/mfa", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mfaToken, code: mfaCode }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "Kode verifikasi MFA tidak valid");
}
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
}
router.push(data.defaultRoute || getDefaultLandingRoute(data.user?.role));
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
return (
<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-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-slate-900 dark:text-white">
EnterpriseCore ERP
</h2>
<p className="mt-1 text-xs text-slate-700 dark:text-slate-100">
Masuk untuk mengakses sistem informasi bisnis terintegrasi
</p>
</div>
<div className="mt-6 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-slate-900 border border-slate-800 py-6 px-6 shadow-xl rounded-2xl sm:px-8">
{!mfaRequired ? (
<>
{infoNotice && (
<div className="mb-4 p-3 rounded-lg bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs">
{infoNotice}
</div>
)}
{error && (
<div className="mb-4 p-3 rounded-lg bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs">
{error}
</div>
)}
<form className="space-y-4" onSubmit={handleLogin}>
<div>
<label className="block text-xs font-medium text-slate-300 mb-1.5">
Alamat Email
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-slate-500">
<Mail className="h-4 w-4" />
</div>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
placeholder="Masukkan email akun Anda"
className="block w-full pl-9 pr-3 py-2 text-sm bg-slate-950/70 border border-slate-700/80 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
</div>
<div>
<label className="block text-xs font-medium text-slate-300 mb-1.5">
Kata Sandi
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-slate-500">
<Lock className="h-4 w-4" />
</div>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
placeholder="Masukkan kata sandi"
className="block w-full pl-9 pr-3 py-2 text-sm bg-slate-950/70 border border-slate-700/80 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
/>
</div>
</div>
<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 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>
</>
) : (
/* MFA / 2FA Step: Either First-Time Authenticator Enrollment OR Regular OTP Verify */
<div>
<div className="text-center mb-4">
<div className="inline-flex h-11 w-11 rounded-full bg-emerald-500/15 border border-emerald-500/30 items-center justify-center text-emerald-400 mb-2">
{isFirstTimeSetup ? (
<Smartphone className="h-5 w-5" />
) : (
<KeyRound className="h-5 w-5" />
)}
</div>
<h3 className="text-base font-bold text-white">
{isFirstTimeSetup
? "Aktivasi Authenticator Pertama Kali"
: "Verifikasi Keamanan 2-Langkah (MFA)"}
</h3>
<p className="text-xs text-slate-400 mt-1">
{isFirstTimeSetup
? "Hubungkan akun Anda ke Google Authenticator / Authy terlebih dahulu untuk mendapatkan kode OTP."
: mfaMethod === "TELEGRAM"
? "Masukkan 6-digit kode OTP yang dikirim ke Telegram / Authenticator Anda"
: "Masukkan 6-digit kode dari aplikasi Authenticator di ponsel Anda"}
</p>
</div>
{/* First-Time MFA Enrollment Box: QR Code + Secret Key */}
{isFirstTimeSetup && mfaSecret && (
<div className="mb-4 p-4 rounded-xl bg-slate-950 border border-slate-800 text-center space-y-3">
<div className="text-[11px] font-semibold text-emerald-400 flex items-center justify-center gap-1.5">
<QrCode className="h-3.5 w-3.5" />
<span>Langkah 1: Scan QR Code di Google Authenticator / Authy</span>
</div>
{otpAuthUri && (
<div className="inline-block p-2.5 bg-white rounded-xl shadow-md">
<img
src={`https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${encodeURIComponent(
otpAuthUri
)}`}
alt="QR Code MFA Authenticator"
className="w-36 h-36 mx-auto"
/>
</div>
)}
<div className="text-left bg-slate-900 p-2.5 rounded-lg border border-slate-800">
<p className="text-[10px] text-slate-400 mb-1">
Atau masukkan <strong>Setup Key / Kode Rahasia</strong> ini secara manual di aplikasi Authenticator:
</p>
<div className="font-mono text-xs font-bold text-amber-300 tracking-wider bg-slate-950 px-2.5 py-1.5 rounded border border-slate-800 select-all text-center">
{mfaSecret}
</div>
</div>
</div>
)}
{error && (
<div className="mb-4 p-3 rounded-lg bg-rose-500/10 border border-rose-500/20 text-rose-400 text-xs">
{error}
</div>
)}
<form onSubmit={handleVerifyMfa} className="space-y-4">
<div>
<label className="block text-xs font-medium text-slate-300 mb-1.5 text-center">
{isFirstTimeSetup
? "Langkah 2: Masukkan 6-Digit Kode OTP yang Muncul di Aplikasi"
: "Kode Verifikasi 6-Digit"}
</label>
<input
type="text"
inputMode="numeric"
maxLength={6}
required
autoFocus
value={mfaCode}
onChange={(e) => setMfaCode(e.target.value.replace(/\D/g, ""))}
placeholder="000000"
className="block w-full py-3 px-4 text-center text-2xl font-mono tracking-[0.5em] bg-slate-950 border border-slate-700 rounded-xl text-white placeholder-slate-700 focus:outline-none focus:ring-2 focus:ring-emerald-500"
/>
</div>
<button
type="submit"
disabled={loading || mfaCode.length !== 6}
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
? "Memverifikasi..."
: isFirstTimeSetup
? "Aktifkan Authenticator & Masuk"
: "Verifikasi & Masuk"}
</span>
<ArrowRight className="h-4 w-4" />
</button>
<button
type="button"
onClick={() => {
setMfaRequired(false);
setIsFirstTimeSetup(false);
setError(null);
}}
className="w-full flex items-center justify-center gap-1.5 py-2 text-xs font-medium text-slate-400 hover:text-slate-200 transition-colors"
>
<ArrowLeft className="h-3.5 w-3.5" />
<span>Kembali ke Login Email</span>
</button>
</form>
</div>
)}
</div>
<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>
);
}
+682
View File
@@ -0,0 +1,682 @@
"use client";
import { useEffect, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { StatCard } from "@/components/StatCard";
import { StatusBadge } from "@/components/Badge";
import { FinancialChart } from "@/components/FinancialChart";
import { formatRupiah, formatDateTime } from "@/lib/utils";
import {
TrendingUp,
Boxes,
Wallet,
FileText,
AlertTriangle,
Truck,
ArrowDownLeft,
ArrowUpRight,
PackageCheck,
Wrench,
Clock,
CheckCircle2,
Building2,
ShoppingBag,
} from "lucide-react";
const ROLE_SUBTITLES: Record<string, string> = {
ADMIN: "Ringkasan menyeluruh keuangan, operasional, stok, dan layanan",
MANAGER: "Ringkasan eksekutif bisnis, kas per PT, stok, dan status operasional (View-Only)",
ACCOUNTANT: "Ringkasan posisi kas & bank per PT, piutang, hutang, dan persetujuan PO",
SALES: "Ringkasan penjualan, tagihan customer, ketersediaan stok, dan status service",
PURCHASING: "Ringkasan pengadaan PO, persetujuan Finance, dan kebutuhan restock",
INVENTORY: "Ringkasan stok gudang, mutasi barang masuk/keluar, pengiriman, dan service/RMA",
};
export default function DashboardPage() {
const [currentUser, setCurrentUser] = useState<any>(null);
const [data, setData] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [selectedCompany, setSelectedCompany] = useState<string>("ALL");
const [recentTab, setRecentTab] = useState<"sales" | "po">("sales");
const loadDashboard = async (company: string) => {
setLoading(true);
try {
const qs = company && company !== "ALL" ? `?company=${encodeURIComponent(company)}` : "";
const [meRes, res] = await Promise.all([
fetch("/api/auth/me"),
fetch(`/api/dashboard${qs}`),
]);
if (meRes.ok) {
const meJson = await meRes.json();
setCurrentUser(meJson.user);
}
if (res.ok) {
const json = await res.json();
setData(json);
}
} catch (err) {
console.error("Failed to fetch dashboard data:", err);
} finally {
setLoading(false);
}
};
useEffect(() => {
const savedPT =
typeof window !== "undefined"
? localStorage.getItem("erp_selected_pt") || "ALL"
: "ALL";
setSelectedCompany(savedPT);
loadDashboard(savedPT);
const handleCompanyChange = (e: any) => {
const comp = e?.detail?.selectedCompany || e?.detail?.company || "ALL";
setSelectedCompany(comp);
loadDashboard(comp);
};
window.addEventListener("erp:company-changed", handleCompanyChange);
return () => {
window.removeEventListener("erp:company-changed", handleCompanyChange);
};
}, []);
const metrics = data?.metrics || {
totalRevenue: 0,
totalSalesCount: 0,
grossProfit: 0,
grossMarginPct: 0,
totalPurchases: 0,
totalPurchasesCount: 0,
inventoryValue: 0,
totalCashBank: 0,
receivables: 0,
unpaidSalesCount: 0,
payables: 0,
unpaidPoCount: 0,
totalStockUnits: 0,
totalProductsCount: 0,
stockInUnits: 0,
stockInCount: 0,
stockOutUnits: 0,
stockOutCount: 0,
pendingFinancePoCount: 0,
pendingShipmentsCount: 0,
};
const cashByCompany: { companyName: string; balance: number }[] = data?.cashByCompany || [];
const deviceSummary = data?.deviceSummary || {
inService: 0,
servicedOk: 0,
cannibalized: 0,
damaged: 0,
total: 0,
};
const lowStock = data?.lowStockAlerts || [];
const lowStockTotal = data?.lowStockTotal || lowStock.length;
const recentOrders = data?.recentSalesOrders || [];
const recentPOs = data?.recentPurchaseOrders || [];
const recentMovements = data?.recentMovements || [];
const monthlyTrends = data?.monthlyTrends || [];
const role = currentUser?.role || "GUEST";
const isInventory = role === "INVENTORY";
const isPurchasing = role === "PURCHASING";
const isSales = role === "SALES";
const canSeeFinance = ["ADMIN", "MANAGER", "ACCOUNTANT"].includes(role);
const canSeeSalesMoney = ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT"].includes(role);
const canSeePurchaseMoney = ["ADMIN", "MANAGER", "PURCHASING", "ACCOUNTANT"].includes(role);
return (
<AppShell
title="Dashboard"
subtitle={
selectedCompany !== "ALL"
? `${selectedCompany} — ${ROLE_SUBTITLES[role] || "Ringkasan operasional"}`
: ROLE_SUBTITLES[role] || "Ringkasan kinerja operasional dan keuangan"
}
>
{/* Baris Filter / Status Ringkas */}
<div className="flex flex-wrap items-center justify-between gap-2 mb-5">
<div className="inline-flex items-center gap-2 text-xs text-slate-500">
<span className="h-2 w-2 rounded-full bg-slate-900" />
<span className="font-medium text-slate-700">
{selectedCompany === "ALL" ? "Semua Perusahaan" : selectedCompany}
</span>
</div>
{loading && (
<span className="text-xs text-slate-400">Memuat data...</span>
)}
</div>
{/* 1. 4 KARTU KPI UTAMA SESUAI ROLE */}
{isInventory ? (
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-5">
<StatCard
title="Stok Fisik"
value={`${metrics.totalStockUnits.toLocaleString("id-ID")} Unit`}
description={`${metrics.totalProductsCount} produk aktif`}
icon={Boxes}
/>
<StatCard
title="Barang Masuk"
value={`+${metrics.stockInUnits.toLocaleString("id-ID")} Unit`}
description={`${metrics.stockInCount} penerimaan`}
icon={ArrowDownLeft}
/>
<StatCard
title="Barang Keluar"
value={`-${metrics.stockOutUnits.toLocaleString("id-ID")} Unit`}
description={`${metrics.stockOutCount} pengiriman`}
icon={ArrowUpRight}
/>
<StatCard
title="Perlu Restock"
value={lowStockTotal > 0 ? `${lowStockTotal} SKU` : "Aman"}
description={lowStockTotal > 0 ? "Di bawah batas minimum" : "Semua stok mencukupi"}
icon={PackageCheck}
/>
</div>
) : isPurchasing ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-5">
<StatCard
title="Total Belanja PO"
value={formatRupiah(metrics.totalPurchases)}
description={`${metrics.totalPurchasesCount} dokumen PO`}
icon={ShoppingBag}
/>
<StatCard
title="Hutang Vendor"
value={formatRupiah(metrics.payables)}
description={`${metrics.unpaidPoCount} PO belum lunas`}
icon={FileText}
/>
<StatCard
title="Review Finance"
value={`${metrics.pendingFinancePoCount} PO`}
description="Menunggu persetujuan anggaran"
icon={Clock}
/>
<StatCard
title="Stok Gudang"
value={`${metrics.totalStockUnits.toLocaleString("id-ID")} Unit`}
description={lowStockTotal > 0 ? `${lowStockTotal} SKU perlu restock` : "Stok aman"}
icon={Boxes}
/>
</div>
) : isSales ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-5">
<StatCard
title="Omzet Penjualan"
value={formatRupiah(metrics.totalRevenue)}
description={`${metrics.totalSalesCount} transaksi`}
icon={TrendingUp}
/>
<StatCard
title="Estimasi Laba Kotor"
value={formatRupiah(metrics.grossProfit)}
description={`Margin ${metrics.grossMarginPct}%`}
icon={PackageCheck}
/>
<StatCard
title="Tagihan Belum Lunas"
value={formatRupiah(metrics.receivables)}
description={`${metrics.unpaidSalesCount} invoice aktif`}
icon={FileText}
/>
<StatCard
title="Stok Tersedia"
value={`${metrics.totalStockUnits.toLocaleString("id-ID")} Unit`}
description={`${metrics.totalProductsCount} produk siap jual`}
icon={Boxes}
/>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-5">
<StatCard
title="Omzet Penjualan"
value={formatRupiah(metrics.totalRevenue)}
description={`${metrics.totalSalesCount} transaksi`}
icon={TrendingUp}
/>
<StatCard
title="Total Belanja (PO)"
value={formatRupiah(metrics.totalPurchases)}
description={`${metrics.totalPurchasesCount} dokumen PO`}
icon={ShoppingBag}
/>
<StatCard
title="Saldo Kas & Bank"
value={formatRupiah(metrics.totalCashBank)}
description={`Nilai stok: ${formatRupiah(metrics.inventoryValue)}`}
icon={Wallet}
/>
<StatCard
title="Piutang Customer"
value={formatRupiah(metrics.receivables)}
description={`Hutang Vendor: ${formatRupiah(metrics.payables)}`}
icon={FileText}
/>
</div>
)}
{/* 2. RINCIAN SALDO KAS & BANK PER PT (Khusus Admin / Manager / Keuangan) */}
{canSeeFinance && cashByCompany.length > 0 && (
<div className="bg-white rounded-xl border border-slate-200/80 p-4 mb-5 shadow-[0_1px_2px_rgba(15,23,42,0.03)]">
<div className="flex items-center justify-between gap-2 mb-3">
<div className="flex items-center gap-2">
<Building2 className="h-4 w-4 text-slate-400" />
<h3 className="text-xs font-semibold uppercase tracking-wider text-slate-600">
Posisi Kas &amp; Bank per Perusahaan
</h3>
</div>
<span className="text-[11px] text-slate-400">
{cashByCompany.length} Entitas
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{cashByCompany.map((item) => (
<div
key={item.companyName}
className="flex items-center justify-between gap-3 px-3.5 py-2.5 rounded-lg bg-slate-50/80 border border-slate-200/70"
>
<span className="text-xs font-medium text-slate-700 truncate">
{item.companyName}
</span>
<span
className={`text-xs font-bold tabular-nums whitespace-nowrap ${
item.balance < 0 ? "text-rose-700" : "text-slate-900"
}`}
>
{formatRupiah(item.balance)}
</span>
</div>
))}
</div>
</div>
)}
{/* 3. STRIP STATUS OPERASIONAL RINGKAS */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
<div className="bg-white rounded-xl border border-slate-200/80 px-4 py-3 flex items-center justify-between gap-2">
<div className="min-w-0">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-400 block">
Stok Gudang
</span>
<div className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums truncate">
{metrics.totalStockUnits.toLocaleString("id-ID")} Unit
</div>
<span className={`text-[11px] ${lowStockTotal > 0 ? "text-rose-600 font-medium" : "text-slate-500"}`}>
{lowStockTotal > 0 ? `${lowStockTotal} SKU menipis` : "Stok aman"}
</span>
</div>
<Boxes className="h-4 w-4 text-slate-400 shrink-0" />
</div>
{!isPurchasing && (
<div className="bg-white rounded-xl border border-slate-200/80 px-4 py-3 flex items-center justify-between gap-2">
<div className="min-w-0">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-400 block">
Belum Dikirim
</span>
<div className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums">
{metrics.pendingShipmentsCount} Pesanan
</div>
<span className="text-[11px] text-slate-500">Menunggu pengiriman</span>
</div>
<Truck className="h-4 w-4 text-slate-400 shrink-0" />
</div>
)}
{(canSeeFinance || isPurchasing) && (
<div className="bg-white rounded-xl border border-slate-200/80 px-4 py-3 flex items-center justify-between gap-2">
<div className="min-w-0">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-400 block">
PO Review Finance
</span>
<div className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums">
{metrics.pendingFinancePoCount} Dokumen
</div>
<span className="text-[11px] text-slate-500">
Dari {metrics.totalPurchasesCount} PO aktif
</span>
</div>
<Clock className="h-4 w-4 text-slate-400 shrink-0" />
</div>
)}
{(isInventory || isSales || canSeeFinance) && (
<div className="bg-white rounded-xl border border-slate-200/80 px-4 py-3 flex items-center justify-between gap-2">
<div className="min-w-0">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-400 block">
Service &amp; RMA
</span>
<div className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums">
{deviceSummary.inService} Service • {deviceSummary.cannibalized} Kanibal
</div>
<span className="text-[11px] text-slate-500">
{deviceSummary.damaged} rusak total
</span>
</div>
<Wrench className="h-4 w-4 text-slate-400 shrink-0" />
</div>
)}
{(isPurchasing || isSales) && (
<div className="bg-white rounded-xl border border-slate-200/80 px-4 py-3 flex items-center justify-between gap-2">
<div className="min-w-0">
<span className="text-[10.5px] font-semibold uppercase tracking-wider text-slate-400 block">
Mutasi Barang
</span>
<div className="text-sm font-bold text-slate-900 mt-0.5 tabular-nums">
+{metrics.stockInUnits.toLocaleString("id-ID")} / -{metrics.stockOutUnits.toLocaleString("id-ID")}
</div>
<span className="text-[11px] text-slate-500">Masuk / keluar</span>
</div>
<PackageCheck className="h-4 w-4 text-slate-400 shrink-0" />
</div>
)}
</div>
{/* 4. GRAFIK TREN 6 BULAN (Untuk role dengan akses transaksi keuangan/penjualan/pembelian) */}
{(canSeeSalesMoney || canSeePurchaseMoney) && (
<FinancialChart
monthlyTrends={monthlyTrends}
metrics={metrics}
canSeeFinance={canSeeFinance}
canSeeSalesMoney={canSeeSalesMoney}
canSeePurchaseMoney={canSeePurchaseMoney}
/>
)}
{/* 5. DUA PANEL BAWAH (Aktivitas Terbaru + Perlu Perhatian) */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
<div className="lg:col-span-2 bg-white rounded-xl border border-slate-200/80 shadow-[0_1px_2px_rgba(15,23,42,0.03)] overflow-hidden">
<div className="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between gap-2">
<h3 className="text-sm font-semibold text-slate-900">
{isInventory
? "Mutasi Barang Terakhir"
: isPurchasing
? "Purchase Order Terakhir"
: isSales
? "Penjualan Terakhir"
: recentTab === "sales"
? "Penjualan Terakhir"
: "Purchase Order Terakhir"}
</h3>
{canSeeFinance ? (
<div className="flex items-center gap-1 p-0.5 bg-slate-100 rounded-md text-[11px] font-medium">
<button
type="button"
onClick={() => setRecentTab("sales")}
className={`px-2.5 py-1 rounded transition-colors ${
recentTab === "sales"
? "bg-white text-slate-900 shadow-2xs font-semibold"
: "text-slate-500 hover:text-slate-900"
}`}
>
Penjualan
</button>
<button
type="button"
onClick={() => setRecentTab("po")}
className={`px-2.5 py-1 rounded transition-colors ${
recentTab === "po"
? "bg-white text-slate-900 shadow-2xs font-semibold"
: "text-slate-500 hover:text-slate-900"
}`}
>
Pembelian
</button>
</div>
) : (
<span className="text-[11px] text-slate-400">5 terbaru</span>
)}
</div>
<div className="overflow-x-auto">
{isInventory ? (
<table className="w-full text-left border-collapse text-xs">
<thead>
<tr className="bg-slate-50/80 text-slate-500 font-medium border-b border-slate-100">
<th className="py-2.5 px-5">Waktu</th>
<th className="py-2.5 px-4">Barang</th>
<th className="py-2.5 px-4">Tipe</th>
<th className="py-2.5 px-5 text-right">Jumlah</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{recentMovements.length === 0 ? (
<tr>
<td colSpan={4} className="py-8 text-center text-slate-400">
Belum ada mutasi barang.
</td>
</tr>
) : (
recentMovements.map((m: any) => (
<tr key={m.id} className="hover:bg-slate-50/50">
<td className="py-2.5 px-5 text-slate-500 font-mono text-[11px] whitespace-nowrap">
{formatDateTime(m.createdAt)}
</td>
<td className="py-2.5 px-4 font-medium text-slate-800">
{m.productName}
</td>
<td className="py-2.5 px-4">
<span className="inline-flex items-center gap-1.5 text-[11px] font-medium text-slate-700">
<span
className={`h-1.5 w-1.5 rounded-full ${
m.type === "IN" ? "bg-emerald-500" : "bg-amber-500"
}`}
/>
{m.type === "IN" ? "Masuk" : "Keluar"}
</span>
</td>
<td className="py-2.5 px-5 text-right font-semibold text-slate-900 tabular-nums whitespace-nowrap">
{m.type === "OUT" ? "-" : "+"}
{Math.abs(m.quantity)} {m.productUnit}
</td>
</tr>
))
)}
</tbody>
</table>
) : isPurchasing || (canSeeFinance && recentTab === "po") ? (
<table className="w-full text-left border-collapse text-xs">
<thead>
<tr className="bg-slate-50/80 text-slate-500 font-medium border-b border-slate-100">
<th className="py-2.5 px-5">No. PO &amp; Vendor</th>
<th className="py-2.5 px-3 text-center">Status</th>
<th className="py-2.5 px-3 text-center">Pembayaran</th>
<th className="py-2.5 px-5 text-right">Nilai</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{recentPOs.length === 0 ? (
<tr>
<td colSpan={4} className="py-8 text-center text-slate-400">
Belum ada dokumen Purchase Order.
</td>
</tr>
) : (
recentPOs.map((po: any) => (
<tr key={po.id} className="hover:bg-slate-50/50">
<td className="py-2.5 px-5">
<div className="font-mono font-semibold text-slate-900">{po.poNumber}</div>
<div className="text-[11px] text-slate-500 truncate max-w-[240px]">
{po.supplierName} • {po.companyName}
</div>
</td>
<td className="py-2.5 px-3 text-center whitespace-nowrap">
<StatusBadge status={po.status} />
</td>
<td className="py-2.5 px-3 text-center whitespace-nowrap">
<StatusBadge status={po.paymentStatus} />
</td>
<td className="py-2.5 px-5 text-right font-semibold text-slate-900 tabular-nums whitespace-nowrap">
{formatRupiah(po.totalAmount)}
</td>
</tr>
))
)}
</tbody>
</table>
) : (
<table className="w-full text-left border-collapse text-xs">
<thead>
<tr className="bg-slate-50/80 text-slate-500 font-medium border-b border-slate-100">
<th className="py-2.5 px-5">No. Order &amp; Pelanggan</th>
<th className="py-2.5 px-3 text-center">Pengiriman</th>
<th className="py-2.5 px-3 text-center">Pembayaran</th>
<th className="py-2.5 px-5 text-right">Nilai</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{recentOrders.length === 0 ? (
<tr>
<td colSpan={4} className="py-8 text-center text-slate-400">
Belum ada transaksi penjualan.
</td>
</tr>
) : (
recentOrders.map((o: any) => (
<tr key={o.id} className="hover:bg-slate-50/50">
<td className="py-2.5 px-5">
<div className="font-mono font-semibold text-slate-900">{o.orderNumber}</div>
<div className="text-[11px] text-slate-500 truncate max-w-[240px]">
{o.customerName}
</div>
</td>
<td className="py-2.5 px-3 text-center whitespace-nowrap">
<StatusBadge status={o.status} />
</td>
<td className="py-2.5 px-3 text-center whitespace-nowrap">
<StatusBadge status={o.paymentStatus} />
</td>
<td className="py-2.5 px-5 text-right font-semibold text-slate-900 tabular-nums whitespace-nowrap">
{formatRupiah(o.totalAmount)}
</td>
</tr>
))
)}
</tbody>
</table>
)}
</div>
</div>
{/* Kanan: Perlu Perhatian */}
<div className="bg-white rounded-xl border border-slate-200/80 shadow-[0_1px_2px_rgba(15,23,42,0.03)] overflow-hidden flex flex-col">
<div className="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between">
<h3 className="text-sm font-semibold text-slate-900">Perlu Perhatian</h3>
</div>
<div className="p-4 space-y-3 text-xs flex-1">
{lowStockTotal > 0 ? (
<div className="p-3 rounded-lg bg-slate-50 border border-slate-200/80 space-y-1.5">
<div className="font-semibold text-slate-800 flex items-center gap-1.5">
<AlertTriangle className="h-3.5 w-3.5 text-amber-600 shrink-0" />
<span>{lowStockTotal} Produk Stok Menipis</span>
</div>
<div className="space-y-1">
{lowStock.slice(0, 4).map((p: any) => (
<div
key={p.id}
className="flex items-center justify-between text-[11px] text-slate-600"
>
<span className="truncate pr-2">{p.name}</span>
<span className="font-mono font-semibold text-rose-700 shrink-0">
{p.currentStock}/{p.minStock} {p.unit}
</span>
</div>
))}
</div>
</div>
) : (
<div className="p-3 rounded-lg bg-slate-50 border border-slate-200/80 text-slate-700 flex items-center gap-2">
<CheckCircle2 className="h-4 w-4 text-emerald-600 shrink-0" />
<span>Seluruh stok produk dalam batas aman.</span>
</div>
)}
{canSeeFinance && (
<div className="p-3 rounded-lg bg-slate-50/70 border border-slate-200/80 space-y-1.5">
<div className="font-semibold text-slate-500 text-[10.5px] uppercase tracking-wider">
Keuangan &amp; Approval
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Invoice Belum Lunas</span>
<strong className="text-slate-900 tabular-nums">{metrics.unpaidSalesCount} SO</strong>
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Tagihan Vendor Belum Lunas</span>
<strong className="text-slate-900 tabular-nums">{metrics.unpaidPoCount} PO</strong>
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">PO Menunggu Approval</span>
<strong className="text-slate-900 tabular-nums">{metrics.pendingFinancePoCount} PO</strong>
</div>
</div>
)}
{isSales && (
<div className="p-3 rounded-lg bg-slate-50/70 border border-slate-200/80 space-y-1.5">
<div className="font-semibold text-slate-500 text-[10.5px] uppercase tracking-wider">
Ringkasan Penjualan
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Invoice Belum Lunas</span>
<strong className="text-slate-900 tabular-nums">{metrics.unpaidSalesCount} SO</strong>
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Pesanan Belum Dikirim</span>
<strong className="text-slate-900 tabular-nums">{metrics.pendingShipmentsCount} SO</strong>
</div>
</div>
)}
{isPurchasing && (
<div className="p-3 rounded-lg bg-slate-50/70 border border-slate-200/80 space-y-1.5">
<div className="font-semibold text-slate-500 text-[10.5px] uppercase tracking-wider">
Ringkasan Pengadaan
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Menunggu Approval Finance</span>
<strong className="text-slate-900 tabular-nums">{metrics.pendingFinancePoCount} PO</strong>
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">PO Belum Lunas</span>
<strong className="text-slate-900 tabular-nums">{metrics.unpaidPoCount} PO</strong>
</div>
</div>
)}
{!isPurchasing && (
<div className="p-3 rounded-lg bg-slate-50/70 border border-slate-200/80 space-y-1.5">
<div className="font-semibold text-slate-500 text-[10.5px] uppercase tracking-wider">
Service &amp; RMA
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Sedang Di-service</span>
<strong className="text-slate-900 tabular-nums">{deviceSummary.inService} unit</strong>
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Selesai Service</span>
<strong className="text-slate-900 tabular-nums">{deviceSummary.servicedOk} unit</strong>
</div>
<div className="flex items-center justify-between">
<span className="text-slate-600">Kanibalan / Rusak Total</span>
<strong className="text-slate-900 tabular-nums">
{deviceSummary.cannibalized} / {deviceSummary.damaged} unit
</strong>
</div>
</div>
)}
</div>
</div>
</div>
</AppShell>
);
}
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>
);
}
File diff suppressed because it is too large. Load diff
+758
View File
@@ -0,0 +1,758 @@
"use client";
import { useEffect, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { formatDateTime } from "@/lib/utils";
import {
Send,
Mail,
Bell,
CheckCircle2,
AlertCircle,
Save,
Radio,
History,
Lock,
ShieldCheck,
Download,
Database,
} from "lucide-react";
const DIVISION_CHANNELS = [
{
key: "TELEGRAM_CHAT_ID_MANAGEMENT",
label: "Grup Direksi & Admin (Management)",
desc: "Menerima seluruh alert mutasi barang & keuangan penting",
},
{
key: "TELEGRAM_CHAT_ID_INVENTORY",
label: "Grup Divisi Gudang & Logistik",
desc: "Khusus alert Barang Masuk (PO) & Barang Keluar (SO)",
},
{
key: "TELEGRAM_CHAT_ID_SALES",
label: "Grup Divisi Penjualan (Sales)",
desc: "Khusus alert Barang Keluar & Pelunasan Invoice Customer",
},
{
key: "TELEGRAM_CHAT_ID_PURCHASING",
label: "Grup Divisi Pengadaan (Purchasing)",
desc: "Khusus alert Penerimaan Barang Supplier & Pembayaran PO",
},
{
key: "TELEGRAM_CHAT_ID_FINANCE",
label: "Grup Divisi Keuangan & Akuntansi",
desc: "Khusus alert Uang Masuk (Kas/Bank) & Uang Keluar",
},
];
export default function SettingsPage() {
const [currentUser, setCurrentUser] = useState<any>(null);
const [settings, setSettings] = useState<Record<string, string>>({});
const [logs, setLogs] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [statusMessage, setStatusMessage] = useState<{
type: "success" | "error";
text: string;
} | null>(null);
const loadData = async () => {
try {
const [meRes, res] = await Promise.all([
fetch("/api/auth/me"),
fetch("/api/settings"),
]);
if (meRes.ok) {
const meJson = await meRes.json();
setCurrentUser(meJson.user);
}
if (res.ok) {
const json = await res.json();
setSettings(json.settings || {});
setLogs(json.logs || []);
}
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadData();
}, []);
const isAdmin = currentUser?.role === "ADMIN";
const handleSaveSettings = async (e: React.FormEvent) => {
e.preventDefault();
if (!isAdmin) return;
setSaving(true);
setStatusMessage(null);
try {
const res = await fetch("/api/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ settings }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
setStatusMessage({
type: "success",
text: "Pengaturan notifikasi & saluran divisi berhasil disimpan!",
});
loadData();
} catch (err: any) {
setStatusMessage({ type: "error", text: err.message });
} finally {
setSaving(false);
}
};
const handleTestTelegram = async () => {
if (!settings.TELEGRAM_BOT_TOKEN || !settings.TELEGRAM_CHAT_ID) {
setStatusMessage({
type: "error",
text: "Harap isi Bot Token dan Default Chat ID Telegram terlebih dahulu",
});
return;
}
setTesting(true);
setStatusMessage(null);
try {
const res = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
channel: "TELEGRAM",
token: settings.TELEGRAM_BOT_TOKEN,
chatId: settings.TELEGRAM_CHAT_ID,
}),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
setStatusMessage({
type: "success",
text: "Pesan uji coba berhasil terkirim ke Telegram! Periksa chat atau channel Anda.",
});
loadData();
} catch (err: any) {
setStatusMessage({
type: "error",
text: `Gagal mengirim ke Telegram: ${err.message}`,
});
} finally {
setTesting(false);
}
};
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);
try {
const res = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ channel: "ALL" }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
setStatusMessage({
type: "success",
text: "Pesan broadcast uji coba berhasil dikirim dan dicatat ke log notifikasi!",
});
loadData();
} catch (err: any) {
setStatusMessage({ type: "error", text: err.message });
} finally {
setTesting(false);
}
};
return (
<AppShell
title="Pengaturan"
subtitle="Konfigurasi email SMTP, notifikasi Telegram, dan aturan pengiriman laporan per divisi"
>
{statusMessage && (
<div
className={`mb-6 p-4 rounded-xl flex items-center gap-3 text-xs font-medium border ${
statusMessage.type === "success"
? "bg-emerald-50 text-emerald-800 border-emerald-200"
: "bg-rose-50 text-rose-800 border-rose-200"
}`}
>
{statusMessage.type === "success" ? (
<CheckCircle2 className="h-4 w-4 text-emerald-600 shrink-0" />
) : (
<AlertCircle className="h-4 w-4 text-rose-600 shrink-0" />
)}
<span>{statusMessage.text}</span>
</div>
)}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
<div className="lg:col-span-2 space-y-6">
<form onSubmit={handleSaveSettings} className="space-y-6">
{/* 1. Telegram Bot & Division Channels */}
<div className="bg-white rounded-xl border border-slate-200 shadow-xs p-6">
<div className="flex items-center justify-between mb-4 border-b border-slate-100 pb-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-sky-50 text-sky-600">
<Send className="h-5 w-5" />
</div>
<div>
<h3 className="text-sm font-bold text-slate-800">
Integrasi Bot Telegram & Routing Per Divisi
</h3>
<p className="text-[11px] text-slate-500">
Arahkan notifikasi otomatis ke grup Telegram masing-masing divisi terkait
</p>
</div>
</div>
<label className="flex items-center gap-2 cursor-pointer text-xs font-bold text-slate-700">
<input
type="checkbox"
disabled={!isAdmin}
checked={settings.TELEGRAM_ENABLED === "true"}
onChange={(e) =>
setSettings({
...settings,
TELEGRAM_ENABLED: e.target.checked ? "true" : "false",
})
}
className="h-4 w-4 rounded text-blue-600 focus:ring-blue-500"
/>
<span>Aktifkan Telegram</span>
</label>
</div>
<div className="space-y-4 text-xs">
<div>
<label className="block font-semibold text-slate-700 mb-1">
Telegram Bot Token (dari @BotFather)
</label>
<input
type="text"
disabled={!isAdmin}
placeholder="misal: 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ"
value={settings.TELEGRAM_BOT_TOKEN || ""}
onChange={(e) =>
setSettings({ ...settings, TELEGRAM_BOT_TOKEN: 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">
Default Group / Channel Chat ID Utama Perusahaan
</label>
<div className="flex items-center gap-2">
<input
type="text"
disabled={!isAdmin}
placeholder="misal: -1001234567890"
value={settings.TELEGRAM_CHAT_ID || ""}
onChange={(e) =>
setSettings({ ...settings, TELEGRAM_CHAT_ID: e.target.value })
}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono disabled:bg-slate-100"
/>
{isAdmin && (
<button
type="button"
disabled={testing}
onClick={handleTestTelegram}
className="shrink-0 px-3 py-2 rounded-lg bg-sky-600 hover:bg-sky-700 text-white font-semibold flex items-center gap-1.5 shadow-xs transition-colors disabled:opacity-50"
>
<Radio className="h-3.5 w-3.5" />
<span>{testing ? "Menguji..." : "Tes Bot"}</span>
</button>
)}
</div>
</div>
{/* Per-Division Group Chat IDs */}
<div className="pt-3 border-t border-slate-100">
<p className="font-bold text-slate-800 mb-2">
Chat ID Grup Spesifik Per Divisi (Opsional):
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{DIVISION_CHANNELS.map((ch) => (
<div
key={ch.key}
className="p-3 rounded-lg bg-slate-50 border border-slate-200"
>
<label className="block font-semibold text-slate-800 mb-0.5">
{ch.label}
</label>
<p className="text-[10px] text-slate-500 mb-1.5">{ch.desc}</p>
<input
type="text"
disabled={!isAdmin}
placeholder="Chat ID Grup Divisi (misal: -100987...)"
value={settings[ch.key] || ""}
onChange={(e) =>
setSettings({ ...settings, [ch.key]: e.target.value })
}
className="w-full px-2.5 py-1.5 border border-slate-300 rounded-md font-mono text-[11px] bg-white disabled:bg-slate-100"
/>
</div>
))}
</div>
</div>
</div>
</div>
{/* 2. Email Notification Section */}
<div className="bg-white rounded-xl border border-slate-200 shadow-xs p-6">
<div className="flex items-center justify-between mb-4 border-b border-slate-100 pb-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-blue-50 text-blue-600">
<Mail className="h-5 w-5" />
</div>
<div>
<h3 className="text-sm font-bold text-slate-800">
Notifikasi Email (SMTP)
</h3>
<p className="text-[11px] text-slate-500">
Pengiriman surat pemberitahuan ke email terdaftar masing-masing user divisi
</p>
</div>
</div>
<label className="flex items-center gap-2 cursor-pointer text-xs font-bold text-slate-700">
<input
type="checkbox"
disabled={!isAdmin}
checked={settings.EMAIL_ENABLED === "true"}
onChange={(e) =>
setSettings({
...settings,
EMAIL_ENABLED: e.target.checked ? "true" : "false",
})
}
className="h-4 w-4 rounded text-blue-600 focus:ring-blue-500"
/>
<span>Aktifkan Email</span>
</label>
</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
</label>
<input
type="text"
disabled={!isAdmin}
placeholder="misal: smtp.gmail.com / mail.perusahaan.id"
value={settings.SMTP_HOST || ""}
onChange={(e) =>
setSettings({ ...settings, SMTP_HOST: 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 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 */}
<div className="bg-white rounded-xl border border-slate-200 shadow-xs p-6">
<div className="flex items-center gap-2.5 mb-4 border-b border-slate-100 pb-3">
<div className="p-2 rounded-lg bg-emerald-50 text-emerald-600">
<Bell className="h-5 w-5" />
</div>
<div>
<h3 className="text-sm font-bold text-slate-800">
Pemicu Otomatis Notifikasi (Trigger Rules)
</h3>
<p className="text-[11px] text-slate-500">
Pilih kejadian operasional apa saja yang akan memicu pengiriman alert ke divisi terkait
</p>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-xs">
<label className="p-3 rounded-lg border border-slate-200 bg-slate-50 flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
disabled={!isAdmin}
checked={settings.NOTIF_STOCK_IN_ENABLED === "true"}
onChange={(e) =>
setSettings({
...settings,
NOTIF_STOCK_IN_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">📦 Barang Masuk</div>
<div className="text-[11px] text-slate-500 mt-0.5">
Rute: Divisi Gudang, Purchasing & Admin
</div>
</div>
</label>
<label className="p-3 rounded-lg border border-slate-200 bg-slate-50 flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
disabled={!isAdmin}
checked={settings.NOTIF_STOCK_OUT_ENABLED === "true"}
onChange={(e) =>
setSettings({
...settings,
NOTIF_STOCK_OUT_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">🚚 Barang Keluar</div>
<div className="text-[11px] text-slate-500 mt-0.5">
Rute: Divisi Gudang, Sales & Admin
</div>
</div>
</label>
<label className="p-3 rounded-lg border border-slate-200 bg-slate-50 flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
disabled={!isAdmin}
checked={settings.NOTIF_MONEY_IN_ENABLED === "true"}
onChange={(e) =>
setSettings({
...settings,
NOTIF_MONEY_IN_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">💵 Uang Masuk</div>
<div className="text-[11px] text-slate-500 mt-0.5">
Rute: Divisi Keuangan (Akuntan), Sales & Admin
</div>
</div>
</label>
<label className="p-3 rounded-lg border border-slate-200 bg-slate-50 flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
disabled={!isAdmin}
checked={settings.NOTIF_MONEY_OUT_ENABLED === "true"}
onChange={(e) =>
setSettings({
...settings,
NOTIF_MONEY_OUT_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">💳 Uang Keluar &amp; Approval PO</div>
<div className="text-[11px] text-slate-500 mt-0.5">
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>
</div>
</div>
{isAdmin ? (
<div className="flex items-center justify-between">
<button
type="button"
onClick={handleTestBroadcast}
className="px-4 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold transition-colors"
>
Uji Siaran Notifikasi Sistem
</button>
<button
type="submit"
disabled={saving}
className="inline-flex items-center gap-2 px-6 py-2.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold shadow-xs transition-colors disabled:opacity-50"
>
<Save className="h-4 w-4" />
<span>{saving ? "Menyimpan..." : "Simpan Konfigurasi"}</span>
</button>
</div>
) : (
<div className="p-3 rounded-lg bg-slate-100 text-slate-600 text-xs flex items-center gap-2">
<Lock className="h-4 w-4 text-slate-400" />
<span>Pengubahan pengaturan sistem dibatasi khusus peran Super Admin.</span>
</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 */}
<div className="bg-white rounded-xl border border-slate-200 shadow-xs p-6 flex flex-col h-[700px]">
<div className="flex items-center justify-between mb-4 border-b border-slate-100 pb-3">
<div className="flex items-center gap-2">
<History className="h-4 w-4 text-slate-600" />
<h3 className="text-sm font-bold text-slate-800">
Riwayat Pengiriman Alert
</h3>
</div>
<span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-slate-100 text-slate-600">
{logs.length} Log
</span>
</div>
<div className="flex-1 overflow-y-auto space-y-3 pr-1 text-xs">
{logs.length === 0 ? (
<p className="text-center text-slate-400 py-12">
Belum ada notifikasi yang terkirim.
</p>
) : (
logs.map((log) => (
<div
key={log.id}
className="p-3 rounded-lg bg-slate-50 border border-slate-100 space-y-1.5"
>
<div className="flex items-center justify-between">
<span
className={`inline-block px-1.5 py-0.2 rounded text-[9px] font-bold ${
log.channel === "TELEGRAM"
? "bg-sky-100 text-sky-800"
: "bg-blue-100 text-blue-800"
}`}
>
{log.channel}
</span>
<span className="text-[10px] text-slate-400 font-mono">
{formatDateTime(log.createdAt)}
</span>
</div>
<div className="font-semibold text-slate-800 line-clamp-1">
{log.title}
</div>
<p className="text-[11px] text-slate-600 line-clamp-2 leading-relaxed">
{log.message}
</p>
<div className="text-[10px] text-slate-400 pt-1 border-t border-slate-200/60 flex items-center justify-between">
<span className="truncate max-w-[170px]">{log.recipient}</span>
<span
className={`font-semibold ${
log.status === "SENT" ? "text-emerald-600" : "text-rose-600"
}`}
>
{log.status}
</span>
</div>
</div>
))
)}
</div>
</div>
</div>
</AppShell>
);
}
+911
View File
@@ -0,0 +1,911 @@
"use client";
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,
FileCheck2,
Lock,
Mail,
Send,
Bell,
Pencil,
KeyRound,
ShieldCheck,
QrCode,
RefreshCw,
} from "lucide-react";
const roleDescriptions: Record<string, string> = {
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 = {
name: "",
email: "",
password: "",
role: "SALES",
isActive: true,
telegramChatId: "",
notifyEmail: true,
notifyTelegram: false,
notifStockIn: false,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: false,
notifRma: true,
mfaEnabled: false,
mfaMethod: "TOTP",
};
const NOTIF_TOPICS = [
{ 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() {
const [currentUser, setCurrentUser] = useState<any>(null);
const [users, setUsers] = useState<any[]>([]);
const [auditLogs, setAuditLogs] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<"users" | "audit">("users");
// Create Modal
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [form, setForm] = useState({ ...EMPTY_FORM });
// Edit Modal
const [isEditOpen, setIsEditOpen] = useState(false);
const [editUser, setEditUser] = useState<any>(null);
const [editForm, setEditForm] = useState({
name: "",
email: "",
password: "",
role: "SALES",
isActive: true,
telegramChatId: "",
notifyEmail: true,
notifyTelegram: false,
notifStockIn: false,
notifStockOut: true,
notifMoneyIn: true,
notifMoneyOut: false,
notifRma: true,
mfaEnabled: false,
mfaMethod: "TOTP",
});
const [editSubmitting, setEditSubmitting] = useState(false);
const [editError, setEditError] = useState<string | null>(null);
// MFA Setup / QR Modal
const [mfaSetupData, setMfaSetupData] = useState<{
mfaSecret: string;
otpAuthUri: string;
currentCode: string;
} | null>(null);
const [loadingMfa, setLoadingMfa] = useState(false);
const loadData = async () => {
try {
const [meRes, res] = await Promise.all([
fetch("/api/auth/me"),
fetch("/api/users"),
]);
if (meRes.ok) {
const meJson = await meRes.json();
setCurrentUser(meJson.user);
}
if (res.ok) {
const json = await res.json();
setUsers(json.users || []);
setAuditLogs(json.auditLogs || []);
}
} catch (err) {
console.error(err);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadData();
}, []);
const handleCreateUser = async (e: React.FormEvent) => {
e.preventDefault();
setSubmitting(true);
setFormError(null);
try {
const res = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
setIsCreateOpen(false);
setForm({ ...EMPTY_FORM });
loadData();
} catch (err: any) {
setFormError(err.message);
} finally {
setSubmitting(false);
}
};
const fetchMfaDetails = async (userId: string, regenerate = false) => {
setLoadingMfa(true);
try {
const res = await fetch(
`/api/auth/mfa?userId=${encodeURIComponent(userId)}${
regenerate ? "&regenerate=true" : ""
}`
);
if (res.ok) {
const data = await res.json();
setMfaSetupData({
mfaSecret: data.mfaSecret,
otpAuthUri: data.otpAuthUri,
currentCode: data.currentCode,
});
}
} catch (e) {
console.error(e);
} finally {
setLoadingMfa(false);
}
};
const openEditModal = (u: any) => {
setEditUser(u);
setEditForm({
name: u.name || "",
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 ?? 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",
});
setMfaSetupData(null);
setEditError(null);
setIsEditOpen(true);
fetchMfaDetails(u.id);
};
const handleEditUser = async (e: React.FormEvent) => {
e.preventDefault();
if (!editUser) return;
setEditSubmitting(true);
setEditError(null);
try {
const res = await fetch("/api/users", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId: editUser.id, ...editForm }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
setIsEditOpen(false);
loadData();
} catch (err: any) {
setEditError(err.message);
} finally {
setEditSubmitting(false);
}
};
const isAdmin = currentUser?.role === "ADMIN";
return (
<AppShell
title={isAdmin ? "Pengguna" : "Profil Saya"}
subtitle={
isAdmin
? "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">
<div className="flex items-center p-1 bg-slate-200/80 rounded-lg text-xs font-semibold text-slate-600 w-fit">
<button
onClick={() => setActiveTab("users")}
className={`px-3 py-1.5 rounded-md flex items-center gap-1.5 transition-colors ${
activeTab === "users"
? "bg-white text-slate-900 shadow-2xs font-bold"
: "hover:text-slate-900"
}`}
>
<Users className="h-3.5 w-3.5" />
<span>{isAdmin ? `Daftar Pengguna (${users.length})` : "Profil Pengguna Saya"}</span>
</button>
<button
onClick={() => setActiveTab("audit")}
className={`px-3 py-1.5 rounded-md flex items-center gap-1.5 transition-colors ${
activeTab === "audit"
? "bg-white text-slate-900 shadow-2xs font-bold"
: "hover:text-slate-900"
}`}
>
<FileCheck2 className="h-3.5 w-3.5" />
<span>Audit Trail Log ({auditLogs.length})</span>
</button>
</div>
{isAdmin ? (
<button
onClick={() => {
setFormError(null);
setForm({ ...EMPTY_FORM });
setIsCreateOpen(true);
}}
className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-semibold shadow-xs transition-colors"
>
<Plus className="h-4 w-4" />
<span>Tambah Pengguna Baru</span>
</button>
) : (
<div className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-blue-50 text-blue-800 border border-blue-200 text-xs">
<Lock className="h-3.5 w-3.5 text-blue-600" />
<span>Anda dapat mengubah nama, email, password, MFA, dan notifikasi. Peran (role) hanya dapat diubah oleh Super Admin.</span>
</div>
)}
</div>
{activeTab === "users" ? (
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
<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-3 px-6">Nama Pengguna</th>
<th className="py-3 px-4">Kontak Notifikasi</th>
<th className="py-3 px-4">Peran (Role)</th>
<th className="py-3 px-4">Keamanan MFA</th>
<th className="py-3 px-4">Saluran & Topik</th>
<th className="py-3 px-6">Deskripsi Kewenangan</th>
<th className="py-3 px-4 text-center">Aksi</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{users.map((u) => (
<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 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>
<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">
<div className="font-mono text-slate-600 flex items-center gap-1">
<Mail className="h-3 w-3 text-slate-400" />
<span>{u.email}</span>
</div>
{u.telegramChatId && (
<div className="font-mono text-[11px] text-blue-600 flex items-center gap-1 mt-0.5">
<Send className="h-2.5 w-2.5 text-blue-500" />
<span>TG: {u.telegramChatId}</span>
</div>
)}
</td>
<td className="py-3.5 px-4">
<span
className={`inline-block px-2.5 py-0.5 rounded-md text-[10px] font-bold border ${
u.role === "ADMIN"
? "bg-rose-50 text-rose-700 border-rose-200"
: u.role === "INVENTORY"
? "bg-emerald-50 text-emerald-700 border-emerald-200"
: u.role === "SALES"
? "bg-amber-50 text-amber-700 border-amber-200"
: u.role === "PURCHASING"
? "bg-blue-50 text-blue-700 border-blue-200"
: "bg-purple-50 text-purple-700 border-purple-200"
}`}
>
{u.role}
</span>
</td>
<td className="py-3.5 px-4">
{u.mfaEnabled ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 text-[10px] font-bold">
<ShieldCheck className="h-3 w-3 text-emerald-600" />
<span>MFA Aktif ({u.mfaMethod || "TOTP"})</span>
</span>
) : (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 border border-slate-200 text-[10px] font-medium">
<span>Nonaktif</span>
</span>
)}
</td>
<td className="py-3.5 px-4">
<div className="flex items-center gap-1 flex-wrap">
{u.notifyEmail && (
<span className="px-1.5 py-0.5 rounded bg-blue-50 text-blue-700 border border-blue-200 text-[10px] font-bold">
Email
</span>
)}
{u.notifyTelegram && (
<span className="px-1.5 py-0.5 rounded bg-sky-50 text-sky-700 border border-sky-200 text-[10px] font-bold">
TG
</span>
)}
{u.notifStockIn && (
<span title="Barang Masuk" className="px-1 py-0.5 rounded bg-emerald-50 border border-emerald-200 text-[10px]">
📦
</span>
)}
{u.notifStockOut && (
<span title="Barang Keluar" className="px-1 py-0.5 rounded bg-amber-50 border border-amber-200 text-[10px]">
🚚
</span>
)}
{u.notifMoneyIn && (
<span title="Uang Masuk" className="px-1 py-0.5 rounded bg-blue-50 border border-blue-200 text-[10px]">
💵
</span>
)}
{u.notifMoneyOut && (
<span title="Uang Keluar" className="px-1 py-0.5 rounded bg-rose-50 border border-rose-200 text-[10px]">
💳
</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">
{roleDescriptions[u.role] || "Akses standar operasional"}
</td>
<td className="py-3.5 px-4 text-center">
<button
onClick={() => openEditModal(u)}
title={isAdmin ? "Edit Akun, Role, Password & MFA" : "Edit Profil Saya"}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 hover:text-blue-800 border border-blue-200 text-blue-700 text-[11px] font-semibold transition-colors"
>
<Pencil className="h-3 w-3" />
<span>{isAdmin ? "Edit Akun" : "Edit Profil Saya"}</span>
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
) : (
<div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
<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-3 px-6">Waktu Kejadian</th>
<th className="py-3 px-4">Pengguna</th>
<th className="py-3 px-4">Modul</th>
<th className="py-3 px-4">Kode Aksi</th>
<th className="py-3 px-6">Uraian Aktivitas</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{auditLogs.map((log) => (
<tr key={log.id} className="hover:bg-slate-50/60 transition-colors">
<td className="py-3.5 px-6 text-slate-400 font-mono text-[11px]">
{formatDateTime(log.createdAt)}
</td>
<td className="py-3.5 px-4 font-semibold text-slate-800">
{log.userName || "System"}
</td>
<td className="py-3.5 px-4">
<span className="inline-block px-2 py-0.5 rounded text-[10px] font-bold bg-slate-100 text-slate-700 border border-slate-200">
{log.module}
</span>
</td>
<td className="py-3.5 px-4 font-mono font-semibold text-blue-600 text-[11px]">
{log.action}
</td>
<td className="py-3.5 px-6 text-slate-700">{log.description}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Modal: Create User */}
<Modal
isOpen={isCreateOpen}
onClose={() => setIsCreateOpen(false)}
title="Daftarkan Akun Pengguna Baru (Akses Admin)"
>
{formError && (
<div className="mb-4 p-3 rounded-lg bg-rose-50 border border-rose-200 text-rose-700 text-xs">
{formError}
</div>
)}
<form onSubmit={handleCreateUser} className="space-y-4 text-xs">
<div>
<label className="block font-semibold text-slate-700 mb-1">Nama Lengkap Karyawan *</label>
<input
type="text"
required
placeholder="misal: Hendra Saputra"
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
/>
</div>
<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
type="email"
required
placeholder="hendra@erp.local"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">ID Chat Telegram (Opsional)</label>
<input
type="text"
placeholder="misal: 123456789"
value={form.telegramChatId}
onChange={(e) => setForm({ ...form, telegramChatId: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
/>
</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">Kata Sandi Awal *</label>
<input
type="password"
required
placeholder="Minimal 6 karakter"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">Peran & Hak Akses (Role) *</label>
<select
value={form.role}
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>
<option value="MANAGER">MANAGER</option>
<option value="INVENTORY">INVENTORY</option>
<option value="SALES">SALES</option>
<option value="PURCHASING">PURCHASING</option>
<option value="ACCOUNTANT">ACCOUNTANT</option>
</select>
</div>
</div>
{/* Keamanan MFA */}
<div className="p-3 bg-emerald-50/60 rounded-lg border border-emerald-200 space-y-2">
<div className="flex items-center justify-between">
<label className="flex items-center gap-2 cursor-pointer font-bold text-slate-800">
<input
type="checkbox"
checked={form.mfaEnabled}
onChange={(e) => setForm({ ...form, mfaEnabled: e.target.checked })}
className="rounded text-emerald-600 focus:ring-emerald-500"
/>
<ShieldCheck className="h-4 w-4 text-emerald-600" />
<span>Wajibkan Verifikasi 2-Langkah (MFA Login)</span>
</label>
{form.mfaEnabled && (
<select
value={form.mfaMethod}
onChange={(e) => setForm({ ...form, mfaMethod: e.target.value })}
className="px-2 py-1 border border-emerald-300 rounded bg-white text-[11px] font-semibold text-slate-800"
>
<option value="TOTP">Google Authenticator (TOTP)</option>
<option value="TELEGRAM">OTP via Telegram</option>
</select>
)}
</div>
</div>
<div className="p-3 bg-slate-50 rounded-lg border border-slate-200 space-y-3">
<span className="font-bold text-slate-800 flex items-center gap-1.5">
<Bell className="h-3.5 w-3.5 text-blue-600" />
<span>Preferensi Notifikasi Otomatis:</span>
</span>
<div className="flex items-center gap-4">
<label className="flex items-center gap-2 cursor-pointer text-slate-700 font-medium">
<input
type="checkbox"
checked={form.notifyEmail}
onChange={(e) => setForm({ ...form, notifyEmail: e.target.checked })}
className="rounded text-blue-600 focus:ring-blue-500"
/>
<span>Kirim via Email</span>
</label>
<label className="flex items-center gap-2 cursor-pointer text-slate-700 font-medium">
<input
type="checkbox"
checked={form.notifyTelegram}
onChange={(e) => setForm({ ...form, notifyTelegram: e.target.checked })}
className="rounded text-blue-600 focus:ring-blue-500"
/>
<span>Kirim via Telegram</span>
</label>
</div>
<div className="border-t border-slate-200 pt-2">
<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>
<div className="pt-2 flex items-center justify-end gap-2 border-t border-slate-200">
<button
type="button"
onClick={() => setIsCreateOpen(false)}
className="px-4 py-2 border border-slate-300 rounded-lg text-slate-600 hover:bg-slate-100 font-semibold"
>
Batal
</button>
<button
type="submit"
disabled={submitting}
className="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold shadow-xs disabled:opacity-50"
>
{submitting ? "Mendaftarkan..." : "Buat Akun Karyawan"}
</button>
</div>
</form>
</Modal>
{/* Modal: Edit Data Pengguna (Nama, Email, Password, Role, MFA & Notifikasi) */}
<Modal
isOpen={isEditOpen}
onClose={() => setIsEditOpen(false)}
title={`Edit Akun & Keamanan MFA — ${editUser?.name ?? ""}`}
>
{editError && (
<div className="mb-4 p-3 rounded-lg bg-rose-50 border border-rose-200 text-rose-700 text-xs">
{editError}
</div>
)}
<form onSubmit={handleEditUser} className="space-y-4 text-xs">
<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 *
</label>
<input
type="text"
required
value={editForm.name}
onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">
Alamat Email Login *
</label>
<input
type="email"
required
value={editForm.email}
onChange={(e) => setEditForm({ ...editForm, email: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono"
/>
</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 flex items-center gap-1">
<KeyRound className="h-3.5 w-3.5 text-amber-600" />
<span>Ganti Password (Opsional)</span>
</label>
<input
type="password"
placeholder="Kosongkan jika tidak diubah"
value={editForm.password}
onChange={(e) => setEditForm({ ...editForm, password: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg"
/>
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1 flex items-center justify-between">
<span>Peran / Role (RBAC) *</span>
{!isAdmin && (
<span className="text-[10px] text-amber-700 font-semibold bg-amber-50 px-1.5 py-0.5 rounded border border-amber-200">
🔒 Khusus Super Admin
</span>
)}
</label>
{isAdmin ? (
<select
value={editForm.role}
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>
<option value="MANAGER">MANAGER - Manajer</option>
<option value="INVENTORY">INVENTORY - Staf Gudang</option>
<option value="SALES">SALES - Staf Penjualan</option>
<option value="PURCHASING">PURCHASING - Staf Pengadaan</option>
<option value="ACCOUNTANT">ACCOUNTANT - Staf Akuntan</option>
</select>
) : (
<div className="w-full px-3 py-2 border border-slate-200 rounded-lg bg-slate-100 text-slate-700 font-semibold flex items-center justify-between">
<span>{editForm.role} — {roleDescriptions[editForm.role] || ""}</span>
<Lock className="h-3.5 w-3.5 text-slate-400" />
</div>
)}
</div>
</div>
{/* Pengaturan MFA / 2FA */}
<div className="p-3 bg-emerald-50/70 rounded-lg border border-emerald-200 space-y-2.5">
<div className="flex items-center justify-between">
<label className="flex items-center gap-2 cursor-pointer font-bold text-slate-800">
<input
type="checkbox"
checked={editForm.mfaEnabled}
onChange={(e) =>
setEditForm({ ...editForm, mfaEnabled: e.target.checked })
}
className="rounded text-emerald-600 focus:ring-emerald-500"
/>
<ShieldCheck className="h-4 w-4 text-emerald-600" />
<span>Aktifkan Login MFA (2FA)</span>
</label>
<select
value={editForm.mfaMethod}
onChange={(e) =>
setEditForm({ ...editForm, mfaMethod: e.target.value })
}
className="px-2 py-1 border border-emerald-300 rounded bg-white text-[11px] font-semibold text-slate-800"
>
<option value="TOTP">Google Authenticator (TOTP)</option>
<option value="TELEGRAM">OTP via Telegram</option>
</select>
</div>
{mfaSetupData && (
<div className="p-2.5 bg-white rounded-md border border-emerald-200 flex items-center justify-between gap-3">
<div className="space-y-1">
<div className="text-[11px] text-slate-500 flex items-center gap-1">
<QrCode className="h-3.5 w-3.5 text-emerald-600" />
<span>Secret Key Authenticator (Base32):</span>
</div>
<div className="font-mono font-bold text-slate-900 bg-slate-100 px-2 py-1 rounded select-all">
{mfaSetupData.mfaSecret}
</div>
<div className="text-[11px] text-emerald-700 font-semibold">
Kode 6-Digit Saat Ini:{" "}
<span className="font-mono font-bold px-1.5 py-0.5 rounded bg-emerald-100">
{mfaSetupData.currentCode}
</span>
</div>
</div>
<button
type="button"
disabled={loadingMfa}
onClick={() => editUser && fetchMfaDetails(editUser.id, true)}
className="px-2.5 py-1.5 rounded border border-slate-200 hover:bg-slate-50 text-slate-600 flex items-center gap-1 text-[11px] font-semibold shrink-0"
>
<RefreshCw className={`h-3 w-3 ${loadingMfa ? "animate-spin" : ""}`} />
<span>Reset Key</span>
</button>
</div>
)}
</div>
<div>
<label className="block font-semibold text-slate-700 mb-1">ID Chat Telegram Pribadi</label>
<input
type="text"
placeholder="misal: 123456789"
value={editForm.telegramChatId}
onChange={(e) => setEditForm({ ...editForm, telegramChatId: e.target.value })}
className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono"
/>
</div>
<div className="p-3 bg-slate-50 rounded-lg border border-slate-200 space-y-2.5">
<span className="font-bold text-slate-800 flex items-center gap-1.5">
<Bell className="h-3.5 w-3.5 text-blue-600" />
<span>Saluran & Topik Notifikasi User:</span>
</span>
<div className="flex items-center gap-4">
<label className="flex items-center gap-2 cursor-pointer text-slate-700 font-medium">
<input
type="checkbox"
checked={editForm.notifyEmail}
onChange={(e) => setEditForm({ ...editForm, notifyEmail: e.target.checked })}
className="rounded text-blue-600 focus:ring-blue-500"
/>
<span>via Email</span>
</label>
<label className="flex items-center gap-2 cursor-pointer text-slate-700 font-medium">
<input
type="checkbox"
checked={editForm.notifyTelegram}
onChange={(e) => setEditForm({ ...editForm, notifyTelegram: e.target.checked })}
className="rounded text-blue-600 focus:ring-blue-500"
/>
<span>via Telegram</span>
</label>
</div>
<div className="border-t border-slate-200 pt-2">
<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"
onClick={() => setIsEditOpen(false)}
className="px-4 py-2 border border-slate-300 rounded-lg text-slate-600 hover:bg-slate-100 font-semibold"
>
Batal
</button>
<button
type="submit"
disabled={editSubmitting}
className="px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold shadow-xs disabled:opacity-50"
>
{editSubmitting ? "Menyimpan..." : "Simpan Perubahan"}
</button>
</div>
</form>
</Modal>
</AppShell>
);
}
+279
View File
@@ -0,0 +1,279 @@
"use client";
import { ReactNode, useEffect, useState } from "react";
import { Sidebar } from "./Sidebar";
import { Navbar } from "./Navbar";
import { useRouter, usePathname } from "next/navigation";
import { canAccessRoute, getDefaultLandingRoute } from "@/lib/permissions";
import { ShieldAlert, ArrowLeft } from "lucide-react";
import Link from "next/link";
interface UserSession {
id?: string;
name: string;
role: string;
email: string;
}
let memoryCachedUser: UserSession | null = null;
let memoryCachedCompanies: string[] = ["PT EnterpriseCore Utama"];
interface AppShellProps {
children: ReactNode;
title: string;
subtitle?: string;
}
export function AppShell({ children, title, subtitle }: AppShellProps) {
const router = useRouter();
const pathname = usePathname();
const [user, setUser] = useState<UserSession | null>(() => {
if (memoryCachedUser) return memoryCachedUser;
if (typeof window !== "undefined") {
try {
const raw = sessionStorage.getItem("erp_cached_user");
if (raw) {
const parsed = JSON.parse(raw);
memoryCachedUser = parsed;
return parsed;
}
} catch {
// ignore
}
}
return null;
});
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";
}
return "ALL";
});
useEffect(() => {
let mounted = true;
async function checkUser() {
try {
const res = await fetch("/api/auth/me");
if (res.ok) {
const data = await res.json();
if (mounted) {
memoryCachedUser = data.user;
setUser(data.user);
if (Array.isArray(data.companies) && data.companies.length > 0) {
memoryCachedCompanies = data.companies;
setCompanies(data.companies);
}
if (typeof window !== "undefined") {
sessionStorage.setItem("erp_cached_user", JSON.stringify(data.user));
}
}
} else {
memoryCachedUser = null;
if (typeof window !== "undefined") {
sessionStorage.removeItem("erp_cached_user");
}
router.push("/login");
}
} catch (e) {
console.error("Auth check failed:", e);
}
}
checkUser();
const handleExternalCompanyUpdate = (e: any) => {
if (e?.detail?.companies) {
memoryCachedCompanies = e.detail.companies;
setCompanies(e.detail.companies);
}
if (e?.detail?.selectedCompany) {
setSelectedCompany(e.detail.selectedCompany);
localStorage.setItem("erp_selected_pt", e.detail.selectedCompany);
}
};
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]);
const handleSelectCompany = (comp: string) => {
setSelectedCompany(comp);
if (typeof window !== "undefined") {
localStorage.setItem("erp_selected_pt", comp);
window.dispatchEvent(
new CustomEvent("erp:company-changed", {
detail: { selectedCompany: comp, companies },
})
);
}
};
const handleAddCompany = async (newComp: string) => {
const clean = newComp.trim();
if (!clean) return;
try {
const res = await fetch("/api/auth/me", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "ADD_COMPANY", companyName: clean }),
});
const data = await res.json();
const updatedList = Array.isArray(data.companies)
? data.companies
: Array.from(new Set([...companies, clean]));
memoryCachedCompanies = updatedList;
setCompanies(updatedList);
setSelectedCompany(clean);
if (typeof window !== "undefined") {
localStorage.setItem("erp_selected_pt", clean);
window.dispatchEvent(
new CustomEvent("erp:company-changed", {
detail: { selectedCompany: clean, companies: updatedList },
})
);
}
} catch (err) {
console.error("Add company error:", err);
}
};
const handleDeleteCompany = async (targetComp: string) => {
if (!targetComp || targetComp === "ALL") return;
if (user?.role !== "ADMIN") {
alert(
"Akses ditolak: Hanya Super Admin yang dapat menghapus Entitas PT. Selain Super Admin hanya dapat melihat dan menambah PT."
);
return;
}
try {
const res = await fetch("/api/auth/me", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action: "DELETE_COMPANY", companyName: targetComp }),
});
const data = await res.json();
if (!res.ok) {
alert(data.error || "Gagal menghapus PT");
return;
}
const updatedList = Array.isArray(data.companies) ? data.companies : companies;
memoryCachedCompanies = updatedList;
setCompanies(updatedList);
setSelectedCompany("ALL");
if (typeof window !== "undefined") {
localStorage.setItem("erp_selected_pt", "ALL");
window.dispatchEvent(
new CustomEvent("erp:company-changed", {
detail: {
selectedCompany: "ALL",
companies: updatedList,
deleted: targetComp,
},
})
);
}
} catch (err) {
console.error("Delete company 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 (responsive drawer on mobile) */}
<Sidebar
user={user}
mobileOpen={mobileMenuOpen}
onCloseMobile={() => setMobileMenuOpen(false)}
/>
{/* Main Content Area */}
<div className="flex-1 lg:ml-64 flex flex-col min-h-screen min-w-0 w-full">
<Navbar
title={title}
subtitle={subtitle}
userRole={user?.role}
onOpenMobileMenu={() => setMobileMenuOpen(true)}
showCompanySelector={["/finance", "/purchases", "/sales", "/inventory", "/"].includes(pathname)}
canDeleteCompany={user?.role === "ADMIN"}
companies={companies}
selectedCompany={selectedCompany}
onSelectCompany={handleSelectCompany}
onAddCompany={handleAddCompany}
onDeleteCompany={handleDeleteCompany}
/>
<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">
<ShieldAlert className="h-8 w-8" />
</div>
<h2 className="text-xl font-bold text-slate-900 mb-2">
Akses Ditolak (403 Forbidden)
</h2>
<p className="text-sm text-slate-600 mb-6 leading-relaxed">
Akun Anda memiliki peran{" "}
<span className="font-semibold text-rose-600 px-2 py-0.5 rounded bg-rose-50 border border-rose-200">
{user?.role}
</span>
. Peran ini tidak memiliki wewenang untuk membuka modul halaman ini.
</p>
<Link
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 Halaman Utama</span>
</Link>
</div>
) : (
children
)}
</main>
</div>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { cn } from "@/lib/utils";
interface BadgeProps {
status: string;
className?: string;
}
const statusLabels: Record<string, string> = {
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 PO",
REJECTED: "Ditolak",
PAID: "Lunas",
UNPAID: "Belum Lunas",
PARTIAL: "Sebagian / DP",
CONFIRMED: "Dikonfirmasi",
SHIPPED: "Terkirim",
COMPLETED: "Selesai",
DRAFT: "Draft",
CANCELLED: "Dibatalkan",
ACTIVE: "Aktif",
LOW_STOCK: "Stok Menipis",
};
export function StatusBadge({ status, className }: BadgeProps) {
let dotColor = "bg-slate-400";
let style = "bg-slate-50 text-slate-700 border-slate-200/90";
switch (status.toUpperCase()) {
case "PAID":
case "COMPLETED":
case "RECEIVED":
case "RECEIVED_AND_PAID":
case "ACTIVE":
case "APPROVED":
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":
dotColor = "bg-slate-700";
style = "bg-slate-100/80 text-slate-800 border-slate-200";
break;
case "PARTIAL":
case "PENDING":
case "WAITING_APPROVAL":
case "PENDING_FINANCE":
case "PENDING_PURCHASING":
case "ON_HOLD":
case "HOLD":
case "DRAFT":
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":
dotColor = "bg-rose-500";
style = "bg-rose-50/50 text-rose-800 border-rose-200/70";
break;
}
const label = statusLabels[status.toUpperCase()] || status;
return (
<span
className={cn(
"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>
);
}
+419
View File
@@ -0,0 +1,419 @@
"use client";
import React, { useState } from "react";
import { formatRupiah } from "@/lib/utils";
import { TrendingUp, PieChart, Boxes } from "lucide-react";
interface MonthlyTrendItem {
key: string;
label: string;
sales: number;
purchases: number;
hpp?: number;
grossProfit: number;
stockInUnits: number;
stockOutUnits: number;
}
interface FinancialChartProps {
monthlyTrends: MonthlyTrendItem[];
metrics: {
totalRevenue: number;
totalPurchases: number;
inventoryValue: number;
totalCashBank: number;
receivables: number;
payables: number;
stockInUnits: number;
stockOutUnits: number;
};
canSeeFinance?: boolean;
canSeeSalesMoney?: boolean;
canSeePurchaseMoney?: boolean;
}
export function FinancialChart({
monthlyTrends = [],
metrics,
canSeeFinance = true,
canSeeSalesMoney = true,
canSeePurchaseMoney = true,
}: FinancialChartProps) {
const [activeTab, setActiveTab] = useState<"finance" | "liquidity" | "stock">("finance");
const maxFinancialVal = Math.max(
...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
);
const maxStockUnitsVal = Math.max(
...monthlyTrends.map((t) => Math.max(t.stockInUnits, t.stockOutUnits)),
metrics.stockInUnits,
metrics.stockOutUnits,
50
);
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);
return (
<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>
<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>
<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-slate-900 shadow-2xs font-semibold"
: "text-slate-500 hover:text-slate-900"
}`}
>
<TrendingUp className="h-3.5 w-3.5" />
<span>Transaksi</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-slate-900 shadow-2xs font-semibold"
: "text-slate-500 hover:text-slate-900"
}`}
>
<Boxes className="h-3.5 w-3.5" />
<span>Volume Stok</span>
</button>
</div>
</div>
{activeTab === "finance" && (
<div className="pt-5">
<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>
)}
</div>
<span className="text-[11px] text-slate-400">
Arahkan kursor pada batang untuk detail
</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 data transaksi bulanan.
</div>
) : (
monthlyTrends.map((item) => {
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"
>
<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>
{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>
<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-medium text-slate-500 group-hover:text-slate-900 mt-2 truncate max-w-full">
{item.label}
</span>
</div>
);
})
)}
</div>
<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>
)}
{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>
)}
{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>
) : (
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>
)}
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
"use client";
import { ReactNode, useEffect } from "react";
import { X } from "lucide-react";
interface ModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
children: ReactNode;
zIndex?: string;
maxWidth?: string;
}
export function Modal({
isOpen,
onClose,
title,
children,
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-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 my-auto`}
>
<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}
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-4 sm:p-6 max-h-[85vh] overflow-y-auto overflow-x-hidden">{children}</div>
</div>
</div>
);
}
+134
View File
@@ -0,0 +1,134 @@
"use client";
import Link from "next/link";
import {
Bell,
Building2,
FileText,
Menu,
} from "lucide-react";
import { ThemeToggle } from "./ThemeToggle";
export function Navbar({
title,
subtitle,
userRole,
onOpenMobileMenu,
showCompanySelector = false,
companies = ["PT EnterpriseCore Utama"],
selectedCompany = "ALL",
onSelectCompany,
}: {
title: string;
subtitle?: string;
userRole?: string;
onOpenMobileMenu?: () => void;
showCompanySelector?: boolean;
canDeleteCompany?: boolean;
companies?: string[];
selectedCompany?: string;
onSelectCompany?: (company: string) => void;
onAddCompany?: (newCompany: string) => Promise<void>;
onDeleteCompany?: (company: string) => Promise<void>;
}) {
const notifHref = userRole === "ADMIN" || userRole === "MANAGER" ? "/settings" : "/users";
return (
<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"
>
<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>
<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>
)}
{/* 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>
);
}
+125
View File
@@ -0,0 +1,125 @@
"use client";
import { ChevronLeft, ChevronRight } from "lucide-react";
interface PaginationProps {
currentPage: number;
totalItems: number;
pageSize: number;
onPageChange: (page: number) => void;
onPageSizeChange: (size: number) => void;
pageSizeOptions?: number[];
}
export function Pagination({
currentPage,
totalItems,
pageSize,
onPageChange,
onPageSizeChange,
pageSizeOptions = [5, 10, 25, 50],
}: PaginationProps) {
const totalPages = Math.max(1, Math.ceil(totalItems / pageSize));
const safeCurrentPage = Math.min(Math.max(1, currentPage), totalPages);
const startItem = totalItems === 0 ? 0 : (safeCurrentPage - 1) * pageSize + 1;
const endItem = Math.min(safeCurrentPage * pageSize, totalItems);
// Generate visible page numbers
const getPageNumbers = () => {
const pages: (number | string)[] = [];
if (totalPages <= 7) {
for (let i = 1; i <= totalPages; i++) pages.push(i);
} else {
if (safeCurrentPage <= 4) {
pages.push(1, 2, 3, 4, 5, "...", totalPages);
} else if (safeCurrentPage >= totalPages - 3) {
pages.push(1, "...", totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages);
} else {
pages.push(1, "...", safeCurrentPage - 1, safeCurrentPage, safeCurrentPage + 1, "...", totalPages);
}
}
return pages;
};
return (
<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-2 sm:pl-3 border-l border-slate-200">
<span className="text-[11px] text-slate-500">Tampilkan:</span>
<select
value={pageSize}
onChange={(e) => {
onPageSizeChange(Number(e.target.value));
onPageChange(1);
}}
className="px-2 py-1 bg-white border border-slate-300 rounded text-xs font-semibold text-slate-700 focus:outline-none focus:ring-1 focus:ring-blue-500"
>
{pageSizeOptions.map((opt) => (
<option key={opt} value={opt}>
{opt}
</option>
))}
</select>
</div>
</div>
<div className="flex flex-wrap items-center justify-center gap-1">
<button
type="button"
onClick={() => onPageChange(Math.max(1, safeCurrentPage - 1))}
disabled={safeCurrentPage <= 1}
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 className="hidden sm:inline">Sebelumnya</span>
</button>
<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-1.5 text-slate-400 font-bold">
...
</span>
);
}
const pageNum = Number(p);
const isActive = pageNum === safeCurrentPage;
return (
<button
key={pageNum}
type="button"
onClick={() => onPageChange(pageNum)}
className={`min-w-[28px] h-7 px-1.5 rounded-md font-semibold text-xs transition-colors ${
isActive
? "bg-blue-600 text-white shadow-2xs"
: "bg-white border border-slate-200 text-slate-700 hover:bg-slate-100"
}`}
>
{pageNum}
</button>
);
})}
</div>
<button
type="button"
onClick={() => onPageChange(Math.min(totalPages, safeCurrentPage + 1))}
disabled={safeCurrentPage >= totalPages}
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 className="hidden sm:inline">Berikutnya</span>
<ChevronRight className="h-3.5 w-3.5" />
</button>
</div>
</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>
);
}
+382
View File
@@ -0,0 +1,382 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
LayoutDashboard,
Boxes,
ShoppingCart,
Truck,
DollarSign,
Users,
LogOut,
Building2,
Settings,
ChevronDown,
Calculator,
BookOpen,
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", 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: "Purchase Order", icon: Truck },
{ id: "requisitions", name: "Pengajuan", icon: ClipboardList },
{ id: "batches", name: "Batch & Alokasi", icon: Layers },
];
const financeSubMenus = [
{ 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 } | null;
mobileOpen?: boolean;
onCloseMobile?: () => void;
}) {
const pathname = usePathname();
const router = useRouter();
const [financeOpen, setFinanceOpen] = useState(pathname === "/finance");
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 === "/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);
};
const handlePurchasesTabSync = (e: any) => {
if (e?.detail?.tab) setActivePurchasesTab(e.detail.tab);
};
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", 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");
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");
onCloseMobile?.();
};
const handleLogout = async () => {
if (typeof window !== "undefined") {
sessionStorage.removeItem("erp_cached_user");
}
await fetch("/api/auth/logout", { method: "POST" });
window.location.href = "/login";
};
const allowedNav = allNavigation.filter((item) =>
user?.role ? canAccessRoute(user.role, item.href) : true
);
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 (
<>
{mobileOpen && (
<div
className="fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-[1px] lg:hidden"
onClick={onCloseMobile}
aria-hidden="true"
/>
)}
<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">
<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>
{/* 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>
</>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { ReactNode } from "react";
import { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
interface StatCardProps {
title: string;
value: string;
description?: string;
icon: LucideIcon;
variant?: "blue" | "emerald" | "amber" | "rose" | "purple" | "neutral";
badge?: ReactNode;
}
export function StatCard({
title,
value,
description,
icon: Icon,
badge,
}: StatCardProps) {
return (
<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 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-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>
);
}
+32
View File
@@ -0,0 +1,32 @@
import { prisma } from "./db";
export async function logAudit({
userId,
userName,
action,
module,
description,
metadata,
}: {
userId?: string;
userName?: string;
action: string;
module: "INVENTORY" | "SALES" | "PURCHASING" | "FINANCE" | "AUTH" | "SYSTEM";
description: string;
metadata?: Record<string, unknown> | null;
}) {
try {
await prisma.auditLog.create({
data: {
userId: userId || null,
userName: userName || "System",
action,
module,
description,
metadata: metadata ? JSON.stringify(metadata) : null,
},
});
} catch (error) {
console.error("Failed to write audit log:", error);
}
}
+148
View File
@@ -0,0 +1,148 @@
import { SignJWT, jwtVerify } from "jose";
import bcrypt from "bcryptjs";
import { cookies } from "next/headers";
import { getPrismaByMode, type EnvMode } from "./db";
const SECRET_KEY = new TextEncoder().encode(
process.env.JWT_SECRET || "enterprisecore-secret-jwt-key-2026-production-ready"
);
export interface SessionUser {
id: string;
email: string;
name: string;
role: string;
envMode?: EnvMode;
}
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, 10);
}
export async function comparePassword(password: string, hash: string): Promise<boolean> {
return bcrypt.compare(password, hash);
}
export async function signToken(user: SessionUser): Promise<string> {
return new SignJWT({
id: user.id,
email: user.email,
name: user.name,
role: user.role,
envMode: "LIVE",
})
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("24h")
.sign(SECRET_KEY);
}
export async function verifyToken(token: string): Promise<SessionUser | null> {
try {
const { payload } = await jwtVerify(token, SECRET_KEY, {
algorithms: ["HS256"],
});
return {
id: payload.id as string,
email: payload.email as string,
name: payload.name as string,
role: payload.role as string,
envMode: "LIVE",
};
} catch {
return null;
}
}
export async function getCurrentUser(): Promise<SessionUser | null> {
try {
const cookieStore = await cookies();
const token = cookieStore.get("erp_session")?.value;
if (!token) return null;
const user = await verifyToken(token);
if (!user) return null;
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 {
id: dbUser.id,
email: dbUser.email,
name: dbUser.name,
role: dbUser.role,
envMode,
};
} catch {
return null;
}
}
// =========================================================================
// Rate Limiter In-Memory untuk Proteksi Brute-Force Login & OTP MFA
// =========================================================================
interface RateLimitRecord {
count: number;
resetAt: number;
}
const rateLimitStore = new Map<string, RateLimitRecord>();
const MAX_ATTEMPTS = 5;
const WINDOW_MS = 5 * 60 * 1000; // 5 menit
export function checkRateLimit(key: string): { allowed: boolean; retryAfterSec: number } {
const now = Date.now();
const entry = rateLimitStore.get(key);
if (!entry || now > entry.resetAt) {
return { allowed: true, retryAfterSec: 0 };
}
if (entry.count >= MAX_ATTEMPTS) {
const retryAfterSec = Math.max(1, Math.ceil((entry.resetAt - now) / 1000));
return { allowed: false, retryAfterSec };
}
return { allowed: true, retryAfterSec: 0 };
}
export function recordFailedAttempt(key: string): void {
const now = Date.now();
const entry = rateLimitStore.get(key);
if (!entry || now > entry.resetAt) {
rateLimitStore.set(key, { count: 1, resetAt: now + WINDOW_MS });
} else {
entry.count += 1;
}
}
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);
}
+98
View File
@@ -0,0 +1,98 @@
import { prisma } from "@/lib/db";
export const DEFAULT_COMPANIES = ["PT EnterpriseCore Utama"];
export const DEFAULT_ACCOUNTS_TEMPLATE = [
{ code: "1001", name: "Kas Kantor Operasional", type: "ASSET" },
{ 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" },
{ code: "6001", name: "Beban Gaji & Operasional", type: "EXPENSE" },
];
export async function getSavedCompanies(): Promise<string[]> {
try {
const setting = await prisma.systemSetting.findUnique({
where: { key: "PAYROLL_COMPANIES" },
});
if (setting?.value) {
try {
const parsed: string[] = JSON.parse(setting.value);
const filtered = parsed.filter(Boolean);
if (filtered.length > 0) {
return Array.from(new Set(filtered));
}
} catch {
// ignore
}
}
return DEFAULT_COMPANIES;
} catch {
return DEFAULT_COMPANIES;
}
}
export async function ensureCompanyAccounts(companyName: string) {
const cleanComp = (companyName || "").trim();
if (!cleanComp) return;
for (const t of DEFAULT_ACCOUNTS_TEMPLATE) {
const existing = await prisma.account.findFirst({
where: { code: t.code, companyName: cleanComp },
});
if (!existing) {
await prisma.account.create({
data: {
code: t.code,
name: cleanComp === "PT EnterpriseCore Utama" ? t.name : `${t.name} (${cleanComp})`,
type: t.type,
companyName: cleanComp,
balance: 0,
},
});
}
}
}
export async function getCompanyAccount(code: string, companyName?: string) {
const cleanComp = (companyName || "").trim();
if (cleanComp && cleanComp !== "ALL") {
const matched = await prisma.account.findFirst({
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 hanya jika benar-benar tidak ada companyName yang dikirim
const fallback = await prisma.account.findFirst({
where: { code, companyName: "PT EnterpriseCore Utama" },
});
if (fallback) return fallback;
return prisma.account.findFirst({ where: { code } });
}
+30
View File
@@ -0,0 +1,30 @@
import { PrismaClient } from "@prisma/client";
export type EnvMode = "LIVE";
const globalForPrisma = globalThis as unknown as {
prismaLive: PrismaClient | undefined;
};
const liveDbUrl = process.env.LIVE_DATABASE_URL || process.env.DATABASE_URL || "file:./live.db";
export const prismaLive =
globalForPrisma.prismaLive ??
new PrismaClient({
datasources: { db: { url: liveDbUrl } },
log: ["error"],
});
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prismaLive = prismaLive;
}
export async function getEnvMode(): Promise<EnvMode> {
return "LIVE";
}
export function getPrismaByMode(_mode?: string): PrismaClient {
return prismaLive;
}
export const prisma = prismaLive;
+131
View File
@@ -0,0 +1,131 @@
import crypto from "crypto";
import { SignJWT, jwtVerify } from "jose";
import type { EnvMode } from "./db";
const SECRET_KEY = new TextEncoder().encode(
process.env.JWT_SECRET || "enterprisecore-secret-jwt-key-2026-production-ready"
);
const BASE32_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
export function generateMfaSecret(length = 16): string {
const bytes = crypto.randomBytes(length);
let secret = "";
for (let i = 0; i < length; i++) {
secret += BASE32_CHARS[bytes[i] % 32];
}
return secret;
}
function base32ToBuffer(base32: string): Buffer {
const cleaned = base32.toUpperCase().replace(/[^A-Z2-7]/g, "");
let bits = "";
for (let i = 0; i < cleaned.length; i++) {
const val = BASE32_CHARS.indexOf(cleaned[i]);
if (val === -1) continue;
bits += val.toString(2).padStart(5, "0");
}
const bytes: number[] = [];
for (let i = 0; i + 8 <= bits.length; i += 8) {
bytes.push(parseInt(bits.slice(i, i + 8), 2));
}
return Buffer.from(bytes);
}
export function generateTOTP(secret: string, windowOffset = 0): string {
const key = base32ToBuffer(secret);
const epoch = Math.floor(Date.now() / 1000);
const counter = Math.floor(epoch / 30) + windowOffset;
const counterBuf = Buffer.alloc(8);
counterBuf.writeUInt32BE(Math.floor(counter / 0x100000000), 0);
counterBuf.writeUInt32BE(counter & 0xffffffff, 4);
const hmac = crypto.createHmac("sha1", key).update(counterBuf).digest();
const offset = hmac[hmac.length - 1] & 0x0f;
const binary =
((hmac[offset] & 0x7f) << 24) |
((hmac[offset + 1] & 0xff) << 16) |
((hmac[offset + 2] & 0xff) << 8) |
(hmac[offset + 3] & 0xff);
const otp = binary % 1000000;
return otp.toString().padStart(6, "0");
}
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]) {
const expectedBuf = Buffer.from(generateTOTP(secret, offset), "utf8");
if (expectedBuf.length === providedBuf.length && crypto.timingSafeEqual(expectedBuf, providedBuf)) {
return true;
}
}
return false;
}
export function getOtpAuthUri(email: string, secret: string): string {
const label = encodeURIComponent(`EnterpriseCore:${email}`);
return `otpauth://totp/${label}?secret=${secret}&issuer=EnterpriseCore&algorithm=SHA1&digits=6&period=30`;
}
export interface MfaChallengePayload {
userId: string;
email: string;
envMode: EnvMode;
mfaMethod: string;
otpHash?: string;
}
const HMAC_SECRET =
process.env.JWT_SECRET || "enterprisecore-secret-jwt-key-2026-production-ready";
export function hashDynamicOtp(code: string): string {
return crypto
.createHmac("sha256", HMAC_SECRET)
.update(code.trim())
.digest("hex");
}
export function verifyDynamicOtpHash(code: string, expectedHash?: string): boolean {
if (!expectedHash || !code) return false;
const computed = hashDynamicOtp(code);
const a = Buffer.from(computed, "hex");
const b = Buffer.from(expectedHash, "hex");
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}
export async function signMfaChallenge(payload: MfaChallengePayload): Promise<string> {
return new SignJWT({
userId: payload.userId,
email: payload.email,
envMode: payload.envMode,
mfaMethod: payload.mfaMethod,
...(payload.otpHash ? { otpHash: payload.otpHash } : {}),
})
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("5m")
.sign(SECRET_KEY);
}
export async function verifyMfaChallenge(token: string): Promise<MfaChallengePayload | null> {
try {
const { payload } = await jwtVerify(token, SECRET_KEY, {
algorithms: ["HS256"],
});
return {
userId: payload.userId as string,
email: payload.email as string,
envMode: (payload.envMode as EnvMode) || "LIVE",
mfaMethod: (payload.mfaMethod as string) || "TOTP",
otpHash: (payload.otpHash as string) || undefined,
};
} catch {
return null;
}
}
+384
View File
@@ -0,0 +1,384 @@
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 {
type: NotificationType;
title: string;
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
TELEGRAM_CHAT_ID_SALES: "", // Divisi Penjualan
TELEGRAM_CHAT_ID_PURCHASING: "", // Divisi Pengadaan
TELEGRAM_CHAT_ID_FINANCE: "", // Divisi Keuangan & Akuntansi
// Global trigger rules
NOTIF_STOCK_IN_ENABLED: "true",
NOTIF_STOCK_OUT_ENABLED: "true",
NOTIF_MONEY_IN_ENABLED: "true",
NOTIF_MONEY_OUT_ENABLED: "true",
NOTIF_RMA_ENABLED: "true",
// Email SMTP
SMTP_HOST: "",
SMTP_PORT: "587",
SMTP_USER: "",
SMTP_PASS: "",
SMTP_FROM: "erp-system@nusantara.id",
};
export async function getAllSettings(dbClient?: PrismaClient): Promise<Record<string, string>> {
try {
const db = dbClient || prisma;
const list = await db.systemSetting.findMany();
const result = { ...DEFAULT_SETTINGS };
list.forEach((item) => {
result[item.key] = item.value;
});
return result;
} catch {
return DEFAULT_SETTINGS;
}
}
export async function sendTelegramMessage(
token: string,
chatId: string,
text: string
): Promise<{ success: boolean; error?: string }> {
if (!token || !chatId) {
return {
success: false,
error: "Telegram Bot Token atau Chat ID belum dikonfigurasi",
};
}
try {
const url = `https://api.telegram.org/bot${token}/sendMessage`;
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
chat_id: chatId,
text,
parse_mode: "HTML",
}),
});
const data = await res.json();
if (!res.ok || !data.ok) {
return { success: false, error: data.description || "Gagal mengirim ke Telegram" };
}
return { success: true };
} catch (err: any) {
return { success: false, error: err.message };
}
}
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 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 sesuai KAPASITAS masing-masing
let baseAllowedRoles: string[] = [];
const targetDivisionChannels: string[] = [];
switch (type) {
case "STOCK_IN":
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":
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":
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":
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:
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]"
: type === "STOCK_OUT"
? "📤 [BARANG KELUAR]"
: type === "MONEY_IN"
? "💰 [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(
"id-ID"
)}</i>`;
// 3. Kirim ke Saluran Grup/Channel Telegram Divisi yang Ditargetkan
if (telegramEnabled && botToken && targetDivisionChannels.length > 0) {
const uniqueChannels = [...new Set(targetDivisionChannels)];
for (const chatId of uniqueChannels) {
const res = await sendTelegramMessage(botToken, chatId, formattedTelegramText);
await db.notificationLog.create({
data: {
recipient: `Grup Divisi TG (${chatId})`,
channel: "TELEGRAM",
type,
title,
message,
status: res.success ? "SENT" : "FAILED",
},
});
}
}
// 4. Kirim ke Pengguna Aktif di Divisi Terkait (Email & Telegram Pribadi sesuai kapasitas role)
const users = await db.user.findMany({
where: {
isActive: true,
role: { in: effectiveRoles },
},
});
for (const u of users) {
// 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, userTelegramText);
await db.notificationLog.create({
data: {
recipient: `${u.name} [${u.role}] (TG: ${u.telegramChatId})`,
channel: "TELEGRAM",
type,
title,
message: safeMessageForRole,
status: res.success ? "SENT" : "FAILED",
},
});
}
// Kirim via Email SMTP staf jika aktif
if (emailEnabled && u.notifyEmail && u.email) {
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: safeMessageForRole,
status: mailRes.status,
},
});
}
}
} catch (error) {
console.error("Failed to dispatch notification:", error);
}
}
+254
View File
@@ -0,0 +1,254 @@
export type Role =
| "ADMIN"
| "MANAGER"
| "INVENTORY"
| "SALES"
| "PURCHASING"
| "ACCOUNTANT";
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;
canCreateSalesOrder: boolean;
canUpdateSalesStatus: boolean;
canCreateRequisition: boolean;
canCreatePurchaseOrder: boolean;
canApproveFinancePurchase: boolean;
canReceiveGoods: boolean;
canCreateJournal: boolean;
canViewFinance: boolean;
canViewUsers: boolean;
canViewAudit: boolean;
canViewPriceAndHpp: boolean; // Khusus Sales, Finance, Manager, dan Admin
}
> = {
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,
canCreateSalesOrder: true,
canUpdateSalesStatus: true,
canCreateRequisition: true,
canCreatePurchaseOrder: true,
canApproveFinancePurchase: true,
canReceiveGoods: true,
canCreateJournal: true,
canViewFinance: true,
canViewUsers: true,
canViewAudit: true,
canViewPriceAndHpp: true,
},
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,
canCreateSalesOrder: true,
canUpdateSalesStatus: true,
canCreateRequisition: true,
canCreatePurchaseOrder: true,
canApproveFinancePurchase: true,
canReceiveGoods: true,
canCreateJournal: false, // Jurnal khusus Akuntan & Admin
canViewFinance: true,
canViewUsers: true,
canViewAudit: true,
canViewPriceAndHpp: true,
},
INVENTORY: {
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,
canCreateSalesOrder: false,
canUpdateSalesStatus: false,
canCreateRequisition: true, // Gudang boleh mengajukan restock jika barang menipis
canCreatePurchaseOrder: false,
canApproveFinancePurchase: false,
canReceiveGoods: true, // Boleh memverifikasi & menerima fisik barang datang dari distributor
canCreateJournal: false,
canViewFinance: false,
canViewUsers: true, // Bisa melihat dan mengedit profil sendiri
canViewAudit: true, // Bisa melihat riwayat PO, stok, dan pembelian operasional
canViewPriceAndHpp: false, // Gudang tidak boleh melihat harga jual & HPP keuntungan
},
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,
canCreateSalesOrder: true,
canUpdateSalesStatus: true,
canCreateRequisition: true, // Sales berwenang membuat Pengajuan Pembelian Barang
canCreatePurchaseOrder: false,
canApproveFinancePurchase: false,
canReceiveGoods: false,
canCreateJournal: false,
canViewFinance: false,
canViewUsers: true, // Bisa melihat dan mengedit profil sendiri
canViewAudit: true, // Bisa melihat riwayat PO, stok, dan pembelian operasional
canViewPriceAndHpp: true, // Sales berhak melihat harga jual dan HPP untuk negosiasi & penawaran
},
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,
canCreateSalesOrder: false,
canUpdateSalesStatus: false,
canCreateRequisition: true,
canCreatePurchaseOrder: true, // Purchasing berwenang memproses pengajuan jadi PO ke vendor
canApproveFinancePurchase: false,
canReceiveGoods: true,
canCreateJournal: false,
canViewFinance: false,
canViewUsers: true, // Bisa melihat dan mengedit profil sendiri
canViewAudit: true, // Bisa melihat riwayat PO, stok, dan pembelian operasional
canViewPriceAndHpp: false, // Purchasing fokus ke harga beli PO ke vendor, tidak melihat margin jual & HPP perusahaan
},
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,
canCreateSalesOrder: false,
canUpdateSalesStatus: true, // Boleh mengubah status pembayaran (PAID)
canCreateRequisition: false,
canCreatePurchaseOrder: false,
canApproveFinancePurchase: true, // Finance / Akuntan berwenang approve anggaran pembelian
canReceiveGoods: false,
canCreateJournal: true, // Akuntan berwenang membuat jurnal
canViewFinance: true,
canViewUsers: true, // Bisa melihat dan mengedit profil sendiri
canViewAudit: true,
canViewPriceAndHpp: true, // Finance berhak penuh melihat HPP & harga jual untuk pembukuan laba rugi
},
};
export function canAccessRoute(role: string | undefined, pathname: string): boolean {
if (!role) return false;
const userRole = (role as Role) || "SALES";
const permissions = ROLE_PERMISSIONS[userRole];
if (!permissions) return false;
// Exact match or sub-path match
return permissions.allowedRoutes.some(
(route) => pathname === route || (route !== "/" && pathname.startsWith(route))
);
}
export function getRolePermissions(role: string | undefined) {
const userRole = (role as Role) || "SALES";
return ROLE_PERMISSIONS[userRole] || ROLE_PERMISSIONS.SALES;
}
export function canViewPriceAndHpp(role: string | undefined): boolean {
if (!role) return false;
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);
}
+74
View File
@@ -0,0 +1,74 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export function formatRupiah(amount: number): string {
return new Intl.NumberFormat("id-ID", {
style: "currency",
currency: "IDR",
maximumFractionDigits: 0,
}).format(amount);
}
export function formatDate(date: string | Date): string {
const d = new Date(date);
return d.toLocaleDateString("id-ID", {
day: "numeric",
month: "short",
year: "numeric",
});
}
export function formatDateTime(date: string | Date): string {
const d = new Date(date);
return d.toLocaleDateString("id-ID", {
day: "numeric",
month: "short",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
});
}
export function escapeHtml(value: unknown): string {
return String(value ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
export function exportToCSV(
filename: string,
headers: string[],
rows: (string | number | null | undefined)[][]
) {
if (typeof window === "undefined") return;
const escapeCell = (val: string | number | null | undefined) => {
let str = String(val ?? "").replace(/"/g, '""');
// Prevent CSV Formula Injection when opened in Excel
if (/^[=+\-@\t\r]/.test(str)) {
str = `'${str}`;
}
return `"${str}"`;
};
const csvContent =
"\uFEFF" +
[headers.map(escapeCell).join(","), ...rows.map((r) => r.map(escapeCell).join(","))].join(
"\r\n"
);
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", filename.endsWith(".csv") ? filename : `${filename}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
+95
View File
@@ -0,0 +1,95 @@
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"
);
const PUBLIC_PATHS = [
"/login",
"/rma",
"/api/public/rma",
"/api/auth/login",
"/api/auth/mfa",
"/api/auth/logout",
];
function applySecurityHeaders(res: NextResponse): NextResponse {
res.headers.set("X-Frame-Options", "DENY");
res.headers.set("X-Content-Type-Options", "nosniff");
res.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
res.headers.set(
"Permissions-Policy",
"camera=(), microphone=(), geolocation=()"
);
res.headers.set("X-XSS-Protection", "1; mode=block");
res.headers.set(
"Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none';"
);
return res;
}
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// Skip static assets and Next.js internals (never bypass /api/ routes)
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/favicon") ||
(!pathname.startsWith("/api/") && pathname.includes("."))
) {
return applySecurityHeaders(NextResponse.next());
}
// Allow public auth endpoints and login page
if (PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
return applySecurityHeaders(NextResponse.next());
}
const token = req.cookies.get("erp_session")?.value;
if (!token) {
if (pathname.startsWith("/api/")) {
return applySecurityHeaders(
NextResponse.json(
{ error: "Sesi tidak valid atau belum terautentikasi." },
{ status: 401 }
)
);
}
const loginUrl = new URL("/login", req.url);
return applySecurityHeaders(NextResponse.redirect(loginUrl));
}
try {
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/")) {
return applySecurityHeaders(
NextResponse.json(
{ error: "Sesi telah kedaluwarsa. Silakan login kembali." },
{ status: 401 }
)
);
}
const loginUrl = new URL("/login", req.url);
const response = NextResponse.redirect(loginUrl);
response.cookies.delete("erp_session");
return applySecurityHeaders(response);
}
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
+105
View File
@@ -0,0 +1,105 @@
export type Role =
| "ADMIN"
| "MANAGER"
| "INVENTORY"
| "SALES"
| "PURCHASING"
| "ACCOUNTANT";
export interface UserSummary {
id: string;
name: string;
email: string;
role: Role;
createdAt: string;
}
export interface ProductItem {
id: string;
sku: string;
name: string;
description?: string | null;
unit: string;
purchasePrice: number;
sellingPrice: number;
minStock: number;
category?: { id: string; name: string } | null;
totalStock: number;
stockItems?: {
id: string;
warehouse: { id: string; name: string; code: string };
quantity: number;
}[];
}
export interface CustomerItem {
id: string;
code: string;
name: string;
company?: string | null;
email?: string | null;
phone?: string | null;
address?: string | null;
}
export interface SupplierItem {
id: string;
code: string;
name: string;
contactPerson?: string | null;
email?: string | null;
phone?: string | null;
address?: string | null;
}
export interface SalesOrderItem {
id: string;
orderNumber: string;
customer: { id: string; name: string; company?: string | null };
orderDate: string;
status: "DRAFT" | "CONFIRMED" | "SHIPPED" | "COMPLETED" | "CANCELLED";
paymentStatus: "UNPAID" | "PARTIAL" | "PAID";
totalAmount: number;
notes?: string | null;
items: {
id: string;
product: { id: string; sku: string; name: string };
quantity: number;
unitPrice: number;
subtotal: number;
}[];
}
export interface PurchaseOrderItem {
id: string;
poNumber: string;
supplier: { id: string; name: string };
orderDate: string;
status: "DRAFT" | "ORDERED" | "RECEIVED" | "CANCELLED";
totalAmount: number;
notes?: string | null;
items: {
id: string;
product: { id: string; sku: string; name: string };
quantity: number;
unitCost: number;
subtotal: number;
}[];
}
export interface AccountItem {
id: string;
code: string;
name: string;
type: "ASSET" | "LIABILITY" | "EQUITY" | "REVENUE" | "EXPENSE";
balance: number;
}
export interface AuditLogItem {
id: string;
userName?: string | null;
action: string;
module: string;
description: string;
createdAt: string;
}
+28
View File
@@ -0,0 +1,28 @@
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}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
brand: {
50: "#eff6ff",
100: "#dbeafe",
500: "#3b82f6",
600: "#2563eb",
700: "#1d4ed8",
800: "#1e40af",
900: "#1e3a8a",
},
},
},
},
plugins: [],
};
export default config;
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
+1
View File
@@ -0,0 +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