From 5c70b9713b14427f970c33ba8f1705a01ce8c5e2 Mon Sep 17 00:00:00 2001 From: Yoga Pratama Date: Fri, 27 Nov 2026 17:04:52 +0700 Subject: [PATCH] Initial clean release EnterpriseCore ERP v3.0 --- .dockerignore | 11 + .env.example | 4 + .gitignore | 14 + Dockerfile | 33 + ...uan_Alur_Penggunaan_EnterpriseCore_ERP.pdf | Bin 0 -> 15611 bytes README.md | 109 + docker-compose.yml | 28 + entrypoint.sh | 11 + next-env.d.ts | 6 + next.config.ts | 8 + package-lock.json | 2924 +++++++++++ package.json | 44 + postcss.config.mjs | 6 + prisma/schema.postgres.prisma | 263 + prisma/schema.prisma | 488 ++ prisma/schema.sqlite.prisma | 288 ++ prisma/seed.js | 231 + ...uan_Alur_Penggunaan_EnterpriseCore_ERP.pdf | Bin 0 -> 15611 bytes scripts/generate-guide-pdf.js | 486 ++ scripts/switch-db.js | 53 + src/app/api/auth/login/route.ts | 202 + src/app/api/auth/logout/route.ts | 8 + src/app/api/auth/me/route.ts | 136 + src/app/api/auth/mfa/route.ts | 185 + src/app/api/dashboard/route.ts | 383 ++ src/app/api/devices/route.ts | 547 ++ src/app/api/finance/route.ts | 1276 +++++ src/app/api/inventory/route.ts | 742 +++ src/app/api/public/rma/route.ts | 543 ++ src/app/api/purchases/route.ts | 1841 +++++++ src/app/api/sales/route.ts | 1778 +++++++ src/app/api/settings/backup/route.ts | 77 + src/app/api/settings/route.ts | 236 + src/app/api/users/route.ts | 420 ++ src/app/finance/page.tsx | 2973 +++++++++++ src/app/globals.css | 599 +++ src/app/inventory/page.tsx | 2986 +++++++++++ src/app/layout.tsx | 48 + src/app/login/page.tsx | 336 ++ src/app/page.tsx | 682 +++ src/app/purchases/page.tsx | 3907 ++++++++++++++ src/app/rma/page.tsx | 782 +++ src/app/sales/page.tsx | 4605 +++++++++++++++++ src/app/settings/page.tsx | 758 +++ src/app/users/page.tsx | 911 ++++ src/components/AppShell.tsx | 279 + src/components/Badge.tsx | 86 + src/components/CurrencyInput.tsx | 75 + src/components/FinancialChart.tsx | 419 ++ src/components/Modal.tsx | 59 + src/components/Navbar.tsx | 134 + src/components/Pagination.tsx | 125 + src/components/SerialNumberInput.tsx | 306 ++ src/components/Sidebar.tsx | 382 ++ src/components/StatCard.tsx | 42 + src/components/ThemeToggle.tsx | 57 + src/lib/audit.ts | 32 + src/lib/auth.ts | 148 + src/lib/companies.ts | 98 + src/lib/db.ts | 30 + src/lib/mfa.ts | 131 + src/lib/notifier.ts | 384 ++ src/lib/permissions.ts | 254 + src/lib/utils.ts | 74 + src/middleware.ts | 95 + src/types/erp.ts | 105 + tailwind.config.ts | 28 + tsconfig.json | 27 + tsconfig.tsbuildinfo | 1 + 69 files changed, 35339 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf create mode 100644 README.md create mode 100644 docker-compose.yml create mode 100755 entrypoint.sh create mode 100644 next-env.d.ts create mode 100644 next.config.ts create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 postcss.config.mjs create mode 100644 prisma/schema.postgres.prisma create mode 100644 prisma/schema.prisma create mode 100644 prisma/schema.sqlite.prisma create mode 100644 prisma/seed.js create mode 100644 public/Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf create mode 100644 scripts/generate-guide-pdf.js create mode 100644 scripts/switch-db.js create mode 100644 src/app/api/auth/login/route.ts create mode 100644 src/app/api/auth/logout/route.ts create mode 100644 src/app/api/auth/me/route.ts create mode 100644 src/app/api/auth/mfa/route.ts create mode 100644 src/app/api/dashboard/route.ts create mode 100644 src/app/api/devices/route.ts create mode 100644 src/app/api/finance/route.ts create mode 100644 src/app/api/inventory/route.ts create mode 100644 src/app/api/public/rma/route.ts create mode 100644 src/app/api/purchases/route.ts create mode 100644 src/app/api/sales/route.ts create mode 100644 src/app/api/settings/backup/route.ts create mode 100644 src/app/api/settings/route.ts create mode 100644 src/app/api/users/route.ts create mode 100644 src/app/finance/page.tsx create mode 100644 src/app/globals.css create mode 100644 src/app/inventory/page.tsx create mode 100644 src/app/layout.tsx create mode 100644 src/app/login/page.tsx create mode 100644 src/app/page.tsx create mode 100644 src/app/purchases/page.tsx create mode 100644 src/app/rma/page.tsx create mode 100644 src/app/sales/page.tsx create mode 100644 src/app/settings/page.tsx create mode 100644 src/app/users/page.tsx create mode 100644 src/components/AppShell.tsx create mode 100644 src/components/Badge.tsx create mode 100644 src/components/CurrencyInput.tsx create mode 100644 src/components/FinancialChart.tsx create mode 100644 src/components/Modal.tsx create mode 100644 src/components/Navbar.tsx create mode 100644 src/components/Pagination.tsx create mode 100644 src/components/SerialNumberInput.tsx create mode 100644 src/components/Sidebar.tsx create mode 100644 src/components/StatCard.tsx create mode 100644 src/components/ThemeToggle.tsx create mode 100644 src/lib/audit.ts create mode 100644 src/lib/auth.ts create mode 100644 src/lib/companies.ts create mode 100644 src/lib/db.ts create mode 100644 src/lib/mfa.ts create mode 100644 src/lib/notifier.ts create mode 100644 src/lib/permissions.ts create mode 100644 src/lib/utils.ts create mode 100644 src/middleware.ts create mode 100644 src/types/erp.ts create mode 100644 tailwind.config.ts create mode 100644 tsconfig.json create mode 100644 tsconfig.tsbuildinfo diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..10d39d4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +node_modules +.next +.git +.env +.env.* +prisma/*.db +prisma/*.db-journal +prisma/*.db-wal +prisma/*.db-shm +*.log +tsconfig.tsbuildinfo diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..22163f3 --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..06e8077 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..72f9b20 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf b/Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2ad03bde68660a5a6160acbd610b2ecd493d26af GIT binary patch literal 15611 zcmch;WmH|;vNcL@haf?MEF6L^+}%A$aCdiiC%C)2ySux)yF+j%As^X$=be4`Ij`NX zz5CjoKbXuKHAmHuxmvFp)k$Opg{grw46r0W-!51d03EgW*1*yp0DNnfgQb-+&^OWHw{ixk(Y*}?HnEMT3} z)>T&{J~qGiSX8=%8Y2mHAb2N$)S3!DB;eh5^I@+$rX?EW9&{LV_yS5%zcFQ<3p@NQ zJ-`CYuOpi3!(?%34jfIB(=4p#gGXc`F(C|4=?{-jT(9hRX&hOu3cv@~M zgSNo-;lE~ShxL&As9$FLE3=9Ypv8h5*BaAe;J0c`cH#`o`%fQxdE8tGti>J;7T$BR zk4e+J7Mx{p<9j|5vGP7J;=R7&eTCv9eFp=oP7Ku9`Rok?it;WX7w)IEj2HL!?c>YE z@d{f*U?Y;?IavT*1=vf210Mph1Hs;3d!Vs=lu3ds{=fQ@|uihLnK7^1e+6VA@?uvz#&sSBsNj2F)j94HJvG3jWh8 z-YFA|(Id#JM(qNk1ZIs!pWCY=@}`F=x6alHfAQ;pk!Q&%!wGoK5)T7)Xobn4HR}|6 zBdGZ@bq^yB3R9tP$4^X!hb#Q(4#hC@7|qk3Hb3tfV!l9A#5h!+A zf)qyx+rqHeB*NE)PSh|U77T@nKgAvzxwvFLojh92)`;y?p?R zKDNwlyx?KY?EOm5DM5|77YTBz}s zSEt8IMZJkcq~Il;cUn=}?Ad27o9WCFkyes6E>L3&!(!jqr8p8FWY@n`=BZXUsyr(PU{S@?YUEgE@E$9>Rh%nfUXd`081dW zrZOPgAk-dySzgy2%*$p|Zj+`M@J!BTrJN7cUm58 zsaF_a2a>hkCb+>1-eSUe71oI+bE562)g8&LuoMW?QR8^UYbpK zX%6k+dppJKp;~Z_DKRzcw zT7O@pGN46C6RXj9Bwo&K9KZ{P%TTcZeKPaXSAU;tQTv`Kzzp|rKAu9uPDTC`5~MlB zR}mPsNw->lCXo!<{NUyf_k9j5fW)O79XX(HEh5bEy^ z9^ef*!6w4)(x}Ef0s>J?!mOs{aQh5bEnrI#eZO3pk#uqui&qP_=eMs)@83dbMn%#n zwLuNRe0V7L&H9$wj40x`xI@$Ng$M)0(;rCSI#RP6NA?=yKs;5}-$Ze&@)gB>>zW_- zr=t3lhlEG1JJ|b4X9jOGgO6~o8yj#ApaUC1Dbq^q#s}0jrWofKQ;{?Wboqx)O4FHU z@%0nlpRFnx)7c3o8SAtWIE-_Xkc7@PrrLAN(7_b+q?{0rUv zM|k!}<8P?+zlP8LaPqg+zW^EoJw5Qh2Wa2Y#v}Hc5WFw$&^&$S#nHsXy0Va3pWfL* zM~$ud;k4Y7&t}(~%<>+JO zY^Tim5ekn7#ShCaR)0*%V4cV7yW3rS?cl&b+M8pmOk_()t00*pwI!hKZt~;NU-yrCCAN^^);R4kcZNMQ|3RcE5T&UKh?@bf&%5q&o2M zC9i6SYs6=XM{^JU=<7u##VfO^8e65F?Wlso^hV9}gOccCh?LZ}*-Hi^%g`Q^A1SeB zbl25o+eyI9T)qNN5PjX3owGK?plaP>gNXC$CcFy3CBx%T)W#u9742O_)uF3myig_i z@%>3($~fLftSn1jWv)UqlGFY5X_Cxr=W=uQFnvX*s(^v{&~It=pp)!qsWuzAHfBAl zCSsW33X{BR{L-(87Fnc9iXqE5jfewpxj2KgD(p$iULR<}0nvfQd+r@38KyG$#8UNc z-_s_l6$RP+GOhB{y&6(Jh&I8Fkc_u&Ypqm}tYsw}0Q9(=3WJQ7S1AJ=38o;`XP(^N zH8HhYB|SMdnOZmxbcG6DOAsMVKV@cs%3U9eT1l`f-Gozme+vO>t%x&^Gq<1I1#yU> zwAv2EPQf6=wQY#%Kr7BuyG0!zBBLg7;iflfzN|L&7J8@!S!xI@rZVRy6ASFBX^jR5 zi-q)siFUBgiGP)Io^5EHx-?SU{(yLp#xSR|HD{YMwRo27sr$(|DTmt}fV4Ve<3vbI zbc&_@jS4AGz)V*cw(Z^-myTwVs!5xbms{rio!Jx-2;zA1J3u65V&%8bd8Os8s48IG zBP3>Ij%57@Ik{zop^{F`)gkJW3WfD2I-EcB8b9T2yld`GK`WQp5)ESl>{nRk+q8&| z;j??n4tBayANJON@7EyD_tB$=4+}+=g1olfP3JUKPUz+BJ`nnVOQbayG~#=TeB}#6 zc4Xr{vxON}OC`LkV&!$b^wOOaK1Cx;F<|Tl7hj>6NUx|BClWMr8W{3LLFOB7%?YK4 zjL|LlybV27))xf~$r2DbC84s?{r0+Bi}i-ya(l~o%Zt?&MfJ6Y7A1$$9reECwCuJLJ58hAGylKzAw z{Yq}rw?T;SzxJZi(em|L7IDG+3r+&moE82QS<)%faH_FC6^gVV<`0Yhhh*CAFGcd- z2($(6^*UHc)}oIo>A$9vACwaj6$_PoE??h^=ZZS?{V5>`UQ)}jWbm1ok{RnImzu19 zYm9xoKf)Db=RL3u+a|jJ?E^Q;D~{G?UmH`fyS8p*M5N~`h)Q`WdW(mDw!!LHUK5S0 z!TaTK*2C5WfvoQw@#v-q*e^GXKU#CUeU+2on2pmuJGa4v&fQC(RTzP_Wl>6);3M1U z(hgAAi{dN&$e_+W<;e_uUJC3v~MOTh<3mUgUIS09WXxt)J?Kd3Y z`iTWIA8(SJ2SpGI$Gtt{)HYJ$WQ0%3MQ_o<;qoGDkHB1v7@C za~c2o{=%o*k!%OUaAr;4SssNSn2Mcx(t~L5WFcQZ|Rcqv>7AIalE) zx5;lAQ_7Q42d($+WNQ%wm=RFtmr~wtwCiAdp14Vs-w8>9C8+6c@R~Q_#2{#_-C?MW zRcFiHVG$rSH8AV?4f#GK7l#rXmHOWY+A7D=dINHlKk;vTkh840k8R1hQpxhe3F~*R zvXJfdc8t|3l5TiRFSs8JYTJ$B(l}^3V>RmO#WK8}_v&C4An*~hT*r13sq@mXC++z> z>Yf*6G($3`#~-8@tKj5&+0y+J6F#UPyq_w6+!Pba#j(AaE%>ObQz}j^VO>}&LMNz)<+AnL+kZ}%&(6n7sv+1W$euIs#2DYf1rj!GSBd)O44VZw2V zF#t!k`+=C5TSGHaHb2q;?17?XITvo@!bSiu7dEdbWn&JKi{SnjP$T_9$G00=<_K3K ziZz}RagoLT!is5gy`!#^oH+$Chr`u08W^d9- zyQq!KR`5yXkRns^tofYA`W!oTKg1s#R}fTz+=clYx>ra+%}-2&E)J2r`i(WKw__mP z3|RM`mFi-z84fA@mWPGsE^W-;ooxflxIURXpS~@~EqOI5WH(Hk1g#5Zi^No>t zk%|ujv?ToXoJT%QWJ-}@eF{5q%r4(gBEhO`C^~A{Gc`|wn2|GDxU$sp4Q}VmO)Snh zXv^!fPMg(0_S&P<_tDwSWT4XPow`M2;?k$5(;*$j^5i2X3OqghXdBnb0)-kMyci}0#TA|Qh1gd)mB-YYlhf*{Cw>JMGOj<3*JiRTpW zy;<$4p3YuAS{Iil7C6W8T}F%)-AQ$Eo{wjpf_$|3V1m+s%PmbKE-d7ejDinSTKfDd*n#@G5>n{_^C z{valoLlwTvDlgEySz&Gn)dO!Vt6eao^6mJj?4BkK!rZqOAsv{2cli|Cn zRgNFn<9@+w{<_}^X%H*Vqyd9?8oHp)=GmUU|A(P5g|48PjIUS%8@5G~>TVsVq>j_6 zQHbsvsoFc5EkPl=s%FmaPc19`&28w#_?XJqcu77FGnQ^&;&3bVg-5ySr=%eG;&|Q;vw^q#^s(Sc^8}+j(#!r?^;Em6fTiI2ILWrv4olLEJzE%-LvQ&*^N>>< z)z?o8NEG|`jXz>$fONcOmNZwrZK;JFe;CSXj;eVfcl8fhGS#$A0oQH=b!)Q5go(7MRbgRO8#?1 z_p9-DZ1ukv(fxArx7FV%cV4j}_g%+OY z^ZNHpFZILD*Q>+h=Tk7&3xOU{2zMRP1|2-GG?lNX%~&-T~T?M`!WIX=YCi|lslQ($tMTF_>f>bqH4LG!+Zs}$ayoYx zkLJ?)#;p(Dl0UR4sDAl@U}g(2B5#sTWG!wsT|F{z=6S2DsW-ZE+n|Qcs-K+A_T^mE5dGV!qZtvP%3P=E|MdiXux<_^o z9d>=Qd)qyDOoY*qmjvx&bs&C^^2r~q>2fU5zwL62M9di!16&j3s)q$ZQS2QbPGxrQ z;P7bgp68KH_LCCye zwVmff$w3d|j_QK!XbN7T`Sj2kDgZoEcBXwEvc+S!mGVx59bpAI$A=`95fAd zoSXtOBQ3~=FUSW$(UhDNi0lK`2G>}#%)2g@Ahd%c`ikNVjS@(!v0`Q12Vsh^HRj`U z2zBZ1tim6z^`N{Ra38wzK=Nb_yrNM>0XZJA34~hpV@CdTNM5)ybUf1P&4O!_I;Yp$ z?v3|UE}mTL<(`{_WYe=ZyZ+Nr3*OgvfLQX2iIeLq5hw~43)0|sE`*^3i;9ACt~UWO2}1C z)yrEd#zGo5*+VF))0FpnQLLVh z$B^bB50E5zuLC+yg zmCHvS8t*7{QBjaWciK!O(j`?IDdBK)38&cHHYjBEGbO}EHjc~pqXN}~yxBuw+yb*xU3KO%#}R-)dR4 zV!L<$&iDf=JK>gJXR=uVHH;FnnoeeGR0yvkr;&e06e~R+(UwmE?X$U^Q#mw8Dm%l}3=|{;!RPSCf%j#x z@(J-t2pZxts-e>~3sys_urvVt{V?T}9@TO)IA!!N7Pstz`o#^TBw-nMrhJQ~3JogF z5<2Ou0CL4jQ%g(OO7YZ;6~%{bS$sA8qC=W`xC)V3-stJXx0Atv?x^m<5h*s=jD1l7j>H| zAcD|{S5n`3*a_vMxqT%Cu}7!|a6&q?s&7+s3HSGwUT!{2DeZ7H7_FLw%|X;$++a_- z8-JjMG*WKPp0p5dw~i$&h&?PP(IoI`V1Z3Rl$BQ*Hqq^-(QCUA>?yWtu=F{x`+O0u`4lmZ;Q>l; zQX5P!buvG)R?SrNV2G)gqZ+tb85=-6Y9)@8u&e**7Spq#@bS=dE`!`^NHnCv-*!&8 zKsf9?CEQd(im$$hv}ZlMl@WLLYff|jN*d7O+iUG}p;VA(moIMlse?kVEgAU5WV`=X zu&w922f6(XZa9|rGhJ^wFuEApkrKvF&iPrQ>w8#pBR%^ZH`F z4uYHpjeTTY$Hu88YqfB|(EV|&g52V2)p5gjvEizM)6 zm&$gtx(;au$>VQ)*gVNU$Y0DMr!1}=%=k7k#Lg9iH3xI8ter`Np7i;|?Ph6wWxI>) zdK*%|5s#OEV<-;Z;|)}W=JijkBxtCjCZ_v&fq-@;X^iZX*s*gb&)$*9VSpOZDtQ<{ zGUVSe`Uk0n3gj8q$h{ z5C(A(p>TbbIZM-ug8A+zQ57Q+mG88Pw`G zJ8GUV6fEpVx3xn=#!k|GvXF?bNFC6R{qe?mdFui6D4BH*oQfnYOsH3R|E z1oL@!c;{C_*gAZUS591MaG^s`@4BS_!<}aym6Ye{IF;^+LeIKc^5$^1(X09OdDs2N z;$}zcftK_}05TTJ2YgtU2~4t!92qtNNm)AZ0!Ej_=$BBJXM@+L+f8{^*FGniJJ%#S znY3k_gX80y%ihf zegt>!zGQv+DJkQ{^W)O~`S4s}_nrPltdl2K9-e9i1UAxu6)UD2MpimyogNSZ64riS z6yjhI=Ep4vUi3`v+Fh4m03pdGg`BQ)S_e!=tGh(kS0V`ZUWCaSH1rq}qo?M9uGJp< zSqR<_yv_S`oJoa}G;cuz1p$X~=j$BQ`HKwMMH3S8hvDzY17(Q=OEb5}FJ5VFqq9Gy zGaZY)hg-9|`1Omc$2(d2xMC#Is4sOsF`Z+yytj>kt}+Ux%scj}K$a*l{IuE3v$CmC^Vo>KXV+$~=~cv_oyM{O0uEQK_?oIsehJuy^Nk9)4?R2P2w{VwSM zHrO(_geWzvY7z?Ba!jA5EnqrIU^D?PSMxz{=^M1hkXrw2$Bq$PuxD0(Hcu@Ce=aRP zg?->DJ|dFB&{N%xUnAxKz>PstGD9eM<9#@*?? zR?b&j>$e;lYmFX9N*0SIxhUzX<09!Y9wqn33co>(Zq<*U7ecBc+GVHb4iK63kW%qn zJkmJ%bs^b&?9Fch={og^c|?2DF!+Ta3(ocW@{}r(Q}qC{VeI;{fR%5l;q7|!Pvh$p zSXpN%`b!4h6OpLolnUxoNwgM6^_g{RN#SAOGI@)2y(5U|`D;snV!ixte8&q-P_{7! zQ#WDHlt&9j75McOKDI%kAZpmw?=SI$V+dh;RUPEj>Kab;t_9EZBq`2^9)hElB zy%)8AR~b)W(QdE*4Xf%*In=nie#XN2aqZfOqiOMWN_1#$FU7GT#j=deR%8wh+aT_T z5l6>4z7aJ;mCDQr%e|XSxX%$?j>cp4RDEDD9+@I)W4bwxK=%R=;}e)pL*&D?-w=80 z+nU7T^jk|c6UQ3LnfT}N1C*gnm0!W*PW?iulW_NY#G9QNn!ik66!f`%U?QOJxoj4P zMpDs%L*O?hR-TT7m@OC1a@QWz&5$F-kXW9zsxf6mNJhF-iEq*8<<7bkN0CT1UKQQ^ zLXG1uhW=yX6*kg})B$bvhi_XQ96ZXrZ54*{rCbu)BCxZy;rmhq9pv~Bk5(3mMCDlN5 zn_$)Q780)ViWkPaeJ;O2vsf_aiqJc90-jGrPS(EZg<_Db_@gQ@)x;l|zX5O5xoqSV zyfl511Dj+Q=goNRP7mk%Ofd6OC&~rJ*4MJ3E)hr?`0I!wIPl$l23m;Wf6(6=9oDIq z6g`&_eee`X1+YVIz(L3}!XhiNGZ>fEvxR98dgCV%muk1r-z#H)DpB+s5gvB|Ix3hdzi%=dUs{dw&X6aO7K*IB*iP80rg{Y9cmipTMO4z1s zlVcVW3>&VR;A@Yuc$E9Y*7A@fwH1>IsR|oYdD~FT>S`;7gf-5NCSzIer~P+BA7Yp@ zr;S(Y3hQ0yf9lb-Y}zOZ3#oUDq+sps@#k>GC(d8Xm%qH&I_F3C=R~I~lR54fSa?Dh zo@!$2<1Crq@c85|9J}}w>Ikg#IUCIGx6IMg-PUM)ly>ae3@6i%ReKptr>?}ax1T9> zaSjUS15FfXi;*St=@A#EHfATsLC9wu+!1N;<14Na-{%l9vG-&sz;kiMx;I5hxi`R=QAE9`#XuMv1kV=OD=}`q!uZew_!r51%=t{|>Ms2dq z{FE^V5yF~Cpe(NzTBcv=+7$z2p(|U^Jx?>5DQtLu?cGraPq6Vh5y(E)WQ58NyTWQ% zA>Zzr=TbQ~26CZh!O&J`GCd-WuOZ>1{;q?eyxo+;;@zc0y?puBXG(_?vj@;!=CSLQ z&=l(S^5HxoF{zQ|lZV(l&Ain#_&)d(S5rxp#|q@uob{AND)( ziM`4k!_hQguB_?oZau4OnL;I(mU-Nd9d;x3KiV~5WSTYz7HV|RO(`U;gwsE7AG|82 zFS0e(Uvmzbl-++^9G>kqYiE~GJ?N;ldCZ}T*IY@RX2I@jl-Nu14W;-d_Q0fRS0U=G z8K|HBfU^N+)!w&;=}c+fvSv>ZGozwaUvhYE=dYIMa`zImyI28brR{mzMm=!Wv4yf9a@!5~u_X?RCDV?N!dDa4uAlFgsXNT| zCdcI0O=%lV8t`*@c6eRf-%PY-?vu$py`s~}kdvm_XY_creY!%TGZ2|QeA$01m&qtN zDwKIcb0XkK9Z}!=DN!KXbh?CIp^)J5zz8?0wtNE!3En}5D0hu&vHAKp77qXPc>Z2E zdcmXhYMXTGs7jwZ%+V>WAwVz)YE_tumt=WO!<%Yh9INq|5e3J9(P1kZ4d+bUVYAg! zE4?Eu`f38ZRrr>TlOoU5L=;O)Lb)6Zz!(s0v)<_n?F*>9ZWo4OwRTV0!?WcS{$-Xq0V@RKnoNd(KKd-+xC zO%7bbjCBDuZYE6;Uh8Pih!utJVzdD0rR#mU=ZL9#H<{Jsr9jp(>g3nk!#i2R_Q7xj z^3bxJG~&g=p=6&6TPNY9ZU(yH=aYRHNuy~qih!_w~bQRJ74Xrx#hJs&SD_=mM{sTIo*Y}bwfX4qG=MUdG6=j;j8xGj|Zm3%usi2I{tRFK2-*E1(M8xWbf z$(1!DR?jBv^Svug8;j;9GC0s_4KTX;Od-!0a87zY7ZS5hE^dmZm>xFH(0AJ7oMY}7 zo}VAr{muNH(3<#*JdPdi8~umX9Q~-gz@~dX8?R+8`*`B(k~Bu5*`a;+9~ga41P9d} z2wzldtHudG97;c0ULB(!QgB0|h`h#8si*Y3T=ZpNb6-ovLC^q_{(9D*-bnc{hebBs z1u9C<22+=t3S5h6v?3&_hb5cIV*|1)(cv~X8+?l%n5kDRlN-`h1DvBn{bDpQV&Kdr z=&k??)aMVjZ6w_+am}BGLo&Ka=`MZBnhwr0#SCOfEd1KacLs1Z@t3Y-I^Eyo0~8Uj z#I_X%d3^d%eASFdg%tDANcFlMOuU_ZoM$w8>Fn^93qua=o_k#uFw(d8*h?@x!J`ybpvB zP{cj!;2LBtc;hH2@MXr*-x+-%A;jG)(AZa?79rQ#7M z%UZ9f>n){68$U?l(wo~i3y=?Oo7w#yUk%|2HN@0;fLtl%+F2gGoc%zR>pwz-bS$Y+ia zh#||o+-;`}*kbLwSt-GW^Gvb*c2VZ3E59M={c*xfQqY@V7vVJDbm_u&!&+ZoLQm+9 zi25mh;Xvwr{A0!27JTTMib{`SkncB8fZv1wM)jkL1=gkTf3sZ9b-O8zHgw1iEKF~W z*>2|d068%m_qFPMUw&f(}!BsY=GbytN=?x$5YS0jCWal%Ix%L^+!T zsmR^(g+`$)J^n0Ya3IBQzbz6HCYBO&B0r!lPP66hG(nfH;XVq6F-T9(p}2B08vSTTAD8^TDjdRX$5z&M;v z2{SeF)5;z!``v?ga84*zq?~VUiTYq4-2610cuT?wHL}~67Nqndp;RU(vE0VkM3)jx z4@yrx>I1i;RCB$=CcQ#sB}c4~Dm{Xd#WCixc-e9^3+1_&uOC~@YLG|{ITpa%N28=o z*^nO>J0w=>cssm20)5oO+{-3+WHZ}!XocL^ghyA{y~C_dTs#3%!{+Tyz^B}V@?{;B zAI`BXG#`=LDb!8Q?s%%WNP??Bte9L*eCp_(r9aD!%N%hsod z)o}5XN^$TsHm@jR<&-o+4hG*lKkU6oV}+{6Y7F?r*5dAG4}nTULI|B<;r84+b4y5~ z_wU7NOSfuTTGO?f!skQ6Z!4BaYWT46_6a<4Fq)l=_%K+irfI@_Q;b9hli^%vV1GTkPi!^dg+hcV6ifqBXj#b8J2p zwnxwOyWlxNu$IiA?3x*zJ}mY_Z@kS9%}!P*ONU*4^j7J+k@@2}DHb#Jf)<-X&d?k% zDuQhlv#SI9NS59E4uNs=CSMVO_!fe=vbl9vwL_$FI++NDjI%@BPbX3@7IX%uX@k(| z*X;vkU!bXNTQ$eEPpp56_ud->Mk}8_mHU3$ErlHv{HRcP7B4irK6Ba}nZiQSH_{t< zh!=MRnkRp1J7ck);%DKb{@^Rp$gy60@$tlYJ6eLwv{ZTge%^V+oW z_Z+v{;XPI-jtZuA$5w}YU6fBWC+x8f5;{MnM^rKmh-BMoX~J*m&KkoxoCFj%?X%BU zBYb2v1W5uGzRUV|5J_OBBU#Vr2W)VRd+h24Ot0+YmpYdszuZs-u?%ny%a>J#Ek9Vj zOkk#WGBB@6%en_@UM##j+du-r#tG`EjCo!SSpZo-ON771O{O#D-~)()&q#_=&F9r^ ztfYnuG#li5tJt|&Nvv8t&Lsaza~}gZ;t=xu*dEf5z^s}Dfw1vAz`9#2T=PX6%F`EBmQ(7^7E-TCGm06_bv3u>@`=>BVUoNWyZVd(($%&>I-&jny+Vq#zd z7y|y3z40vR-Uj;X0$Bb_#`@;LKV&S7Z|?k4_A9{pFETnhdZxG8{D%z4@HWhU$mo6z z_P@x0jLg4A{tp?`uW9%%GCF#ef75&0>u)3Yrye8AKW)%4(=)xL+W%{R%s_^J+NEQr z1O9Vf=-A%Aqkq232K;xstZe^g7YJmb|EFCbkeTkE{Q=(=}` **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://:3005` + - Portal RMA Customer (tanpa login): `http://: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. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0df9910 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,28 @@ +version: "3.8" + +services: + erp: + image: /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: "" + 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 diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100755 index 0000000..0bbeb16 --- /dev/null +++ b/entrypoint.sh @@ -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}" diff --git a/next-env.d.ts b/next-env.d.ts new file mode 100644 index 0000000..830fb59 --- /dev/null +++ b/next-env.d.ts @@ -0,0 +1,6 @@ +/// +/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. diff --git a/next.config.ts b/next.config.ts new file mode 100644 index 0000000..b72dd64 --- /dev/null +++ b/next.config.ts @@ -0,0 +1,8 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + reactStrictMode: true, + poweredByHeader: false, +}; + +export default nextConfig; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c62b33b --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2924 @@ +{ + "name": "enterprisecore-erp", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "enterprisecore-erp", + "version": "1.0.0", + "dependencies": { + "@prisma/client": "^6.2.1", + "@types/pdfkit": "^0.17.7", + "bcryptjs": "^2.4.3", + "clsx": "^2.1.1", + "jose": "^5.9.6", + "lucide-react": "^0.473.0", + "next": "^15.1.5", + "nodemailer": "^10.6.1", + "pdfkit": "^0.20.2", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "tailwind-merge": "^2.6.0", + "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" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.3.0.tgz", + "integrity": "sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@next/env": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/env/-/env-15.5.28.tgz", + "integrity": "sha512-xxW5EBI8fMPuVTPBW7LL980IRbuDXlbkUAwp9DDhtb4Lnich3nJ13uYpvrX4VE74hWPf6AvHHAMmGCidcHjbfg==", + "license": "MIT" + }, + "node_modules/@next/swc-darwin-arm64": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.5.28.tgz", + "integrity": "sha512-dPoQYXcfSIqx5o+TOXVXO7kONK5qbtNRDeiTfII0bT3puGIT6VF5e0QwmxNZfEZ5Zety5f3m9P/p4xqwfiLlPg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-x64": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.28.tgz", + "integrity": "sha512-RgCJ7buBivTH+6sddqaVm+/v8kwMHlFkobvdt3DfETutws5HrxnToMIWSN9X3MZ3aAi7BbKrGZZWUDQLEycXqw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.28.tgz", + "integrity": "sha512-OHXQe13olE59aKe++zHavGcJPh5SLHXi6Anret3BBeq1+qhSuOJDNAli/EDDfxs6UTqA4Qddo4uyYry2slyjiQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.28.tgz", + "integrity": "sha512-nTB7bB6vfn4ezCJNYP43ukt2o8L3+WxKF/sTcTxepdXsJh3SM9RhlU7wrZYbH7L4HO5M87dqDTwm8587vAkCiw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.28.tgz", + "integrity": "sha512-WXCfVI32rW3xCusoUX1RpZKtyChWU2Zwe27JUDmM3KrXwcDNc9vV4zEq0GKFAURnuQ/Ouo/XqPvB0yh445XZCg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-musl": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.28.tgz", + "integrity": "sha512-Miq+NDb/HWsXuxseYxMM6fuEOQXgTziarkKIRpVKCn8W69cEfhQaQr+90pO+u4q2CbJR2wzXmUuCFyZaJs/Nng==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.28.tgz", + "integrity": "sha512-5LR79lemgDlgxvG7MQJ+zHCkVcrUoQuO7CiIvq3I58vNW4goSOE2b+19Z6FujRWMouvni4gvudYFuFuNxolGWA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.28.tgz", + "integrity": "sha512-GNipvXUYROSTf4PXEyH95FrWImIB5zdaK6uEOg0RP1/X2drnvoMwiBkJ0VWdzX7w3iiBm3y5g2TxkKDGVTOQcg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@noble/ciphers": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.3.0.tgz", + "integrity": "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@prisma/client": { + "version": "6.19.3", + "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.19.3.tgz", + "integrity": "sha512-mKq3jQFhjvko5LTJFHGilsuQs+W+T3Gm451NzuTDGQxwCzwXHYnIu2zGkRoW+Exq3Rob7yp2MfzSrdIiZVhrBg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "prisma": "*", + "typescript": ">=5.1.0" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/@prisma/config": { + "version": "6.19.3", + "resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.19.3.tgz", + "integrity": "sha512-CBPT44BjlQxEt8kiMEauji2WHTDoVBOKl7UlewXmUgBPnr/oPRZC3psci5chJnYmH0ivEIog2OU9PGWoki3DLQ==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "c12": "3.1.0", + "deepmerge-ts": "7.1.5", + "effect": "3.21.0", + "empathic": "2.0.0" + } + }, + "node_modules/@prisma/debug": { + "version": "6.19.3", + "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.19.3.tgz", + "integrity": "sha512-ljkJ+SgpXNktLG0Q/n4JGYCkKf0f8oYLyjImS2I8e2q2WCfdRRtWER062ZV/ixaNP2M2VKlWXVJiGzZaUgbKZw==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/engines": { + "version": "6.19.3", + "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.19.3.tgz", + "integrity": "sha512-RSYxtlYFl5pJ8ZePgMv0lZ9IzVCOdTPOegrs2qcbAEFrBI1G33h6wyC9kjQvo0DnYEhEVY0X4LsuFHXLKQk88g==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.3", + "@prisma/engines-version": "7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7", + "@prisma/fetch-engine": "6.19.3", + "@prisma/get-platform": "6.19.3" + } + }, + "node_modules/@prisma/engines-version": { + "version": "7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7", + "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7.tgz", + "integrity": "sha512-03bgb1VD5gvuumNf+7fVGBzfpJPjmqV423l/WxsWk2cNQ42JD0/SsFBPhN6z8iAvdHs07/7ei77SKu7aZfq8bA==", + "devOptional": true, + "license": "Apache-2.0" + }, + "node_modules/@prisma/fetch-engine": { + "version": "6.19.3", + "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.19.3.tgz", + "integrity": "sha512-tKtl/qco9Nt7LU5iKhpultD8O4vMCZcU2CHjNTnRrL1QvSUr5W/GcyFPjNL87GtRrwBc7ubXXD9xy4EvLvt8JA==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.3", + "@prisma/engines-version": "7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7", + "@prisma/get-platform": "6.19.3" + } + }, + "node_modules/@prisma/get-platform": { + "version": "6.19.3", + "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.19.3.tgz", + "integrity": "sha512-xFj1VcJ1N3MKooOQAGO0W5tsd0W2QzIvW7DD7c/8H14Zmp4jseeWAITm+w2LLoLrlhoHdPPh0NMZ8mfL6puoHA==", + "devOptional": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/debug": "6.19.3" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/@swc/helpers": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz", + "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@types/bcryptjs": { + "version": "2.4.6", + "resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz", + "integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/nodemailer": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz", + "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/pdfkit": { + "version": "0.17.7", + "resolved": "https://registry.npmjs.org/@types/pdfkit/-/pdfkit-0.17.7.tgz", + "integrity": "sha512-VMOZDWw7HtNtLbjIuHIhVArm9PlV0gxpz32jAl1IuXWlIgbr1lKFoTsrtvEzY8a9BIpQJEE5DwNPKD50otTs6g==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, + "node_modules/adler-32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", + "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "dev": true, + "license": "MIT" + }, + "node_modules/autoprefixer": { + "version": "10.6.2", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.6.2.tgz", + "integrity": "sha512-VOw9/yGTGwPPgzFcODtcv6zhEPIeIWkRSe10L2ri2f5vZ7ID7lCt6jZzRF5/ubgOZ+szYydmEF5AYsA5jxX1tA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.9", + "caniuse-lite": "^1.0.30001810", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.34", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.34.tgz", + "integrity": "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/bcryptjs": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz", + "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==", + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/brotli": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz", + "integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.1.2" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/c12": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.1.0.tgz", + "integrity": "sha512-uWoS8OU1MEIsOv8p/5a82c3H31LsWVR5qiyXVfBNOzfffjUWtPnhAb4BYI2uG2HfGmZmFjCtui5XNWaps+iFuw==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "chokidar": "^4.0.3", + "confbox": "^0.2.2", + "defu": "^6.1.4", + "dotenv": "^16.6.1", + "exsolve": "^1.0.7", + "giget": "^2.0.0", + "jiti": "^2.4.2", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^1.0.0", + "pkg-types": "^2.2.0", + "rc9": "^2.1.2" + }, + "peerDependencies": { + "magicast": "^0.3.5" + }, + "peerDependenciesMeta": { + "magicast": { + "optional": true + } + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001820", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001820.tgz", + "integrity": "sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/cfb": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", + "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/citty": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.1.6.tgz", + "integrity": "sha512-tskPPKEs8D2KPafUypv2gxwJP8h/OaJmC82QQGGDQcHvXX43xF2VDACcJVmZ0EuSxkpO9Kc4MlrA3q0+FG58AQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "consola": "^3.2.3" + } + }, + "node_modules/client-only": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", + "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", + "license": "MIT" + }, + "node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/codepage": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", + "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/confbox": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", + "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/deepmerge-ts": { + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/deepmerge-ts/-/deepmerge-ts-7.1.5.tgz", + "integrity": "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw==", + "devOptional": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dfa": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz", + "integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==", + "license": "MIT" + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "devOptional": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/effect": { + "version": "3.21.0", + "resolved": "https://registry.npmjs.org/effect/-/effect-3.21.0.tgz", + "integrity": "sha512-PPN80qRokCd1f015IANNhrwOnLO7GrrMQfk4/lnZRE/8j7UPWrNNjPV0uBrZutI/nHzernbW+J0hdqQysHiSnQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "fast-check": "^3.23.1" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.472", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.472.tgz", + "integrity": "sha512-s4+nfT29b0FKpVKoaIxl2pWsoNcn7A/nMPSrxayw4T3BsmPeV2lF9Y06BsAQeMGhCTQ4nYJ5XST7jkqe4ZEqFw==", + "dev": true, + "license": "ISC" + }, + "node_modules/empathic": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.0.0.tgz", + "integrity": "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/exsolve": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz", + "integrity": "sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/fast-check": { + "version": "3.23.2", + "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-3.23.2.tgz", + "integrity": "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT", + "dependencies": { + "pure-rand": "^6.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "license": "MIT" + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fontkit": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz", + "integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==", + "license": "MIT", + "dependencies": { + "@swc/helpers": "^0.5.12", + "brotli": "^1.3.2", + "clone": "^2.1.2", + "dfa": "^1.2.0", + "fast-deep-equal": "^3.1.3", + "restructure": "^3.0.0", + "tiny-inflate": "^1.0.3", + "unicode-properties": "^1.4.0", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/frac": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/giget": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/giget/-/giget-2.0.0.tgz", + "integrity": "sha512-L5bGsVkxJbJgdnwyuheIunkGatUF/zssUoxxjACCseZYAVbaqdh9Tsmmlkl8vYan09H7sbvKt4pS8GqKLBrEzA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "citty": "^0.1.6", + "consola": "^3.4.0", + "defu": "^6.1.4", + "node-fetch-native": "^1.6.6", + "nypm": "^0.6.0", + "pathe": "^2.0.3" + }, + "bin": { + "giget": "dist/cli.mjs" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.17.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz", + "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "devOptional": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/jose": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", + "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/lilconfig": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.4.tgz", + "integrity": "sha512-zJZyBmQhArDRefuWTypZxwDpFDIYmrj8ypSBvwGD5P13Y95s6DjzKgu4DVdGbeQa5PDEsAOCAPNk4X+QOR006w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/linebreak": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", + "integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==", + "license": "MIT", + "dependencies": { + "base64-js": "0.0.8", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/linebreak/node_modules/base64-js": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz", + "integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lucide-react": { + "version": "0.473.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.473.0.tgz", + "integrity": "sha512-KW6u5AKeIjkvrxXZ6WuCu9zHE/gEYSXCay+Gre2ZoInD0Je/e3RBtP4OHpJVJ40nDklSvjVKjgH7VU8/e2dzRw==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/next": { + "version": "15.5.28", + "resolved": "https://registry.npmjs.org/next/-/next-15.5.28.tgz", + "integrity": "sha512-JjhLBBY1PNnuwPtcZ7t8yxVeJVYvD2Jyp633J+gRCNbzSt7N0E+xqCf6uQiff3+3qmUkwcF/ksfSsK1xsZ76Tw==", + "license": "MIT", + "dependencies": { + "@next/env": "15.5.28", + "@swc/helpers": "0.5.15", + "caniuse-lite": "^1.0.30001579", + "postcss": "8.4.31", + "styled-jsx": "5.1.6" + }, + "bin": { + "next": "dist/bin/next" + }, + "engines": { + "node": "^18.18.0 || ^19.8.0 || >= 20.0.0" + }, + "optionalDependencies": { + "@next/swc-darwin-arm64": "15.5.28", + "@next/swc-darwin-x64": "15.5.28", + "@next/swc-linux-arm64-gnu": "15.5.28", + "@next/swc-linux-arm64-musl": "15.5.28", + "@next/swc-linux-x64-gnu": "15.5.28", + "@next/swc-linux-x64-musl": "15.5.28", + "@next/swc-win32-arm64-msvc": "15.5.28", + "@next/swc-win32-x64-msvc": "15.5.28", + "sharp": "^0.34.3 || ^0.35.5" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.1.0", + "@playwright/test": "^1.51.1", + "babel-plugin-react-compiler": "*", + "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "sass": "^1.3.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@playwright/test": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "sass": { + "optional": true + } + } + }, + "node_modules/next/node_modules/postcss": { + "version": "8.4.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", + "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.6", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/node-fetch-native": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", + "integrity": "sha512-g9yhqoedzIUm0nTnTqAQvueMPVOuIY16bqgAJJC8XOOubYFNwz6IER9qs0Gq2Xd0+CecCKFjtdDTMA4u4xG06Q==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.63", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.63.tgz", + "integrity": "sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/nodemailer": { + "version": "10.6.1", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.6.1.tgz", + "integrity": "sha512-d7kfFfS/tR4Aca+SBvRaQ+MXKNv7d2JiRe5TxaRcFT/kYMh4GGPnW9aKksTIEvyEbA7d/7HYWE4YPDEHxzJj/g==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/nypm": { + "version": "0.6.12", + "resolved": "https://registry.npmjs.org/nypm/-/nypm-0.6.12.tgz", + "integrity": "sha512-4AhWntz+ds/P5kz1rN25yGegTPYsO5ffOy+8S0TeuXKZrgjlmgcEBLA1xubzcP/dWX4zYfNybv4TQERlL9Z0LQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "citty": "^0.2.2", + "pathe": "^2.0.3", + "tinyexec": "^1.3.1" + }, + "bin": { + "nypm": "dist/cli.mjs" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/nypm/node_modules/citty": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", + "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/ohash": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", + "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", + "license": "MIT" + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/pdfkit": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.20.2.tgz", + "integrity": "sha512-Q/w03ICAQyXfHNfTsg1udp0ADerdBN0s7a6XSPL7J7Ro6ABnafoBOCDBstIO9U02mvzHEV8HrvFIw5iV5ejIRA==", + "license": "MIT", + "dependencies": { + "@noble/ciphers": "^1.3.0", + "@noble/hashes": "^1.8.0", + "fflate": "^0.8.3", + "fontkit": "^2.0.4", + "linebreak": "^1.1.0", + "png-js": "^2.0.0" + } + }, + "node_modules/perfect-debounce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz", + "integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-types": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz", + "integrity": "sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.3.1", + "exsolve": "^1.1.3", + "pathe": "^2.0.3" + } + }, + "node_modules/pkg-types/node_modules/confbox": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz", + "integrity": "sha512-ZUAKhKlkCOrIGKc8cj7zek9s9z1mveHif/25nUshI2BzCRzF7KH7KHa+Lnh2ubq+e1tIlaFuP763mzW4qVoehg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/png-js": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/png-js/-/png-js-2.0.0.tgz", + "integrity": "sha512-GdzJuUMc6ZSpxFJWVxtOH1bzYHym+TOnveqUjb+VJIbZWbZzyiRGFiKhbiielfpYbgMlhHVhsJ0FTazfuRFkMA==", + "dependencies": { + "fflate": "^0.8.2" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz", + "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.5", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.5.tgz", + "integrity": "sha512-TEHFzb5KRDKaOgJ4TYE+0jyJtFbjLvkdVOu0fZ2b6MTWzoqZd4Le+61aEppWkvTlYePgOX4ATL1wsAIPMLTw6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/prisma": { + "version": "6.19.3", + "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.19.3.tgz", + "integrity": "sha512-++ZJ0ijLrDJF6hNB4t4uxg2br3fC4H9Yc9tcbjr2fcNFP3rh/SBNrAgjhsqBU4Ght8JPrVofG/ZkXfnSfnYsFg==", + "devOptional": true, + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@prisma/config": "6.19.3", + "@prisma/engines": "6.19.3" + }, + "bin": { + "prisma": "build/index.js" + }, + "engines": { + "node": ">=18.18" + }, + "peerDependencies": { + "typescript": ">=5.1.0" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/pure-rand": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", + "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", + "devOptional": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/dubzzz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fast-check" + } + ], + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/rc9": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-2.1.2.tgz", + "integrity": "sha512-btXCnMmRIBINM2LDZoEmOogIZU7Qe7zn4BpomSKZ/ykbLObuBdvG+mFq11DL6fjH1DRwHhrlgtYWG96bJiC7Cg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "defu": "^6.1.4", + "destr": "^2.0.3" + } + }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, + "node_modules/read-cache": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.2.tgz", + "integrity": "sha512-/peqiBB/n07gQGLsWaHho3WfvUyRscw0gYTsEFMhrIe/nWLkYaf5SbKYjGYqtRV3aPwykJgF2VEMo1ac4bnsGA==", + "dev": true, + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/resolve": { + "version": "1.22.13", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz", + "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.17.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/restructure": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz", + "integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==", + "license": "MIT" + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ssf": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", + "dependencies": { + "frac": "~1.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/styled-jsx": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz", + "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==", + "license": "MIT", + "dependencies": { + "client-only": "0.0.1" + }, + "engines": { + "node": ">= 12.0.0" + }, + "peerDependencies": { + "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwind-merge": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz", + "integrity": "sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.19", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz", + "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.6.0", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.2", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.7", + "lilconfig": "^3.1.3", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.47", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0", + "postcss-nested": "^6.2.0", + "postcss-selector-parser": "^6.1.2", + "resolve": "^1.22.8", + "sucrase": "^3.35.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tailwindcss/node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/tailwindcss/node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/tailwindcss/node_modules/jiti": { + "version": "1.21.7", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", + "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/tailwindcss/node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "devOptional": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/unicode-properties": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz", + "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.0", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/unicode-trie": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz", + "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==", + "license": "MIT", + "dependencies": { + "pako": "^0.2.5", + "tiny-inflate": "^1.0.0" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/wmf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/xlsx": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", + "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "cfb": "~1.2.1", + "codepage": "~1.15.0", + "crc-32": "~1.2.1", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..56dc1d4 --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/postcss.config.mjs b/postcss.config.mjs new file mode 100644 index 0000000..2aa7205 --- /dev/null +++ b/postcss.config.mjs @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/prisma/schema.postgres.prisma b/prisma/schema.postgres.prisma new file mode 100644 index 0000000..8c093fe --- /dev/null +++ b/prisma/schema.postgres.prisma @@ -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) +} diff --git a/prisma/schema.prisma b/prisma/schema.prisma new file mode 100644 index 0000000..65736bb --- /dev/null +++ b/prisma/schema.prisma @@ -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) +} diff --git a/prisma/schema.sqlite.prisma b/prisma/schema.sqlite.prisma new file mode 100644 index 0000000..26eb423 --- /dev/null +++ b/prisma/schema.sqlite.prisma @@ -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()) +} diff --git a/prisma/seed.js b/prisma/seed.js new file mode 100644 index 0000000..47fa4e1 --- /dev/null +++ b/prisma/seed.js @@ -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(); + }); diff --git a/public/Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf b/public/Panduan_Alur_Penggunaan_EnterpriseCore_ERP.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2ad03bde68660a5a6160acbd610b2ecd493d26af GIT binary patch literal 15611 zcmch;WmH|;vNcL@haf?MEF6L^+}%A$aCdiiC%C)2ySux)yF+j%As^X$=be4`Ij`NX zz5CjoKbXuKHAmHuxmvFp)k$Opg{grw46r0W-!51d03EgW*1*yp0DNnfgQb-+&^OWHw{ixk(Y*}?HnEMT3} z)>T&{J~qGiSX8=%8Y2mHAb2N$)S3!DB;eh5^I@+$rX?EW9&{LV_yS5%zcFQ<3p@NQ zJ-`CYuOpi3!(?%34jfIB(=4p#gGXc`F(C|4=?{-jT(9hRX&hOu3cv@~M zgSNo-;lE~ShxL&As9$FLE3=9Ypv8h5*BaAe;J0c`cH#`o`%fQxdE8tGti>J;7T$BR zk4e+J7Mx{p<9j|5vGP7J;=R7&eTCv9eFp=oP7Ku9`Rok?it;WX7w)IEj2HL!?c>YE z@d{f*U?Y;?IavT*1=vf210Mph1Hs;3d!Vs=lu3ds{=fQ@|uihLnK7^1e+6VA@?uvz#&sSBsNj2F)j94HJvG3jWh8 z-YFA|(Id#JM(qNk1ZIs!pWCY=@}`F=x6alHfAQ;pk!Q&%!wGoK5)T7)Xobn4HR}|6 zBdGZ@bq^yB3R9tP$4^X!hb#Q(4#hC@7|qk3Hb3tfV!l9A#5h!+A zf)qyx+rqHeB*NE)PSh|U77T@nKgAvzxwvFLojh92)`;y?p?R zKDNwlyx?KY?EOm5DM5|77YTBz}s zSEt8IMZJkcq~Il;cUn=}?Ad27o9WCFkyes6E>L3&!(!jqr8p8FWY@n`=BZXUsyr(PU{S@?YUEgE@E$9>Rh%nfUXd`081dW zrZOPgAk-dySzgy2%*$p|Zj+`M@J!BTrJN7cUm58 zsaF_a2a>hkCb+>1-eSUe71oI+bE562)g8&LuoMW?QR8^UYbpK zX%6k+dppJKp;~Z_DKRzcw zT7O@pGN46C6RXj9Bwo&K9KZ{P%TTcZeKPaXSAU;tQTv`Kzzp|rKAu9uPDTC`5~MlB zR}mPsNw->lCXo!<{NUyf_k9j5fW)O79XX(HEh5bEy^ z9^ef*!6w4)(x}Ef0s>J?!mOs{aQh5bEnrI#eZO3pk#uqui&qP_=eMs)@83dbMn%#n zwLuNRe0V7L&H9$wj40x`xI@$Ng$M)0(;rCSI#RP6NA?=yKs;5}-$Ze&@)gB>>zW_- zr=t3lhlEG1JJ|b4X9jOGgO6~o8yj#ApaUC1Dbq^q#s}0jrWofKQ;{?Wboqx)O4FHU z@%0nlpRFnx)7c3o8SAtWIE-_Xkc7@PrrLAN(7_b+q?{0rUv zM|k!}<8P?+zlP8LaPqg+zW^EoJw5Qh2Wa2Y#v}Hc5WFw$&^&$S#nHsXy0Va3pWfL* zM~$ud;k4Y7&t}(~%<>+JO zY^Tim5ekn7#ShCaR)0*%V4cV7yW3rS?cl&b+M8pmOk_()t00*pwI!hKZt~;NU-yrCCAN^^);R4kcZNMQ|3RcE5T&UKh?@bf&%5q&o2M zC9i6SYs6=XM{^JU=<7u##VfO^8e65F?Wlso^hV9}gOccCh?LZ}*-Hi^%g`Q^A1SeB zbl25o+eyI9T)qNN5PjX3owGK?plaP>gNXC$CcFy3CBx%T)W#u9742O_)uF3myig_i z@%>3($~fLftSn1jWv)UqlGFY5X_Cxr=W=uQFnvX*s(^v{&~It=pp)!qsWuzAHfBAl zCSsW33X{BR{L-(87Fnc9iXqE5jfewpxj2KgD(p$iULR<}0nvfQd+r@38KyG$#8UNc z-_s_l6$RP+GOhB{y&6(Jh&I8Fkc_u&Ypqm}tYsw}0Q9(=3WJQ7S1AJ=38o;`XP(^N zH8HhYB|SMdnOZmxbcG6DOAsMVKV@cs%3U9eT1l`f-Gozme+vO>t%x&^Gq<1I1#yU> zwAv2EPQf6=wQY#%Kr7BuyG0!zBBLg7;iflfzN|L&7J8@!S!xI@rZVRy6ASFBX^jR5 zi-q)siFUBgiGP)Io^5EHx-?SU{(yLp#xSR|HD{YMwRo27sr$(|DTmt}fV4Ve<3vbI zbc&_@jS4AGz)V*cw(Z^-myTwVs!5xbms{rio!Jx-2;zA1J3u65V&%8bd8Os8s48IG zBP3>Ij%57@Ik{zop^{F`)gkJW3WfD2I-EcB8b9T2yld`GK`WQp5)ESl>{nRk+q8&| z;j??n4tBayANJON@7EyD_tB$=4+}+=g1olfP3JUKPUz+BJ`nnVOQbayG~#=TeB}#6 zc4Xr{vxON}OC`LkV&!$b^wOOaK1Cx;F<|Tl7hj>6NUx|BClWMr8W{3LLFOB7%?YK4 zjL|LlybV27))xf~$r2DbC84s?{r0+Bi}i-ya(l~o%Zt?&MfJ6Y7A1$$9reECwCuJLJ58hAGylKzAw z{Yq}rw?T;SzxJZi(em|L7IDG+3r+&moE82QS<)%faH_FC6^gVV<`0Yhhh*CAFGcd- z2($(6^*UHc)}oIo>A$9vACwaj6$_PoE??h^=ZZS?{V5>`UQ)}jWbm1ok{RnImzu19 zYm9xoKf)Db=RL3u+a|jJ?E^Q;D~{G?UmH`fyS8p*M5N~`h)Q`WdW(mDw!!LHUK5S0 z!TaTK*2C5WfvoQw@#v-q*e^GXKU#CUeU+2on2pmuJGa4v&fQC(RTzP_Wl>6);3M1U z(hgAAi{dN&$e_+W<;e_uUJC3v~MOTh<3mUgUIS09WXxt)J?Kd3Y z`iTWIA8(SJ2SpGI$Gtt{)HYJ$WQ0%3MQ_o<;qoGDkHB1v7@C za~c2o{=%o*k!%OUaAr;4SssNSn2Mcx(t~L5WFcQZ|Rcqv>7AIalE) zx5;lAQ_7Q42d($+WNQ%wm=RFtmr~wtwCiAdp14Vs-w8>9C8+6c@R~Q_#2{#_-C?MW zRcFiHVG$rSH8AV?4f#GK7l#rXmHOWY+A7D=dINHlKk;vTkh840k8R1hQpxhe3F~*R zvXJfdc8t|3l5TiRFSs8JYTJ$B(l}^3V>RmO#WK8}_v&C4An*~hT*r13sq@mXC++z> z>Yf*6G($3`#~-8@tKj5&+0y+J6F#UPyq_w6+!Pba#j(AaE%>ObQz}j^VO>}&LMNz)<+AnL+kZ}%&(6n7sv+1W$euIs#2DYf1rj!GSBd)O44VZw2V zF#t!k`+=C5TSGHaHb2q;?17?XITvo@!bSiu7dEdbWn&JKi{SnjP$T_9$G00=<_K3K ziZz}RagoLT!is5gy`!#^oH+$Chr`u08W^d9- zyQq!KR`5yXkRns^tofYA`W!oTKg1s#R}fTz+=clYx>ra+%}-2&E)J2r`i(WKw__mP z3|RM`mFi-z84fA@mWPGsE^W-;ooxflxIURXpS~@~EqOI5WH(Hk1g#5Zi^No>t zk%|ujv?ToXoJT%QWJ-}@eF{5q%r4(gBEhO`C^~A{Gc`|wn2|GDxU$sp4Q}VmO)Snh zXv^!fPMg(0_S&P<_tDwSWT4XPow`M2;?k$5(;*$j^5i2X3OqghXdBnb0)-kMyci}0#TA|Qh1gd)mB-YYlhf*{Cw>JMGOj<3*JiRTpW zy;<$4p3YuAS{Iil7C6W8T}F%)-AQ$Eo{wjpf_$|3V1m+s%PmbKE-d7ejDinSTKfDd*n#@G5>n{_^C z{valoLlwTvDlgEySz&Gn)dO!Vt6eao^6mJj?4BkK!rZqOAsv{2cli|Cn zRgNFn<9@+w{<_}^X%H*Vqyd9?8oHp)=GmUU|A(P5g|48PjIUS%8@5G~>TVsVq>j_6 zQHbsvsoFc5EkPl=s%FmaPc19`&28w#_?XJqcu77FGnQ^&;&3bVg-5ySr=%eG;&|Q;vw^q#^s(Sc^8}+j(#!r?^;Em6fTiI2ILWrv4olLEJzE%-LvQ&*^N>>< z)z?o8NEG|`jXz>$fONcOmNZwrZK;JFe;CSXj;eVfcl8fhGS#$A0oQH=b!)Q5go(7MRbgRO8#?1 z_p9-DZ1ukv(fxArx7FV%cV4j}_g%+OY z^ZNHpFZILD*Q>+h=Tk7&3xOU{2zMRP1|2-GG?lNX%~&-T~T?M`!WIX=YCi|lslQ($tMTF_>f>bqH4LG!+Zs}$ayoYx zkLJ?)#;p(Dl0UR4sDAl@U}g(2B5#sTWG!wsT|F{z=6S2DsW-ZE+n|Qcs-K+A_T^mE5dGV!qZtvP%3P=E|MdiXux<_^o z9d>=Qd)qyDOoY*qmjvx&bs&C^^2r~q>2fU5zwL62M9di!16&j3s)q$ZQS2QbPGxrQ z;P7bgp68KH_LCCye zwVmff$w3d|j_QK!XbN7T`Sj2kDgZoEcBXwEvc+S!mGVx59bpAI$A=`95fAd zoSXtOBQ3~=FUSW$(UhDNi0lK`2G>}#%)2g@Ahd%c`ikNVjS@(!v0`Q12Vsh^HRj`U z2zBZ1tim6z^`N{Ra38wzK=Nb_yrNM>0XZJA34~hpV@CdTNM5)ybUf1P&4O!_I;Yp$ z?v3|UE}mTL<(`{_WYe=ZyZ+Nr3*OgvfLQX2iIeLq5hw~43)0|sE`*^3i;9ACt~UWO2}1C z)yrEd#zGo5*+VF))0FpnQLLVh z$B^bB50E5zuLC+yg zmCHvS8t*7{QBjaWciK!O(j`?IDdBK)38&cHHYjBEGbO}EHjc~pqXN}~yxBuw+yb*xU3KO%#}R-)dR4 zV!L<$&iDf=JK>gJXR=uVHH;FnnoeeGR0yvkr;&e06e~R+(UwmE?X$U^Q#mw8Dm%l}3=|{;!RPSCf%j#x z@(J-t2pZxts-e>~3sys_urvVt{V?T}9@TO)IA!!N7Pstz`o#^TBw-nMrhJQ~3JogF z5<2Ou0CL4jQ%g(OO7YZ;6~%{bS$sA8qC=W`xC)V3-stJXx0Atv?x^m<5h*s=jD1l7j>H| zAcD|{S5n`3*a_vMxqT%Cu}7!|a6&q?s&7+s3HSGwUT!{2DeZ7H7_FLw%|X;$++a_- z8-JjMG*WKPp0p5dw~i$&h&?PP(IoI`V1Z3Rl$BQ*Hqq^-(QCUA>?yWtu=F{x`+O0u`4lmZ;Q>l; zQX5P!buvG)R?SrNV2G)gqZ+tb85=-6Y9)@8u&e**7Spq#@bS=dE`!`^NHnCv-*!&8 zKsf9?CEQd(im$$hv}ZlMl@WLLYff|jN*d7O+iUG}p;VA(moIMlse?kVEgAU5WV`=X zu&w922f6(XZa9|rGhJ^wFuEApkrKvF&iPrQ>w8#pBR%^ZH`F z4uYHpjeTTY$Hu88YqfB|(EV|&g52V2)p5gjvEizM)6 zm&$gtx(;au$>VQ)*gVNU$Y0DMr!1}=%=k7k#Lg9iH3xI8ter`Np7i;|?Ph6wWxI>) zdK*%|5s#OEV<-;Z;|)}W=JijkBxtCjCZ_v&fq-@;X^iZX*s*gb&)$*9VSpOZDtQ<{ zGUVSe`Uk0n3gj8q$h{ z5C(A(p>TbbIZM-ug8A+zQ57Q+mG88Pw`G zJ8GUV6fEpVx3xn=#!k|GvXF?bNFC6R{qe?mdFui6D4BH*oQfnYOsH3R|E z1oL@!c;{C_*gAZUS591MaG^s`@4BS_!<}aym6Ye{IF;^+LeIKc^5$^1(X09OdDs2N z;$}zcftK_}05TTJ2YgtU2~4t!92qtNNm)AZ0!Ej_=$BBJXM@+L+f8{^*FGniJJ%#S znY3k_gX80y%ihf zegt>!zGQv+DJkQ{^W)O~`S4s}_nrPltdl2K9-e9i1UAxu6)UD2MpimyogNSZ64riS z6yjhI=Ep4vUi3`v+Fh4m03pdGg`BQ)S_e!=tGh(kS0V`ZUWCaSH1rq}qo?M9uGJp< zSqR<_yv_S`oJoa}G;cuz1p$X~=j$BQ`HKwMMH3S8hvDzY17(Q=OEb5}FJ5VFqq9Gy zGaZY)hg-9|`1Omc$2(d2xMC#Is4sOsF`Z+yytj>kt}+Ux%scj}K$a*l{IuE3v$CmC^Vo>KXV+$~=~cv_oyM{O0uEQK_?oIsehJuy^Nk9)4?R2P2w{VwSM zHrO(_geWzvY7z?Ba!jA5EnqrIU^D?PSMxz{=^M1hkXrw2$Bq$PuxD0(Hcu@Ce=aRP zg?->DJ|dFB&{N%xUnAxKz>PstGD9eM<9#@*?? zR?b&j>$e;lYmFX9N*0SIxhUzX<09!Y9wqn33co>(Zq<*U7ecBc+GVHb4iK63kW%qn zJkmJ%bs^b&?9Fch={og^c|?2DF!+Ta3(ocW@{}r(Q}qC{VeI;{fR%5l;q7|!Pvh$p zSXpN%`b!4h6OpLolnUxoNwgM6^_g{RN#SAOGI@)2y(5U|`D;snV!ixte8&q-P_{7! zQ#WDHlt&9j75McOKDI%kAZpmw?=SI$V+dh;RUPEj>Kab;t_9EZBq`2^9)hElB zy%)8AR~b)W(QdE*4Xf%*In=nie#XN2aqZfOqiOMWN_1#$FU7GT#j=deR%8wh+aT_T z5l6>4z7aJ;mCDQr%e|XSxX%$?j>cp4RDEDD9+@I)W4bwxK=%R=;}e)pL*&D?-w=80 z+nU7T^jk|c6UQ3LnfT}N1C*gnm0!W*PW?iulW_NY#G9QNn!ik66!f`%U?QOJxoj4P zMpDs%L*O?hR-TT7m@OC1a@QWz&5$F-kXW9zsxf6mNJhF-iEq*8<<7bkN0CT1UKQQ^ zLXG1uhW=yX6*kg})B$bvhi_XQ96ZXrZ54*{rCbu)BCxZy;rmhq9pv~Bk5(3mMCDlN5 zn_$)Q780)ViWkPaeJ;O2vsf_aiqJc90-jGrPS(EZg<_Db_@gQ@)x;l|zX5O5xoqSV zyfl511Dj+Q=goNRP7mk%Ofd6OC&~rJ*4MJ3E)hr?`0I!wIPl$l23m;Wf6(6=9oDIq z6g`&_eee`X1+YVIz(L3}!XhiNGZ>fEvxR98dgCV%muk1r-z#H)DpB+s5gvB|Ix3hdzi%=dUs{dw&X6aO7K*IB*iP80rg{Y9cmipTMO4z1s zlVcVW3>&VR;A@Yuc$E9Y*7A@fwH1>IsR|oYdD~FT>S`;7gf-5NCSzIer~P+BA7Yp@ zr;S(Y3hQ0yf9lb-Y}zOZ3#oUDq+sps@#k>GC(d8Xm%qH&I_F3C=R~I~lR54fSa?Dh zo@!$2<1Crq@c85|9J}}w>Ikg#IUCIGx6IMg-PUM)ly>ae3@6i%ReKptr>?}ax1T9> zaSjUS15FfXi;*St=@A#EHfATsLC9wu+!1N;<14Na-{%l9vG-&sz;kiMx;I5hxi`R=QAE9`#XuMv1kV=OD=}`q!uZew_!r51%=t{|>Ms2dq z{FE^V5yF~Cpe(NzTBcv=+7$z2p(|U^Jx?>5DQtLu?cGraPq6Vh5y(E)WQ58NyTWQ% zA>Zzr=TbQ~26CZh!O&J`GCd-WuOZ>1{;q?eyxo+;;@zc0y?puBXG(_?vj@;!=CSLQ z&=l(S^5HxoF{zQ|lZV(l&Ain#_&)d(S5rxp#|q@uob{AND)( ziM`4k!_hQguB_?oZau4OnL;I(mU-Nd9d;x3KiV~5WSTYz7HV|RO(`U;gwsE7AG|82 zFS0e(Uvmzbl-++^9G>kqYiE~GJ?N;ldCZ}T*IY@RX2I@jl-Nu14W;-d_Q0fRS0U=G z8K|HBfU^N+)!w&;=}c+fvSv>ZGozwaUvhYE=dYIMa`zImyI28brR{mzMm=!Wv4yf9a@!5~u_X?RCDV?N!dDa4uAlFgsXNT| zCdcI0O=%lV8t`*@c6eRf-%PY-?vu$py`s~}kdvm_XY_creY!%TGZ2|QeA$01m&qtN zDwKIcb0XkK9Z}!=DN!KXbh?CIp^)J5zz8?0wtNE!3En}5D0hu&vHAKp77qXPc>Z2E zdcmXhYMXTGs7jwZ%+V>WAwVz)YE_tumt=WO!<%Yh9INq|5e3J9(P1kZ4d+bUVYAg! zE4?Eu`f38ZRrr>TlOoU5L=;O)Lb)6Zz!(s0v)<_n?F*>9ZWo4OwRTV0!?WcS{$-Xq0V@RKnoNd(KKd-+xC zO%7bbjCBDuZYE6;Uh8Pih!utJVzdD0rR#mU=ZL9#H<{Jsr9jp(>g3nk!#i2R_Q7xj z^3bxJG~&g=p=6&6TPNY9ZU(yH=aYRHNuy~qih!_w~bQRJ74Xrx#hJs&SD_=mM{sTIo*Y}bwfX4qG=MUdG6=j;j8xGj|Zm3%usi2I{tRFK2-*E1(M8xWbf z$(1!DR?jBv^Svug8;j;9GC0s_4KTX;Od-!0a87zY7ZS5hE^dmZm>xFH(0AJ7oMY}7 zo}VAr{muNH(3<#*JdPdi8~umX9Q~-gz@~dX8?R+8`*`B(k~Bu5*`a;+9~ga41P9d} z2wzldtHudG97;c0ULB(!QgB0|h`h#8si*Y3T=ZpNb6-ovLC^q_{(9D*-bnc{hebBs z1u9C<22+=t3S5h6v?3&_hb5cIV*|1)(cv~X8+?l%n5kDRlN-`h1DvBn{bDpQV&Kdr z=&k??)aMVjZ6w_+am}BGLo&Ka=`MZBnhwr0#SCOfEd1KacLs1Z@t3Y-I^Eyo0~8Uj z#I_X%d3^d%eASFdg%tDANcFlMOuU_ZoM$w8>Fn^93qua=o_k#uFw(d8*h?@x!J`ybpvB zP{cj!;2LBtc;hH2@MXr*-x+-%A;jG)(AZa?79rQ#7M z%UZ9f>n){68$U?l(wo~i3y=?Oo7w#yUk%|2HN@0;fLtl%+F2gGoc%zR>pwz-bS$Y+ia zh#||o+-;`}*kbLwSt-GW^Gvb*c2VZ3E59M={c*xfQqY@V7vVJDbm_u&!&+ZoLQm+9 zi25mh;Xvwr{A0!27JTTMib{`SkncB8fZv1wM)jkL1=gkTf3sZ9b-O8zHgw1iEKF~W z*>2|d068%m_qFPMUw&f(}!BsY=GbytN=?x$5YS0jCWal%Ix%L^+!T zsmR^(g+`$)J^n0Ya3IBQzbz6HCYBO&B0r!lPP66hG(nfH;XVq6F-T9(p}2B08vSTTAD8^TDjdRX$5z&M;v z2{SeF)5;z!``v?ga84*zq?~VUiTYq4-2610cuT?wHL}~67Nqndp;RU(vE0VkM3)jx z4@yrx>I1i;RCB$=CcQ#sB}c4~Dm{Xd#WCixc-e9^3+1_&uOC~@YLG|{ITpa%N28=o z*^nO>J0w=>cssm20)5oO+{-3+WHZ}!XocL^ghyA{y~C_dTs#3%!{+Tyz^B}V@?{;B zAI`BXG#`=LDb!8Q?s%%WNP??Bte9L*eCp_(r9aD!%N%hsod z)o}5XN^$TsHm@jR<&-o+4hG*lKkU6oV}+{6Y7F?r*5dAG4}nTULI|B<;r84+b4y5~ z_wU7NOSfuTTGO?f!skQ6Z!4BaYWT46_6a<4Fq)l=_%K+irfI@_Q;b9hli^%vV1GTkPi!^dg+hcV6ifqBXj#b8J2p zwnxwOyWlxNu$IiA?3x*zJ}mY_Z@kS9%}!P*ONU*4^j7J+k@@2}DHb#Jf)<-X&d?k% zDuQhlv#SI9NS59E4uNs=CSMVO_!fe=vbl9vwL_$FI++NDjI%@BPbX3@7IX%uX@k(| z*X;vkU!bXNTQ$eEPpp56_ud->Mk}8_mHU3$ErlHv{HRcP7B4irK6Ba}nZiQSH_{t< zh!=MRnkRp1J7ck);%DKb{@^Rp$gy60@$tlYJ6eLwv{ZTge%^V+oW z_Z+v{;XPI-jtZuA$5w}YU6fBWC+x8f5;{MnM^rKmh-BMoX~J*m&KkoxoCFj%?X%BU zBYb2v1W5uGzRUV|5J_OBBU#Vr2W)VRd+h24Ot0+YmpYdszuZs-u?%ny%a>J#Ek9Vj zOkk#WGBB@6%en_@UM##j+du-r#tG`EjCo!SSpZo-ON771O{O#D-~)()&q#_=&F9r^ ztfYnuG#li5tJt|&Nvv8t&Lsaza~}gZ;t=xu*dEf5z^s}Dfw1vAz`9#2T=PX6%F`EBmQ(7^7E-TCGm06_bv3u>@`=>BVUoNWyZVd(($%&>I-&jny+Vq#zd z7y|y3z40vR-Uj;X0$Bb_#`@;LKV&S7Z|?k4_A9{pFETnhdZxG8{D%z4@HWhU$mo6z z_P@x0jLg4A{tp?`uW9%%GCF#ef75&0>u)3Yrye8AKW)%4(=)xL+W%{R%s_^J+NEQr z1O9Vf=-A%Aqkq232K;xstZe^g7YJmb|EFCbkeTkE{Q=(=}` 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(); diff --git a/scripts/switch-db.js b/scripts/switch-db.js new file mode 100644 index 0000000..e17a89e --- /dev/null +++ b/scripts/switch-db.js @@ -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]'); +} diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts new file mode 100644 index 0000000..cc18598 --- /dev/null +++ b/src/app/api/auth/login/route.ts @@ -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, + `🔐 KODE VERIFIKASI LOGIN MFA (ERP)\n\nHalo ${user.name},\nKode OTP Login 2-Langkah Anda adalah:\n\n${dynamicOtp}\n\nKode ini berlaku selama 5 menit. Jangan berikan kode ini kepada siapa pun.` + ); + } + 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 } + ); + } +} diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts new file mode 100644 index 0000000..1f436b9 --- /dev/null +++ b/src/app/api/auth/logout/route.ts @@ -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; +} diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts new file mode 100644 index 0000000..941159f --- /dev/null +++ b/src/app/api/auth/me/route.ts @@ -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 } + ); +} diff --git a/src/app/api/auth/mfa/route.ts b/src/app/api/auth/mfa/route.ts new file mode 100644 index 0000000..63a6c3d --- /dev/null +++ b/src/app/api/auth/mfa/route.ts @@ -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 } + ); + } +} diff --git a/src/app/api/dashboard/route.ts b/src/app/api/dashboard/route.ts new file mode 100644 index 0000000..e0cde89 --- /dev/null +++ b/src/app/api/dashboard/route.ts @@ -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>(); + 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>(); + 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(); + 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 } + ); + } +} diff --git a/src/app/api/devices/route.ts b/src/app/api/devices/route.ts new file mode 100644 index 0000000..a92aabe --- /dev/null +++ b/src/app/api/devices/route.ts @@ -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 }); + } +} diff --git a/src/app/api/finance/route.ts b/src/app/api/finance/route.ts new file mode 100644 index 0000000..96dff94 --- /dev/null +++ b/src/app/api/finance/route.ts @@ -0,0 +1,1276 @@ +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"; + +export async function GET() { + try { + const user = await getCurrentUser(); + if (!user) { + return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 }); + } + + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: `Akses ditolak: Peran ${user.role} tidak memiliki hak akses modul keuangan.` }, + { status: 403 } + ); + } + + const [ + accounts, + journalEntries, + payrollRecords, + savedEmployees, + posSetting, + compSetting, + openSalesOrders, + openPurchaseOrders, + ] = await Promise.all([ + prisma.account.findMany({ + orderBy: { code: "asc" }, + }), + prisma.journalEntry.findMany({ + take: 25, + orderBy: { date: "desc" }, + include: { + lines: { + include: { + account: true, + }, + }, + }, + }), + prisma.payrollRecord.findMany({ + orderBy: { createdAt: "desc" }, + }), + prisma.payrollEmployee.findMany({ + orderBy: { name: "asc" }, + }), + prisma.systemSetting.findUnique({ + where: { key: "PAYROLL_POSITIONS" }, + }), + prisma.systemSetting.findUnique({ + where: { key: "PAYROLL_COMPANIES" }, + }), + prisma.salesOrder.findMany({ + where: { status: { not: "CANCELLED" }, paymentStatus: { not: "PAID" } }, + include: { customer: true }, + orderBy: { orderDate: "asc" }, + }), + prisma.purchaseOrder.findMany({ + where: { status: { notIn: ["CANCELLED", "REJECTED"] }, paymentStatus: { not: "PAID" } }, + include: { supplier: true }, + orderBy: { orderDate: "asc" }, + }), + ]); + + // Gabungkan daftar karyawan dari PayrollEmployee dan riwayat PayrollRecord (terpisah dari user login RBAC) + const employeeMap = new Map< + string, + { + id: string; + name: string; + companyName: string; + position: string; + baseSalary: number; + dailyMealRate: number; + } + >(); + + savedEmployees.forEach((emp) => { + employeeMap.set(emp.name.toLowerCase(), { + id: emp.id, + name: emp.name, + companyName: emp.companyName || "PT EnterpriseCore Utama", + position: emp.position, + baseSalary: emp.baseSalary, + dailyMealRate: emp.dailyMealRate, + }); + }); + + payrollRecords.forEach((pr) => { + const key = pr.employeeName.toLowerCase(); + if (!employeeMap.has(key)) { + employeeMap.set(key, { + id: pr.id, + name: pr.employeeName, + companyName: pr.companyName || "PT EnterpriseCore Utama", + position: pr.role, + baseSalary: pr.baseSalary, + dailyMealRate: pr.dailyMealRate, + }); + } + }); + + const payrollEmployees = Array.from(employeeMap.values()); + + // Gabungkan daftar Jabatan yang pernah disimpan (bebas & berbeda dari RBAC) + const posSet = new Set(); + if (posSetting?.value) { + try { + const parsed: string[] = JSON.parse(posSetting.value); + parsed.forEach((p) => p && posSet.add(p)); + } catch { + // ignore + } + } + payrollEmployees.forEach((e) => e.position && posSet.add(e.position)); + payrollRecords.forEach((r) => r.role && posSet.add(r.role)); + const positions = Array.from(posSet); + + // Gabungkan daftar Entitas PT (Perusahaan) untuk pemisahan Payroll & Bank per PT + const compSet = new Set(); + if (compSetting?.value) { + try { + const parsedComp: string[] = JSON.parse(compSetting.value); + parsedComp.forEach((c) => c && compSet.add(c)); + } catch { + // ignore + } + } + if (compSet.size === 0) { + compSet.add("PT EnterpriseCore Utama"); + } + accounts.forEach((a) => a.companyName && compSet.add(a.companyName)); + payrollEmployees.forEach((e) => e.companyName && compSet.add(e.companyName)); + payrollRecords.forEach((r) => r.companyName && compSet.add(r.companyName)); + const companies = Array.from(compSet); + + const nowMs = Date.now(); + const arList = openSalesOrders + .map((so) => { + const remaining = Math.max(0, (so.totalAmount || 0) - (so.paidAmount || 0)); + const ageDays = Math.max( + 0, + Math.floor((nowMs - new Date(so.orderDate || so.createdAt).getTime()) / (1000 * 60 * 60 * 24)) + ); + return { + id: so.id, + number: so.orderNumber, + counterparty: so.customer?.company || so.customer?.name || "-", + companyName: so.companyName || "PT EnterpriseCore Utama", + orderDate: so.orderDate || so.createdAt, + totalAmount: so.totalAmount || 0, + paidAmount: so.paidAmount || 0, + remaining, + paymentStatus: so.paymentStatus, + ageDays, + }; + }) + .filter((x) => x.remaining > 0); + + const apList = openPurchaseOrders + .map((po) => { + const remaining = Math.max(0, (po.totalAmount || 0) - (po.paidAmount || 0)); + const ageDays = Math.max( + 0, + Math.floor((nowMs - new Date(po.orderDate || po.createdAt).getTime()) / (1000 * 60 * 60 * 24)) + ); + return { + id: po.id, + number: po.poNumber, + counterparty: po.supplier?.name || "-", + companyName: po.companyName || "PT EnterpriseCore Utama", + orderDate: po.orderDate || po.createdAt, + totalAmount: po.totalAmount || 0, + paidAmount: po.paidAmount || 0, + remaining, + paymentStatus: po.paymentStatus, + ageDays, + }; + }) + .filter((x) => x.remaining > 0); + + return NextResponse.json({ + accounts, + journalEntries, + payrollRecords, + payrollEmployees, + positions, + companies, + arList, + apList, + }); + } catch (error: any) { + console.error("Finance 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 }); + } + + const body = await req.json(); + + // ========================================================================= + // A1. TAMBAH ENTITAS PT BARU UNTUK PEMISAHAN PAYROLL & AKUN BANK + // ========================================================================= + if (body.action === "ADD_COMPANY") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json({ error: "Akses ditolak" }, { status: 403 }); + } + const newComp = (body.companyName || "").trim(); + if (!newComp) { + return NextResponse.json({ error: "Nama PT wajib diisi" }, { status: 400 }); + } + + const existingSetting = await prisma.systemSetting.findUnique({ + where: { key: "PAYROLL_COMPANIES" }, + }); + + let list: string[] = ["PT EnterpriseCore Utama"]; + if (existingSetting?.value) { + try { + list = JSON.parse(existingSetting.value); + } catch { + list = ["PT EnterpriseCore Utama"]; + } + } + if (!list.includes(newComp)) { + list.push(newComp); + } + + await prisma.systemSetting.upsert({ + where: { key: "PAYROLL_COMPANIES" }, + update: { value: JSON.stringify(list) }, + create: { + key: "PAYROLL_COMPANIES", + value: JSON.stringify(list), + category: "FINANCE", + }, + }); + + return NextResponse.json({ success: true, companies: list }); + } + + // ========================================================================= + // A1-B. HAPUS ENTITAS PT (KHUSUS SUPERADMIN / ADMIN) + // ========================================================================= + if (body.action === "DELETE_COMPANY") { + if (user.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(); + const existingSetting = await prisma.systemSetting.findUnique({ + where: { key: "PAYROLL_COMPANIES" }, + }); + + let list: string[] = ["PT EnterpriseCore Utama"]; + if (existingSetting?.value) { + try { + list = JSON.parse(existingSetting.value); + } catch { + list = ["PT EnterpriseCore Utama"]; + } + } + + const updatedList = list.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]; + 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, + fallbackCompany, + }); + } + + if (!["ADMIN", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { + error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang transaksi keuangan. Hanya Finance (Akuntan) dan Admin yang diizinkan.`, + }, + { status: 403 } + ); + } + + // ========================================================================= + // A2. TAMBAH KODE AKUN / REKENING BANK BARU (COA) + // ========================================================================= + if (body.action === "CREATE_ACCOUNT") { + const code = (body.code || "").trim(); + const name = (body.name || "").trim(); + const type = (body.type || "ASSET").trim(); + const companyName = (body.companyName || "PT EnterpriseCore Utama").trim(); + const balance = Number(body.balance) || 0; + + if (!code || !name) { + return NextResponse.json( + { error: "Kode Akun dan Nama Akun/Bank wajib diisi" }, + { status: 400 } + ); + } + + const existingCode = await prisma.account.findFirst({ where: { code, companyName } }); + if (existingCode) { + return NextResponse.json( + { error: `Kode Akun ${code} sudah digunakan oleh "${existingCode.name}". Gunakan kode lain atau edit akun tersebut.` }, + { status: 400 } + ); + } + + const account = await prisma.account.create({ + data: { + code, + name, + type, + companyName, + balance, + }, + }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "CREATE_ACCOUNT", + module: "FINANCE", + description: `[${user.role}] Menambahkan Kode Akun / Bank baru [${code}] ${name} (${companyName})`, + }); + + return NextResponse.json({ success: true, account }); + } + + // ========================================================================= + // A3. EDIT KODE AKUN / NAMA AKUN / BANK & ENTITAS PT (COA) + // ========================================================================= + if (body.action === "UPDATE_ACCOUNT") { + const id = body.id; + const code = (body.code || "").trim(); + const name = (body.name || "").trim(); + const type = (body.type || "ASSET").trim(); + const companyName = (body.companyName || "PT EnterpriseCore Utama").trim(); + + if (!id || !code || !name) { + return NextResponse.json( + { error: "ID, Kode Akun, dan Nama Akun/Bank wajib diisi" }, + { status: 400 } + ); + } + + const duplicate = await prisma.account.findFirst({ + where: { + code, + companyName, + NOT: { id }, + }, + }); + + if (duplicate) { + return NextResponse.json( + { error: `Kode Akun ${code} sudah dipakai oleh akun "${duplicate.name}"` }, + { status: 400 } + ); + } + + const updatedData: any = { + code, + name, + type, + companyName, + }; + if (body.balance !== undefined && body.balance !== "") { + updatedData.balance = Number(body.balance) || 0; + } + + const account = await prisma.account.update({ + where: { id }, + data: updatedData, + }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE_ACCOUNT", + module: "FINANCE", + description: `[${user.role}] Memperbarui Kode Akun / Bank menjadi [${code}] ${name} (${companyName})`, + }); + + return NextResponse.json({ success: true, account }); + } + + // ========================================================================= + // A3-B. HAPUS KODE AKUN / REKENING BANK TAMBAHAN (KHUSUS ADMIN) + // ========================================================================= + if (body.action === "DELETE_ACCOUNT") { + if (user.role !== "ADMIN") { + return NextResponse.json( + { error: "Akses ditolak: Hanya Super Admin yang dapat menghapus Kode Akun / Bank." }, + { status: 403 } + ); + } + + const { id } = body; + if (!id) { + return NextResponse.json({ error: "ID Akun wajib diisi" }, { status: 400 }); + } + + const acc = await prisma.account.findUnique({ + where: { id }, + }); + + if (!acc) { + return NextResponse.json({ error: "Akun tidak ditemukan" }, { status: 404 }); + } + + const systemCodes = [ + "1001", + "1002", + "1101", + "1201", + "1301", + "2001", + "2101", + "3001", + "4001", + "5001", + "6001", + ]; + if (systemCodes.includes(acc.code)) { + return NextResponse.json( + { + error: `Kode Akun sistem [${acc.code}] ${acc.name} tidak boleh dihapus karena digunakan oleh otomatisasi jurnal ERP. Anda cukup mengedit namanya.`, + }, + { status: 400 } + ); + } + + const lineCount = await prisma.journalLine.count({ + where: { accountId: id }, + }); + + if (lineCount > 0) { + return NextResponse.json( + { + error: `Akun [${acc.code}] ${acc.name} masih memiliki riwayat jurnal aktif. Hapus jurnal terkait terlebih dahulu.`, + }, + { status: 400 } + ); + } + + await prisma.account.delete({ where: { id } }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "DELETE_ACCOUNT", + module: "FINANCE", + description: `[${user.role}] Menghapus Kode Akun / Bank [${acc.code}] ${acc.name} (${acc.companyName})`, + }); + + return NextResponse.json({ success: true, deletedId: id }); + } + + // ========================================================================= + // A3-C. HAPUS JURNAL TRANSAKSI & KEMBALIKAN SALDO AKUN (KHUSUS ADMIN) + // ========================================================================= + if (body.action === "DELETE_JOURNAL") { + if (user.role !== "ADMIN") { + return NextResponse.json( + { error: "Akses ditolak: Hanya Super Admin yang dapat menghapus Jurnal Transaksi." }, + { status: 403 } + ); + } + + const { id } = body; + if (!id) { + return NextResponse.json({ error: "ID Jurnal wajib diisi" }, { status: 400 }); + } + + const je = await prisma.journalEntry.findUnique({ + where: { id }, + include: { lines: true }, + }); + + if (!je) { + return NextResponse.json({ error: "Jurnal tidak ditemukan" }, { status: 404 }); + } + + for (const line of je.lines) { + const acc = await prisma.account.findUnique({ where: { id: line.accountId } }); + if (acc) { + const isNormalDebit = acc.type === "ASSET" || acc.type === "EXPENSE"; + let reversedBalance = acc.balance; + if (line.type === "DEBIT") { + reversedBalance = isNormalDebit + ? acc.balance - line.amount + : acc.balance + line.amount; + } else { + const isNormalCredit = + acc.type === "LIABILITY" || + acc.type === "EQUITY" || + acc.type === "REVENUE"; + reversedBalance = isNormalCredit + ? acc.balance - line.amount + : acc.balance + line.amount; + } + await prisma.account.update({ + where: { id: acc.id }, + data: { balance: reversedBalance }, + }); + } + } + + await prisma.journalEntry.delete({ where: { id } }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "DELETE_JOURNAL", + module: "FINANCE", + description: `[${user.role}] Menghapus Jurnal ${je.entryNumber} dan mengembalikan saldo akun terkait`, + }); + + return NextResponse.json({ success: true, deletedId: id }); + } + + // ========================================================================= + // A4. TAMBAH JABATAN BARU (TERPISAH DARI RBAC) + // ========================================================================= + if (body.action === "ADD_POSITION") { + const newPos = (body.position || "").trim(); + if (!newPos) { + return NextResponse.json({ error: "Nama jabatan wajib diisi" }, { status: 400 }); + } + + const existingSetting = await prisma.systemSetting.findUnique({ + where: { key: "PAYROLL_POSITIONS" }, + }); + + let list: string[] = []; + if (existingSetting?.value) { + try { + list = JSON.parse(existingSetting.value); + } catch { + list = []; + } + } + if (!list.includes(newPos)) { + list.push(newPos); + } + + await prisma.systemSetting.upsert({ + where: { key: "PAYROLL_POSITIONS" }, + update: { value: JSON.stringify(list) }, + create: { + key: "PAYROLL_POSITIONS", + value: JSON.stringify(list), + category: "FINANCE", + }, + }); + + return NextResponse.json({ success: true, positions: list }); + } + + // ========================================================================= + // A5. EDIT SLIP GAJI / PAYROLL (KHUSUS SUPER ADMIN / ADMIN) + // ========================================================================= + if (body.action === "UPDATE_PAYROLL") { + if (user.role !== "ADMIN") { + return NextResponse.json( + { + error: + "Akses ditolak: Hanya Admin yang dapat mengedit Slip Gaji yang sudah terbit. Selain Admin hanya dapat melihat, mencetak, dan menambah Slip Gaji.", + }, + { status: 403 } + ); + } + + const { + id, + companyName, + employeeName, + role, + period, + workDays, + absentDays, + lateCount, + baseSalary, + dailyMealRate, + transportAllowance, + absenceDeduction, + paymentAccountId, + notes, + } = body; + + if (!id) { + return NextResponse.json({ error: "ID Slip Gaji wajib diisi" }, { status: 400 }); + } + + const existing = await prisma.payrollRecord.findUnique({ where: { id } }); + if (!existing) { + return NextResponse.json( + { error: "Data Slip Gaji tidak ditemukan" }, + { status: 404 } + ); + } + + const wDays = Math.max(0, Number(workDays) || 0); + const aDays = Math.max(0, Number(absentDays) || 0); + const lCount = Math.max(0, Number(lateCount) || 0); + const bSalary = Math.max(0, Number(baseSalary) || 0); + const mealRate = Math.max(0, Number(dailyMealRate) || 0); + const transAllow = Math.max(0, Number(transportAllowance) || 0); + const deduct = Math.max(0, Number(absenceDeduction) || 0); + + const totalMealAllowance = wDays * mealRate; + const netSalary = Math.max(0, bSalary + totalMealAllowance + transAllow - deduct); + + const cleanCompany = (companyName || existing.companyName).trim(); + const cleanName = (employeeName || existing.employeeName).trim(); + const cleanRole = (role || existing.role).trim(); + + // 1. Kembalikan (reverse) saldo akun dari Jurnal Payroll lama sebelum mengupdate + const oldJournals = await prisma.journalEntry.findMany({ + where: { reference: existing.payrollNumber }, + include: { lines: true }, + }); + + if (oldJournals.length > 0) { + for (const je of oldJournals) { + for (const line of je.lines) { + const acc = await prisma.account.findUnique({ where: { id: line.accountId } }); + if (acc) { + const isNormalDebit = acc.type === "ASSET" || acc.type === "EXPENSE"; + let newBalance = acc.balance; + if (line.type === "DEBIT") { + newBalance = isNormalDebit + ? acc.balance - line.amount + : acc.balance + line.amount; + } else { + const isNormalCredit = + acc.type === "LIABILITY" || + acc.type === "EQUITY" || + acc.type === "REVENUE"; + newBalance = isNormalCredit + ? acc.balance - line.amount + : acc.balance + line.amount; + } + await prisma.account.update({ + where: { id: acc.id }, + data: { balance: newBalance }, + }); + } + } + } + await prisma.journalEntry.deleteMany({ + where: { reference: existing.payrollNumber }, + }); + } else if (existing.netSalary > 0) { + // Fallback jika jurnal lama tidak ditemukan via reference + const expAcc = await prisma.account.findFirst({ where: { code: "6001", companyName: existing.companyName || "PT EnterpriseCore Utama" } }); + if (expAcc) { + await prisma.account.update({ + where: { id: expAcc.id }, + data: { balance: expAcc.balance - existing.netSalary }, + }); + } + const codeMatch = (existing.paymentAccountName || "").match(/\[([^\]]+)\]/); + const oldCashCode = codeMatch ? codeMatch[1] : "1001"; + const oldCashAcc = await prisma.account.findFirst({ where: { code: oldCashCode, companyName: existing.companyName || "PT EnterpriseCore Utama" } }); + if (oldCashAcc) { + await prisma.account.update({ + where: { id: oldCashAcc.id }, + data: { balance: oldCashAcc.balance + existing.netSalary }, + }); + } + } + + // 2. Tentukan akun kas/bank pembayar baru + let cashAcc = paymentAccountId + ? await prisma.account.findUnique({ where: { id: paymentAccountId } }) + : null; + if (!cashAcc && existing.paymentAccountName) { + const codeMatch = existing.paymentAccountName.match(/\[([^\]]+)\]/); + if (codeMatch) { + cashAcc = await prisma.account.findFirst({ where: { code: codeMatch[1], companyName: existing.companyName || "PT EnterpriseCore Utama" } }); + } + } + if (!cashAcc) { + cashAcc = await prisma.account.findFirst({ where: { code: "1001", companyName: existing.companyName || "PT EnterpriseCore Utama" } }); + } + + const paymentAccountLabel = cashAcc + ? `[${cashAcc.code}] ${cashAcc.name}` + : existing.paymentAccountName || "Kas / Bank Perusahaan"; + + const updatedPayroll = await prisma.payrollRecord.update({ + where: { id }, + data: { + companyName: cleanCompany, + employeeName: cleanName, + role: cleanRole, + period: period || existing.period, + workDays: wDays, + absentDays: aDays, + lateCount: lCount, + baseSalary: bSalary, + dailyMealRate: mealRate, + totalMealAllowance, + transportAllowance: transAllow, + absenceDeduction: deduct, + netSalary, + paymentAccountName: paymentAccountLabel, + notes: notes !== undefined ? notes : existing.notes, + }, + }); + + // 3. Sinkronkan Master Karyawan Payroll + await prisma.payrollEmployee.upsert({ + where: { name: cleanName }, + update: { + companyName: cleanCompany, + position: cleanRole, + baseSalary: bSalary, + dailyMealRate: mealRate, + }, + create: { + name: cleanName, + companyName: cleanCompany, + position: cleanRole, + baseSalary: bSalary, + dailyMealRate: mealRate, + }, + }); + + // 4. Posting ulang Jurnal dan update saldo akun sesuai nominal baru + if (netSalary > 0) { + const expenseAcc = await prisma.account.findFirst({ where: { code: "6001", companyName: cleanCompany } }); + if (expenseAcc && cashAcc) { + const jCount = await prisma.journalEntry.count(); + const entryNumber = `JV-PAY-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`; + const desc = `[${cleanCompany}] Pembayaran Payroll & Uang Makan ${cleanName} [${cleanRole}] (${ + period || existing.period + }) — Hadir: ${wDays} hr, Absen: ${aDays} hr`; + + await prisma.journalEntry.create({ + data: { + entryNumber, + description: desc, + reference: existing.payrollNumber, + lines: { + create: [ + { + accountId: expenseAcc.id, + type: "DEBIT", + amount: netSalary, + }, + { + accountId: cashAcc.id, + type: "CREDIT", + amount: netSalary, + }, + ], + }, + }, + }); + + const freshExpense = await prisma.account.findUnique({ + where: { id: expenseAcc.id }, + }); + if (freshExpense) { + await prisma.account.update({ + where: { id: freshExpense.id }, + data: { balance: freshExpense.balance + netSalary }, + }); + } + + const freshCash = await prisma.account.findUnique({ + where: { id: cashAcc.id }, + }); + if (freshCash) { + await prisma.account.update({ + where: { id: freshCash.id }, + data: { balance: freshCash.balance - netSalary }, + }); + } + } + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE_PAYROLL", + module: "FINANCE", + description: `[${user.role}] Mengedit Slip Gaji ${existing.payrollNumber} a.n ${cleanName} (${cleanCompany}) menjadi THP Rp ${netSalary.toLocaleString("id-ID")}`, + }); + + return NextResponse.json({ success: true, payroll: updatedPayroll }); + } + + // ========================================================================= + // A6. HAPUS SLIP GAJI / PAYROLL (KHUSUS SUPER ADMIN / ADMIN) + // ========================================================================= + if (body.action === "DELETE_PAYROLL") { + if (user.role !== "ADMIN") { + return NextResponse.json( + { + error: + "Akses ditolak: Hanya Admin yang dapat menghapus Slip Gaji. Selain Admin hanya dapat melihat, mencetak, dan menambah Slip Gaji.", + }, + { status: 403 } + ); + } + + const { id } = body; + if (!id) { + return NextResponse.json({ error: "ID Slip Gaji wajib diisi" }, { status: 400 }); + } + + const existing = await prisma.payrollRecord.findUnique({ where: { id } }); + if (!existing) { + return NextResponse.json( + { error: "Data Slip Gaji tidak ditemukan" }, + { status: 404 } + ); + } + + // 1. Cari jurnal terkait dan kembalikan (reverse) saldo Kas/Bank serta Beban Gaji + const relatedJournals = await prisma.journalEntry.findMany({ + where: { reference: existing.payrollNumber }, + include: { lines: true }, + }); + + if (relatedJournals.length > 0) { + for (const je of relatedJournals) { + for (const line of je.lines) { + const acc = await prisma.account.findUnique({ where: { id: line.accountId } }); + if (acc) { + const isNormalDebit = acc.type === "ASSET" || acc.type === "EXPENSE"; + let reversedBalance = acc.balance; + if (line.type === "DEBIT") { + reversedBalance = isNormalDebit + ? acc.balance - line.amount + : acc.balance + line.amount; + } else { + const isNormalCredit = + acc.type === "LIABILITY" || + acc.type === "EQUITY" || + acc.type === "REVENUE"; + reversedBalance = isNormalCredit + ? acc.balance - line.amount + : acc.balance + line.amount; + } + await prisma.account.update({ + where: { id: acc.id }, + data: { balance: reversedBalance }, + }); + } + } + } + + // Hapus jurnal otomatis yang terkait dengan nomor slip gaji ini + await prisma.journalEntry.deleteMany({ + where: { reference: existing.payrollNumber }, + }); + } else if (existing.netSalary > 0) { + // Fallback apabila jurnal sudah terhapus namun saldo akun belum dikembalikan + const expAcc = await prisma.account.findFirst({ where: { code: "6001", companyName: existing.companyName || "PT EnterpriseCore Utama" } }); + if (expAcc) { + await prisma.account.update({ + where: { id: expAcc.id }, + data: { balance: expAcc.balance - existing.netSalary }, + }); + } + const codeMatch = (existing.paymentAccountName || "").match(/\[([^\]]+)\]/); + const cashCode = codeMatch ? codeMatch[1] : "1001"; + const cashAcc = await prisma.account.findFirst({ where: { code: cashCode, companyName: existing.companyName || "PT EnterpriseCore Utama" } }); + if (cashAcc) { + await prisma.account.update({ + where: { id: cashAcc.id }, + data: { balance: cashAcc.balance + existing.netSalary }, + }); + } + } + + // 2. Hapus record Slip Gaji + await prisma.payrollRecord.delete({ where: { id } }); + + // 3. Jika karyawan ini tidak memiliki riwayat slip gaji lain lagi, bersihkan juga dari PayrollEmployee + const remainingForEmployee = await prisma.payrollRecord.count({ + where: { employeeName: existing.employeeName }, + }); + if (remainingForEmployee === 0) { + await prisma.payrollEmployee.deleteMany({ + where: { name: existing.employeeName }, + }); + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "DELETE_PAYROLL", + module: "FINANCE", + description: `[${user.role}] Menghapus Slip Gaji ${existing.payrollNumber} a.n ${existing.employeeName} dan mengembalikan saldo akun Rp ${existing.netSalary.toLocaleString("id-ID")}`, + }); + + return NextResponse.json({ success: true, deletedId: id }); + } + + // ========================================================================= + // B. PROSES PAYROLL, HITUNG UANG MAKAN & ABSENSI KARYAWAN (PER PT) + // ========================================================================= + if (body.action === "CREATE_PAYROLL") { + const { + companyName, + employeeName, + role, + period, + workDays, + absentDays, + lateCount, + baseSalary, + dailyMealRate, + transportAllowance, + absenceDeduction, + paymentAccountId, + notes, + } = body; + + const cleanCompany = (companyName || "").trim() || "PT EnterpriseCore Utama"; + const cleanName = (employeeName || "").trim(); + const cleanPosition = (role || "").trim() || "Staf Operasional"; + + if (!cleanName || !period) { + return NextResponse.json( + { error: "Nama karyawan dan periode penggajian wajib diisi" }, + { status: 400 } + ); + } + + const wDays = Math.max(0, Number(workDays) || 0); + const aDays = Math.max(0, Number(absentDays) || 0); + const lCount = Math.max(0, Number(lateCount) || 0); + const bSalary = Math.max(0, Number(baseSalary) || 0); + const mealRate = Math.max(0, Number(dailyMealRate) || 0); + const transAllow = Math.max(0, Number(transportAllowance) || 0); + const deduct = Math.max(0, Number(absenceDeduction) || 0); + + const totalMealAllowance = wDays * mealRate; + const netSalary = Math.max(0, bSalary + totalMealAllowance + transAllow - deduct); + + const dateStr = new Date().toISOString().slice(0, 7).replace("-", ""); + const pCount = await prisma.payrollRecord.count(); + const payrollNumber = `PAY-${dateStr}-${String(pCount + 1).padStart(3, "0")}`; + + const cashAcc = paymentAccountId + ? await prisma.account.findUnique({ where: { id: paymentAccountId } }) + : await prisma.account.findFirst({ where: { code: "1001", companyName: cleanCompany } }); + + const paymentAccountLabel = cashAcc + ? `[${cashAcc.code}] ${cashAcc.name}` + : "Kas / Bank Perusahaan"; + + // 1. Simpan ke riwayat PayrollRecord (beserta Nama PT dan Akun Bank Pembayar) + const payroll = await prisma.payrollRecord.create({ + data: { + payrollNumber, + companyName: cleanCompany, + employeeName: cleanName, + role: cleanPosition, + period, + workDays: wDays, + absentDays: aDays, + lateCount: lCount, + baseSalary: bSalary, + dailyMealRate: mealRate, + totalMealAllowance, + transportAllowance: transAllow, + absenceDeduction: deduct, + netSalary, + paymentAccountName: paymentAccountLabel, + status: "PAID", + notes: notes || null, + }, + }); + + // 2. Simpan/Update otomatis ke Master Karyawan Payroll agar muncul di Dropdown berikutnya + await prisma.payrollEmployee.upsert({ + where: { name: cleanName }, + update: { + companyName: cleanCompany, + position: cleanPosition, + baseSalary: bSalary, + dailyMealRate: mealRate, + }, + create: { + name: cleanName, + companyName: cleanCompany, + position: cleanPosition, + baseSalary: bSalary, + dailyMealRate: mealRate, + }, + }); + + // 3. Simpan Jabatan & Nama PT ke SystemSetting bila belum ada + const [posSetting, compSetting] = await Promise.all([ + prisma.systemSetting.findUnique({ where: { key: "PAYROLL_POSITIONS" } }), + prisma.systemSetting.findUnique({ where: { key: "PAYROLL_COMPANIES" } }), + ]); + + let posList: string[] = []; + if (posSetting?.value) { + try { + posList = JSON.parse(posSetting.value); + } catch { + posList = []; + } + } + if (!posList.includes(cleanPosition)) { + posList.push(cleanPosition); + await prisma.systemSetting.upsert({ + where: { key: "PAYROLL_POSITIONS" }, + update: { value: JSON.stringify(posList) }, + create: { + key: "PAYROLL_POSITIONS", + value: JSON.stringify(posList), + category: "FINANCE", + }, + }); + } + + let compList: string[] = ["PT EnterpriseCore Utama"]; + if (compSetting?.value) { + try { + compList = JSON.parse(compSetting.value); + } catch { + compList = ["PT EnterpriseCore Utama"]; + } + } + if (!compList.includes(cleanCompany)) { + compList.push(cleanCompany); + await prisma.systemSetting.upsert({ + where: { key: "PAYROLL_COMPANIES" }, + update: { value: JSON.stringify(compList) }, + create: { + key: "PAYROLL_COMPANIES", + value: JSON.stringify(compList), + category: "FINANCE", + }, + }); + } + + // 4. Otomatis catat Jurnal Pengeluaran Gaji & Uang Makan jika netSalary > 0 + if (netSalary > 0) { + const expenseAcc = await prisma.account.findFirst({ where: { code: "6001", companyName: cleanCompany } }); + + if (expenseAcc && cashAcc) { + const jCount = await prisma.journalEntry.count(); + const entryNumber = `JV-PAY-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`; + const desc = `[${cleanCompany}] Pembayaran Payroll & Uang Makan ${cleanName} [${cleanPosition}] (${period}) — Hadir: ${wDays} hr, Absen: ${aDays} hr`; + + await prisma.journalEntry.create({ + data: { + entryNumber, + description: desc, + reference: payrollNumber, + lines: { + create: [ + { + accountId: expenseAcc.id, + type: "DEBIT", + amount: netSalary, + }, + { + accountId: cashAcc.id, + type: "CREDIT", + amount: netSalary, + }, + ], + }, + }, + }); + + await prisma.account.update({ + where: { id: expenseAcc.id }, + data: { balance: expenseAcc.balance + netSalary }, + }); + + await prisma.account.update({ + where: { id: cashAcc.id }, + data: { balance: cashAcc.balance - netSalary }, + }); + + await dispatchNotification({ + type: "MONEY_OUT", + title: `Pembayaran Payroll (${cleanCompany}): ${payrollNumber}`, + message: `[${cleanCompany}] Pencairan gaji & uang makan untuk ${cleanName} (${cleanPosition} - ${period}) sebesar Rp ${netSalary.toLocaleString( + "id-ID" + )} melalui ${paymentAccountLabel}.`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT"], + }); + } + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "CREATE_PAYROLL", + module: "FINANCE", + description: `[${user.role}] Memproses Payroll (${cleanCompany}) ${payrollNumber} a.n ${cleanName} (${cleanPosition} - ${period}) senilai Rp ${netSalary.toLocaleString( + "id-ID" + )} via ${paymentAccountLabel}`, + }); + + return NextResponse.json({ success: true, payroll }); + } + + // ========================================================================= + // C. PROSES JURNAL UMUM MANUAL + // ========================================================================= + const { description, reference, debitAccountId, creditAccountId, amount } = body; + + if (!description || !debitAccountId || !creditAccountId || !amount || amount <= 0) { + return NextResponse.json( + { error: "Deskripsi, Akun Debit, Akun Kredit, dan Jumlah wajib diisi" }, + { status: 400 } + ); + } + + if (debitAccountId === creditAccountId) { + return NextResponse.json( + { error: "Akun Debit dan Kredit tidak boleh sama" }, + { status: 400 } + ); + } + + const amt = parseFloat(amount); + const debitAcc = await prisma.account.findUnique({ where: { id: debitAccountId } }); + const creditAcc = await prisma.account.findUnique({ where: { id: creditAccountId } }); + + const journalCompany = (body.companyName || "").trim() || debitAcc?.companyName || creditAcc?.companyName || "PT EnterpriseCore Utama"; + + const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); + const count = await prisma.journalEntry.count(); + const entryNumber = `JV-${dateStr}-${Date.now().toString().slice(-4)}-${String(count + 1).padStart(3, "0")}`; + + const journal = await prisma.journalEntry.create({ + data: { + entryNumber, + description, + reference: reference || null, + companyName: journalCompany, + lines: { + create: [ + { + accountId: debitAccountId, + type: "DEBIT", + amount: amt, + }, + { + accountId: creditAccountId, + type: "CREDIT", + amount: amt, + }, + ], + }, + }, + include: { + lines: { + include: { + account: true, + }, + }, + }, + }); + + if (debitAcc) { + const isNormalDebit = debitAcc.type === "ASSET" || debitAcc.type === "EXPENSE"; + await prisma.account.update({ + where: { id: debitAccountId }, + data: { + balance: isNormalDebit ? debitAcc.balance + amt : debitAcc.balance - amt, + }, + }); + } + + if (creditAcc) { + const isNormalCredit = + creditAcc.type === "LIABILITY" || + creditAcc.type === "EQUITY" || + creditAcc.type === "REVENUE"; + await prisma.account.update({ + where: { id: creditAccountId }, + data: { + balance: isNormalCredit ? creditAcc.balance + amt : creditAcc.balance - amt, + }, + }); + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "CREATE_JOURNAL_ENTRY", + module: "FINANCE", + description: `[${user.role}] Memposting jurnal transaksi ${entryNumber} senilai Rp ${amt.toLocaleString("id-ID")}: ${description}`, + }); + + const isDebitCash = debitAcc?.code.startsWith("10"); + const isCreditCash = creditAcc?.code.startsWith("10"); + + if (isDebitCash && !isCreditCash) { + await dispatchNotification({ + type: "MONEY_IN", + title: `Penerimaan Kas/Bank: ${entryNumber}`, + message: `Penerimaan uang sebesar Rp ${amt.toLocaleString("id-ID")} ke akun [${debitAcc?.code}] ${debitAcc?.name}. Uraian: ${description}`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT"], + }); + } else if (isCreditCash && !isDebitCash) { + await dispatchNotification({ + type: "MONEY_OUT", + title: `Pengeluaran Kas/Bank: ${entryNumber}`, + message: `Pengeluaran uang sebesar Rp ${amt.toLocaleString("id-ID")} dari akun [${creditAcc?.code}] ${creditAcc?.name}. Uraian: ${description}`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT"], + }); + } + + return NextResponse.json({ success: true, journal }); + } catch (error: any) { + console.error("Finance POST error:", error); + return NextResponse.json({ error: error.message }, { status: 500 }); + } +} diff --git a/src/app/api/inventory/route.ts b/src/app/api/inventory/route.ts new file mode 100644 index 0000000..fcf1b6b --- /dev/null +++ b/src/app/api/inventory/route.ts @@ -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>(); + const outSnByProduct = new Map>(); + const batchStockByProdCompany = new Map>(); + const manualStockByProdCompany = new Map>(); + + 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(); + const outSet = outSnByProduct.get(p.id) || new Set(); + 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 = {}; + 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 }); + } +} diff --git a/src/app/api/public/rma/route.ts b/src/app/api/public/rma/route.ts new file mode 100644 index 0000000..4b841c5 --- /dev/null +++ b/src/app/api/public/rma/route.ts @@ -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(); + +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 { + 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 { + 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 } + ); + } +} diff --git a/src/app/api/purchases/route.ts b/src/app/api/purchases/route.ts new file mode 100644 index 0000000..6161179 --- /dev/null +++ b/src/app/api/purchases/route.ts @@ -0,0 +1,1841 @@ +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 { getSavedCompanies, getCompanyAccount } from "@/lib/companies"; + +export async function GET() { + try { + const user = await getCurrentUser(); + if (!user) { + return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 }); + } + + if ( + !["ADMIN", "MANAGER", "PURCHASING", "ACCOUNTANT", "INVENTORY", "SALES"].includes(user.role) + ) { + return NextResponse.json( + { error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang modul pembelian.` }, + { status: 403 } + ); + } + + const [orders, suppliers, requisitions, products, warehouses, customers, batches, companies] = await Promise.all([ + prisma.purchaseOrder.findMany({ + include: { + supplier: true, + requisition: { + include: { customer: true }, + }, + batches: true, + items: { + include: { + product: true, + }, + }, + }, + orderBy: { createdAt: "desc" }, + }), + prisma.supplier.findMany({ + orderBy: { name: "asc" }, + }), + prisma.purchaseRequisition.findMany({ + include: { + customer: true, + items: { + include: { + product: true, + }, + }, + purchaseOrders: { + select: { id: true, poNumber: true, status: true }, + }, + }, + orderBy: { createdAt: "desc" }, + }), + prisma.product.findMany({ + select: { + id: true, + sku: true, + name: true, + isService: true, + unit: true, + purchasePrice: true, + sellingPrice: true, + }, + orderBy: { name: "asc" }, + }), + prisma.warehouse.findMany({ + orderBy: { name: "asc" }, + }), + prisma.customer.findMany({ + select: { + id: true, + code: true, + name: true, + company: true, + phone: true, + }, + orderBy: { company: "asc" }, + }), + prisma.purchaseBatch.findMany({ + include: { + product: true, + warehouse: true, + purchaseOrder: { + include: { supplier: true }, + }, + allocations: { + include: { + salesOrderItem: { + include: { + salesOrder: { + include: { customer: true }, + }, + }, + }, + }, + orderBy: { createdAt: "desc" }, + }, + }, + orderBy: { receivedAt: "desc" }, + }), + getSavedCompanies(), + ]); + + const canSeePurchasesMoney = ["ADMIN", "MANAGER", "PURCHASING", "ACCOUNTANT"].includes(user.role); + const canSeeSellingPrice = ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT"].includes(user.role); + const canSeeHpp = ["ADMIN", "MANAGER", "PURCHASING", "ACCOUNTANT", "SALES"].includes(user.role); + + const sanitizedOrders = canSeePurchasesMoney + ? orders.map((po) => ({ + ...po, + items: po.items.map((item) => ({ + ...item, + product: item.product + ? { + ...item.product, + purchasePrice: canSeeHpp ? item.product.purchasePrice : 0, + sellingPrice: canSeeSellingPrice ? item.product.sellingPrice : 0, + } + : item.product, + })), + })) + : orders.map((po) => ({ + ...po, + subtotalProducts: 0, + shippingCost: 0, + exportCost: 0, + shippingCostUsd: 0, + exportCostUsd: 0, + taxRate: 0, + taxAmount: 0, + totalAmount: 0, + totalAmountUsd: 0, + paidAmount: 0, + items: po.items.map((item) => ({ + ...item, + unitCost: 0, + unitCostUsd: 0, + subtotal: 0, + product: item.product + ? { + ...item.product, + purchasePrice: canSeeHpp ? item.product.purchasePrice : 0, + sellingPrice: canSeeSellingPrice ? item.product.sellingPrice : 0, + } + : item.product, + })), + })); + + const sanitizedProducts = products.map((p) => ({ + ...p, + purchasePrice: canSeeHpp ? p.purchasePrice : 0, + sellingPrice: canSeeSellingPrice ? p.sellingPrice : 0, + })); + + const sanitizedRequisitions = requisitions.map((reqItem) => ({ + ...reqItem, + items: reqItem.items.map((it) => ({ + ...it, + product: it.product + ? { + ...it.product, + purchasePrice: canSeeHpp ? it.product.purchasePrice : 0, + sellingPrice: canSeeSellingPrice ? it.product.sellingPrice : 0, + } + : it.product, + })), + })); + + const sanitizedBatches = batches.map((b) => ({ + ...b, + unitCost: canSeePurchasesMoney ? b.unitCost : 0, + product: b.product + ? { + ...b.product, + purchasePrice: canSeeHpp ? b.product.purchasePrice : 0, + sellingPrice: canSeeSellingPrice ? b.product.sellingPrice : 0, + } + : b.product, + purchaseOrder: b.purchaseOrder + ? { + ...b.purchaseOrder, + totalAmount: canSeePurchasesMoney ? b.purchaseOrder.totalAmount : 0, + paidAmount: canSeePurchasesMoney ? b.purchaseOrder.paidAmount : 0, + } + : b.purchaseOrder, + allocations: b.allocations.map((al) => ({ + ...al, + salesOrderItem: al.salesOrderItem + ? { + ...al.salesOrderItem, + unitPrice: canSeeSellingPrice ? al.salesOrderItem.unitPrice : 0, + subtotal: canSeeSellingPrice ? al.salesOrderItem.subtotal : 0, + salesOrder: al.salesOrderItem.salesOrder + ? { + ...al.salesOrderItem.salesOrder, + totalAmount: canSeeSellingPrice ? al.salesOrderItem.salesOrder.totalAmount : 0, + totalHpp: canSeeSellingPrice ? al.salesOrderItem.salesOrder.totalHpp : 0, + } + : al.salesOrderItem.salesOrder, + } + : al.salesOrderItem, + })), + })); + + return NextResponse.json({ + orders: sanitizedOrders, + suppliers, + requisitions: sanitizedRequisitions, + products: sanitizedProducts, + warehouses, + customers, + batches: sanitizedBatches, + companies, + }); + } catch (error: any) { + console.error("Purchases 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 }); + } + + const body = await req.json(); + + // ========================================================================= + // 0. ACTION: CREATE_CUSTOMER (Tambah PT / Pelanggan Baru dari Sales) + // ========================================================================= + if (body.action === "CREATE_CUSTOMER") { + if (!["ADMIN", "MANAGER", "SALES", "PURCHASING"].includes(user.role)) { + return NextResponse.json( + { error: `Akses ditolak: Peran ${user.role} tidak berwenang menambahkan pelanggan baru.` }, + { status: 403 } + ); + } + const { name, company, phone, email, address } = body; + const ptName = (company || name || "").trim(); + if (!ptName) { + return NextResponse.json({ error: "Nama PT atau nama pelanggan wajib diisi" }, { status: 400 }); + } + const count = await prisma.customer.count(); + const code = `CUST-${String(count + 1).padStart(3, "0")}`; + const customer = await prisma.customer.create({ + data: { + code, + name: (name || ptName).trim(), + company: ptName, + phone: phone?.trim() || null, + email: email?.trim() || null, + address: address?.trim() || null, + }, + }); + return NextResponse.json({ success: true, customer }); + } + + // ========================================================================= + // 1. ACTION: CREATE_REQUISITION (Pengajuan Pembelian Barang dari Sales / Gudang) + // ========================================================================= + if (body.action === "CREATE_REQUISITION") { + if (!["SALES", "INVENTORY", "PURCHASING", "MANAGER", "ADMIN"].includes(user.role)) { + return NextResponse.json( + { error: `Peran ${user.role} tidak memiliki akses membuat pengajuan pembelian.` }, + { status: 403 } + ); + } + + const { + customerId, + customerCompany, + purpose, + customerPoRef, + urgency = "NORMAL", + notes, + items, + companyName, + } = body; + + const cleanInternalCompany = (companyName || "").trim() || "PT EnterpriseCore Utama"; + + if (!purpose || !purpose.trim()) { + return NextResponse.json({ error: "Keperluan / alasan pengadaan wajib diisi" }, { status: 400 }); + } + + if (!items || !Array.isArray(items) || items.length === 0) { + return NextResponse.json({ error: "Minimal 1 item barang yang diajukan wajib dipilih" }, { status: 400 }); + } + + let finalCustomerId = customerId || null; + let finalCustomerCompany = (customerCompany || "").trim(); + + if (finalCustomerId) { + const custRecord = await prisma.customer.findUnique({ where: { id: finalCustomerId } }); + if (custRecord) { + finalCustomerCompany = custRecord.company || custRecord.name; + } + } + + const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); + const count = await prisma.purchaseRequisition.count(); + const reqNumber = `REQ-${dateStr}-${String(count + 1).padStart(4, "0")}`; + + const requisition = await prisma.purchaseRequisition.create({ + data: { + reqNumber, + salesUserId: user.id, + salesUserName: user.name, + customerId: finalCustomerId, + customerCompany: finalCustomerCompany || null, + customerPoRef: customerPoRef?.trim() || null, + purpose: purpose.trim(), + urgency: urgency || "NORMAL", + companyName: cleanInternalCompany, + notes: notes?.trim() || null, + status: "PENDING_PURCHASING", + items: { + create: items.map((it: any) => ({ + productId: it.productId, + requestedQty: Math.max(1, parseInt(it.quantity || it.requestedQty) || 1), + notes: it.notes?.trim() || null, + })), + }, + }, + include: { + customer: true, + items: { + include: { product: true }, + }, + }, + }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "CREATE_REQUISITION", + module: "PURCHASING", + description: `[${user.role}] Membuat Pengajuan Pengadaan Barang ${reqNumber} (PT: ${finalCustomerCompany || "-"}, "${purpose}")`, + metadata: { reqNumber, purpose, customerCompany: finalCustomerCompany, customerPoRef, urgency, itemCount: items.length }, + }); + + await dispatchNotification({ + type: "STOCK_IN", + title: `Pengajuan Pembelian Baru: ${reqNumber}`, + message: `${user.name} (${user.role}) mengajukan pengadaan barang ${reqNumber} untuk keperluan "${purpose}". Menunggu diproses Tim Purchasing.`, + targetRoles: ["ADMIN", "MANAGER", "PURCHASING"], + }); + + return NextResponse.json({ success: true, requisition }); + } + + // ========================================================================= + // 2. ACTION: CREATE_SUPPLIER (Tambah Pemasok Baru) + // ========================================================================= + if (body.action === "CREATE_SUPPLIER") { + if (!["PURCHASING", "MANAGER", "ADMIN"].includes(user.role)) { + return NextResponse.json( + { error: `Peran ${user.role} tidak memiliki wewenang menambah pemasok baru.` }, + { status: 403 } + ); + } + + const { name, contactPerson, email, phone, address } = body; + if (!name || !name.trim()) { + return NextResponse.json({ error: "Nama pemasok wajib diisi" }, { status: 400 }); + } + const sCount = await prisma.supplier.count(); + const code = `SUP-${String(sCount + 1).padStart(3, "0")}`; + const supplier = await prisma.supplier.create({ + data: { + code, + name: name.trim(), + contactPerson: contactPerson || null, + email: email || null, + phone: phone || null, + address: address || null, + }, + }); + return NextResponse.json({ success: true, supplier }); + } + + // ========================================================================= + // 3. ACTION: FINANCE_APPROVE (Persetujuan Anggaran Belanja oleh Finance) + // ========================================================================= + if (body.action === "FINANCE_APPROVE") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: "Hanya Finance (Akuntan), Manager, atau Admin yang dapat menyetujui anggaran PO." }, + { status: 403 } + ); + } + + const { orderId, financeNotes } = body; + const po = await prisma.purchaseOrder.findUnique({ + where: { id: orderId }, + include: { supplier: true, items: { include: { product: true } } }, + }); + if (!po) { + return NextResponse.json({ error: "PO tidak ditemukan" }, { status: 404 }); + } + + // Cek apakah seluruh item di PO ini adalah Layanan / Non-Fisik (misal Akses Internet) + const allItemsAreService = + po.items.length > 0 && po.items.every((it) => it.product?.isService === true); + + // Update HPP otomatis untuk item Layanan / Non-Fisik begitu PO di-approve Finance + const additionalCost = (po.shippingCost || 0) + (po.exportCost || 0); + const subtotalProducts = + po.subtotalProducts > 0 + ? po.subtotalProducts + : po.items.reduce((s, it) => s + it.subtotal, 0); + + const defaultWh = await prisma.warehouse.findFirst(); + const fallbackWhId = po.warehouseTargetId || defaultWh?.id || ""; + + for (const item of po.items) { + if (item.product?.isService) { + const itemRatio = + subtotalProducts > 0 ? item.subtotal / subtotalProducts : 1 / po.items.length; + const itemAdditionalCost = Math.round(additionalCost * itemRatio); + const landedUnitCost = Math.round( + (item.subtotal + itemAdditionalCost) / item.quantity + ); + await prisma.product.update({ + where: { id: item.productId }, + data: { purchasePrice: landedUnitCost }, + }); + + if (fallbackWhId) { + await prisma.purchaseBatch.create({ + data: { + purchaseOrderId: po.id, + poNumber: po.poNumber, + productId: item.productId, + warehouseId: fallbackWhId, + initialQty: item.quantity, + remainingQty: item.quantity, + unitCost: landedUnitCost, + }, + }); + } + } + } + + const updated = await prisma.purchaseOrder.update({ + where: { id: po.id }, + data: { + status: allItemsAreService ? "RECEIVED" : "ORDERED", + financeApprovedAt: new Date(), + financeApprovedBy: user.name, + financeNotes: financeNotes || null, + ...(allItemsAreService + ? { + warehouseReceivedAt: new Date(), + warehouseReceivedBy: "Otomatis (Layanan Non-Fisik)", + warehouseNotes: "Layanan / Akses Internet aktif otomatis tanpa fisik gudang", + } + : {}), + }, + }); + + const poCompany = po.companyName || "PT EnterpriseCore Utama"; + const apAcc = await getCompanyAccount("2001", poCompany); + if (apAcc) { + await prisma.account.update({ + where: { id: apAcc.id }, + data: { balance: { increment: po.totalAmount } }, + }); + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "FINANCE_APPROVE", + module: "PURCHASING", + description: `[${user.role}] Menyetujui (Approved) PO ${po.poNumber} senilai Rp ${po.totalAmount.toLocaleString("id-ID")}`, + metadata: { poNumber: po.poNumber, totalAmount: po.totalAmount, financeNotes }, + }); + + await dispatchNotification({ + type: "MONEY_OUT", + title: `PO Approved Finance: ${po.poNumber}`, + message: `Anggaran belanja untuk PO ${po.poNumber} (${po.supplier.name}) telah disetujui Finance (${user.name}). Diteruskan ke pemasok & siap diverifikasi saat tiba di gudang.`, + targetRoles: ["ADMIN", "MANAGER", "PURCHASING", "INVENTORY"], + }); + + return NextResponse.json({ success: true, order: updated }); + } + + // ========================================================================= + // 3B. ACTION: FINANCE_HOLD (Tahan / Hold Sementara Review PO oleh Finance) + // ========================================================================= + if (body.action === "FINANCE_HOLD") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: "Hanya Finance (Akuntan), Manager, atau Admin yang dapat melakukan Hold PO." }, + { status: 403 } + ); + } + + const { orderId, financeNotes } = body; + const po = await prisma.purchaseOrder.findUnique({ + where: { id: orderId }, + include: { supplier: true }, + }); + if (!po) { + return NextResponse.json({ error: "PO tidak ditemukan" }, { status: 404 }); + } + + const updated = await prisma.purchaseOrder.update({ + where: { id: po.id }, + data: { + status: "ON_HOLD", + financeApprovedAt: new Date(), + financeApprovedBy: user.name, + financeNotes: financeNotes || "Ditahan (Hold) oleh Finance untuk peninjauan ulang", + }, + }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "FINANCE_HOLD", + module: "PURCHASING", + description: `[${user.role}] Menahan (Hold) PO ${po.poNumber}. Catatan: ${financeNotes || "-"}`, + metadata: { poNumber: po.poNumber, financeNotes }, + }); + + return NextResponse.json({ success: true, order: updated }); + } + + // ========================================================================= + // 4. ACTION: FINANCE_REJECT (Tolak Anggaran Belanja oleh Finance) + // ========================================================================= + if (body.action === "FINANCE_REJECT") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: "Hanya Finance (Akuntan), Manager, atau Admin yang dapat menolak PO." }, + { status: 403 } + ); + } + + const { orderId, financeNotes } = body; + const po = await prisma.purchaseOrder.findUnique({ where: { id: orderId } }); + if (!po) { + return NextResponse.json({ error: "PO tidak ditemukan" }, { status: 404 }); + } + + const updated = await prisma.purchaseOrder.update({ + where: { id: po.id }, + data: { + status: "REJECTED", + financeApprovedAt: new Date(), + financeApprovedBy: user.name, + financeNotes: financeNotes || "Ditolak (Rejected) oleh Finance", + }, + }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "FINANCE_REJECT", + module: "PURCHASING", + description: `[${user.role}] Menolak (Reject) anggaran PO ${po.poNumber}. Catatan: ${financeNotes || "-"}`, + }); + + return NextResponse.json({ success: true, order: updated }); + } + + // ========================================================================= + // 5. STANDARD ACTION: PEMBELIAN OLEH PURCHASING (Create Purchase Order) + // ========================================================================= + if (!["ADMIN", "MANAGER", "PURCHASING"].includes(user.role)) { + return NextResponse.json( + { + error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang untuk menerbitkan Purchase Order.`, + }, + { status: 403 } + ); + } + + const { + supplierId, + requisitionId, + notes, + items, + poNumber: customPoNumber, + currency: inputCurrency, + exchangeRate: inputExchangeRate, + warehouseId, + autoReceive = false, + shippingCost: inputShippingCost = 0, + exportCost: inputExportCost = 0, + shippingCostUsd: inputShippingCostUsd, + exportCostUsd: inputExportCostUsd, + logisticsMode: inputLogisticsMode = "DETAILED", + forwardingCompany: inputForwardingCompany, + allInCost: inputAllInCost, + companyName: inputCompanyName, + } = body; + + let cleanPoCompany = (inputCompanyName || "").trim(); + if (!cleanPoCompany && requisitionId) { + const reqRecord = await prisma.purchaseRequisition.findUnique({ where: { id: requisitionId } }); + if (reqRecord?.companyName) { + cleanPoCompany = reqRecord.companyName; + } + } + if (!cleanPoCompany) { + cleanPoCompany = "PT EnterpriseCore Utama"; + } + + if (!supplierId || !items || !items.length) { + return NextResponse.json( + { error: "Pemasok dan minimal 1 item barang harus diisi" }, + { status: 400 } + ); + } + + const currency = (inputCurrency || "IDR").toUpperCase() === "USD" ? "USD" : "IDR"; + const exchangeRate = currency === "USD" ? Math.max(1, parseFloat(inputExchangeRate) || 16200) : 1; + + let poNumber = (customPoNumber || "").trim(); + if (poNumber) { + const existingPo = await prisma.purchaseOrder.findUnique({ where: { poNumber } }); + if (existingPo) { + return NextResponse.json( + { error: `Nomor PO "${poNumber}" sudah digunakan. Gunakan nomor PO lain.` }, + { status: 400 } + ); + } + } else { + const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); + const count = await prisma.purchaseOrder.count(); + poNumber = `PO-${dateStr}-${String(count + 1).padStart(4, "0")}`; + } + + let subtotalProducts = 0; // IDR murni produk + let subtotalProductsUsd = 0; // USD murni produk + const poItemsData = []; + + for (const item of items) { + const product = await prisma.product.findUnique({ + where: { id: item.productId }, + }); + + if (!product) { + return NextResponse.json( + { error: `Produk ID ${item.productId} tidak ditemukan` }, + { status: 404 } + ); + } + + const qty = parseInt(item.quantity); + if (isNaN(qty) || qty <= 0) { + return NextResponse.json( + { error: `Kuantitas produk ${product.name} harus lebih dari 0` }, + { status: 400 } + ); + } + + let unitCost = 0; + let unitCostUsd: number | null = null; + let subtotal = 0; + + if (currency === "USD") { + unitCostUsd = Math.max(0, parseFloat(item.unitCostUsd !== undefined ? item.unitCostUsd : item.unitCost) || 0); + unitCost = Math.round(unitCostUsd * exchangeRate); + const subtotalUsd = qty * unitCostUsd; + subtotal = qty * unitCost; + subtotalProductsUsd += subtotalUsd; + subtotalProducts += subtotal; + } else { + unitCost = Math.max(0, parseFloat(item.unitCost) || product.purchasePrice); + subtotal = qty * unitCost; + subtotalProducts += subtotal; + } + + poItemsData.push({ + productId: product.id, + quantity: qty, + unitCostUsd: currency === "USD" ? unitCostUsd : null, + unitCost, + subtotal, + }); + } + + // Detail Biaya Ongkir, Ekspor & PPN Masukan: HANYA Finance (ACCOUNTANT), Manager, atau Admin yang berwenang mengisi! + const canSetPoLogisticsAndTax = ["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role); + + const logisticsMode = + canSetPoLogisticsAndTax && inputLogisticsMode === "ASSISTED_ALL_IN" + ? "ASSISTED_ALL_IN" + : "DETAILED"; + const forwardingCompany = + canSetPoLogisticsAndTax && logisticsMode === "ASSISTED_ALL_IN" && inputForwardingCompany + ? String(inputForwardingCompany).trim() + : null; + + let shippingCost = 0; + let shippingCostUsd: number | null = null; + let exportCost = 0; + + if (canSetPoLogisticsAndTax) { + if (logisticsMode === "ASSISTED_ALL_IN") { + // Mode Dibantu Perusahaan Lain (All-In: Gabungan Ongkir + Pajak Masuk dijadikan satu tagihan Rupiah) + shippingCost = 0; + shippingCostUsd = null; + exportCost = Math.max( + 0, + parseFloat(inputAllInCost !== undefined ? inputAllInCost : inputExportCost) || 0 + ); + } else { + // Mode Rincian Terpisah (Mandiri) + exportCost = Math.max(0, parseFloat(inputExportCost) || 0); + if (currency === "USD") { + shippingCostUsd = Math.max( + 0, + parseFloat(inputShippingCostUsd !== undefined ? inputShippingCostUsd : inputShippingCost) || 0 + ); + shippingCost = Math.round(shippingCostUsd * exchangeRate); + } else { + shippingCost = Math.max(0, parseFloat(inputShippingCost) || 0); + } + } + } + + const includeTax = canSetPoLogisticsAndTax && Boolean(body.includeTax); + const taxRate = includeTax ? Math.max(0, parseFloat(body.taxRate) || 11) : 0; + const taxAmount = includeTax ? Math.round((subtotalProducts * taxRate) / 100) : 0; + + const totalAmount = subtotalProducts + shippingCost + exportCost + taxAmount; + // Nilai tagihan vendor luar negeri dalam USD: Barang + Ongkir International (jika tidak All-In lokal) + const totalAmountUsd = + currency === "USD" ? subtotalProductsUsd + (shippingCostUsd || 0) : null; + + // Default Alur: PO dibuat Purchasing -> Menunggu Approve Finance (PENDING_FINANCE) + const shouldAutoReceive = Boolean(autoReceive); + const initialStatus = shouldAutoReceive ? "RECEIVED" : "PENDING_FINANCE"; + + let targetWhId = warehouseId; + if (!targetWhId) { + const firstWh = await prisma.warehouse.findFirst({ orderBy: { code: "asc" } }); + targetWhId = firstWh?.id; + } + + const po = await prisma.purchaseOrder.create({ + data: { + poNumber, + supplierId, + requisitionId: requisitionId || null, + warehouseTargetId: targetWhId || null, + companyName: cleanPoCompany, + currency, + exchangeRate, + logisticsMode, + forwardingCompany, + subtotalProducts, + shippingCost, + exportCost, + shippingCostUsd, + exportCostUsd: null, + taxRate, + taxAmount, + includeTax, + totalAmountUsd, + totalAmount, + notes, + status: initialStatus, + items: { + create: poItemsData, + }, + }, + include: { + supplier: true, + requisition: true, + items: { + include: { + product: true, + }, + }, + }, + }); + + // Jika PO dibuat dari Pengajuan Sales, update status pengajuan menjadi "PROCESSED_PO" + if (requisitionId) { + await prisma.purchaseRequisition.update({ + where: { id: requisitionId }, + data: { status: "PROCESSED_PO" }, + }); + } + + // Jika auto-receive aktif langsung masukkan ke gudang & daftarkan batch PO FIFO + if (shouldAutoReceive && targetWhId) { + const additionalCost = shippingCost + exportCost; + for (const item of po.items) { + const itemRatio = subtotalProducts > 0 ? item.subtotal / subtotalProducts : 1 / po.items.length; + const itemAdditionalCost = Math.round(additionalCost * itemRatio); + const landedUnitCost = Math.round((item.subtotal + itemAdditionalCost) / item.quantity); + + // 1. Moving Average HPP dengan landed cost + const currentProduct = await prisma.product.findUnique({ + where: { id: item.productId }, + include: { stockItems: true }, + }); + + if (currentProduct) { + const totalOldStock = currentProduct.stockItems.reduce((acc, curr) => acc + curr.quantity, 0); + const oldHpp = currentProduct.purchasePrice || 0; + const incomingQty = item.quantity; + const incomingCost = landedUnitCost; + + let newAverageHpp = incomingCost; + if (totalOldStock > 0 && oldHpp > 0) { + newAverageHpp = Math.round( + ((totalOldStock * oldHpp) + (incomingQty * incomingCost)) / (totalOldStock + incomingQty) + ); + } else { + newAverageHpp = incomingCost; + } + + await prisma.product.update({ + where: { id: item.productId }, + data: { purchasePrice: newAverageHpp }, + }); + } + + // 2. Buat Record Batch PO (FIFO) + await prisma.purchaseBatch.create({ + data: { + purchaseOrderId: po.id, + poNumber: po.poNumber, + productId: item.productId, + warehouseId: targetWhId, + initialQty: item.quantity, + remainingQty: item.quantity, + unitCost: landedUnitCost, + receivedAt: new Date(), + }, + }); + + // 3. Update / Create StockItem + const stock = await prisma.stockItem.findUnique({ + where: { + productId_warehouseId: { + productId: item.productId, + warehouseId: targetWhId, + }, + }, + }); + + if (stock) { + await prisma.stockItem.update({ + where: { id: stock.id }, + data: { quantity: stock.quantity + item.quantity }, + }); + } else { + await prisma.stockItem.create({ + data: { + productId: item.productId, + warehouseId: targetWhId, + quantity: item.quantity, + }, + }); + } + + // 4. Catat Mutasi Stok Masuk (IN) dengan info Batch + await prisma.stockMovement.create({ + data: { + productId: item.productId, + warehouseId: targetWhId, + type: "IN", + quantity: item.quantity, + referenceType: "PURCHASE_ORDER", + referenceId: po.poNumber, + notes: `Penerimaan otomatis PO ${po.poNumber} [Batch FIFO: ${item.quantity} pcs @ HPP Rp ${landedUnitCost.toLocaleString("id-ID")}${additionalCost > 0 ? ` (Inc. Ongkir & Ekspor)` : ""}]`, + }, + }); + } + + const autoPoCompany = po.companyName || "PT EnterpriseCore Utama"; + const autoInvAcc = await getCompanyAccount("1201", autoPoCompany); + const autoTaxAcc = await getCompanyAccount("1301", autoPoCompany); + const autoApAcc = await getCompanyAccount("2001", autoPoCompany); + const autoInvValue = Math.max(0, totalAmount - taxAmount); + + if (autoInvAcc && autoInvValue > 0) { + await prisma.account.update({ + where: { id: autoInvAcc.id }, + data: { balance: { increment: autoInvValue } }, + }); + } + if (autoTaxAcc && taxAmount > 0) { + await prisma.account.update({ + where: { id: autoTaxAcc.id }, + data: { balance: { increment: taxAmount } }, + }); + } + if (autoApAcc && totalAmount > 0) { + await prisma.account.update({ + where: { id: autoApAcc.id }, + data: { balance: { increment: totalAmount } }, + }); + } + } + + const usdInfo = currency === "USD" && totalAmountUsd !== null ? ` ($${totalAmountUsd.toLocaleString("en-US", { minimumFractionDigits: 2 })} @ Kurs Rp ${exchangeRate.toLocaleString("id-ID")})` : ""; + await logAudit({ + userId: user.id, + userName: user.name, + action: "CREATE_PURCHASE_ORDER", + module: "PURCHASING", + description: `[${user.role}] Menerbitkan PO ${poNumber} (${initialStatus}) senilai Rp ${totalAmount.toLocaleString("id-ID")}${usdInfo}`, + metadata: { poNumber, totalAmount, supplierId, status: initialStatus, requisitionId }, + }); + + // Kirim notifikasi ke Finance bahwa ada PO baru yang membutuhkan approval anggaran + if (!shouldAutoReceive) { + await dispatchNotification({ + type: "MONEY_OUT", + title: `PO Baru Menunggu Approve Finance: ${poNumber}`, + message: `Purchasing (${user.name}) menerbitkan PO ${poNumber} senilai Rp ${totalAmount.toLocaleString("id-ID")}${usdInfo}. Memerlukan persetujuan anggaran dari Finance.`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT"], + }); + } + + return NextResponse.json({ success: true, order: po }); + } catch (error: any) { + console.error("Purchases 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 }); + } + + const body = await req.json(); + + // ========================================================================= + // 1. APPROVAL ANGGARAN PO OLEH FINANCE + // ========================================================================= + if (body.action === "FINANCE_APPROVE" || body.action === "APPROVE_PO") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: "Hanya Finance (Akuntan), Manager, atau Admin yang dapat menyetujui anggaran PO." }, + { status: 403 } + ); + } + + const po = await prisma.purchaseOrder.findUnique({ + where: { id: body.orderId }, + include: { supplier: true }, + }); + if (!po) { + return NextResponse.json({ error: "PO tidak ditemukan" }, { status: 404 }); + } + + const updated = await prisma.purchaseOrder.update({ + where: { id: po.id }, + data: { + status: "ORDERED", + financeApprovedAt: new Date(), + financeApprovedBy: user.name, + financeNotes: body.financeNotes || null, + }, + }); + + await prisma.account.updateMany({ + where: { code: "2001" }, + data: { balance: { increment: po.totalAmount } }, + }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "FINANCE_APPROVE", + module: "PURCHASING", + description: `[${user.role}] Menyetujui anggaran PO ${po.poNumber} senilai Rp ${po.totalAmount.toLocaleString("id-ID")}`, + metadata: { poNumber: po.poNumber, totalAmount: po.totalAmount }, + }); + + await dispatchNotification({ + type: "MONEY_OUT", + title: `PO Disetujui Finance: ${po.poNumber}`, + message: `Anggaran belanja untuk PO ${po.poNumber} (${po.supplier.name}) telah disetujui Finance (${user.name}). Siap dikirim ke pemasok dan menunggu barang tiba di gudang.`, + targetRoles: ["ADMIN", "MANAGER", "PURCHASING", "INVENTORY"], + }); + + return NextResponse.json({ success: true, order: updated }); + } + + // ========================================================================= + // 2. APPROVAL & PENERIMAAN BARANG DATANG DARI DISTRIBUTOR OLEH GUDANG / ADMIN + // ========================================================================= + if (body.action === "RECEIVE_GOODS" || !body.action) { + if (!["ADMIN", "MANAGER", "INVENTORY", "PURCHASING"].includes(user.role)) { + return NextResponse.json( + { + error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang verifikasi & approve penerimaan barang gudang.`, + }, + { status: 403 } + ); + } + + const { orderId, warehouseId, warehouseNotes, itemSerialNumbers, serialNumbers } = body; + + const po = await prisma.purchaseOrder.findUnique({ + where: { id: orderId }, + include: { items: true, supplier: true }, + }); + + if (!po) { + return NextResponse.json({ error: "PO tidak ditemukan" }, { status: 404 }); + } + + if ( + po.status === "PENDING_FINANCE" || + po.status === "ON_HOLD" || + po.status === "REJECTED" || + po.status === "CANCELLED" + ) { + return NextResponse.json( + { error: `PO berstatus ${po.status}. Pembelian wajib disetujui (Approved) oleh Finance terlebih dahulu.` }, + { status: 400 } + ); + } + + if (po.status === "RECEIVED" || po.status === "COMPLETED") { + return NextResponse.json( + { error: "Barang untuk PO ini sudah diterima dan diverifikasi di gudang sebelumnya." }, + { status: 400 } + ); + } + + const defaultWh = await prisma.warehouse.findFirst(); + const finalWarehouseId = warehouseId || po.warehouseTargetId || defaultWh?.id; + if (!finalWarehouseId) { + return NextResponse.json( + { error: "Lokasi gudang penerimaan barang harus ditentukan." }, + { status: 400 } + ); + } + + const additionalCost = (po.shippingCost || 0) + (po.exportCost || 0); + const subtotalProducts = po.subtotalProducts > 0 ? po.subtotalProducts : po.items.reduce((s, it) => s + it.subtotal, 0); + + for (const item of po.items) { + // Alokasi proporsional ongkir & biaya ekspor ke HPP tiap unit barang + const itemRatio = subtotalProducts > 0 ? item.subtotal / subtotalProducts : 1 / po.items.length; + const itemAdditionalCost = Math.round(additionalCost * itemRatio); + const landedUnitCost = Math.round((item.subtotal + itemAdditionalCost) / item.quantity); + + // 1. Moving Average HPP Calculation dengan Landed Cost + const currentProduct = await prisma.product.findUnique({ + where: { id: item.productId }, + include: { stockItems: true }, + }); + + if (currentProduct) { + const totalOldStock = currentProduct.stockItems.reduce((acc, curr) => acc + curr.quantity, 0); + const oldHpp = currentProduct.purchasePrice || 0; + const incomingQty = item.quantity; + const incomingCost = landedUnitCost; + + let newAverageHpp = incomingCost; + if (totalOldStock > 0 && oldHpp > 0) { + newAverageHpp = Math.round( + ((totalOldStock * oldHpp) + (incomingQty * incomingCost)) / (totalOldStock + incomingQty) + ); + } else { + newAverageHpp = incomingCost; + } + + await prisma.product.update({ + where: { id: currentProduct.id }, + data: { purchasePrice: newAverageHpp }, + }); + } + + const sn = (itemSerialNumbers && itemSerialNumbers[item.id]) || serialNumbers || null; + const cleanSn = sn ? String(sn).trim() : null; + + if (cleanSn) { + await prisma.purchaseOrderItem.update({ + where: { id: item.id }, + data: { serialNumbers: cleanSn }, + }); + } + + // 2. Buat Record Batch PO (FIFO) untuk pelacakan penjualan + await prisma.purchaseBatch.create({ + data: { + purchaseOrderId: po.id, + poNumber: po.poNumber, + productId: item.productId, + warehouseId: finalWarehouseId, + initialQty: item.quantity, + remainingQty: item.quantity, + unitCost: landedUnitCost, + serialNumbers: cleanSn, + receivedAt: new Date(), + }, + }); + + // 3. Tambah stok fisik gudang + let stockItem = await prisma.stockItem.findUnique({ + where: { + productId_warehouseId: { productId: item.productId, warehouseId: finalWarehouseId }, + }, + }); + + if (!stockItem) { + stockItem = await prisma.stockItem.create({ + data: { + productId: item.productId, + warehouseId: finalWarehouseId, + quantity: 0, + }, + }); + } + + await prisma.stockItem.update({ + where: { id: stockItem.id }, + data: { quantity: stockItem.quantity + item.quantity }, + }); + + // 4. Catat Mutasi Stok Masuk (IN) dengan referensi Batch PO + await prisma.stockMovement.create({ + data: { + productId: item.productId, + warehouseId: finalWarehouseId, + type: "IN", + quantity: item.quantity, + referenceType: "PURCHASE_ORDER", + referenceId: po.poNumber, + companyName: po.companyName || "PT EnterpriseCore Utama", + serialNumbers: cleanSn, + notes: `Penerimaan & Verifikasi Gudang PO ${po.poNumber} (${po.companyName || "PT Utama"}) [Batch FIFO: ${item.quantity} pcs @ HPP Rp ${landedUnitCost.toLocaleString("id-ID")}${additionalCost > 0 ? ` (Inc. Ongkir & Ekspor)` : ""}]${cleanSn ? ` (SN: ${cleanSn})` : ""}`, + }, + }); + } + + const updated = await prisma.purchaseOrder.update({ + where: { id: orderId }, + data: { + status: "RECEIVED", + warehouseReceivedAt: new Date(), + warehouseReceivedBy: user.name, + warehouseNotes: warehouseNotes || null, + warehouseTargetId: finalWarehouseId, + }, + }); + + // 4. Pembukuan otomatis: Tambah Persediaan (1201), PPN Masukan (1301), dan Hutang (2001) untuk PT terkait + const poCompany = po.companyName || "PT EnterpriseCore Utama"; + const invAcc = await getCompanyAccount("1201", poCompany); + const taxInAcc = await getCompanyAccount("1301", poCompany); + const apAcc = await getCompanyAccount("2001", poCompany); + + const poTaxVal = po.includeTax && po.taxAmount > 0 ? po.taxAmount : 0; + const poInvVal = Math.max(0, po.totalAmount - poTaxVal); + + if (invAcc && poInvVal > 0) { + await prisma.account.update({ + where: { id: invAcc.id }, + data: { balance: { increment: poInvVal } }, + }); + } + if (taxInAcc && poTaxVal > 0) { + await prisma.account.update({ + where: { id: taxInAcc.id }, + data: { balance: { increment: poTaxVal } }, + }); + } + if (apAcc && po.totalAmount > 0) { + await prisma.account.update({ + where: { id: apAcc.id }, + data: { balance: { increment: po.totalAmount } }, + }); + } + + if (invAcc && apAcc && po.totalAmount > 0) { + const jCount = await prisma.journalEntry.count(); + const journalLines: { accountId: string; type: string; amount: number }[] = []; + if (poInvVal > 0) { + journalLines.push({ accountId: invAcc.id, type: "DEBIT", amount: poInvVal }); + } + if (taxInAcc && poTaxVal > 0) { + journalLines.push({ accountId: taxInAcc.id, type: "DEBIT", amount: poTaxVal }); + } else if (poTaxVal > 0) { + // Fallback jika akun 1301 belum ada + journalLines.push({ accountId: invAcc.id, type: "DEBIT", amount: poTaxVal }); + } + journalLines.push({ accountId: apAcc.id, type: "CREDIT", amount: po.totalAmount }); + + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-PO-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`, + description: `Penerimaan Barang PO ${po.poNumber} (${poCompany}) dari ${po.supplier.name}${poTaxVal > 0 ? ` (Inc. PPN Masukan ${po.taxRate}%)` : ""}`, + reference: po.poNumber, + companyName: poCompany, + lines: { + create: journalLines, + }, + }, + }); + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "RECEIVE_GOODS", + module: "PURCHASING", + description: `[${user.role}] Memverifikasi dan menyetujui penerimaan barang PO ${po.poNumber} masuk ke inventaris gudang`, + }); + + await dispatchNotification({ + type: "STOCK_IN", + title: `Barang Telah Tiba di Gudang: ${po.poNumber}`, + message: `Pengiriman barang PO ${po.poNumber} (${po.supplier.name}) telah tiba dan disetujui oleh Petugas Gudang/Admin (${user.name}). Stok telah tersinkronisasi.`, + targetRoles: ["ADMIN", "MANAGER", "INVENTORY", "PURCHASING", "SALES", "ACCOUNTANT"], + }); + + return NextResponse.json({ success: true, order: updated }); + } + + // ========================================================================= + // 3. KONFIRMASI PAYMENT PO (PAID / UNPAID) OLEH FINANCE + // ========================================================================= + if (body.action === "PAY_PO" || body.action === "CONFIRM_PAYMENT") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: "Hanya Finance (Akuntan), Manager, atau Admin yang dapat mengonfirmasi status pembayaran PO." }, + { status: 403 } + ); + } + + const { orderId, paidAmount: inputPaidAmount, paymentNotes, paymentStatus: manualStatus } = body; + const po = await prisma.purchaseOrder.findUnique({ + where: { id: orderId || body.orderId }, + include: { supplier: true }, + }); + if (!po) { + return NextResponse.json({ error: "PO tidak ditemukan" }, { status: 404 }); + } + + const totalPO = po.totalAmount; + const prevPaid = po.paidAmount || (po.paymentStatus === "PAID" ? totalPO : 0); + + let finalPaid = prevPaid; + if (inputPaidAmount !== undefined && inputPaidAmount !== "") { + finalPaid = Math.max(0, parseFloat(inputPaidAmount) || 0); + } else if (manualStatus === "PAID") { + finalPaid = totalPO; + } else if (manualStatus === "UNPAID") { + finalPaid = 0; + } + + let finalPaymentStatus = "UNPAID"; + if (finalPaid >= totalPO && totalPO > 0) { + finalPaid = totalPO; + finalPaymentStatus = "PAID"; + } else if (finalPaid > 0) { + finalPaymentStatus = "PARTIAL"; // DP / Pembayaran Termin + } else { + finalPaid = 0; + finalPaymentStatus = "UNPAID"; + } + + const delta = finalPaid - prevPaid; + + const updated = await prisma.purchaseOrder.update({ + where: { id: po.id }, + data: { + paidAmount: finalPaid, + paymentStatus: finalPaymentStatus, + paidAt: finalPaid > 0 ? (po.paidAt || new Date()) : null, + paidBy: user.name, + paymentNotes: paymentNotes !== undefined ? String(paymentNotes).trim() : po.paymentNotes, + ...(finalPaymentStatus === "PAID" && po.status === "RECEIVED" + ? { status: "COMPLETED" } + : finalPaymentStatus !== "PAID" && po.status === "COMPLETED" + ? { status: "RECEIVED" } + : {}), + }, + }); + + const poCompany = po.companyName || "PT EnterpriseCore Utama"; + const apAcc = await getCompanyAccount("2001", poCompany); + const bankAcc = await getCompanyAccount("1002", poCompany); + + if (delta !== 0) { + if (delta > 0) { + // Bayar uang muka (DP) atau pelunasan: kurangi utang AP & kurangi kas bank + if (apAcc) { + await prisma.account.update({ + where: { id: apAcc.id }, + data: { balance: { decrement: delta } }, + }); + } + if (bankAcc) { + await prisma.account.update({ + where: { id: bankAcc.id }, + data: { balance: { decrement: delta } }, + }); + } + if (apAcc && bankAcc) { + const jCount = await prisma.journalEntry.count(); + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-PAY-PO-${String(jCount + 1).padStart(4, "0")}`, + description: `${finalPaymentStatus === "PARTIAL" ? "Pembayaran Uang Muka (DP) / Termin" : "Pelunasan"} PO ${po.poNumber} (${poCompany}) kepada ${po.supplier.name}`, + reference: po.poNumber, + companyName: poCompany, + lines: { + create: [ + { accountId: apAcc.id, type: "DEBIT", amount: delta }, + { accountId: bankAcc.id, type: "CREDIT", amount: delta }, + ], + }, + }, + }); + } + } else { + // Pengembalian / koreksi penurunan nominal bayar + const absDelta = Math.abs(delta); + if (apAcc) { + await prisma.account.update({ + where: { id: apAcc.id }, + data: { balance: { increment: absDelta } }, + }); + } + if (bankAcc) { + await prisma.account.update({ + where: { id: bankAcc.id }, + data: { balance: { increment: absDelta } }, + }); + } + } + } + + const remainingDebt = Math.max(0, totalPO - finalPaid); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "CONFIRM_PAYMENT", + module: "PURCHASING", + description: `[${user.role}] Pembayaran PO ${po.poNumber} (${finalPaymentStatus}): Bayar Rp ${finalPaid.toLocaleString("id-ID")} (Sisa Hutang: Rp ${remainingDebt.toLocaleString("id-ID")}). Catatan: ${paymentNotes || "-"}`, + metadata: { + poNumber: po.poNumber, + paymentStatus: finalPaymentStatus, + paidAmount: finalPaid, + remainingDebt, + paymentNotes: paymentNotes || body.paymentNotes, + }, + }); + + await dispatchNotification({ + type: "MONEY_OUT", + title: `Pembayaran PO (${finalPaymentStatus === "PARTIAL" ? "DP" : finalPaymentStatus}): ${po.poNumber}`, + message: `Pembayaran PO ${po.poNumber} (${po.supplier.name}) sebesar Rp ${finalPaid.toLocaleString("id-ID")} (${finalPaymentStatus === "PARTIAL" ? `DP / Kurang Bayar, Sisa Hutang: Rp ${remainingDebt.toLocaleString("id-ID")}` : "Lunas"}) telah dikonfirmasi oleh Finance (${user.name}).`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "PURCHASING"], + }); + + return NextResponse.json({ success: true, order: updated }); + } + + // ========================================================================= + // 4. UPDATE BIAYA FORWARDER, PAJAK MASUK & ONGKIR PO BELAKANGAN (KHUSUS FINANCE) + // ========================================================================= + if (body.action === "UPDATE_PO_LOGISTICS") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: `Akses ditolak: Hanya Finance (Akuntan), Manager, atau Admin yang berwenang menginput biaya ongkir, forwarder, dan pajak PO.` }, + { status: 403 } + ); + } + + const { + orderId, + logisticsMode: inputMode, + forwardingCompany, + allInCost, + shippingCost: inputShippingCost, + shippingCostUsd: inputShippingCostUsd, + exportCost: inputExportCost, + includeTax: inputIncludeTax, + taxRate: inputTaxRate, + notes: inputNotes, + } = body; + + if (!orderId) { + return NextResponse.json({ error: "ID Purchase Order wajib disertakan" }, { status: 400 }); + } + + const po = await prisma.purchaseOrder.findUnique({ + where: { id: orderId }, + include: { + supplier: true, + items: true, + batches: true, + }, + }); + + if (!po) { + return NextResponse.json({ error: "Purchase Order tidak ditemukan" }, { status: 404 }); + } + + const mode = inputMode === "ASSISTED_ALL_IN" ? "ASSISTED_ALL_IN" : "DETAILED"; + const cleanForwarder = + mode === "ASSISTED_ALL_IN" && forwardingCompany + ? String(forwardingCompany).trim() + : mode === "ASSISTED_ALL_IN" + ? po.forwardingCompany + : null; + + let newShippingCost = 0; + let newExportCost = 0; + let newShippingCostUsd: number | null = null; + + if (mode === "ASSISTED_ALL_IN") { + const cleanAllIn = Math.max(0, parseFloat(allInCost) || 0); + newShippingCost = 0; + newExportCost = cleanAllIn; + newShippingCostUsd = null; + } else { + if (po.currency === "USD" && inputShippingCostUsd !== undefined && inputShippingCostUsd !== null && inputShippingCostUsd !== "") { + newShippingCostUsd = Math.max(0, parseFloat(inputShippingCostUsd) || 0); + newShippingCost = Math.round(newShippingCostUsd * (po.exchangeRate || 1)); + } else { + newShippingCost = Math.max(0, parseFloat(inputShippingCost) || 0); + newShippingCostUsd = po.currency === "USD" && po.exchangeRate > 0 ? Number((newShippingCost / po.exchangeRate).toFixed(2)) : null; + } + newExportCost = Math.max(0, parseFloat(inputExportCost) || 0); + } + + const itemsSubtotal = po.subtotalProducts > 0 + ? po.subtotalProducts + : po.items.reduce((sum, it) => sum + it.subtotal, 0); + const oldAdditionalCost = (po.shippingCost || 0) + (po.exportCost || 0); + const newAdditionalCost = newShippingCost + newExportCost; + const deltaLogisticsCost = newAdditionalCost - oldAdditionalCost; + + const oldTaxVal = po.includeTax ? (po.taxAmount || 0) : 0; + const newIncludeTax = inputIncludeTax !== undefined ? Boolean(inputIncludeTax) : po.includeTax; + const newTaxRate = newIncludeTax + ? Math.max(0, parseFloat(inputTaxRate !== undefined ? inputTaxRate : String(po.taxRate || 11)) || 11) + : 0; + const newTaxVal = newIncludeTax ? Math.round((itemsSubtotal * newTaxRate) / 100) : 0; + const deltaTax = newTaxVal - oldTaxVal; + + const newTotalAmount = itemsSubtotal + newAdditionalCost + newTaxVal; + const deltaCost = newTotalAmount - po.totalAmount; + + // Hitung ulang total USD bila mata uang USD + let newTotalAmountUsd = po.totalAmountUsd; + if (po.currency === "USD") { + const itemsSubtotalUsd = po.items.reduce( + (sum, it) => sum + (it.unitCostUsd || 0) * it.quantity, + 0 + ); + newTotalAmountUsd = + mode === "ASSISTED_ALL_IN" + ? itemsSubtotalUsd + : itemsSubtotalUsd + (newShippingCostUsd || 0); + } + + // Sesuaikan status pembayaran jika total PO berubah setelah sebelumnya sudah dibayar/DP + const currentPaid = po.paidAmount || (po.paymentStatus === "PAID" ? po.totalAmount : 0); + let nextPaymentStatus = po.paymentStatus; + if (currentPaid >= newTotalAmount && newTotalAmount > 0) { + nextPaymentStatus = "PAID"; + } else if (currentPaid > 0 && currentPaid < newTotalAmount) { + nextPaymentStatus = "PARTIAL"; + } else { + nextPaymentStatus = "UNPAID"; + } + + const updatedPo = await prisma.purchaseOrder.update({ + where: { id: orderId }, + data: { + logisticsMode: mode, + forwardingCompany: cleanForwarder, + shippingCost: newShippingCost, + exportCost: newExportCost, + shippingCostUsd: newShippingCostUsd, + includeTax: newIncludeTax, + taxRate: newTaxRate, + taxAmount: newTaxVal, + totalAmountUsd: newTotalAmountUsd, + totalAmount: newTotalAmount, + paymentStatus: nextPaymentStatus, + ...(inputNotes !== undefined && { notes: String(inputNotes).trim() || null }), + }, + include: { supplier: true, items: { include: { product: true } }, batches: true }, + }); + + // Jika PO sudah RECEIVED / sudah masuk batch gudang, perbarui Landed Cost (HPP) Batch & Produk + Jurnal Akuntansi! + if ((po.status === "RECEIVED" || po.batches.length > 0) && (deltaLogisticsCost !== 0 || deltaTax !== 0)) { + if (deltaLogisticsCost !== 0) { + for (const item of po.items) { + const itemRatio = itemsSubtotal > 0 ? item.subtotal / itemsSubtotal : 1 / Math.max(1, po.items.length); + const oldItemExtra = Math.round(oldAdditionalCost * itemRatio); + const newItemExtra = Math.round(newAdditionalCost * itemRatio); + const oldUnitCost = Math.round((item.subtotal + oldItemExtra) / Math.max(1, item.quantity)); + const newUnitCost = Math.round((item.subtotal + newItemExtra) / Math.max(1, item.quantity)); + const unitCostDelta = newUnitCost - oldUnitCost; + + // Update unitCost di PurchaseBatch untuk PO & produk ini + await prisma.purchaseBatch.updateMany({ + where: { purchaseOrderId: po.id, productId: item.productId }, + data: { unitCost: newUnitCost }, + }); + + // Sesuaikan rata-rata HPP produk secara proporsional + if (unitCostDelta !== 0) { + const prod = await prisma.product.findUnique({ + where: { id: item.productId }, + include: { stockItems: true }, + }); + if (prod) { + const totalStock = prod.stockItems.reduce((acc, s) => acc + s.quantity, 0); + const batchForItem = po.batches.find((b) => b.productId === item.productId); + const remainingBatchQty = batchForItem ? batchForItem.remainingQty : item.quantity; + const weight = totalStock > 0 ? Math.min(1, remainingBatchQty / totalStock) : 1; + const adjustedHpp = Math.max(0, Math.round((prod.purchasePrice || 0) + unitCostDelta * weight)); + await prisma.product.update({ + where: { id: prod.id }, + data: { purchasePrice: adjustedHpp }, + }); + } + } + } + } + + // Update Akuntansi: Persediaan (1201), PPN Masukan (1301) & Hutang Usaha (2001) + const poCompany = po.companyName || "PT EnterpriseCore Utama"; + const invAcc = await getCompanyAccount("1201", poCompany); + const taxInAcc = await getCompanyAccount("1301", poCompany); + const apAcc = await getCompanyAccount("2001", poCompany); + + if (invAcc && deltaLogisticsCost !== 0) { + await prisma.account.update({ + where: { id: invAcc.id }, + data: { balance: { increment: deltaLogisticsCost } }, + }); + } + if (taxInAcc && deltaTax !== 0) { + await prisma.account.update({ + where: { id: taxInAcc.id }, + data: { balance: { increment: deltaTax } }, + }); + } + if (apAcc && deltaCost !== 0) { + await prisma.account.update({ + where: { id: apAcc.id }, + data: { balance: { increment: deltaCost } }, + }); + } + + if (apAcc && (deltaLogisticsCost !== 0 || deltaTax !== 0)) { + const lines: { accountId: string; type: string; amount: number }[] = []; + if (invAcc && deltaLogisticsCost !== 0) { + lines.push({ + accountId: invAcc.id, + type: deltaLogisticsCost > 0 ? "DEBIT" : "CREDIT", + amount: Math.abs(deltaLogisticsCost), + }); + } + if (taxInAcc && deltaTax !== 0) { + lines.push({ + accountId: taxInAcc.id, + type: deltaTax > 0 ? "DEBIT" : "CREDIT", + amount: Math.abs(deltaTax), + }); + } + if (deltaCost !== 0) { + lines.push({ + accountId: apAcc.id, + type: deltaCost > 0 ? "CREDIT" : "DEBIT", + amount: Math.abs(deltaCost), + }); + } + + if (lines.length >= 2) { + const jCount = await prisma.journalEntry.count(); + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-LOG-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`, + description: `Penyesuaian Biaya ${mode === "ASSISTED_ALL_IN" ? `Forwarder${cleanForwarder ? ` (${cleanForwarder})` : ""}` : "Ongkir & Pajak"} PO ${po.poNumber} (${poCompany})${newIncludeTax ? ` [PPN ${newTaxRate}%]` : ""}`, + reference: po.poNumber, + companyName: poCompany, + lines: { create: lines }, + }, + }); + } + } + } + + const modeLabel = + mode === "ASSISTED_ALL_IN" + ? `Via Forwarder${cleanForwarder ? ` (${cleanForwarder})` : ""}: Rp ${newExportCost.toLocaleString("id-ID")}` + : `Ongkir: Rp ${newShippingCost.toLocaleString("id-ID")}, Bea Cukai/Pajak: Rp ${newExportCost.toLocaleString("id-ID")}`; + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE_PO_LOGISTICS", + module: "PURCHASING", + description: `[${user.role}] Memperbarui biaya logistik/forwarder PO ${po.poNumber} (${modeLabel}). Total PO baru: Rp ${newTotalAmount.toLocaleString("id-ID")}.`, + metadata: { + orderId, + poNumber: po.poNumber, + logisticsMode: mode, + forwardingCompany: cleanForwarder, + shippingCost: newShippingCost, + exportCost: newExportCost, + deltaCost, + newTotalAmount, + }, + }); + + await dispatchNotification({ + type: "MONEY_OUT", + title: `Update Biaya Forwarder / Pajak PO: ${po.poNumber}`, + message: `${user.name} (${user.role}) memperbarui biaya logistik PO ${po.poNumber} (${modeLabel}). Total nilai PO kini Rp ${newTotalAmount.toLocaleString("id-ID")}${po.status === "RECEIVED" ? " & HPP (Landed Cost) telah disesuaikan otomatis." : "."}`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "PURCHASING"], + }); + + return NextResponse.json({ success: true, order: updatedPo }); + } + + // ========================================================================= + // 5. UPDATE / CATAT SERIAL NUMBER (SN) BARANG MASUK OLEH GUDANG (MANUAL / EXCEL) + // ========================================================================= + if (body.action === "UPDATE_PO_SERIALS") { + if (!["ADMIN", "MANAGER", "INVENTORY", "PURCHASING"].includes(user.role)) { + return NextResponse.json( + { + error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang mencatat Serial Number barang masuk.`, + }, + { status: 403 } + ); + } + + const { orderId, itemSerialNumbers } = body; + if (!orderId || !itemSerialNumbers || typeof itemSerialNumbers !== "object") { + return NextResponse.json( + { error: "ID Purchase Order dan daftar Serial Number wajib disertakan" }, + { status: 400 } + ); + } + + const po = await prisma.purchaseOrder.findUnique({ + where: { id: orderId }, + include: { items: { include: { product: true } } }, + }); + + if (!po) { + return NextResponse.json({ error: "Purchase Order tidak ditemukan" }, { status: 404 }); + } + + let updatedCount = 0; + const summaryParts: string[] = []; + + for (const item of po.items) { + if (item.product?.isService) continue; + if (!(item.id in itemSerialNumbers)) continue; + + const rawSn = itemSerialNumbers[item.id]; + const cleanSn = rawSn ? String(rawSn).trim() : null; + + await prisma.purchaseOrderItem.update({ + where: { id: item.id }, + data: { serialNumbers: cleanSn }, + }); + + await prisma.purchaseBatch.updateMany({ + where: { purchaseOrderId: po.id, productId: item.productId }, + data: { serialNumbers: cleanSn }, + }); + + await prisma.stockMovement.updateMany({ + where: { + referenceType: "PURCHASE_ORDER", + referenceId: po.poNumber, + productId: item.productId, + type: "IN", + }, + data: { serialNumbers: cleanSn }, + }); + + const snTotal = cleanSn + ? Array.from(new Set(cleanSn.split(/[\n,;]+/).map((s) => s.trim()).filter(Boolean))).length + : 0; + summaryParts.push(`${item.product?.name || "Produk"} (${snTotal} SN)`); + updatedCount++; + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE_PO_SERIALS", + module: "PURCHASING", + description: `[${user.role}] Memperbarui pencatatan Serial Number (SN) barang masuk PO ${po.poNumber}: ${summaryParts.join(", ") || "-"}`, + metadata: { orderId, poNumber: po.poNumber, updatedCount }, + }); + + return NextResponse.json({ success: true, updatedCount }); + } + + return NextResponse.json({ error: "Tindakan tidak dikenal" }, { status: 400 }); + } catch (error: any) { + console.error("Purchases PUT error:", error); + 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", "PURCHASING"].includes(user.role)) { + return NextResponse.json( + { error: "Akses ditolak: Hanya Superadmin (ADMIN), Manager, atau Tim Purchasing yang memiliki wewenang menghapus data pembelian." }, + { status: 403 } + ); + } + + const { searchParams } = new URL(req.url); + const id = searchParams.get("id"); + const type = searchParams.get("type") || "po"; // "po", "pr", or "batch" + + if (!id) { + return NextResponse.json({ error: "ID transaksi wajib disertakan" }, { status: 400 }); + } + + if (type === "pr") { + const pr = await prisma.purchaseRequisition.findFirst({ + where: { OR: [{ id }, { reqNumber: id }] }, + }); + if (!pr) return NextResponse.json({ error: "Pengajuan PR tidak ditemukan" }, { status: 404 }); + + await prisma.purchaseRequisitionItem.deleteMany({ where: { requisitionId: pr.id } }); + await prisma.purchaseOrder.updateMany({ + where: { requisitionId: pr.id }, + data: { requisitionId: null }, + }); + await prisma.purchaseRequisition.delete({ where: { id: pr.id } }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "DELETE", + module: "PURCHASING", + description: `[${user.role}] Menghapus Pengajuan Pembelian PR ${pr.reqNumber}`, + metadata: { requisitionId: pr.id, reqNumber: pr.reqNumber }, + }); + + return NextResponse.json({ success: true, message: `PR ${pr.reqNumber} berhasil dihapus.` }); + } + + if (type === "batch") { + const batch = await prisma.purchaseBatch.findUnique({ + where: { id }, + include: { purchaseOrder: true }, + }); + if (!batch) return NextResponse.json({ error: "Batch PO tidak ditemukan" }, { status: 404 }); + + await prisma.salesItemBatchAllocation.deleteMany({ where: { purchaseBatchId: batch.id } }); + await prisma.purchaseBatch.delete({ where: { id: batch.id } }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "DELETE_BATCH", + module: "PURCHASING", + description: `[${user.role}] Menghapus Batch FIFO PO ${batch.poNumber} (${batch.productId})`, + metadata: { batchId: batch.id, poNumber: batch.poNumber }, + }); + + return NextResponse.json({ success: true, message: `Batch ${batch.poNumber} berhasil dihapus.` }); + } + + // Default: PO Vendor (cari berdasarkan ID UUID atau poNumber) + const po = await prisma.purchaseOrder.findFirst({ + where: { OR: [{ id }, { poNumber: id }] }, + include: { batches: true, items: true }, + }); + if (!po) return NextResponse.json({ error: "PO Vendor tidak ditemukan" }, { status: 404 }); + + // Hapus relasi alokasi penjualan jika ada + for (const b of po.batches) { + await prisma.salesItemBatchAllocation.deleteMany({ where: { purchaseBatchId: b.id } }); + } + await prisma.purchaseBatch.deleteMany({ where: { purchaseOrderId: po.id } }); + await prisma.purchaseOrderItem.deleteMany({ where: { purchaseOrderId: po.id } }); + + await prisma.stockMovement.deleteMany({ + where: { referenceType: "PURCHASE_ORDER", referenceId: po.poNumber }, + }); + + const entries = await prisma.journalEntry.findMany({ + where: { reference: po.poNumber }, + select: { id: true }, + }); + for (const entry of entries) { + await prisma.journalLine.deleteMany({ where: { journalEntryId: entry.id } }); + await prisma.journalEntry.delete({ where: { id: entry.id } }); + } + + await prisma.purchaseOrder.delete({ where: { id: po.id } }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "DELETE", + module: "PURCHASING", + description: `[${user.role}] Menghapus PO Vendor ${po.poNumber} senilai Rp ${po.totalAmount.toLocaleString("id-ID")}`, + metadata: { purchaseOrderId: po.id, poNumber: po.poNumber }, + }); + + return NextResponse.json({ success: true, message: `PO Vendor ${po.poNumber} berhasil dihapus.` }); + } catch (error: any) { + console.error("Purchases DELETE error:", error); + return NextResponse.json({ error: error.message }, { status: 500 }); + } +} diff --git a/src/app/api/sales/route.ts b/src/app/api/sales/route.ts new file mode 100644 index 0000000..fa9ce56 --- /dev/null +++ b/src/app/api/sales/route.ts @@ -0,0 +1,1778 @@ +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 { getSavedCompanies, getCompanyAccount } from "@/lib/companies"; + +export async function GET() { + try { + const user = await getCurrentUser(); + if (!user) { + return NextResponse.json({ error: "Sesi tidak valid" }, { status: 401 }); + } + + // Role check: ADMIN, MANAGER, SALES, ACCOUNTANT, dan INVENTORY (untuk pengiriman, resi, & ongkir gudang) + if (!["ADMIN", "MANAGER", "SALES", "ACCOUNTANT", "INVENTORY"].includes(user.role)) { + return NextResponse.json( + { error: `Akses ditolak: Peran ${user.role} tidak memiliki izin melihat data penjualan/pengiriman.` }, + { status: 403 } + ); + } + + const isInventoryOnly = user.role === "INVENTORY"; + + const [orders, customers, customerPrices, activeBatches, suppliers, companies] = await Promise.all([ + prisma.salesOrder.findMany({ + include: { + customer: true, + items: { + include: { + product: true, + batchAllocations: { + include: { + purchaseBatch: { + include: { + purchaseOrder: { + select: { poNumber: true, supplier: { select: { name: true } } }, + }, + }, + }, + }, + }, + }, + }, + }, + orderBy: { createdAt: "desc" }, + }), + prisma.customer.findMany({ + include: { + specialPrices: true, + }, + orderBy: { name: "asc" }, + }), + prisma.customerProductPrice.findMany({ + include: { + customer: true, + product: true, + }, + }), + prisma.purchaseBatch.findMany({ + where: { + remainingQty: { gt: 0 }, + purchaseOrder: { + status: { in: ["RECEIVED", "COMPLETED"] }, + }, + }, + include: { + product: true, + warehouse: true, + purchaseOrder: { + select: { poNumber: true, status: true, supplier: { select: { name: true } } }, + }, + }, + orderBy: { receivedAt: "asc" }, + }), + prisma.supplier.findMany({ + orderBy: { name: "asc" }, + }), + getSavedCompanies(), + ]); + + if (isInventoryOnly) { + const sanitizedOrders = orders.map((o) => ({ + ...o, + totalAmount: 0, + totalHpp: 0, + paidAmount: 0, + taxRate: 0, + taxAmount: 0, + items: o.items.map((it) => ({ + ...it, + costPrice: 0, + unitPrice: 0, + subtotal: 0, + serviceFee: 0, + product: it.product + ? { ...it.product, purchasePrice: 0, sellingPrice: 0 } + : it.product, + batchAllocations: it.batchAllocations.map((al) => ({ + ...al, + unitCost: 0, + purchaseBatch: al.purchaseBatch + ? { ...al.purchaseBatch, unitCost: 0 } + : al.purchaseBatch, + })), + })), + })); + + const sanitizedBatches = activeBatches.map((b) => ({ + ...b, + unitCost: 0, + product: b.product ? { ...b.product, purchasePrice: 0, sellingPrice: 0 } : b.product, + })); + + return NextResponse.json({ + orders: sanitizedOrders, + customers: customers.map((c) => ({ ...c, specialPrices: [] })), + customerPrices: [], + activeBatches: sanitizedBatches, + suppliers, + companies, + isInventoryOnly: true, + }); + } + + return NextResponse.json({ orders, customers, customerPrices, activeBatches, suppliers, companies, isInventoryOnly: false }); + } catch (error: any) { + console.error("Sales 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 }); + } + + const body = await req.json(); + + // Update Manual Resi, Ekspedisi & Ongkos Kirim ke Customer (KHUSUS Finance & Pihak Gudang + Admin/Manager) + if (body.action === "UPDATE_SHIPPING") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT", "INVENTORY"].includes(user.role)) { + return NextResponse.json( + { error: `Akses ditolak: Hanya Finance (Akuntan), Pihak Gudang (Inventory), Manager, atau Admin yang berwenang menginput ongkos kirim & resi customer.` }, + { status: 403 } + ); + } + + const { + orderId, + shippingCost: inputCost, + courierName, + trackingNumber, + shippingNotes, + nextStatus, + } = body; + if (!orderId) { + return NextResponse.json({ error: "ID Sales Order wajib ada" }, { status: 400 }); + } + + const order = await prisma.salesOrder.findUnique({ + where: { id: orderId }, + include: { items: true, customer: true }, + }); + + if (!order) { + return NextResponse.json({ error: "Sales Order tidak ditemukan" }, { status: 404 }); + } + + const newShippingCost = Math.max(0, parseFloat(inputCost) || 0); + const cleanCourier = courierName !== undefined ? String(courierName).trim() || null : order.courierName; + const cleanTracking = trackingNumber !== undefined ? String(trackingNumber).trim() || null : order.trackingNumber; + const cleanShippingNotes = + shippingNotes !== undefined + ? String(shippingNotes).trim() || null + : order.shippingNotes; + + const itemsSubtotal = order.items.reduce((sum, it) => sum + it.subtotal, 0); + const taxAmount = order.includeTax + ? Math.round((itemsSubtotal * (order.taxRate || 11)) / 100) + : (order.taxAmount || 0); + const newTotalAmount = itemsSubtotal + newShippingCost + taxAmount; + const costDifference = newTotalAmount - order.totalAmount; + + // Sesuaikan status pembayaran jika ongkir baru menambah total tagihan melebihi yang sudah dibayar + const paidAmt = order.paidAmount || (order.paymentStatus === "PAID" ? order.totalAmount : 0); + let nextPaymentStatus = order.paymentStatus; + if (paidAmt >= newTotalAmount && newTotalAmount > 0) { + nextPaymentStatus = "PAID"; + } else if (paidAmt > 0 && paidAmt < newTotalAmount) { + nextPaymentStatus = "PARTIAL"; + } else if (paidAmt === 0) { + nextPaymentStatus = "UNPAID"; + } + + const validStatuses = new Set(["CONFIRMED", "SHIPPED", "COMPLETED"]); + const updatedStatus = + nextStatus && validStatuses.has(nextStatus) + ? nextStatus + : order.status === "CONFIRMED" && (cleanCourier || cleanTracking) + ? "SHIPPED" + : order.status; + + const updatedOrder = await prisma.salesOrder.update({ + where: { id: orderId }, + data: { + shippingCost: newShippingCost, + courierName: cleanCourier, + trackingNumber: cleanTracking, + shippingNotes: cleanShippingNotes, + totalAmount: newTotalAmount, + paymentStatus: nextPaymentStatus, + status: updatedStatus, + }, + }); + + // Sesuaikan pembukuan akuntansi: Piutang Usaha (1101) & Pendapatan Penjualan/Ongkir (4001) + if (costDifference !== 0) { + const orderCompany = order.companyName || "PT EnterpriseCore Utama"; + const arAcc = await getCompanyAccount("1101", orderCompany); + const revAcc = await getCompanyAccount("4001", orderCompany); + + if (arAcc) { + await prisma.account.update({ + where: { id: arAcc.id }, + data: { balance: { increment: costDifference } }, + }); + } + if (revAcc) { + await prisma.account.update({ + where: { id: revAcc.id }, + data: { balance: { increment: costDifference } }, + }); + } + + if (arAcc && revAcc) { + const absDiff = Math.abs(costDifference); + const jCount = await prisma.journalEntry.count(); + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-SHP-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`, + description: `Penyesuaian Ongkos Kirim SO ${order.orderNumber} (${order.customer?.name || "-"})${cleanCourier ? ` via ${cleanCourier}` : ""}${cleanTracking ? ` [Resi: ${cleanTracking}]` : ""}`, + reference: order.orderNumber, + companyName: orderCompany, + lines: { + create: + costDifference > 0 + ? [ + { accountId: arAcc.id, type: "DEBIT", amount: absDiff }, + { accountId: revAcc.id, type: "CREDIT", amount: absDiff }, + ] + : [ + { accountId: revAcc.id, type: "DEBIT", amount: absDiff }, + { accountId: arAcc.id, type: "CREDIT", amount: absDiff }, + ], + }, + }, + }); + } + } + + const resiSummary = [ + cleanCourier ? `Ekspedisi: ${cleanCourier}` : null, + cleanTracking ? `Resi: ${cleanTracking}` : null, + cleanShippingNotes ? `Catatan: ${cleanShippingNotes}` : null, + ] + .filter(Boolean) + .join(" | "); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE_SHIPPING", + module: "SALES", + description: `[${user.role}] Update Pengiriman & Ongkir SO ${order.orderNumber}: Ongkir Rp ${newShippingCost.toLocaleString("id-ID")}${resiSummary ? ` (${resiSummary})` : ""}. Status Kirim: ${updatedStatus}.`, + metadata: { + orderId, + shippingCost: newShippingCost, + courierName: cleanCourier, + trackingNumber: cleanTracking, + shippingNotes: cleanShippingNotes, + status: updatedStatus, + }, + }); + + await dispatchNotification({ + type: "STOCK_OUT", + title: `Update Pengiriman & Ongkir SO: ${order.orderNumber}`, + message: `${user.name} (${user.role}) memperbarui pengiriman untuk ${order.customer?.name || "Customer"}${cleanCourier ? ` via ${cleanCourier}` : ""}${cleanTracking ? ` (Resi: ${cleanTracking})` : ""}. Ongkos kirim Rp ${newShippingCost.toLocaleString("id-ID")} telah otomatis ditambahkan ke Invoice.`, + targetRoles: ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT", "INVENTORY"], + }); + + return NextResponse.json({ + success: true, + order: + user.role === "INVENTORY" + ? { ...updatedOrder, totalAmount: 0, totalHpp: 0, paidAmount: 0, taxAmount: 0 } + : updatedOrder, + }); + } + + // Update PPN Penjualan pada Invoice SO (KHUSUS Finance / Akuntan, Manager, Admin) + if (body.action === "UPDATE_SO_TAX") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { error: `Akses ditolak: Hanya Finance (Akuntan), Manager, atau Admin yang berwenang mengatur PPN pada invoice customer.` }, + { status: 403 } + ); + } + + const { orderId, includeTax: inputIncludeTax, taxRate: inputTaxRate } = body; + if (!orderId) { + return NextResponse.json({ error: "ID Sales Order wajib ada" }, { status: 400 }); + } + + const order = await prisma.salesOrder.findUnique({ + where: { id: orderId }, + include: { items: true, customer: true }, + }); + + if (!order) { + return NextResponse.json({ error: "Sales Order tidak ditemukan" }, { status: 404 }); + } + + const itemsSubtotal = order.items.reduce((sum, it) => sum + it.subtotal, 0); + const oldTaxAmount = order.includeTax ? (order.taxAmount || 0) : 0; + const newIncludeTax = Boolean(inputIncludeTax); + const newTaxRate = newIncludeTax ? Math.max(0, parseFloat(inputTaxRate) || 11) : 0; + const newTaxAmount = newIncludeTax ? Math.round((itemsSubtotal * newTaxRate) / 100) : 0; + const deltaTax = newTaxAmount - oldTaxAmount; + const newTotalAmount = itemsSubtotal + (order.shippingCost || 0) + newTaxAmount; + + const paidAmt = order.paidAmount || (order.paymentStatus === "PAID" ? order.totalAmount : 0); + let nextPaymentStatus = order.paymentStatus; + if (paidAmt >= newTotalAmount && newTotalAmount > 0) { + nextPaymentStatus = "PAID"; + } else if (paidAmt > 0 && paidAmt < newTotalAmount) { + nextPaymentStatus = "PARTIAL"; + } else { + nextPaymentStatus = "UNPAID"; + } + + const updatedOrder = await prisma.salesOrder.update({ + where: { id: orderId }, + data: { + includeTax: newIncludeTax, + taxRate: newTaxRate, + taxAmount: newTaxAmount, + totalAmount: newTotalAmount, + paymentStatus: nextPaymentStatus, + }, + }); + + if (deltaTax !== 0) { + const orderCompany = order.companyName || "PT EnterpriseCore Utama"; + const arAcc = await getCompanyAccount("1101", orderCompany); + const taxOutAcc = await getCompanyAccount("2101", orderCompany); + + if (arAcc) { + await prisma.account.update({ + where: { id: arAcc.id }, + data: { balance: { increment: deltaTax } }, + }); + } + if (taxOutAcc) { + await prisma.account.update({ + where: { id: taxOutAcc.id }, + data: { balance: { increment: deltaTax } }, + }); + } + if (arAcc && taxOutAcc) { + const absTax = Math.abs(deltaTax); + const jCount = await prisma.journalEntry.count(); + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-TAX-${Date.now().toString().slice(-5)}-${String(jCount + 1).padStart(4, "0")}`, + description: `Penyesuaian PPN Keluaran (${newIncludeTax ? `${newTaxRate}%` : "Non-PPN"}) SO ${order.orderNumber} (${order.customer?.name || "-"})`, + reference: order.orderNumber, + companyName: orderCompany, + lines: { + create: + deltaTax > 0 + ? [ + { accountId: arAcc.id, type: "DEBIT", amount: absTax }, + { accountId: taxOutAcc.id, type: "CREDIT", amount: absTax }, + ] + : [ + { accountId: taxOutAcc.id, type: "DEBIT", amount: absTax }, + { accountId: arAcc.id, type: "CREDIT", amount: absTax }, + ], + }, + }, + }); + } + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE_SO_TAX", + module: "SALES", + description: `[${user.role}] Mengatur PPN Invoice SO ${order.orderNumber}: ${newIncludeTax ? `PPN ${newTaxRate}% (Rp ${newTaxAmount.toLocaleString("id-ID")})` : "Tanpa PPN"}. Total Invoice baru: Rp ${newTotalAmount.toLocaleString("id-ID")}`, + }); + + return NextResponse.json({ success: true, order: updatedOrder }); + } + + // Konfirmasi Pembayaran Jasa Service Berbayar (KHUSUS Finance / Manager / Admin) + if (body.action === "CONFIRM_SERVICE_PAYMENT") { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { + error: + "Akses ditolak: Hanya Finance (Akuntan), Manager, atau Admin yang berwenang mengonfirmasi pembayaran jasa service.", + }, + { status: 403 } + ); + } + + const { salesOrderItemId, servicePaymentStatus: targetPayStatus, serviceFee: optionalFee } = body; + if (!salesOrderItemId) { + return NextResponse.json({ error: "Item Sales Order wajib disertakan" }, { status: 400 }); + } + + const item = await prisma.salesOrderItem.findUnique({ + where: { id: salesOrderItemId }, + include: { + salesOrder: { include: { customer: true } }, + product: true, + }, + }); + + if (!item) { + return NextResponse.json({ error: "Item Sales Order tidak ditemukan" }, { status: 404 }); + } + + const finalFee = + optionalFee !== undefined ? Math.max(0, parseFloat(optionalFee) || 0) : item.serviceFee || 0; + const returnShipping = item.returnShippingCost || 0; + const totalCharge = finalFee + returnShipping; + if (totalCharge <= 0) { + return NextResponse.json( + { error: "Total tagihan jasa service & biaya kirim bernilai Rp 0 (Gratis). Tidak perlu konfirmasi pembayaran." }, + { status: 400 } + ); + } + + const nextStatus = targetPayStatus === "UNPAID" ? "UNPAID" : "PAID"; + const prevPaid = item.servicePaymentStatus === "PAID"; + const nowPaid = nextStatus === "PAID"; + + const updated = await prisma.salesOrderItem.update({ + where: { id: salesOrderItemId }, + data: { + serviceFee: finalFee, + serviceType: finalFee > 0 ? "PAID_SERVICE" : item.serviceType || "FREE_WARRANTY", + servicePaymentStatus: nextStatus, + }, + }); + + const companyName = item.salesOrder.companyName || "PT EnterpriseCore Utama"; + const bankAcc = await getCompanyAccount("1002", companyName); + const revAcc = await getCompanyAccount("4001", companyName); + + if (!prevPaid && nowPaid) { + if (bankAcc) { + await prisma.account.update({ + where: { id: bankAcc.id }, + data: { balance: { increment: totalCharge } }, + }); + } + if (revAcc) { + await prisma.account.update({ + where: { id: revAcc.id }, + data: { balance: { increment: totalCharge } }, + }); + } + if (bankAcc && revAcc) { + const jCount = await prisma.journalEntry.count(); + const detailParts: string[] = []; + if (finalFee > 0) detailParts.push(`Jasa Service Rp ${finalFee.toLocaleString("id-ID")}`); + if (returnShipping > 0) detailParts.push(`Ongkir Balik Rp ${returnShipping.toLocaleString("id-ID")}`); + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-SRV-${Date.now().toString().slice(-4)}-${String(jCount + 1).padStart(4, "0")}`, + description: `Pembayaran Purna Jual (${detailParts.join(" + ")}) SO ${item.salesOrder.orderNumber} (${item.product.name}) - ${item.salesOrder.customer?.name || "Customer"}`, + reference: item.salesOrder.orderNumber, + companyName, + lines: { + create: [ + { accountId: bankAcc.id, type: "DEBIT", amount: totalCharge }, + { accountId: revAcc.id, type: "CREDIT", amount: totalCharge }, + ], + }, + }, + }); + } + + await dispatchNotification({ + type: "MONEY_IN", + title: `Pembayaran Service / Ongkir Balik Lunas: SO ${item.salesOrder.orderNumber}`, + message: `Pembayaran tagihan purna jual untuk ${item.product.name} (${item.salesOrder.customer?.name || "Customer"}) sebesar Rp ${totalCharge.toLocaleString("id-ID")} (Jasa: Rp ${finalFee.toLocaleString("id-ID")}, Ongkir Balik: Rp ${returnShipping.toLocaleString("id-ID")}) telah dikonfirmasi LUNAS oleh ${user.name}.`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "SALES"], + }); + } else if (prevPaid && !nowPaid) { + const revertAmount = (item.serviceFee || finalFee) + returnShipping; + if (bankAcc && revertAmount > 0) { + await prisma.account.update({ + where: { id: bankAcc.id }, + data: { balance: { decrement: revertAmount } }, + }); + } + if (revAcc && revertAmount > 0) { + await prisma.account.update({ + where: { id: revAcc.id }, + data: { balance: { decrement: revertAmount } }, + }); + } + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "CONFIRM_SERVICE_PAYMENT", + module: "SALES", + description: `[${user.role}] Mengubah status pembayaran Service/Ongkir Balik SO ${item.salesOrder.orderNumber} (${item.product.name}) menjadi ${nextStatus} senilai Rp ${totalCharge.toLocaleString("id-ID")}`, + metadata: { salesOrderItemId, serviceFee: finalFee, returnShippingCost: returnShipping, totalCharge, servicePaymentStatus: nextStatus }, + }); + + // Sinkronkan status pembayaran pada catatan riwayat DeviceRecord terkait + await prisma.deviceRecord.updateMany({ + where: { + salesOrderId: item.salesOrderId, + productId: item.productId, + }, + data: { + serviceFee: finalFee, + returnShippingCost: returnShipping, + servicePaymentStatus: nextStatus, + }, + }); + + return NextResponse.json({ success: true, item: updated }); + } + + // Role check: Only ADMIN, MANAGER, SALES can create sales orders / customers / RMA + if (!["ADMIN", "MANAGER", "SALES"].includes(user.role)) { + return NextResponse.json( + { + error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang untuk membuat Sales Order. Hanya Sales, Manager, atau Admin yang diizinkan.`, + }, + { status: 403 } + ); + } + + if (body.action === "CREATE_CUSTOMER") { + const { name, email, phone, address } = body; + if (!name || !name.trim()) { + return NextResponse.json({ error: "Nama pelanggan wajib diisi" }, { status: 400 }); + } + const cCount = await prisma.customer.count(); + const code = `CUST-${String(cCount + 1).padStart(3, "0")}`; + const customer = await prisma.customer.create({ + data: { + code, + name: name.trim(), + email: email || null, + phone: phone || null, + address: address || null, + }, + }); + return NextResponse.json({ success: true, customer }); + } + + // Quick Add PO Vendor dinonaktifkan untuk Sales: barang harus diambil dari PO yang sudah sampai di gudang + if (body.action === "QUICK_ADD_VENDOR_PO") { + return NextResponse.json( + { + error: + "Pembuatan PO Vendor langsung dari Sales Order tidak diizinkan. Ambil stok dari PO yang sudah sampai di gudang, atau ajukan pengadaan melalui menu Pembelian.", + }, + { status: 403 } + ); + } + + // Layanan Purna Jual: Update Status Service / Perbaikan (Gratis Garansi vs Jasa Service Berbayar + Biaya Kirim Balik Ditanggung User) + if (body.action === "RMA_SERVICE") { + const { + salesOrderItemId, + serviceStatus, + serviceNotes, + damagedSerialNumbers, + serviceFee, + serviceMode, // "FREE_WARRANTY" | "PAID_SERVICE" + returnShippingCost, + returnCourierName, + returnTrackingNumber, + } = body; + if (!salesOrderItemId || !serviceStatus) { + return NextResponse.json({ error: "Item barang dan status service wajib diisi" }, { status: 400 }); + } + + const item = await prisma.salesOrderItem.findUnique({ + where: { id: salesOrderItemId }, + include: { salesOrder: { include: { customer: true } }, product: true }, + }); + + if (!item) { + return NextResponse.json({ error: "Item Sales Order tidak ditemukan" }, { status: 404 }); + } + + const expDate = item.warrantyExpiry + ? new Date(item.warrantyExpiry) + : (() => { + const d = new Date(item.salesOrder.orderDate || item.salesOrder.createdAt); + d.setMonth(d.getMonth() + (item.salesOrder.warrantyMonths || 12)); + return d; + })(); + const isExpired = new Date() > expDate; + + const isPaidService = isExpired || serviceMode === "PAID_SERVICE"; + const cleanDamagedSn = + damagedSerialNumbers !== undefined + ? damagedSerialNumbers + ? String(damagedSerialNumbers).trim() + : null + : item.damagedSerialNumbers; + + const cleanReturnShipping = + returnShippingCost !== undefined + ? Math.max(0, parseFloat(returnShippingCost) || 0) + : item.returnShippingCost || 0; + const cleanReturnCourier = + returnCourierName !== undefined + ? String(returnCourierName).trim() || null + : item.returnCourierName; + const cleanReturnTracking = + returnTrackingNumber !== undefined + ? String(returnTrackingNumber).trim() || null + : item.returnTrackingNumber; + + let cleanFee = 0; + let finalServiceType = "FREE_WARRANTY"; + + if (serviceStatus === "NORMAL") { + cleanFee = 0; + finalServiceType = isExpired ? "PAID_SERVICE" : "FREE_WARRANTY"; + } else if (isPaidService) { + finalServiceType = "PAID_SERVICE"; + cleanFee = + serviceFee !== undefined ? Math.max(0, parseFloat(serviceFee) || 0) : item.serviceFee || 0; + if (cleanFee <= 0 && !["DAMAGED_UNUSABLE", "CANNIBALIZED"].includes(serviceStatus)) { + return NextResponse.json( + { + error: + "Masa garansi telah habis / layanan dipilih sebagai Jasa Service Berbayar. Masukkan nominal biaya jasa service (> Rp 0).", + }, + { status: 400 } + ); + } + } else { + // Garansi masih aktif -> Service Gratis (Free), ongkir balik tetap bisa ditagihkan jika ada + finalServiceType = "FREE_WARRANTY"; + cleanFee = 0; + } + + const prevTotalCharge = (item.serviceFee || 0) + (item.returnShippingCost || 0); + const newTotalCharge = cleanFee + cleanReturnShipping; + const finalPaymentStatus = + newTotalCharge > 0 + ? item.servicePaymentStatus === "PAID" && prevTotalCharge === newTotalCharge + ? "PAID" + : "UNPAID" + : "FREE"; + + const updated = await prisma.salesOrderItem.update({ + where: { id: salesOrderItemId }, + data: { + serviceStatus, + serviceType: finalServiceType, + serviceNotes: serviceNotes !== undefined ? String(serviceNotes).trim() : item.serviceNotes, + damagedSerialNumbers: cleanDamagedSn, + serviceFee: cleanFee, + returnShippingCost: cleanReturnShipping, + returnCourierName: cleanReturnCourier, + returnTrackingNumber: cleanReturnTracking, + servicePaymentStatus: finalPaymentStatus, + }, + }); + + // Otomatis catat/sinkronkan ke Riwayat Device (Pernah Diservis / Rusak Total / Kanibalan) + if (!item.product.isService) { + const mappedCondition = + serviceStatus === "DAMAGED_UNUSABLE" + ? "DAMAGED_UNUSABLE" + : serviceStatus === "CANNIBALIZED" + ? "CANNIBALIZED" + : serviceStatus === "SERVICED_RETURNED" || serviceStatus === "NORMAL" + ? "SERVICED_OK" + : "IN_SERVICE"; + + const snTokens = cleanDamagedSn + ? Array.from(new Set(cleanDamagedSn.split(/[\n,;]+/).map((s) => s.trim()).filter(Boolean))) + : [`${item.salesOrder.orderNumber}-${item.product.sku}`]; + + const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); + const devCount = await prisma.deviceRecord.count(); + const originCode = finalServiceType === "PAID_SERVICE" ? "PAID_SERVICE" : "WARRANTY_FREE"; + const noteText = + (serviceNotes !== undefined ? String(serviceNotes).trim() : item.serviceNotes) || + `Pencatatan service dari SO ${item.salesOrder.orderNumber}`; + + for (let idx = 0; idx < snTokens.length; idx++) { + const sn = snTokens[idx]; + const existingRec = await prisma.deviceRecord.findFirst({ + where: { + serialNumber: sn, + productId: item.productId, + salesOrderId: item.salesOrderId, + }, + }); + + if (existingRec) { + await prisma.deviceRecord.update({ + where: { id: existingRec.id }, + data: { + condition: mappedCondition, + serviceOrigin: originCode, + warrantyStatus: isExpired ? "OUT_OF_WARRANTY" : "IN_WARRANTY", + serviceFee: cleanFee, + returnShippingCost: cleanReturnShipping, + returnCourierName: cleanReturnCourier, + returnTrackingNumber: cleanReturnTracking, + servicePaymentStatus: finalPaymentStatus, + damageDescription: noteText, + actionTaken: `Status RMA: ${serviceStatus}`, + recordedBy: user.name, + }, + }); + } else { + await prisma.deviceRecord.create({ + data: { + recordNumber: `DEV-${dateStr}-${String(devCount + idx + 1).padStart(4, "0")}-${Math.floor( + 10 + Math.random() * 89 + )}`, + serialNumber: sn, + productId: item.productId, + customerId: item.salesOrder.customerId, + salesOrderId: item.salesOrderId, + salesOrderNumber: item.salesOrder.orderNumber, + companyName: item.salesOrder.companyName || "PT EnterpriseCore Utama", + condition: mappedCondition, + serviceOrigin: originCode, + warrantyStatus: isExpired ? "OUT_OF_WARRANTY" : "IN_WARRANTY", + serviceFee: cleanFee, + returnShippingCost: cleanReturnShipping, + returnCourierName: cleanReturnCourier, + returnTrackingNumber: cleanReturnTracking, + servicePaymentStatus: finalPaymentStatus, + damageDescription: noteText, + actionTaken: `Status RMA: ${serviceStatus}`, + recordedBy: user.name, + }, + }); + } + } + } + + const modeText = + finalServiceType === "PAID_SERVICE" + ? `Jasa Service Berbayar (Rp ${cleanFee.toLocaleString("id-ID")})` + : "Service Gratis (Masa Garansi Aktif)"; + const shipText = + cleanReturnShipping > 0 + ? ` | Ongkir Balik (Ditanggung User): Rp ${cleanReturnShipping.toLocaleString("id-ID")}${cleanReturnCourier ? ` via ${cleanReturnCourier}` : ""}${cleanReturnTracking ? ` [Resi: ${cleanReturnTracking}]` : ""}` + : ""; + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE", + module: "SALES", + description: `[${user.role}] Update Status Service SO ${item.salesOrder.orderNumber} - ${item.product.name}: ${serviceStatus} | ${modeText}${shipText} | Catatan: ${serviceNotes || "-"} | SN Rusak: ${cleanDamagedSn || "-"}`, + metadata: { + salesOrderItemId, + serviceStatus, + serviceType: finalServiceType, + serviceNotes, + damagedSerialNumbers: cleanDamagedSn, + serviceFee: cleanFee, + returnShippingCost: cleanReturnShipping, + returnCourierName: cleanReturnCourier, + returnTrackingNumber: cleanReturnTracking, + servicePaymentStatus: finalPaymentStatus, + }, + }); + + if (newTotalCharge > 0 && finalPaymentStatus === "UNPAID") { + await dispatchNotification({ + type: "MONEY_IN", + title: `Tagihan Purna Jual / Ongkir Service: SO ${item.salesOrder.orderNumber}`, + message: `${user.name} mencatat tagihan service/pengiriman balik (${item.product.name} - ${item.salesOrder.customer?.name || "Customer"}) sebesar Rp ${newTotalCharge.toLocaleString("id-ID")} (Jasa: Rp ${cleanFee.toLocaleString("id-ID")}, Ongkir User: Rp ${cleanReturnShipping.toLocaleString("id-ID")}). Menunggu konfirmasi pembayaran Finance.`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "SALES"], + }); + } + + return NextResponse.json({ success: true, item: updated }); + } + + // Layanan Purna Jual: Klaim Ganti Unit Baru (Unit Replacement) selama Garansi + if (body.action === "RMA_REPLACE_UNIT") { + const { + salesOrderItemId, + replaceQty: inputReplaceQty, + replacementBatchId, + replacementNotes, + forceReplace, + damagedSerialNumbers, + replacementSerialNumbers, + damagedCondition, // HANYA "DAMAGED_UNUSABLE" atau "CANNIBALIZED" + salvagedParts, + returnShippingCost, + returnCourierName, + returnTrackingNumber, + } = body; + + if (!salesOrderItemId) { + return NextResponse.json({ error: "Item barang wajib dipilih" }, { status: 400 }); + } + + const item = await prisma.salesOrderItem.findUnique({ + where: { id: salesOrderItemId }, + include: { + salesOrder: true, + product: true, + }, + }); + + if (!item) { + return NextResponse.json({ error: "Item Sales Order tidak ditemukan" }, { status: 404 }); + } + + if (item.product.isService) { + return NextResponse.json({ error: "Produk jenis layanan tidak memiliki unit fisik untuk diganti" }, { status: 400 }); + } + + const replaceQty = parseInt(inputReplaceQty) || 1; + if (replaceQty <= 0) { + return NextResponse.json({ error: "Jumlah unit pengganti harus minimal 1" }, { status: 400 }); + } + + const alreadyReplaced = item.replacedQty || 0; + if (alreadyReplaced + replaceQty > item.quantity) { + return NextResponse.json( + { + error: `Total unit pengganti (${alreadyReplaced + replaceQty}) melebihi kuantitas pembelian awal (${item.quantity} unit).`, + }, + { status: 400 } + ); + } + + // Validasi masa garansi + const expDate = item.warrantyExpiry + ? new Date(item.warrantyExpiry) + : (() => { + const d = new Date(item.salesOrder.orderDate || item.salesOrder.createdAt); + d.setMonth(d.getMonth() + (item.salesOrder.warrantyMonths || 12)); + return d; + })(); + const isExpired = new Date() > expDate; + if (isExpired) { + const canOverrideExpired = ["ADMIN", "MANAGER"].includes(user.role); + if (!forceReplace || !canOverrideExpired) { + return NextResponse.json( + { + error: `Masa garansi untuk item ini telah berakhir pada ${expDate.toLocaleDateString("id-ID")}. Tukar unit garansi tidak berlaku — silakan gunakan layanan Jasa Service Berbayar (atau persetujuan khusus Manager/Admin).`, + }, + { status: 400 } + ); + } + } + + // Gudang Utama + const defaultWh = await prisma.warehouse.findFirst(); + if (!defaultWh) { + return NextResponse.json({ error: "Gudang Utama tidak ditemukan" }, { status: 400 }); + } + + // Cek stok fisik di Gudang Utama + const stockItem = await prisma.stockItem.findUnique({ + where: { + productId_warehouseId: { productId: item.productId, warehouseId: defaultWh.id }, + }, + }); + + if (!stockItem || stockItem.quantity < replaceQty) { + return NextResponse.json( + { + error: `Stok produk ${item.product.name} di ${defaultWh.name} tidak mencukupi untuk ganti unit (Tersedia: ${stockItem?.quantity || 0} unit, Dibutuhkan: ${replaceQty} unit).`, + }, + { status: 400 } + ); + } + + // Potong stok fisik Gudang Utama + await prisma.stockItem.update({ + where: { id: stockItem.id }, + data: { quantity: stockItem.quantity - replaceQty }, + }); + + // Potong alokasi batch PO jika dipilih atau FIFO + let batchDeductedNotes = ""; + if (replacementBatchId) { + const batch = await prisma.purchaseBatch.findUnique({ + where: { id: replacementBatchId }, + include: { purchaseOrder: true }, + }); + if (batch && batch.remainingQty >= replaceQty) { + await prisma.purchaseBatch.update({ + where: { id: batch.id }, + data: { remainingQty: { decrement: replaceQty } }, + }); + batchDeductedNotes = `[PO Pengganti: ${batch.poNumber} sisa ${batch.remainingQty - replaceQty}/${batch.initialQty}]`; + } else if (batch) { + const takeFromChosen = batch.remainingQty; + await prisma.purchaseBatch.update({ + where: { id: batch.id }, + data: { remainingQty: 0 }, + }); + batchDeductedNotes = `[PO Pengganti: ${batch.poNumber} diambil ${takeFromChosen}]`; + } + } else { + // FIFO deduction from available batches + const availableBatches = await prisma.purchaseBatch.findMany({ + where: { productId: item.productId, remainingQty: { gt: 0 } }, + orderBy: { receivedAt: "asc" }, + }); + let needed = replaceQty; + const takenBatches: string[] = []; + for (const b of availableBatches) { + if (needed <= 0) break; + const take = Math.min(needed, b.remainingQty); + await prisma.purchaseBatch.update({ + where: { id: b.id }, + data: { remainingQty: { decrement: take } }, + }); + needed -= take; + takenBatches.push(`${b.poNumber} (${take} unit)`); + } + if (takenBatches.length > 0) { + batchDeductedNotes = `[PO Pengganti FIFO: ${takenBatches.join(", ")}]`; + } + } + + const cleanReplSn = replacementSerialNumbers ? String(replacementSerialNumbers).trim() : null; + const cleanDamagedSn = damagedSerialNumbers ? String(damagedSerialNumbers).trim() : null; + + // Catat riwayat Mutasi Stok Keluar (OUT) + const fullNotes = `[Ganti Unit Garansi] Penggantian ${replaceQty} ${item.product.unit} baru untuk SO ${item.salesOrder.orderNumber} (${item.product.name}) ${batchDeductedNotes}. Alasan: ${replacementNotes || "Klaim kerusakan garansi"}${cleanDamagedSn ? ` | SN Rusak: ${cleanDamagedSn}` : ""}${cleanReplSn ? ` | SN Unit Pengganti: ${cleanReplSn}` : ""}`; + await prisma.stockMovement.create({ + data: { + productId: item.productId, + warehouseId: defaultWh.id, + type: "OUT", + outboundCategory: "GANTI_UNIT_GARANSI", + quantity: replaceQty, + referenceType: "SALES_ORDER", + referenceId: item.salesOrder.orderNumber, + companyName: item.salesOrder.companyName, + serialNumbers: cleanReplSn, + notes: fullNotes, + }, + }); + + const cleanReturnShipping = Math.max(0, parseFloat(returnShippingCost) || 0); + const cleanReturnCourier = returnCourierName ? String(returnCourierName).trim() : null; + const cleanReturnTracking = returnTrackingNumber ? String(returnTrackingNumber).trim() : null; + const finalDamagedCondition = + damagedCondition === "CANNIBALIZED" ? "CANNIBALIZED" : "DAMAGED_UNUSABLE"; + const cleanSalvagedParts = salvagedParts ? String(salvagedParts).trim() : null; + const replPayStatus = cleanReturnShipping > 0 ? "UNPAID" : "FREE"; + + // Update SalesOrderItem + const updatedItem = await prisma.salesOrderItem.update({ + where: { id: salesOrderItemId }, + data: { + serviceStatus: "REPLACED", + serviceType: "WARRANTY_REPLACEMENT", + serviceFee: 0, + returnShippingCost: cleanReturnShipping, + returnCourierName: cleanReturnCourier, + returnTrackingNumber: cleanReturnTracking, + servicePaymentStatus: replPayStatus, + replacedQty: alreadyReplaced + replaceQty, + replacedAt: new Date(), + replacementNotes: replacementNotes ? String(replacementNotes).trim() : item.replacementNotes, + damagedSerialNumbers: cleanDamagedSn || item.damagedSerialNumbers, + replacementSerialNumbers: cleanReplSn || item.replacementSerialNumbers, + }, + }); + + // Otomatis catat unit lama yang rusak ke Riwayat Device: HANYA Rusak Total (DAMAGED_UNUSABLE) atau Kanibalan (CANNIBALIZED) + const damagedSnTokens = cleanDamagedSn + ? Array.from(new Set(cleanDamagedSn.split(/[\n,;]+/).map((s) => s.trim()).filter(Boolean))) + : [`RETUR-${item.salesOrder.orderNumber}-${item.product.sku}`]; + const replDateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); + const replDevCount = await prisma.deviceRecord.count(); + for (let idx = 0; idx < damagedSnTokens.length; idx++) { + const sn = damagedSnTokens[idx]; + const existingRec = await prisma.deviceRecord.findFirst({ + where: { + serialNumber: sn, + productId: item.productId, + salesOrderId: item.salesOrderId, + }, + }); + const actionDesc = `Unit lama retur ganti unit garansi (Diganti unit baru${cleanReplSn ? ` SN: ${cleanReplSn}` : ""})`; + if (existingRec) { + await prisma.deviceRecord.update({ + where: { id: existingRec.id }, + data: { + condition: finalDamagedCondition, + serviceOrigin: "WARRANTY_REPLACE", + warrantyStatus: isExpired ? "OUT_OF_WARRANTY" : "IN_WARRANTY", + serviceFee: 0, + returnShippingCost: cleanReturnShipping, + returnCourierName: cleanReturnCourier, + returnTrackingNumber: cleanReturnTracking, + servicePaymentStatus: replPayStatus, + damageDescription: replacementNotes ? String(replacementNotes).trim() : "Klaim tukar unit garansi", + actionTaken: actionDesc, + salvagedParts: finalDamagedCondition === "CANNIBALIZED" ? cleanSalvagedParts : null, + recordedBy: user.name, + }, + }); + } else { + await prisma.deviceRecord.create({ + data: { + recordNumber: `DEV-${replDateStr}-${String(replDevCount + idx + 1).padStart(4, "0")}-${Math.floor( + 10 + Math.random() * 89 + )}`, + serialNumber: sn, + productId: item.productId, + customerId: item.salesOrder.customerId, + salesOrderId: item.salesOrderId, + salesOrderNumber: item.salesOrder.orderNumber, + companyName: item.salesOrder.companyName || "PT EnterpriseCore Utama", + condition: finalDamagedCondition, + serviceOrigin: "WARRANTY_REPLACE", + warrantyStatus: isExpired ? "OUT_OF_WARRANTY" : "IN_WARRANTY", + serviceFee: 0, + returnShippingCost: cleanReturnShipping, + returnCourierName: cleanReturnCourier, + returnTrackingNumber: cleanReturnTracking, + servicePaymentStatus: replPayStatus, + damageDescription: replacementNotes ? String(replacementNotes).trim() : "Klaim tukar unit garansi", + actionTaken: actionDesc, + salvagedParts: finalDamagedCondition === "CANNIBALIZED" ? cleanSalvagedParts : null, + recordedBy: user.name, + }, + }); + } + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE", + module: "SALES", + description: `[${user.role}] Klaim Garansi Ganti Unit SO ${item.salesOrder.orderNumber}: ${replaceQty} ${item.product.unit} ${item.product.name} dikeluarkan dari Gudang Utama. SN Rusak: ${cleanDamagedSn || "-"} | SN Pengganti: ${cleanReplSn || "-"}`, + metadata: { + salesOrderItemId, + replaceQty, + replacementNotes, + damagedSerialNumbers: cleanDamagedSn, + replacementSerialNumbers: cleanReplSn, + }, + }); + + await dispatchNotification({ + type: "STOCK_OUT", + title: `Ganti Unit Garansi: SO ${item.salesOrder.orderNumber}`, + message: `${replaceQty} ${item.product.unit} ${item.product.name} telah dikeluarkan dari ${defaultWh.name} untuk penggantian klaim garansi SO ${item.salesOrder.orderNumber}.`, + targetRoles: ["ADMIN", "MANAGER", "INVENTORY", "SALES"], + }); + + return NextResponse.json({ success: true, item: updatedItem }); + } + + // (UPDATE_SHIPPING sudah ditangani di blok atas agar pihak Gudang/INVENTORY bisa mengaksesnya) + + const { + customerId, + warehouseId: rawWhId, + notes, + items, + orderNumber: customOrderNumber, + invoiceNumber: customInvoiceNumber, + customerPoNumber, + companyName, + saleType: inputSaleType, + warrantyMonths: inputWarrantyMonths, + shippingCost: inputShippingCost, + courierName: inputCourierName, + trackingNumber: inputTrackingNumber, + shippingNotes: inputShippingNotes, + includeTax: inputIncludeTax, + taxRate: inputTaxRate, + } = body; + + const defaultWh = await prisma.warehouse.findFirst(); + const warehouseId = rawWhId || defaultWh?.id; + + const cleanSoCompany = (companyName || "").trim() || "PT EnterpriseCore Utama"; + const finalSaleType = inputSaleType === "MANAGED_SERVICE" ? "MANAGED_SERVICE" : "JUAL_PUTUS"; + const saleTypeLabel = finalSaleType === "MANAGED_SERVICE" ? "Jual Manage Service" : "Jual Putus"; + // Keamanan: Hanya Finance/Admin/Manager yang boleh input Pajak (PPN) dan Finance/Gudang/Admin/Manager yang boleh input Ongkir Customer + const canSetSoTax = ["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role); + const canSetSoShipping = ["ADMIN", "MANAGER", "ACCOUNTANT", "INVENTORY"].includes(user.role); + const shippingCost = canSetSoShipping ? Math.max(0, parseFloat(inputShippingCost) || 0) : 0; + const cleanCourierName = canSetSoShipping && inputCourierName ? String(inputCourierName).trim() : null; + const cleanTrackingNumber = canSetSoShipping && inputTrackingNumber ? String(inputTrackingNumber).trim() : null; + const cleanShippingNotes = canSetSoShipping && inputShippingNotes ? String(inputShippingNotes).trim() : null; + const includeTax = canSetSoTax && Boolean(inputIncludeTax); + const taxRate = includeTax ? Math.max(0, parseFloat(inputTaxRate) || 11) : 0; + + if (!customerId || !items || !items.length) { + return NextResponse.json( + { error: "Pelanggan dan minimal 1 item barang harus diisi" }, + { status: 400 } + ); + } + + let orderNumber = (customOrderNumber || customInvoiceNumber || "").trim(); + const finalInvoiceNumber = (customInvoiceNumber || "").trim() || orderNumber; + + if (orderNumber) { + const existingOrder = await prisma.salesOrder.findUnique({ where: { orderNumber } }); + if (existingOrder) { + return NextResponse.json( + { error: `Nomor SO / Invoice "${orderNumber}" sudah terdaftar. Gunakan nomor lain.` }, + { status: 400 } + ); + } + } else { + const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, ""); + const count = await prisma.salesOrder.count(); + orderNumber = `SO-${dateStr}-${String(count + 1).padStart(4, "0")}`; + } + + let totalAmount = 0; + let totalHpp = 0; + const orderItemsData = []; + + for (const item of items) { + const product = await prisma.product.findUnique({ + where: { id: item.productId }, + }); + + if (!product) { + return NextResponse.json( + { error: `Produk ID ${item.productId} tidak ditemukan` }, + { status: 404 } + ); + } + + const qty = parseInt(item.quantity); + if (isNaN(qty) || qty <= 0) { + return NextResponse.json( + { error: `Kuantitas produk ${product.name} harus lebih dari 0` }, + { status: 400 } + ); + } + const unitPrice = Math.max(0, parseFloat(item.unitPrice) || product.sellingPrice); + const subtotal = qty * unitPrice; + totalAmount += subtotal; + + // 1. Simpan / Perbarui Kesepakatan Harga Khusus Pelanggan (Customer-Specific Pricing) + await prisma.customerProductPrice.upsert({ + where: { + customerId_productId: { customerId, productId: product.id }, + }, + create: { + customerId, + productId: product.id, + specialPrice: unitPrice, + notes: `Harga disepakati pada SO ${orderNumber}`, + }, + update: { + specialPrice: unitPrice, + notes: `Harga diperbarui pada SO ${orderNumber}`, + }, + }); + + // 2. Alokasi Stok FIFO dari Batch PO Vendor yang tersedia + let allocatedQty = 0; + let itemTotalHpp = 0; + const batchAllocationsList: { + poSeqLabel: string; + poNumber: string; + purchaseBatchId?: string; + quantity: number; + unitCost: number; + subtotalCost: number; + remainingAfter: number; + initialQty: number; + }[] = []; + + if (!product.isService && warehouseId) { + // Cek stok fisik gudang + const stock = await prisma.stockItem.findUnique({ + where: { + productId_warehouseId: { productId: product.id, warehouseId }, + }, + }); + + if (!stock || stock.quantity < qty) { + return NextResponse.json( + { + error: `Stok ${product.name} tidak mencukupi di gudang terpilih (Tersedia: ${ + stock?.quantity || 0 + }). Silakan klik "+ Tambah PO Vendor (PO Ke-2)" pada baris barang untuk menambah pasokan PO baru.`, + }, + { status: 400 } + ); + } + } + + // Ambil seluruh batch PO Vendor produk ini + // A. Jika user memilih alokasi PO tertentu secara manual: + if (item.allocations && Array.isArray(item.allocations) && item.allocations.length > 0) { + for (let aIdx = 0; aIdx < item.allocations.length; aIdx++) { + const userAlloc = item.allocations[aIdx]; + if (!userAlloc.batchId || !userAlloc.quantity || userAlloc.quantity <= 0) continue; + if (allocatedQty >= qty) break; + + const batch = await prisma.purchaseBatch.findUnique({ + where: { id: userAlloc.batchId }, + }); + + if (batch && batch.remainingQty > 0) { + const needed = qty - allocatedQty; + const takeQty = Math.min(needed, userAlloc.quantity, batch.remainingQty); + const remainingAfter = batch.remainingQty - takeQty; + + batchAllocationsList.push({ + poSeqLabel: `PO Pilihan #${aIdx + 1}`, + poNumber: batch.poNumber, + purchaseBatchId: batch.id, + quantity: takeQty, + unitCost: batch.unitCost, + subtotalCost: takeQty * batch.unitCost, + remainingAfter, + initialQty: batch.initialQty, + }); + + allocatedQty += takeQty; + itemTotalHpp += takeQty * batch.unitCost; + + await prisma.purchaseBatch.update({ + where: { id: batch.id }, + data: { remainingQty: { decrement: takeQty } }, + }); + } + } + } + + // B. Alokasi otomatis FIFO jika belum terpenuhi: + if (allocatedQty < qty) { + const allProductBatches = await prisma.purchaseBatch.findMany({ + where: { + productId: product.id, + ...(!product.isService && warehouseId ? { warehouseId } : {}), + remainingQty: { gt: 0 }, + purchaseOrder: { status: { in: ["RECEIVED", "COMPLETED"] } }, + }, + orderBy: { receivedAt: "asc" }, + }); + + for (let bIdx = 0; bIdx < allProductBatches.length; bIdx++) { + const batch = allProductBatches[bIdx]; + if (batch.remainingQty <= 0) continue; + if (allocatedQty >= qty) break; + + const needed = qty - allocatedQty; + const takeQty = Math.min(needed, batch.remainingQty); + const remainingAfter = batch.remainingQty - takeQty; + + batchAllocationsList.push({ + poSeqLabel: `PO ke-${bIdx + 1}`, + poNumber: batch.poNumber, + purchaseBatchId: batch.id, + quantity: takeQty, + unitCost: batch.unitCost, + subtotalCost: takeQty * batch.unitCost, + remainingAfter, + initialQty: batch.initialQty, + }); + + allocatedQty += takeQty; + itemTotalHpp += takeQty * batch.unitCost; + + // Kurangi sisa unit batch PO Vendor tersebut + await prisma.purchaseBatch.update({ + where: { id: batch.id }, + data: { remainingQty: { decrement: takeQty } }, + }); + } + } + + // Jika ada sisa kuantitas yang belum tertutup batch PO Vendor (misal stok saldo awal manual atau layanan tanpa PO) + if (allocatedQty < qty) { + const remainingNeeded = qty - allocatedQty; + const fallbackCost = product.purchasePrice || 0; + if (!product.isService) { + batchAllocationsList.push({ + poSeqLabel: "Stok Awal", + poNumber: "STOK-AWAL", + quantity: remainingNeeded, + unitCost: fallbackCost, + subtotalCost: remainingNeeded * fallbackCost, + remainingAfter: 0, + initialQty: remainingNeeded, + }); + } + itemTotalHpp += remainingNeeded * fallbackCost; + } + + const batchNotesSummary = + batchAllocationsList.length > 0 + ? batchAllocationsList + .map((a) => + a.poNumber === "STOK-AWAL" + ? `Stok Awal: ${a.quantity} ${product.unit}` + : `${a.poSeqLabel} (${a.poNumber}): Terjual ${a.quantity} ${product.unit} [Sisa PO: ${a.remainingAfter}/${a.initialQty} ${product.unit}]` + ) + .join(" + ") + : product.isService + ? `Layanan / Non-Fisik (${qty} ${product.unit})` + : `Stok Reguler (${qty} ${product.unit})`; + + if (!product.isService && warehouseId) { + const stock = await prisma.stockItem.findUnique({ + where: { + productId_warehouseId: { productId: product.id, warehouseId }, + }, + }); + if (stock) { + // Potong stok fisik gudang + await prisma.stockItem.update({ + where: { id: stock.id }, + data: { quantity: stock.quantity - qty }, + }); + } + + const itemSerialNumbers = item.serialNumbers ? String(item.serialNumbers).trim() : null; + + // Catat Mutasi Stok Keluar (OUT) dengan rincian alokasi batch PO & tipe Jual Putus / Manage Service + await prisma.stockMovement.create({ + data: { + productId: product.id, + warehouseId, + type: "OUT", + outboundCategory: finalSaleType, + quantity: qty, + referenceType: "SALES_ORDER", + referenceId: orderNumber, + companyName: cleanSoCompany, + serialNumbers: itemSerialNumbers, + notes: `[${saleTypeLabel}] Pengurangan stok penjualan ${orderNumber} (${cleanSoCompany}) [Alokasi FIFO: ${batchNotesSummary}]${ + customerPoNumber ? ` (PO Cust: ${String(customerPoNumber).trim()})` : "" + }${itemSerialNumbers ? ` (SN: ${itemSerialNumbers})` : ""}`, + }, + }); + } + + totalHpp += itemTotalHpp; + const averageItemCost = Math.round(itemTotalHpp / qty); + + let itemWarrantyExpiry: Date | null = null; + if (!product.isService && finalSaleType === "JUAL_PUTUS") { + const exp = new Date(); + exp.setMonth(exp.getMonth() + (parseInt(inputWarrantyMonths) || 12)); + itemWarrantyExpiry = exp; + } + + const itemSerialNumbers = item.serialNumbers ? String(item.serialNumbers).trim() : null; + + orderItemsData.push({ + productId: product.id, + quantity: qty, + costPrice: averageItemCost, + unitPrice, + subtotal, + batchAllocationNotes: batchNotesSummary, + warrantyExpiry: itemWarrantyExpiry, + serviceStatus: !product.isService && finalSaleType === "JUAL_PUTUS" ? "NORMAL" : null, + serialNumbers: itemSerialNumbers, + batchAllocations: { + create: batchAllocationsList.map((b) => ({ + poNumber: b.poNumber, + purchaseBatchId: b.purchaseBatchId || null, + quantity: b.quantity, + unitCost: b.unitCost, + subtotalCost: b.subtotalCost, + })), + }, + }); + } + + const taxAmount = includeTax ? Math.round((totalAmount * taxRate) / 100) : 0; + const grandTotalAmount = totalAmount + shippingCost + taxAmount; + + const order = await prisma.salesOrder.create({ + data: { + orderNumber, + invoiceNumber: finalInvoiceNumber || orderNumber, + customerPoNumber: customerPoNumber ? String(customerPoNumber).trim() : null, + customerId, + companyName: cleanSoCompany, + saleType: finalSaleType, + warrantyMonths: parseInt(inputWarrantyMonths) || 12, + shippingCost, + courierName: cleanCourierName, + trackingNumber: cleanTrackingNumber, + shippingNotes: cleanShippingNotes, + taxRate, + taxAmount, + includeTax, + totalAmount: grandTotalAmount, + totalHpp, + notes, + status: "CONFIRMED", + paymentStatus: "UNPAID", + items: { + create: orderItemsData, + }, + }, + include: { + customer: true, + items: { + include: { + product: true, + }, + }, + }, + }); + + const arAcc = await getCompanyAccount("1101", cleanSoCompany); + const revAcc = await getCompanyAccount("4001", cleanSoCompany); + const vatAcc = taxAmount > 0 ? await getCompanyAccount("2101", cleanSoCompany) : null; + + if (arAcc) { + await prisma.account.update({ + where: { id: arAcc.id }, + data: { balance: { increment: grandTotalAmount } }, + }); + } + const salesRevenue = totalAmount + shippingCost; + if (revAcc) { + await prisma.account.update({ + where: { id: revAcc.id }, + data: { balance: { increment: salesRevenue } }, + }); + } + if (vatAcc && taxAmount > 0) { + await prisma.account.update({ + where: { id: vatAcc.id }, + data: { balance: { increment: taxAmount } }, + }); + } + + // 1. Otomatis catat Jurnal Penjualan (Piutang pada Pendapatan & PPN Keluaran) + if (arAcc && revAcc && grandTotalAmount > 0) { + const jCount = await prisma.journalEntry.count(); + const journalLines: { accountId: string; type: "DEBIT" | "CREDIT"; amount: number }[] = [ + { accountId: arAcc.id, type: "DEBIT", amount: grandTotalAmount }, + { accountId: revAcc.id, type: "CREDIT", amount: salesRevenue }, + ]; + if (vatAcc && taxAmount > 0) { + journalLines.push({ accountId: vatAcc.id, type: "CREDIT", amount: taxAmount }); + } + + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-SO-${String(jCount + 1).padStart(4, "0")}`, + description: `Tagihan Penjualan Sales Order / Invoice ${orderNumber} (${cleanSoCompany}) - ${order.customer.name}${includeTax ? ` (Inc. PPN ${taxRate}%)` : ""}`, + reference: orderNumber, + companyName: cleanSoCompany, + lines: { + create: journalLines, + }, + }, + }); + } + + // 2. Otomatis catat Jurnal HPP (Beban Pokok Penjualan pada Persediaan Barang Dagang) + if (totalHpp > 0) { + const hppAcc = await getCompanyAccount("5001", cleanSoCompany); + const invAcc = await getCompanyAccount("1201", cleanSoCompany); + + if (hppAcc) { + await prisma.account.update({ + where: { id: hppAcc.id }, + data: { balance: { increment: totalHpp } }, + }); + } + if (invAcc) { + await prisma.account.update({ + where: { id: invAcc.id }, + data: { balance: { decrement: totalHpp } }, + }); + } + + if (hppAcc && invAcc) { + const jCountHpp = await prisma.journalEntry.count(); + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-HPP-${String(jCountHpp + 1).padStart(4, "0")}`, + description: `Beban Pokok Penjualan (HPP) SO / Invoice ${orderNumber} (${cleanSoCompany}) - ${order.customer.name}`, + reference: orderNumber, + companyName: cleanSoCompany, + lines: { + create: [ + { accountId: hppAcc.id, type: "DEBIT", amount: totalHpp }, + { accountId: invAcc.id, type: "CREDIT", amount: totalHpp }, + ], + }, + }, + }); + } + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "CREATE_SALES_ORDER", + module: "SALES", + description: `[${user.role}] Membuat Sales Order baru ${orderNumber} senilai Rp ${totalAmount.toLocaleString("id-ID")}`, + metadata: { orderNumber, totalAmount, customerId }, + }); + + // Notifikasi barang keluar & order baru + await dispatchNotification({ + type: "STOCK_OUT", + title: `Sales Order Diterbitkan: ${orderNumber}`, + message: `Sales Order ${orderNumber} berhasil diterbitkan dengan nilai total Rp ${totalAmount.toLocaleString("id-ID")}. Stok barang otomatis dikeluarkan dari gudang.`, + targetRoles: ["ADMIN", "MANAGER", "INVENTORY", "SALES", "ACCOUNTANT"], + }); + + return NextResponse.json({ success: true, order }); + } catch (error: any) { + console.error("Sales 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", "SALES", "ACCOUNTANT", "INVENTORY"].includes(user.role)) { + return NextResponse.json( + { error: `Akses ditolak: Peran ${user.role} tidak memiliki wewenang mengubah status Sales Order.` }, + { status: 403 } + ); + } + + const body = await req.json(); + const { orderId, status, paymentStatus, paidAmount: inputPaidAmount } = body; + + const currentOrder = await prisma.salesOrder.findUnique({ + where: { id: orderId }, + include: { customer: true }, + }); + + if (!currentOrder) { + return NextResponse.json({ error: "Order tidak ditemukan" }, { status: 404 }); + } + + // Role check for payment update: Only ADMIN, MANAGER, ACCOUNTANT can verify payment + if ( + (paymentStatus && paymentStatus !== currentOrder.paymentStatus) || + inputPaidAmount !== undefined + ) { + if (!["ADMIN", "MANAGER", "ACCOUNTANT"].includes(user.role)) { + return NextResponse.json( + { + error: `Akses ditolak: Hanya peran Admin, Manager, atau Akuntan yang dapat memvalidasi pelunasan invoice.`, + }, + { status: 403 } + ); + } + } + + let finalPaymentStatus = paymentStatus || currentOrder.paymentStatus; + let finalPaidAmount = currentOrder.paidAmount || 0; + + if (inputPaidAmount !== undefined) { + const parsedAmount = Math.max(0, parseFloat(inputPaidAmount) || 0); + finalPaidAmount = parsedAmount; + if (finalPaidAmount >= currentOrder.totalAmount) { + finalPaymentStatus = "PAID"; + finalPaidAmount = currentOrder.totalAmount; + } else if (finalPaidAmount > 0) { + finalPaymentStatus = "PARTIAL"; + } else { + finalPaymentStatus = "UNPAID"; + } + } else if (paymentStatus === "PAID") { + finalPaidAmount = currentOrder.totalAmount; + finalPaymentStatus = "PAID"; + } else if (paymentStatus === "UNPAID") { + finalPaidAmount = 0; + finalPaymentStatus = "UNPAID"; + } + + const previousPaidAmount = currentOrder.paidAmount || 0; + const additionalPayment = Math.max(0, finalPaidAmount - previousPaidAmount); + + const updated = await prisma.salesOrder.update({ + where: { id: orderId }, + data: { + ...(status && { status }), + paymentStatus: finalPaymentStatus, + paidAmount: finalPaidAmount, + }, + }); + + // Catat kas/bank & piutang jika ada penambahan pembayaran + if (additionalPayment > 0) { + const soCompany = currentOrder.companyName || "PT EnterpriseCore Utama"; + const bankAcc = await getCompanyAccount("1002", soCompany); + const arAcc = await getCompanyAccount("1101", soCompany); + + if (arAcc) { + await prisma.account.update({ + where: { id: arAcc.id }, + data: { balance: { decrement: additionalPayment } }, + }); + } + if (bankAcc) { + await prisma.account.update({ + where: { id: bankAcc.id }, + data: { balance: { increment: additionalPayment } }, + }); + } + + if (bankAcc && arAcc) { + const jCount = await prisma.journalEntry.count(); + const isPartial = finalPaymentStatus === "PARTIAL"; + await prisma.journalEntry.create({ + data: { + entryNumber: `JV-IN-${String(jCount + 1).padStart(4, "0")}`, + description: `${isPartial ? "Pembayaran Sebagian" : "Pelunasan"} Tagihan SO ${currentOrder.orderNumber} (${soCompany}) - ${currentOrder.customer?.name || "Pelanggan"}${isPartial ? ` [Kurang Bayar: Rp ${(currentOrder.totalAmount - finalPaidAmount).toLocaleString("id-ID")}]` : ""}`, + reference: currentOrder.orderNumber, + companyName: soCompany, + lines: { + create: [ + { accountId: bankAcc.id, type: "DEBIT", amount: additionalPayment }, + { accountId: arAcc.id, type: "CREDIT", amount: additionalPayment }, + ], + }, + }, + }); + } + } + + // Notifikasi Pembayaran + if (finalPaymentStatus === "PAID" && currentOrder.paymentStatus !== "PAID") { + await dispatchNotification({ + type: "MONEY_IN", + title: `Pelunasan Invoice SO: ${currentOrder.orderNumber}`, + message: `Pembayaran lunas sebesar Rp ${currentOrder.totalAmount.toLocaleString("id-ID")} untuk pesanan ${currentOrder.orderNumber} telah terverifikasi dan masuk ke rekening kas/bank.`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "SALES"], + }); + } else if (finalPaymentStatus === "PARTIAL") { + const underpaidAmount = currentOrder.totalAmount - finalPaidAmount; + await dispatchNotification({ + type: "MONEY_IN", + title: `Peringatan Kurang Bayar SO: ${currentOrder.orderNumber}`, + message: `Pembayaran sebesar Rp ${finalPaidAmount.toLocaleString("id-ID")} telah diterima untuk pesanan ${currentOrder.orderNumber}. Terjadi KEKURANGAN PEMBAYARAN sebesar Rp ${underpaidAmount.toLocaleString("id-ID")} dari total tagihan Rp ${currentOrder.totalAmount.toLocaleString("id-ID")}.`, + targetRoles: ["ADMIN", "MANAGER", "ACCOUNTANT", "SALES"], + }); + } + + await logAudit({ + userId: user.id, + userName: user.name, + action: "UPDATE_SALES_ORDER", + module: "SALES", + description: `[${user.role}] Mengubah status SO ${currentOrder.orderNumber}: Status=${status || currentOrder.status}, Payment=${finalPaymentStatus} (Terbayar: Rp ${finalPaidAmount.toLocaleString("id-ID")}/${currentOrder.totalAmount.toLocaleString("id-ID")})`, + metadata: { orderId, status, paymentStatus: finalPaymentStatus, paidAmount: finalPaidAmount }, + }); + + return NextResponse.json({ success: true, order: updated }); + } catch (error: any) { + console.error("Sales 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", "SALES"].includes(user.role)) { + return NextResponse.json( + { error: "Akses ditolak: Hanya Superadmin (ADMIN), Manager, atau Tim Penjualan yang memiliki wewenang menghapus Sales Order." }, + { status: 403 } + ); + } + + const { searchParams } = new URL(req.url); + const id = searchParams.get("id"); + if (!id) { + return NextResponse.json({ error: "ID pesanan penjualan wajib disertakan" }, { status: 400 }); + } + + const order = await prisma.salesOrder.findFirst({ + where: { OR: [{ id }, { orderNumber: id }] }, + include: { items: true }, + }); + + if (!order) { + return NextResponse.json({ error: "Pesanan penjualan tidak ditemukan" }, { status: 404 }); + } + + // Bersihkan alokasi batch jika ada + for (const item of order.items) { + await prisma.salesItemBatchAllocation.deleteMany({ + where: { salesOrderItemId: item.id }, + }); + } + + // Bersihkan mutasi stok dan jurnal terkait SO ini + await prisma.stockMovement.deleteMany({ + where: { referenceType: "SALES_ORDER", referenceId: order.orderNumber }, + }); + + const entries = await prisma.journalEntry.findMany({ + where: { reference: order.orderNumber }, + select: { id: true }, + }); + for (const entry of entries) { + await prisma.journalLine.deleteMany({ where: { journalEntryId: entry.id } }); + await prisma.journalEntry.delete({ where: { id: entry.id } }); + } + + await prisma.salesOrderItem.deleteMany({ where: { salesOrderId: order.id } }); + await prisma.salesOrder.delete({ where: { id: order.id } }); + + await logAudit({ + userId: user.id, + userName: user.name, + action: "DELETE", + module: "SALES", + description: `[${user.role}] Menghapus Sales Order ${order.orderNumber} senilai Rp ${order.totalAmount.toLocaleString("id-ID")} secara permanen`, + metadata: { orderId: order.id, orderNumber: order.orderNumber }, + }); + + return NextResponse.json({ + success: true, + message: `Sales Order ${order.orderNumber} berhasil dihapus.`, + }); + } catch (error: any) { + console.error("Sales DELETE error:", error); + return NextResponse.json({ error: error.message }, { status: 500 }); + } +} diff --git a/src/app/api/settings/backup/route.ts b/src/app/api/settings/backup/route.ts new file mode 100644 index 0000000..aa7f180 --- /dev/null +++ b/src/app/api/settings/backup/route.ts @@ -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(() => {}); + } + } +} diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.ts new file mode 100644 index 0000000..7d6369b --- /dev/null +++ b/src/app/api/settings/route.ts @@ -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 = {}; + 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 = `🔔 Tes Notifikasi EnterpriseCore ERP\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 }); + } +} diff --git a/src/app/api/users/route.ts b/src/app/api/users/route.ts new file mode 100644 index 0000000..e9c5800 --- /dev/null +++ b/src/app/api/users/route.ts @@ -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 }); + } +} diff --git a/src/app/finance/page.tsx b/src/app/finance/page.tsx new file mode 100644 index 0000000..8be435d --- /dev/null +++ b/src/app/finance/page.tsx @@ -0,0 +1,2973 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { AppShell } from "@/components/AppShell"; +import { Modal } from "@/components/Modal"; +import { CurrencyInput } from "@/components/CurrencyInput"; +import { formatRupiah, formatDateTime, exportToCSV, escapeHtml } from "@/lib/utils"; +import { + Plus, + ArrowRightLeft, + BookOpen, + PieChart, + Landmark, + Lock, + Calculator, + Utensils, + CalendarCheck, + UserPlus, + Briefcase, + FileText, + Printer, + Building2, + CheckCircle2, + Pencil, + Download, + Trash2, + BarChart3, +} from "lucide-react"; +import { FinancialChart } from "@/components/FinancialChart"; + +const DEFAULT_POSITIONS = [ + "Staf Operasional", + "Teknisi Lapangan", + "Driver & Logistik", + "Admin Gudang", + "Marketing & Sales", + "Staf Keuangan", + "Supervisor", +]; + +const DEFAULT_COMPANIES = ["PT EnterpriseCore Utama"]; + +const MONTHS_ID = [ + "Januari", + "Februari", + "Maret", + "April", + "Mei", + "Juni", + "Juli", + "Agustus", + "September", + "Oktober", + "November", + "Desember", +]; + +const YEARS_LIST = ["2024", "2025", "2026", "2027", "2028", "2029", "2030"]; + +export default function FinancePage() { + const [currentUser, setCurrentUser] = useState(null); + const [accounts, setAccounts] = useState([]); + const [journalEntries, setJournalEntries] = useState([]); + const [payrollRecords, setPayrollRecords] = useState([]); + const [payrollEmployees, setPayrollEmployees] = useState([]); + const [arList, setArList] = useState([]); + const [apList, setApList] = useState([]); + const [positions, setPositions] = useState(DEFAULT_POSITIONS); + const [companies, setCompanies] = useState(DEFAULT_COMPANIES); + const [selectedCompanyFilter, setSelectedCompanyFilter] = useState("ALL"); + const [loading, setLoading] = useState(true); + const [activeTab, setActiveTab] = useState< + "reports" | "payroll" | "coa" | "journal" | "companies" + >("reports"); + + const switchFinanceTab = (tab: "reports" | "payroll" | "coa" | "journal" | "companies") => { + setActiveTab(tab); + if (typeof window !== "undefined") { + sessionStorage.setItem("erp_finance_tab", tab); + window.dispatchEvent( + new CustomEvent("erp:finance-tab-sync", { detail: { tab } }) + ); + } + }; + + // Modal Tambah / Edit Kode Akun & Bank (COA) + const [isAccountModalOpen, setIsAccountModalOpen] = useState(false); + const [editingAccount, setEditingAccount] = useState(null); + const [accCode, setAccCode] = useState(""); + const [accName, setAccName] = useState(""); + const [accType, setAccType] = useState("ASSET"); + const [accCompany, setAccCompany] = useState("PT EnterpriseCore Utama"); + const [accBalance, setAccBalance] = useState(0); + const [accSubmitting, setAccSubmitting] = useState(false); + const [accError, setAccError] = useState(null); + + // Journal Modal State + const [isModalOpen, setIsModalOpen] = useState(false); + const [submitting, setSubmitting] = useState(false); + const [formError, setFormError] = useState(null); + + // Journal Entry Form + const [description, setDescription] = useState(""); + const [reference, setReference] = useState(""); + const [debitAccountId, setDebitAccountId] = useState(""); + const [creditAccountId, setCreditAccountId] = useState(""); + const [amount, setAmount] = useState(""); + + // Payroll & Meal Allowance Calculator Modal State + const [isPayrollOpen, setIsPayrollOpen] = useState(false); + const [editingPayroll, setEditingPayroll] = useState(null); + const [payrollSubmitting, setPayrollSubmitting] = useState(false); + const [payrollError, setPayrollError] = useState(null); + + // Slip Gaji (Payslip) Preview & Print Modal State + const [selectedSlip, setSelectedSlip] = useState(null); + + // Mode Input PT (Perusahaan) pada Payroll + const [companyInputMode, setCompanyInputMode] = useState<"SELECT" | "NEW">("SELECT"); + const [payrollCompany, setPayrollCompany] = useState("PT EnterpriseCore Utama"); + const [newCompanyName, setNewCompanyName] = useState(""); + + // Mode Input Karyawan: jika sudah ada data payroll tersimpan, otomatis pakai Dropdown ("SELECT"), jika belum ada pakai "NEW" + const [employeeInputMode, setEmployeeInputMode] = useState<"SELECT" | "NEW">("NEW"); + const [employeeName, setEmployeeName] = useState(""); + + // Mode Input Jabatan (berbeda dari RBAC): bisa pilih dari Dropdown atau tambah Jabatan baru + const [positionInputMode, setPositionInputMode] = useState<"SELECT" | "NEW">("SELECT"); + const [employeeRole, setEmployeeRole] = useState("Staf Operasional"); + const [newPositionName, setNewPositionName] = useState(""); + + // Dropdown Periode Bulan & Tahun + const now = new Date(); + const [periodMonth, setPeriodMonth] = useState(MONTHS_ID[now.getMonth()] || "November"); + const [periodYear, setPeriodYear] = useState(String(now.getFullYear() || "2026")); + + const [workDays, setWorkDays] = useState(22); + const [absentDays, setAbsentDays] = useState(0); + const [lateCount, setLateCount] = useState(0); + const [baseSalary, setBaseSalary] = useState(5000000); + const [dailyMealRate, setDailyMealRate] = useState(35000); + const [transportAllowance, setTransportAllowance] = useState(500000); + const [deductionPerAbsent, setDeductionPerAbsent] = useState(150000); + const [paymentAccountId, setPaymentAccountId] = useState(""); + const [payrollNotes, setPayrollNotes] = useState(""); + const [showChart, setShowChart] = useState(false); + const [chartData, setChartData] = useState(null); + + const loadData = async () => { + try { + const [meRes, res, dashRes] = await Promise.all([ + fetch("/api/auth/me"), + fetch("/api/finance"), + fetch("/api/dashboard"), + ]); + if (meRes.ok) { + const meJson = await meRes.json(); + setCurrentUser(meJson.user); + } + if (dashRes.ok) { + const dashJson = await dashRes.json(); + setChartData(dashJson); + } + + if (res.ok) { + const json = await res.json(); + setAccounts(json.accounts || []); + setJournalEntries(json.journalEntries || []); + setPayrollRecords(json.payrollRecords || []); + setArList(json.arList || []); + setApList(json.apList || []); + + const savedEmps = json.payrollEmployees || []; + setPayrollEmployees(savedEmps); + + const mergedPositions = Array.from( + new Set([...DEFAULT_POSITIONS, ...(json.positions || [])]) + ); + setPositions(mergedPositions); + + const mergedCompanies = + Array.isArray(json.companies) && json.companies.length > 0 + ? Array.from(new Set(json.companies)) + : DEFAULT_COMPANIES; + setCompanies(mergedCompanies); + if (typeof window !== "undefined") { + window.dispatchEvent( + new CustomEvent("erp:company-sync", { + detail: { companies: mergedCompanies }, + }) + ); + } + + if (savedEmps.length > 0) { + setEmployeeInputMode("SELECT"); + setEmployeeName(savedEmps[0].name); + setPayrollCompany(savedEmps[0].companyName || mergedCompanies[0]); + setEmployeeRole(savedEmps[0].position || mergedPositions[0]); + setBaseSalary(savedEmps[0].baseSalary || 5000000); + setDailyMealRate(savedEmps[0].dailyMealRate || 35000); + } else { + setEmployeeInputMode("NEW"); + setEmployeeName(""); + setPayrollCompany(mergedCompanies[0]); + setEmployeeRole(mergedPositions[0]); + } + + if (json.accounts?.length >= 2) { + setDebitAccountId(json.accounts[0].id); + setCreditAccountId(json.accounts[1].id); + const cashAcc = json.accounts.find( + (a: any) => a.code === "1001" || a.code === "1002" + ); + if (cashAcc) setPaymentAccountId(cashAcc.id); + } + } + } catch (err) { + console.error(err); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + if (typeof window !== "undefined") { + const savedPt = localStorage.getItem("erp_selected_pt"); + if (savedPt) { + setSelectedCompanyFilter(savedPt); + } + const savedTab = sessionStorage.getItem("erp_finance_tab"); + if ( + savedTab === "reports" || + savedTab === "payroll" || + savedTab === "coa" || + savedTab === "journal" || + savedTab === "companies" + ) { + setActiveTab(savedTab); + } + } + loadData(); + + const handleSidebarTabChange = (e: any) => { + const t = e?.detail?.tab; + if ( + t === "reports" || + t === "payroll" || + t === "coa" || + t === "journal" || + t === "companies" + ) { + setActiveTab(t); + } + }; + + const handleTopNavbarPtChange = (e: any) => { + if (e?.detail?.selectedCompany) { + setSelectedCompanyFilter(e.detail.selectedCompany); + if (e.detail.selectedCompany !== "ALL") { + setPayrollCompany(e.detail.selectedCompany); + setAccCompany(e.detail.selectedCompany); + } + } + if (Array.isArray(e?.detail?.companies)) { + setCompanies(e.detail.companies); + if (e?.detail?.selectedCompany === "ALL" && e.detail.companies.length > 0) { + setPayrollCompany(e.detail.companies[0]); + setAccCompany(e.detail.companies[0]); + } + } + if (e?.detail?.deleted) { + loadData(); + } + }; + + window.addEventListener("erp:finance-tab", handleSidebarTabChange); + window.addEventListener("erp:company-changed", handleTopNavbarPtChange); + return () => { + window.removeEventListener("erp:finance-tab", handleSidebarTabChange); + window.removeEventListener("erp:company-changed", handleTopNavbarPtChange); + }; + }, []); + + const canCreateJournal = ["ADMIN", "ACCOUNTANT"].includes(currentUser?.role); + + // Filter berdasarkan PT yang dipilih (jika bukan "ALL") + const filteredPayrollRecords = + selectedCompanyFilter === "ALL" + ? payrollRecords + : payrollRecords.filter( + (r) => (r.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter + ); + + const filteredAccounts = + selectedCompanyFilter === "ALL" + ? accounts + : accounts.filter( + (a) => (a.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter + ); + + const filteredJournalEntries = + selectedCompanyFilter === "ALL" + ? journalEntries + : journalEntries.filter( + (j) => + (j.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter || + j.lines?.some((l: any) => l.account?.companyName === selectedCompanyFilter) + ); + + const totalAssets = filteredAccounts + .filter((a) => a.type === "ASSET") + .reduce((sum, a) => sum + a.balance, 0); + + const totalLiabilities = filteredAccounts + .filter((a) => a.type === "LIABILITY") + .reduce((sum, a) => sum + a.balance, 0); + + const totalEquity = filteredAccounts + .filter((a) => a.type === "EQUITY") + .reduce((sum, a) => sum + a.balance, 0); + + const totalRevenue = filteredAccounts + .filter((a) => a.type === "REVENUE") + .reduce((sum, a) => sum + a.balance, 0); + + const totalCogs = filteredAccounts + .filter((a) => a.type === "EXPENSE" && String(a.code || "").startsWith("5")) + .reduce((sum, a) => sum + a.balance, 0); + + const totalOpex = filteredAccounts + .filter((a) => a.type === "EXPENSE" && !String(a.code || "").startsWith("5")) + .reduce((sum, a) => sum + a.balance, 0); + + const totalExpenses = totalCogs + totalOpex; + const grossProfit = totalRevenue - totalCogs; + const netProfit = totalRevenue - totalExpenses; + const totalLiabAndEquity = totalLiabilities + totalEquity + netProfit; + const isBalanceSheetBalanced = Math.abs(totalAssets - totalLiabAndEquity) < 1; + + const filteredArList = + selectedCompanyFilter === "ALL" + ? arList + : arList.filter((x) => (x.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter); + + const filteredApList = + selectedCompanyFilter === "ALL" + ? apList + : apList.filter((x) => (x.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter); + + const totalArRemaining = filteredArList.reduce((s, x) => s + (x.remaining || 0), 0); + const totalApRemaining = filteredApList.reduce((s, x) => s + (x.remaining || 0), 0); + + const handleExportFinancialReport = () => { + const labelPt = selectedCompanyFilter === "ALL" ? "Semua_PT" : selectedCompanyFilter.replace(/\s+/g, "_"); + const headers = ["Bagian", "Kode / Referensi", "Akun / Keterangan", "Entitas PT", "Nominal (Rp)"]; + const rows: (string | number)[][] = [ + ["LABA RUGI", "-", "Total Pendapatan", selectedCompanyFilter, totalRevenue], + ["LABA RUGI", "5xxx", "Beban Pokok Penjualan (HPP)", selectedCompanyFilter, -totalCogs], + ["LABA RUGI", "-", "LABA KOTOR", selectedCompanyFilter, grossProfit], + ["LABA RUGI", "6xxx", "Beban Operasional & Gaji", selectedCompanyFilter, -totalOpex], + ["LABA RUGI", "-", "LABA / RUGI BERSIH BERJALAN", selectedCompanyFilter, netProfit], + ...filteredAccounts + .filter((a) => ["ASSET", "LIABILITY", "EQUITY"].includes(a.type)) + .map((a) => [ + `NERACA - ${a.type}`, + a.code, + a.name, + a.companyName || "PT EnterpriseCore Utama", + a.balance, + ]), + ["NERACA - TOTAL", "-", "TOTAL ASET", selectedCompanyFilter, totalAssets], + ["NERACA - TOTAL", "-", "TOTAL KEWAJIBAN + EKUITAS + LABA BERJALAN", selectedCompanyFilter, totalLiabAndEquity], + ...filteredArList.map((r) => [ + "PIUTANG CUSTOMER (AR)", + r.number, + `${r.counterparty} (${r.ageDays} hari)`, + r.companyName, + r.remaining, + ]), + ...filteredApList.map((p) => [ + "HUTANG VENDOR (AP)", + p.number, + `${p.counterparty} (${p.ageDays} hari)`, + p.companyName, + p.remaining, + ]), + ]; + exportToCSV( + `Laporan_Keuangan_${labelPt}_${new Date().toISOString().slice(0, 10)}.csv`, + headers, + rows + ); + }; + + // Live Payroll Calculator Values + const calculatedMealTotal = (Number(workDays) || 0) * (Number(dailyMealRate) || 0); + const calculatedAbsenceDeduction = + (Number(absentDays) || 0) * (Number(deductionPerAbsent) || 0) + + (Number(lateCount) || 0) * 25000; + const calculatedNetSalary = Math.max( + 0, + (Number(baseSalary) || 0) + + calculatedMealTotal + + (Number(transportAllowance) || 0) - + calculatedAbsenceDeduction + ); + + const totalPayrollDisbursed = filteredPayrollRecords.reduce((s, r) => s + r.netSalary, 0); + const totalMealDisbursed = filteredPayrollRecords.reduce( + (s, r) => s + r.totalMealAllowance, + 0 + ); + + const handleAddCompany = async () => { + const cleanComp = newCompanyName.trim(); + if (!cleanComp) return; + + const updatedList = companies.includes(cleanComp) + ? companies + : [...companies, cleanComp]; + + setCompanies(updatedList); + setPayrollCompany(cleanComp); + setAccCompany(cleanComp); + setSelectedCompanyFilter(cleanComp); + setNewCompanyName(""); + setCompanyInputMode("SELECT"); + + if (typeof window !== "undefined") { + localStorage.setItem("erp_selected_pt", cleanComp); + window.dispatchEvent( + new CustomEvent("erp:company-sync", { + detail: { companies: updatedList, selectedCompany: cleanComp }, + }) + ); + } + + try { + await fetch("/api/auth/me", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: "ADD_COMPANY", companyName: cleanComp }), + }); + } catch (e) { + console.error(e); + } + }; + + const handleDeleteCompanyItem = async (targetComp: string) => { + if (currentUser?.role !== "ADMIN") { + alert( + "Akses ditolak: Hanya Super Admin yang dapat menghapus Entitas PT. Selain Super Admin hanya dapat melihat (view) dan menambah (add) 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 Entitas PT"); + return; + } + + const updatedList = Array.isArray(data.companies) ? data.companies : companies; + setCompanies(updatedList); + if (selectedCompanyFilter === targetComp) { + setSelectedCompanyFilter("ALL"); + } + if (typeof window !== "undefined") { + localStorage.setItem("erp_selected_pt", "ALL"); + window.dispatchEvent( + new CustomEvent("erp:company-sync", { + detail: { companies: updatedList, selectedCompany: "ALL" }, + }) + ); + } + await loadData(); + } catch (e) { + console.error(e); + } + }; + + const handleAddPosition = async () => { + const cleanPos = newPositionName.trim(); + if (!cleanPos) return; + + if (!positions.includes(cleanPos)) { + setPositions([...positions, cleanPos]); + } + setEmployeeRole(cleanPos); + setNewPositionName(""); + setPositionInputMode("SELECT"); + + try { + await fetch("/api/finance", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: "ADD_POSITION", position: cleanPos }), + }); + } catch (e) { + console.error(e); + } + }; + + const openAddAccountModal = (defaultType = "ASSET", defaultCompany?: string) => { + setEditingAccount(null); + setAccError(null); + // Suggest next bank code if ASSET + const bankCodes = accounts + .filter((a) => a.code.startsWith("10")) + .map((a) => parseInt(a.code, 10)) + .filter((n) => !isNaN(n)); + const nextCode = + bankCodes.length > 0 ? String(Math.max(...bankCodes) + 1) : "1005"; + + setAccCode(defaultType === "ASSET" ? nextCode : ""); + setAccName(""); + setAccType(defaultType); + setAccCompany( + defaultCompany || + (selectedCompanyFilter !== "ALL" + ? selectedCompanyFilter + : companies[0] || "PT EnterpriseCore Utama") + ); + setAccBalance(0); + setIsAccountModalOpen(true); + }; + + const openEditAccountModal = (acc: any) => { + setEditingAccount(acc); + setAccError(null); + setAccCode(acc.code); + setAccName(acc.name); + setAccType(acc.type || "ASSET"); + setAccCompany(acc.companyName || "PT EnterpriseCore Utama"); + setAccBalance(acc.balance ?? 0); + setIsAccountModalOpen(true); + }; + + const handleSaveAccount = async (e: React.FormEvent) => { + e.preventDefault(); + setAccSubmitting(true); + setAccError(null); + + try { + const res = await fetch("/api/finance", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + action: editingAccount ? "UPDATE_ACCOUNT" : "CREATE_ACCOUNT", + id: editingAccount?.id, + code: accCode, + name: accName, + type: accType, + companyName: accCompany, + balance: accBalance, + }), + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + setIsAccountModalOpen(false); + await loadData(); + if (data.account?.id) { + setPaymentAccountId(data.account.id); + } + } catch (err: any) { + setAccError(err.message); + } finally { + setAccSubmitting(false); + } + }; + + const handleDeleteAccount = async (acc: any) => { + if (currentUser?.role !== "ADMIN") return; + try { + const res = await fetch("/api/finance", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + action: "DELETE_ACCOUNT", + id: acc.id, + }), + }); + const data = await res.json(); + if (!res.ok) { + alert(data.error || "Gagal menghapus akun"); + return; + } + await loadData(); + } catch (err) { + console.error(err); + } + }; + + const handleDeleteJournal = async (je: any) => { + if (currentUser?.role !== "ADMIN") return; + try { + const res = await fetch("/api/finance", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + action: "DELETE_JOURNAL", + id: je.id, + }), + }); + const data = await res.json(); + if (!res.ok) { + alert(data.error || "Gagal menghapus jurnal"); + return; + } + await loadData(); + } catch (err) { + console.error(err); + } + }; + + const handleCreateJournal = async (e: React.FormEvent) => { + e.preventDefault(); + setSubmitting(true); + setFormError(null); + + if (debitAccountId === creditAccountId) { + setFormError("Akun Debit dan Akun Kredit tidak boleh sama"); + setSubmitting(false); + return; + } + + try { + const res = await fetch("/api/finance", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + description, + reference, + debitAccountId, + creditAccountId, + amount, + }), + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + setIsModalOpen(false); + setDescription(""); + setReference(""); + setAmount(""); + loadData(); + } catch (err: any) { + setFormError(err.message); + } finally { + setSubmitting(false); + } + }; + + const openEditPayrollModal = (pr: any) => { + if (currentUser?.role !== "ADMIN") return; + setEditingPayroll(pr); + setPayrollError(null); + setCompanyInputMode("SELECT"); + setPayrollCompany(pr.companyName || "PT EnterpriseCore Utama"); + setEmployeeInputMode("NEW"); + setEmployeeName(pr.employeeName || ""); + setPositionInputMode("SELECT"); + setEmployeeRole(pr.role || "Staf Operasional"); + + const parts = (pr.period || "").split(" "); + if (parts.length >= 2) { + setPeriodMonth(parts[0]); + setPeriodYear(parts[1]); + } + setWorkDays(pr.workDays ?? 22); + setAbsentDays(pr.absentDays ?? 0); + setLateCount(pr.lateCount ?? 0); + setBaseSalary(pr.baseSalary ?? 5000000); + setDailyMealRate(pr.dailyMealRate ?? 35000); + setTransportAllowance(pr.transportAllowance ?? 0); + setPayrollNotes(pr.notes || ""); + + if (pr.paymentAccountName) { + const codeMatch = pr.paymentAccountName.match(/\[([^\]]+)\]/); + const matchedAcc = accounts.find( + (a) => + (codeMatch && a.code === codeMatch[1]) || + `[${a.code}] ${a.name}` === pr.paymentAccountName + ); + if (matchedAcc) { + setPaymentAccountId(matchedAcc.id); + } + } + + setIsPayrollOpen(true); + }; + + const handleDeletePayroll = async (pr: any) => { + if (currentUser?.role !== "ADMIN") { + alert( + "Akses ditolak: Hanya Admin yang dapat menghapus Slip Gaji. Selain Admin hanya dapat melihat, mencetak, dan menambah Slip Gaji." + ); + return; + } + + try { + const res = await fetch("/api/finance", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + action: "DELETE_PAYROLL", + id: pr.id, + }), + }); + const data = await res.json(); + if (!res.ok) { + alert(data.error || "Gagal menghapus Slip Gaji"); + return; + } + if (selectedSlip?.id === pr.id) { + setSelectedSlip(null); + } + await loadData(); + } catch (err) { + console.error(err); + } + }; + + const handleCreatePayroll = async (e: React.FormEvent) => { + e.preventDefault(); + setPayrollSubmitting(true); + setPayrollError(null); + + const finalCompany = + companyInputMode === "NEW" && newCompanyName.trim() + ? newCompanyName.trim() + : payrollCompany; + + const finalRole = + positionInputMode === "NEW" && newPositionName.trim() + ? newPositionName.trim() + : employeeRole; + const fullPeriod = `${periodMonth} ${periodYear}`; + + try { + const res = await fetch("/api/finance", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + action: editingPayroll ? "UPDATE_PAYROLL" : "CREATE_PAYROLL", + id: editingPayroll?.id, + companyName: finalCompany, + employeeName, + role: finalRole, + period: fullPeriod, + workDays, + absentDays, + lateCount, + baseSalary, + dailyMealRate, + transportAllowance, + absenceDeduction: calculatedAbsenceDeduction, + paymentAccountId, + notes: payrollNotes, + }), + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + setIsPayrollOpen(false); + setEditingPayroll(null); + setNewPositionName(""); + setPositionInputMode("SELECT"); + setNewCompanyName(""); + setCompanyInputMode("SELECT"); + setPayrollNotes(""); + await loadData(); + + // Langsung tampilkan Slip Gaji yang baru saja dibuat/diedit! + if (data.payroll) { + setSelectedSlip(data.payroll); + } + } catch (err: any) { + setPayrollError(err.message); + } finally { + setPayrollSubmitting(false); + } + }; + + const handlePrintSlip = (slip: any) => { + const grossTotal = + (Number(slip.baseSalary) || 0) + + (Number(slip.totalMealAllowance) || 0) + + (Number(slip.transportAllowance) || 0); + + const printWindow = window.open("", "_blank", "width=800,height=700"); + if (!printWindow) return; + + const ptName = escapeHtml(slip.companyName || "PT EnterpriseCore Utama"); + const bankLabel = escapeHtml(slip.paymentAccountName || "Rekening Bank / Kas Perusahaan"); + const empName = escapeHtml(slip.employeeName); + const empRole = escapeHtml(slip.role); + const empPeriod = escapeHtml(slip.period); + const slipNo = escapeHtml(slip.payrollNumber); + + const html = ` + + + + Slip Gaji - ${empName} (${empPeriod}) - ${ptName} + + + +
+
+
${ptName}
+
Dokumen Resmi Slip Gaji, Uang Makan & Kehadiran Karyawan
+
Sumber Pembayaran: ${bankLabel}
+
+
+
LUNAS (PAID)
+
No: ${slipNo}
+
+
+ +
+
+
Entitas PT: ${ptName}
+
Nama Karyawan: ${empName}
+
Jabatan: ${empRole}
+
Periode Gaji: ${empPeriod}
+
+
+
Hari Hadir (Masuk): ${Number(slip.workDays) || 0} Hari
+
Ketidakhadiran (Absen): ${Number(slip.absentDays) || 0} Hari
+
Frekuensi Terlambat: ${Number(slip.lateCount) || 0} Kali
+
Rekening Sumber: ${bankLabel}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Komponen Penerimaan & PotonganKeterangan PerhitunganNominal (Rp)
Gaji Pokok BulananGaji tetap periode ${empPeriod}${formatRupiah(slip.baseSalary)}
Tunjangan Uang Makan Kehadiran${Number(slip.workDays) || 0} Hari Hadir × ${formatRupiah(slip.dailyMealRate)} / hari+${formatRupiah(slip.totalMealAllowance)}
Tunjangan Transport / LemburTunjangan operasional tambahan+${formatRupiah(slip.transportAllowance)}
Total Penerimaan Kotor (Gross Income)${formatRupiah(grossTotal)}
Potongan Absen & KeterlambatanAbsen: ${Number(slip.absentDays) || 0} hari | Terlambat: ${Number(slip.lateCount) || 0}x-${formatRupiah(slip.absenceDeduction)}
+ +
+ TOTAL GAJI BERSIH DITERIMA (TAKE HOME PAY) + ${formatRupiah(slip.netSalary)} +
+ +
+
+
Disetujui Oleh,
+
Finance ${ptName}
+
+
+
Diterima Oleh,
+
${empName}
+
+
+ + + + `; + + printWindow.document.write(html); + printWindow.document.close(); + }; + + const cashBankAccounts = accounts.filter( + (a) => + a.type === "ASSET" && + (a.code.startsWith("10") || + a.name.toLowerCase().includes("kas") || + a.name.toLowerCase().includes("bank") || + a.name.toLowerCase().includes("rekening") || + a.name.toLowerCase().includes("bca") || + a.name.toLowerCase().includes("mandiri") || + a.name.toLowerCase().includes("bri") || + a.name.toLowerCase().includes("bni")) + ); + + // Urutkan agar rekening bank milik PT yang sedang dipilih muncul paling atas + const sortedCashBankAccounts = [...(cashBankAccounts.length > 0 ? cashBankAccounts : accounts)].sort( + (a, b) => { + const aMatch = (a.companyName || "PT EnterpriseCore Utama") === payrollCompany ? 0 : 1; + const bMatch = (b.companyName || "PT EnterpriseCore Utama") === payrollCompany ? 0 : 1; + return aMatch - bMatch; + } + ); + + const handleExportFinanceCSV = () => { + if (activeTab === "payroll") { + exportToCSV( + "Rekap_Payroll_Slip_Gaji.csv", + [ + "No Slip", + "Entitas PT", + "Nama Karyawan", + "Jabatan", + "Periode", + "Hari Hadir", + "Hari Absen", + "Gaji Pokok", + "Total Uang Makan", + "Potongan Absen", + "Gaji Bersih (THP)", + ], + filteredPayrollRecords.map((pr) => [ + pr.payrollNumber, + pr.companyName || "PT EnterpriseCore Utama", + pr.employeeName, + pr.role, + pr.period, + pr.workDays, + pr.absentDays, + pr.baseSalary, + pr.totalMealAllowance, + pr.absenceDeduction, + pr.netSalary, + ]) + ); + } else if (activeTab === "coa") { + exportToCSV( + "Bagan_Akun_COA.csv", + ["Kode Akun", "Nama Akun / Bank", "Entitas PT", "Klasifikasi", "Saldo (Rp)"], + filteredAccounts.map((a) => [ + a.code, + a.name, + a.companyName || "PT EnterpriseCore Utama", + a.type, + a.balance, + ]) + ); + } else { + exportToCSV( + "Jurnal_Umum_Transaksi.csv", + ["No Voucher", "Tanggal", "Keterangan", "Referensi"], + journalEntries.map((j) => [ + j.entryNumber, + formatDateTime(j.date), + j.description, + j.reference || "-", + ]) + ); + } + }; + + const handlePrintFinancialReport = () => { + const printWindow = window.open("", "_blank", "width=820,height=750"); + if (!printWindow) return; + + const ptLabel = escapeHtml( + selectedCompanyFilter === "ALL" + ? "KONSOLIDASI SEMUA PT" + : selectedCompanyFilter + ); + + const revRows = filteredAccounts + .filter((a) => a.type === "REVENUE") + .map( + (a) => + `[${escapeHtml(a.code)}] ${escapeHtml(a.name)}${formatRupiah( + a.balance + )}` + ) + .join(""); + + const expRows = filteredAccounts + .filter((a) => a.type === "EXPENSE") + .map( + (a) => + `[${escapeHtml(a.code)}] ${escapeHtml(a.name)}${formatRupiah( + a.balance + )}` + ) + .join(""); + + const assetRows = filteredAccounts + .filter((a) => a.type === "ASSET") + .map( + (a) => + `[${escapeHtml(a.code)}] ${escapeHtml(a.name)} (${escapeHtml( + a.companyName || "PT Utama" + )})${formatRupiah( + a.balance + )}` + ) + .join(""); + + const html = ` + + + + Laporan Laba Rugi & Posisi Kas — ${ptLabel} + + + +
+
+
${ptLabel}
+
Laporan Resmi Laba Rugi (Profit & Loss) & Posisi Aset Kas/Bank
+
+
+ Dicetak: ${formatDateTime(new Date())} +
+
+ +

I. PENDAPATAN USAHA (REVENUE)

+ ${revRows || ""}
Belum ada pendapatanRp 0
+ +

II. BEBAN OPERASIONAL & GAJI (EXPENSE)

+ ${expRows || ""}
Belum ada bebanRp 0
+ +
+ LABA / (RUGI) BERSIH BERJALAN + ${formatRupiah(netProfit)} +
+ +

III. POSISI ASET KAS, BANK & PERSEDIAAN (ASSET)

+ ${assetRows}
+
+ Total Aset: ${formatRupiah(totalAssets)} +
+ + + + `; + + printWindow.document.write(html); + printWindow.document.close(); + }; + + return ( + + {/* Financial Summary KPIs */} +
+
+
+ + Total Aset ({selectedCompanyFilter === "ALL" ? "Semua PT" : selectedCompanyFilter}) + +
+ +
+
+

+ {formatRupiah(totalAssets)} +

+

Kas, Rekening Bank, Piutang & Persediaan

+
+ +
+
+ + Payroll & Uang Makan ({selectedCompanyFilter === "ALL" ? "Semua PT" : selectedCompanyFilter}) + +
+ +
+
+

+ {formatRupiah(totalPayrollDisbursed)} +

+

+ Uang Makan: {formatRupiah(totalMealDisbursed)} ({filteredPayrollRecords.length} Slip Gaji) +

+
+ +
+
+ + Laba Bersih Berjalan + +
+ +
+
+

= 0 ? "text-emerald-600" : "text-rose-600" + }`} + > + {formatRupiah(netProfit)} +

+

+ Pendapatan ({formatRupiah(totalRevenue)}) - Beban ({formatRupiah(totalExpenses)}) +

+
+
+ + {/* Header controls (Sub-menu navigasi hanya di Sidebar kiri, tombol aksi rapi sesuai sub-menu aktif) */} +
+
+
+ + {activeTab === "reports" + ? `Laporan Keuangan: Laba Rugi, Neraca & Piutang/Hutang` + : activeTab === "payroll" + ? `Payroll & Slip Gaji (${filteredPayrollRecords.length})` + : activeTab === "coa" + ? `Kode Akun & Bank / COA (${filteredAccounts.length})` + : activeTab === "journal" + ? `Jurnal Transaksi (${filteredJournalEntries.length})` + : `Manajemen Entitas PT (${companies.length})`} + +
+ + {canCreateJournal ? ( +
+ {activeTab !== "companies" && ( + <> + + + + + + + )} + + {activeTab === "coa" && ( + + )} + + {activeTab === "payroll" && ( + + )} + + {activeTab === "journal" && ( + + )} +
+ ) : ( +
+ + Transaksi keuangan & payroll dibatasi khusus Finance & Admin +
+ )} +
+ + {/* Visual Financial Chart Container if Toggled */} + {showChart && chartData && ( +
+ +
+ )} + + {/* TAB 0: LAPORAN KEUANGAN (LABA RUGI, NERACA & AR/AP AGING) */} + {activeTab === "reports" && ( +
+
+
+

+ Laporan Keuangan Terkonsolidasi —{" "} + {selectedCompanyFilter === "ALL" ? "Semua Perusahaan" : selectedCompanyFilter} +

+

+ Dihitung otomatis dari Buku Besar (COA), Jurnal, Sales Order, dan Purchase Order aktif +

+
+
+ + +
+
+ + {/* Laba Rugi & Neraca Side-by-Side */} +
+ {/* Laporan Laba Rugi (Profit & Loss) */} +
+
+

Laporan Laba Rugi (Profit & Loss)

+ Periode Berjalan +
+
+
+
+ Pendapatan Usaha +
+ {filteredAccounts.filter((a) => a.type === "REVENUE").length === 0 ? ( +
Belum ada akun pendapatan.
+ ) : ( + filteredAccounts + .filter((a) => a.type === "REVENUE") + .map((a) => ( +
+ + {a.code} + {a.name} + + {formatRupiah(a.balance)} +
+ )) + )} +
+ Total Pendapatan + {formatRupiah(totalRevenue)} +
+
+ +
+
+ Beban Pokok Penjualan (HPP) +
+ {filteredAccounts + .filter((a) => a.type === "EXPENSE" && String(a.code || "").startsWith("5")) + .map((a) => ( +
+ + {a.code} + {a.name} + + {formatRupiah(a.balance)} +
+ ))} +
+ Laba Kotor (Gross Profit) + {formatRupiah(grossProfit)} +
+
+ +
+
+ Beban Operasional & Gaji +
+ {filteredAccounts + .filter((a) => a.type === "EXPENSE" && !String(a.code || "").startsWith("5")) + .map((a) => ( +
+ + {a.code} + {a.name} + + {formatRupiah(a.balance)} +
+ ))} +
+ +
+ Laba / Rugi Bersih + = 0 ? "text-emerald-600" : "text-rose-600"}`}> + {formatRupiah(netProfit)} + +
+
+
+ + {/* Laporan Neraca (Balance Sheet) */} +
+
+

Neraca (Balance Sheet)

+ + + {isBalanceSheetBalanced ? "Seimbang (Balance)" : "Cek Penyesuaian"} + +
+
+
+
+ Aset (Aktiva) +
+ {filteredAccounts + .filter((a) => a.type === "ASSET") + .map((a) => ( +
+ + {a.code} + {a.name} + + + {formatRupiah(a.balance)} + +
+ ))} +
+ Total Aset + {formatRupiah(totalAssets)} +
+
+ +
+
+ Kewajiban (Liabilitas) & Ekuitas +
+ {filteredAccounts + .filter((a) => a.type === "LIABILITY" || a.type === "EQUITY") + .map((a) => ( +
+ + {a.code} + {a.name} + + + {formatRupiah(a.balance)} + +
+ ))} +
+ Laba / Rugi Tahun Berjalan + = 0 ? "text-emerald-600" : "text-rose-600"}`}> + {formatRupiah(netProfit)} + +
+
+ Total Kewajiban & Ekuitas + {formatRupiah(totalLiabAndEquity)} +
+
+
+
+
+ + {/* Piutang Customer (AR) & Hutang Vendor (AP) Aging */} +
+
+
+
+

Piutang Customer Belum Lunas (AR)

+

{filteredArList.length} invoice menunggu pembayaran

+
+ + {formatRupiah(totalArRemaining)} + +
+
+ + + + + + + + + + {filteredArList.length === 0 ? ( + + + + ) : ( + filteredArList.map((r) => ( + + + + + + )) + )} + +
No. SO & CustomerUmurSisa Tagihan
+ Tidak ada piutang belum lunas. +
+
{r.number}
+
+ {r.counterparty} • {r.companyName} +
+
+ 60 + ? "bg-rose-50 text-rose-700 border-rose-200" + : r.ageDays > 30 + ? "bg-amber-50 text-amber-700 border-amber-200" + : "bg-slate-50 text-slate-700 border-slate-200" + }`} + > + {r.ageDays} hari + + + {formatRupiah(r.remaining)} +
+
+
+ +
+
+
+

Hutang Vendor Belum Lunas (AP)

+

{filteredApList.length} PO belum lunas

+
+ + {formatRupiah(totalApRemaining)} + +
+
+ + + + + + + + + + {filteredApList.length === 0 ? ( + + + + ) : ( + filteredApList.map((p) => ( + + + + + + )) + )} + +
No. PO & VendorUmurSisa Hutang
+ Tidak ada hutang vendor belum lunas. +
+
{p.number}
+
+ {p.counterparty} • {p.companyName} +
+
+ 60 + ? "bg-rose-50 text-rose-700 border-rose-200" + : p.ageDays > 30 + ? "bg-amber-50 text-amber-700 border-amber-200" + : "bg-slate-50 text-slate-700 border-slate-200" + }`} + > + {p.ageDays} hari + + + {formatRupiah(p.remaining)} +
+
+
+
+
+ )} + + {/* TAB 1: PAYROLL, SLIP GAJI, UANG MAKAN & ABSENSI (TERPISAH PER PT) */} + {activeTab === "payroll" && ( +
+
+
+

+ Daftar Slip Gaji, Rekap Absensi & Uang Makan{" "} + {selectedCompanyFilter !== "ALL" ? `— ${selectedCompanyFilter}` : "(Semua PT)"} +

+

+ Setiap payroll tercatat terpisah per Entitas PT dan Rekening Bank pembayar. Klik{" "} + Lihat Slip Gaji untuk mencetak/unduh PDF. +

+
+ + {payrollEmployees.length} Karyawan Tersimpan + +
+ +
+ + + + + + + + + + + + + + {filteredPayrollRecords.length === 0 ? ( + + + + ) : ( + filteredPayrollRecords.map((pr) => ( + + + + + + + + + + )) + )} + +
No. Slip, Periode & PTNama Karyawan & JabatanRekap AbsensiGaji PokokTotal Uang MakanTotal Diterima (THP)Slip Gaji
+ Belum ada pencatatan Payroll / Slip Gaji pada filter PT ini. Klik tombol{" "} + Hitung Payroll & Buat Slip Gaji di kanan atas. +
+
+ {pr.payrollNumber} +
+
+ {pr.period} +
+ + {pr.companyName || "PT EnterpriseCore Utama"} + +
+
{pr.employeeName}
+ + {pr.role} + + {pr.paymentAccountName && ( +
+ Via: {pr.paymentAccountName} +
+ )} +
+
+ + Hadir: {pr.workDays} Hari + + {pr.absentDays > 0 && ( + + Absen: {pr.absentDays} Hari + + )} + {pr.lateCount > 0 && ( + + Telat: {pr.lateCount}x + + )} +
+
+ {formatRupiah(pr.baseSalary)} + +
+ +{formatRupiah(pr.totalMealAllowance)} +
+
+ ({pr.workDays} hr × {formatRupiah(pr.dailyMealRate)}) +
+
+ {formatRupiah(pr.netSalary)} + {pr.absenceDeduction > 0 && ( +
+ Potongan: -{formatRupiah(pr.absenceDeduction)} +
+ )} +
+
+ + + {/* Khusus Admin bisa Edit & Hapus Slip Gaji, selain Admin hanya View, Print & Add */} + {currentUser?.role === "ADMIN" && ( + <> + + + + )} +
+
+
+
+ )} + + {/* TAB 2: BAGAN AKUN / KODE AKUN & BANK (BISA ADD & EDIT KODE/NAMA/PT) */} + {activeTab === "coa" && ( +
+
+
+

+ Daftar Kode Akun & Rekening Bank (Chart of Accounts) +

+

+ Anda dapat menambahkan Bank lain (BCA, Mandiri, BRI, BNI, dll.) atau mengedit Kode & Nama Akun serta memisahkannya per PT. +

+
+
+ +
+ + + + + + + + + {canCreateJournal && } + + + + {filteredAccounts.map((acc) => { + const isSystemAccount = [ + "1001", + "1002", + "1101", + "1201", + "2001", + "3001", + "4001", + "5001", + "6001", + ].includes(acc.code); + + return ( + + + + + + + {canCreateJournal && ( + + )} + + ); + })} + +
Kode AkunNama Akun / Rekening BankEntitas PT (Perusahaan)KlasifikasiSaldo Saat IniTindakan
+ {acc.code} + + {acc.name} + + + {acc.companyName || "PT EnterpriseCore Utama"} + + + + {acc.type} + + + {formatRupiah(acc.balance)} + +
+ + {currentUser?.role === "ADMIN" && !isSystemAccount && ( + + )} +
+
+
+
+ )} + + {/* TAB 3: JURNAL TRANSAKSI */} + {activeTab === "journal" && ( +
+
+
+

+ Buku Besar Jurnal Transaksi (Double-Entry Ledger) +

+

+ Seluruh pencatatan jurnal umum dan jurnal otomatis tercatat seimbang (Debit = Kredit). +

+
+
+
+ + + + + + + + + {currentUser?.role === "ADMIN" && ( + + )} + + + + {filteredJournalEntries.length === 0 ? ( + + + + ) : ( + filteredJournalEntries.map((je) => ( + + + + + + + {currentUser?.role === "ADMIN" && ( + + )} + + )) + )} + +
No. Voucher & TanggalKeterangan TransaksiPosisi Akun Double-EntryDebitKreditAksi
+ Belum ada catatan jurnal umum. +
+
+ {je.entryNumber} +
+
+ {formatDateTime(je.date)} +
+
+
{je.description}
+ {je.reference && ( + + Ref: {je.reference} + + )} +
+
+ {je.lines.map((l: any) => ( +
+ {l.account.name} ({l.account.code}) +
+ ))} +
+
+ {je.lines + .filter((l: any) => l.type === "DEBIT") + .map((l: any) => ( +
{formatRupiah(l.amount)}
+ ))} +
+ {je.lines + .filter((l: any) => l.type === "CREDIT") + .map((l: any) => ( +
{formatRupiah(l.amount)}
+ ))} +
+ +
+
+
+ )} + + {/* TAB 4: KELOLA ENTITAS PT (PERUSAHAAN) */} + {activeTab === "companies" && ( +
+
+
+

+ Manajemen Entitas Perusahaan (PT) — Payroll & Rekening Bank +

+

+ Semua pengguna Keuangan dapat melihat (View) dan menambah (Add) PT baru.{" "} + Penghapusan PT dikhususkan hanya untuk Super Admin. +

+
+ + {/* Form Cepat Tambah Entitas PT Baru */} +
+ setNewCompanyName(e.target.value)} + className="px-3 py-2 text-xs bg-white border border-slate-300 rounded-lg font-semibold w-64 focus:outline-none focus:ring-2 focus:ring-blue-500" + /> + +
+
+ +
+ + + + + + + + + + + + {companies.map((comp) => { + const ptAccounts = accounts.filter( + (a) => (a.companyName || "PT EnterpriseCore Utama") === comp + ); + const ptPayrolls = payrollRecords.filter( + (r) => (r.companyName || "PT EnterpriseCore Utama") === comp + ); + const ptTotalPaid = ptPayrolls.reduce((s, r) => s + r.netSalary, 0); + const isCurrentlySelected = selectedCompanyFilter === comp; + + return ( + + + + + + + + ); + })} + +
Nama Entitas PTJumlah Akun / BankJumlah Slip GajiTotal Payroll TerbayarTindakan
+
+ + {comp} + {isCurrentlySelected && ( + + PT Aktif Terpilih + + )} +
+
+ {ptAccounts.length} Akun / Bank + + {ptPayrolls.length} Slip Gaji + + {formatRupiah(ptTotalPaid)} + +
+ + + {currentUser?.role === "ADMIN" ? ( + + ) : ( + + View & Add Only + + )} +
+
+
+
+ )} + + {/* ===================================================================== */} + {/* MODAL 1: KALKULATOR PAYROLL, UANG MAKAN & ABSENSI (MULTI-PT & BANK) */} + {/* ===================================================================== */} + setIsPayrollOpen(false)} + title="Hitung Payroll Terpisah per PT, Uang Makan, Absensi & Slip Gaji" + > + {payrollError && ( +
+ {payrollError} +
+ )} + +
+ {/* 0. Pilih / Tambah Entitas PT untuk Pemisahan Penggunaan Payroll */} +
+
+ + +
+ + {companyInputMode === "SELECT" ? ( + + ) : ( +
+ setNewCompanyName(e.target.value)} + className="w-full px-3 py-2 border border-blue-400 rounded-lg font-semibold bg-white" + /> + +
+ )} +
+ + {/* 1. Nama Karyawan: Dropdown (jika sudah pernah simpan payroll) atau Input Baru */} +
+
+ + {payrollEmployees.length > 0 && ( + + )} +
+ + {payrollEmployees.length > 0 && employeeInputMode === "SELECT" ? ( + + ) : ( +
+ setEmployeeName(e.target.value)} + className="w-full px-3 py-2 border border-slate-300 rounded-lg font-semibold" + /> + {payrollEmployees.length === 0 && ( + + Setelah Anda menyimpan payroll pertama, nama karyawan ini otomatis muncul di Dropdown. + + )} +
+ )} +
+ + {/* 2. Jabatan (Bisa ditambah bebas, berbeda dengan RBAC) & Periode (Dropdown Bulan & Tahun) */} +
+
+
+ + +
+ + {positionInputMode === "SELECT" ? ( + + ) : ( +
+ setNewPositionName(e.target.value)} + className="w-full px-3 py-2 border border-emerald-400 rounded-lg font-semibold" + /> + +
+ )} +
+ + {/* Dropdown Periode Bulan & Tahun */} +
+ +
+ + + +
+
+
+ + {/* Rekap Kehadiran / Absensi */} +
+
+ + Rekap Kehadiran & Absensi ({periodMonth} {periodYear}): +
+
+
+ + setWorkDays(Number(e.target.value))} + className="w-full px-3 py-1.5 border border-slate-300 rounded-lg bg-white font-bold text-emerald-700" + /> +
+
+ + setAbsentDays(Number(e.target.value))} + className="w-full px-3 py-1.5 border border-slate-300 rounded-lg bg-white font-bold text-rose-600" + /> +
+
+ + setLateCount(Number(e.target.value))} + className="w-full px-3 py-1.5 border border-slate-300 rounded-lg bg-white font-bold text-amber-600" + /> +
+
+
+ + {/* Komponen Gaji, Uang Makan & Potongan */} +
+
+ + setBaseSalary(Number(val) || 0)} + /> +
+ +
+ + setDailyMealRate(Number(val) || 0)} + /> +
+ +
+ + setTransportAllowance(Number(val) || 0)} + /> +
+ +
+ + setDeductionPerAbsent(Number(val) || 0)} + /> +
+
+ + {/* Sumber Dana Pembayaran (Kode Akun Kas / Bank) + Tombol Tambah/Edit Bank */} +
+
+ +
+ {paymentAccountId && ( + + )} + +
+
+ +
+ + {/* Ringkasan Hasil Perhitungan Otomatis */} +
+
+ Entitas Perusahaan (PT): + + {companyInputMode === "NEW" && newCompanyName + ? newCompanyName + : payrollCompany} + +
+
+ Gaji Pokok: + {formatRupiah(baseSalary)} +
+
+ + Total Uang Makan ({workDays} hari hadir × {formatRupiah(dailyMealRate)}): + + + +{formatRupiah(calculatedMealTotal)} + +
+
+ Tunjangan Transport / Lembur: + +{formatRupiah(transportAllowance)} +
+
+ + Potongan Absen ({absentDays} hr) & Telat ({lateCount}x): + + -{formatRupiah(calculatedAbsenceDeduction)} +
+
+ Total Gaji Bersih (Take Home Pay): + + {formatRupiah(calculatedNetSalary)} + +
+
+ +
+ + +
+
+
+ + {/* ===================================================================== */} + {/* MODAL 2: TAMBAH / EDIT KODE AKUN & REKENING BANK (COA PER PT) */} + {/* ===================================================================== */} + setIsAccountModalOpen(false)} + title={ + editingAccount + ? `Edit Kode Akun / Bank — [${editingAccount.code}]` + : "Tambah Kode Akun / Rekening Bank Baru (COA)" + } + > + {accError && ( +
+ {accError} +
+ )} + +
+
+
+ + setAccCode(e.target.value)} + className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono font-bold text-purple-700" + /> +
+ +
+ + setAccName(e.target.value)} + className="w-full px-3 py-2 border border-slate-300 rounded-lg font-semibold text-slate-800" + /> +
+
+ +
+
+ + +
+ +
+ + +
+
+ +
+ + setAccBalance(val)} + /> +
+ +
+ + +
+
+
+ + {/* ===================================================================== */} + {/* MODAL 3: PREVIEW & CETAK SLIP GAJI RESMI (PAYSLIP PER PT) */} + {/* ===================================================================== */} + setSelectedSlip(null)} + title={`Slip Gaji Karyawan — ${selectedSlip?.payrollNumber ?? ""}`} + > + {selectedSlip && ( +
+ {/* Header Slip Gaji */} +
+
+
+ +
+
+

+ {selectedSlip.companyName || "PT EnterpriseCore Utama"} +

+

+ Slip Gaji Resmi, Uang Makan & Kehadiran +

+
+
+
+ + + PAID / LUNAS + +
+ {selectedSlip.period} +
+
+
+ + {/* Info Karyawan & Absensi */} +
+
+
+ Data Karyawan & PT +
+
+ {selectedSlip.employeeName} +
+
{selectedSlip.role}
+
+ {selectedSlip.companyName || "PT EnterpriseCore Utama"} +
+ {selectedSlip.paymentAccountName && ( +
+ Sumber: {selectedSlip.paymentAccountName} +
+ )} +
+ +
+
+ Rekap Kehadiran ({selectedSlip.period}) +
+
+ Hari Hadir (Masuk): + + {selectedSlip.workDays} Hari + +
+
+ Hari Absen: + + {selectedSlip.absentDays} Hari + +
+
+ Terlambat: + + {selectedSlip.lateCount} Kali + +
+
+
+ + {/* Tabel Rincian Komponen Gaji */} +
+
+ Komponen Penerimaan & Potongan + Nominal +
+
+
+
+
Gaji Pokok Bulanan
+
+ Gaji tetap periode {selectedSlip.period} +
+
+ + {formatRupiah(selectedSlip.baseSalary)} + +
+ +
+
+
+ Tunjangan Uang Makan Kehadiran +
+
+ {selectedSlip.workDays} hari hadir × {formatRupiah(selectedSlip.dailyMealRate)} / hari +
+
+ + +{formatRupiah(selectedSlip.totalMealAllowance)} + +
+ +
+
+
+ Tunjangan Transport / Lembur +
+
+ Tunjangan operasional tambahan +
+
+ + +{formatRupiah(selectedSlip.transportAllowance)} + +
+ +
+
+
+ Potongan Absen & Keterlambatan +
+
+ Absen: {selectedSlip.absentDays} hari | Telat: {selectedSlip.lateCount}x +
+
+ + -{formatRupiah(selectedSlip.absenceDeduction)} + +
+
+ +
+
+
+ Total Gaji Bersih Diterima (Take Home Pay) +
+
+ Dibayarkan tanggal {formatDateTime(selectedSlip.createdAt)} +
+
+
+ {formatRupiah(selectedSlip.netSalary)} +
+
+
+ + {/* Action Buttons: Print / Download PDF (+ Edit/Hapus khusus Admin) */} +
+
+ + {currentUser?.role === "ADMIN" && ( + <> + + + + )} +
+ + +
+
+ )} +
+ + {/* Modal: Create Journal Entry */} + setIsModalOpen(false)} + title="Catat Jurnal Transaksi Keuangan Baru" + > + {formError && ( +
+ {formError} +
+ )} + +
+
+ + setDescription(e.target.value)} + className="w-full px-3 py-2 border border-slate-300 rounded-lg" + /> +
+ +
+
+ + +
+ +
+ + +
+
+ +
+
+ + setAmount(val)} + /> +
+
+ + setReference(e.target.value)} + className="w-full px-3 py-2 border border-slate-300 rounded-lg" + /> +
+
+ +
+ + +
+
+
+ + ); +} diff --git a/src/app/globals.css b/src/app/globals.css new file mode 100644 index 0000000..63571cb --- /dev/null +++ b/src/app/globals.css @@ -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; + } +} diff --git a/src/app/inventory/page.tsx b/src/app/inventory/page.tsx new file mode 100644 index 0000000..775c883 --- /dev/null +++ b/src/app/inventory/page.tsx @@ -0,0 +1,2986 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { AppShell } from "@/components/AppShell"; +import { Modal } from "@/components/Modal"; +import { Pagination } from "@/components/Pagination"; +import { CurrencyInput } from "@/components/CurrencyInput"; +import { SerialNumberInput } from "@/components/SerialNumberInput"; +import { cn, formatRupiah, formatDateTime, exportToCSV } from "@/lib/utils"; +import { + Boxes, + Plus, + ArrowUpDown, + Search, + Warehouse as WarehouseIcon, + AlertCircle, + History, + Lock, + Download, + PackageCheck, + Pencil, + GitMerge, + CheckCircle2, + Trash2, + Wrench, + Ban, + Cpu, + ChevronDown, +} from "lucide-react"; + +export default function InventoryPage() { + const [currentUser, setCurrentUser] = useState(null); + const [products, setProducts] = useState([]); + const [warehouses, setWarehouses] = useState([]); + const [categories, setCategories] = useState([]); + const [movements, setMovements] = useState([]); + const [companies, setCompanies] = useState(["PT EnterpriseCore Utama"]); + const [selectedCompanyFilter, setSelectedCompanyFilter] = useState("ALL"); + const [loading, setLoading] = useState(true); + + const [search, setSearch] = useState(""); + const [selectedCategory, setSelectedCategory] = useState("ALL"); + const [activeTab, setActiveTab] = useState<"catalog" | "movements" | "devices">("catalog"); + const [tabDropdownOpen, setTabDropdownOpen] = useState(false); + const tabDropdownRef = useRef(null); + const [snPreviewProduct, setSnPreviewProduct] = useState(null); + + const switchInventoryTab = (tab: "catalog" | "movements" | "devices") => { + setActiveTab(tab); + if (typeof window !== "undefined") { + sessionStorage.setItem("erp_inventory_tab", tab); + window.dispatchEvent( + new CustomEvent("erp:inventory-tab-sync", { detail: { tab } }) + ); + } + }; + + // Device Lifecycle (Pernah Diservis, Rusak Total / Afkir, & Unit Kanibalan) + const [deviceRecords, setDeviceRecords] = useState([]); + const [deviceCustomers, setDeviceCustomers] = useState([]); + const [deviceSearch, setDeviceSearch] = useState(""); + const [deviceConditionFilter, setDeviceConditionFilter] = useState("ALL"); + const [devPage, setDevPage] = useState(1); + const [devPageSize, setDevPageSize] = useState(10); + const [isDeviceModalOpen, setIsDeviceModalOpen] = useState(false); + const [editingDevice, setEditingDevice] = useState(null); + const [deviceSubmitting, setDeviceSubmitting] = useState(false); + const [deviceFormError, setDeviceFormError] = useState(null); + const [deviceToDelete, setDeviceToDelete] = useState(null); + const [isDeletingDevice, setIsDeletingDevice] = useState(false); + const [deviceForm, setDeviceForm] = useState<{ + productId: string; + serialNumbers: string; + condition: string; + serviceOrigin: string; + customerId: string; + salesOrderNumber: string; + serviceFee: number | string; + returnShippingCost: number | string; + returnCourierName: string; + returnTrackingNumber: string; + damageDescription: string; + actionTaken: string; + salvagedParts: string; + deductWarehouseStock: boolean; + }>({ + productId: "", + serialNumbers: "", + condition: "IN_SERVICE", + serviceOrigin: "WAREHOUSE_DEFECT", + customerId: "", + salesOrderNumber: "", + serviceFee: 0, + returnShippingCost: 0, + returnCourierName: "", + returnTrackingNumber: "", + damageDescription: "", + actionTaken: "", + salvagedParts: "", + deductWarehouseStock: false, + }); + + // Pagination States (Default 5 items, pilihan 5, 10, 25, 50) + const [prodPage, setProdPage] = useState(1); + const [prodPageSize, setProdPageSize] = useState(5); + const [movPage, setMovPage] = useState(1); + const [movPageSize, setMovPageSize] = useState(5); + + // Modals state + const [isAddModalOpen, setIsAddModalOpen] = useState(false); + const [isAdjustModalOpen, setIsAdjustModalOpen] = useState(false); + const [isEditModalOpen, setIsEditModalOpen] = useState(false); + const [isMergeModalOpen, setIsMergeModalOpen] = useState(false); + const [selectedProduct, setSelectedProduct] = useState(null); + + // Edit Product state + const [editProductData, setEditProductData] = useState<{ + id: string; + sku: string; + name: string; + description: string; + unit: string; + purchasePrice: number | string; + sellingPrice: number | string; + minStock: number | string; + categoryId: string; + }>({ + id: "", + sku: "", + name: "", + description: "", + unit: "PCS", + purchasePrice: 0, + sellingPrice: 0, + minStock: 5, + categoryId: "", + }); + + // Merge Products state + const [mergeSourceId, setMergeSourceId] = useState(""); + const [mergeTargetId, setMergeTargetId] = useState(""); + + // Quick Add Category inside modals + const [addingCat, setAddingCat] = useState(false); + const [newCatName, setNewCatName] = useState(""); + + // Form states + const [newProduct, setNewProduct] = useState<{ + sku: string; + name: string; + description: string; + isService: boolean; + unit: string; + purchasePrice: number | string; + sellingPrice: number | string; + minStock: number | string; + categoryId: string; + warehouseId: string; + initialQuantity: number | string; + }>({ + sku: "", + name: "", + description: "", + isService: false, + unit: "PCS", + purchasePrice: 0, + sellingPrice: 0, + minStock: 0, + categoryId: "", + warehouseId: "", + initialQuantity: 0, + }); + + const [adjustData, setAdjustData] = useState({ + warehouseId: "", + type: "IN", + outboundCategory: "JUAL_PUTUS", + quantity: 1, + serialNumbers: "", + notes: "", + }); + + // State Konfirmasi Hapus Produk (Bebas dari window.confirm yang sering diblokir browser) + const [productToDelete, setProductToDelete] = useState(null); + const [isDeletingProduct, setIsDeletingProduct] = useState(false); + const [deleteError, setDeleteError] = useState(null); + const [notificationMsg, setNotificationMsg] = useState(null); + + const [formError, setFormError] = useState(null); + const [submitting, setSubmitting] = useState(false); + + const loadData = async () => { + try { + const [meRes, res, devRes] = await Promise.all([ + fetch("/api/auth/me"), + fetch("/api/inventory"), + fetch("/api/devices"), + ]); + if (meRes.ok) { + const meJson = await meRes.json(); + setCurrentUser(meJson.user); + } + + if (res.ok) { + const json = await res.json(); + setProducts(json.products || []); + setWarehouses(json.warehouses || []); + setCategories(json.categories || []); + setMovements(json.movements || []); + if (json.warehouses && json.warehouses.length > 0) { + const mainWhId = json.warehouses[0].id; + setNewProduct((prev) => ({ ...prev, warehouseId: mainWhId })); + setAdjustData((prev) => ({ ...prev, warehouseId: mainWhId })); + } + if (json.companies && json.companies.length > 0) { + setCompanies(json.companies); + } + } + + if (devRes.ok) { + const devJson = await devRes.json(); + setDeviceRecords(devJson.records || []); + setDeviceCustomers(devJson.customers || []); + } + } catch (err) { + console.error(err); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + const handleClickOutside = (e: MouseEvent) => { + if (tabDropdownRef.current && !tabDropdownRef.current.contains(e.target as Node)) { + setTabDropdownOpen(false); + } + }; + document.addEventListener("mousedown", handleClickOutside); + return () => { + document.removeEventListener("mousedown", handleClickOutside); + }; + }, []); + + useEffect(() => { + if (typeof window !== "undefined") { + const savedTab = sessionStorage.getItem("erp_inventory_tab"); + if (savedTab === "catalog" || savedTab === "movements" || savedTab === "devices") { + setActiveTab(savedTab); + } + const savedPT = localStorage.getItem("erp_selected_pt") || "ALL"; + setSelectedCompanyFilter(savedPT); + } + loadData(); + + const handleSidebarTabChange = (e: any) => { + const t = e?.detail?.tab; + if (t === "catalog" || t === "movements" || t === "devices") { + setActiveTab(t); + } + }; + + const handleCompanyChange = (e: any) => { + const comp = e.detail?.company || "ALL"; + setSelectedCompanyFilter(comp); + }; + + window.addEventListener("erp:inventory-tab", handleSidebarTabChange); + window.addEventListener("erp:company-changed", handleCompanyChange); + return () => { + window.removeEventListener("erp:inventory-tab", handleSidebarTabChange); + window.removeEventListener("erp:company-changed", handleCompanyChange); + }; + }, []); + + const canManageInventory = ["ADMIN", "MANAGER", "INVENTORY"].includes( + currentUser?.role + ); + + const canRecordDevice = ["ADMIN", "MANAGER", "INVENTORY", "SALES"].includes( + currentUser?.role + ); + + const canDeleteProduct = ["ADMIN", "MANAGER", "INVENTORY"].includes( + currentUser?.role + ); + + // Penyesuaian hak akses melihat uang: + // - Gudang (INVENTORY) & Purchasing: TIDAK BISA melihat uang harga jual atau margin laba katalog + // - Sales: HANYA melihat Harga Jual (tanpa HPP modal & Margin keuntungan perusahaan) + // - Admin, Manager, Finance (ACCOUNTANT): Melihat seluruh Harga Beli HPP, Harga Jual, dan Margin Laba + const canSeeSellingPrice = ["ADMIN", "MANAGER", "SALES", "ACCOUNTANT"].includes( + currentUser?.role + ); + const canSeeHppAndMargin = ["ADMIN", "MANAGER", "ACCOUNTANT"].includes( + currentUser?.role + ); + + const handleQuickAddCategory = async () => { + const clean = newCatName.trim(); + if (!clean) return; + try { + const res = await fetch("/api/inventory", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: "CREATE_CATEGORY", name: clean }), + }); + const data = await res.json(); + if (res.ok && data.category) { + setCategories([...categories, data.category]); + setNewProduct({ ...newProduct, categoryId: data.category.id }); + setNewCatName(""); + setAddingCat(false); + } + } catch (e) { + console.error(e); + } + }; + + const handleAddProduct = async (e: React.FormEvent) => { + e.preventDefault(); + setSubmitting(true); + setFormError(null); + + try { + const cleanProduct = { + ...newProduct, + purchasePrice: 0, + sellingPrice: 0, + initialQuantity: 0, + warehouseId: warehouses[0]?.id || "", + minStock: typeof newProduct.minStock === "string" ? parseInt(newProduct.minStock) || 0 : newProduct.minStock, + }; + + const res = await fetch("/api/inventory", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(cleanProduct), + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + setIsAddModalOpen(false); + setNewProduct({ + sku: "", + name: "", + description: "", + isService: false, + unit: "PCS", + purchasePrice: 0, + sellingPrice: 0, + minStock: 0, + categoryId: "", + warehouseId: warehouses[0]?.id || "", + initialQuantity: 0, + }); + loadData(); + } catch (err: any) { + setFormError(err.message); + } finally { + setSubmitting(false); + } + }; + + const handleAdjustStock = async (e: React.FormEvent) => { + e.preventDefault(); + setSubmitting(true); + setFormError(null); + + try { + const res = await fetch("/api/inventory", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + productId: selectedProduct?.id, + ...adjustData, + }), + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + setIsAdjustModalOpen(false); + loadData(); + } catch (err: any) { + setFormError(err.message); + } finally { + setSubmitting(false); + } + }; + + const handleOpenEditModal = (p: any) => { + setEditProductData({ + id: p.id, + sku: p.sku || "", + name: p.name || "", + description: p.description || "", + unit: p.unit || "PCS", + purchasePrice: p.purchasePrice || 0, + sellingPrice: p.sellingPrice || 0, + minStock: p.minStock !== undefined ? p.minStock : 5, + categoryId: p.categoryId || "", + }); + setFormError(null); + setIsEditModalOpen(true); + }; + + const handleUpdateProduct = async (e: React.FormEvent) => { + e.preventDefault(); + setSubmitting(true); + setFormError(null); + + try { + const payload: Record = { + action: "UPDATE_PRODUCT", + productId: editProductData.id, + name: editProductData.name, + sku: editProductData.sku, + description: editProductData.description, + unit: editProductData.unit, + minStock: editProductData.minStock, + categoryId: editProductData.categoryId, + }; + if (canSeeHppAndMargin) { + payload.purchasePrice = editProductData.purchasePrice; + } + if (canSeeSellingPrice) { + payload.sellingPrice = editProductData.sellingPrice; + } + + const res = await fetch("/api/inventory", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + setIsEditModalOpen(false); + loadData(); + } catch (err: any) { + setFormError(err.message); + } finally { + setSubmitting(false); + } + }; + + const handleMergeProducts = async (e: React.FormEvent) => { + e.preventDefault(); + if (!mergeSourceId || !mergeTargetId) { + setFormError("Pilih produk sumber dan target untuk digabungkan"); + return; + } + if (mergeSourceId === mergeTargetId) { + setFormError("Produk sumber dan target tidak boleh sama"); + return; + } + + setSubmitting(true); + setFormError(null); + + try { + const res = await fetch("/api/inventory", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + action: "MERGE_PRODUCTS", + sourceProductId: mergeSourceId, + targetProductId: mergeTargetId, + }), + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error); + + setIsMergeModalOpen(false); + setMergeSourceId(""); + setMergeTargetId(""); + loadData(); + } catch (err: any) { + setFormError(err.message); + } finally { + setSubmitting(false); + } + }; + + const handleConfirmDeleteProduct = async () => { + if (!productToDelete) return; + setIsDeletingProduct(true); + setDeleteError(null); + try { + const res = await fetch(`/api/inventory?id=${productToDelete.id}`, { method: "DELETE" }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || "Gagal menghapus produk"); + setNotificationMsg(data.message || `Produk "${productToDelete.name}" berhasil dihapus.`); + setProductToDelete(null); + await loadData(); + setTimeout(() => setNotificationMsg(null), 5000); + } catch (err: any) { + setDeleteError(err.message || "Gagal menghapus produk"); + } finally { + setIsDeletingProduct(false); + } + }; + + const filteredProducts = products.filter((p) => { + const matchesSearch = + p.name.toLowerCase().includes(search.toLowerCase()) || + p.sku.toLowerCase().includes(search.toLowerCase()); + const matchesCat = + selectedCategory === "ALL" || p.categoryId === selectedCategory; + return matchesSearch && matchesCat; + }); + + const getProductStockForPT = (p: any) => { + if (selectedCompanyFilter === "ALL") return p.totalStock || 0; + if (p.stockByCompany && Object.keys(p.stockByCompany).length > 0) { + return p.stockByCompany[selectedCompanyFilter] || 0; + } + return (p.stockItems || []) + .filter((s: any) => (s.warehouse?.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter) + .reduce((sum: number, it: any) => sum + (it.quantity || 0), 0); + }; + + const filteredMovements = movements.filter((m) => { + const mComp = m.companyName || m.warehouse?.companyName || "PT EnterpriseCore Utama"; + if (selectedCompanyFilter !== "ALL" && mComp !== selectedCompanyFilter) return false; + return true; + }); + + const filteredDevices = deviceRecords.filter((d) => { + const dComp = d.companyName || "PT EnterpriseCore Utama"; + if (selectedCompanyFilter !== "ALL" && dComp !== selectedCompanyFilter) return false; + if (deviceConditionFilter !== "ALL" && d.condition !== deviceConditionFilter) return false; + if (deviceSearch.trim()) { + const q = deviceSearch.toLowerCase(); + const hay = [ + d.serialNumber, + d.recordNumber, + d.product?.name, + d.product?.sku, + d.customer?.name, + d.salesOrderNumber, + d.damageDescription, + d.actionTaken, + d.salvagedParts, + ] + .filter(Boolean) + .join(" ") + .toLowerCase(); + if (!hay.includes(q)) return false; + } + return true; + }); + + const paginatedDevices = filteredDevices.slice((devPage - 1) * devPageSize, devPage * devPageSize); + + const deviceStats = { + serviced: deviceRecords.filter((d) => d.condition === "IN_SERVICE" || d.condition === "SERVICED_OK").length, + replaced: deviceRecords.filter((d) => d.condition === "REPLACED_WARRANTY").length, + cannibalized: deviceRecords.filter((d) => d.condition === "CANNIBALIZED").length, + damaged: deviceRecords.filter((d) => d.condition === "DAMAGED_UNUSABLE").length, + }; + + const getDeviceConditionBadge = (cond: string) => { + switch (cond) { + case "IN_SERVICE": + return { label: "⚙️ Sedang Diservis", cls: "bg-blue-50 text-blue-700 border-blue-200" }; + case "SERVICED_OK": + return { label: "✅ Pernah Diservis (Normal)", cls: "bg-emerald-50 text-emerald-700 border-emerald-200" }; + case "CANNIBALIZED": + return { label: "🛠️ Unit Kanibalan / Sparepart", cls: "bg-purple-50 text-purple-800 border-purple-300" }; + case "DAMAGED_UNUSABLE": + return { label: "🚫 Rusak Total (Tidak Bisa Dipakai)", cls: "bg-rose-50 text-rose-800 border-rose-300" }; + case "REPLACED_WARRANTY": + return { label: "🔄 Retur Tukar Unit Garansi", cls: "bg-amber-50 text-amber-800 border-amber-300" }; + default: + return { label: cond, cls: "bg-slate-100 text-slate-700 border-slate-200" }; + } + }; + + const getDeviceOriginLabel = (origin: string) => { + switch (origin) { + case "WARRANTY_FREE": + return "Service Gratis (Garansi)"; + case "WARRANTY_REPLACE": + return "Tukar Unit Garansi"; + case "PAID_SERVICE": + return "Jasa Service Berbayar"; + default: + return "Barang Gudang / Internal"; + } + }; + + const handleOpenAddDevice = (defaultCondition: string = "IN_SERVICE") => { + setEditingDevice(null); + setDeviceFormError(null); + setDeviceForm({ + productId: products.find((p) => !p.isService)?.id || "", + serialNumbers: "", + condition: defaultCondition, + serviceOrigin: "WAREHOUSE_DEFECT", + customerId: "", + salesOrderNumber: "", + serviceFee: 0, + returnShippingCost: 0, + returnCourierName: "", + returnTrackingNumber: "", + damageDescription: "", + actionTaken: "", + salvagedParts: "", + deductWarehouseStock: false, + }); + setIsDeviceModalOpen(true); + }; + + const handleOpenEditDevice = (rec: any) => { + setEditingDevice(rec); + setDeviceFormError(null); + const isReplaceOrigin = rec.serviceOrigin === "WARRANTY_REPLACE"; + const safeCondition = + isReplaceOrigin && !["DAMAGED_UNUSABLE", "CANNIBALIZED"].includes(rec.condition) + ? "DAMAGED_UNUSABLE" + : rec.condition || "IN_SERVICE"; + setDeviceForm({ + productId: rec.productId || "", + serialNumbers: rec.serialNumber || "", + condition: safeCondition, + serviceOrigin: rec.serviceOrigin || "WAREHOUSE_DEFECT", + customerId: rec.customerId || "", + salesOrderNumber: rec.salesOrderNumber || "", + serviceFee: rec.serviceFee || 0, + returnShippingCost: rec.returnShippingCost || 0, + returnCourierName: rec.returnCourierName || "", + returnTrackingNumber: rec.returnTrackingNumber || "", + damageDescription: rec.damageDescription || "", + actionTaken: rec.actionTaken || "", + salvagedParts: rec.salvagedParts || "", + deductWarehouseStock: Boolean(rec.stockAdjusted), + }); + setIsDeviceModalOpen(true); + }; + + const handleSubmitDeviceRecord = async (e: React.FormEvent) => { + e.preventDefault(); + setDeviceSubmitting(true); + setDeviceFormError(null); + try { + const companyName = + selectedCompanyFilter !== "ALL" + ? selectedCompanyFilter + : companies[0] || "PT EnterpriseCore Utama"; + + const isEdit = Boolean(editingDevice); + const numericReturnShipping = + typeof deviceForm.returnShippingCost === "string" + ? parseFloat(deviceForm.returnShippingCost) || 0 + : deviceForm.returnShippingCost; + + const res = await fetch("/api/devices", { + method: isEdit ? "PUT" : "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify( + isEdit + ? { + id: editingDevice.id, + condition: deviceForm.condition, + serviceOrigin: deviceForm.serviceOrigin, + serviceFee: + typeof deviceForm.serviceFee === "string" + ? parseFloat(deviceForm.serviceFee) || 0 + : deviceForm.serviceFee, + returnShippingCost: numericReturnShipping, + returnCourierName: deviceForm.returnCourierName, + returnTrackingNumber: deviceForm.returnTrackingNumber, + damageDescription: deviceForm.damageDescription, + actionTaken: deviceForm.actionTaken, + salvagedParts: deviceForm.salvagedParts, + } + : { + productId: deviceForm.productId, + serialNumbers: deviceForm.serialNumbers, + condition: deviceForm.condition, + serviceOrigin: deviceForm.serviceOrigin, + customerId: deviceForm.customerId || undefined, + salesOrderNumber: deviceForm.salesOrderNumber || undefined, + companyName, + serviceFee: + typeof deviceForm.serviceFee === "string" + ? parseFloat(deviceForm.serviceFee) || 0 + : deviceForm.serviceFee, + returnShippingCost: numericReturnShipping, + returnCourierName: deviceForm.returnCourierName || undefined, + returnTrackingNumber: deviceForm.returnTrackingNumber || undefined, + damageDescription: deviceForm.damageDescription, + actionTaken: deviceForm.actionTaken, + salvagedParts: deviceForm.salvagedParts, + deductWarehouseStock: deviceForm.deductWarehouseStock, + warehouseId: warehouses[0]?.id, + } + ), + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || "Gagal menyimpan catatan device"); + + setIsDeviceModalOpen(false); + setEditingDevice(null); + setNotificationMsg( + isEdit + ? `Kondisi device SN ${editingDevice.serialNumber} berhasil diperbarui.` + : `Berhasil mencatat ${data.count || 1} unit device ke daftar Riwayat Service / Rusak / Kanibalan.` + ); + await loadData(); + setTimeout(() => setNotificationMsg(null), 5000); + } catch (err: any) { + setDeviceFormError(err.message || "Terjadi kesalahan saat menyimpan catatan device"); + } finally { + setDeviceSubmitting(false); + } + }; + + const handleConfirmDeleteDevice = async () => { + if (!deviceToDelete) return; + setIsDeletingDevice(true); + try { + const res = await fetch(`/api/devices?id=${encodeURIComponent(deviceToDelete.id)}`, { + method: "DELETE", + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || "Gagal menghapus catatan device"); + setNotificationMsg(data.message || "Catatan device berhasil dihapus."); + setDeviceToDelete(null); + await loadData(); + setTimeout(() => setNotificationMsg(null), 4000); + } catch (err: any) { + alert(err.message || "Gagal menghapus catatan device"); + } finally { + setIsDeletingDevice(false); + } + }; + + // Pagination Slices (Default 5 items, pilihan 5, 10, 25, 50) + const paginatedProducts = filteredProducts.slice((prodPage - 1) * prodPageSize, prodPage * prodPageSize); + const paginatedMovements = filteredMovements.slice((movPage - 1) * movPageSize, movPage * movPageSize); + + const totalPhysicalUnits = products.reduce((s, p) => s + getProductStockForPT(p), 0); + + // Filter produk fisik yang stoknya benar-benar ada (>0) tapi di bawah atau sama dengan batas aman minimum + const lowStockProducts = products.filter((p) => { + if (p.isService) return false; + const stock = getProductStockForPT(p); + return stock > 0 && stock <= p.minStock; + }); + const lowStockCount = lowStockProducts.length; + + // Filter produk fisik yang stoknya benar-benar 0 (Stok Kosong / Belum Ada Barang Fisik) + const outOfStockProducts = products.filter((p) => { + if (p.isService) return false; + return getProductStockForPT(p) === 0; + }); + const outOfStockCount = outOfStockProducts.length; + + const handleExportCSV = () => { + if (activeTab === "catalog") { + exportToCSV( + "Katalog_Stok_Gudang.csv", + ["SKU", "Nama Produk", "Kategori", "Satuan", "Total Stok Fisik", "Min Stok", "SN Tersedia di Gudang"], + filteredProducts.map((p) => [ + p.sku, + p.name, + p.category?.name || "Umum", + p.unit, + getProductStockForPT(p), + p.minStock, + (p.availableSerialNumbers || []).join(", ") || "-", + ]) + ); + } else if (activeTab === "devices") { + exportToCSV( + "Riwayat_Device_Service_Rusak_Kanibalan.csv", + [ + "No. Record", + "Serial Number (SN)", + "Produk", + "SKU", + "Kondisi", + "Sumber / Kategori", + "Customer", + "Ref SO", + "Kerusakan", + "Tindakan Teknisi", + "Komponen Kanibalan", + "Dicatat Oleh", + "Terakhir Diubah", + ], + filteredDevices.map((d) => [ + d.recordNumber, + d.serialNumber, + d.product?.name || "-", + d.product?.sku || "-", + getDeviceConditionBadge(d.condition).label, + getDeviceOriginLabel(d.serviceOrigin), + d.customer?.name || "Internal Gudang", + d.salesOrderNumber || "-", + d.damageDescription || "-", + d.actionTaken || "-", + d.salvagedParts || "-", + d.recordedBy || "-", + formatDateTime(d.updatedAt || d.createdAt), + ]) + ); + } else { + exportToCSV( + "Riwayat_Mutasi_Stok.csv", + ["Waktu", "SKU", "Nama Produk", "PT", "Gudang", "Tipe Mutasi", "Jumlah", "Serial Number (SN)", "Keterangan"], + filteredMovements.map((m) => [ + formatDateTime(m.createdAt), + m.product?.sku || "-", + m.product?.name || "-", + m.companyName || m.warehouse?.companyName || "PT EnterpriseCore Utama", + m.warehouse?.name || "-", + m.type, + m.quantity, + m.serialNumbers || "-", + m.notes || m.referenceId || "-", + ]) + ); + } + }; + + return ( + + {/* Ringkasan Cepat Inventaris */} +
+
+
+ + Total SKU / Jenis Barang + +
+ {products.length} SKU +
+ + Tersimpan di Gudang Utama + +
+
+ +
+
+ +
+
+ + Total Unit Fisik Tersedia + +
+ {totalPhysicalUnits.toLocaleString("id-ID")} Unit +
+ + Stok fisik di Gudang Utama + +
+
+ +
+
+ +
+
+ + Peringatan Stok Menipis + +
0 ? "text-rose-600" : "text-slate-900" + }`} + > + {lowStockCount} Barang +
+ + {lowStockCount > 0 + ? `Di bawah batas minimum aman${outOfStockCount > 0 ? ` • ${outOfStockCount} Stok Kosong` : ""}` + : outOfStockCount > 0 + ? `${outOfStockCount} barang stok fisik 0 (kosong)` + : "Semua stok dalam batas aman"} + +
+
0 ? "bg-rose-50 text-rose-600" : "bg-slate-50 text-slate-400" + }`} + > + +
+
+
+ + {/* Banner Notifikasi Aksi */} + {notificationMsg && ( +
+ ✓ {notificationMsg} + +
+ )} + + {/* Header Controls — Sub-menu Dropdown Navigasi (seperti Pembelian & Pemasok) */} +
+
+
+
+ + + {tabDropdownOpen && ( +
+ + + + + +
+ )} +
+
+ +
+ + + {activeTab === "devices" && canRecordDevice && ( + + )} + + {canManageInventory && ( + + )} + + {canManageInventory ? ( + + ) : ( +
+ + Mode Hanya Baca ({currentUser?.role || "STAFF"}) +
+ )} +
+
+ + {activeTab === "catalog" ? ( +
+
+
+ + setSearch(e.target.value)} + className="w-full pl-9 pr-3 py-2 text-xs bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" + /> +
+ +
+ Kategori: + +
+
+ +
+ + + + + + {canSeeHppAndMargin && } + {canSeeSellingPrice && } + {canSeeHppAndMargin && } + + + {canManageInventory && ( + + )} + + + + {paginatedProducts.length === 0 ? ( + + + + ) : ( + paginatedProducts.map((p) => { + const pStock = getProductStockForPT(p); + const isOutOfStock = !p.isService && pStock === 0; + const isLow = !p.isService && pStock > 0 && pStock <= p.minStock; + const relevantStockItems = (p.stockItems || []).filter((s: any) => + selectedCompanyFilter === "ALL" || (s.warehouse?.companyName || "PT EnterpriseCore Utama") === selectedCompanyFilter + ); + return ( + + + + {canSeeHppAndMargin && ( + + )} + {canSeeSellingPrice && ( + + )} + {canSeeHppAndMargin && ( + + )} + + + {canManageInventory && ( + + )} + + ); + }) + )} + +
SKU / Nama ProdukKategoriHarga Beli (HPP)Harga JualMargin LabaTotal Stok FisikLokasi GudangAksi
+ Belum ada produk yang terdaftar atau cocok dengan pencarian. +
+
{p.name}
+
+ + {p.sku} + + {p.isService && ( + + 🌐 Layanan / Non-Fisik + + )} +
+ {!p.isService && (p.availableSerialNumbers?.length > 0 || p.allRecordedSerialNumbers?.length > 0) && ( + + )} +
+ {p.category?.name || "Umum"} + + {formatRupiah(p.purchasePrice)} + + {formatRupiah(p.sellingPrice)} + + {(() => { + const profit = p.sellingPrice - p.purchasePrice; + const marginPct = + p.purchasePrice > 0 + ? Math.round((profit / p.purchasePrice) * 100) + : 100; + return profit >= 0 ? ( + + +{formatRupiah(profit)} (+{marginPct}%) + + ) : ( + + -{formatRupiah(Math.abs(profit))} ({marginPct}%) + + ); + })()} + + {p.isService ? ( + + 🌐 Non-Fisik ({p.unit}) + + ) : isOutOfStock ? ( + + 0 {p.unit} (Stok Kosong) + + ) : ( + + {isLow && } + + {pStock} {p.unit} {isLow ? "(Menipis)" : ""} + + + )} + + {p.isService ? ( + + Layanan / Non-Fisik + + ) : ( +
+ + Gudang Utama +
+ )} +
+
+ + {!p.isService && ( + + )} + {canDeleteProduct && ( + + )} +
+
+
+ + {/* Pagination Katalog Produk */} + +
+ ) : activeTab === "movements" ? ( +
+
+ + + + + + + + + + + + + {paginatedMovements.length === 0 ? ( + + + + ) : ( + paginatedMovements.map((m) => ( + + + + + + + + + )) + )} + +
Tanggal & WaktuProdukGudangJenis MutasiJumlahKeterangan / Referensi
+ Belum ada riwayat mutasi stok barang. +
+ {formatDateTime(m.createdAt)} + + {m.product.name} + +
{m.warehouse.name}
+ + 🏢 {m.companyName || m.warehouse?.companyName || "PT EnterpriseCore Utama"} + +
+
+ + {m.type} + + {m.type === "OUT" && ( + m.outboundCategory === "KANIBALAN" ? ( + + 🛠️ Kanibalan + + ) : m.outboundCategory === "RUSAK_AFKIR" ? ( + + 🚫 Rusak / Afkir + + ) : m.outboundCategory === "GANTI_UNIT_GARANSI" ? ( + + 🔄 Tukar Garansi + + ) : m.saleType === "MANAGED_SERVICE" ? ( + + Jual Manage Service + + ) : m.saleType === "OPERASIONAL" ? ( + + Operasional + + ) : ( + + Jual Putus + + ) + )} +
+
+ {m.type === "OUT" ? `-${m.quantity}` : `+${m.quantity}`} + +
{m.notes || "-"}
+
+ {m.referenceId && ( + + Ref: {m.referenceId} + + )} + {m.serialNumbers && ( + + SN: {m.serialNumbers} + + )} + {m.customerPoNumber && ( + + PO Cust: {m.customerPoNumber} + + )} + {m.invoiceNumber && m.invoiceNumber !== m.referenceId && ( + + Inv: {m.invoiceNumber} + + )} +
+
+
+ + {/* Pagination Mutasi Stok */} + +
+ ) : null} + + {activeTab === "devices" && ( +
+ {/* 4 Kartu Ringkasan Kondisi Device */} +
+ + + + + + + +
+ +
+ {/* Filter & Pencarian SN */} +
+
+ + { + setDeviceSearch(e.target.value); + setDevPage(1); + }} + className="w-full pl-9 pr-3 py-2 text-xs bg-white border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500" + /> +
+ +
+ Filter Kondisi: + + {deviceConditionFilter !== "ALL" && ( + + )} +
+
+ +
+ + + + + + + + + + + + {paginatedDevices.length === 0 ? ( + + + + ) : ( + paginatedDevices.map((d) => { + const badge = getDeviceConditionBadge(d.condition); + return ( + + + + + + + + + + + + ); + }) + )} + +
Serial Number (SN) & TanggalPerangkat & SumberStatus Kondisi DeviceKerusakan, Tindakan & Part KanibalanTindakan
+
+ +
+ Belum Ada Catatan Device Service, Rusak, atau Kanibalan +
+

+ Device yang diservis/ditukar di menu Penjualan (Service / Garansi) akan masuk otomatis ke sini, atau klik tombol Catat Device di atas untuk mencatat barang rusak total / kanibalan secara manual atau via Excel. +

+
+
+
+ {d.serialNumber} +
+
+ {d.recordNumber} +
+
+ {formatDateTime(d.updatedAt || d.createdAt)} +
+ {d.recordedBy && ( +
+ PIC: {d.recordedBy} +
+ )} +
+
{d.product?.name || "-"}
+
+ SKU: {d.product?.sku || "-"} +
+
+ {d.customer ? ( +
+ Customer: {d.customer.name} +
+ ) : ( +
+ Internal / Stok Gudang +
+ )} + {d.salesOrderNumber && ( + + Ref: {d.salesOrderNumber} + + )} + {d.stockAdjusted && ( + + Stok Gudang Dipotong + + )} +
+
+
+ + {badge.label} + +
+ {getDeviceOriginLabel(d.serviceOrigin)} +
+ {canSeeSellingPrice && d.serviceFee > 0 && ( +
+ Biaya Jasa: {formatRupiah(d.serviceFee)} ( + {d.servicePaymentStatus === "PAID" ? "Lunas" : "Belum Bayar"}) +
+ )} + {(d.returnShippingCost > 0 || d.returnTrackingNumber || d.returnCourierName) && ( +
+
+ 🚚 Ongkir Balik (User): {formatRupiah(d.returnShippingCost || 0)} + {d.returnShippingCost > 0 && ( + + ({d.servicePaymentStatus === "PAID" ? "Lunas" : "Ditanggung User"}) + + )} +
+ {(d.returnCourierName || d.returnTrackingNumber) && ( +
+ {d.returnCourierName || "Kurir"} + {d.returnTrackingNumber ? ` • Resi: ${d.returnTrackingNumber}` : ""} +
+ )} +
+ )} +
+
+
+
+ Kerusakan:{" "} + {d.damageDescription} +
+ {d.actionTaken && ( +
+ Tindakan: {d.actionTaken} +
+ )} + {d.salvagedParts && ( +
+ 🛠️ Part Kanibalan: {d.salvagedParts} +
+ )} +
+
+
+ {canRecordDevice && ( + + )} + {canDeleteProduct && ( + + )} +
+
+
+ + +
+
+ )} + + {/* Modal: Add New Product */} + setIsAddModalOpen(false)} + title="Tambah Produk / Layanan Baru ke Katalog" + > + {formError && ( +
+ {formError} +
+ )} + +
+ {/* Pilihan Jenis Item: Barang Fisik vs Layanan / Non-Fisik */} +
+ +
+ + +
+
+ +
+
+ + setNewProduct({ ...newProduct, sku: e.target.value })} + className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 uppercase font-mono" + /> +
+
+ + setNewProduct({ ...newProduct, unit: e.target.value })} + className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 uppercase" + /> +
+
+ +
+ + setNewProduct({ ...newProduct, name: e.target.value })} + className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500" + /> +
+ +
+
+
+ + +
+ {!addingCat ? ( + + ) : ( +
+ setNewCatName(e.target.value)} + className="w-full px-2.5 py-2 border border-blue-400 rounded-lg" + /> + +
+ )} +
+ {!newProduct.isService && ( +
+ + { + const v = e.target.value; + setNewProduct({ ...newProduct, minStock: v === "" ? "" : parseInt(v) || 0 }); + }} + className="w-full px-3 py-2 border border-slate-300 rounded-lg" + /> +
+ )} +
+ + {/* Info Pendaftaran Master Produk */} +
+ ℹ️ Pendaftaran Master Produk + Form ini hanya untuk mendaftarkan nama dan SKU barang ke katalog. HPP Modal dan Stok Fisik akan otomatis tercatat saat barang tiba dari PO Vendor. Harga Jual dapat disesuaikan kemudian melalui tombol Edit. +
+ +
+ + +
+
+
+ + {/* Modal: Adjust Stock */} + setIsAdjustModalOpen(false)} + title={`Mutasi Stok: ${selectedProduct?.name}`} + > + {formError && ( +
+ {formError} +
+ )} + +
+
+ +
+ + Gudang Utama +
+
+ +
+
+ + +
+
+ + + setAdjustData({ + ...adjustData, + quantity: parseInt(e.target.value) || 1, + }) + } + className="w-full px-3 py-2 border border-slate-300 rounded-lg" + /> +
+
+ + {adjustData.type === "OUT" && ( +
+ +
+ + + +
+
+ )} + + {/* Pilih Cepat SN Otomatis dari Gudang saat Mutasi Keluar */} + {adjustData.type === "OUT" && + selectedProduct?.availableSerialNumbers && + selectedProduct.availableSerialNumbers.length > 0 && ( +
+
+ + SN Tersedia di Gudang ({selectedProduct.availableSerialNumbers.length}) — Klik untuk pilih: + + +
+
+ {selectedProduct.availableSerialNumbers.slice(0, 40).map((sn: string) => { + const currentTokens = adjustData.serialNumbers + .split(/[\n,;]+/) + .map((s) => s.trim()) + .filter(Boolean); + const selected = currentTokens.includes(sn); + return ( + + ); + })} +
+
+ )} + + + setAdjustData({ ...adjustData, serialNumbers: val }) + } + /> + +
+ +