mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 13:32:00 +00:00
Compare commits
563 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 359cdb2534 | |||
| 8a64780135 | |||
| 3b7836c8ba | |||
| ba1d462a0a | |||
| 352688054e | |||
| 06c4631ca5 | |||
| 2b6676b4eb | |||
| 14c208f494 | |||
| 27ab373ebb | |||
| ab4e9fbd39 | |||
| dd586f07d2 | |||
| 9d70f94b33 | |||
| 5ebeeeedb3 | |||
| a9ff4579b0 | |||
| a1fe08fdeb | |||
| fc81fa9ad3 | |||
| e980320d00 | |||
| 5509f52464 | |||
| 0ed6c246b1 | |||
| c7818cefbb | |||
| b004877584 | |||
| a51a020dfa | |||
| a3670271de | |||
| adaac46236 | |||
| 49e843f3b2 | |||
| b9ed7df063 | |||
| 60d5551dff | |||
| db33247d6c | |||
| aab8e0c5ce | |||
| 6c6634fa1d | |||
| e93a9c8011 | |||
| b8031448ff | |||
| c63df91e08 | |||
| 0e43957e6e | |||
| dada6a542f | |||
| b305d43ce6 | |||
| 8d5b195691 | |||
| 6c2baca807 | |||
| d9a1d340bb | |||
| 8511a75842 | |||
| 4452b6fd03 | |||
| 1ed83351e0 | |||
| 9817864c3d | |||
| 564d6d0da1 | |||
| 2c8160f816 | |||
| 23402370b8 | |||
| e3d929435a | |||
| ef3797e724 | |||
| cddb1422f6 | |||
| f28aeda74c | |||
| 75dfd96934 | |||
| 079d69dffb | |||
| 711536975c | |||
| 97bf785fe9 | |||
| dce913815e | |||
| 737d8e943c | |||
| 0bdf27de2c | |||
| 9cff99cba9 | |||
| 46cfc2539e | |||
| 34f93f8dcc | |||
| 1a800a1157 | |||
| 3c96855b86 | |||
| 607bf28121 | |||
| d8361be28f | |||
| 031d51947a | |||
| 554037bfe5 | |||
| 9f93200bd5 | |||
| 70fcbf795b | |||
| 406befc21b | |||
| 558f219e8b | |||
| 8671f37ada | |||
| 15dc04bb95 | |||
| f801378ad2 | |||
| 73e8697097 | |||
| b3f6f36c00 | |||
| b9c4f44e3f | |||
| 5a7b750203 | |||
| bb30b6cb21 | |||
| 0cc857378f | |||
| e68e5a6d51 | |||
| c20b1c5942 | |||
| 0a5efbe383 | |||
| 2e769b234d | |||
| f87736154a | |||
| ca0d379c2c | |||
| 87492876e5 | |||
| 3d8d0d9e4d | |||
| 956f1ce500 | |||
| a11b648bf9 | |||
| 31581e963f | |||
| c63882fbd7 | |||
| ab84f59929 | |||
| 5fe0236686 | |||
| 8f6597e7df | |||
| c4f4775a48 | |||
| 81e5a180ba | |||
| 1d65cf0d08 | |||
| 4ef5ee7142 | |||
| 19a90c9045 | |||
| fcbb34624d | |||
| 68ccb66e5c | |||
| a094eb94a5 | |||
| 4db2bc187a | |||
| e8ff69b43f | |||
| b03a47ddc6 | |||
| 62a78b8619 | |||
| 7f43ef6c56 | |||
| 51ad37cc48 | |||
| 9a00d4b98e | |||
| 6528899aaf | |||
| f94c8ba799 | |||
| df4b513739 | |||
| 50477d0850 | |||
| 79f0e2b7b7 | |||
| 63c3818766 | |||
| f6a360ee2b | |||
| aa39478318 | |||
| 02fbd677fc | |||
| 98608576b9 | |||
| 80d9dd689a | |||
| 0d1907f729 | |||
| 3aab90d3d6 | |||
| 6f96f20b49 | |||
| 142ce7fe3a | |||
| b7085f5d2a | |||
| 628facb23d | |||
| 27c112e479 | |||
| b19340536a | |||
| 163d225dba | |||
| f07db1be7a | |||
| 4323040bd3 | |||
| 97a753133e | |||
| 273810804d | |||
| 2be417ac0a | |||
| f98e9d6930 | |||
| 4c336f81c7 | |||
| 1389cb7ed6 | |||
| a7958166bf | |||
| 34f01abb32 | |||
| 66c537ec10 | |||
| 2847f50bf7 | |||
| 7b4d69b0b0 | |||
| 37ab614a97 | |||
| 7c73e8e5c6 | |||
| 85f4a5deaa | |||
| 4011d26193 | |||
| afb0c40fd2 | |||
| 2a03eae8a2 | |||
| e9238e2bb5 | |||
| 40eaa729ef | |||
| 47e51e0105 | |||
| 56326cc8d2 | |||
| 860a2d988e | |||
| 79701fbcfe | |||
| 8b1e43cdb9 | |||
| 4768a7d6fd | |||
| caba77d871 | |||
| 37c0c1cf42 | |||
| 1d06c6f02a | |||
| ae206b9426 | |||
| d3d3859021 | |||
| 447ef81871 | |||
| 2507f733fb | |||
| 2d6e8480f5 | |||
| 9d0fdb346d | |||
| 08f3372b46 | |||
| 6307cdc0dc | |||
| 52213fc8c4 | |||
| 826e83b025 | |||
| c300bdcb0f | |||
| 84a7b0e50f | |||
| 839bf4daac | |||
| 38955b96de | |||
| 542992eaab | |||
| 982d0294b6 | |||
| 42ebf1015f | |||
| 4991b1160f | |||
| 71a430c99c | |||
| db1e224c3b | |||
| bb74b90790 | |||
| a890ed571b | |||
| 2d81b0dfba | |||
| ab390ab461 | |||
| 335b254a60 | |||
| 5e53f8764e | |||
| f0051b58bb | |||
| 8c73a8f61a | |||
| 6636648813 | |||
| 151af5707d | |||
| 716f064858 | |||
| be87bc7c1d | |||
| 111531b803 | |||
| d59cf359ee | |||
| 2f7ae0ae66 | |||
| 8cc7f2f526 | |||
| 25074edaa1 | |||
| 0b1349ca8d | |||
| 6c70dc93ce | |||
| ed3d525c06 | |||
| af9c4bbdb9 | |||
| 5a88718454 | |||
| d1a0cdc1b9 | |||
| 196db657e8 | |||
| 51c3277b6c | |||
| abc35314a0 | |||
| 146a63fc70 | |||
| d46652cb68 | |||
| b46f06a739 | |||
| 6cc5e5e931 | |||
| 7b82888aa6 | |||
| 762fb08568 | |||
| b7c0a80a04 | |||
| 143674533a | |||
| b046b64ed2 | |||
| 9f6fec5a3c | |||
| e386d2a389 | |||
| cdef3e797e | |||
| 6af2609f44 | |||
| 6f5540eb91 | |||
| 5c286128e4 | |||
| df875eda1d | |||
| ae2b27521e | |||
| d026a3b5ae | |||
| ed9a8021c1 | |||
| 31d9c5e38d | |||
| e749faedca | |||
| 27c696c797 | |||
| 28b58d9cac | |||
| 1d0d42dc16 | |||
| 1b3dd34add | |||
| 1d29f62bf2 | |||
| e35f857057 | |||
| bcc2f71623 | |||
| 359f0f7b01 | |||
| 6a9f672d27 | |||
| 8c976b6d0b | |||
| e00a81cebb | |||
| a82860cb68 | |||
| 52a18dac24 | |||
| c2272ee5e0 | |||
| c012f39a38 | |||
| 0f72a14fde | |||
| 1c35c7db32 | |||
| 1f6ce36976 | |||
| 756701722a | |||
| 8e48c4d7cf | |||
| 282f651d96 | |||
| 49abb129e3 | |||
| 9d6148e877 | |||
| d914eb86f2 | |||
| e8a6bf05c3 | |||
| ffa0b23b82 | |||
| 49e9e958fa | |||
| b17ccd502e | |||
| 1a7b969c3f | |||
| eca8bd7026 | |||
| 1e421e4230 | |||
| 9cffa53122 | |||
| 2ff217efcb | |||
| 475467cca6 | |||
| d0f6e965f0 | |||
| 9a1be88bce | |||
| 76fb5a2625 | |||
| b75ed86949 | |||
| 426b6bfc85 | |||
| c7ffae68d8 | |||
| 362ae16c7d | |||
| 149b14e0f8 | |||
| 4d7bbaf771 | |||
| 99fc3f8cae | |||
| 507f53ace8 | |||
| fd4b584ccd | |||
| f73672f65c | |||
| b62424af18 | |||
| 951d2bca0a | |||
| 4081a326e3 | |||
| 0dbcb83c54 | |||
| 248d4f75d8 | |||
| 4b2e00d91a | |||
| d679b5b54e | |||
| b2fa4786b2 | |||
| aaca46356a | |||
| 1f03222e42 | |||
| c472375f38 | |||
| 469542bd2e | |||
| 98e1623c19 | |||
| 480e8a3226 | |||
| 7317eb7129 | |||
| c4f8051fba | |||
| 7be811f2b1 | |||
| 5053ce35df | |||
| 9bd4df3f4c | |||
| 6c4672e38e | |||
| c695afa1e7 | |||
| 93513c4a3a | |||
| ead338fa0f | |||
| afbb007309 | |||
| 732fe85cde | |||
| 43fe8ad1b3 | |||
| d53afb6b74 | |||
| e13f3358f4 | |||
| 26d89c35a5 | |||
| 7a45926c49 | |||
| 0439c21ec6 | |||
| 696ec3a69c | |||
| 6b2f95b9a3 | |||
| 324b6b69e2 | |||
| 876217d1af | |||
| 7a2bdb25e4 | |||
| 1a3ea5be8c | |||
| 572e5233b4 | |||
| 6ece591d2b | |||
| 122bdbbf54 | |||
| 5eb1296391 | |||
| 3cc85a894f | |||
| 71e6ac9c63 | |||
| 596e2d0095 | |||
| 4cb8343f74 | |||
| fc785bc63c | |||
| defbcd9867 | |||
| f69fc08ef8 | |||
| 41bf12846d | |||
| bbb9c5f190 | |||
| de11534e20 | |||
| 8b0a6f054b | |||
| 46b819c200 | |||
| 72356917ff | |||
| 28a32cb6c4 | |||
| 0e179f1643 | |||
| 6319b6d5fe | |||
| a538c3ea90 | |||
| cbc54eb501 | |||
| 67f7a68f1b | |||
| b1981867ff | |||
| 8a84542c60 | |||
| f091b4be43 | |||
| 6e4c214821 | |||
| aa6d205491 | |||
| 2e6e11984e | |||
| 0824225080 | |||
| e4ae1566f1 | |||
| 0f21731008 | |||
| 9b2b5d8307 | |||
| ff6f6136cc | |||
| 4ad2b54128 | |||
| 7b939f57af | |||
| 18f3295562 | |||
| 9c540e7cd8 | |||
| eefec93811 | |||
| 04e54044e9 | |||
| e143668f82 | |||
| 949b5cbc12 | |||
| 0f64baca23 | |||
| d9c154997d | |||
| b3f8fc451d | |||
| da040a4f7e | |||
| 200290a0b3 | |||
| 366864582f | |||
| 876d564f26 | |||
| 979f803d75 | |||
| f4166f4dbd | |||
| 56d4eca034 | |||
| 24ff7a080f | |||
| ee1f759a37 | |||
| 23c758b0cf | |||
| 1c002a1b95 | |||
| fb980c38c9 | |||
| dc2c2228a8 | |||
| 6def4e0fcd | |||
| aaaa126c42 | |||
| 70a15d3044 | |||
| 5c8e97ebf9 | |||
| f8ae023c45 | |||
| d03414f7ab | |||
| 3cda11c66e | |||
| 55b50d4184 | |||
| a9c22d778b | |||
| c576933ba2 | |||
| b66054c9a2 | |||
| ccf535cbd9 | |||
| df550abc46 | |||
| 0aa96b9c46 | |||
| 4391fe1de7 | |||
| 6377557ef0 | |||
| 4d319ca9c8 | |||
| 93c886551d | |||
| d31c1deaa2 | |||
| aad08593c7 | |||
| 36da05890a | |||
| a82c5e5593 | |||
| 08715e39c2 | |||
| 138ad6a7c9 | |||
| 9ae5bdd969 | |||
| d19b1e885e | |||
| f4abfd4279 | |||
| 1152b6d2c3 | |||
| 0cdbff6954 | |||
| f32b77c552 | |||
| cd9fa31ad7 | |||
| 4c4c70e10f | |||
| 67d695303e | |||
| b85bace073 | |||
| 835ba077d8 | |||
| 13abc6d7ce | |||
| a26919f037 | |||
| e6cbb3013d | |||
| c55081f358 | |||
| ff9ad8237c | |||
| f371d06386 | |||
| 79cb89b9a0 | |||
| 9a3617edf1 | |||
| 80dfbcb858 | |||
| db51619fbe | |||
| 6395a32f43 | |||
| 3c6f7ce0d3 | |||
| 01b8841e3c | |||
| 40e8f52fe4 | |||
| 8c6a87c011 | |||
| a17089f4bb | |||
| 45700be730 | |||
| 228e79bb31 | |||
| 87bf474cf6 | |||
| b25418b51e | |||
| 0a24c4541f | |||
| 7d3a4c1ecc | |||
| 8fe51c976b | |||
| 5a4e3ab5ab | |||
| a1bbe4e2d7 | |||
| 6c8e901a99 | |||
| a2e04dad9f | |||
| 73100aa1ce | |||
| e349b9dfa4 | |||
| 4a9cbdc219 | |||
| 76c1b2f628 | |||
| 0a5414a3ac | |||
| c7b4361cb6 | |||
| 00e0bc387b | |||
| 4285e2e269 | |||
| 9df64eeafa | |||
| 34901aa11c | |||
| b2ce9c93b7 | |||
| 0c4448f396 | |||
| 7114470c13 | |||
| 0de4f9d745 | |||
| a6fe07de07 | |||
| 438082c94c | |||
| 081048f0c5 | |||
| fce2cfee73 | |||
| bd64694c73 | |||
| 105d23e4f7 | |||
| 68f9e27b5f | |||
| d786b7b5ba | |||
| 23e8487a97 | |||
| 02b97117eb | |||
| 0f6e224870 | |||
| e15b7e11d3 | |||
| 8f55ced55a | |||
| 781a5ca0d9 | |||
| ac84841b05 | |||
| a08ab7abaf | |||
| 1d689da546 | |||
| 96f96f6c5a | |||
| a403800fb0 | |||
| 49b7ca4be5 | |||
| dd080b1d19 | |||
| 63461173e5 | |||
| 9d7140beb6 | |||
| 817420ee62 | |||
| f3b1091890 | |||
| c9bace04ec | |||
| dc3b4f1850 | |||
| 27a398a1c8 | |||
| 9a87f1c404 | |||
| fc1a0d6a3f | |||
| 6a7990e722 | |||
| 294c843bd4 | |||
| 12f22833c9 | |||
| d46355f7f0 | |||
| bf38178969 | |||
| 790b590668 | |||
| 3952704643 | |||
| 57a148b6cf | |||
| 8a7245f5dd | |||
| b02a3c5eee | |||
| a1301121ac | |||
| 3bc5030a3d | |||
| 4b88b684af | |||
| cf332b5346 | |||
| 94c6d82967 | |||
| c75563491f | |||
| 3827204f13 | |||
| 76e15d13ad | |||
| 5e7f55000a | |||
| 427c8aec34 | |||
| f1dba4012a | |||
| a72fbec5ce | |||
| d8e134d404 | |||
| 359326e575 | |||
| dbe9b26818 | |||
| b290f7692a | |||
| 7a6bee57c2 | |||
| b52a414eb0 | |||
| 4137683d05 | |||
| 9237d4e731 | |||
| efde742518 | |||
| 916de1432b | |||
| e134f0994b | |||
| f22ba83dd0 | |||
| 3cb11f6158 | |||
| c5baff6f33 | |||
| ab2175d903 | |||
| 524036a6bf | |||
| 6c320ce59a | |||
| cb8a1a17ac | |||
| 08c28f4077 | |||
| 66fa65e4bb | |||
| 01e94b57c1 | |||
| 8d586e7cb4 | |||
| 447a953ed3 | |||
| 141d695a7d | |||
| ae35d42484 | |||
| 3f285a74bc | |||
| c81f7faf93 | |||
| c81b250cbb | |||
| fc71defa08 | |||
| 54e05b7150 | |||
| d28fa77405 | |||
| 53277b5893 | |||
| 97d131be12 | |||
| 3937c27c77 | |||
| bdf84c3802 | |||
| ba679865c4 | |||
| 8d7adbbd27 | |||
| adb8d0f69e | |||
| e6eac6b62d | |||
| e87f9087e1 | |||
| c4b505047c | |||
| fee9328699 | |||
| b90fdabc4b | |||
| a5d2d85572 | |||
| 4560073f6a | |||
| a205e57d39 | |||
| 582b971c09 | |||
| 54ce9e5458 | |||
| 8481b77c90 | |||
| e77a43300a | |||
| 34d7310cc9 | |||
| 8998d815a5 | |||
| e5ec0f8deb | |||
| 60eaec261d | |||
| 92bfef850a | |||
| 502564da0a | |||
| 8b99be34ae | |||
| a781431683 | |||
| d34413fa3a | |||
| b9212d1241 | |||
| 6a58be8c67 | |||
| d4b8d25bd5 | |||
| 19c4e0fd4b | |||
| 9ffa60b935 | |||
| 55376e9631 | |||
| 06accca19e | |||
| 0f5ac917d2 |
Generated
+914
-10
File diff suppressed because it is too large
Load Diff
+3
-1
@@ -19,7 +19,9 @@
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"exceljs": "^4.4.0",
|
||||
"formik": "^2.4.6",
|
||||
"html-to-image": "^1.11.13",
|
||||
"input-otp": "^1.4.2",
|
||||
"jspdf": "^3.0.4",
|
||||
"jspdf-autotable": "^5.0.2",
|
||||
@@ -54,7 +56,7 @@
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"daisyui": "^5.5.8",
|
||||
"daisyui": "^5.5.14",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "^15.5.7",
|
||||
"husky": "^9.1.7",
|
||||
|
||||
@@ -35,13 +35,30 @@ const ClosingDetailPage = () => {
|
||||
);
|
||||
|
||||
const { data: salesData, isLoading: isLoadingSales } = useSWR(
|
||||
closingId ? `sales-${closingId}` : null,
|
||||
() => ClosingApi.getPenjualan(Number(closingId))
|
||||
kandangId
|
||||
? `sales-${closingId}-${kandangId}`
|
||||
: closingId
|
||||
? `sales-${closingId}`
|
||||
: null,
|
||||
() =>
|
||||
kandangId
|
||||
? ClosingApi.getPenjualanByKandang(Number(closingId), Number(kandangId))
|
||||
: ClosingApi.getPenjualan(Number(closingId))
|
||||
);
|
||||
|
||||
const { data: hppEkspedisiData, isLoading: isLoadingHppEkspedisi } = useSWR(
|
||||
closingId ? `hpp-ekspedisi-${closingId}` : null,
|
||||
() => ClosingApi.getHppEkspedisi(Number(closingId))
|
||||
kandangId
|
||||
? `hpp-ekspedisi-${closingId}-${kandangId}`
|
||||
: closingId
|
||||
? `hpp-ekspedisi-${closingId}`
|
||||
: null,
|
||||
() =>
|
||||
kandangId
|
||||
? ClosingApi.getHppEkspedisiByKandang(
|
||||
Number(closingId),
|
||||
Number(kandangId)
|
||||
)
|
||||
: ClosingApi.getHppEkspedisi(Number(closingId))
|
||||
);
|
||||
|
||||
if (!closingId) {
|
||||
|
||||
@@ -38,9 +38,11 @@ const ExpenseEditPage = () => {
|
||||
!isLoadingExpense &&
|
||||
isResponseSuccess(expense) &&
|
||||
expense.data.latest_approval.step_number !== 5 &&
|
||||
expense.data.latest_approval.step_number !== 6 &&
|
||||
(expense.data.latest_approval.step_number === 1 ||
|
||||
expense.data.latest_approval.step_number === 2 ||
|
||||
expense.data.latest_approval.step_number === 3);
|
||||
expense.data.latest_approval.step_number === 3 ||
|
||||
expense.data.latest_approval.step_number === 4);
|
||||
|
||||
if (!isLoadingExpense && !isExpenseCanBeEdited) {
|
||||
router.back();
|
||||
|
||||
@@ -2,7 +2,7 @@ import ExpensesTable from '@/components/pages/expense/ExpensesTable';
|
||||
|
||||
const Expense = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<section className='w-full p-4 sm:p-0'>
|
||||
<ExpensesTable />
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -38,8 +38,8 @@ const ExpenseRealizationEditPage = () => {
|
||||
!isLoadingExpense &&
|
||||
isResponseSuccess(expense) &&
|
||||
expense.data.latest_approval.action !== 'REJECTED' &&
|
||||
(expense.data.latest_approval.step_number === 4 ||
|
||||
expense.data.latest_approval.step_number === 5);
|
||||
(expense.data.latest_approval.step_number === 5 ||
|
||||
expense.data.latest_approval.step_number === 6);
|
||||
|
||||
if (!isLoadingExpense && !isExpenseRealizationCanBeEdited) {
|
||||
router.back();
|
||||
|
||||
@@ -24,8 +24,6 @@ const FinanceDetailPage = () => {
|
||||
);
|
||||
}
|
||||
|
||||
console.log(finance);
|
||||
|
||||
// if (!finance || isResponseError(finance)) {
|
||||
// router.replace('/404');
|
||||
// return;
|
||||
|
||||
+10
-5
@@ -1,5 +1,6 @@
|
||||
@import 'tailwindcss';
|
||||
@plugin "daisyui";
|
||||
@import '../styles/tailwind.css';
|
||||
@import '../styles/daisyui.css';
|
||||
@import '../figma-make/styles/theme.css';
|
||||
|
||||
@@ -29,16 +30,16 @@
|
||||
--color-base-100: oklch(100% 0 0); /* #ffffff */
|
||||
--color-base-200: oklch(97.2% 0 0); /* #f2f2f2 */
|
||||
--color-base-300: oklch(93.1% 0.002 249.7); /* #e5e6e6 */
|
||||
--color-base-content: oklch(18.6% 0.024 257.7); /* #1f2937 */
|
||||
--color-base-content: #18181b;
|
||||
|
||||
/* Status/Utility Colors */
|
||||
--color-info: oklch(67.4% 0.176 238.9);
|
||||
--color-info-content: oklch(0% 0 0); /* #000000 */
|
||||
--color-success: oklch(62.3% 0.147 149);
|
||||
--color-success: #00d390;
|
||||
--color-success-content: oklch(100% 0 0); /* #ffffff */
|
||||
--color-warning: oklch(82.2% 0.165 91.9);
|
||||
--color-warning: #fcb700;
|
||||
--color-warning-content: oklch(0% 0 0); /* #000000 */
|
||||
--color-error: oklch(61.8% 0.203 27.8);
|
||||
--color-error: #ff3a3a;
|
||||
--color-error-content: oklch(100% 0 0); /* #fffffff */
|
||||
|
||||
--radius-selector: 0rem;
|
||||
@@ -52,17 +53,21 @@
|
||||
}
|
||||
|
||||
:root {
|
||||
--color-primary: #1f74bf;
|
||||
--color-primary: #0069e0;
|
||||
}
|
||||
|
||||
@theme {
|
||||
--font-inter: var(--font-inter);
|
||||
--font-roboto: var(--font-roboto);
|
||||
|
||||
--container-sm: 40rem;
|
||||
--container-md: 48rem;
|
||||
--container-lg: 64rem;
|
||||
--container-xl: 80rem;
|
||||
--container-2xl: 96rem;
|
||||
|
||||
--shadow-button-soft:
|
||||
0 3px 2px -2px var(--color-base-200), 0 4px 3px -2px var(--color-base-200);
|
||||
}
|
||||
|
||||
html {
|
||||
|
||||
@@ -2,7 +2,7 @@ import MovementTable from '@/components/pages/inventory/movement/MovementTable';
|
||||
|
||||
const Movement = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<section className='w-full p-4 sm:p-0'>
|
||||
<MovementTable />
|
||||
</section>
|
||||
);
|
||||
|
||||
+10
-2
@@ -1,5 +1,5 @@
|
||||
import type { Metadata, Viewport } from 'next';
|
||||
import { Inter } from 'next/font/google';
|
||||
import { Inter, Roboto } from 'next/font/google';
|
||||
import '@/app/globals.css';
|
||||
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
@@ -12,6 +12,12 @@ const inter = Inter({
|
||||
subsets: ['latin'],
|
||||
});
|
||||
|
||||
const roboto = Roboto({
|
||||
variable: '--font-roboto',
|
||||
subsets: ['latin'],
|
||||
weight: ['200', '300', '400', '500', '600', '700', '900'],
|
||||
});
|
||||
|
||||
export const viewport: Viewport = {
|
||||
themeColor: '#1f74bf',
|
||||
colorScheme: 'light',
|
||||
@@ -30,7 +36,9 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang='en' data-theme='lti'>
|
||||
<body className={`${inter.variable} antialiased font-inter`}>
|
||||
<body
|
||||
className={`${inter.variable} ${roboto.variable} antialiased font-inter`}
|
||||
>
|
||||
<RequireAuth>
|
||||
<MainDrawer>{children}</MainDrawer>
|
||||
</RequireAuth>
|
||||
|
||||
+5
-1
@@ -25,5 +25,9 @@ export default function Home() {
|
||||
);
|
||||
}
|
||||
|
||||
return <>Loading...</>;
|
||||
return (
|
||||
<main className='w-full h-full min-h-screen flex flex-row justify-center items-center'>
|
||||
<span className='loading loading-spinner loading-lg'></span>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import RecordingTable from '@/components/pages/production/recording/RecordingTab
|
||||
|
||||
const Recording = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<section className='w-full p-4 sm:p-0'>
|
||||
<RecordingTable />
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
|
||||
|
||||
const AddTransferToLaying = () => {
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
<TransferToLayingForm />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddTransferToLaying;
|
||||
@@ -1,63 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
|
||||
|
||||
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
const TransferToLayingEdit = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const transferToLayingId = searchParams.get('transferToLayingId');
|
||||
|
||||
const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
|
||||
useSWR(transferToLayingId, (id: number) =>
|
||||
TransferToLayingApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!transferToLayingId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!isLoadingTransferToLaying &&
|
||||
(!transferToLaying || isResponseError(transferToLaying))
|
||||
) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
isResponseSuccess(transferToLaying) &&
|
||||
transferToLaying.data.approval.step_number === 2
|
||||
) {
|
||||
router.replace('/production/transfer-to-laying');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingTransferToLaying && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
{!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
|
||||
<TransferToLayingForm
|
||||
type='edit'
|
||||
initialValues={transferToLaying.data}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferToLayingEdit;
|
||||
@@ -1,11 +0,0 @@
|
||||
import SuspenseHelper from '@/components/helper/SuspenseHelper';
|
||||
|
||||
const Layout = ({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) => {
|
||||
return <SuspenseHelper>{children}</SuspenseHelper>;
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
@@ -1,56 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import TransferToLayingForm from '@/components/pages/production/transfer-to-laying/form/TransferToLayingForm';
|
||||
|
||||
import { TransferToLayingApi } from '@/services/api/production/transfer-to-laying';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
const TransferToLayingDetail = () => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const transferToLayingId = searchParams.get('transferToLayingId');
|
||||
|
||||
const { data: transferToLaying, isLoading: isLoadingTransferToLaying } =
|
||||
useSWR(transferToLayingId, (id: number) =>
|
||||
TransferToLayingApi.getSingle(id)
|
||||
);
|
||||
|
||||
if (!transferToLayingId) {
|
||||
router.back();
|
||||
|
||||
return (
|
||||
<div className='w-full flex flex-row justify-center items-center p-4'>
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!isLoadingTransferToLaying &&
|
||||
(!transferToLaying || isResponseError(transferToLaying))
|
||||
) {
|
||||
router.replace('/404');
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-row justify-center'>
|
||||
{isLoadingTransferToLaying && (
|
||||
<span className='loading loading-spinner loading-xl' />
|
||||
)}
|
||||
|
||||
{!isLoadingTransferToLaying && isResponseSuccess(transferToLaying) && (
|
||||
<TransferToLayingForm
|
||||
type='detail'
|
||||
initialValues={transferToLaying.data}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferToLayingDetail;
|
||||
@@ -1,9 +1,15 @@
|
||||
import TransferToLayingsTable from '@/components/pages/production/transfer-to-laying/TransferToLayingsTable';
|
||||
import TransferToLayingFormModal from '@/components/pages/production/transfer-to-laying/TransferToLayingFormModal';
|
||||
import TransferToLayingDetailModal from '@/components/pages/production/transfer-to-laying/TransferToLayingDetailModal';
|
||||
|
||||
const TransferToLaying = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<section className='w-full'>
|
||||
<TransferToLayingsTable />
|
||||
|
||||
<TransferToLayingFormModal />
|
||||
|
||||
<TransferToLayingDetailModal />
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@ import PurchaseTable from '@/components/pages/purchase/PurchaseTable';
|
||||
|
||||
const Purchase = () => {
|
||||
return (
|
||||
<section className='w-full p-4'>
|
||||
<section className='w-full p-4 sm:p-0'>
|
||||
<PurchaseTable />
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import React, { useId } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { cn, findMenuPath } from '@/lib/helper';
|
||||
import { Size } from '@/types/theme';
|
||||
import Button from '@/components/Button';
|
||||
import { MAIN_DRAWER_LINKS } from '@/config/constant';
|
||||
|
||||
interface BreadcrumbItem {
|
||||
label: string;
|
||||
href?: string;
|
||||
icon?: React.ReactNode;
|
||||
isActive?: boolean;
|
||||
isDisabled?: boolean;
|
||||
}
|
||||
|
||||
interface BreadcrumbsProps extends React.HTMLAttributes<HTMLElement> {
|
||||
items: BreadcrumbItem[];
|
||||
size?: Size;
|
||||
maxVisibleItems?: number;
|
||||
showEllipsisDropdown?: boolean;
|
||||
}
|
||||
|
||||
export function buildBreadcrumbs(pathname: string): BreadcrumbItem[] {
|
||||
const menuPath = findMenuPath(MAIN_DRAWER_LINKS, pathname);
|
||||
|
||||
if (!menuPath) return [];
|
||||
|
||||
return menuPath.map((menu, index) => {
|
||||
const isLast = index === menuPath.length - 1;
|
||||
|
||||
return {
|
||||
label: menu.text,
|
||||
href: isLast ? menu.link : undefined,
|
||||
isActive: isLast,
|
||||
icon: menu.icon ? (
|
||||
<Icon icon={menu.icon} width={16} height={16} />
|
||||
) : undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const EllipsisDropdown = ({
|
||||
hiddenItems,
|
||||
}: {
|
||||
hiddenItems: BreadcrumbItem[];
|
||||
}) => {
|
||||
const dropdownId = useId();
|
||||
const anchorId = useId();
|
||||
|
||||
return (
|
||||
<li>
|
||||
{/* Ellipsis Button */}
|
||||
<Button
|
||||
popoverTarget={dropdownId}
|
||||
variant='ghost'
|
||||
color='none'
|
||||
style={
|
||||
{
|
||||
anchorName: `--breadcrumb-ellipsis-anchor-${anchorId}`,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
<Icon icon='material-symbols:more-horiz' width={16} height={16} />
|
||||
</Button>
|
||||
|
||||
{/* Dropdown Menu using popover API */}
|
||||
<ul
|
||||
className='dropdown menu rounded-box bg-base-100 border border-base-300 shadow-lg z-[9999] [&_a:hover]:no-underline [&_a:focus]:no-underline [&&]:no-underline [&&_a]:no-underline [&&]:hover:no-underline [&&]:flex [&&]:items-start [&&]:justify-start w-max'
|
||||
popover='auto'
|
||||
id={dropdownId}
|
||||
style={
|
||||
{
|
||||
positionAnchor: `--breadcrumb-ellipsis-anchor-${anchorId}`,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
>
|
||||
{hiddenItems.map((item, index) => {
|
||||
const itemStyles = cn(
|
||||
'[&]:flex [&]:items-center [&]:justify-start py-1 text-sm',
|
||||
// Disabled state
|
||||
item.isDisabled && 'text-base-content/40 opacity-50',
|
||||
// Active/Last state
|
||||
(item.isActive || item.isDisabled) && 'text-primary',
|
||||
// Regular clickable state
|
||||
!item.isDisabled && 'text-base-content/50'
|
||||
);
|
||||
|
||||
const itemContent = (
|
||||
<div className={itemStyles}>
|
||||
{item.icon && (
|
||||
<span className='inline-flex mr-2'>{item.icon}</span>
|
||||
)}
|
||||
{item.label}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<li
|
||||
key={`ellipsis-${index}`}
|
||||
className='[&&]:text-left [&&]:block w-full'
|
||||
>
|
||||
{item.href && !item.isDisabled ? (
|
||||
<Link
|
||||
href={item.href}
|
||||
className='block !no-underline [&&]:text-left w-full'
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{itemContent}
|
||||
</Link>
|
||||
) : (
|
||||
<div className='block !no-underline [&&]:cursor-default [&&]:hover:cursor-default [&&]:hover:bg-base-100 [&&]:text-left'>
|
||||
{itemContent}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
const Breadcrumb = ({
|
||||
items,
|
||||
size = 'md',
|
||||
maxVisibleItems = 3,
|
||||
showEllipsisDropdown = true,
|
||||
className,
|
||||
...props
|
||||
}: BreadcrumbsProps) => {
|
||||
const sizeClasses = {
|
||||
xs: 'text-xs',
|
||||
sm: 'text-sm',
|
||||
md: 'text-base',
|
||||
lg: 'text-lg',
|
||||
xl: 'text-xl',
|
||||
};
|
||||
|
||||
const getItemStyles = (
|
||||
item: BreadcrumbItem,
|
||||
position: 'first' | 'middle' | 'last' = 'middle'
|
||||
) => {
|
||||
const baseClasses = 'inline-flex items-center gap-2';
|
||||
|
||||
// Disabled state
|
||||
if (item.isDisabled) {
|
||||
return `${baseClasses} text-base-content/40 !cursor-default opacity-50 hover:!no-underline`;
|
||||
}
|
||||
|
||||
// Active/Last state (no underline)
|
||||
if (item.isActive || position === 'last') {
|
||||
return `${baseClasses} text-primary !cursor-pointer hover:!no-underline`;
|
||||
}
|
||||
|
||||
// Regular clickable state
|
||||
return `${baseClasses} text-base-content/60`;
|
||||
};
|
||||
|
||||
const renderItem = (
|
||||
item: BreadcrumbItem,
|
||||
position: 'first' | 'middle' | 'last' = 'middle'
|
||||
) => {
|
||||
const styles = getItemStyles(item, position);
|
||||
|
||||
// Disabled items
|
||||
if (item.isDisabled) {
|
||||
return (
|
||||
<span className={styles}>
|
||||
{item.icon && item.icon}
|
||||
{item.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Active/Last items
|
||||
if (item.isActive || position === 'last') {
|
||||
if (item.href) {
|
||||
return (
|
||||
<Link href={item.href} className={styles}>
|
||||
{item.icon && (
|
||||
<span className='inline-flex gap-2'>{item.icon}</span>
|
||||
)}
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className={styles}>
|
||||
{item.icon && item.icon}
|
||||
{item.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular items
|
||||
if (item.href) {
|
||||
return (
|
||||
<Link href={item.href} className={styles}>
|
||||
{item.icon && <span className='inline-flex gap-2'>{item.icon}</span>}
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={styles}>
|
||||
{item.icon && item.icon}
|
||||
{item.label}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const renderBreadcrumbList = () => {
|
||||
// Show all items if within limit
|
||||
if (items.length <= maxVisibleItems) {
|
||||
return items.map((item, index) => {
|
||||
const position =
|
||||
index === 0
|
||||
? 'first'
|
||||
: index === items.length - 1
|
||||
? 'last'
|
||||
: 'middle';
|
||||
return <li key={index}>{renderItem(item, position)}</li>;
|
||||
});
|
||||
}
|
||||
|
||||
// Collapsed items indexing when exceeding limit
|
||||
const firstItem = items[0];
|
||||
const lastItem = items[items.length - 1];
|
||||
const visibleMiddleItems = items.slice(1, -1).slice(-(maxVisibleItems - 2));
|
||||
const hiddenItems = items.slice(1, -1).slice(0, -(maxVisibleItems - 2));
|
||||
const showEllipsis = showEllipsisDropdown && hiddenItems.length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<li>{renderItem(firstItem, 'first')}</li>
|
||||
|
||||
{/* Ellipsis for hidden items with dropdown */}
|
||||
{showEllipsis && <EllipsisDropdown hiddenItems={hiddenItems} />}
|
||||
|
||||
{/* Middle items */}
|
||||
{visibleMiddleItems.map((item, index) => (
|
||||
<li key={`middle-${index}`}>{renderItem(item, 'middle')}</li>
|
||||
))}
|
||||
|
||||
<li>{renderItem(lastItem, 'last')}</li>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<nav
|
||||
aria-label='Breadcrumb'
|
||||
className={cn('breadcrumbs', sizeClasses[size], className)}
|
||||
{...props}
|
||||
>
|
||||
<ul className='text-sm'>{renderBreadcrumbList()}</ul>
|
||||
</nav>
|
||||
);
|
||||
};
|
||||
|
||||
export default Breadcrumb;
|
||||
@@ -2,11 +2,12 @@ import react from 'react';
|
||||
import Link from 'next/link';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Color } from '@/types/theme';
|
||||
import { UrlObject } from 'url';
|
||||
|
||||
export interface ButtonProps extends react.ComponentProps<'button'> {
|
||||
variant?: 'soft' | 'outline' | 'dash' | 'ghost' | 'link' | 'active';
|
||||
color?: Color;
|
||||
href?: string;
|
||||
href?: string | UrlObject;
|
||||
isLoading?: boolean;
|
||||
target?: string;
|
||||
rel?: string;
|
||||
|
||||
+17
-3
@@ -22,6 +22,7 @@ export interface CardProps
|
||||
onCollapsedChange?: (collapsed: boolean) => void;
|
||||
className?: {
|
||||
wrapper?: string;
|
||||
wrapperContent?: string;
|
||||
image?: string;
|
||||
body?: string;
|
||||
title?: string;
|
||||
@@ -122,6 +123,10 @@ const Card = ({
|
||||
return cn(baseClasses, 'p-6', className?.body);
|
||||
};
|
||||
|
||||
const getCollapsibleClasses = () => {
|
||||
return cn('', className?.collapsible);
|
||||
};
|
||||
|
||||
const getTitleClasses = () => {
|
||||
const sizeClasses = {
|
||||
sm: 'text-lg',
|
||||
@@ -144,11 +149,19 @@ const Card = ({
|
||||
return cn('border-t border-base-300 mt-4 pt-4', className?.footer);
|
||||
};
|
||||
|
||||
const getWrapperContentClasses = () => {
|
||||
return cn('space-y-4', className?.wrapperContent);
|
||||
};
|
||||
|
||||
const renderCardContent = () => {
|
||||
const hasContent = children || actions || footer;
|
||||
|
||||
const titleContent = (
|
||||
<div className='group flex items-center !justify-between w-full'>
|
||||
<div
|
||||
className={
|
||||
`group flex items-center justify-between! w-full` + getTitleClasses()
|
||||
}
|
||||
>
|
||||
<div className='flex-1'>
|
||||
{title && <h2 className={getTitleClasses()}>{title}</h2>}
|
||||
{subtitle && <p className={getSubtitleClasses()}>{subtitle}</p>}
|
||||
@@ -156,7 +169,7 @@ const Card = ({
|
||||
{collapsible && (
|
||||
<button
|
||||
onClick={() => handleCollapsedChange(!isCollapsed)}
|
||||
className='btn btn-ghost btn-sm btn-circle'
|
||||
className={`btn btn-ghost btn-sm btn-circle` + getTitleClasses()}
|
||||
aria-label={isCollapsed ? 'Expand content' : 'Collapse content'}
|
||||
>
|
||||
<Icon
|
||||
@@ -173,7 +186,7 @@ const Card = ({
|
||||
);
|
||||
|
||||
const cardContent = (
|
||||
<div className='space-y-4'>
|
||||
<div className={getWrapperContentClasses()}>
|
||||
{children}
|
||||
{actions && <div className={getActionsClasses()}>{actions}</div>}
|
||||
{footer && <div className={getFooterClasses()}>{footer}</div>}
|
||||
@@ -204,6 +217,7 @@ const Card = ({
|
||||
titleClassName='w-full cursor-pointer'
|
||||
contentClassName='p-0'
|
||||
fullWidth={true}
|
||||
className={getCollapsibleClasses()}
|
||||
>
|
||||
{cardContent}
|
||||
</Collapse>
|
||||
|
||||
@@ -162,7 +162,7 @@ const Drawer = ({
|
||||
<div
|
||||
className={cn(
|
||||
varianClassName?.drawerSidebarContent,
|
||||
className?.drawerContent,
|
||||
className?.drawerSidebarContent,
|
||||
'overflow-y-auto'
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -26,29 +26,34 @@ const MainDrawerContent = () => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='w-full p-4 flex flex-col gap-4'>
|
||||
<div className='flex flex-row items-center gap-4'>
|
||||
<Image
|
||||
src='/assets/img/lti-logo.png'
|
||||
alt='MBU Logo'
|
||||
width={256}
|
||||
height={256}
|
||||
className='w-full max-w-16 h-auto'
|
||||
/>
|
||||
<div className='w-full flex flex-col'>
|
||||
<div className='p-3 flex flex-row items-center gap-4 border-b border-base-content/10'>
|
||||
<div className='flex flex-row items-center gap-2'>
|
||||
<Image
|
||||
src='/assets/img/lti-logo.png'
|
||||
alt='LTI Logo'
|
||||
width={40}
|
||||
height={40}
|
||||
className='w-full max-w-10 h-auto'
|
||||
/>
|
||||
|
||||
<h1 className='text-xl font-bold'>LTI ERP</h1>
|
||||
<div className='font-roboto'>
|
||||
<h1 className='text-sm font-semibold'>LTI ERP</h1>
|
||||
<p className='text-sm text-black/50'>Lumbung Telur Indonesia</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='grow flex flex-row justify-end sm:hidden'>
|
||||
<Button
|
||||
variant='soft'
|
||||
color='error'
|
||||
onClick={closeMainDrawerHandler}
|
||||
className='rounded-full'
|
||||
className='p-1 rounded-full'
|
||||
>
|
||||
<Icon
|
||||
icon='material-symbols:close-rounded'
|
||||
width={24}
|
||||
height={24}
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
@@ -73,40 +78,6 @@ const MainDrawer = ({
|
||||
permissionCheck(permission)
|
||||
);
|
||||
|
||||
const getPageTitle = useCallback(() => {
|
||||
let title = '';
|
||||
|
||||
const activeMenu = MAIN_DRAWER_LINKS.find((item) =>
|
||||
isPathActive(pathname, item.link)
|
||||
);
|
||||
|
||||
const traverseMenuTitle = (menu: typeof activeMenu) => {
|
||||
if (!menu) return;
|
||||
|
||||
const hasSubmenu = menu?.submenu && menu?.submenu.length > 0;
|
||||
|
||||
if (!title) {
|
||||
title += menu?.text;
|
||||
} else {
|
||||
title += ' - ' + menu?.text;
|
||||
}
|
||||
|
||||
if (!hasSubmenu || !menu.submenu) return;
|
||||
|
||||
const activeSubmenu = menu.submenu?.find((item) =>
|
||||
isPathActive(pathname, item.link)
|
||||
);
|
||||
|
||||
traverseMenuTitle(activeSubmenu);
|
||||
};
|
||||
|
||||
traverseMenuTitle(activeMenu);
|
||||
|
||||
return title;
|
||||
}, [pathname]);
|
||||
|
||||
const pageTitle = getPageTitle();
|
||||
|
||||
const toggleSidebar = () => {
|
||||
setMainDrawerOpen(!mainDrawerOpen);
|
||||
};
|
||||
@@ -121,9 +92,13 @@ const MainDrawer = ({
|
||||
setOpen={setMainDrawerOpen}
|
||||
openOnLarge
|
||||
sidebarContent={<MainDrawerContent />}
|
||||
className={{
|
||||
drawerSide: 'border-r border-base-content/10',
|
||||
drawerSidebarContent: 'min-w-[244px] lg:w-[244px]',
|
||||
}}
|
||||
>
|
||||
<main className='w-full h-full flex flex-col'>
|
||||
<Navbar title={pageTitle as string} toggleSidebar={toggleSidebar} />
|
||||
<Navbar toggleSidebar={toggleSidebar} />
|
||||
|
||||
{children}
|
||||
</main>
|
||||
|
||||
@@ -53,15 +53,25 @@ interface ModalProps {
|
||||
ref: RefObject<HTMLDialogElement | null>;
|
||||
children?: ReactNode;
|
||||
closeOnBackdrop?: boolean;
|
||||
onBackdropClick?: () => void;
|
||||
position?: 'top' | 'middle' | 'bottom' | 'start' | 'end';
|
||||
className?: {
|
||||
modal?: string;
|
||||
modalBox?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const Modal = ({ ref, children, closeOnBackdrop, className }: ModalProps) => {
|
||||
const Modal = ({
|
||||
ref,
|
||||
children,
|
||||
closeOnBackdrop,
|
||||
onBackdropClick,
|
||||
position = 'middle',
|
||||
className,
|
||||
}: ModalProps) => {
|
||||
const handleBackdropClick = (e: React.MouseEvent<HTMLDialogElement>) => {
|
||||
if (closeOnBackdrop && e.target === ref.current) {
|
||||
onBackdropClick?.();
|
||||
ref.current?.close();
|
||||
}
|
||||
};
|
||||
@@ -69,7 +79,17 @@ const Modal = ({ ref, children, closeOnBackdrop, className }: ModalProps) => {
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
className={cn('modal', className?.modal)}
|
||||
className={cn(
|
||||
'modal',
|
||||
{
|
||||
'modal-top': position === 'top',
|
||||
'modal-middle': position === 'middle',
|
||||
'modal-bottom': position === 'bottom',
|
||||
'modal-start': position === 'start',
|
||||
'modal-end': position === 'end',
|
||||
},
|
||||
className?.modal
|
||||
)}
|
||||
onClick={handleBackdropClick}
|
||||
>
|
||||
<div className={cn('modal-box', className?.modalBox)}>{children}</div>
|
||||
|
||||
+46
-32
@@ -1,26 +1,28 @@
|
||||
'use client';
|
||||
|
||||
import toast from 'react-hot-toast';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
|
||||
import { Icon } from '@iconify/react';
|
||||
import Menu from '@/components/menu/Menu';
|
||||
import MenuItem from '@/components/menu/MenuItem';
|
||||
import Button from '@/components/Button';
|
||||
import Dropdown from '@/components/Dropdown';
|
||||
import Breadcrumb, { buildBreadcrumbs } from '@/components/Breadcrumb';
|
||||
import PopoverButton from '@/components/popover/PopoverButton';
|
||||
import PopoverContent from '@/components/popover/PopoverContent';
|
||||
|
||||
import { useAuth } from '@/services/hooks/useAuth';
|
||||
import { AuthApi } from '@/services/api/auth';
|
||||
import { isResponseError } from '@/lib/api-helper';
|
||||
import { useUiStore } from '@/stores/ui/ui.store';
|
||||
|
||||
interface NavbarProps {
|
||||
title: string;
|
||||
toggleSidebar?: () => void;
|
||||
}
|
||||
|
||||
const Navbar = ({ title, toggleSidebar }: NavbarProps) => {
|
||||
const Navbar = ({ toggleSidebar }: NavbarProps) => {
|
||||
const { setUser } = useAuth();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const navbarActions = useUiStore((state) => state.navbarActions);
|
||||
|
||||
const logoutClickHandler = async () => {
|
||||
const logoutRes = await AuthApi.logout();
|
||||
@@ -35,42 +37,54 @@ const Navbar = ({ title, toggleSidebar }: NavbarProps) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='navbar px-4 bg-base-100 shadow-sm'>
|
||||
<div className='navbar p-3 bg-base-100 border-b border-base-content/10'>
|
||||
<div className='flex-1'>
|
||||
<div className='flex flex-row items-center gap-4'>
|
||||
{toggleSidebar && (
|
||||
<Button onClick={toggleSidebar} className='block lg:hidden'>
|
||||
<Icon
|
||||
icon='material-symbols:menu-rounded'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
<Button
|
||||
variant='ghost'
|
||||
color='none'
|
||||
onClick={toggleSidebar}
|
||||
className='block lg:hidden p-[9px] text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
|
||||
>
|
||||
<Icon icon='heroicons:bars-3' width={20} height={20} />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<span className='font-bold text-xl text-primary'>{title}</span>
|
||||
<Breadcrumb items={buildBreadcrumbs(pathname)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='flex gap-2'>
|
||||
<Dropdown
|
||||
align='end'
|
||||
direction='bottom'
|
||||
trigger={
|
||||
<div className='btn btn-ghost btn-circle avatar'>
|
||||
<div className='w-10 rounded-full border flex justify-center items-center'>
|
||||
<Icon icon='uil:user' width={40} height={40} />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
className={{
|
||||
content: 'w-52 mt-3',
|
||||
}}
|
||||
<div className='flex gap-2 items-center'>
|
||||
{/* Page-specific actions */}
|
||||
{navbarActions && <div className='mr-2'>{navbarActions}</div>}
|
||||
<PopoverButton
|
||||
tabIndex={0}
|
||||
variant='ghost'
|
||||
color='none'
|
||||
popoverTarget='accountNavbar'
|
||||
anchorName='--account-navbar'
|
||||
className='p-[9px] text-base-content/50 border border-base-content/10 rounded-xl shadow-button-soft'
|
||||
>
|
||||
<Menu>
|
||||
<MenuItem title='Logout' onClick={logoutClickHandler} />
|
||||
</Menu>
|
||||
</Dropdown>
|
||||
<Icon icon='heroicons:user' width={20} height={20} />
|
||||
</PopoverButton>
|
||||
|
||||
<PopoverContent
|
||||
id='accountNavbar'
|
||||
anchorName='--account-navbar'
|
||||
position='bottom-start'
|
||||
className='rounded-xl border border-base-content/5 shadow-sm'
|
||||
>
|
||||
<Button
|
||||
onClick={logoutClickHandler}
|
||||
variant='ghost'
|
||||
color='error'
|
||||
className='p-3 justify-start text-sm font-semibold w-full'
|
||||
>
|
||||
<Icon icon='heroicons-outline:logout' width={20} height={20} />
|
||||
Logout
|
||||
</Button>
|
||||
</PopoverContent>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+180
-49
@@ -1,11 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { ReactNode, useCallback, useEffect, useState } from 'react';
|
||||
import { Fragment, ReactNode, useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
getFilteredRowModel,
|
||||
getPaginationRowModel,
|
||||
getExpandedRowModel,
|
||||
getSortedRowModel,
|
||||
TableOptions,
|
||||
useReactTable,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
OnChangeFn,
|
||||
Row,
|
||||
HeaderContext,
|
||||
ExpandedState,
|
||||
} from '@tanstack/react-table';
|
||||
import { rankItem } from '@tanstack/match-sorter-utils';
|
||||
import { Icon } from '@iconify/react';
|
||||
@@ -31,11 +33,16 @@ interface TableClassNames {
|
||||
headerColumnClassName?: string;
|
||||
tableBodyClassName?: string;
|
||||
bodyRowClassName?: string;
|
||||
selectedBodyRowClassName?: string;
|
||||
bodyColumnClassName?: string;
|
||||
bodySubRowClassName?: (depth: number) => string;
|
||||
selectedBodySubRowClassName?: (depth: number) => string;
|
||||
bodySubRowColumnClassName?: (depth: number) => string;
|
||||
tableFooterClassName?: string;
|
||||
footerRowClassName?: string;
|
||||
footerColumnClassName?: string;
|
||||
paginationClassName?: string;
|
||||
skeletonCellClassName?: string;
|
||||
}
|
||||
|
||||
export interface TableProps<TData extends object> {
|
||||
@@ -59,6 +66,7 @@ export interface TableProps<TData extends object> {
|
||||
enableRowSelection?: boolean | ((row: Row<TData>) => boolean);
|
||||
renderFooter?: boolean;
|
||||
withCheckbox?: boolean;
|
||||
withPagination?: boolean;
|
||||
rowOptions?: number[];
|
||||
/**
|
||||
* Custom row renderer. Should return a complete <tr> element or null.
|
||||
@@ -66,9 +74,15 @@ export interface TableProps<TData extends object> {
|
||||
* Return null to render the default row.
|
||||
*/
|
||||
renderCustomRow?: (row: Row<TData>) => ReactNode | null;
|
||||
getRowCanExpand?: (row: Row<TData>) => boolean;
|
||||
renderSubComponent?: (props: { row: Row<TData> }) => React.ReactElement;
|
||||
expanded?: ExpandedState;
|
||||
getSubRows?: (originalRow: TData, index: number) => TData[] | undefined;
|
||||
}
|
||||
|
||||
const DUMMY_SKELETON_DATA = [{}, {}, {}, {}, {}];
|
||||
const DUMMY_SKELETON_DATA = Array.from({ length: 10 }, (_, index) => ({
|
||||
id: index,
|
||||
}));
|
||||
|
||||
const emptyContentDefaultValue = (
|
||||
<div className='w-full p-5 text-center'>
|
||||
@@ -86,11 +100,18 @@ export const TABLE_DEFAULT_STYLING = {
|
||||
tableHeaderClassName: '',
|
||||
headerRowClassName: '',
|
||||
headerColumnClassName:
|
||||
'px-4 py-3 border-base-content/10 text-base-content/50',
|
||||
'px-4 py-3 border-base-content/10 text-base-content/50 text-sm font-medium',
|
||||
tableBodyClassName: '',
|
||||
bodyRowClassName: 'border-t border-base-content/10',
|
||||
bodyColumnClassName: 'px-4 py-3 text-base-content',
|
||||
paginationClassName: '',
|
||||
bodyRowClassName:
|
||||
'transition-all duration-200 border-t border-base-content/10 bg-transparent',
|
||||
selectedBodyRowClassName: 'bg-primary/5',
|
||||
bodyColumnClassName: 'px-4 py-3 text-base-content font-medium',
|
||||
bodySubRowClassName: (depth: number) =>
|
||||
'transition-all duration-200 border-t border-base-content/10 bg-transparent',
|
||||
selectedBodySubRowClassName: (depth: number) => 'bg-primary/5',
|
||||
bodySubRowColumnClassName: (depth: number) =>
|
||||
'px-4 py-3 text-base-content font-medium',
|
||||
paginationClassName: 'px-3',
|
||||
tableFooterClassName: 'font-semibold border-base-content/10',
|
||||
footerRowClassName: 'bg-base-200 border-t-2 border-base-content/10',
|
||||
footerColumnClassName: 'p-4 text-base-content whitespace-nowrap',
|
||||
@@ -117,8 +138,13 @@ const Table = <TData extends object>({
|
||||
enableRowSelection,
|
||||
renderFooter = false,
|
||||
withCheckbox = false,
|
||||
withPagination = true,
|
||||
rowOptions = [10, 20, 50, 100],
|
||||
renderCustomRow,
|
||||
getRowCanExpand,
|
||||
renderSubComponent,
|
||||
expanded = {},
|
||||
getSubRows,
|
||||
}: TableProps<TData>) => {
|
||||
const isServerSideTable =
|
||||
totalItems !== undefined &&
|
||||
@@ -151,10 +177,14 @@ const Table = <TData extends object>({
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getPaginationRowModel: getPaginationRowModel(),
|
||||
onPaginationChange: setPagination,
|
||||
getExpandedRowModel: getExpandedRowModel(),
|
||||
getRowCanExpand: getRowCanExpand ?? (getSubRows ? undefined : () => false),
|
||||
getSubRows,
|
||||
manualSorting,
|
||||
state: {
|
||||
pagination,
|
||||
globalFilter: fuzzySearchValue,
|
||||
expanded,
|
||||
},
|
||||
filterFns: {
|
||||
fuzzy: fuzzyFilter,
|
||||
@@ -222,14 +252,40 @@ const Table = <TData extends object>({
|
||||
}, [pageSize, setPageSize]);
|
||||
|
||||
return (
|
||||
<div className={tableClassNames.containerClassName}>
|
||||
<div className={tableClassNames.tableWrapperClassName}>
|
||||
<table className={tableClassNames.tableClassName}>
|
||||
<thead className={tableClassNames.tableHeaderClassName}>
|
||||
<div
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.containerClassName,
|
||||
tableClassNames.containerClassName,
|
||||
{
|
||||
'mb-0': !withPagination,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.tableWrapperClassName,
|
||||
tableClassNames.tableWrapperClassName
|
||||
)}
|
||||
>
|
||||
<table
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.tableClassName,
|
||||
tableClassNames.tableClassName
|
||||
)}
|
||||
>
|
||||
<thead
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.tableHeaderClassName,
|
||||
tableClassNames.tableHeaderClassName
|
||||
)}
|
||||
>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<tr
|
||||
key={headerGroup.id}
|
||||
className={tableClassNames.headerRowClassName}
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.headerRowClassName,
|
||||
tableClassNames.headerRowClassName
|
||||
)}
|
||||
>
|
||||
{headerGroup.headers.map((header) => {
|
||||
const columnRelativeDepth =
|
||||
@@ -262,6 +318,7 @@ const Table = <TData extends object>({
|
||||
{
|
||||
'border-b': header.colSpan > 1,
|
||||
},
|
||||
TABLE_DEFAULT_STYLING.headerColumnClassName,
|
||||
tableClassNames.headerColumnClassName
|
||||
)}
|
||||
>
|
||||
@@ -311,7 +368,12 @@ const Table = <TData extends object>({
|
||||
))}
|
||||
</thead>
|
||||
|
||||
<tbody className={tableClassNames.tableBodyClassName}>
|
||||
<tbody
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.tableBodyClassName,
|
||||
tableClassNames.tableBodyClassName
|
||||
)}
|
||||
>
|
||||
{table.getRowModel().rows.map((row) => {
|
||||
const customRowContent = renderCustomRow?.(row);
|
||||
|
||||
@@ -320,36 +382,96 @@ const Table = <TData extends object>({
|
||||
}
|
||||
|
||||
return (
|
||||
<tr key={row.id} className={tableClassNames.bodyRowClassName}>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td
|
||||
key={cell.id}
|
||||
className={cn(
|
||||
{ 'first:w-9 first:pr-0': withCheckbox },
|
||||
tableClassNames.bodyColumnClassName
|
||||
)}
|
||||
>
|
||||
{!isLoading &&
|
||||
flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext()
|
||||
<Fragment key={row.id}>
|
||||
<tr
|
||||
data-depth={row.depth}
|
||||
className={cn(
|
||||
row.depth > 0
|
||||
? tableClassNames.bodySubRowClassName(row.depth)
|
||||
: tableClassNames.bodyRowClassName,
|
||||
{
|
||||
[tableClassNames.selectedBodyRowClassName!]:
|
||||
row.getIsSelected() && row.depth === 0,
|
||||
[tableClassNames.selectedBodySubRowClassName(
|
||||
row.depth
|
||||
)!]: row.getIsSelected() && row.depth > 0,
|
||||
}
|
||||
)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<td
|
||||
key={cell.id}
|
||||
className={cn(
|
||||
{ 'first:w-9 first:pr-0': withCheckbox },
|
||||
TABLE_DEFAULT_STYLING.bodyColumnClassName,
|
||||
row.depth > 0
|
||||
? tableClassNames.bodySubRowColumnClassName(
|
||||
row.depth
|
||||
)
|
||||
: tableClassNames.bodyColumnClassName
|
||||
)}
|
||||
>
|
||||
{!isLoading &&
|
||||
flexRender(
|
||||
cell.column.columnDef.cell,
|
||||
cell.getContext()
|
||||
)}
|
||||
|
||||
{isLoading && <div className='skeleton w-full h-4' />}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
{isLoading && (
|
||||
<div
|
||||
className={cn(
|
||||
'skeleton w-full h-4',
|
||||
tableClassNames.skeletonCellClassName
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
|
||||
{row.getIsExpanded() && (
|
||||
<>
|
||||
{renderSubComponent && (
|
||||
<tr
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.bodySubRowClassName(1),
|
||||
tableClassNames.bodySubRowClassName(1),
|
||||
{
|
||||
[tableClassNames.selectedBodySubRowClassName(1)]:
|
||||
row.getIsSelected(),
|
||||
}
|
||||
)}
|
||||
>
|
||||
<td colSpan={row.getVisibleCells().length}>
|
||||
{renderSubComponent({ row })}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot className={cn(tableClassNames.tableFooterClassName)}>
|
||||
<tfoot
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.tableFooterClassName,
|
||||
tableClassNames.tableFooterClassName
|
||||
)}
|
||||
>
|
||||
{renderFooter && (
|
||||
<tr className={cn(tableClassNames.footerRowClassName)}>
|
||||
<tr
|
||||
className={cn(
|
||||
TABLE_DEFAULT_STYLING.footerRowClassName,
|
||||
tableClassNames.footerRowClassName
|
||||
)}
|
||||
>
|
||||
{table.getAllLeafColumns().map((column) => (
|
||||
<td
|
||||
key={column.id}
|
||||
className={cn(
|
||||
{ 'first:w-9 first:pr-0': withCheckbox },
|
||||
TABLE_DEFAULT_STYLING.footerColumnClassName,
|
||||
tableClassNames.footerColumnClassName
|
||||
)}
|
||||
>
|
||||
@@ -371,24 +493,33 @@ const Table = <TData extends object>({
|
||||
!isLoading &&
|
||||
emptyContent}
|
||||
|
||||
{data.length > 0 && table.getRowModel().rows.length > 0 && !isLoading && (
|
||||
<div className={cn('mt-5', tableClassNames.paginationClassName)}>
|
||||
<Pagination
|
||||
totalItems={isServerSideTable ? totalItems : table.getRowCount()}
|
||||
itemsPerPage={table.getState().pagination.pageSize}
|
||||
currentPage={
|
||||
isServerSideTable
|
||||
? page
|
||||
: table.getState().pagination.pageIndex + 1
|
||||
}
|
||||
onPrevPage={prevPageClickHandler}
|
||||
onNextPage={nextPageClickHandler}
|
||||
onPageChange={pageChangeHandler}
|
||||
rowOptions={rowOptions}
|
||||
onRowChange={onPageSizeChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{data.length > 0 &&
|
||||
table.getRowModel().rows.length > 0 &&
|
||||
!isLoading &&
|
||||
withPagination && (
|
||||
<div
|
||||
className={cn(
|
||||
'mt-5',
|
||||
TABLE_DEFAULT_STYLING.paginationClassName,
|
||||
tableClassNames.paginationClassName
|
||||
)}
|
||||
>
|
||||
<Pagination
|
||||
totalItems={isServerSideTable ? totalItems : table.getRowCount()}
|
||||
itemsPerPage={table.getState().pagination.pageSize}
|
||||
currentPage={
|
||||
isServerSideTable
|
||||
? page
|
||||
: table.getState().pagination.pageIndex + 1
|
||||
}
|
||||
onPrevPage={prevPageClickHandler}
|
||||
onNextPage={nextPageClickHandler}
|
||||
onPageChange={pageChangeHandler}
|
||||
rowOptions={rowOptions}
|
||||
onRowChange={onPageSizeChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+23
-12
@@ -25,8 +25,10 @@ export interface TabsProps
|
||||
wrapper?: string;
|
||||
tab?: string;
|
||||
content?: string;
|
||||
tabHeaderWrapper?: string;
|
||||
};
|
||||
onTabChange?: (tabId: string) => void;
|
||||
sideContent?: ReactNode;
|
||||
}
|
||||
|
||||
const Tabs = ({
|
||||
@@ -38,6 +40,7 @@ const Tabs = ({
|
||||
activeTabId: controlledActiveId,
|
||||
className,
|
||||
onTabChange,
|
||||
sideContent,
|
||||
...props
|
||||
}: TabsProps) => {
|
||||
// State internal hanya dipakai kalau `activeTabId` (controlled) tidak diset
|
||||
@@ -59,6 +62,7 @@ const Tabs = ({
|
||||
wrapper: wrapperClassName,
|
||||
tab: tabClassName,
|
||||
content: contentClassName,
|
||||
tabHeaderWrapper: tabHeaderWrapperClassName,
|
||||
} = typeof className === 'object'
|
||||
? className
|
||||
: { wrapper: className, tab: undefined };
|
||||
@@ -102,6 +106,10 @@ const Tabs = ({
|
||||
tabClassName
|
||||
);
|
||||
|
||||
const getSideContentClasses = () => {
|
||||
return cn('flex flex-row', tabHeaderWrapperClassName);
|
||||
};
|
||||
|
||||
const activeContent = tabs.find((tab) => tab.id === activeTabId)?.content;
|
||||
|
||||
return (
|
||||
@@ -112,18 +120,21 @@ const Tabs = ({
|
||||
typeof className === 'string' ? className : containerClassName
|
||||
)}
|
||||
>
|
||||
<div role='tablist' className={getTabsClasses()}>
|
||||
{tabs.map(({ id, label, disabled }) => (
|
||||
<button
|
||||
key={id}
|
||||
role='tab'
|
||||
className={getTabClasses(id === activeTabId, disabled)}
|
||||
onClick={() => !disabled && handleTabChange(id)}
|
||||
disabled={disabled}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
<div className={getSideContentClasses()}>
|
||||
<div role='tablist' className={getTabsClasses()}>
|
||||
{tabs.map(({ id, label, disabled }) => (
|
||||
<button
|
||||
key={id}
|
||||
role='tab'
|
||||
className={getTabClasses(id === activeTabId, disabled)}
|
||||
onClick={() => !disabled && handleTabChange(id)}
|
||||
disabled={disabled}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{sideContent && sideContent}
|
||||
</div>
|
||||
|
||||
{activeContent && (
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { Icon } from '@iconify/react';
|
||||
import { BaseApproval } from '@/types/api/api-general';
|
||||
import Button from '@/components/Button';
|
||||
|
||||
import { cn, formatDate } from '@/lib/helper';
|
||||
|
||||
interface ApprovalStepsV2Props {
|
||||
approvals?: BaseApproval[];
|
||||
steps: {
|
||||
step_number: number;
|
||||
step_name: string;
|
||||
}[];
|
||||
maxVisibleSteps?: number;
|
||||
className?: {
|
||||
wrapper?: string;
|
||||
stepsWrapper?: string;
|
||||
stepsContainer?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const ApprovalStepsV2 = ({
|
||||
approvals,
|
||||
steps,
|
||||
maxVisibleSteps = 2,
|
||||
className,
|
||||
}: ApprovalStepsV2Props) => {
|
||||
const [isSeeAll, setIsSeeAll] = useState(false);
|
||||
const [formattedApprovals, setFormattedApprovals] = useState<
|
||||
(BaseApproval & { isActive: boolean })[]
|
||||
>([]);
|
||||
|
||||
const latestApprovalStepNumber =
|
||||
approvals?.[approvals.length - 1].step_number ?? 0;
|
||||
|
||||
const lastStepNumber = steps[steps.length - 1].step_number;
|
||||
|
||||
const isLatestApprovalStepNumberLessThanLastStepNumber =
|
||||
latestApprovalStepNumber < lastStepNumber;
|
||||
|
||||
const slicedFormattedApprovals = useMemo(() => {
|
||||
return formattedApprovals.slice(0, isSeeAll ? undefined : maxVisibleSteps);
|
||||
}, [formattedApprovals, isSeeAll]);
|
||||
|
||||
const seeMoreClickHandler = () => {
|
||||
setIsSeeAll((prevVal) => !prevVal);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (approvals) {
|
||||
const tempFormattedApprovals: (BaseApproval & { isActive: boolean })[] =
|
||||
[];
|
||||
|
||||
approvals.forEach((approval) => {
|
||||
tempFormattedApprovals.push({
|
||||
...approval,
|
||||
isActive: true,
|
||||
});
|
||||
});
|
||||
|
||||
if (isLatestApprovalStepNumberLessThanLastStepNumber) {
|
||||
const latestApprovalStepNumberIndexInSteps = steps.findIndex(
|
||||
(step) => step.step_number === latestApprovalStepNumber
|
||||
);
|
||||
|
||||
const slicedSteps = steps.slice(
|
||||
latestApprovalStepNumberIndexInSteps + 1
|
||||
);
|
||||
|
||||
slicedSteps.forEach((step) => {
|
||||
tempFormattedApprovals.push({
|
||||
action: 'APPROVED',
|
||||
action_at: new Date().toISOString(),
|
||||
action_by: {
|
||||
id: 0,
|
||||
id_user: 0,
|
||||
email: '',
|
||||
name: '',
|
||||
},
|
||||
step_name: step.step_name,
|
||||
step_number: step.step_number,
|
||||
isActive: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
setFormattedApprovals(tempFormattedApprovals);
|
||||
}
|
||||
}, [approvals]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full p-4 flex flex-col border-b border-base-content/10',
|
||||
className?.wrapper
|
||||
)}
|
||||
>
|
||||
<h4 className='text-base font-medium text-base-content/50 font-roboto'>
|
||||
Progress Details
|
||||
</h4>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'mt-6 mb-8 flex flex-col gap-10',
|
||||
className?.stepsWrapper
|
||||
)}
|
||||
>
|
||||
{slicedFormattedApprovals.map((approval, idx) => {
|
||||
const isApprovalActionCreated = approval.action === 'CREATED';
|
||||
const isApprovalActionUpdated = approval.action === 'UPDATED';
|
||||
const isApprovalActionRejected = approval.action === 'REJECTED';
|
||||
const isApprovalActionApproved = approval.action === 'APPROVED';
|
||||
|
||||
const approvalIcon =
|
||||
isApprovalActionCreated || isApprovalActionUpdated
|
||||
? 'heroicons:clock-solid'
|
||||
: isApprovalActionRejected
|
||||
? 'heroicons:x-circle-solid'
|
||||
: isApprovalActionApproved
|
||||
? 'heroicons:check-badge-solid'
|
||||
: 'heroicons:check-badge-solid';
|
||||
|
||||
return (
|
||||
<div key={idx} className='w-full flex flex-row items-stretch gap-3'>
|
||||
<div className='w-fit self-stretch relative'>
|
||||
<div className='w-fit h-fit flex flex-col items-start'>
|
||||
<Icon
|
||||
icon={approvalIcon}
|
||||
width={24}
|
||||
height={24}
|
||||
className={cn({
|
||||
'text-warning':
|
||||
isApprovalActionCreated || isApprovalActionUpdated,
|
||||
'text-error': isApprovalActionRejected,
|
||||
'text-success': isApprovalActionApproved,
|
||||
'text-base-content/20': !approval.isActive,
|
||||
})}
|
||||
/>
|
||||
|
||||
{idx < formattedApprovals.length - 1 && (
|
||||
<div className='absolute top-6 left-1/2 -translate-x-1/2 w-0 min-h-full h-[calc(100%)] mx-auto my-2 border border-dashed border-base-content/10' />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={cn('w-full flex flex-col gap-1 text-base-content', {
|
||||
'text-base-content/20': !approval.isActive,
|
||||
})}
|
||||
>
|
||||
<div className='flex flex-col'>
|
||||
<span className='text-xs'>{approval.step_name}</span>
|
||||
<span className='text-sm font-semibold'>
|
||||
{(isApprovalActionCreated || isApprovalActionUpdated) &&
|
||||
'Diajukan oleh '}
|
||||
{isApprovalActionRejected && 'Ditolak oleh '}
|
||||
{isApprovalActionApproved && 'Disetujui oleh '}
|
||||
{approval.isActive ? approval.action_by.name : '...'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{approval.isActive && (
|
||||
<p className='w-full max-w-60 p-3 bg-base-content/5 rounded-xl text-xs text-base-content/50'>
|
||||
Created at :{' '}
|
||||
{formatDate(approval.action_at, 'DD-MM-YYYY, HH:mm')}
|
||||
<br />
|
||||
Notes : {approval.notes ?? '-'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{formattedApprovals.length > maxVisibleSteps && (
|
||||
<Button
|
||||
variant='outline'
|
||||
color='none'
|
||||
onClick={seeMoreClickHandler}
|
||||
className={cn(
|
||||
'px-3 py-2 gap-2.5 text-sm text-base-content/50 border border-base-content/10 rounded-lg transition-all'
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons-outline:chevron-double-down'
|
||||
width={20}
|
||||
height={20}
|
||||
className={cn('transition-all duration-300', {
|
||||
'-rotate-180': isSeeAll,
|
||||
})}
|
||||
/>
|
||||
See {isSeeAll ? 'Less' : 'More'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ApprovalStepsV2;
|
||||
@@ -0,0 +1,48 @@
|
||||
import Button, { ButtonProps } from '@/components/Button';
|
||||
import { getFilledFormikValuesCount } from '@/lib/formik-helper';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { FormikValues } from 'formik';
|
||||
|
||||
export type ButtonFilterProps = ButtonProps & {
|
||||
values: FormikValues;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
// 'bg-gradient-to-t from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200
|
||||
|
||||
const ButtonFilter = ({ values, onClick, ...props }: ButtonFilterProps) => {
|
||||
return (
|
||||
<Button
|
||||
{...props}
|
||||
onClick={onClick}
|
||||
variant='outline'
|
||||
color='none'
|
||||
className={cn(
|
||||
'rounded-lg max-h-10 font-semibold text-sm gap-1.5',
|
||||
'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft',
|
||||
getFilledFormikValuesCount(values) > 0
|
||||
? 'border-primary-gradient text-primary rounded-lg!'
|
||||
: 'rounded-lg',
|
||||
props.className
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon='heroicons:funnel'
|
||||
width={20}
|
||||
height={20}
|
||||
className={
|
||||
getFilledFormikValuesCount(values) > 0 ? 'text-blue-600' : ''
|
||||
}
|
||||
/>
|
||||
Filter
|
||||
{getFilledFormikValuesCount(values) > 0 && (
|
||||
<span className='w-5 h-5 text-white bg-[#FF3535] rounded-lg border border-base-300 flex items-center justify-center text-xs'>
|
||||
{getFilledFormikValuesCount(values)}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export default ButtonFilter;
|
||||
@@ -72,8 +72,10 @@ const RequireAuth = ({ children }: RequireAuthProps) => {
|
||||
await AuthApi.refresh();
|
||||
};
|
||||
|
||||
refreshUserSession();
|
||||
}, []);
|
||||
if (user) {
|
||||
refreshUserSession();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
if (
|
||||
(isLoadingUserResponse && !userResponse && !userErrorResponse) ||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import Badge from '@/components/Badge';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { Color } from '@/types/theme';
|
||||
|
||||
interface StatusBadgeProps {
|
||||
color: Color;
|
||||
text: string;
|
||||
className?: {
|
||||
badge?: string;
|
||||
status?: string;
|
||||
};
|
||||
}
|
||||
|
||||
const StatusBadge = ({
|
||||
color = 'neutral',
|
||||
text,
|
||||
className,
|
||||
}: StatusBadgeProps) => {
|
||||
return (
|
||||
<Badge
|
||||
variant='soft'
|
||||
className={{
|
||||
badge: cn(
|
||||
'px-2 py-1 w-full flex flex-row justify-start gap-1 rounded-lg border border-base-content/10 text-xs font-medium text-base-content',
|
||||
{
|
||||
'bg-base-content/5': color === 'neutral',
|
||||
'bg-success/30': color === 'success',
|
||||
'bg-error/20': color === 'error',
|
||||
'bg-primary/20': color === 'info',
|
||||
'bg-[#FF9A20]/12': color === 'warning',
|
||||
},
|
||||
className?.badge
|
||||
),
|
||||
status: cn(className?.status),
|
||||
}}
|
||||
color={color}
|
||||
>
|
||||
<svg
|
||||
height='12'
|
||||
width='12'
|
||||
xmlns='http://www.w3.org/2000/svg'
|
||||
className={cn({
|
||||
'text-base-content/10': color === 'neutral',
|
||||
'text-[#008000]': color === 'success',
|
||||
'text-error': color === 'error',
|
||||
'text-primary': color === 'info',
|
||||
'text-[#FF9A20]': color === 'warning',
|
||||
})}
|
||||
>
|
||||
<circle r='6' cx='6' cy='6' fill='currentColor' />
|
||||
</svg>
|
||||
|
||||
{text}
|
||||
</Badge>
|
||||
);
|
||||
};
|
||||
|
||||
export default StatusBadge;
|
||||
@@ -58,6 +58,7 @@ const DrawerHeader = ({
|
||||
if (leftIconOnClick) {
|
||||
return (
|
||||
<button
|
||||
type='button'
|
||||
onClick={leftIconOnClick}
|
||||
className='hover:text-gray-400 bg-transparent border-none p-0'
|
||||
>
|
||||
@@ -72,12 +73,12 @@ const DrawerHeader = ({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-row justify-between items-center px-4 pt-4',
|
||||
'flex flex-row justify-between items-center px-4 pt-4 pb-4 border-b border-base-content/10',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{/* Left Side */}
|
||||
<div className='flex flex-row h-full gap-2 items-center'>
|
||||
<div className='flex flex-row h-full gap-3 items-center'>
|
||||
{renderLeftIcon()}
|
||||
|
||||
{showDivider && subtitle && (
|
||||
@@ -85,7 +86,12 @@ const DrawerHeader = ({
|
||||
)}
|
||||
|
||||
{subtitle && (
|
||||
<div className={cn('text-sm text-neutral', subtitleClassName)}>
|
||||
<div
|
||||
className={cn(
|
||||
'text-sm font-medium text-base-content/50',
|
||||
subtitleClassName
|
||||
)}
|
||||
>
|
||||
{subtitle}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -18,7 +18,7 @@ const AlertErrorList = ({
|
||||
if (formErrorList.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Alert color='error' className='w-full flex flex-col gap-2 px-4 m-4'>
|
||||
<Alert color='error' className='w-full flex flex-col gap-2 px-4'>
|
||||
<div className='flex justify-between items-center gap-2 w-full'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon icon='material-symbols:error-outline' width={24} height={24} />
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import { View, StyleSheet } from '@react-pdf/renderer';
|
||||
import { PdfThead, PdfColumn } from './PdfThead';
|
||||
import { PdfTbody, PdfTbodyCell } from './PdfTbody';
|
||||
import { PdfTfoot, PdfTfootCell } from './PdfTfoot';
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
table: {
|
||||
borderWidth: 1,
|
||||
borderColor: '#000000',
|
||||
marginBottom: 15,
|
||||
},
|
||||
});
|
||||
|
||||
interface PdfTableProps {
|
||||
columns: PdfColumn[];
|
||||
data: PdfTbodyCell[][];
|
||||
footer?: PdfTfootCell[];
|
||||
footerLabel?: string;
|
||||
firstRow?: {
|
||||
valueKey: string;
|
||||
value: number;
|
||||
align?: 'right';
|
||||
color?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const PdfTable = ({
|
||||
columns,
|
||||
data,
|
||||
footer,
|
||||
footerLabel = 'Total',
|
||||
firstRow,
|
||||
}: PdfTableProps) => {
|
||||
return (
|
||||
<View style={styles.table}>
|
||||
<PdfThead columns={columns} />
|
||||
<PdfTbody columns={columns} rows={data} firstRow={firstRow} />
|
||||
{footer && footer.length > 0 && (
|
||||
<PdfTfoot columns={columns} cells={footer} label={footerLabel} />
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,219 @@
|
||||
'use client';
|
||||
|
||||
import { Text, View, StyleSheet } from '@react-pdf/renderer';
|
||||
|
||||
export interface PdfColumn {
|
||||
key: string;
|
||||
header: string;
|
||||
flex: number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
}
|
||||
|
||||
export interface PdfTbodyCell {
|
||||
key: string;
|
||||
value: string | number | React.ReactNode;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
color?: string;
|
||||
formatAs?: 'text' | 'date' | 'currency' | 'number';
|
||||
formatDate?: string;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
tableRow: {
|
||||
flexDirection: 'row',
|
||||
},
|
||||
tableBorderBottom: {
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#000000',
|
||||
borderBottomStyle: 'solid',
|
||||
},
|
||||
tableCell: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'left',
|
||||
},
|
||||
tableCellLast: {
|
||||
flex: 1,
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
borderRightWidth: 0,
|
||||
},
|
||||
tableCellRight: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'right',
|
||||
},
|
||||
tableCellCenter: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'center',
|
||||
},
|
||||
tableCellNo: {
|
||||
flex: 0.5,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'center',
|
||||
},
|
||||
});
|
||||
|
||||
interface PdfTbodyProps {
|
||||
columns: PdfColumn[];
|
||||
rows: PdfTbodyCell[][];
|
||||
firstRow?: {
|
||||
valueKey: string;
|
||||
value: number;
|
||||
align?: 'right';
|
||||
color?: string;
|
||||
};
|
||||
formatDate?: (date: string, format: string) => string;
|
||||
formatNumber?: (num: number) => string;
|
||||
formatCurrency?: (num: number) => string;
|
||||
}
|
||||
|
||||
export const PdfTbody = ({ columns, rows, firstRow }: PdfTbodyProps) => {
|
||||
return (
|
||||
<>
|
||||
{/* First Row */}
|
||||
{firstRow && (
|
||||
<View style={[styles.tableRow, styles.tableBorderBottom]}>
|
||||
{columns.map((column, index) => {
|
||||
const isLastColumn = index === columns.length - 1;
|
||||
const isfirstRowColumn = column.key === firstRow.valueKey;
|
||||
const align = column.align || 'center';
|
||||
|
||||
const cellStyle =
|
||||
column.key === 'no'
|
||||
? [styles.tableCellNo, { flex: column.flex }]
|
||||
: isfirstRowColumn
|
||||
? [
|
||||
styles.tableCellRight,
|
||||
{
|
||||
flex: column.flex,
|
||||
color: firstRow.color || 'black',
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: align === 'right'
|
||||
? [
|
||||
styles.tableCellRight,
|
||||
{
|
||||
flex: column.flex,
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: align === 'center'
|
||||
? [
|
||||
styles.tableCellCenter,
|
||||
{
|
||||
flex: column.flex,
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: isLastColumn
|
||||
? [
|
||||
styles.tableCellLast,
|
||||
{
|
||||
flex: column.flex,
|
||||
borderRightWidth: 0,
|
||||
},
|
||||
]
|
||||
: [styles.tableCell, { flex: column.flex }];
|
||||
|
||||
return (
|
||||
<View key={column.key} style={cellStyle}>
|
||||
<Text>{isfirstRowColumn ? firstRow.value : ''}</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Data Rows */}
|
||||
{rows.map((row, rowIndex) => {
|
||||
const isLastRow = rowIndex === rows.length - 1;
|
||||
|
||||
return (
|
||||
<View
|
||||
key={rowIndex}
|
||||
style={[
|
||||
styles.tableRow,
|
||||
!isLastRow ? styles.tableBorderBottom : {},
|
||||
]}
|
||||
>
|
||||
{columns.map((column, colIndex) => {
|
||||
const cell = row.find((c) => c.key === column.key);
|
||||
const isLastColumn = colIndex === columns.length - 1;
|
||||
const align = cell?.align || column.align || 'center';
|
||||
|
||||
const cellStyle =
|
||||
column.key === 'no'
|
||||
? [styles.tableCellNo, { flex: column.flex }]
|
||||
: align === 'right'
|
||||
? [
|
||||
styles.tableCellRight,
|
||||
{
|
||||
flex: column.flex,
|
||||
color: cell?.color || 'black',
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: align === 'center'
|
||||
? [
|
||||
styles.tableCellCenter,
|
||||
{
|
||||
flex: column.flex,
|
||||
color: cell?.color || 'black',
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: isLastColumn
|
||||
? [
|
||||
styles.tableCellLast,
|
||||
{ flex: column.flex, borderRightWidth: 0 },
|
||||
]
|
||||
: [
|
||||
styles.tableCell,
|
||||
{
|
||||
flex: column.flex,
|
||||
color: cell?.color || 'black',
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<View key={column.key} style={cellStyle}>
|
||||
{cell?.value !== undefined &&
|
||||
cell?.value !== null &&
|
||||
cell?.value !== '' ? (
|
||||
typeof cell.value === 'object' ? (
|
||||
cell.value
|
||||
) : (
|
||||
<Text>{String(cell.value)}</Text>
|
||||
)
|
||||
) : (
|
||||
<Text>-</Text>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,131 @@
|
||||
'use client';
|
||||
|
||||
import { Text, View, StyleSheet } from '@react-pdf/renderer';
|
||||
|
||||
export interface PdfColumn {
|
||||
key: string;
|
||||
header: string;
|
||||
flex: number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
}
|
||||
|
||||
export interface PdfTfootCell {
|
||||
key: string;
|
||||
value: string | number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
flex?: number;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
tableRow: {
|
||||
flexDirection: 'row',
|
||||
},
|
||||
summaryRow: {
|
||||
backgroundColor: '#F0F0F0',
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
tableCell: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'left',
|
||||
},
|
||||
tableCellLast: {
|
||||
flex: 1,
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
borderRightWidth: 0,
|
||||
},
|
||||
tableCellRight: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'right',
|
||||
},
|
||||
tableCellCenter: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'center',
|
||||
},
|
||||
tableCellNo: {
|
||||
flex: 0.5,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
textAlign: 'center',
|
||||
},
|
||||
});
|
||||
|
||||
interface PdfTfootProps {
|
||||
columns: PdfColumn[];
|
||||
cells: PdfTfootCell[];
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export const PdfTfoot = ({
|
||||
columns,
|
||||
cells,
|
||||
label = 'Total',
|
||||
}: PdfTfootProps) => {
|
||||
return (
|
||||
<View style={[styles.tableRow, styles.summaryRow]}>
|
||||
{columns.map((column, index) => {
|
||||
const isLastColumn = index === columns.length - 1;
|
||||
const cellData = cells.find((c) => c.key === column.key);
|
||||
|
||||
const cellStyle =
|
||||
column.key === 'no'
|
||||
? [
|
||||
styles.tableCellNo,
|
||||
{ flex: column.flex, borderRightWidth: isLastColumn ? 0 : 1 },
|
||||
]
|
||||
: cellData?.align === 'right'
|
||||
? [
|
||||
styles.tableCellRight,
|
||||
{
|
||||
flex: column.flex,
|
||||
color: cellData?.color || 'black',
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: cellData?.align === 'center'
|
||||
? [
|
||||
styles.tableCellCenter,
|
||||
{
|
||||
flex: column.flex,
|
||||
color: cellData?.color || 'black',
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: isLastColumn
|
||||
? [styles.tableCellLast, { flex: column.flex }]
|
||||
: [
|
||||
styles.tableCell,
|
||||
{
|
||||
flex: column.flex,
|
||||
color: cellData?.color || 'black',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<View key={column.key} style={cellStyle}>
|
||||
<Text>{column.key === 'no' ? label : cellData?.value || ''}</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
'use client';
|
||||
|
||||
import { Text, View, StyleSheet } from '@react-pdf/renderer';
|
||||
|
||||
export interface PdfColumn {
|
||||
key: string;
|
||||
header: string;
|
||||
flex: number;
|
||||
align?: 'left' | 'center' | 'right';
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
tableRow: {
|
||||
flexDirection: 'row',
|
||||
},
|
||||
tableHeader: {
|
||||
backgroundColor: '#F5F5F5',
|
||||
},
|
||||
tableCellHeader: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
fontWeight: 'bold',
|
||||
backgroundColor: '#F5F5F5',
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#000000',
|
||||
borderBottomStyle: 'solid',
|
||||
paddingVertical: 12,
|
||||
textAlign: 'center',
|
||||
},
|
||||
tableCellHeaderRight: {
|
||||
flex: 1,
|
||||
borderRightWidth: 1,
|
||||
borderRightColor: '#000000',
|
||||
borderRightStyle: 'solid',
|
||||
padding: 4,
|
||||
fontSize: 7,
|
||||
fontWeight: 'bold',
|
||||
backgroundColor: '#F5F5F5',
|
||||
textAlign: 'right',
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#000000',
|
||||
borderBottomStyle: 'solid',
|
||||
paddingVertical: 12,
|
||||
},
|
||||
});
|
||||
|
||||
interface PdfTheadProps {
|
||||
columns: PdfColumn[];
|
||||
}
|
||||
|
||||
export const PdfThead = ({ columns }: PdfTheadProps) => {
|
||||
return (
|
||||
<View style={[styles.tableRow, styles.tableHeader]}>
|
||||
{columns.map((column, index) => {
|
||||
const align = column.align || 'center';
|
||||
const isLastColumn = index === columns.length - 1;
|
||||
|
||||
const cellStyle =
|
||||
align === 'right'
|
||||
? [
|
||||
styles.tableCellHeaderRight,
|
||||
{
|
||||
flex: column.flex,
|
||||
textAlign: 'right' as const,
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
]
|
||||
: [
|
||||
styles.tableCellHeader,
|
||||
{
|
||||
flex: column.flex,
|
||||
textAlign: align as 'left' | 'center' | 'right',
|
||||
borderRightWidth: isLastColumn ? 0 : 1,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<View key={column.key} style={cellStyle}>
|
||||
<Text>{column.header}</Text>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
export { PdfTable } from './PdfTable';
|
||||
export { PdfThead } from './PdfThead';
|
||||
export { PdfTbody } from './PdfTbody';
|
||||
export { PdfTfoot } from './PdfTfoot';
|
||||
export type { PdfColumn } from './PdfThead';
|
||||
export type { PdfTbodyCell } from './PdfTbody';
|
||||
export type { PdfTfootCell } from './PdfTfoot';
|
||||
@@ -0,0 +1,32 @@
|
||||
import IconSkeleton from '@/components/helper/skeleton/IconSkeleton';
|
||||
import { Icon } from '@iconify/react';
|
||||
|
||||
const DataStateSkeleton = ({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description: string;
|
||||
}) => {
|
||||
return (
|
||||
<div className='flex flex-col items-center justify-center'>
|
||||
<IconSkeleton
|
||||
className={{
|
||||
outer: 'mb-2.25',
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</IconSkeleton>
|
||||
<h3 className='text-base-content/50 font-semibold text-sm mb-1'>
|
||||
{title}
|
||||
</h3>
|
||||
<p className='text-base-content/50 text-xs text-center max-w-xs'>
|
||||
{description}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DataStateSkeleton;
|
||||
@@ -0,0 +1,33 @@
|
||||
import { cn } from '@/lib/helper';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
const IconSkeleton = ({
|
||||
children,
|
||||
className,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
className?: {
|
||||
outer?: string;
|
||||
inner?: string;
|
||||
};
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-12.5 h-12.5 bg-[var(--main-color-base-100,#FFFFFF)] border border-base-content/10 rounded-[0.875rem] shadow-[0px_25px_50px_-12px_#00000040] flex items-center justify-center',
|
||||
className?.outer
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'w-9.5 h-9.5 bg-primary rounded-lg border border-primary flex items-center justify-center shadow-[inset_0px_4px_4px_0px_#FFFFFF80,inset_0px_2px_0px_0px_#FFFFFF80]',
|
||||
className?.inner
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default IconSkeleton;
|
||||
@@ -113,7 +113,15 @@ const DateInput = ({
|
||||
};
|
||||
|
||||
const handleSelectSingle = (selectedDate?: Date) => {
|
||||
if (!selectedDate) return;
|
||||
if (!selectedDate) {
|
||||
setSelected(undefined);
|
||||
setDisplayValue('');
|
||||
const syntheticEvent = {
|
||||
target: { name, value: '' },
|
||||
} as unknown as React.ChangeEvent<HTMLInputElement>;
|
||||
onChange?.(syntheticEvent);
|
||||
return;
|
||||
}
|
||||
if (minDate && selectedDate < minDate) {
|
||||
setInternalError(`Tanggal tidak boleh sebelum ${min}`);
|
||||
return;
|
||||
@@ -136,7 +144,15 @@ const DateInput = ({
|
||||
};
|
||||
|
||||
const handleSelectRange = (range?: { from?: Date; to?: Date }) => {
|
||||
if (!range) return;
|
||||
if (!range) {
|
||||
setSelectedRange({});
|
||||
setDisplayValue('');
|
||||
const syntheticEvent = {
|
||||
target: { name, value: { from: '', to: '' } },
|
||||
} as unknown as React.ChangeEvent<HTMLInputElement>;
|
||||
onChange?.(syntheticEvent);
|
||||
return;
|
||||
}
|
||||
setSelectedRange(range);
|
||||
|
||||
const fromStr = range.from ? formatDate(range.from, 'DD/MM/YYYY') : '';
|
||||
@@ -188,17 +204,12 @@ const DateInput = ({
|
||||
const finalErrorMessage = internalError || externalErrorMessage;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full flex flex-col gap-2 text-start',
|
||||
className?.wrapper
|
||||
)}
|
||||
>
|
||||
<div className={cn('w-full flex flex-col text-start', className?.wrapper)}>
|
||||
{label && (
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'w-full text-sm font-normal leading-5',
|
||||
'w-full py-2 text-xs font-semibold leading-5',
|
||||
{ 'text-error': finalIsError },
|
||||
className?.label
|
||||
)}
|
||||
@@ -215,7 +226,7 @@ const DateInput = ({
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'input h-12 bg-inherit px-4 py-2 text-base font-normal leading-6 w-full rounded transition-all duration-200 flex items-center border',
|
||||
'input h-fit bg-inherit px-3 py-2.5 text-base font-normal leading-6 w-full rounded-lg transition-all duration-200 flex items-center border border-base-content/10',
|
||||
{
|
||||
'border-error': finalIsError,
|
||||
'border-success': externalValid && !finalIsError,
|
||||
@@ -234,7 +245,10 @@ const DateInput = ({
|
||||
disabled={disabled}
|
||||
readOnly // ✅ tidak bisa diketik manual
|
||||
className={cn(
|
||||
'grow bg-transparent cursor-pointer focus:outline-none',
|
||||
'grow bg-transparent cursor-pointer focus:outline-none text-sm leading-tight',
|
||||
{
|
||||
'cursor-not-allowed': readOnly,
|
||||
},
|
||||
className?.input
|
||||
)}
|
||||
/>
|
||||
@@ -245,10 +259,10 @@ const DateInput = ({
|
||||
</div>
|
||||
)}
|
||||
<Icon
|
||||
icon='uil:calendar'
|
||||
width={24}
|
||||
height={24}
|
||||
className='cursor-pointer text-dark'
|
||||
icon='heroicons:calendar-date-range'
|
||||
width={15}
|
||||
height={15}
|
||||
className='cursor-pointer text-base-content/20'
|
||||
onClick={(e) =>
|
||||
handleClick(e as unknown as React.MouseEvent<HTMLInputElement>)
|
||||
}
|
||||
@@ -256,17 +270,17 @@ const DateInput = ({
|
||||
</div>
|
||||
|
||||
{!finalIsError && bottomLabel && (
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
|
||||
)}
|
||||
{finalIsError && finalErrorMessage && (
|
||||
<p className='w-full text-sm text-error'>{finalErrorMessage}</p>
|
||||
<p className='w-full mt-1.5 text-xs text-error'>{finalErrorMessage}</p>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
ref={calendarModal.ref}
|
||||
className={{
|
||||
modal: 'rounded',
|
||||
modalBox: `!max-w-max min-h-${isRange ? '124' : '110'} flex flex-col`,
|
||||
modalBox: `max-w-max flex flex-col`,
|
||||
}}
|
||||
closeOnBackdrop
|
||||
>
|
||||
@@ -282,7 +296,11 @@ const DateInput = ({
|
||||
endMonth={maxDate ?? new Date(new Date().getFullYear() + 5, 11)}
|
||||
selected={selectedRange as DateRange}
|
||||
onSelect={handleSelectRange}
|
||||
footer={<div className='text-center mt-3'>{displayValue}</div>}
|
||||
footer={
|
||||
<div className='text-center py-2 text-base-content/65 font-semibold text-xs'>
|
||||
{displayValue}
|
||||
</div>
|
||||
}
|
||||
disabled={
|
||||
[
|
||||
minDate ? { before: minDate } : undefined,
|
||||
@@ -312,17 +330,26 @@ const DateInput = ({
|
||||
)}
|
||||
<div className='mt-auto flex flex-col gap-2'>
|
||||
{isRange && (
|
||||
<small className='text-secondary'>
|
||||
Tekan dua kali untuk memilih tanggal awal
|
||||
<small className='text-base-content/65'>
|
||||
Tekan dua kali untuk reset tanggal awal
|
||||
</small>
|
||||
)}
|
||||
|
||||
<div className='flex h-full justify-end items-end gap-2'>
|
||||
<Button type='button' color='warning' onClick={handleResetDate}>
|
||||
<div className='flex h-full justify-end items-end gap-1.5 mt-3'>
|
||||
<Button
|
||||
type='button'
|
||||
color='none'
|
||||
className='bg-transparent hover:bg-base-content/10 border-none text-base text-base-content/65 px-3'
|
||||
onClick={handleResetDate}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
{isRange && (
|
||||
<Button type='button' onClick={handleSaveDate}>
|
||||
<Button
|
||||
type='button'
|
||||
className='rounded-lg px-3 py-2 text-white'
|
||||
onClick={handleSaveDate}
|
||||
>
|
||||
Simpan
|
||||
</Button>
|
||||
)}
|
||||
|
||||
@@ -41,7 +41,7 @@ const FileInput = ({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full flex flex-col gap-2 text-start',
|
||||
'w-full flex flex-col gap-0 text-start rounded-lg',
|
||||
className?.wrapper
|
||||
)}
|
||||
>
|
||||
@@ -49,7 +49,7 @@ const FileInput = ({
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'w-full text-sm font-normal leading-5',
|
||||
'w-full py-2 text-xs font-semibold leading-5',
|
||||
{
|
||||
'text-error': isError,
|
||||
},
|
||||
@@ -77,15 +77,19 @@ const FileInput = ({
|
||||
onChange={onChange}
|
||||
onBlur={onBlur}
|
||||
disabled={disabled}
|
||||
className={cn('grow file-input w-full h-12 rounded', className?.input)}
|
||||
className={cn(
|
||||
'grow file-input w-full h-fit px-3 py-1.5 text-sm font-normal leading-6 rounded-lg! outline-none! transition-all duration-200 bg-white border-base-content/10',
|
||||
className?.input
|
||||
)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
|
||||
{bottomLabel && (
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
{!isError && bottomLabel && (
|
||||
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
|
||||
)}
|
||||
{isError && errorMessage && (
|
||||
<p className='w-full mt-1.5 text-xs text-error'>{errorMessage}</p>
|
||||
)}
|
||||
|
||||
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -9,15 +9,20 @@ import Select, {
|
||||
SingleValue,
|
||||
components as ReactSelectComponents,
|
||||
ControlProps,
|
||||
MenuListProps,
|
||||
} from 'react-select';
|
||||
import CreatableSelect from 'react-select/creatable';
|
||||
import makeAnimated from 'react-select/animated';
|
||||
import { useDebounce } from 'use-debounce';
|
||||
import { cn, getByPath } from '@/lib/helper';
|
||||
import useSWR from 'swr';
|
||||
import useSWRInfinite from 'swr/infinite';
|
||||
import { httpClientFetcher } from '@/services/http/client';
|
||||
import { BaseApiResponse } from '@/types/api/api-general';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import {
|
||||
BaseApiResponse,
|
||||
ErrorApiResponse,
|
||||
SuccessApiResponse,
|
||||
} from '@/types/api/api-general';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
|
||||
export interface OptionType {
|
||||
value: string | number;
|
||||
@@ -35,7 +40,9 @@ interface SelectInputBaseProps<T = OptionType> {
|
||||
bottomLabel?: ReactNode;
|
||||
options: T[];
|
||||
optionComponent?: OptionComponent<T>;
|
||||
components?: Partial<typeof ReactSelectComponents>;
|
||||
isDisabled?: boolean;
|
||||
readOnly?: boolean;
|
||||
isLoading?: boolean;
|
||||
isClearable?: boolean;
|
||||
isRtl?: boolean;
|
||||
@@ -47,6 +54,9 @@ interface SelectInputBaseProps<T = OptionType> {
|
||||
wrapper?: string;
|
||||
label?: string;
|
||||
select?: string;
|
||||
inputPrefix?: string;
|
||||
inputSuffix?: string;
|
||||
inputPrefixSuffixWrapper?: string;
|
||||
};
|
||||
isError?: boolean;
|
||||
errorMessage?: string;
|
||||
@@ -55,10 +65,16 @@ interface SelectInputBaseProps<T = OptionType> {
|
||||
delay?: number;
|
||||
onInputChange?: (search: string) => void;
|
||||
startAdornment?: ReactNode;
|
||||
inputPrefix?: ReactNode;
|
||||
inputSuffix?: ReactNode;
|
||||
menuPortalTarget?: HTMLElement | null;
|
||||
closeMenuOnSelect?: boolean;
|
||||
hideSelectedOptions?: boolean;
|
||||
onMenuScrollToBottom?: ((event: WheelEvent | TouchEvent) => void) | undefined;
|
||||
}
|
||||
|
||||
interface SelectInputProps<T = OptionType> extends SelectInputBaseProps<T> {
|
||||
export interface SelectInputProps<T = OptionType>
|
||||
extends SelectInputBaseProps<T> {
|
||||
createables?: boolean;
|
||||
value?: T | T[] | null;
|
||||
onChange?: (val: T | T[] | null) => void;
|
||||
@@ -73,7 +89,7 @@ const CustomControl = <
|
||||
>(
|
||||
props: ControlProps<Option, IsMulti, Group>
|
||||
) => {
|
||||
const { children } = props;
|
||||
const { children, innerProps } = props;
|
||||
|
||||
const customProps = props.selectProps as unknown as {
|
||||
shouldShowAdornment?: boolean;
|
||||
@@ -85,7 +101,7 @@ const CustomControl = <
|
||||
|
||||
return (
|
||||
<ReactSelectComponents.Control {...props}>
|
||||
<div className='flex-1 px-4! py-1.5 gap-1 flex items-center'>
|
||||
<div className='flex-1 pl-3 gap-1 flex items-center' {...innerProps}>
|
||||
{shouldShowAdornment && startAdornment}
|
||||
{children}
|
||||
</div>
|
||||
@@ -93,6 +109,29 @@ const CustomControl = <
|
||||
);
|
||||
};
|
||||
|
||||
const CustomMenuList = <
|
||||
Option,
|
||||
IsMulti extends boolean,
|
||||
Group extends GroupBase<Option>,
|
||||
>(
|
||||
props: MenuListProps<Option, IsMulti, Group>
|
||||
) => {
|
||||
const { children, selectProps, options } = props;
|
||||
const { isLoading } = selectProps;
|
||||
|
||||
return (
|
||||
<ReactSelectComponents.MenuList {...props}>
|
||||
{children}
|
||||
|
||||
{options.length > 0 && isLoading && (
|
||||
<div className='px-3 py-2 rounded-md text-center text-gray-400'>
|
||||
<span className='loading loading-spinner loading-md' />
|
||||
</div>
|
||||
)}
|
||||
</ReactSelectComponents.MenuList>
|
||||
);
|
||||
};
|
||||
|
||||
const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
const {
|
||||
label,
|
||||
@@ -101,6 +140,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
onChange,
|
||||
options,
|
||||
optionComponent,
|
||||
components: customComponents,
|
||||
isDisabled,
|
||||
isLoading,
|
||||
isClearable,
|
||||
@@ -118,7 +158,13 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
createables = false,
|
||||
onInputChange,
|
||||
startAdornment,
|
||||
inputPrefix,
|
||||
inputSuffix,
|
||||
menuPortalTarget,
|
||||
closeMenuOnSelect,
|
||||
hideSelectedOptions,
|
||||
onMenuScrollToBottom,
|
||||
readOnly,
|
||||
} = props;
|
||||
|
||||
const [internalInputValue, setInternalInputValue] = useState('');
|
||||
@@ -128,14 +174,18 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
|
||||
const components = useMemo(() => {
|
||||
const base = isAnimated ? animatedComponents : {};
|
||||
const customComponents = { ...base, IndicatorSeparator: () => null };
|
||||
const mergedComponents = { ...base, IndicatorSeparator: () => null };
|
||||
|
||||
if (startAdornment) {
|
||||
customComponents.Control = CustomControl;
|
||||
mergedComponents.Control = CustomControl;
|
||||
}
|
||||
|
||||
return customComponents;
|
||||
}, [isAnimated, startAdornment]);
|
||||
if (customComponents) {
|
||||
Object.assign(mergedComponents, customComponents);
|
||||
}
|
||||
|
||||
return mergedComponents;
|
||||
}, [isAnimated, startAdornment, customComponents]);
|
||||
|
||||
const internalInputChangeHandler = (val: string, meta: InputActionMeta) => {
|
||||
if (meta.action === 'input-change') setInternalInputValue(val);
|
||||
@@ -163,16 +213,11 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full flex flex-col gap-2 text-start',
|
||||
className?.wrapper
|
||||
)}
|
||||
>
|
||||
<div className={cn('w-full flex flex-col text-start', className?.wrapper)}>
|
||||
{label && (
|
||||
<span
|
||||
className={cn(
|
||||
'w-full text-sm font-normal leading-5',
|
||||
'w-full py-2 text-xs font-semibold leading-5',
|
||||
{ 'text-error': isError },
|
||||
className?.label
|
||||
)}
|
||||
@@ -189,87 +234,264 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
</span>
|
||||
)}
|
||||
|
||||
<SelectComponent<T, boolean, GroupBase<T>>
|
||||
instanceId='select'
|
||||
value={value ?? (isMulti ? [] : null)}
|
||||
onChange={onChange ? handleChange : undefined}
|
||||
options={options}
|
||||
menuIsOpen={openMenu}
|
||||
inputValue={internalInputValue}
|
||||
onInputChange={internalInputChangeHandler}
|
||||
onMenuClose={() => setInternalInputValue('')}
|
||||
isMulti={isMulti}
|
||||
isDisabled={isDisabled}
|
||||
isLoading={isLoading}
|
||||
isClearable={isClearable}
|
||||
isRtl={isRtl}
|
||||
isSearchable={isSearchable}
|
||||
placeholder={placeholder}
|
||||
className={cn('w-full', className?.select)}
|
||||
classNames={{
|
||||
...(!startAdornment && {
|
||||
{inputPrefix || inputSuffix ? (
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex text-sm',
|
||||
className?.inputPrefixSuffixWrapper
|
||||
)}
|
||||
>
|
||||
{inputPrefix && (
|
||||
<div
|
||||
className={cn(
|
||||
'inline-flex items-center px-3 border border-r-0 border-base-content/10 rounded-l-lg transition-all duration-200',
|
||||
{
|
||||
'bg-gray-100 border-base-content/10': !isDisabled,
|
||||
'bg-gray-50 border-base-content/10': isDisabled,
|
||||
'border-error': isError,
|
||||
},
|
||||
className?.inputPrefix
|
||||
)}
|
||||
>
|
||||
{inputPrefix}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SelectComponent<T, boolean, GroupBase<T>>
|
||||
instanceId='select'
|
||||
value={value ?? (isMulti ? [] : null)}
|
||||
onChange={onChange ? handleChange : undefined}
|
||||
options={options}
|
||||
menuIsOpen={openMenu}
|
||||
inputValue={internalInputValue}
|
||||
onInputChange={internalInputChangeHandler}
|
||||
onMenuClose={() => setInternalInputValue('')}
|
||||
isMulti={isMulti}
|
||||
isDisabled={isDisabled || readOnly}
|
||||
isLoading={isLoading}
|
||||
isClearable={isClearable}
|
||||
isRtl={isRtl}
|
||||
isSearchable={isSearchable}
|
||||
placeholder={placeholder}
|
||||
closeMenuOnSelect={closeMenuOnSelect}
|
||||
hideSelectedOptions={hideSelectedOptions}
|
||||
className={cn('w-full flex-1', className?.select)}
|
||||
classNames={{
|
||||
control: ({ isFocused, isDisabled }) =>
|
||||
cn('w-full border bg-white transition-shadow', 'rounded-lg!', {
|
||||
'cursor-pointer!': !readOnly && !isDisabled,
|
||||
'border-red-500! ring-2 ring-red-200': isError,
|
||||
'border-indigo-500 ring-2 ring-indigo-200':
|
||||
isFocused && !startAdornment,
|
||||
'border-base-content/10!': !isError && !isFocused,
|
||||
'bg-gray-100 text-gray-400 cursor-not-allowed':
|
||||
isDisabled && !readOnly,
|
||||
'bg-transparent! cursor-not-allowed!': readOnly,
|
||||
'rounded-l-none!': inputPrefix && !startAdornment,
|
||||
'rounded-r-none!': inputSuffix && !startAdornment,
|
||||
}),
|
||||
valueContainer: () => cn('flex-1 px-3! pr-2! py-2.5! gap-1'),
|
||||
placeholder: () =>
|
||||
cn({
|
||||
'text-gray-400 text-sm leading-tight': !isError,
|
||||
'text-red-300!': isError,
|
||||
}),
|
||||
singleValue: () =>
|
||||
cn({
|
||||
'm-0! text-gray-900 text-sm leading-tight': !isError,
|
||||
'text-error!': isError,
|
||||
'text-gray-900!': readOnly,
|
||||
}),
|
||||
input: () => cn('text-gray-900 m-0! p-0! text-sm leading-tight'),
|
||||
indicatorsContainer: () =>
|
||||
cn('flex items-center gap-1 pr-3 py-2'),
|
||||
dropdownIndicator: ({ isFocused }) =>
|
||||
cn('p-0! rounded hover:bg-gray-100', {
|
||||
'text-gray-900': isFocused,
|
||||
'text-gray-500': !isFocused,
|
||||
'text-error!': isError,
|
||||
}),
|
||||
clearIndicator: () => cn('p-0! rounded hover:bg-gray-100'),
|
||||
menu: () =>
|
||||
cn(
|
||||
'border border-base-content/5 rounded-xl! bg-base-100 shadow-lg! my-1.5!'
|
||||
),
|
||||
menuList: () => cn('p-0! max-h-60 overflow-auto'),
|
||||
option: ({ isFocused, isSelected }) =>
|
||||
cn('px-3 py-2 rounded-md cursor-pointer!', {
|
||||
'bg-indigo-600 text-white': isFocused,
|
||||
'bg-blue-500!': isSelected,
|
||||
'text-gray-700': !isFocused && !isSelected,
|
||||
}),
|
||||
multiValue: ({ getValue, index }) => {
|
||||
const selectedValues = getValue() as T[];
|
||||
return cn(
|
||||
'bg-base-200! rounded-lg! py-[3px] px-2.5 m-0! flex items-center gap-1! w-fit gap-2!',
|
||||
selectedValues[index]?.className
|
||||
);
|
||||
},
|
||||
multiValueRemove: () => cn('p-0! w-3 h-3'),
|
||||
multiValueLabel: ({ getValue, index }) => {
|
||||
const selectedValues = getValue() as T[];
|
||||
return cn(
|
||||
'p-0! text-base-content! text-xs!',
|
||||
selectedValues[index]?.labelClassName
|
||||
);
|
||||
},
|
||||
}}
|
||||
components={{
|
||||
...components,
|
||||
...(optionComponent ? { Option: optionComponent } : {}),
|
||||
MenuList: CustomMenuList,
|
||||
}}
|
||||
{...(startAdornment && {
|
||||
shouldShowAdornment,
|
||||
startAdornment,
|
||||
})}
|
||||
menuPortalTarget={
|
||||
typeof document !== 'undefined'
|
||||
? (menuPortalTarget ?? document.body)
|
||||
: undefined
|
||||
}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
multiValue(base) {
|
||||
return {
|
||||
...base,
|
||||
borderRadius: '8px',
|
||||
};
|
||||
},
|
||||
}}
|
||||
onMenuScrollToBottom={onMenuScrollToBottom}
|
||||
/>
|
||||
|
||||
{inputSuffix && (
|
||||
<div
|
||||
className={cn(
|
||||
'inline-flex items-center px-3 border border-l-0 border-base-content/10 rounded-r-lg transition-all duration-200',
|
||||
{
|
||||
'bg-gray-100 border-base-content/10': !isDisabled,
|
||||
'bg-gray-50 border-base-content/10': isDisabled,
|
||||
'border-error': isError,
|
||||
},
|
||||
className?.inputSuffix
|
||||
)}
|
||||
>
|
||||
{inputSuffix}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<SelectComponent<T, boolean, GroupBase<T>>
|
||||
instanceId='select'
|
||||
value={value ?? (isMulti ? [] : null)}
|
||||
onChange={onChange ? handleChange : undefined}
|
||||
options={options}
|
||||
menuIsOpen={openMenu}
|
||||
inputValue={internalInputValue}
|
||||
onInputChange={internalInputChangeHandler}
|
||||
onMenuClose={() => setInternalInputValue('')}
|
||||
isMulti={isMulti}
|
||||
isDisabled={isDisabled || readOnly}
|
||||
isLoading={isLoading}
|
||||
isClearable={isClearable}
|
||||
isRtl={isRtl}
|
||||
isSearchable={isSearchable}
|
||||
placeholder={placeholder}
|
||||
closeMenuOnSelect={closeMenuOnSelect}
|
||||
hideSelectedOptions={hideSelectedOptions}
|
||||
className={cn('w-full', className?.select)}
|
||||
classNames={{
|
||||
control: ({ isFocused, isDisabled }) =>
|
||||
cn(
|
||||
'w-full min-h-12! rounded border bg-white transition-shadow cursor-pointer!',
|
||||
'w-full border bg-white transition-shadow',
|
||||
// Gunakan rounded-lg untuk semua kasus
|
||||
'rounded-lg!',
|
||||
{
|
||||
'cursor-pointer!': !readOnly && !isDisabled,
|
||||
'border-red-500! ring-2 ring-red-200': isError,
|
||||
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
|
||||
'border-gray-300': !isError && !isFocused,
|
||||
'bg-gray-100 text-gray-400 cursor-not-allowed': isDisabled,
|
||||
'border-indigo-500 ring-2 ring-indigo-200':
|
||||
isFocused && !startAdornment,
|
||||
'border-base-content/10!': !isError && !isFocused,
|
||||
'bg-gray-100 text-gray-400 cursor-not-allowed':
|
||||
isDisabled && !readOnly,
|
||||
'bg-transparent! cursor-not-allowed!': readOnly,
|
||||
}
|
||||
),
|
||||
valueContainer: () => cn('flex-1 px-4! py-2! gap-1'),
|
||||
}),
|
||||
placeholder: () =>
|
||||
cn({ 'text-gray-400': !isError, 'text-red-300!': isError }),
|
||||
singleValue: () =>
|
||||
cn({ 'text-gray-900': !isError, 'text-error!': isError }),
|
||||
input: () => cn('text-gray-900'),
|
||||
indicatorsContainer: () => cn('flex items-center gap-1 pr-2'),
|
||||
dropdownIndicator: ({ isFocused }) =>
|
||||
cn('p-1 rounded hover:bg-gray-100', {
|
||||
'text-gray-900': isFocused,
|
||||
'text-gray-500': !isFocused,
|
||||
'text-error!': isError,
|
||||
}),
|
||||
menu: () =>
|
||||
cn('border border-gray-200 rounded! bg-base-100 shadow-lg!'),
|
||||
menuList: () => cn('p-2! max-h-60 overflow-auto'),
|
||||
option: ({ isFocused, isSelected }) =>
|
||||
cn('mt-1 px-3 py-2 rounded-md cursor-pointer!', {
|
||||
'bg-indigo-600 text-white': isFocused,
|
||||
'bg-blue-500!': isSelected,
|
||||
'text-gray-700': !isFocused && !isSelected,
|
||||
}),
|
||||
multiValue: ({ getValue, index }) => {
|
||||
const selectedValues = getValue() as T[];
|
||||
return cn(
|
||||
'bg-indigo-50 rounded py-0.5 pl-2 pr-1 flex items-center gap-1!',
|
||||
selectedValues[index]?.className
|
||||
);
|
||||
},
|
||||
multiValueLabel: ({ getValue, index }) => {
|
||||
const selectedValues = getValue() as T[];
|
||||
return cn('text-indigo-700', selectedValues[index]?.labelClassName);
|
||||
},
|
||||
}}
|
||||
components={{
|
||||
...components,
|
||||
...(optionComponent ? { Option: optionComponent } : {}),
|
||||
}}
|
||||
{...(startAdornment && {
|
||||
shouldShowAdornment,
|
||||
startAdornment,
|
||||
})}
|
||||
menuPortalTarget={
|
||||
typeof document !== 'undefined'
|
||||
? (menuPortalTarget ?? document.body)
|
||||
: undefined
|
||||
}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
}}
|
||||
/>
|
||||
valueContainer: () => cn('flex-1 px-3! pr-2! py-2.5! gap-1'),
|
||||
placeholder: () =>
|
||||
cn({
|
||||
'text-gray-400 text-sm leading-tight': !isError,
|
||||
'text-red-300!': isError,
|
||||
}),
|
||||
singleValue: () =>
|
||||
cn({
|
||||
'm-0! text-gray-900 text-sm leading-tight': !isError,
|
||||
'text-error!': isError,
|
||||
'text-gray-900!': readOnly,
|
||||
}),
|
||||
input: () => cn('text-gray-900 m-0! p-0! text-sm leading-tight'),
|
||||
indicatorsContainer: () => cn('flex items-center gap-1 pr-3 py-2'),
|
||||
dropdownIndicator: ({ isFocused }) =>
|
||||
cn('p-0! rounded hover:bg-gray-100', {
|
||||
'text-gray-900': isFocused,
|
||||
'text-gray-500': !isFocused,
|
||||
'text-error!': isError,
|
||||
}),
|
||||
clearIndicator: () => cn('p-0! rounded hover:bg-gray-100'),
|
||||
menu: () =>
|
||||
cn(
|
||||
'border border-base-content/5 rounded-xl! bg-base-100 shadow-lg! my-1.5!'
|
||||
),
|
||||
menuList: () => cn('p-0! max-h-60 overflow-auto'),
|
||||
option: ({ isFocused, isSelected }) =>
|
||||
cn('px-3 py-2 rounded-md cursor-pointer!', {
|
||||
'bg-indigo-600 text-white': isFocused,
|
||||
'bg-blue-500!': isSelected,
|
||||
'text-gray-700': !isFocused && !isSelected,
|
||||
}),
|
||||
multiValue: ({ getValue, index }) => {
|
||||
const selectedValues = getValue() as T[];
|
||||
return cn(
|
||||
'bg-base-200! rounded-lg! py-[3px] px-2.5 m-0! flex items-center gap-1! w-fit gap-2!',
|
||||
selectedValues[index]?.className
|
||||
);
|
||||
},
|
||||
multiValueRemove: () => cn('p-0! w-3 h-3'),
|
||||
multiValueLabel: ({ getValue, index }) => {
|
||||
const selectedValues = getValue() as T[];
|
||||
return cn(
|
||||
'p-0! text-base-content! text-xs!',
|
||||
selectedValues[index]?.labelClassName
|
||||
);
|
||||
},
|
||||
}}
|
||||
components={{
|
||||
...components,
|
||||
...(optionComponent ? { Option: optionComponent } : {}),
|
||||
MenuList: CustomMenuList,
|
||||
}}
|
||||
{...(startAdornment && {
|
||||
shouldShowAdornment,
|
||||
startAdornment,
|
||||
})}
|
||||
menuPortalTarget={
|
||||
typeof document !== 'undefined'
|
||||
? (menuPortalTarget ?? document.body)
|
||||
: undefined
|
||||
}
|
||||
styles={{
|
||||
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
|
||||
multiValue(base) {
|
||||
return {
|
||||
...base,
|
||||
borderRadius: '8px',
|
||||
};
|
||||
},
|
||||
}}
|
||||
onMenuScrollToBottom={onMenuScrollToBottom}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
|
||||
{!isError && bottomLabel && (
|
||||
@@ -280,7 +502,7 @@ const SelectInput = <T extends OptionType>(props: SelectInputProps<T>) => {
|
||||
};
|
||||
|
||||
const useSelect = <T,>(
|
||||
basePath: string,
|
||||
basePath: string | null,
|
||||
valueKey: keyof T | string,
|
||||
labelKey: keyof T | string,
|
||||
searchKey: string = 'search',
|
||||
@@ -288,34 +510,96 @@ const useSelect = <T,>(
|
||||
) => {
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
|
||||
const optionsUrlParams = useMemo(() => {
|
||||
return new URLSearchParams({
|
||||
const pageKey = 'page';
|
||||
const limitKey = 'limit';
|
||||
const limit = params?.['limit'] ?? 10;
|
||||
|
||||
const getKey = (
|
||||
pageIndex: number,
|
||||
previousPageData?: BaseApiResponse<T[]>
|
||||
) => {
|
||||
// stop when backend says no more pages
|
||||
if (previousPageData && isResponseSuccess(previousPageData)) {
|
||||
const meta = previousPageData.meta;
|
||||
if (meta && meta.page >= meta.total_pages) return null;
|
||||
}
|
||||
|
||||
const qs = new URLSearchParams({
|
||||
...(params ?? {}),
|
||||
[searchKey]: inputValue ?? '',
|
||||
...params,
|
||||
[pageKey]: String(pageIndex + 1),
|
||||
[limitKey]: String(limit),
|
||||
}).toString();
|
||||
}, [inputValue, searchKey, params]);
|
||||
|
||||
const optionsUrl = `${basePath}?${optionsUrlParams}`;
|
||||
return basePath ? `${basePath}?${qs}` : null;
|
||||
};
|
||||
|
||||
const { data, isLoading } = useSWR(optionsUrl, async (url) => {
|
||||
return await httpClientFetcher<BaseApiResponse<T[]>>(url);
|
||||
});
|
||||
const {
|
||||
data: pages,
|
||||
isLoading,
|
||||
isValidating,
|
||||
size,
|
||||
setSize,
|
||||
} = useSWRInfinite<BaseApiResponse<T[]>>(getKey, (url) =>
|
||||
httpClientFetcher<BaseApiResponse<T[]>>(url)
|
||||
);
|
||||
|
||||
const options = isResponseSuccess(data)
|
||||
? data.data.map((item) => {
|
||||
return {
|
||||
value: getByPath<T, number>(item, valueKey as string),
|
||||
label: getByPath<T, string>(item, labelKey as string),
|
||||
};
|
||||
})
|
||||
: [];
|
||||
const options = useMemo(() => {
|
||||
if (!pages) return [];
|
||||
|
||||
return pages.flatMap((page) =>
|
||||
isResponseSuccess(page)
|
||||
? page.data.map((item) => ({
|
||||
value: getByPath<T, number>(item, valueKey as string),
|
||||
label: getByPath<T, string>(item, labelKey as string),
|
||||
}))
|
||||
: []
|
||||
);
|
||||
}, [pages, valueKey, labelKey]);
|
||||
|
||||
const lastPage = pages?.[pages.length - 1];
|
||||
const hasMore =
|
||||
!!lastPage &&
|
||||
isResponseSuccess(lastPage) &&
|
||||
!!lastPage.meta &&
|
||||
lastPage.meta.page < lastPage.meta.total_pages;
|
||||
|
||||
const loadMore = () => {
|
||||
if (!hasMore) return;
|
||||
setSize(size + 1);
|
||||
};
|
||||
|
||||
let formattedSuccessRawData: SuccessApiResponse<T[]> | undefined = undefined;
|
||||
let formattedErrorRawData: ErrorApiResponse | undefined = undefined;
|
||||
|
||||
const latestPagesIndex = pages?.length ? pages.length - 1 : 0;
|
||||
|
||||
if (isResponseSuccess(pages?.[latestPagesIndex])) {
|
||||
formattedSuccessRawData = {
|
||||
...pages?.[latestPagesIndex],
|
||||
data:
|
||||
pages?.flatMap((page) => (isResponseSuccess(page) ? page.data : [])) ??
|
||||
[],
|
||||
};
|
||||
}
|
||||
|
||||
if (isResponseError(pages?.[latestPagesIndex])) {
|
||||
formattedErrorRawData = pages?.[latestPagesIndex];
|
||||
}
|
||||
|
||||
return {
|
||||
inputValue,
|
||||
setInputValue,
|
||||
|
||||
options,
|
||||
isLoadingOptions: isLoading,
|
||||
rawData: data,
|
||||
rawData: isResponseSuccess(pages?.[latestPagesIndex])
|
||||
? formattedSuccessRawData
|
||||
: formattedErrorRawData,
|
||||
|
||||
isLoadingOptions: isLoading || isValidating,
|
||||
isLoadingMore: isValidating && size > 1,
|
||||
hasMore,
|
||||
loadMore,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import {
|
||||
OptionProps,
|
||||
GroupBase,
|
||||
components as ReactSelectComponents,
|
||||
} from 'react-select';
|
||||
import SelectInput, { OptionType, SelectInputProps } from './SelectInput';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
interface SelectInputCheckboxProps<T = OptionType>
|
||||
extends Omit<
|
||||
SelectInputProps<T>,
|
||||
'closeMenuOnSelect' | 'hideSelectedOptions' | 'optionComponent'
|
||||
> {
|
||||
closeMenuOnSelect?: boolean;
|
||||
hideSelectedOptions?: boolean;
|
||||
}
|
||||
|
||||
const CheckboxOption = <
|
||||
T extends OptionType,
|
||||
IsMulti extends boolean,
|
||||
Group extends GroupBase<T>,
|
||||
>(
|
||||
props: OptionProps<T, IsMulti, Group>
|
||||
) => {
|
||||
const { isSelected, label, innerRef, innerProps, className, isFocused } =
|
||||
props;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={innerRef}
|
||||
{...innerProps}
|
||||
className={cn(
|
||||
'flex items-center gap-3 p-3 cursor-pointer transition-all hover:bg-primary/5',
|
||||
{
|
||||
'bg-primary/5': isFocused,
|
||||
},
|
||||
className
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type='checkbox'
|
||||
checked={isSelected}
|
||||
onChange={() => null}
|
||||
className='checkbox checkbox-sm rounded-md checkbox-primary pointer-events-none border-base-content/10'
|
||||
/>
|
||||
|
||||
<label className='cursor-pointer flex-1 select-none text-sm text-base-content/50 font-medium'>
|
||||
{label}
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const SelectInputCheckbox = <T extends OptionType>(
|
||||
props: SelectInputCheckboxProps<T>
|
||||
) => {
|
||||
const {
|
||||
closeMenuOnSelect = false,
|
||||
hideSelectedOptions = false,
|
||||
isMulti = true,
|
||||
className,
|
||||
...restProps
|
||||
} = props;
|
||||
|
||||
const customComponents = useMemo(() => {
|
||||
return {
|
||||
Option: CheckboxOption as typeof ReactSelectComponents.Option,
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SelectInput<T>
|
||||
{...restProps}
|
||||
isMulti={isMulti}
|
||||
closeMenuOnSelect={closeMenuOnSelect}
|
||||
hideSelectedOptions={hideSelectedOptions}
|
||||
className={{
|
||||
...className,
|
||||
select: cn(className?.select, 'select-checkbox'),
|
||||
}}
|
||||
components={customComponents}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default SelectInputCheckbox;
|
||||
@@ -0,0 +1,77 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import {
|
||||
OptionProps,
|
||||
GroupBase,
|
||||
components as ReactSelectComponents,
|
||||
} from 'react-select';
|
||||
import SelectInput, { OptionType, SelectInputProps } from './SelectInput';
|
||||
import { cn } from '@/lib/helper';
|
||||
|
||||
interface SelectInputRadioProps<T = OptionType>
|
||||
extends Omit<SelectInputProps<T>, 'closeMenuOnSelect' | 'optionComponent'> {
|
||||
closeMenuOnSelect?: boolean;
|
||||
}
|
||||
|
||||
const RadioOption = <
|
||||
T extends OptionType,
|
||||
IsMulti extends boolean,
|
||||
Group extends GroupBase<T>,
|
||||
>(
|
||||
props: OptionProps<T, IsMulti, Group>
|
||||
) => {
|
||||
const { isSelected, label, innerRef, innerProps, className, isFocused } =
|
||||
props;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={innerRef}
|
||||
{...innerProps}
|
||||
className={cn(
|
||||
'flex items-center gap-3 p-3 cursor-pointer transition-all hover:bg-primary/5',
|
||||
{
|
||||
'bg-primary/5': isFocused,
|
||||
},
|
||||
className
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type='radio'
|
||||
checked={isSelected}
|
||||
onChange={() => null}
|
||||
className='radio radio-md radio-primary pointer-events-none'
|
||||
/>
|
||||
|
||||
<label className='cursor-pointer flex-1 select-none text-sm text-base-content/50 font-medium'>
|
||||
{label}
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const SelectInputRadio = <T extends OptionType>(
|
||||
props: SelectInputRadioProps<T>
|
||||
) => {
|
||||
const { closeMenuOnSelect = true, className, ...restProps } = props;
|
||||
|
||||
const customComponents = useMemo(() => {
|
||||
return {
|
||||
Option: RadioOption as typeof ReactSelectComponents.Option,
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<SelectInput<T>
|
||||
{...restProps}
|
||||
closeMenuOnSelect={closeMenuOnSelect}
|
||||
className={{
|
||||
...className,
|
||||
select: cn(className?.select, 'select-radio'),
|
||||
}}
|
||||
components={customComponents}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default SelectInputRadio;
|
||||
@@ -53,7 +53,7 @@ const TextArea = ({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full flex flex-col gap-2 text-start',
|
||||
'w-full flex flex-col gap-0 text-start',
|
||||
className?.wrapper
|
||||
)}
|
||||
>
|
||||
@@ -61,7 +61,7 @@ const TextArea = ({
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'w-full text-sm font-normal leading-5',
|
||||
'w-full py-2 text-xs font-semibold leading-5',
|
||||
{
|
||||
'text-error': isError,
|
||||
},
|
||||
@@ -83,7 +83,7 @@ const TextArea = ({
|
||||
|
||||
<textarea
|
||||
className={cn(
|
||||
'textarea h-auto px-4 py-2 text-base font-normal leading-6 w-full rounded outline-none! transition-all bg-white',
|
||||
'textarea h-auto px-3 py-2.5 text-sm text-base-content font-normal leading-6 w-full rounded-lg outline-none! transition-all bg-white border-base-content/10',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
@@ -110,9 +110,11 @@ const TextArea = ({
|
||||
)}
|
||||
|
||||
{!isError && bottomLabel && (
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
|
||||
)}
|
||||
{isError && (
|
||||
<p className='w-full mt-1.5 text-xs text-error'>{errorMessage}</p>
|
||||
)}
|
||||
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -21,6 +21,9 @@ export interface TextInputProps {
|
||||
label?: string;
|
||||
inputWrapper?: string;
|
||||
input?: string;
|
||||
inputPrefix?: string;
|
||||
inputSuffix?: string;
|
||||
inputPrefixSuffixWrapper?: string;
|
||||
};
|
||||
isError?: boolean;
|
||||
isValid?: boolean;
|
||||
@@ -62,7 +65,7 @@ const TextInput = ({
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'w-full flex flex-col gap-2 text-start',
|
||||
'w-full flex flex-col gap-0 text-start rounded-lg',
|
||||
className?.wrapper
|
||||
)}
|
||||
>
|
||||
@@ -70,7 +73,7 @@ const TextInput = ({
|
||||
<label
|
||||
htmlFor={name}
|
||||
className={cn(
|
||||
'w-full text-sm font-normal leading-5',
|
||||
'w-full py-2 text-xs font-semibold leading-5',
|
||||
{
|
||||
'text-error': isError,
|
||||
},
|
||||
@@ -90,15 +93,23 @@ const TextInput = ({
|
||||
)}
|
||||
|
||||
{inputPrefix || inputSuffix ? (
|
||||
<div className='relative flex'>
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex text-sm',
|
||||
className?.inputPrefixSuffixWrapper
|
||||
)}
|
||||
>
|
||||
{inputPrefix && (
|
||||
<div
|
||||
className={cn(
|
||||
'inline-flex items-center px-4 py-2 border border-r-0 rounded-l-md transition-all duration-200',
|
||||
'inline-flex items-center px-3 border border-r-0 border-base-content/10 rounded-l-lg transition-all duration-200',
|
||||
{
|
||||
'bg-gray-100 border-gray-300': !disabled,
|
||||
'bg-gray-50 border-gray-200': disabled,
|
||||
}
|
||||
'bg-gray-100 border-base-content/10': !disabled,
|
||||
'bg-gray-50 border-base-content/10': disabled,
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
},
|
||||
className?.inputPrefix
|
||||
)}
|
||||
>
|
||||
{inputPrefix}
|
||||
@@ -107,7 +118,7 @@ const TextInput = ({
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'input h-12 text-base font-normal leading-6 flex-1 rounded-lg! outline-none! transition-all duration-200 flex items-center bg-white',
|
||||
'input h-fit px-3 py-2.5 gap-1.5 text-sm font-normal leading-6 flex-1 rounded-lg! outline-none! transition-all duration-200 flex items-center bg-white border-base-content/10',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
@@ -154,11 +165,14 @@ const TextInput = ({
|
||||
{inputSuffix && (
|
||||
<div
|
||||
className={cn(
|
||||
'inline-flex items-center px-4 py-2 border border-l-0 rounded-r-md transition-all duration-200',
|
||||
'inline-flex items-center px-3 border border-l-0 border-base-content/10 rounded-r-lg transition-all duration-200',
|
||||
{
|
||||
'bg-gray-100 border-gray-300': !disabled,
|
||||
'bg-gray-50 border-gray-200': disabled,
|
||||
}
|
||||
'bg-gray-100 border-base-content/10': !disabled,
|
||||
'bg-gray-50 border-base-content/10': disabled,
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
},
|
||||
className?.inputSuffix
|
||||
)}
|
||||
>
|
||||
{inputSuffix}
|
||||
@@ -168,7 +182,7 @@ const TextInput = ({
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all duration-200 bg-white',
|
||||
'input h-fit px-3 py-2.5 gap-1.5 text-sm font-normal leading-6 w-full rounded-lg! outline-none! transition-all duration-200 bg-white border-base-content/10',
|
||||
{
|
||||
'border-error': isError,
|
||||
'border-success!': isValid,
|
||||
@@ -202,10 +216,10 @@ const TextInput = ({
|
||||
)}
|
||||
|
||||
{!isError && bottomLabel && (
|
||||
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
|
||||
<p className='w-full mt-1.5 text-xs opacity-60'>{bottomLabel}</p>
|
||||
)}
|
||||
{isError && errorMessage && (
|
||||
<p className='w-full text-sm text-error'>{errorMessage}</p>
|
||||
<p className='w-full mt-1.5 text-xs text-error'>{errorMessage}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -35,29 +35,29 @@ const iconConfig = {
|
||||
info: {
|
||||
icon: 'material-symbols:info-outline-rounded',
|
||||
iconClassName: 'text-info-content',
|
||||
bgClassName: 'bg-info',
|
||||
outerRingClassName: 'bg-info/20',
|
||||
borderClassName: 'border-info',
|
||||
innerRingClassName: 'bg-info',
|
||||
middleRingClassName: 'bg-info/12',
|
||||
outerRingClassName: 'border-info/12 bg-info/8',
|
||||
},
|
||||
success: {
|
||||
icon: 'heroicons:check',
|
||||
iconClassName: 'text-white',
|
||||
bgClassName: 'bg-[#00D390]',
|
||||
outerRingClassName: 'bg-[#00D3901F]',
|
||||
borderClassName: 'border-[#CCF7EB]',
|
||||
innerRingClassName: 'bg-success',
|
||||
middleRingClassName: 'bg-success/12',
|
||||
outerRingClassName: 'border-success/12 bg-success/8',
|
||||
},
|
||||
error: {
|
||||
icon: 'solar:danger-triangle-linear',
|
||||
icon: 'heroicons:exclamation-triangle',
|
||||
iconClassName: 'text-error-content',
|
||||
bgClassName: 'bg-[#f03338]',
|
||||
outerRingClassName: 'bg-[#f3cdcd]',
|
||||
borderClassName: 'border-[#fff0ef]',
|
||||
innerRingClassName: 'bg-error',
|
||||
middleRingClassName: 'bg-error/12',
|
||||
outerRingClassName: 'border-error/12 bg-error/8',
|
||||
},
|
||||
} as const;
|
||||
|
||||
const ConfirmationModalIcon = ({
|
||||
type,
|
||||
size = 24,
|
||||
size = 16,
|
||||
}: {
|
||||
type: 'info' | 'success' | 'error';
|
||||
size?: number;
|
||||
@@ -65,28 +65,22 @@ const ConfirmationModalIcon = ({
|
||||
const config = iconConfig[type];
|
||||
|
||||
return (
|
||||
<div className='flex items-center justify-center p-2'>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-full border-4 p-1',
|
||||
config.outerRingClassName,
|
||||
config.borderClassName
|
||||
)}
|
||||
>
|
||||
<div className={cn('rounded-full p-1', config.outerRingClassName)}>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-full p-3 flex items-center justify-center',
|
||||
config.bgClassName
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon={config.icon}
|
||||
width={size}
|
||||
height={size}
|
||||
className={config.iconClassName}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={cn('rounded-full border p-[5px]', config.outerRingClassName)}
|
||||
>
|
||||
<div className={cn('rounded-full p-2', config.middleRingClassName)}>
|
||||
<div
|
||||
className={cn(
|
||||
'rounded-full p-1 flex items-center justify-center',
|
||||
config.innerRingClassName
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
icon={config.icon}
|
||||
width={size}
|
||||
height={size}
|
||||
className={config.iconClassName}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -103,7 +97,7 @@ const ConfirmationModal = ({
|
||||
secondaryButton,
|
||||
className,
|
||||
children,
|
||||
iconSize = 32,
|
||||
iconSize = 16,
|
||||
iconPosition = 'center',
|
||||
}: ConfirmationModalProps) => {
|
||||
const [isPrimaryButtonLoading, setIsPrimaryButtonLoading] = useState(false);
|
||||
@@ -123,7 +117,14 @@ const ConfirmationModal = ({
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal ref={ref} closeOnBackdrop={closeOnBackdrop} className={className}>
|
||||
<Modal
|
||||
ref={ref}
|
||||
closeOnBackdrop={closeOnBackdrop}
|
||||
className={{
|
||||
...className,
|
||||
modalBox: cn('rounded-xl p-4', className?.modalBox),
|
||||
}}
|
||||
>
|
||||
<div className='w-full flex flex-col gap-4'>
|
||||
{iconPosition === 'center' ? (
|
||||
<>
|
||||
@@ -143,7 +144,7 @@ const ConfirmationModal = ({
|
||||
</>
|
||||
) : (
|
||||
<div
|
||||
className={cn('flex flex-row items-center gap-4', {
|
||||
className={cn('flex flex-row items-center gap-3', {
|
||||
'flex-row': iconPosition === 'left',
|
||||
'flex-row-reverse': iconPosition === 'right',
|
||||
})}
|
||||
@@ -153,12 +154,12 @@ const ConfirmationModal = ({
|
||||
</div>
|
||||
|
||||
<div className='flex flex-col gap-1'>
|
||||
<p className='font-medium'>
|
||||
<p className='text-sm font-semibold'>
|
||||
{text ?? 'Apakah anda yakin ingin melakukan hal ini?'}
|
||||
</p>
|
||||
|
||||
{subtitleText && (
|
||||
<p className='text-sm text-gray-400'>{subtitleText}</p>
|
||||
<p className='text-xs text-base-content/50'>{subtitleText}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -166,46 +167,67 @@ const ConfirmationModal = ({
|
||||
|
||||
{children && <div className='w-full'>{children}</div>}
|
||||
|
||||
<div className='w-full flex flex-row gap-2'>
|
||||
{secondaryButton && secondaryButton.text && (
|
||||
<Button
|
||||
{...secondaryButton}
|
||||
variant='outline'
|
||||
color={secondaryButton?.color}
|
||||
isLoading={secondaryButton?.isLoading}
|
||||
disabled={
|
||||
secondaryButton?.isLoading !== undefined
|
||||
? secondaryButton?.isLoading
|
||||
: isPrimaryButtonLoading
|
||||
}
|
||||
onClick={closeModalHandler}
|
||||
className='grow'
|
||||
>
|
||||
{secondaryButton?.text ?? 'Tidak'}
|
||||
</Button>
|
||||
)}
|
||||
{(secondaryButton || primaryButton) && (
|
||||
<div
|
||||
className={cn('w-full grid gap-3', {
|
||||
'grid-cols-2': secondaryButton && primaryButton,
|
||||
'grid-cols-1':
|
||||
(secondaryButton && !primaryButton) ||
|
||||
(!secondaryButton && primaryButton),
|
||||
})}
|
||||
>
|
||||
{secondaryButton && secondaryButton.text && (
|
||||
<Button
|
||||
{...secondaryButton}
|
||||
variant='outline'
|
||||
color={secondaryButton?.color}
|
||||
isLoading={secondaryButton?.isLoading}
|
||||
disabled={
|
||||
secondaryButton?.isLoading !== undefined
|
||||
? secondaryButton?.isLoading
|
||||
: isPrimaryButtonLoading
|
||||
}
|
||||
onClick={(e) => {
|
||||
if (secondaryButton?.onClick) {
|
||||
secondaryButton.onClick(e);
|
||||
} else {
|
||||
closeModalHandler();
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
'p-2 rounded-xl text-sm',
|
||||
secondaryButton?.className
|
||||
)}
|
||||
>
|
||||
{secondaryButton?.text ?? 'Tidak'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{primaryButton && primaryButton.text && (
|
||||
<Button
|
||||
{...primaryButton}
|
||||
color={primaryButton?.color ?? 'info'}
|
||||
onClick={primaryButtonClickHandler}
|
||||
isLoading={
|
||||
primaryButton?.isLoading !== undefined
|
||||
? primaryButton?.isLoading
|
||||
: isPrimaryButtonLoading
|
||||
}
|
||||
disabled={
|
||||
primaryButton?.isLoading !== undefined
|
||||
? primaryButton?.isLoading
|
||||
: isPrimaryButtonLoading
|
||||
}
|
||||
className='grow'
|
||||
>
|
||||
{primaryButton?.text ?? 'Ya'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{primaryButton && primaryButton.text && (
|
||||
<Button
|
||||
{...primaryButton}
|
||||
color={primaryButton?.color ?? 'info'}
|
||||
onClick={primaryButtonClickHandler}
|
||||
isLoading={
|
||||
primaryButton?.isLoading !== undefined
|
||||
? primaryButton?.isLoading
|
||||
: isPrimaryButtonLoading
|
||||
}
|
||||
disabled={
|
||||
primaryButton?.isLoading !== undefined
|
||||
? primaryButton?.isLoading
|
||||
: isPrimaryButtonLoading
|
||||
}
|
||||
className={cn(
|
||||
'p-2 rounded-xl text-sm',
|
||||
primaryButton?.className
|
||||
)}
|
||||
>
|
||||
{primaryButton?.text ?? 'Ya'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
|
||||
@@ -32,6 +32,7 @@ const ConfirmationModalWithNotes: React.FC<ConfirmationModalWithNotesProps> = ({
|
||||
className,
|
||||
rows = 3,
|
||||
placeholder = 'Catatan...',
|
||||
...props
|
||||
}) => {
|
||||
const randomId = useId();
|
||||
const [notes, setNotes] = useState('');
|
||||
@@ -55,6 +56,7 @@ const ConfirmationModalWithNotes: React.FC<ConfirmationModalWithNotesProps> = ({
|
||||
}}
|
||||
secondaryButton={secondaryButton}
|
||||
className={className}
|
||||
{...props}
|
||||
>
|
||||
<TextArea
|
||||
name={randomId}
|
||||
|
||||
@@ -39,16 +39,15 @@ const SidebarMenuItem = ({ item, activeLink }: SidebarMenuItemProps) => {
|
||||
<li>
|
||||
<Link
|
||||
href={item.link}
|
||||
className={cn(
|
||||
{
|
||||
'menu-active border-2 border-solid border-base-300': isItemActive,
|
||||
},
|
||||
'px-3 py-1.5'
|
||||
)}
|
||||
className={cn('px-3 py-1.5', {
|
||||
'text-base-content/60': !isItemActive,
|
||||
'menu-active border-[1.5px] border-solid border-base-300':
|
||||
isItemActive,
|
||||
})}
|
||||
>
|
||||
{item.icon && <Icon icon={item.icon} width={20} height={20} />}
|
||||
|
||||
<span className='text-base'>{item.text}</span>
|
||||
<span className='text-sm'>{item.text}</span>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
@@ -62,12 +61,13 @@ const SidebarMenuItem = ({ item, activeLink }: SidebarMenuItemProps) => {
|
||||
<details open={isItemActive}>
|
||||
<summary
|
||||
className={cn({
|
||||
'text-base-content/60': !isItemActive,
|
||||
'text-primary': isItemActive,
|
||||
})}
|
||||
>
|
||||
{item.icon && <Icon icon={item.icon} width={20} height={20} />}
|
||||
|
||||
<span className='text-base'>{item.text}</span>
|
||||
<span className='text-sm'>{item.text}</span>
|
||||
</summary>
|
||||
|
||||
<ul>
|
||||
@@ -88,7 +88,7 @@ const SidebarMenuItem = ({ item, activeLink }: SidebarMenuItemProps) => {
|
||||
|
||||
const SidebarMenu = ({ menu, activeLink }: SidebarMenuProps) => {
|
||||
return (
|
||||
<Menu>
|
||||
<Menu className='p-3'>
|
||||
{menu.map((menuItem, menuIdx) => {
|
||||
return (
|
||||
<SidebarMenuItem
|
||||
|
||||
@@ -3,224 +3,82 @@ import Table, { TABLE_DEFAULT_STYLING } from '@/components/Table';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { formatCurrency, formatTitleCase } from '@/lib/helper';
|
||||
import { ClosingApi } from '@/services/api/closing';
|
||||
import {
|
||||
DataSummarySubTotal,
|
||||
HppPurchaseData,
|
||||
ProfitLossDataAmount,
|
||||
} from '@/types/api/closing';
|
||||
import { HppItem, ProfitLossItem } from '@/types/api/closing';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useMemo } from 'react';
|
||||
import useSWR from 'swr';
|
||||
|
||||
type HppTableRow =
|
||||
| (HppPurchaseData & {
|
||||
group_name: string;
|
||||
group_index: number;
|
||||
isGroupHeader?: boolean;
|
||||
})
|
||||
| {
|
||||
group_name: string;
|
||||
group_index: number;
|
||||
isGroupHeader: true;
|
||||
type?: never;
|
||||
budgeting?: never;
|
||||
realization?: never;
|
||||
}
|
||||
| {
|
||||
type: string;
|
||||
group_name: string;
|
||||
group_index: number;
|
||||
isGroupHeader: false;
|
||||
budgeting?: { rp_per_bird: number; rp_per_kg: number; amount: number };
|
||||
realization?: { rp_per_bird: number; rp_per_kg: number; amount: number };
|
||||
};
|
||||
|
||||
type ProfitLossTableRow =
|
||||
| (DataSummarySubTotal & {
|
||||
type: string;
|
||||
group_name: string;
|
||||
group_index: number;
|
||||
isGroupHeader?: boolean;
|
||||
})
|
||||
| {
|
||||
group_name: string;
|
||||
group_index: number;
|
||||
isGroupHeader: true;
|
||||
type?: never;
|
||||
rp_per_bird?: never;
|
||||
rp_per_kg?: never;
|
||||
amount?: never;
|
||||
};
|
||||
|
||||
const ClosingFinanceTable = ({
|
||||
projectFlockId,
|
||||
}: {
|
||||
projectFlockId: number;
|
||||
}) => {
|
||||
const searchParams = useSearchParams();
|
||||
const kandangId = searchParams.get('kandangId');
|
||||
|
||||
const { data: finance, isLoading } = useSWR(
|
||||
`/closing/finance/${projectFlockId}`,
|
||||
() => ClosingApi.getFinance(projectFlockId)
|
||||
`/closing/finance/${projectFlockId}${kandangId ? `/${kandangId}` : ''}`,
|
||||
() =>
|
||||
ClosingApi.getFinance(
|
||||
projectFlockId,
|
||||
kandangId ? Number(kandangId) : undefined
|
||||
)
|
||||
);
|
||||
|
||||
const staticHppRows: Array<{
|
||||
group_name: string;
|
||||
type: string;
|
||||
group_index: number;
|
||||
}> = [
|
||||
{
|
||||
group_name: 'HPP dan Pengeluaran',
|
||||
type: 'Pembelian PAKAN',
|
||||
group_index: 0,
|
||||
},
|
||||
{
|
||||
group_name: 'HPP dan Pengeluaran',
|
||||
type: 'Pembelian STARTER',
|
||||
group_index: 0,
|
||||
},
|
||||
{
|
||||
group_name: 'HPP dan Pengeluaran',
|
||||
type: 'Pembelian DOC',
|
||||
group_index: 0,
|
||||
},
|
||||
{
|
||||
group_name: 'HPP dan Pengeluaran',
|
||||
type: 'Pembelian PULLET',
|
||||
group_index: 0,
|
||||
},
|
||||
{
|
||||
group_name: 'HPP dan Pengeluaran',
|
||||
type: 'Pembelian LAYER',
|
||||
group_index: 0,
|
||||
},
|
||||
{
|
||||
group_name: 'HPP dan Bahan Baku',
|
||||
type: 'Pengeluaran Overhead',
|
||||
group_index: 1,
|
||||
},
|
||||
{
|
||||
group_name: 'HPP dan Bahan Baku',
|
||||
type: 'Beban Ekspedisi',
|
||||
group_index: 1,
|
||||
},
|
||||
];
|
||||
const hppTableData: HppItem[] = useMemo(() => {
|
||||
if (isResponseSuccess(finance)) {
|
||||
const customItems = {
|
||||
label: 'HPP dan Pengeluaran',
|
||||
code: 'custom_row',
|
||||
} as HppItem;
|
||||
const purchases = finance.data.hpp.items.filter(
|
||||
(item) => item.category === 'purchase'
|
||||
);
|
||||
const totalBudgeting = {
|
||||
label: 'HPP dan Bahan Baku',
|
||||
code: 'custom_row',
|
||||
} as HppItem;
|
||||
const overheads = finance.data.hpp.items.filter(
|
||||
(item) => item.category === 'overhead'
|
||||
);
|
||||
return [customItems, ...purchases, totalBudgeting, ...overheads];
|
||||
}
|
||||
return [];
|
||||
}, [finance]);
|
||||
|
||||
const hppTableData: HppTableRow[] = [
|
||||
{
|
||||
group_name: 'HPP dan Pengeluaran',
|
||||
group_index: 0,
|
||||
isGroupHeader: true as const,
|
||||
},
|
||||
...staticHppRows
|
||||
.filter((row) => row.group_index === 0)
|
||||
.map((staticRow) => {
|
||||
const apiData = isResponseSuccess(finance)
|
||||
? finance.data.hpp_purchases.hpp
|
||||
.find((g) => g.group_name === staticRow.group_name)
|
||||
?.data.find((d) => d.type === staticRow.type)
|
||||
: null;
|
||||
|
||||
return {
|
||||
group_name: staticRow.group_name,
|
||||
group_index: staticRow.group_index,
|
||||
type: staticRow.type,
|
||||
budgeting: apiData?.budgeting || {
|
||||
rp_per_bird: 0,
|
||||
rp_per_kg: 0,
|
||||
amount: 0,
|
||||
},
|
||||
realization: apiData?.realization || {
|
||||
rp_per_bird: 0,
|
||||
rp_per_kg: 0,
|
||||
amount: 0,
|
||||
},
|
||||
isGroupHeader: false as const,
|
||||
};
|
||||
}),
|
||||
{
|
||||
group_name: 'HPP dan Bahan Baku',
|
||||
group_index: 1,
|
||||
isGroupHeader: true as const,
|
||||
},
|
||||
...staticHppRows
|
||||
.filter((row) => row.group_index === 1)
|
||||
.map((staticRow) => {
|
||||
const apiData = isResponseSuccess(finance)
|
||||
? finance.data.hpp_purchases.hpp
|
||||
.find((g) => g.group_name === staticRow.group_name)
|
||||
?.data.find((d) => d.type === staticRow.type)
|
||||
: null;
|
||||
|
||||
return {
|
||||
group_name: staticRow.group_name,
|
||||
group_index: staticRow.group_index,
|
||||
type: staticRow.type,
|
||||
budgeting: apiData?.budgeting || {
|
||||
rp_per_bird: 0,
|
||||
rp_per_kg: 0,
|
||||
amount: 0,
|
||||
},
|
||||
realization: apiData?.realization || {
|
||||
rp_per_bird: 0,
|
||||
rp_per_kg: 0,
|
||||
amount: 0,
|
||||
},
|
||||
isGroupHeader: false as const,
|
||||
};
|
||||
}),
|
||||
{
|
||||
group_name: 'HPP',
|
||||
group_index: 2,
|
||||
isGroupHeader: true as const,
|
||||
},
|
||||
];
|
||||
|
||||
const profitLossTableData: ProfitLossTableRow[] = isResponseSuccess(finance)
|
||||
? [
|
||||
// Pembelian group
|
||||
...finance.data.profit_loss.data.pembelian.map((item) => ({
|
||||
label: 'Pembelian',
|
||||
group_name: 'Pembelian',
|
||||
group_index: 1,
|
||||
type: item.type,
|
||||
rp_per_bird: item.rp_per_bird,
|
||||
rp_per_kg: item.rp_per_kg,
|
||||
amount: item.amount,
|
||||
isGroupHeader: false as const,
|
||||
})),
|
||||
{
|
||||
label: finance.data.profit_loss.data.summary.gross_profit.label,
|
||||
group_name: 'Penjualan',
|
||||
group_index: 0,
|
||||
isGroupHeader: true as const,
|
||||
type: finance.data.profit_loss.data.summary.gross_profit.label,
|
||||
rp_per_bird:
|
||||
finance.data.profit_loss.data.summary.gross_profit.rp_per_bird,
|
||||
rp_per_kg:
|
||||
finance.data.profit_loss.data.summary.gross_profit.rp_per_kg,
|
||||
amount: finance.data.profit_loss.data.summary.gross_profit.amount,
|
||||
},
|
||||
// Penjualan group
|
||||
...finance.data.profit_loss.data.penjualan.map((item) => ({
|
||||
label: 'Penjualan',
|
||||
group_name: 'Penjualan',
|
||||
group_index: 0,
|
||||
type: item.type,
|
||||
rp_per_bird: item.rp_per_bird,
|
||||
rp_per_kg: item.rp_per_kg,
|
||||
amount: item.amount,
|
||||
isGroupHeader: false as const,
|
||||
})),
|
||||
{
|
||||
label: finance.data.profit_loss.data.summary.sub_total.label,
|
||||
group_name: 'Pembelian',
|
||||
group_index: 1,
|
||||
isGroupHeader: true as const,
|
||||
type: finance.data.profit_loss.data.summary.sub_total.label,
|
||||
rp_per_bird:
|
||||
finance.data.profit_loss.data.summary.sub_total.rp_per_bird,
|
||||
rp_per_kg: finance.data.profit_loss.data.summary.sub_total.rp_per_kg,
|
||||
amount: finance.data.profit_loss.data.summary.sub_total.amount,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const profitLossTableData: ProfitLossItem[] = useMemo(() => {
|
||||
if (isResponseSuccess(finance)) {
|
||||
const incomes = finance.data.profit_loss.items.filter(
|
||||
(item) => item.type === 'income'
|
||||
);
|
||||
const purchases = finance.data.profit_loss.items.filter(
|
||||
(item) => item.type === 'purchase'
|
||||
);
|
||||
const overheads = finance.data.profit_loss.items.filter(
|
||||
(item) => item.type === 'overhead'
|
||||
);
|
||||
const grossProfit = {
|
||||
label: 'LABA RUGI BRUTO',
|
||||
code: 'custom_row',
|
||||
type: 'gross_profit',
|
||||
rp_per_bird:
|
||||
finance.data.profit_loss.summary.gross_profit.rp_per_bird ?? 0,
|
||||
rp_per_kg: finance.data.profit_loss.summary.gross_profit.rp_per_kg ?? 0,
|
||||
amount: finance.data.profit_loss.summary.gross_profit.amount ?? 0,
|
||||
} as ProfitLossItem;
|
||||
const subtotal = {
|
||||
label: 'Subtotal',
|
||||
code: 'custom_row',
|
||||
type: 'subtotal',
|
||||
rp_per_bird:
|
||||
finance.data.profit_loss.summary.sub_total.rp_per_bird ?? 0,
|
||||
rp_per_kg: finance.data.profit_loss.summary.sub_total.rp_per_kg ?? 0,
|
||||
amount: finance.data.profit_loss.summary.sub_total.amount ?? 0,
|
||||
} as ProfitLossItem;
|
||||
return [...incomes, ...purchases, grossProfit, ...overheads, subtotal];
|
||||
}
|
||||
return [];
|
||||
}, [finance]);
|
||||
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
@@ -233,35 +91,21 @@ const ClosingFinanceTable = ({
|
||||
>
|
||||
<div className='grid grid-cols-2 gap-6'>
|
||||
<div className='flex flex-col gap-1'>
|
||||
<div>
|
||||
{isResponseSuccess(finance)
|
||||
? formatTitleCase(
|
||||
finance.data.profit_loss.data.summary.gross_profit
|
||||
.label || '-'
|
||||
)
|
||||
: 'Laba Rugi Brutto'}
|
||||
</div>
|
||||
<div>Laba Rugi Brutto</div>
|
||||
<div className='text-lg font-bold'>
|
||||
{isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.profit_loss.data.summary.gross_profit.amount
|
||||
finance.data.profit_loss.summary.gross_profit.amount
|
||||
)
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-col gap-1'>
|
||||
<div>
|
||||
{isResponseSuccess(finance)
|
||||
? formatTitleCase(
|
||||
finance.data.profit_loss.data.summary.net_profit.label ||
|
||||
'-'
|
||||
)
|
||||
: 'Laba Rugi Netto'}
|
||||
</div>
|
||||
<div>Laba Rugi Netto</div>
|
||||
<div className='text-lg font-bold'>
|
||||
{isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.profit_loss.data.summary.net_profit.amount
|
||||
finance.data.profit_loss.summary.net_profit.amount
|
||||
)
|
||||
: '-'}
|
||||
</div>
|
||||
@@ -269,11 +113,7 @@ const ClosingFinanceTable = ({
|
||||
</div>
|
||||
</Card>
|
||||
<Card
|
||||
title={
|
||||
isResponseSuccess(finance)
|
||||
? finance.data.hpp_purchases.title
|
||||
: 'HPP Purchases'
|
||||
}
|
||||
title='HPP Purchases'
|
||||
variant='bordered'
|
||||
collapsible
|
||||
className={{
|
||||
@@ -281,17 +121,18 @@ const ClosingFinanceTable = ({
|
||||
}}
|
||||
>
|
||||
<div className='mt-6 p-0 mb-0'>
|
||||
<Table<HppTableRow>
|
||||
<Table<HppItem>
|
||||
data={hppTableData}
|
||||
isLoading={isLoading}
|
||||
columns={[
|
||||
{
|
||||
header: 'No.',
|
||||
enableSorting: false,
|
||||
accessorFn: (item, index) => {
|
||||
if (item.isGroupHeader) return '-';
|
||||
if (item.code === 'custom_row') return '-';
|
||||
const dataRowsBefore = hppTableData
|
||||
.slice(0, index)
|
||||
.filter((row) => !row.isGroupHeader).length;
|
||||
.filter((row) => row.code !== 'custom_row').length;
|
||||
return dataRowsBefore + 1;
|
||||
},
|
||||
footer: (props) => {
|
||||
@@ -299,9 +140,9 @@ const ClosingFinanceTable = ({
|
||||
},
|
||||
},
|
||||
{
|
||||
header: 'Type',
|
||||
header: 'Jenis',
|
||||
enableSorting: false,
|
||||
accessorFn: (item) => formatTitleCase(item.type || '-'),
|
||||
accessorFn: (item) => formatTitleCase(item.label || '-'),
|
||||
},
|
||||
{
|
||||
header: 'Budgeting',
|
||||
@@ -317,7 +158,7 @@ const ClosingFinanceTable = ({
|
||||
return props.column.id === 'budgeting_rp_per_bird' &&
|
||||
isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.hpp_purchases.summary_hpp?.budgeting
|
||||
finance.data.hpp.summary?.budgeting
|
||||
?.rp_per_bird || 0
|
||||
)
|
||||
: '-';
|
||||
@@ -333,8 +174,8 @@ const ClosingFinanceTable = ({
|
||||
return props.column.id === 'budgeting_rp_per_kg' &&
|
||||
isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.hpp_purchases.summary_hpp?.budgeting
|
||||
?.rp_per_kg || 0
|
||||
finance.data.hpp.summary?.budgeting?.rp_per_kg ||
|
||||
0
|
||||
)
|
||||
: '-';
|
||||
},
|
||||
@@ -349,8 +190,7 @@ const ClosingFinanceTable = ({
|
||||
return props.column.id === 'budgeting_amount' &&
|
||||
isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.hpp_purchases.summary_hpp?.budgeting
|
||||
?.amount || 0
|
||||
finance.data.hpp.summary?.budgeting?.amount || 0
|
||||
)
|
||||
: '-';
|
||||
},
|
||||
@@ -371,8 +211,8 @@ const ClosingFinanceTable = ({
|
||||
return props.column.id === 'realization_rp_per_bird' &&
|
||||
isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.hpp_purchases.summary_hpp
|
||||
?.realization?.rp_per_bird || 0
|
||||
finance.data.hpp.summary?.realization
|
||||
?.rp_per_bird || 0
|
||||
)
|
||||
: '-';
|
||||
},
|
||||
@@ -387,8 +227,8 @@ const ClosingFinanceTable = ({
|
||||
return props.column.id === 'realization_rp_per_kg' &&
|
||||
isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.hpp_purchases.summary_hpp
|
||||
?.realization?.rp_per_kg || 0
|
||||
finance.data.hpp.summary?.realization
|
||||
?.rp_per_kg || 0
|
||||
)
|
||||
: '-';
|
||||
},
|
||||
@@ -403,8 +243,7 @@ const ClosingFinanceTable = ({
|
||||
return props.column.id === 'realization_amount' &&
|
||||
isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.hpp_purchases.summary_hpp
|
||||
?.realization?.amount || 0
|
||||
finance.data.hpp.summary?.realization?.amount || 0
|
||||
)
|
||||
: '-';
|
||||
},
|
||||
@@ -414,7 +253,7 @@ const ClosingFinanceTable = ({
|
||||
]}
|
||||
renderCustomRow={(row) => {
|
||||
const rowData = row.original;
|
||||
if (rowData.isGroupHeader) {
|
||||
if (rowData.code === 'custom_row') {
|
||||
return (
|
||||
<tr
|
||||
key={row.id}
|
||||
@@ -428,7 +267,7 @@ const ClosingFinanceTable = ({
|
||||
className={TABLE_DEFAULT_STYLING.bodyColumnClassName}
|
||||
>
|
||||
<div className='font-bold'>
|
||||
{formatTitleCase(rowData.group_name ?? '-')}
|
||||
{formatTitleCase(rowData.label ?? '-')}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -441,11 +280,7 @@ const ClosingFinanceTable = ({
|
||||
</div>
|
||||
</Card>
|
||||
<Card
|
||||
title={
|
||||
isResponseSuccess(finance)
|
||||
? finance.data.profit_loss.title
|
||||
: 'Profit/Loss'
|
||||
}
|
||||
title='Profit/Loss'
|
||||
variant='bordered'
|
||||
collapsible
|
||||
className={{
|
||||
@@ -453,38 +288,32 @@ const ClosingFinanceTable = ({
|
||||
}}
|
||||
>
|
||||
<div className='mt-6 p-0 mb-0'>
|
||||
<Table<ProfitLossTableRow>
|
||||
<Table<ProfitLossItem>
|
||||
data={profitLossTableData}
|
||||
isLoading={isLoading}
|
||||
columns={[
|
||||
{
|
||||
header: 'Jenis',
|
||||
enableSorting: false,
|
||||
accessorFn: (item) => item.type,
|
||||
accessorFn: (item) => item.label,
|
||||
cell: (item) => (
|
||||
<div className=''>
|
||||
{formatTitleCase(item.row.original.type || '-')}
|
||||
{formatTitleCase(item.row.original.label || '-')}
|
||||
</div>
|
||||
),
|
||||
footer: (item) => (
|
||||
<div className='font-bold uppercase'>
|
||||
{isResponseSuccess(finance)
|
||||
? formatTitleCase(
|
||||
finance.data.profit_loss.data.summary.net_profit
|
||||
.label || '-'
|
||||
)
|
||||
: '-'}
|
||||
</div>
|
||||
footer: () => (
|
||||
<div className='font-bold uppercase'>LABA RUGI NETTO</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: 'Rp/Ekor',
|
||||
enableSorting: false,
|
||||
accessorFn: (item) => formatCurrency(item.rp_per_bird || 0),
|
||||
footer: (item) => (
|
||||
footer: () => (
|
||||
<div className='font-bold'>
|
||||
{isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.profit_loss.data.summary.net_profit
|
||||
finance.data.profit_loss.summary.net_profit
|
||||
.rp_per_bird || 0
|
||||
)
|
||||
: formatCurrency(0)}
|
||||
@@ -495,11 +324,11 @@ const ClosingFinanceTable = ({
|
||||
header: 'Rp/Kg',
|
||||
enableSorting: false,
|
||||
accessorFn: (item) => formatCurrency(item.rp_per_kg || 0),
|
||||
footer: (item) => (
|
||||
footer: () => (
|
||||
<div className='font-bold'>
|
||||
{isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.profit_loss.data.summary.net_profit
|
||||
finance.data.profit_loss.summary.net_profit
|
||||
.rp_per_kg || 0
|
||||
)
|
||||
: formatCurrency(0)}
|
||||
@@ -510,11 +339,11 @@ const ClosingFinanceTable = ({
|
||||
header: 'Jumlah (Rp)',
|
||||
enableSorting: false,
|
||||
accessorFn: (item) => formatCurrency(item.amount || 0),
|
||||
footer: (item) => (
|
||||
footer: () => (
|
||||
<div className='font-bold'>
|
||||
{isResponseSuccess(finance)
|
||||
? formatCurrency(
|
||||
finance.data.profit_loss.data.summary.net_profit
|
||||
finance.data.profit_loss.summary.net_profit
|
||||
.amount || 0
|
||||
)
|
||||
: formatCurrency(0)}
|
||||
@@ -524,55 +353,30 @@ const ClosingFinanceTable = ({
|
||||
]}
|
||||
renderCustomRow={(row) => {
|
||||
const rowData = row.original;
|
||||
if (rowData.isGroupHeader) {
|
||||
if (rowData.amount) {
|
||||
return (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={TABLE_DEFAULT_STYLING.footerRowClassName}
|
||||
>
|
||||
<td
|
||||
className={TABLE_DEFAULT_STYLING.bodyColumnClassName}
|
||||
>
|
||||
<div className='font-bold ps-6 uppercase'>
|
||||
{formatTitleCase(rowData.label ?? '-')}
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
className={TABLE_DEFAULT_STYLING.bodyColumnClassName}
|
||||
>
|
||||
<div className='font-bold'>
|
||||
{formatCurrency(rowData.rp_per_bird ?? 0)}
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
className={TABLE_DEFAULT_STYLING.bodyColumnClassName}
|
||||
>
|
||||
<div className='font-bold'>
|
||||
{formatCurrency(rowData.rp_per_kg ?? 0)}
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
className={TABLE_DEFAULT_STYLING.bodyColumnClassName}
|
||||
>
|
||||
<div className='font-bold'>
|
||||
{formatCurrency(rowData.amount ?? 0)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
if (rowData.code === 'custom_row') {
|
||||
return (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={TABLE_DEFAULT_STYLING.bodyRowClassName}
|
||||
className={TABLE_DEFAULT_STYLING.footerRowClassName}
|
||||
>
|
||||
<td
|
||||
colSpan={4}
|
||||
className={TABLE_DEFAULT_STYLING.bodyColumnClassName}
|
||||
>
|
||||
<td className={TABLE_DEFAULT_STYLING.bodyColumnClassName}>
|
||||
<div className='font-bold ps-6 uppercase'>
|
||||
{formatTitleCase(rowData.label ?? '-')}
|
||||
</div>
|
||||
</td>
|
||||
<td className={TABLE_DEFAULT_STYLING.bodyColumnClassName}>
|
||||
<div className='font-bold'>
|
||||
{formatTitleCase(rowData.group_name ?? '-')}
|
||||
{formatCurrency(rowData.rp_per_bird ?? 0)}
|
||||
</div>
|
||||
</td>
|
||||
<td className={TABLE_DEFAULT_STYLING.bodyColumnClassName}>
|
||||
<div className='font-bold'>
|
||||
{formatCurrency(rowData.rp_per_kg ?? 0)}
|
||||
</div>
|
||||
</td>
|
||||
<td className={TABLE_DEFAULT_STYLING.bodyColumnClassName}>
|
||||
<div className='font-bold'>
|
||||
{formatCurrency(rowData.amount ?? 0)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEventHandler, useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
import { ColumnDef, SortingState } from '@tanstack/react-table';
|
||||
|
||||
import { Icon } from '@iconify/react';
|
||||
import Table from '@/components/Table';
|
||||
import Card from '@/components/Card';
|
||||
import Collapse from '@/components/Collapse';
|
||||
|
||||
import { cn, formatNumber } from '@/lib/helper';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { ClosingApi } from '@/services/api/closing';
|
||||
import { ClosingIncomingSapronakSummary } from '@/types/api/closing';
|
||||
|
||||
interface ClosingIncomingSapronaksSummaryTableProps {
|
||||
projectFlockId: number;
|
||||
}
|
||||
|
||||
const ClosingIncomingSapronaksSummaryTable = ({
|
||||
projectFlockId,
|
||||
}: ClosingIncomingSapronaksSummaryTableProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const kandangId = searchParams.get('kandangId');
|
||||
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
search: '',
|
||||
nameSort: '',
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
nameSort: 'sort_name',
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
data: incomingSapronakSummaries,
|
||||
isLoading: isLoadingIncomingSapronakSummaries,
|
||||
} = useSWR(
|
||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak/summary${getTableFilterQueryString()}&type=incoming&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
||||
ClosingApi.getAllIncomingSapronakSummaryFetcher,
|
||||
{
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
const [open, setOpen] = useState(true);
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||
|
||||
const incomingSapronaksColumns: ColumnDef<ClosingIncomingSapronakSummary>[] =
|
||||
[
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) => props.row.index + 1,
|
||||
},
|
||||
{
|
||||
accessorKey: 'category',
|
||||
header: 'Kategori',
|
||||
},
|
||||
{
|
||||
accessorKey: 'total_qty',
|
||||
header: 'Total Kuantitas',
|
||||
cell: (props) =>
|
||||
`${formatNumber(props.row.original.total_qty)} ${props.row.original.uom.name}`,
|
||||
},
|
||||
];
|
||||
|
||||
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
updateFilter('search', e.target.value);
|
||||
};
|
||||
|
||||
// track sorting
|
||||
useEffect(() => {
|
||||
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
|
||||
|
||||
if (!isNameSorted) {
|
||||
updateFilter('nameSort', '');
|
||||
} else {
|
||||
updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
|
||||
}
|
||||
}, [sorting, updateFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setOpen(
|
||||
isResponseSuccess(incomingSapronakSummaries)
|
||||
? incomingSapronakSummaries.data.length > 0
|
||||
: false
|
||||
);
|
||||
}
|
||||
}, [incomingSapronakSummaries, isResponseSuccess]);
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={{
|
||||
wrapper: 'w-full',
|
||||
body: 'p-4 shadow',
|
||||
}}
|
||||
>
|
||||
<Collapse
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
title={
|
||||
<div className='card-actions p-4 justify-between items-center w-full'>
|
||||
<div className='card-title'>Ringkasan Sapronak Masuk</div>
|
||||
|
||||
<Icon
|
||||
icon='material-symbols:keyboard-arrow-down'
|
||||
width={24}
|
||||
height={24}
|
||||
className={cn('text-primary transition-transform', {
|
||||
'-rotate-180': open,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
className='w-full!'
|
||||
titleClassName='w-full p-0!'
|
||||
>
|
||||
<div className='w-full p-0'>
|
||||
<Table<ClosingIncomingSapronakSummary>
|
||||
data={
|
||||
isResponseSuccess(incomingSapronakSummaries)
|
||||
? incomingSapronakSummaries?.data
|
||||
: []
|
||||
}
|
||||
columns={incomingSapronaksColumns}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
onPageSizeChange={setPageSize}
|
||||
rowOptions={[10, 20, 50, 100]}
|
||||
page={
|
||||
isResponseSuccess(incomingSapronakSummaries)
|
||||
? incomingSapronakSummaries?.meta?.page
|
||||
: 0
|
||||
}
|
||||
totalItems={
|
||||
isResponseSuccess(incomingSapronakSummaries)
|
||||
? incomingSapronakSummaries?.meta?.total_results
|
||||
: 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoadingIncomingSapronakSummaries}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'w-full mb-20':
|
||||
isResponseSuccess(incomingSapronakSummaries) &&
|
||||
incomingSapronakSummaries?.data?.length === 0,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Collapse>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default ClosingIncomingSapronaksSummaryTable;
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEventHandler, useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
import { ColumnDef, SortingState } from '@tanstack/react-table';
|
||||
|
||||
@@ -23,6 +24,9 @@ interface ClosingIncomingSapronaksTableProps {
|
||||
const ClosingIncomingSapronaksTable = ({
|
||||
projectFlockId,
|
||||
}: ClosingIncomingSapronaksTableProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const kandangId = searchParams.get('kandangId');
|
||||
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
@@ -43,7 +47,7 @@ const ClosingIncomingSapronaksTable = ({
|
||||
|
||||
const { data: incomingSapronaks, isLoading: isLoadingIncomingSapronaks } =
|
||||
useSWR(
|
||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=incoming`,
|
||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=incoming&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
||||
ClosingApi.getAllIncomingSapronakFetcher,
|
||||
{
|
||||
keepPreviousData: true,
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEventHandler, useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
import { ColumnDef, SortingState } from '@tanstack/react-table';
|
||||
|
||||
import { Icon } from '@iconify/react';
|
||||
import Table from '@/components/Table';
|
||||
import Card from '@/components/Card';
|
||||
import Collapse from '@/components/Collapse';
|
||||
|
||||
import { cn, formatNumber } from '@/lib/helper';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { ClosingApi } from '@/services/api/closing';
|
||||
import { ClosingOutgoingSapronakSummary } from '@/types/api/closing';
|
||||
|
||||
interface ClosingOutgoingSapronaksSummaryTableProps {
|
||||
projectFlockId: number;
|
||||
}
|
||||
|
||||
const ClosingOutgoingSapronaksSummaryTable = ({
|
||||
projectFlockId,
|
||||
}: ClosingOutgoingSapronaksSummaryTableProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const kandangId = searchParams.get('kandangId');
|
||||
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
setPage,
|
||||
setPageSize,
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
search: '',
|
||||
nameSort: '',
|
||||
},
|
||||
paramMap: {
|
||||
page: 'page',
|
||||
pageSize: 'limit',
|
||||
nameSort: 'sort_name',
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
data: outgoingSapronakSummaries,
|
||||
isLoading: isLoadingOutgoingSapronakSummaries,
|
||||
} = useSWR(
|
||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak/summary${getTableFilterQueryString()}&type=outgoing&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
||||
ClosingApi.getAllIncomingSapronakSummaryFetcher,
|
||||
{
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
const [open, setOpen] = useState(true);
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
|
||||
|
||||
const outgoingSapronaksColumns: ColumnDef<ClosingOutgoingSapronakSummary>[] =
|
||||
[
|
||||
{
|
||||
header: '#',
|
||||
cell: (props) => props.row.index + 1,
|
||||
},
|
||||
{
|
||||
accessorKey: 'category',
|
||||
header: 'Kategori',
|
||||
},
|
||||
{
|
||||
accessorKey: 'total_qty',
|
||||
header: 'Total Kuantitas',
|
||||
cell: (props) =>
|
||||
`${formatNumber(props.row.original.total_qty)} ${props.row.original.uom.name}`,
|
||||
},
|
||||
];
|
||||
|
||||
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
updateFilter('search', e.target.value);
|
||||
};
|
||||
|
||||
// track sorting
|
||||
useEffect(() => {
|
||||
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
|
||||
|
||||
if (!isNameSorted) {
|
||||
updateFilter('nameSort', '');
|
||||
} else {
|
||||
updateFilter('nameSort', isNameSorted.desc ? 'desc' : 'asc');
|
||||
}
|
||||
}, [sorting, updateFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setOpen(
|
||||
isResponseSuccess(outgoingSapronakSummaries)
|
||||
? outgoingSapronakSummaries.data.length > 0
|
||||
: false
|
||||
);
|
||||
}
|
||||
}, [outgoingSapronakSummaries, isResponseSuccess]);
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={{
|
||||
wrapper: 'w-full',
|
||||
body: 'p-4 shadow',
|
||||
}}
|
||||
>
|
||||
<Collapse
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
title={
|
||||
<div className='card-actions p-4 justify-between items-center w-full'>
|
||||
<div className='card-title'>Ringkasan Sapronak Keluar</div>
|
||||
|
||||
<Icon
|
||||
icon='material-symbols:keyboard-arrow-down'
|
||||
width={24}
|
||||
height={24}
|
||||
className={cn('text-primary transition-transform', {
|
||||
'-rotate-180': open,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
className='w-full!'
|
||||
titleClassName='w-full p-0!'
|
||||
>
|
||||
<div className='w-full p-0'>
|
||||
<Table<ClosingOutgoingSapronakSummary>
|
||||
data={
|
||||
isResponseSuccess(outgoingSapronakSummaries)
|
||||
? outgoingSapronakSummaries?.data
|
||||
: []
|
||||
}
|
||||
columns={outgoingSapronaksColumns}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
onPageSizeChange={setPageSize}
|
||||
rowOptions={[10, 20, 50, 100]}
|
||||
page={
|
||||
isResponseSuccess(outgoingSapronakSummaries)
|
||||
? outgoingSapronakSummaries?.meta?.page
|
||||
: 0
|
||||
}
|
||||
totalItems={
|
||||
isResponseSuccess(outgoingSapronakSummaries)
|
||||
? outgoingSapronakSummaries?.meta?.total_results
|
||||
: 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoadingOutgoingSapronakSummaries}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'w-full mb-20':
|
||||
isResponseSuccess(outgoingSapronakSummaries) &&
|
||||
outgoingSapronakSummaries?.data?.length === 0,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Collapse>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default ClosingOutgoingSapronaksSummaryTable;
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { ChangeEventHandler, useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
import { ColumnDef, SortingState } from '@tanstack/react-table';
|
||||
|
||||
@@ -23,6 +24,9 @@ interface ClosingOutgoingSapronaksTableProps {
|
||||
const ClosingOutgoingSapronaksTable = ({
|
||||
projectFlockId,
|
||||
}: ClosingOutgoingSapronaksTableProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const kandangId = searchParams.get('kandangId');
|
||||
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
@@ -43,7 +47,7 @@ const ClosingOutgoingSapronaksTable = ({
|
||||
|
||||
const { data: outgoingSapronaks, isLoading: isLoadingOutgoingSapronaks } =
|
||||
useSWR(
|
||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=outgoing`,
|
||||
`${ClosingApi.basePath}/${projectFlockId}/sapronak${getTableFilterQueryString()}&type=outgoing&kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
||||
ClosingApi.getAllOutgoingSapronakFetcher,
|
||||
{
|
||||
keepPreviousData: true,
|
||||
|
||||
@@ -5,122 +5,187 @@ import { cn, formatCurrency, formatDate, formatNumber } from '@/lib/helper';
|
||||
import { ClosingApi } from '@/services/api/closing';
|
||||
import { Overhead, OverheadTotal } from '@/types/api/closing';
|
||||
import { ColumnDef } from '@tanstack/react-table';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useMemo } from 'react';
|
||||
import useSWR from 'swr';
|
||||
|
||||
interface ClosingOverheadTableProps {
|
||||
type?: 'detail';
|
||||
projectFlockId: number;
|
||||
}
|
||||
|
||||
const ClosingOverheadTable = ({
|
||||
type,
|
||||
projectFlockId,
|
||||
}: ClosingOverheadTableProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const kandangId = searchParams.get('kandangId');
|
||||
|
||||
const { data: overhead, isLoading: isLoadingOverhead } = useSWR(
|
||||
`${ClosingApi.basePath}/${projectFlockId}/overhead`,
|
||||
() => ClosingApi.getOverhead(projectFlockId),
|
||||
`${ClosingApi.basePath}/${projectFlockId}${kandangId ? `/${kandangId}` : ''}/overhead`,
|
||||
() =>
|
||||
ClosingApi.getOverhead(
|
||||
projectFlockId,
|
||||
kandangId ? Number(kandangId) : undefined
|
||||
),
|
||||
{
|
||||
keepPreviousData: true,
|
||||
}
|
||||
);
|
||||
|
||||
// Helper function to create columns with footer support
|
||||
const createColumns = (total?: OverheadTotal): ColumnDef<Overhead>[] => [
|
||||
// Group untuk kolom tanpa footer
|
||||
{
|
||||
header: 'Nama Item',
|
||||
accessorFn: (props) => props.item_name,
|
||||
footer: 'Total Pengeluaran Overhead',
|
||||
},
|
||||
{
|
||||
header: 'Satuan',
|
||||
accessorFn: (props) => props.uom_name,
|
||||
},
|
||||
{
|
||||
header: 'Budget Pengajuan',
|
||||
footer: '',
|
||||
columns: [
|
||||
{
|
||||
id: 'budget_quantity',
|
||||
header: 'Jumlah',
|
||||
accessorFn: (props) =>
|
||||
props.budget_quantity ? formatNumber(props.budget_quantity) : '-',
|
||||
footer: total ? () => formatNumber(total.budget_quantity) : '',
|
||||
},
|
||||
{
|
||||
id: 'budget_unit_price',
|
||||
header: 'Harga Satuan',
|
||||
accessorFn: (props) =>
|
||||
props.budget_unit_price
|
||||
? formatCurrency(props.budget_unit_price)
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'budget_total_amount',
|
||||
header: 'Total',
|
||||
accessorFn: (props) =>
|
||||
props.budget_total_amount
|
||||
? formatCurrency(props.budget_total_amount)
|
||||
: '-',
|
||||
footer: total ? () => formatCurrency(total.budget_total_amount) : '',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
header: 'Realisasi',
|
||||
footer: '',
|
||||
columns: [
|
||||
{
|
||||
id: 'actual_date',
|
||||
header: 'Tanggal',
|
||||
accessorFn: (props) =>
|
||||
props.actual_date
|
||||
? formatDate(props.actual_date, 'DD MMM, YYYY')
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'actual_quantity',
|
||||
header: 'Jumlah',
|
||||
accessorFn: (props) =>
|
||||
props.actual_quantity ? formatNumber(props.actual_quantity) : '-',
|
||||
footer: total ? () => formatNumber(total.actual_quantity) : '',
|
||||
},
|
||||
{
|
||||
id: 'actual_unit_price',
|
||||
header: 'Harga Satuan',
|
||||
accessorFn: (props) =>
|
||||
props.actual_unit_price
|
||||
? formatCurrency(props.actual_unit_price)
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'actual_total_amount',
|
||||
header: 'Total',
|
||||
accessorFn: (props) =>
|
||||
props.actual_total_amount
|
||||
? formatCurrency(props.actual_total_amount)
|
||||
: '-',
|
||||
footer: total ? () => formatCurrency(total.actual_total_amount) : '',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'cost_per_bird',
|
||||
header: 'Rp/Ekor',
|
||||
accessorFn: (props) =>
|
||||
props.cost_per_bird ? formatCurrency(props.cost_per_bird) : '-',
|
||||
footer: total ? () => formatCurrency(total.cost_per_bird) : '',
|
||||
},
|
||||
];
|
||||
const createColumns = (
|
||||
total?: OverheadTotal,
|
||||
kandangId?: number
|
||||
): ColumnDef<Overhead>[] => {
|
||||
const flockColumn: ColumnDef<Overhead>[] = [
|
||||
{
|
||||
header: 'Budget Pengajuan',
|
||||
footer: '',
|
||||
columns: [
|
||||
{
|
||||
id: 'budget_quantity',
|
||||
header: 'Jumlah',
|
||||
accessorFn: (props) =>
|
||||
props.budget_quantity ? formatNumber(props.budget_quantity) : '-',
|
||||
footer: total ? () => formatNumber(total.budget_quantity) : '',
|
||||
},
|
||||
{
|
||||
id: 'budget_unit_price',
|
||||
header: 'Harga Satuan',
|
||||
accessorFn: (props) =>
|
||||
props.budget_unit_price
|
||||
? formatCurrency(props.budget_unit_price)
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'budget_total_amount',
|
||||
header: 'Total',
|
||||
accessorFn: (props) =>
|
||||
props.budget_total_amount
|
||||
? formatCurrency(props.budget_total_amount)
|
||||
: '-',
|
||||
footer: total
|
||||
? () => formatCurrency(total.budget_total_amount)
|
||||
: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
header: 'Realisasi',
|
||||
footer: '',
|
||||
columns: [
|
||||
{
|
||||
id: 'actual_date',
|
||||
header: 'Tanggal',
|
||||
accessorFn: (props) =>
|
||||
props.actual_date
|
||||
? formatDate(props.actual_date, 'DD MMM, YYYY')
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'actual_quantity',
|
||||
header: 'Jumlah',
|
||||
accessorFn: (props) =>
|
||||
props.actual_quantity ? formatNumber(props.actual_quantity) : '-',
|
||||
footer: total ? () => formatNumber(total.actual_quantity) : '',
|
||||
},
|
||||
{
|
||||
id: 'actual_unit_price',
|
||||
header: 'Harga Satuan',
|
||||
accessorFn: (props) =>
|
||||
props.actual_unit_price
|
||||
? formatCurrency(props.actual_unit_price)
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'actual_total_amount',
|
||||
header: 'Total',
|
||||
accessorFn: (props) =>
|
||||
props.actual_total_amount
|
||||
? formatCurrency(props.actual_total_amount)
|
||||
: '-',
|
||||
footer: total
|
||||
? () => formatCurrency(total.actual_total_amount)
|
||||
: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const kandangColumn: ColumnDef<Overhead>[] = [
|
||||
{
|
||||
id: 'actual_date',
|
||||
header: 'Tanggal',
|
||||
accessorFn: (props) =>
|
||||
props.actual_date
|
||||
? formatDate(props.actual_date, 'DD MMM, YYYY')
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'actual_quantity',
|
||||
header: 'Jumlah',
|
||||
accessorFn: (props) =>
|
||||
props.actual_quantity ? formatNumber(props.actual_quantity) : '-',
|
||||
footer: total ? () => formatNumber(total.actual_quantity) : '',
|
||||
},
|
||||
{
|
||||
id: 'actual_unit_price',
|
||||
header: 'Harga Satuan',
|
||||
accessorFn: (props) =>
|
||||
props.actual_unit_price
|
||||
? formatCurrency(props.actual_unit_price)
|
||||
: '-',
|
||||
footer: '',
|
||||
},
|
||||
{
|
||||
id: 'actual_total_amount',
|
||||
header: 'Total',
|
||||
accessorFn: (props) =>
|
||||
props.actual_total_amount
|
||||
? formatCurrency(props.actual_total_amount)
|
||||
: '-',
|
||||
footer: total ? () => formatCurrency(total.actual_total_amount) : '',
|
||||
},
|
||||
];
|
||||
|
||||
const finalColumns: ColumnDef<Overhead>[] = [
|
||||
// Group untuk kolom tanpa footer
|
||||
{
|
||||
header: 'No',
|
||||
accessorFn: (_, index) => index,
|
||||
cell: (props) => props.row.index + 1,
|
||||
},
|
||||
{
|
||||
header: 'Nama Item',
|
||||
accessorFn: (props) => props.item_name,
|
||||
footer: 'Total Pengeluaran Overhead',
|
||||
},
|
||||
{
|
||||
header: 'Satuan',
|
||||
accessorFn: (props) => props.uom_name,
|
||||
},
|
||||
...(kandangId ? kandangColumn : flockColumn),
|
||||
{
|
||||
id: 'cost_per_bird',
|
||||
header: 'Rp/Ekor',
|
||||
accessorFn: (props) =>
|
||||
props.cost_per_bird ? formatCurrency(props.cost_per_bird) : '-',
|
||||
footer: total ? () => formatCurrency(total.cost_per_bird) : '',
|
||||
},
|
||||
];
|
||||
return finalColumns;
|
||||
};
|
||||
|
||||
const columns = useMemo(
|
||||
() =>
|
||||
isResponseSuccess(overhead)
|
||||
? createColumns(overhead.data?.total)
|
||||
? createColumns(
|
||||
overhead.data?.total,
|
||||
kandangId ? Number(kandangId) : undefined
|
||||
)
|
||||
: createColumns(),
|
||||
[overhead]
|
||||
);
|
||||
@@ -148,6 +213,7 @@ const ClosingOverheadTable = ({
|
||||
'whitespace-nowrap'
|
||||
),
|
||||
}}
|
||||
isLoading={isLoadingOverhead}
|
||||
renderFooter={
|
||||
isResponseSuccess(overhead)
|
||||
? overhead.data?.overheads.length > 0
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
import { ClosingApi } from '@/services/api/closing';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
@@ -12,9 +13,12 @@ interface ClosingProductionDataTabContentProps {
|
||||
const ClosingProductionDataTabContent = ({
|
||||
projectFlockId,
|
||||
}: ClosingProductionDataTabContentProps) => {
|
||||
const searchParams = useSearchParams();
|
||||
const kandangId = searchParams.get('kandangId');
|
||||
|
||||
const { data: productionData, isLoading } = useSWR(
|
||||
`${ClosingApi.basePath}/${projectFlockId}/production-data`,
|
||||
() => ClosingApi.getProductionData(projectFlockId)
|
||||
`${ClosingApi.basePath}/${projectFlockId}/production-data?kandang_id=${kandangId ? `${kandangId}` : ''}`,
|
||||
() => ClosingApi.getProductionData(projectFlockId, Number(kandangId))
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
@@ -197,7 +201,7 @@ const ClosingProductionDataTabContent = ({
|
||||
value={formatNumber(performance.mor_diff)}
|
||||
unitClassName='hidden'
|
||||
/>
|
||||
<DataRow
|
||||
{/* <DataRow
|
||||
label='AWG Std'
|
||||
value={formatNumber(performance.awg_std)}
|
||||
unit='Gr/Hari'
|
||||
@@ -206,7 +210,7 @@ const ClosingProductionDataTabContent = ({
|
||||
label='AWG Act'
|
||||
value={formatNumber(performance.awg_act)}
|
||||
unit='Gr/Hari'
|
||||
/>
|
||||
/> */}
|
||||
<DataRow
|
||||
label='Feed Intake Std'
|
||||
value={formatNumber(performance.feed_intake_std)}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import ClosingIncomingSapronaksTable from '@/components/pages/closing/ClosingIncomingSapronaksTable';
|
||||
import ClosingOutgoingSapronaksTable from '@/components/pages/closing/ClosingOutgoingSapronaksTable';
|
||||
import ClosingIncomingSapronaksSummaryTable from '@/components/pages/closing/ClosingIncomingSapronaksSummaryTable';
|
||||
import ClosingOutgoingSapronaksSummaryTable from './ClosingOutgoingSapronaksSummaryTable';
|
||||
|
||||
interface ClosingSapronakTableProps {
|
||||
projectFlockId?: number;
|
||||
@@ -16,7 +18,15 @@ const ClosingSapronakTabContent = ({
|
||||
<>
|
||||
<ClosingIncomingSapronaksTable projectFlockId={projectFlockId} />
|
||||
|
||||
<ClosingIncomingSapronaksSummaryTable
|
||||
projectFlockId={projectFlockId}
|
||||
/>
|
||||
|
||||
<ClosingOutgoingSapronaksTable projectFlockId={projectFlockId} />
|
||||
|
||||
<ClosingOutgoingSapronaksSummaryTable
|
||||
projectFlockId={projectFlockId}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -104,6 +104,10 @@ const ClosingsTable = () => {
|
||||
header: '#',
|
||||
cell: (props) => props.row.index + 1,
|
||||
},
|
||||
{
|
||||
accessorKey: 'project_name',
|
||||
header: 'Flock',
|
||||
},
|
||||
{
|
||||
accessorKey: 'location_name',
|
||||
header: 'Lokasi',
|
||||
@@ -163,6 +167,7 @@ const ClosingsTable = () => {
|
||||
setInputValue: setLocationInputValue,
|
||||
options: locationOptions,
|
||||
isLoadingOptions: isLoadingLocationOptions,
|
||||
loadMore: loadMoreLocations,
|
||||
} = useSelect<Location>(LocationApi.basePath, 'id', 'name');
|
||||
|
||||
const [selectedLocation, setSelectedLocation] = useState<OptionType | null>(
|
||||
@@ -228,6 +233,7 @@ const ClosingsTable = () => {
|
||||
value={selectedLocation}
|
||||
onChange={locationChangeHandler}
|
||||
onInputChange={setLocationInputValue}
|
||||
onMenuScrollToBottom={loadMoreLocations}
|
||||
isClearable
|
||||
className={{
|
||||
wrapper: 'col-span-12 sm:col-span-6',
|
||||
|
||||
@@ -13,7 +13,6 @@ interface HppExpeditionReportTableProps {
|
||||
}
|
||||
|
||||
const HppExpeditionReportTable = ({
|
||||
type = 'detail',
|
||||
initialValues,
|
||||
}: HppExpeditionReportTableProps) => {
|
||||
const costOfRevenueExpeditionData: BaseExpeditionCost[] = useMemo(() => {
|
||||
|
||||
@@ -4,9 +4,12 @@ import React, { useMemo } from 'react';
|
||||
import { ColumnDef } from '@tanstack/react-table';
|
||||
import Table from '@/components/Table';
|
||||
import Card from '@/components/Card';
|
||||
import Badge from '@/components/Badge';
|
||||
import { formatCurrency, formatNumber, formatDate } from '@/lib/helper';
|
||||
import { BaseClosingSales, BaseSales } from '@/types/api/closing';
|
||||
import {
|
||||
BaseClosingSales,
|
||||
BaseSales,
|
||||
ClosingSalesSummary,
|
||||
} from '@/types/api/closing';
|
||||
import { Product } from '@/types/api/master-data/product';
|
||||
import { Customer } from '@/types/api/master-data/customer';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
@@ -16,22 +19,25 @@ interface SalesReportTableProps {
|
||||
initialValues?: BaseClosingSales;
|
||||
}
|
||||
|
||||
const SalesReportTable = ({
|
||||
type = 'detail',
|
||||
initialValues,
|
||||
}: SalesReportTableProps) => {
|
||||
const SalesReportTable = ({ initialValues }: SalesReportTableProps) => {
|
||||
const salesData: BaseSales[] = useMemo(() => {
|
||||
return initialValues?.sales || [];
|
||||
}, [initialValues]);
|
||||
|
||||
const summary: ClosingSalesSummary | undefined = useMemo(() => {
|
||||
return initialValues?.summary;
|
||||
}, [initialValues]);
|
||||
|
||||
const totals = useMemo(() => {
|
||||
if (salesData.length === 0) {
|
||||
return {
|
||||
totalQuantity: 0,
|
||||
totalWeight: 0,
|
||||
avgWeight: 0,
|
||||
avgPricePartner: 0,
|
||||
totalPartner: 0,
|
||||
avgSalesPrice: 0,
|
||||
totalSalesPrice: 0,
|
||||
avgActualPrice: 0,
|
||||
totalActualPrice: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,26 +51,46 @@ const SalesReportTable = ({
|
||||
);
|
||||
const avgWeight = totalQuantity > 0 ? totalWeight / totalQuantity : 0;
|
||||
|
||||
const validPriceItems = salesData.filter(
|
||||
(item) => item.price != null && item.price > 0
|
||||
);
|
||||
const avgPricePartner =
|
||||
validPriceItems.length > 0
|
||||
? validPriceItems.reduce((sum, item) => sum + item.price, 0) /
|
||||
validPriceItems.length
|
||||
: 0;
|
||||
|
||||
const totalPartner = salesData.reduce(
|
||||
(sum, item) => sum + (item.total_price || 0),
|
||||
const totalSalesPrice = salesData.reduce(
|
||||
(sum, item) => sum + (item.total_sales_price || 0),
|
||||
0
|
||||
);
|
||||
|
||||
const validSalesPriceItems = salesData.filter(
|
||||
(item) => item.sales_price != null && item.sales_price > 0
|
||||
);
|
||||
const avgSalesPrice =
|
||||
validSalesPriceItems.length > 0
|
||||
? validSalesPriceItems.reduce(
|
||||
(sum, item) => sum + item.sales_price,
|
||||
0
|
||||
) / validSalesPriceItems.length
|
||||
: 0;
|
||||
|
||||
const totalActualPrice = salesData.reduce(
|
||||
(sum, item) => sum + (item.total_actual_price || 0),
|
||||
0
|
||||
);
|
||||
|
||||
const validActualPriceItems = salesData.filter(
|
||||
(item) => item.actual_price != null && item.actual_price > 0
|
||||
);
|
||||
const avgActualPrice =
|
||||
validActualPriceItems.length > 0
|
||||
? validActualPriceItems.reduce(
|
||||
(sum, item) => sum + item.actual_price,
|
||||
0
|
||||
) / validActualPriceItems.length
|
||||
: 0;
|
||||
|
||||
return {
|
||||
totalQuantity,
|
||||
totalWeight,
|
||||
avgWeight,
|
||||
avgPricePartner,
|
||||
totalPartner,
|
||||
avgSalesPrice,
|
||||
totalSalesPrice,
|
||||
avgActualPrice,
|
||||
totalActualPrice,
|
||||
};
|
||||
}, [salesData]);
|
||||
|
||||
@@ -86,7 +112,11 @@ const SalesReportTable = ({
|
||||
id: 'age',
|
||||
accessorKey: 'age',
|
||||
header: 'Umur',
|
||||
cell: (props) => props.getValue() || '-',
|
||||
cell: (props) => {
|
||||
const age = props.row.original.age;
|
||||
const week = props.row.original.week;
|
||||
return age && week ? `${age} hari (${week} minggu)` : '-';
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'do_number',
|
||||
@@ -161,50 +191,68 @@ const SalesReportTable = ({
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'price_partner',
|
||||
accessorKey: 'price',
|
||||
header: 'Harga Mitra (Rp)',
|
||||
id: 'sales_price',
|
||||
accessorKey: 'sales_price',
|
||||
header: 'Harga Sales (Rp)',
|
||||
cell: (props) => {
|
||||
const value = props.getValue() as number;
|
||||
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||
},
|
||||
footer: () => (
|
||||
<div className='text-right font-semibold text-gray-900'>
|
||||
{formatCurrency(totals.avgPricePartner)}
|
||||
{summary
|
||||
? formatCurrency(summary.avg_sales_price)
|
||||
: formatCurrency(totals.avgSalesPrice)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'total_mitra',
|
||||
accessorKey: 'total_price',
|
||||
header: 'Total Mitra (Rp)',
|
||||
id: 'total_sales_price',
|
||||
accessorKey: 'total_sales_price',
|
||||
header: 'Total Sales (Rp)',
|
||||
cell: (props) => {
|
||||
const value = props.getValue() as number;
|
||||
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||
},
|
||||
footer: () => (
|
||||
<div className='text-right font-semibold text-gray-900'>
|
||||
{formatCurrency(totals.totalPartner)}
|
||||
{summary
|
||||
? formatCurrency(summary.total_sales_price)
|
||||
: formatCurrency(totals.totalSalesPrice)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'price_act',
|
||||
accessorKey: 'price',
|
||||
id: 'actual_price',
|
||||
accessorKey: 'actual_price',
|
||||
header: 'Harga Act (Rp)',
|
||||
cell: (props) => {
|
||||
const value = props.getValue() as number;
|
||||
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||
},
|
||||
footer: () => (
|
||||
<div className='text-right font-semibold text-gray-900'>
|
||||
{summary
|
||||
? formatCurrency(summary.avg_actual_price)
|
||||
: formatCurrency(totals.avgActualPrice)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'total_act',
|
||||
accessorKey: 'total_price',
|
||||
id: 'total_actual_price',
|
||||
accessorKey: 'total_actual_price',
|
||||
header: 'Total Act (Rp)',
|
||||
cell: (props) => {
|
||||
const value = props.getValue() as number;
|
||||
return <div className='text-right'>{formatCurrency(value)}</div>;
|
||||
},
|
||||
footer: () => (
|
||||
<div className='text-right font-semibold text-gray-900'>
|
||||
{summary
|
||||
? formatCurrency(summary.total_actual_price)
|
||||
: formatCurrency(totals.totalActualPrice)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'kandang',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,11 @@
|
||||
import Button from '@/components/Button';
|
||||
import Card from '@/components/Card';
|
||||
import Dropdown from '@/components/Dropdown';
|
||||
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
|
||||
import { OptionType } from '@/components/input/SelectInput';
|
||||
import Menu from '@/components/menu/Menu';
|
||||
import MenuItem from '@/components/menu/MenuItem';
|
||||
import { formatNumber } from '@/lib/helper';
|
||||
import {
|
||||
Dashboard,
|
||||
DashboardOverviewCharts,
|
||||
@@ -25,20 +28,29 @@ import {
|
||||
type DashboardLineChartProps = {
|
||||
analysisMode: 'OVERVIEW' | 'COMPARISON';
|
||||
data: Dashboard;
|
||||
selectedKandang?: OptionType;
|
||||
};
|
||||
|
||||
// Type guard to check if charts is DashboardOverviewCharts
|
||||
function isOverviewCharts(
|
||||
charts: DashboardOverviewCharts | DashboardComparisonCharts
|
||||
charts: DashboardOverviewCharts | DashboardComparisonCharts | undefined
|
||||
): charts is DashboardOverviewCharts {
|
||||
return 'deplesi' in charts;
|
||||
if (!charts) return false;
|
||||
return (
|
||||
'deplesi' in charts ||
|
||||
'body_weight' in charts ||
|
||||
'fcr' in charts ||
|
||||
'performance' in charts ||
|
||||
'quality_control' in charts
|
||||
);
|
||||
}
|
||||
|
||||
// Type guard to check if charts is DashboardComparisonCharts
|
||||
function isComparisonCharts(
|
||||
charts: DashboardOverviewCharts | DashboardComparisonCharts
|
||||
charts: DashboardOverviewCharts | DashboardComparisonCharts | undefined
|
||||
): charts is DashboardComparisonCharts {
|
||||
return 'location' in charts || 'flock' in charts || 'kandang' in charts;
|
||||
if (!charts) return false;
|
||||
return 'farm' in charts || 'flock' in charts || 'kandang' in charts;
|
||||
}
|
||||
|
||||
const lineColors: Record<string, string> = {
|
||||
@@ -94,6 +106,7 @@ const getLineColor = (
|
||||
const DashboardLineChart = ({
|
||||
analysisMode,
|
||||
data,
|
||||
selectedKandang,
|
||||
}: DashboardLineChartProps) => {
|
||||
const [chartData, setChartData] =
|
||||
useState<keyof DashboardOverviewCharts>('body_weight');
|
||||
@@ -123,7 +136,7 @@ const DashboardLineChart = ({
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.location || data.charts.flock || data.charts.kandang;
|
||||
data.charts.farm || data.charts.flock || data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
}
|
||||
|
||||
@@ -135,11 +148,12 @@ const DashboardLineChart = ({
|
||||
return (
|
||||
<Card
|
||||
className={{
|
||||
wrapper: 'w-full rounded-lg',
|
||||
wrapper: 'w-full rounded-lg p-0',
|
||||
body: 'p-4',
|
||||
}}
|
||||
variant='bordered'
|
||||
>
|
||||
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6'>
|
||||
<div className='flex flex-col sm:flex-row justify-between items-start gap-4 mb-3'>
|
||||
<div className='text-lg font-semibold'>
|
||||
Performance{' '}
|
||||
<Icon
|
||||
@@ -153,26 +167,28 @@ const DashboardLineChart = ({
|
||||
<Dropdown
|
||||
align='end'
|
||||
direction='bottom'
|
||||
className={{
|
||||
content: 'mt-1 min-w-full',
|
||||
}}
|
||||
trigger={
|
||||
<Button
|
||||
variant='outline'
|
||||
color='none'
|
||||
className='text-neutral-500 hover:text-neutral-700 rounded-lg px-4 py-2 border-neutral-300'
|
||||
className='py-2.5 pl-3 pr-2 text-base-content/50 rounded-lg text-sm border-base-content/10 shadow-button-soft'
|
||||
onClick={() => setOpen(!open)}
|
||||
>
|
||||
{chartTypeLabels[chartData]}{' '}
|
||||
<div className='divider divider-horizontal p-0 m-0 before:bg-neutral-300 after:bg-neutral-300'></div>
|
||||
<Icon icon='heroicons:chevron-down' width={20} height={20} />
|
||||
<div className='w-6 h-5 flex items-center justify-center border-l border-base-content/10'>
|
||||
<Icon icon='heroicons:chevron-down' width={14} height={14} />
|
||||
</div>
|
||||
</Button>
|
||||
}
|
||||
className={{
|
||||
content: 'w-52 mt-3',
|
||||
}}
|
||||
controlled={open}
|
||||
>
|
||||
<Menu>
|
||||
<Menu className='p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg'>
|
||||
<MenuItem
|
||||
title='Body weight'
|
||||
className='text-sm padding-3 whitespace-nowrap'
|
||||
onClick={() => {
|
||||
setChartData('body_weight');
|
||||
setOpen(!open);
|
||||
@@ -180,6 +196,7 @@ const DashboardLineChart = ({
|
||||
/>
|
||||
<MenuItem
|
||||
title='Performance'
|
||||
className='text-sm padding-3 whitespace-nowrap'
|
||||
onClick={() => {
|
||||
setChartData('performance');
|
||||
setOpen(!open);
|
||||
@@ -187,6 +204,7 @@ const DashboardLineChart = ({
|
||||
/>
|
||||
<MenuItem
|
||||
title='FCR'
|
||||
className='text-sm padding-3 whitespace-nowrap'
|
||||
onClick={() => {
|
||||
setChartData('fcr');
|
||||
setOpen(!open);
|
||||
@@ -194,6 +212,7 @@ const DashboardLineChart = ({
|
||||
/>
|
||||
<MenuItem
|
||||
title='Quality Control'
|
||||
className='text-sm padding-3 whitespace-nowrap'
|
||||
onClick={() => {
|
||||
setChartData('quality_control');
|
||||
setOpen(!open);
|
||||
@@ -201,6 +220,7 @@ const DashboardLineChart = ({
|
||||
/>
|
||||
<MenuItem
|
||||
title='Deplesi'
|
||||
className='text-sm padding-3 whitespace-nowrap'
|
||||
onClick={() => {
|
||||
setChartData('deplesi');
|
||||
setOpen(!open);
|
||||
@@ -224,7 +244,7 @@ const DashboardLineChart = ({
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.location || data.charts.flock || data.charts.kandang;
|
||||
data.charts.farm || data.charts.flock || data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
}
|
||||
|
||||
@@ -236,8 +256,8 @@ const DashboardLineChart = ({
|
||||
.includes('std');
|
||||
|
||||
return (
|
||||
<button
|
||||
key={series.id}
|
||||
<Button
|
||||
key={`${series.id}-${index}`}
|
||||
onClick={() => {
|
||||
const newVisible = new Set(visibleSeries);
|
||||
if (isVisible) {
|
||||
@@ -247,14 +267,16 @@ const DashboardLineChart = ({
|
||||
}
|
||||
setVisibleSeries(newVisible);
|
||||
}}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
|
||||
variant='outline'
|
||||
color='none'
|
||||
className={`flex items-center gap-2 p-3 rounded-lg border transition-colors ${
|
||||
isVisible
|
||||
? 'border-neutral-400 bg-neutral-50'
|
||||
: 'border-neutral-300 hover:bg-neutral-50'
|
||||
? 'border-base-content/10 hover:bg-base-content/4'
|
||||
: 'border-base-content/10 bg-base-content/4'
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`w-6 h-0.5 ${
|
||||
className={`w-5 h-0.5 ${
|
||||
isStandard ? 'border-t-2 border-dashed' : ''
|
||||
} ${!isVisible ? 'opacity-30' : ''}`}
|
||||
style={{
|
||||
@@ -267,277 +289,457 @@ const DashboardLineChart = ({
|
||||
}}
|
||||
></div>
|
||||
<span
|
||||
className={`text-sm ${isVisible ? 'text-neutral-900 font-medium' : 'text-neutral-700'}`}
|
||||
className={`font-semibold text-sm ${isVisible ? 'text-base-content/50' : 'text-base-content/50'}`}
|
||||
>
|
||||
{series.label}
|
||||
</span>
|
||||
<Icon
|
||||
icon='heroicons:information-circle'
|
||||
icon='heroicons:eye'
|
||||
width={16}
|
||||
height={16}
|
||||
className='text-neutral-400'
|
||||
className='text-base-content/40'
|
||||
/>
|
||||
</button>
|
||||
</Button>
|
||||
);
|
||||
});
|
||||
})()}
|
||||
</div>
|
||||
|
||||
{/* Chart */}
|
||||
<ResponsiveContainer width='100%' height={350}>
|
||||
<LineChart
|
||||
data={(() => {
|
||||
// Transform data based on analysisMode
|
||||
if (analysisMode === 'OVERVIEW') {
|
||||
// For OVERVIEW mode, use the selected chart data
|
||||
if (isOverviewCharts(data.charts)) {
|
||||
const selectedChartData = data.charts[chartData];
|
||||
if (!selectedChartData || !selectedChartData.dataset) return [];
|
||||
return selectedChartData.dataset;
|
||||
{/* Chart Container with Empty State Overlay */}
|
||||
<div className='relative'>
|
||||
{/* Chart */}
|
||||
<ResponsiveContainer width='100%' height={350}>
|
||||
<LineChart
|
||||
data={(() => {
|
||||
// Transform data based on analysisMode
|
||||
if (analysisMode === 'OVERVIEW') {
|
||||
// For OVERVIEW mode, use the selected chart data
|
||||
if (isOverviewCharts(data.charts)) {
|
||||
const selectedChartData = data.charts[chartData];
|
||||
if (!selectedChartData || !selectedChartData.dataset)
|
||||
return [];
|
||||
return selectedChartData.dataset;
|
||||
}
|
||||
return [];
|
||||
} else {
|
||||
// For COMPARISON mode, use the first available comparison chart
|
||||
if (isComparisonCharts(data.charts)) {
|
||||
const chartData =
|
||||
data.charts.farm ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
|
||||
if (!chartData || !chartData.dataset) return [];
|
||||
return chartData.dataset;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
} else {
|
||||
// For COMPARISON mode, use the first available comparison chart
|
||||
if (isComparisonCharts(data.charts)) {
|
||||
const chartData =
|
||||
data.charts.location ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
|
||||
if (!chartData || !chartData.dataset) return [];
|
||||
return chartData.dataset;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
})()}
|
||||
margin={{
|
||||
top: 5,
|
||||
right: 10,
|
||||
left: 0,
|
||||
bottom: 5,
|
||||
}}
|
||||
>
|
||||
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
|
||||
<XAxis
|
||||
dataKey='week'
|
||||
tick={{ fontSize: 11, fill: '#9ca3af' }}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: '#e5e7eb' }}
|
||||
label={{
|
||||
value: 'Weeks',
|
||||
position: 'insideBottom',
|
||||
offset: -5,
|
||||
style: { fontSize: 12, fill: '#9ca3af' },
|
||||
}}
|
||||
/>
|
||||
<YAxis
|
||||
tick={{ fontSize: 11, fill: '#9ca3af' }}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: '#e5e7eb' }}
|
||||
domain={(() => {
|
||||
// Calculate dynamic domain based on visible data
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
let dataset: DashboardChartsDataset[] = [];
|
||||
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
dataset = data.charts[chartData]?.dataset || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.location ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
dataset = comparisonChart?.dataset || [];
|
||||
}
|
||||
|
||||
// Get all values from visible series
|
||||
const visibleSeriesIds = Array.from(visibleSeries);
|
||||
const allValues: number[] = [];
|
||||
|
||||
dataset.forEach((item: DashboardChartsDataset) => {
|
||||
visibleSeriesIds.forEach((seriesId) => {
|
||||
const value = item[seriesId];
|
||||
if (typeof value === 'number') {
|
||||
allValues.push(value);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (allValues.length === 0) return [0, 100];
|
||||
|
||||
const minValue = Math.min(...allValues);
|
||||
const maxValue = Math.max(...allValues);
|
||||
|
||||
// Add padding (10% on each side)
|
||||
const padding = (maxValue - minValue) * 0.1;
|
||||
const domainMin = Math.floor(Math.max(0, minValue - padding));
|
||||
const domainMax = Math.ceil(maxValue + padding);
|
||||
|
||||
return [domainMin, domainMax];
|
||||
})()}
|
||||
ticks={(() => {
|
||||
// Calculate dynamic ticks based on domain
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
let dataset: DashboardChartsDataset[] = [];
|
||||
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
dataset = data.charts[chartData]?.dataset || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.location ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
dataset = comparisonChart?.dataset || [];
|
||||
}
|
||||
|
||||
const visibleSeriesIds = Array.from(visibleSeries);
|
||||
const allValues: number[] = [];
|
||||
|
||||
dataset.forEach((item: DashboardChartsDataset) => {
|
||||
visibleSeriesIds.forEach((seriesId) => {
|
||||
const value = item[seriesId];
|
||||
if (typeof value === 'number') {
|
||||
allValues.push(value);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (allValues.length === 0) return [0, 25, 50, 75, 100];
|
||||
|
||||
const minValue = Math.min(...allValues);
|
||||
const maxValue = Math.max(...allValues);
|
||||
const padding = (maxValue - minValue) * 0.1;
|
||||
const domainMin = Math.floor(Math.max(0, minValue - padding));
|
||||
const domainMax = Math.ceil(maxValue + padding);
|
||||
|
||||
// Generate 5 evenly spaced ticks
|
||||
const range = domainMax - domainMin;
|
||||
const step = range / 4;
|
||||
|
||||
return [
|
||||
domainMin,
|
||||
Math.round(domainMin + step),
|
||||
Math.round(domainMin + step * 2),
|
||||
Math.round(domainMin + step * 3),
|
||||
domainMax,
|
||||
];
|
||||
})()}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: '#1f2937',
|
||||
border: 'none',
|
||||
borderRadius: '8px',
|
||||
padding: '8px 12px',
|
||||
color: 'white',
|
||||
margin={{
|
||||
top: 5,
|
||||
right: 10,
|
||||
left: 0,
|
||||
bottom: 5,
|
||||
}}
|
||||
labelStyle={{ color: 'white', marginBottom: '4px' }}
|
||||
itemStyle={{ color: 'white', fontSize: '12px' }}
|
||||
labelFormatter={(value) => `Week ${value}`}
|
||||
formatter={(
|
||||
value: number | undefined,
|
||||
name: string | undefined
|
||||
) => {
|
||||
if (value === undefined || name === undefined) return ['', ''];
|
||||
|
||||
// Get series data to find the unit
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.location ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
}
|
||||
|
||||
// Find the series that matches this line's name
|
||||
const series = seriesData.find((s) => s.label === name);
|
||||
const unit = series?.unit || '';
|
||||
|
||||
return [`${value} ${unit}`, name];
|
||||
}}
|
||||
/>
|
||||
{/* Dynamic Line rendering based on visible series */}
|
||||
{(() => {
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
|
||||
if (analysisMode === 'OVERVIEW' && isOverviewCharts(data.charts)) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.location ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
}
|
||||
|
||||
return seriesData
|
||||
.filter((series) => visibleSeries.has(series.id))
|
||||
.map((series, index) => {
|
||||
const isStandard = series.id
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.includes('std');
|
||||
// Use series.id directly as dataKey to match dataset fields
|
||||
const dataKey = series.id.toString();
|
||||
|
||||
return (
|
||||
<Line
|
||||
key={series.id}
|
||||
type='monotone'
|
||||
dataKey={dataKey}
|
||||
name={series.label}
|
||||
stroke={getLineColor(series.id, index, analysisMode)}
|
||||
opacity={isStandard ? 0.5 : 1}
|
||||
strokeWidth={2}
|
||||
strokeDasharray={isStandard ? '5 5' : undefined}
|
||||
dot={
|
||||
isStandard
|
||||
? false
|
||||
: {
|
||||
r: 3,
|
||||
fill: '#fff',
|
||||
stroke: getLineColor(
|
||||
series.id,
|
||||
index,
|
||||
analysisMode
|
||||
),
|
||||
strokeWidth: 2,
|
||||
}
|
||||
>
|
||||
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
|
||||
<XAxis
|
||||
dataKey='week'
|
||||
tick={{
|
||||
fontSize: 12,
|
||||
fill: '#18181B',
|
||||
opacity: 0.5,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: '#C1C1C180', opacity: 0.5 }}
|
||||
label={{
|
||||
value: 'Weeks',
|
||||
position: 'insideBottom',
|
||||
offset: -5,
|
||||
style: {
|
||||
fontSize: 12,
|
||||
fill: '#18181B',
|
||||
opacity: 0.2,
|
||||
fontWeight: 600,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
<YAxis
|
||||
tick={{
|
||||
fontSize: 12,
|
||||
fill: '#18181B',
|
||||
opacity: 0.5,
|
||||
fontWeight: 600,
|
||||
}}
|
||||
label={
|
||||
(chartData === 'body_weight' || chartData === 'performance') &&
|
||||
analysisMode === 'OVERVIEW'
|
||||
? {
|
||||
value:
|
||||
chartData === 'body_weight'
|
||||
? 'Body Weight'
|
||||
: 'Percentage',
|
||||
position: 'insideLeft',
|
||||
angle: -90,
|
||||
offset: 5,
|
||||
style: {
|
||||
fontSize: 12,
|
||||
fill: '#18181B',
|
||||
opacity: 0.2,
|
||||
fontWeight: 600,
|
||||
},
|
||||
}
|
||||
activeDot={isStandard ? undefined : { r: 5 }}
|
||||
/>
|
||||
: analysisMode === 'COMPARISON'
|
||||
? {
|
||||
value: 'Percentage',
|
||||
position: 'insideLeft',
|
||||
angle: -90,
|
||||
offset: 5,
|
||||
style: {
|
||||
fontSize: 12,
|
||||
fill: '#18181B',
|
||||
opacity: 0.2,
|
||||
fontWeight: 600,
|
||||
},
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: '#C1C1C180', opacity: 0.5 }}
|
||||
domain={(() => {
|
||||
// Calculate dynamic domain based on visible data
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
let dataset: DashboardChartsDataset[] = [];
|
||||
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
dataset = data.charts[chartData]?.dataset || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.farm ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
dataset = comparisonChart?.dataset || [];
|
||||
}
|
||||
|
||||
// Get all values from visible series
|
||||
const visibleSeriesIds = Array.from(visibleSeries);
|
||||
const allValues: number[] = [];
|
||||
|
||||
dataset.forEach((item: DashboardChartsDataset) => {
|
||||
visibleSeriesIds.forEach((seriesId) => {
|
||||
const value = item[seriesId];
|
||||
if (typeof value === 'number') {
|
||||
allValues.push(value);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (allValues.length === 0) return [0, 100];
|
||||
|
||||
const minValue = Math.min(...allValues);
|
||||
const maxValue = Math.max(...allValues);
|
||||
|
||||
// Add padding (10% on each side)
|
||||
const padding = (maxValue - minValue) * 0.1;
|
||||
const domainMin = Math.floor(Math.max(0, minValue - padding));
|
||||
const domainMax = Math.ceil(maxValue + padding);
|
||||
|
||||
return [domainMin, domainMax];
|
||||
})()}
|
||||
ticks={(() => {
|
||||
// Calculate dynamic ticks based on domain
|
||||
let dataset: DashboardChartsDataset[] = [];
|
||||
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
dataset = data.charts[chartData]?.dataset || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.farm ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
dataset = comparisonChart?.dataset || [];
|
||||
}
|
||||
|
||||
const visibleSeriesIds = Array.from(visibleSeries);
|
||||
const allValues: number[] = [];
|
||||
|
||||
dataset.forEach((item: DashboardChartsDataset) => {
|
||||
visibleSeriesIds.forEach((seriesId) => {
|
||||
const value = item[seriesId];
|
||||
if (typeof value === 'number') {
|
||||
allValues.push(value);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (allValues.length === 0) return [0, 25, 50, 75, 100];
|
||||
|
||||
const minValue = Math.min(...allValues);
|
||||
const maxValue = Math.max(...allValues);
|
||||
|
||||
// Handle edge case where min equals max
|
||||
if (minValue === maxValue) {
|
||||
const value = Math.round(minValue);
|
||||
const padding = Math.max(10, Math.abs(value) * 0.2);
|
||||
return [
|
||||
Math.floor(value - padding),
|
||||
Math.floor(value - padding / 2),
|
||||
value,
|
||||
Math.ceil(value + padding / 2),
|
||||
Math.ceil(value + padding),
|
||||
];
|
||||
}
|
||||
|
||||
const padding = (maxValue - minValue) * 0.1;
|
||||
const domainMin = Math.floor(Math.max(0, minValue - padding));
|
||||
const domainMax = Math.ceil(maxValue + padding);
|
||||
|
||||
// Generate 5 evenly spaced ticks
|
||||
const range = domainMax - domainMin;
|
||||
const step = range / 4;
|
||||
|
||||
// Use Set to ensure unique values
|
||||
const tickSet = new Set([
|
||||
domainMin,
|
||||
Math.round(domainMin + step),
|
||||
Math.round(domainMin + step * 2),
|
||||
Math.round(domainMin + step * 3),
|
||||
domainMax,
|
||||
]);
|
||||
|
||||
return Array.from(tickSet).sort((a, b) => a - b);
|
||||
})()}
|
||||
tickFormatter={(value) => formatNumber(Number(value))}
|
||||
/>
|
||||
<Tooltip
|
||||
contentStyle={{
|
||||
backgroundColor: '#1f2937',
|
||||
border: 'none',
|
||||
borderRadius: '8px',
|
||||
padding: '12px 12px',
|
||||
color: 'white',
|
||||
}}
|
||||
labelStyle={{ color: 'white', marginBottom: '4px' }}
|
||||
itemStyle={{ color: 'white', fontSize: '12px' }}
|
||||
labelFormatter={(value) => `Week ${value}`}
|
||||
content={(props) => {
|
||||
return (
|
||||
<div className='flex flex-col gap-1.5 rounded-lg bg-neutral-950 p-4 text-white'>
|
||||
<p className='text-white/50 text-xs font-semibold text-start'>
|
||||
{analysisMode === 'OVERVIEW'
|
||||
? selectedKandang
|
||||
? selectedKandang.label || 'Overview Performance'
|
||||
: 'Overview Performance'
|
||||
: 'Comparison Performance'}
|
||||
</p>
|
||||
<ul className='flex flex-col gap-1'>
|
||||
{props.payload.map((item, index) => {
|
||||
if (item.name.startsWith('STD. ')) return null;
|
||||
// Get series data to find the unit
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.farm ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
}
|
||||
|
||||
// Find the series that matches this line's name
|
||||
const series = seriesData.find(
|
||||
(s) => s.label === item.name
|
||||
);
|
||||
const color = series?.id
|
||||
? getLineColor(series.id, index, analysisMode)
|
||||
: '#9ca3af';
|
||||
const unit = series?.unit;
|
||||
|
||||
return (
|
||||
<li
|
||||
key={`${item.name}-${index}`}
|
||||
className='flex w-full justify-between items-center flex-row gap-y-1.5 gap-x-3 p-0'
|
||||
>
|
||||
<span className='flex flex-row gap-1.5 items-center'>
|
||||
<div
|
||||
className='h-5 w-5 m-0 rounded'
|
||||
style={{
|
||||
backgroundColor: color,
|
||||
}}
|
||||
></div>
|
||||
<div className='m-0'>
|
||||
{formatNumber(item.value)}
|
||||
{unit}
|
||||
</div>
|
||||
</span>
|
||||
<span className='m-0'>{item.name}</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className='text-white/50 text-xs text-start'>
|
||||
Week {props.label}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
})()}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
}}
|
||||
formatter={(
|
||||
value: number | undefined,
|
||||
name: string | undefined
|
||||
) => {
|
||||
if (
|
||||
value === undefined ||
|
||||
name === undefined ||
|
||||
name.startsWith('STD. ')
|
||||
)
|
||||
return [undefined, undefined];
|
||||
|
||||
// Get series data to find the unit
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.farm ||
|
||||
data.charts.flock ||
|
||||
data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
}
|
||||
|
||||
// Find the series that matches this line's name
|
||||
const series = seriesData.find((s) => s.label === name);
|
||||
const id = series?.id || '';
|
||||
|
||||
return [value, id];
|
||||
}}
|
||||
/>
|
||||
{/* Dynamic Line rendering based on visible series */}
|
||||
{(() => {
|
||||
let seriesData: DashboardChartsSeries[] = [];
|
||||
|
||||
if (
|
||||
analysisMode === 'OVERVIEW' &&
|
||||
isOverviewCharts(data.charts)
|
||||
) {
|
||||
seriesData = data.charts[chartData]?.series || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.farm || data.charts.flock || data.charts.kandang;
|
||||
seriesData = comparisonChart?.series || [];
|
||||
}
|
||||
|
||||
return seriesData
|
||||
.filter((series) => visibleSeries.has(series.id))
|
||||
.map((series, index) => {
|
||||
const isStandard = series.id
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.includes('std');
|
||||
// Use series.id directly as dataKey to match dataset fields
|
||||
const dataKey = series.id.toString();
|
||||
|
||||
return (
|
||||
<Line
|
||||
key={`${series.id}--${index}`}
|
||||
type='monotone'
|
||||
dataKey={dataKey}
|
||||
name={series.label}
|
||||
stroke={getLineColor(series.id, index, analysisMode)}
|
||||
opacity={isStandard ? 0.5 : 1}
|
||||
strokeWidth={2}
|
||||
strokeDasharray={isStandard ? '5 5' : undefined}
|
||||
dot={
|
||||
isStandard
|
||||
? false
|
||||
: {
|
||||
r: 3,
|
||||
fill: '#fff',
|
||||
stroke: getLineColor(
|
||||
series.id,
|
||||
index,
|
||||
analysisMode
|
||||
),
|
||||
strokeWidth: 2,
|
||||
}
|
||||
}
|
||||
activeDot={isStandard ? undefined : { r: 5 }}
|
||||
/>
|
||||
);
|
||||
});
|
||||
})()}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
|
||||
{/* Empty State Overlay */}
|
||||
{(() => {
|
||||
// Get current dataset
|
||||
let dataset: DashboardChartsDataset[] = [];
|
||||
|
||||
if (analysisMode === 'OVERVIEW' && isOverviewCharts(data.charts)) {
|
||||
dataset = data.charts[chartData]?.dataset || [];
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
const comparisonChart =
|
||||
data.charts.farm || data.charts.flock || data.charts.kandang;
|
||||
dataset = comparisonChart?.dataset || [];
|
||||
}
|
||||
|
||||
// Show empty state if dataset is empty
|
||||
if (dataset.length === 0) {
|
||||
return (
|
||||
<div className='absolute inset-x-0 inset-y-15 z-10 flex flex-col items-center justify-center rounded-lg'>
|
||||
{/* Chart icon */}
|
||||
<DataStateSkeleton
|
||||
icon={
|
||||
<Icon
|
||||
icon='heroicons:chart-bar'
|
||||
className='text-white'
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
}
|
||||
title='Data Not Yet Available'
|
||||
description='Please change your filters to get the data.'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})()}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ const CARD_CONFIG = [
|
||||
key: 'Avg. Selling Price',
|
||||
icon: 'heroicons:document-currency-dollar',
|
||||
alertColor: 'success' as const,
|
||||
suffix: ' /Kg',
|
||||
suffix: ' /Kg Telur',
|
||||
prefix: '',
|
||||
},
|
||||
{
|
||||
@@ -48,7 +48,7 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
|
||||
icon: isPositive
|
||||
? 'heroicons:arrow-trending-up'
|
||||
: 'heroicons:arrow-trending-down',
|
||||
color: isPositive ? 'text-success' : 'text-error',
|
||||
color: isPositive ? 'text-[#008000]' : 'text-[#FF3A3A]',
|
||||
value: Math.abs(percent),
|
||||
};
|
||||
};
|
||||
@@ -60,14 +60,16 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
|
||||
{prefix}
|
||||
{formatNumber(value)}
|
||||
{suffix && (
|
||||
<span className='text-sm font-normal text-neutral-500'>{suffix}</span>
|
||||
<span className='text-sm font-normal text-base-content/50'>
|
||||
{suffix}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='grid sm:grid-cols-2 xl:grid-cols-4 gap-6'>
|
||||
<div className='grid sm:grid-cols-2 xl:grid-cols-4 gap-3'>
|
||||
{CARD_CONFIG.map((config) => {
|
||||
// Find matching data from API
|
||||
const cardData = data.find((item) => item.label === config.key);
|
||||
@@ -78,35 +80,41 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
|
||||
<Card
|
||||
key={config.key}
|
||||
className={{
|
||||
wrapper: 'w-full rounded-lg',
|
||||
wrapper: 'w-full rounded-xl border border-base-content/10',
|
||||
body: 'p-0',
|
||||
wrapperContent:
|
||||
'h-full flex flex-col items-between justify-between',
|
||||
footer: 'mt-0!',
|
||||
}}
|
||||
variant='bordered'
|
||||
footer={
|
||||
<div className='flex flex-row justify-between px-4 pb-4'>
|
||||
<div className='text-neutral-400 font-semibold text-sm'>
|
||||
<div className='flex flex-row justify-between px-4 pb-4 max-h-12'>
|
||||
<div className='text-base-content/50 font-semibold text-xs'>
|
||||
From last month
|
||||
</div>
|
||||
<div className='text-neutral-400 font-semibold text-sm'>
|
||||
<div className='text-base-content/50 font-semibold text-xs'>
|
||||
Filter Required
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className='flex flex-row items-center gap-4 px-4 pt-4'>
|
||||
<Alert variant='soft' className='rounded-lg p-3 bg-neutral-100'>
|
||||
<div className='flex flex-row items-center gap-3 px-4 py-4'>
|
||||
<Alert
|
||||
variant='soft'
|
||||
className={`rounded-lg p-0 w-12.5 h-12.5 bg-[${config.alertColor}]/12 flex items-center justify-center`}
|
||||
>
|
||||
<Icon
|
||||
icon={config.icon}
|
||||
width={32}
|
||||
height={32}
|
||||
className='text-neutral-400'
|
||||
width={24}
|
||||
height={24}
|
||||
className='text-base-content/50'
|
||||
/>
|
||||
</Alert>
|
||||
<div>
|
||||
<h3 className='text-neutral-400 font-semibold text-sm'>
|
||||
<h3 className='text-base-content/50 font-semibold text-sm'>
|
||||
{config.key}
|
||||
</h3>
|
||||
<p className='text-2xl font-semibold text-neutral-400'>
|
||||
<p className='text-xl font-semibold text-base-content/50'>
|
||||
********
|
||||
</p>
|
||||
</div>
|
||||
@@ -121,17 +129,20 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
|
||||
<Card
|
||||
key={config.key}
|
||||
className={{
|
||||
wrapper: 'w-full rounded-lg',
|
||||
wrapper: 'w-full rounded-xl border border-base-content/10',
|
||||
body: 'p-0',
|
||||
wrapperContent:
|
||||
'h-full flex flex-col items-between justify-between',
|
||||
footer: 'mt-0!',
|
||||
}}
|
||||
variant='bordered'
|
||||
footer={
|
||||
<div className='flex flex-row justify-between px-4 pb-4'>
|
||||
<div className='text-neutral-500 font-semibold text-sm'>
|
||||
<div className='text-base-content/50 font-semibold text-xs'>
|
||||
From last month
|
||||
</div>
|
||||
<div
|
||||
className={`${trend.color} font-semibold flex flex-row items-center gap-1 text-sm`}
|
||||
className={`${trend.color} font-semibold flex flex-row items-center gap-2 text-xs`}
|
||||
>
|
||||
<Icon icon={trend.icon} width={16} height={16} />
|
||||
{trend.value}%
|
||||
@@ -143,15 +154,15 @@ const DashboardStats = ({ data }: DashboardStatsProps) => {
|
||||
<Alert
|
||||
variant='soft'
|
||||
color={config.alertColor}
|
||||
className='rounded-lg p-3'
|
||||
className={`rounded-lg p-3 bg-[${config.alertColor}]/12 flex items-center justify-center`}
|
||||
>
|
||||
<Icon icon={config.icon} width={32} height={32} />
|
||||
<Icon icon={config.icon} width={24} height={24} />
|
||||
</Alert>
|
||||
<div>
|
||||
<h3 className='text-neutral-500 font-semibold text-sm'>
|
||||
<div className='space-y-1'>
|
||||
<h3 className='text-base-content/50 font-semibold text-sm'>
|
||||
{cardData.label}
|
||||
</h3>
|
||||
<p className='text-2xl font-semibold'>
|
||||
<p className='text-xl font-semibold'>
|
||||
{formatValue(cardData.value, config.prefix, config.suffix)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import Card from '@/components/Card';
|
||||
import {
|
||||
Dashboard,
|
||||
DashboardOverviewCharts,
|
||||
DashboardComparisonCharts,
|
||||
DashboardChartsSeries,
|
||||
DashboardChartsDataset,
|
||||
} from '@/types/api/dashboard/dashboard';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { forwardRef, useImperativeHandle, useRef } from 'react';
|
||||
import {
|
||||
CartesianGrid,
|
||||
Line,
|
||||
LineChart,
|
||||
ResponsiveContainer,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts';
|
||||
|
||||
type DashboardExportChartsProps = {
|
||||
data: Dashboard;
|
||||
analysisMode: string;
|
||||
};
|
||||
|
||||
export type DashboardExportChartsRef = {
|
||||
getChartRefs: () => {
|
||||
key: string;
|
||||
ref: HTMLDivElement | null;
|
||||
label: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
// Type guard to check if charts is DashboardOverviewCharts
|
||||
function isOverviewCharts(
|
||||
charts: DashboardOverviewCharts | DashboardComparisonCharts | undefined
|
||||
): charts is DashboardOverviewCharts {
|
||||
if (!charts) return false;
|
||||
return (
|
||||
'deplesi' in charts ||
|
||||
'body_weight' in charts ||
|
||||
'fcr' in charts ||
|
||||
'performance' in charts ||
|
||||
'quality_control' in charts
|
||||
);
|
||||
}
|
||||
|
||||
// Type guard to check if charts is DashboardComparisonCharts
|
||||
function isComparisonCharts(
|
||||
charts: DashboardOverviewCharts | DashboardComparisonCharts | undefined
|
||||
): charts is DashboardComparisonCharts {
|
||||
if (!charts) return false;
|
||||
return 'farm' in charts || 'flock' in charts || 'kandang' in charts;
|
||||
}
|
||||
|
||||
const lineColors: Record<string, string> = {
|
||||
body_weight: '#10B981',
|
||||
std_body_weight: '#10B981',
|
||||
act_laying: '#1062B9',
|
||||
std_laying: '#1062B9',
|
||||
act_egg_weight: '#10B981',
|
||||
std_egg_weight: '#10B981',
|
||||
act_feed_intake: '#F52419',
|
||||
std_feed_intake: '#F52419',
|
||||
act_uniformity: '#F59E0B',
|
||||
std_uniformity: '#F59E0B',
|
||||
act_fcr: '#10B981',
|
||||
std_fcr: '#10B981',
|
||||
act_fcr_cum: '#F52419',
|
||||
std_fcr_cum: '#10B981',
|
||||
normal: '#10B981',
|
||||
abnormal: '#F52419',
|
||||
act_deplesi: '#10B981',
|
||||
std_deplesi: '#10B981',
|
||||
};
|
||||
|
||||
const defaultLineColors: string[] = [
|
||||
'#10B981',
|
||||
'#1062B9',
|
||||
'#F52419',
|
||||
'#F59E0B',
|
||||
'#7F56D9',
|
||||
];
|
||||
|
||||
// Helper function to get line color
|
||||
const getLineColor = (seriesId: string | number, index: number): string => {
|
||||
const predefinedColor = lineColors[seriesId];
|
||||
if (predefinedColor) {
|
||||
return predefinedColor;
|
||||
}
|
||||
return defaultLineColors[index % defaultLineColors.length];
|
||||
};
|
||||
|
||||
// Mapping for chart type labels
|
||||
const chartTypeLabels: Record<keyof DashboardOverviewCharts, string> = {
|
||||
body_weight: 'Body Weight',
|
||||
performance: 'Performance',
|
||||
fcr: 'FCR',
|
||||
quality_control: 'Quality Control',
|
||||
deplesi: 'Deplesi',
|
||||
};
|
||||
|
||||
const DashboardExportCharts = forwardRef<
|
||||
DashboardExportChartsRef,
|
||||
DashboardExportChartsProps
|
||||
>(({ data, analysisMode }, ref) => {
|
||||
// Create refs for charts - use string keys for flexibility
|
||||
const chartRefs = useRef<{
|
||||
[key: string]: HTMLDivElement | null;
|
||||
}>({});
|
||||
|
||||
// Determine chart keys and labels based on analysis mode
|
||||
const getChartConfig = () => {
|
||||
if (analysisMode === 'OVERVIEW' && isOverviewCharts(data.charts)) {
|
||||
const overviewKeys: (keyof DashboardOverviewCharts)[] = [
|
||||
'body_weight',
|
||||
'performance',
|
||||
'fcr',
|
||||
'quality_control',
|
||||
'deplesi',
|
||||
];
|
||||
return overviewKeys.map((key) => ({
|
||||
key,
|
||||
label: chartTypeLabels[key],
|
||||
chartData: (data.charts as DashboardOverviewCharts)[key],
|
||||
}));
|
||||
} else if (
|
||||
analysisMode === 'COMPARISON' &&
|
||||
isComparisonCharts(data.charts)
|
||||
) {
|
||||
// For comparison mode, find which comparison type has data
|
||||
const comparisonKey = data.charts.farm
|
||||
? 'farm'
|
||||
: data.charts.flock
|
||||
? 'flock'
|
||||
: 'kandang';
|
||||
|
||||
const comparisonLabels: Record<string, string> = {
|
||||
farm: 'Farm Comparison',
|
||||
flock: 'Flock Comparison',
|
||||
kandang: 'Kandang Comparison',
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
key: comparisonKey,
|
||||
label: comparisonLabels[comparisonKey],
|
||||
chartData: data.charts[comparisonKey],
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const chartConfig = getChartConfig();
|
||||
|
||||
// Expose method to get all chart refs
|
||||
useImperativeHandle(ref, () => ({
|
||||
getChartRefs: () => {
|
||||
return chartConfig
|
||||
.map(({ key, label }) => ({
|
||||
key,
|
||||
ref: chartRefs.current[key] || null,
|
||||
label,
|
||||
}))
|
||||
.filter((item) => item.ref !== null);
|
||||
},
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className='space-y-6'>
|
||||
{chartConfig.map(({ key, label, chartData }) => {
|
||||
if (
|
||||
!chartData ||
|
||||
!chartData.dataset ||
|
||||
chartData.dataset.length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const seriesData: DashboardChartsSeries[] = chartData.series || [];
|
||||
const dataset: DashboardChartsDataset[] = chartData.dataset || [];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
ref={(el: HTMLDivElement | null) => {
|
||||
chartRefs.current[key] = el;
|
||||
}}
|
||||
>
|
||||
<Card
|
||||
className={{
|
||||
wrapper: 'w-full rounded-lg p-0',
|
||||
body: 'p-4',
|
||||
}}
|
||||
variant='bordered'
|
||||
>
|
||||
<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6'>
|
||||
<div className='text-lg font-semibold'>
|
||||
{label}{' '}
|
||||
<Icon
|
||||
icon='heroicons:information-circle'
|
||||
width={20}
|
||||
height={20}
|
||||
className='inline text-neutral-500'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Legend */}
|
||||
<div className='flex flex-wrap gap-3 mb-6'>
|
||||
{seriesData.map((series, index) => {
|
||||
const isStandard = series.id
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.includes('std');
|
||||
|
||||
return (
|
||||
<div
|
||||
key={series.id}
|
||||
className='flex items-center gap-2 px-3 py-2 rounded-lg border border-neutral-400 bg-neutral-50'
|
||||
>
|
||||
<div
|
||||
className={`w-6 h-0.5 ${
|
||||
isStandard ? 'border-t-2 border-dashed' : ''
|
||||
}`}
|
||||
style={{
|
||||
backgroundColor: isStandard
|
||||
? 'transparent'
|
||||
: getLineColor(series.id, index),
|
||||
borderColor: isStandard
|
||||
? getLineColor(series.id, index)
|
||||
: 'transparent',
|
||||
}}
|
||||
></div>
|
||||
<span className='text-sm text-neutral-900 font-medium'>
|
||||
{series.label}
|
||||
</span>
|
||||
<Icon
|
||||
icon='heroicons:information-circle'
|
||||
width={16}
|
||||
height={16}
|
||||
className='text-neutral-400'
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Chart */}
|
||||
<ResponsiveContainer width='100%' height={350}>
|
||||
<LineChart
|
||||
data={dataset}
|
||||
margin={{
|
||||
top: 5,
|
||||
right: 10,
|
||||
left: 0,
|
||||
bottom: 5,
|
||||
}}
|
||||
>
|
||||
<CartesianGrid strokeDasharray='3 3' stroke='#e5e7eb' />
|
||||
<XAxis
|
||||
dataKey='week'
|
||||
tick={{ fontSize: 11, fill: '#9ca3af' }}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: '#e5e7eb' }}
|
||||
label={{
|
||||
value: 'Weeks',
|
||||
position: 'insideBottom',
|
||||
offset: -5,
|
||||
style: { fontSize: 12, fill: '#9ca3af' },
|
||||
}}
|
||||
/>
|
||||
<YAxis
|
||||
tick={{ fontSize: 11, fill: '#9ca3af' }}
|
||||
tickLine={false}
|
||||
axisLine={{ stroke: '#e5e7eb' }}
|
||||
domain={(() => {
|
||||
const allValues: number[] = [];
|
||||
dataset.forEach((item: DashboardChartsDataset) => {
|
||||
seriesData.forEach((series) => {
|
||||
const value = item[series.id];
|
||||
if (typeof value === 'number') {
|
||||
allValues.push(value);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (allValues.length === 0) return [0, 100];
|
||||
|
||||
const minValue = Math.min(...allValues);
|
||||
const maxValue = Math.max(...allValues);
|
||||
const padding = (maxValue - minValue) * 0.1;
|
||||
const domainMin = Math.floor(
|
||||
Math.max(0, minValue - padding)
|
||||
);
|
||||
const domainMax = Math.ceil(maxValue + padding);
|
||||
|
||||
return [domainMin, domainMax];
|
||||
})()}
|
||||
/>
|
||||
{seriesData.map((series, index) => {
|
||||
const isStandard = series.id
|
||||
.toString()
|
||||
.toLowerCase()
|
||||
.includes('std');
|
||||
const dataKey = series.id.toString();
|
||||
|
||||
return (
|
||||
<Line
|
||||
key={series.id}
|
||||
type='monotone'
|
||||
dataKey={dataKey}
|
||||
name={series.label}
|
||||
stroke={getLineColor(series.id, index)}
|
||||
opacity={isStandard ? 0.5 : 1}
|
||||
strokeWidth={2}
|
||||
strokeDasharray={isStandard ? '5 5' : undefined}
|
||||
dot={
|
||||
isStandard
|
||||
? false
|
||||
: {
|
||||
r: 3,
|
||||
fill: '#fff',
|
||||
stroke: getLineColor(series.id, index),
|
||||
strokeWidth: 2,
|
||||
}
|
||||
}
|
||||
activeDot={isStandard ? undefined : { r: 5 }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
DashboardExportCharts.displayName = 'DashboardExportCharts';
|
||||
|
||||
export default DashboardExportCharts;
|
||||
@@ -0,0 +1,197 @@
|
||||
import Alert from '@/components/Alert';
|
||||
import Card from '@/components/Card';
|
||||
import { formatNumber } from '@/lib/helper';
|
||||
import { DashboardStatisticsData } from '@/types/api/dashboard/dashboard';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { forwardRef, useImperativeHandle, useRef } from 'react';
|
||||
interface DashboardStatsProps {
|
||||
data: DashboardStatisticsData[];
|
||||
}
|
||||
export type DashboardExportStatsRef = {
|
||||
getStatsRefs: () => {
|
||||
key: string;
|
||||
ref: HTMLDivElement | null;
|
||||
label: string;
|
||||
}[];
|
||||
getContainerRef: () => HTMLDivElement | null;
|
||||
};
|
||||
|
||||
// Konfigurasi untuk setiap kartu
|
||||
const CARD_CONFIG = [
|
||||
{
|
||||
key: 'HPP Global',
|
||||
icon: 'heroicons:banknotes',
|
||||
alertColor: 'warning' as const,
|
||||
suffix: ' /Kg',
|
||||
prefix: 'RP ',
|
||||
},
|
||||
{
|
||||
key: 'Avg. Selling Price',
|
||||
icon: 'heroicons:document-currency-dollar',
|
||||
alertColor: 'success' as const,
|
||||
suffix: ' /Kg',
|
||||
prefix: '',
|
||||
},
|
||||
{
|
||||
key: 'FCR',
|
||||
icon: 'heroicons:clipboard-document-list',
|
||||
alertColor: 'info' as const,
|
||||
suffix: '',
|
||||
prefix: '',
|
||||
},
|
||||
{
|
||||
key: 'Mortality',
|
||||
icon: 'heroicons:exclamation-triangle',
|
||||
alertColor: 'error' as const,
|
||||
suffix: ' %',
|
||||
prefix: '',
|
||||
},
|
||||
];
|
||||
|
||||
const DashboardExportStats = forwardRef<
|
||||
DashboardExportStatsRef,
|
||||
DashboardStatsProps
|
||||
>(({ data }, ref) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
// Helper to get trend icon and color
|
||||
const getTrendDisplay = (percent: number) => {
|
||||
const isPositive = percent >= 0;
|
||||
return {
|
||||
icon: isPositive
|
||||
? 'heroicons:arrow-trending-up'
|
||||
: 'heroicons:arrow-trending-down',
|
||||
color: isPositive ? 'text-[#008000]' : 'text-[#FF3A3A]',
|
||||
value: Math.abs(percent),
|
||||
};
|
||||
};
|
||||
|
||||
// Helper to format value
|
||||
const formatValue = (value: number, prefix: string, suffix: string) => {
|
||||
return (
|
||||
<>
|
||||
{prefix}
|
||||
{formatNumber(value)}
|
||||
{suffix && (
|
||||
<span className='text-sm font-normal text-base-content/50'>
|
||||
{suffix}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Expose container ref through imperative handle
|
||||
useImperativeHandle(ref, () => ({
|
||||
getStatsRefs: () => [],
|
||||
getContainerRef: () => containerRef.current,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className='grid grid-cols-4 gap-3'>
|
||||
{CARD_CONFIG.map((config) => {
|
||||
// Find matching data from API
|
||||
const cardData = data.find((item) => item.label === config.key);
|
||||
|
||||
if (!cardData) {
|
||||
// Show placeholder card for missing data (FCR & Mortality)
|
||||
return (
|
||||
<Card
|
||||
key={config.key}
|
||||
className={{
|
||||
wrapper: 'w-full rounded-lg',
|
||||
body: 'p-0',
|
||||
wrapperContent:
|
||||
'h-full flex flex-col items-between justify-between',
|
||||
footer: 'mt-0!',
|
||||
}}
|
||||
variant='bordered'
|
||||
footer={
|
||||
<div className='flex flex-row justify-between px-4 pb-4 max-h-12'>
|
||||
<div className='text-base-content/50 font-semibold text-xs'>
|
||||
From last month
|
||||
</div>
|
||||
<div className='text-base-content/50 font-semibold text-xs'>
|
||||
Filter Required
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className='flex flex-row items-center gap-3 px-4 pt-4'>
|
||||
<Alert
|
||||
variant='soft'
|
||||
className={`rounded-lg p-0 w-12.5 h-12.5 bg-[${config.alertColor}]/12 flex items-center justify-center`}
|
||||
>
|
||||
<Icon
|
||||
icon={config.icon}
|
||||
width={24}
|
||||
height={24}
|
||||
className='text-base-content/50'
|
||||
/>
|
||||
</Alert>
|
||||
<div>
|
||||
<h3 className='text-base-content/50 font-semibold text-sm'>
|
||||
{config.key}
|
||||
</h3>
|
||||
<p className='text-xl font-semibold text-base-content/50'>
|
||||
********
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const trend = getTrendDisplay(cardData.percent_last_month);
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={config.key}
|
||||
className={{
|
||||
wrapper: 'w-full rounded-lg border border-base-content/10',
|
||||
body: 'p-0',
|
||||
wrapperContent:
|
||||
'h-full flex flex-col items-between justify-between',
|
||||
footer: 'mt-0!',
|
||||
}}
|
||||
variant='bordered'
|
||||
footer={
|
||||
<div className='flex flex-row justify-between px-4 pb-4 max-h-12'>
|
||||
<div className='text-base-content/50 font-semibold text-xs'>
|
||||
From last month
|
||||
</div>
|
||||
<div
|
||||
className={`${trend.color} font-semibold flex flex-row items-center gap-2 text-xs`}
|
||||
>
|
||||
<Icon icon={trend.icon} width={16} height={16} />
|
||||
{trend.value}%
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className='flex flex-row items-center gap-4 px-4 pt-4'>
|
||||
<Alert
|
||||
variant='soft'
|
||||
color={config.alertColor}
|
||||
className={`rounded-lg p-0 w-12.5 h-12.5 bg-[${config.alertColor}]/12 flex items-center justify-center`}
|
||||
>
|
||||
<Icon icon={config.icon} width={24} height={24} />
|
||||
</Alert>
|
||||
<div>
|
||||
<h3 className='text-base-content/50 font-semibold text-sm'>
|
||||
{cardData.label}
|
||||
</h3>
|
||||
<p className='text-xl font-semibold'>
|
||||
{formatValue(cardData.value, config.prefix, config.suffix)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
DashboardExportStats.displayName = 'DashboardExportStats';
|
||||
|
||||
export default DashboardExportStats;
|
||||
@@ -0,0 +1,266 @@
|
||||
import jsPDF from 'jspdf';
|
||||
import { toPng } from 'html-to-image';
|
||||
import toast from 'react-hot-toast';
|
||||
import { formatDate } from '@/lib/helper';
|
||||
import { DashboardFilterType } from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
|
||||
import { DashboardExportChartsRef } from '@/components/pages/dashboard/export/DashboardExportCharts';
|
||||
import { DashboardExportStatsRef } from '@/components/pages/dashboard/export/DashboardExportStats';
|
||||
|
||||
interface DashboardPDFExportParams {
|
||||
filterValues: DashboardFilterType;
|
||||
allStatsRef: React.RefObject<DashboardExportStatsRef | null>;
|
||||
allChartsRef: React.RefObject<DashboardExportChartsRef | null>;
|
||||
setExporting: (value: boolean) => void;
|
||||
}
|
||||
|
||||
export const generateDashboardPDF = async ({
|
||||
filterValues,
|
||||
allStatsRef,
|
||||
allChartsRef,
|
||||
setExporting,
|
||||
}: DashboardPDFExportParams): Promise<void> => {
|
||||
try {
|
||||
setExporting(true);
|
||||
toast.loading('Generating PDF...', { id: 'export-pdf' });
|
||||
|
||||
// Wait for DOM to update
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
const pdf = new jsPDF('p', 'mm', 'a4');
|
||||
const pageWidth = pdf.internal.pageSize.getWidth();
|
||||
const pageHeight = pdf.internal.pageSize.getHeight();
|
||||
const margin = 10;
|
||||
let yPosition = margin;
|
||||
|
||||
// Add title
|
||||
pdf.setFontSize(16);
|
||||
pdf.setFont('helvetica', 'bold');
|
||||
pdf.text('Dashboard Produksi', margin, yPosition);
|
||||
yPosition += 10;
|
||||
|
||||
// Add filter information (horizontal layout)
|
||||
pdf.setFontSize(6);
|
||||
pdf.setFont('helvetica', 'normal');
|
||||
|
||||
const filterItems: string[] = [];
|
||||
|
||||
// Period
|
||||
if (filterValues.startDate || filterValues.endDate) {
|
||||
const periodText = `Periode: ${
|
||||
filterValues.startDate
|
||||
? formatDate(filterValues.startDate, 'DD MMM YYYY')
|
||||
: '-'
|
||||
} s.d ${
|
||||
filterValues.endDate
|
||||
? formatDate(filterValues.endDate, 'DD MMM YYYY')
|
||||
: '-'
|
||||
}`;
|
||||
filterItems.push(periodText);
|
||||
}
|
||||
|
||||
// Analysis Mode
|
||||
const analysisModeText = `Analysis Mode: ${
|
||||
filterValues.analysisMode === 'OVERVIEW'
|
||||
? 'Performance Overview'
|
||||
: 'Performance Comparison'
|
||||
}`;
|
||||
filterItems.push(analysisModeText);
|
||||
|
||||
// Comparison Type (only for COMPARISON mode)
|
||||
if (
|
||||
filterValues.analysisMode === 'COMPARISON' &&
|
||||
filterValues.comparisonType
|
||||
) {
|
||||
const comparisonTypeLabel =
|
||||
filterValues.comparisonType === 'FARM'
|
||||
? 'Farm'
|
||||
: filterValues.comparisonType === 'FLOCK'
|
||||
? 'Flock'
|
||||
: filterValues.comparisonType === 'KANDANG'
|
||||
? 'Kandang'
|
||||
: filterValues.comparisonType;
|
||||
filterItems.push(`Compared By: ${comparisonTypeLabel}`);
|
||||
}
|
||||
|
||||
// Farm
|
||||
if (filterValues.location) {
|
||||
const locationText = Array.isArray(filterValues.location)
|
||||
? filterValues.location.map((loc) => loc.label).join(', ')
|
||||
: filterValues.location.label;
|
||||
filterItems.push(`Farm: ${locationText || '-'}`);
|
||||
}
|
||||
|
||||
// Flock
|
||||
if (
|
||||
filterValues.flock &&
|
||||
(Array.isArray(filterValues.flock)
|
||||
? filterValues.flock.length > 0
|
||||
: filterValues.flock)
|
||||
) {
|
||||
const flockText = Array.isArray(filterValues.flock)
|
||||
? filterValues.flock.map((f) => f.label).join(', ')
|
||||
: filterValues.flock.label;
|
||||
filterItems.push(`Flock: ${flockText || '-'}`);
|
||||
}
|
||||
|
||||
// Kandang
|
||||
if (
|
||||
filterValues.kandang &&
|
||||
(Array.isArray(filterValues.kandang)
|
||||
? filterValues.kandang.length > 0
|
||||
: filterValues.kandang)
|
||||
) {
|
||||
const kandangText = Array.isArray(filterValues.kandang)
|
||||
? filterValues.kandang.map((k) => k.label).join(', ')
|
||||
: filterValues.kandang.label;
|
||||
filterItems.push(`Kandang: ${kandangText || '-'}`);
|
||||
}
|
||||
|
||||
// Generated timestamp
|
||||
filterItems.push(`Dicetak: ${formatDate(new Date(), 'DD MMM YYYY HH:mm')}`);
|
||||
|
||||
// Render filter items horizontally with word wrap and gray background
|
||||
const maxWidth = pageWidth - 2 * margin;
|
||||
let currentLine = '';
|
||||
const lines: string[] = [];
|
||||
|
||||
// First pass: calculate all lines
|
||||
filterItems.forEach((item, index) => {
|
||||
const separator = index > 0 ? ' | ' : '';
|
||||
const testLine = currentLine + separator + item;
|
||||
const testWidth = pdf.getTextWidth(testLine);
|
||||
|
||||
if (testWidth > maxWidth && currentLine !== '') {
|
||||
lines.push(currentLine);
|
||||
currentLine = item;
|
||||
} else {
|
||||
currentLine = testLine;
|
||||
}
|
||||
});
|
||||
|
||||
// Add last line
|
||||
if (currentLine) {
|
||||
lines.push(currentLine);
|
||||
}
|
||||
|
||||
// Calculate background dimensions
|
||||
const lineHeight = 3;
|
||||
const padding = 1;
|
||||
const backgroundHeight = lines.length * lineHeight + padding * 2;
|
||||
|
||||
// Draw gray background
|
||||
pdf.setFillColor(240, 240, 240); // Light gray (RGB: 240, 240, 240)
|
||||
pdf.rect(
|
||||
margin - padding,
|
||||
yPosition - padding - 2,
|
||||
pageWidth - 2 * margin + padding * 2,
|
||||
backgroundHeight,
|
||||
'F'
|
||||
);
|
||||
|
||||
// Render text on top of background
|
||||
lines.forEach((line, index) => {
|
||||
pdf.text(line, margin, yPosition);
|
||||
if (index < lines.length - 1) {
|
||||
yPosition += lineHeight;
|
||||
}
|
||||
});
|
||||
|
||||
yPosition += 10;
|
||||
|
||||
// Capture and add stats if available
|
||||
if (allStatsRef.current) {
|
||||
const statsContainer = allStatsRef.current.getContainerRef();
|
||||
if (statsContainer) {
|
||||
const statsImage = await toPng(statsContainer, {
|
||||
quality: 1,
|
||||
pixelRatio: 2,
|
||||
});
|
||||
const statsImgProps = pdf.getImageProperties(statsImage);
|
||||
const statsWidth = pageWidth - 2 * margin;
|
||||
const statsHeight =
|
||||
(statsImgProps.height * statsWidth) / statsImgProps.width;
|
||||
|
||||
// Check if we need a new page
|
||||
if (yPosition + statsHeight > pageHeight - margin) {
|
||||
pdf.addPage();
|
||||
yPosition = margin;
|
||||
}
|
||||
|
||||
pdf.addImage(
|
||||
statsImage,
|
||||
'PNG',
|
||||
margin,
|
||||
yPosition,
|
||||
statsWidth,
|
||||
statsHeight
|
||||
);
|
||||
yPosition += statsHeight + 10;
|
||||
}
|
||||
}
|
||||
|
||||
if (allChartsRef.current) {
|
||||
// Get all individual chart refs
|
||||
const chartRefs = allChartsRef.current.getChartRefs();
|
||||
|
||||
// Capture each chart separately and add to PDF
|
||||
for (let i = 0; i < chartRefs.length; i++) {
|
||||
const { ref: chartElement, label } = chartRefs[i];
|
||||
|
||||
if (chartElement) {
|
||||
// Add chart title
|
||||
pdf.setFontSize(12);
|
||||
pdf.setFont('helvetica', 'bold');
|
||||
|
||||
const chartImage = await toPng(chartElement, {
|
||||
quality: 1,
|
||||
pixelRatio: 2,
|
||||
});
|
||||
const chartImgProps = pdf.getImageProperties(chartImage);
|
||||
const chartWidth = pageWidth - 2 * margin;
|
||||
const chartHeight =
|
||||
(chartImgProps.height * chartWidth) / chartImgProps.width;
|
||||
|
||||
// Calculate total height needed (title + spacing + chart)
|
||||
const titleHeight = 10;
|
||||
const totalHeight = titleHeight + chartHeight;
|
||||
|
||||
// Check if chart fits on current page
|
||||
if (yPosition + totalHeight > pageHeight - margin) {
|
||||
pdf.addPage();
|
||||
yPosition = margin;
|
||||
}
|
||||
|
||||
// Add title
|
||||
pdf.text(label, margin, yPosition);
|
||||
yPosition += titleHeight;
|
||||
|
||||
// Add chart image
|
||||
pdf.addImage(
|
||||
chartImage,
|
||||
'PNG',
|
||||
margin,
|
||||
yPosition,
|
||||
chartWidth,
|
||||
chartHeight
|
||||
);
|
||||
|
||||
// Update yPosition for next chart (add spacing between charts)
|
||||
yPosition += chartHeight + 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save the PDF
|
||||
const fileName = `dashboard-production-${new Date().toISOString().split('T')[0]}.pdf`;
|
||||
pdf.save(fileName);
|
||||
|
||||
toast.success('PDF exported successfully!', { id: 'export-pdf' });
|
||||
} catch (error) {
|
||||
toast.error('Failed to export PDF. Please try again.', {
|
||||
id: 'export-pdf',
|
||||
});
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
@@ -7,7 +7,7 @@ export type DashboardFilterType = {
|
||||
analysisMode: string;
|
||||
comparisonType: string | undefined;
|
||||
location: OptionType | OptionType[];
|
||||
lokasiIds: number[] | undefined;
|
||||
locationIds: number[] | undefined;
|
||||
flock: OptionType | OptionType[] | undefined;
|
||||
flockIds: number[] | undefined;
|
||||
kandang: OptionType | OptionType[] | undefined;
|
||||
@@ -25,7 +25,7 @@ export const DashboardFilterOverviewSchema: yup.ObjectSchema<DashboardFilterType
|
||||
then: (schema) => schema.required('Compared by is required'),
|
||||
otherwise: (schema) => schema.optional(),
|
||||
}),
|
||||
lokasiIds: yup.array().optional(),
|
||||
locationIds: yup.array().optional(),
|
||||
flockIds: yup.array().optional(),
|
||||
kandangIds: yup.array().optional(),
|
||||
location: yup
|
||||
@@ -68,7 +68,7 @@ export const DashboardFilterComparisonSchema: yup.ObjectSchema<DashboardFilterTy
|
||||
then: (schema) => schema.required('Compared by is required'),
|
||||
otherwise: (schema) => schema.optional(),
|
||||
}),
|
||||
lokasiIds: yup.array().optional(),
|
||||
locationIds: yup.array().optional(),
|
||||
flockIds: yup.array().optional(),
|
||||
kandangIds: yup.array().optional(),
|
||||
location: yup
|
||||
|
||||
@@ -1,96 +1,89 @@
|
||||
import { Icon } from '@iconify/react';
|
||||
import { DashboardMeta } from '@/types/api/dashboard/dashboard';
|
||||
import DataStateSkeleton from '@/components/helper/skeleton/DataStateSkeleton';
|
||||
|
||||
const DashboardLineChartSkeleton = ({ meta }: { meta?: DashboardMeta }) => {
|
||||
return (
|
||||
<div className='w-full bg-white rounded-lg shadow-sm border border-gray-200 p-6 relative'>
|
||||
<div className='w-full bg-white rounded-xl border border-base-content/10 p-4 relative'>
|
||||
{/* Header with title skeleton */}
|
||||
<div className='text-lg font-semibold'>
|
||||
<div className='text-base font-semibold'>
|
||||
Performance{' '}
|
||||
<Icon
|
||||
icon='heroicons:information-circle'
|
||||
width={20}
|
||||
height={20}
|
||||
className='inline text-neutral-500'
|
||||
className='inline text-base-content/50'
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Chart area with axes skeleton */}
|
||||
<div className='relative mt-6'>
|
||||
{/* Main chart container */}
|
||||
<div className='flex gap-4'>
|
||||
{/* Y-axis skeleton (left side) */}
|
||||
<div className='flex flex-col justify-between py-4 space-y-4'>
|
||||
{[1, 2, 3, 4, 5, 6].map((item) => (
|
||||
<div
|
||||
key={item}
|
||||
className='h-4 w-12 bg-gray-100 rounded animate-pulse'
|
||||
></div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Chart content area */}
|
||||
<div className='flex-1 relative'>
|
||||
{/* Empty state centered in chart area */}
|
||||
<div className='absolute inset-0 flex flex-col items-center justify-center pb-12'>
|
||||
{!meta?.filters && (
|
||||
<>
|
||||
{/* Filter icon */}
|
||||
<div className='w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center mb-4'>
|
||||
<div className='relative mt-6 '>
|
||||
{/* Chart content area */}
|
||||
<div className='flex-1 relative'>
|
||||
{/* Empty state centered in chart area */}
|
||||
<div className='absolute inset-0 flex flex-col items-center justify-center pb-10'>
|
||||
{!meta?.filters && (
|
||||
<>
|
||||
{/* Filter icon */}
|
||||
<DataStateSkeleton
|
||||
icon={
|
||||
<Icon
|
||||
icon='heroicons:funnel'
|
||||
className='text-white'
|
||||
width={24}
|
||||
height={24}
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Empty state text */}
|
||||
<h3 className='text-gray-900 font-semibold text-base mb-2'>
|
||||
No Filters Selected
|
||||
</h3>
|
||||
<p className='text-gray-500 text-sm text-center max-w-xs'>
|
||||
Please choose filters to narrow down your results and make
|
||||
your search easier.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{meta?.filters && (
|
||||
<>
|
||||
{/* Filter icon */}
|
||||
<div className='w-12 h-12 bg-blue-500 rounded-xl flex items-center justify-center mb-4'>
|
||||
}
|
||||
title='No Filters Selected'
|
||||
description='Please choose filters to narrow down your results and make your search easier.'
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{meta?.filters && (
|
||||
<>
|
||||
{/* Filter icon */}
|
||||
<DataStateSkeleton
|
||||
icon={
|
||||
<Icon
|
||||
icon='heroicons:chart-bar'
|
||||
className='text-white'
|
||||
width={24}
|
||||
height={24}
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
title='Data Not Yet Available'
|
||||
description='Please change your filters to get the data.'
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Empty state text */}
|
||||
<h3 className='text-gray-900 font-semibold text-base mb-2'>
|
||||
Data Not Yet Available
|
||||
</h3>
|
||||
<p className='text-gray-500 text-sm text-center max-w-xs'>
|
||||
Please change your filters to get the data.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<div className='flex flex-row w-full items-center gap-4'>
|
||||
<div className='flex-1 h-full min-w-4'>
|
||||
<div className='h-28.5 w-4 bg-base-content/4 rounded'></div>
|
||||
</div>
|
||||
|
||||
{/* Placeholder for chart height */}
|
||||
<div className='h-64'></div>
|
||||
|
||||
{/* X-axis skeleton (bottom) */}
|
||||
<div className='flex justify-between pt-4 border-t border-gray-100'>
|
||||
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => (
|
||||
<div
|
||||
key={item}
|
||||
className='h-4 w-8 bg-gray-100 rounded animate-pulse'
|
||||
></div>
|
||||
<div className='w-full grid grid-cols-1 gap-y-13.25 mb-2'>
|
||||
{[1, 2, 3, 4].map((item) => (
|
||||
<div key={item} className='flex items-center w-full h-4 gap-4'>
|
||||
<div className='h-4 w-6 bg-base-content/4 rounded'></div>
|
||||
<div className='h-0.25 w-full bg-base-content/4 rounded'></div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* X-axis skeleton (bottom) */}
|
||||
<div className='grid grid-cols-10 gap-15 mt-4 ps-13 sm:ps-26 overflow-x-hidden'>
|
||||
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((item) => (
|
||||
<div
|
||||
key={item}
|
||||
className='h-4 w-9.5 bg-base-content/4 rounded'
|
||||
></div>
|
||||
))}
|
||||
</div>
|
||||
<div className='flex justify-center pt-4 ps-13 sm:ps-26'>
|
||||
<div className='h-4 w-28.5 bg-base-content/4 rounded'></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -43,7 +43,7 @@ const ExpenseDetail: React.FC<ExpenseDetailProps> = ({ initialValues }) => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className='w-full max-w-7xl pb-16'>
|
||||
<section className='w-full max-w-full pb-16'>
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button
|
||||
href='/expense'
|
||||
@@ -65,7 +65,7 @@ const ExpenseDetail: React.FC<ExpenseDetailProps> = ({ initialValues }) => {
|
||||
tabs={expenseDetailTabs}
|
||||
variant='lifted'
|
||||
className={{
|
||||
wrapper: 'max-w-5xl mx-auto mt-4',
|
||||
wrapper: 'mx-auto mt-4',
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
|
||||
@@ -68,7 +68,7 @@ const ExpenseRealizationContent = ({
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className='w-full max-w-5xl mx-auto flex flex-col sm:flex-row justify-end gap-2'>
|
||||
<div className='w-full mx-auto flex flex-col sm:flex-row justify-end gap-2'>
|
||||
<div className='w-full sm:w-fit sm:ml-2 flex flex-row gap-2 items-center'>
|
||||
<RequirePermission permissions='lti.expense.update.realization'>
|
||||
<Button
|
||||
@@ -84,7 +84,7 @@ const ExpenseRealizationContent = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='overflow-x-auto w-full max-w-5xl mx-auto'>
|
||||
<div className='overflow-x-auto w-full mx-auto'>
|
||||
<table className='table table-sm table-zebra'>
|
||||
<tbody>
|
||||
<tr>
|
||||
@@ -179,7 +179,7 @@ const ExpenseRealizationContent = ({
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className='w-full max-w-5xl mt-8 mx-auto'>
|
||||
<div className='w-full mt-8 mx-auto'>
|
||||
<div className='flex flex-row gap-4'>
|
||||
<Card variant='bordered' size='sm' className={{ wrapper: 'grow' }}>
|
||||
<div className='w-full flex flex-col gap-2'>
|
||||
@@ -216,127 +216,141 @@ const ExpenseRealizationContent = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='w-full max-w-5xl mt-8 mx-auto'>
|
||||
<h2 className='font-bold text-xl text-center'>
|
||||
Rincian Pengajuan Biaya Operasional
|
||||
</h2>
|
||||
<div className='w-full mt-8 mx-auto grid grid-cols-2 gap-4'>
|
||||
<div>
|
||||
<h2 className='font-bold text-xl text-center'>
|
||||
Rincian Pengajuan Biaya Operasional
|
||||
</h2>
|
||||
|
||||
<div className='w-full mt-2 flex flex-col gap-4'>
|
||||
{initialValues?.kandangs.map((kandangExpense, kandangExpenseIdx) => {
|
||||
let expenseGrandTotal = 0;
|
||||
<div className='w-full mt-2 flex flex-col gap-4'>
|
||||
{initialValues?.kandangs.map(
|
||||
(kandangExpense, kandangExpenseIdx) => {
|
||||
let expenseGrandTotal = 0;
|
||||
|
||||
kandangExpense.pengajuans?.forEach(
|
||||
(item) => (expenseGrandTotal += item.qty * item.price)
|
||||
);
|
||||
kandangExpense.pengajuans?.forEach(
|
||||
(item) => (expenseGrandTotal += item.qty * item.price)
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={kandangExpenseIdx}
|
||||
className='overflow-x-auto w-full mx-auto'
|
||||
>
|
||||
<table className='table table-sm table-zebra'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
colSpan={5}
|
||||
className='font-bold text-center text-base-content text-lg'
|
||||
>
|
||||
Biaya {kandangExpense.name}
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Nonstock</th>
|
||||
<th>Total Kuantitas</th>
|
||||
<th>Total Biaya</th>
|
||||
<th>Catatan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{kandangExpense.pengajuans?.map(
|
||||
(pengajuanItem, pengajuanIdx) => (
|
||||
<tr key={pengajuanIdx}>
|
||||
<td>{pengajuanItem.nonstock.name}</td>
|
||||
<td>{pengajuanItem.qty}</td>
|
||||
<td>{formatCurrency(pengajuanItem.price)}</td>
|
||||
<td className='w-xs'>{pengajuanItem.note ?? '-'}</td>
|
||||
return (
|
||||
<div
|
||||
key={kandangExpenseIdx}
|
||||
className='overflow-x-auto w-full mx-auto'
|
||||
>
|
||||
<table className='table table-sm table-zebra'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
colSpan={5}
|
||||
className='font-bold text-center text-base-content text-lg'
|
||||
>
|
||||
Biaya {kandangExpense.name}
|
||||
</th>
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='border-y'>
|
||||
<th colSpan={2} className='text-right'>
|
||||
Total Biaya Keseluruhan:
|
||||
</th>
|
||||
<th colSpan={2}>{formatCurrency(expenseGrandTotal)}</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<tr>
|
||||
<th>Nonstock</th>
|
||||
<th>Total Kuantitas</th>
|
||||
<th>Total Biaya</th>
|
||||
<th>Catatan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{kandangExpense.pengajuans?.map(
|
||||
(pengajuanItem, pengajuanIdx) => (
|
||||
<tr key={pengajuanIdx}>
|
||||
<td>{pengajuanItem.nonstock.name}</td>
|
||||
<td>{pengajuanItem.qty}</td>
|
||||
<td>{formatCurrency(pengajuanItem.price)}</td>
|
||||
<td className='w-xs'>
|
||||
{pengajuanItem.notes ?? '-'}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='border-y'>
|
||||
<th colSpan={2} className='text-right'>
|
||||
Total Biaya Keseluruhan:
|
||||
</th>
|
||||
<th colSpan={2}>
|
||||
{formatCurrency(expenseGrandTotal)}
|
||||
</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='w-full max-w-5xl mt-8 mx-auto'>
|
||||
<h2 className='font-bold text-xl text-center'>
|
||||
Rincian Realisasi Biaya Operasional
|
||||
</h2>
|
||||
<div>
|
||||
<h2 className='font-bold text-xl text-center'>
|
||||
Rincian Realisasi Biaya Operasional
|
||||
</h2>
|
||||
|
||||
<div className='w-full mt-2 flex flex-col gap-4'>
|
||||
{initialValues?.kandangs.map((kandangExpense, kandangExpenseIdx) => {
|
||||
let expenseGrandTotal = 0;
|
||||
<div className='w-full mt-2 flex flex-col gap-4'>
|
||||
{initialValues?.kandangs.map(
|
||||
(kandangExpense, kandangExpenseIdx) => {
|
||||
let expenseGrandTotal = 0;
|
||||
|
||||
kandangExpense.realisasi?.forEach(
|
||||
(item) => (expenseGrandTotal += item.qty * item.price)
|
||||
);
|
||||
kandangExpense.realisasi?.forEach(
|
||||
(item) => (expenseGrandTotal += item.qty * item.price)
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={kandangExpenseIdx}
|
||||
className='overflow-x-auto w-full mx-auto'
|
||||
>
|
||||
<table className='table table-sm table-zebra'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
colSpan={5}
|
||||
className='font-bold text-center text-base-content text-lg'
|
||||
>
|
||||
Biaya {kandangExpense.name}
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Nonstock</th>
|
||||
<th>Total Kuantitas</th>
|
||||
<th>Total Biaya</th>
|
||||
<th>Catatan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{kandangExpense.realisasi?.map(
|
||||
(realisasiItem, realisasiIdx) => (
|
||||
<tr key={realisasiIdx}>
|
||||
<td>{realisasiItem.nonstock.name}</td>
|
||||
<td>{realisasiItem.qty}</td>
|
||||
<td>{formatCurrency(realisasiItem.price)}</td>
|
||||
<td className='w-xs'>{realisasiItem.note ?? '-'}</td>
|
||||
return (
|
||||
<div
|
||||
key={kandangExpenseIdx}
|
||||
className='overflow-x-auto w-full mx-auto'
|
||||
>
|
||||
<table className='table table-sm table-zebra'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
colSpan={5}
|
||||
className='font-bold text-center text-base-content text-lg'
|
||||
>
|
||||
Biaya {kandangExpense.name}
|
||||
</th>
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='border-y'>
|
||||
<th colSpan={2} className='text-right'>
|
||||
Total Biaya Keseluruhan:
|
||||
</th>
|
||||
<th colSpan={2}>{formatCurrency(expenseGrandTotal)}</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<tr>
|
||||
<th>Nonstock</th>
|
||||
<th>Total Kuantitas</th>
|
||||
<th>Total Biaya</th>
|
||||
<th>Catatan</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{kandangExpense.realisasi?.map(
|
||||
(realisasiItem, realisasiIdx) => (
|
||||
<tr key={realisasiIdx}>
|
||||
<td>{realisasiItem.nonstock.name}</td>
|
||||
<td>{realisasiItem.qty}</td>
|
||||
<td>{formatCurrency(realisasiItem.price)}</td>
|
||||
<td className='w-xs'>
|
||||
{realisasiItem.notes ?? '-'}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className='border-y'>
|
||||
<th colSpan={2} className='text-right'>
|
||||
Total Biaya Keseluruhan:
|
||||
</th>
|
||||
<th colSpan={2}>
|
||||
{formatCurrency(expenseGrandTotal)}
|
||||
</th>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useFormik } from 'formik';
|
||||
import useSWR from 'swr';
|
||||
import toast from 'react-hot-toast';
|
||||
|
||||
import { Icon } from '@iconify/react';
|
||||
@@ -57,10 +56,6 @@ const ExpenseRequestContent = ({
|
||||
const isLatestApprovalRejected =
|
||||
initialValues?.latest_approval.action === 'REJECTED';
|
||||
|
||||
const isLatestApprovalRejectedOrDone =
|
||||
isLatestApprovalRejected ||
|
||||
initialValues?.latest_approval.step_number === 6;
|
||||
|
||||
const isCurrentApprovalOnHeadArea =
|
||||
!isLatestApprovalRejected &&
|
||||
initialValues?.latest_approval.step_number === 1;
|
||||
@@ -273,7 +268,7 @@ const ExpenseRequestContent = ({
|
||||
<>
|
||||
<div>
|
||||
{initialValues && !isLoadingApprovalHistory && approvalHistory && (
|
||||
<div className='w-full max-w-5xl my-4 mx-auto'>
|
||||
<div className='w-full my-4 mx-auto'>
|
||||
<ApprovalSteps approvals={approvalHistory} />
|
||||
</div>
|
||||
)}
|
||||
@@ -281,7 +276,7 @@ const ExpenseRequestContent = ({
|
||||
<div className='w-full mt-4 flex flex-col gap-4'>
|
||||
{/* TODO: apply RBAC */}
|
||||
|
||||
<div className='w-full max-w-5xl mx-auto flex flex-col sm:flex-row justify-end gap-2'>
|
||||
<div className='w-full mx-auto flex flex-col sm:flex-row justify-end gap-2'>
|
||||
{isCurrentApprovalOnHeadArea && (
|
||||
<RequirePermission permissions='lti.expense.approve.head_area'>
|
||||
<Button
|
||||
@@ -414,7 +409,7 @@ const ExpenseRequestContent = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='overflow-x-auto w-full max-w-5xl mx-auto'>
|
||||
<div className='overflow-x-auto w-full mx-auto'>
|
||||
<table className='table table-sm table-zebra'>
|
||||
<tbody>
|
||||
<tr>
|
||||
@@ -608,7 +603,7 @@ const ExpenseRequestContent = ({
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div className='w-full max-w-5xl mt-8 mx-auto'>
|
||||
<div className='w-full mt-8 mx-auto'>
|
||||
<h2 className='font-bold text-xl text-center'>
|
||||
Rincian Pengajuan Biaya Operasional
|
||||
</h2>
|
||||
@@ -654,7 +649,7 @@ const ExpenseRequestContent = ({
|
||||
<td>{pengajuanItem.qty}</td>
|
||||
<td>{formatCurrency(pengajuanItem.price)}</td>
|
||||
<td className='w-xs'>
|
||||
{pengajuanItem.note ?? '-'}
|
||||
{pengajuanItem.notes ?? '-'}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
|
||||
@@ -35,7 +35,6 @@ import { ExpenseApi } from '@/services/api/expense';
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/helper';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import { LocationApi, SupplierApi } from '@/services/api/master-data';
|
||||
import { Location } from '@/types/api/master-data/location';
|
||||
import { Supplier } from '@/types/api/master-data/supplier';
|
||||
@@ -44,8 +43,6 @@ import { BaseApiResponse } from '@/types/api/api-general';
|
||||
const RowOptionsMenu = ({
|
||||
type = 'dropdown',
|
||||
props,
|
||||
approveClickHandler,
|
||||
rejectClickHandler,
|
||||
deleteClickHandler,
|
||||
}: {
|
||||
type: 'dropdown' | 'collapse';
|
||||
@@ -54,17 +51,19 @@ const RowOptionsMenu = ({
|
||||
rejectClickHandler: () => void;
|
||||
deleteClickHandler: () => void;
|
||||
}) => {
|
||||
const showEditButton =
|
||||
props.row.original.latest_approval.step_number !== 6 &&
|
||||
(props.row.original.latest_approval.step_number === 1 ||
|
||||
props.row.original.latest_approval.step_number === 2 ||
|
||||
props.row.original.latest_approval.step_number === 3 ||
|
||||
props.row.original.latest_approval.step_number === 4);
|
||||
const showEditButton = props.row.original.latest_approval
|
||||
? props.row.original.latest_approval.step_number !== 6 &&
|
||||
(props.row.original.latest_approval.step_number === 1 ||
|
||||
props.row.original.latest_approval.step_number === 2 ||
|
||||
props.row.original.latest_approval.step_number === 3 ||
|
||||
props.row.original.latest_approval.step_number === 4)
|
||||
: false;
|
||||
|
||||
// TODO: apply RBAC
|
||||
const showRealizationButton =
|
||||
props.row.original.latest_approval.action !== 'REJECTED' &&
|
||||
props.row.original.latest_approval.step_number === 4;
|
||||
const showRealizationButton = props.row.original.latest_approval
|
||||
? props.row.original.latest_approval.action !== 'REJECTED' &&
|
||||
props.row.original.latest_approval.step_number === 4
|
||||
: false;
|
||||
|
||||
return (
|
||||
<RowOptionsMenuWrapper type={type}>
|
||||
@@ -184,7 +183,6 @@ const ExpensesTable = () => {
|
||||
undefined
|
||||
);
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
const [isCompleteLoading, setIsCompleteLoading] = useState(false);
|
||||
const [isApproveLoading, setIsApproveLoading] = useState(false);
|
||||
const [isRejectLoading, setIsRejectLoading] = useState(false);
|
||||
|
||||
@@ -245,23 +243,6 @@ const ExpensesTable = () => {
|
||||
});
|
||||
}, [expenses, selectedRowIds]);
|
||||
|
||||
const isAllSelectedRowLatestApprovalOnRealization = useMemo(() => {
|
||||
return selectedRowIds.every((rowId) => {
|
||||
if (!isResponseSuccess(expenses)) return false;
|
||||
|
||||
const expenseItem = expenses.data.find((item) => item.id === rowId);
|
||||
|
||||
const isLatestApprovalRejected =
|
||||
expenseItem?.latest_approval.action === 'REJECTED';
|
||||
|
||||
const isCurrentApprovalOnRealization =
|
||||
!isLatestApprovalRejected &&
|
||||
expenseItem?.latest_approval.step_number === 5;
|
||||
|
||||
return isCurrentApprovalOnRealization;
|
||||
});
|
||||
}, [expenses, selectedRowIds]);
|
||||
|
||||
const expensesColumns: ColumnDef<Expense>[] = [
|
||||
{
|
||||
id: 'select',
|
||||
@@ -278,6 +259,7 @@ const ExpensesTable = () => {
|
||||
cell: ({ row }) => {
|
||||
const isCheckboxDisabled =
|
||||
!row.getCanSelect() ||
|
||||
!row.original.latest_approval ||
|
||||
row.original.latest_approval.action === 'REJECTED';
|
||||
|
||||
return (
|
||||
@@ -413,6 +395,8 @@ const ExpensesTable = () => {
|
||||
const tableEnableRowSelectionHandler: (row: Row<Expense>) => boolean = (
|
||||
row
|
||||
) => {
|
||||
if (!row.original.latest_approval) return false;
|
||||
|
||||
return (
|
||||
row.original.latest_approval.action !== 'REJECTED' &&
|
||||
row.original.latest_approval.step_number !== 6
|
||||
@@ -584,12 +568,6 @@ const ExpensesTable = () => {
|
||||
updateFilter('realizationDate', e.target.value);
|
||||
};
|
||||
|
||||
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
const newVal = val as OptionType;
|
||||
|
||||
setPageSize(newVal.value as number);
|
||||
};
|
||||
|
||||
// track sorting
|
||||
useEffect(() => {
|
||||
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
|
||||
@@ -692,14 +670,6 @@ const ExpensesTable = () => {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
placeholder='Cari Biaya Operasional'
|
||||
value={tableFilterState.search}
|
||||
onChange={searchChangeHandler}
|
||||
className={{ wrapper: 'sm:max-w-3xs' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-12 justify-end gap-2'>
|
||||
@@ -753,17 +723,12 @@ const ExpensesTable = () => {
|
||||
}}
|
||||
/>
|
||||
|
||||
<SelectInput
|
||||
label='Baris'
|
||||
options={ROWS_OPTIONS}
|
||||
value={{
|
||||
label: String(tableFilterState.pageSize),
|
||||
value: tableFilterState.pageSize,
|
||||
}}
|
||||
onChange={pageSizeChangeHandler}
|
||||
className={{
|
||||
wrapper: 'col-span-12 max-w-28 justify-self-end',
|
||||
}}
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
placeholder='Cari Biaya Operasional'
|
||||
value={tableFilterState.search}
|
||||
onChange={searchChangeHandler}
|
||||
className={{ wrapper: 'col-span-12 max-w-52 justify-self-end' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,7 @@ import { isResponseSuccess } from '@/lib/api-helper';
|
||||
interface ExpenseKandangsTableProps {
|
||||
locationId?: number;
|
||||
type: 'add' | 'edit' | 'detail';
|
||||
formType?: 'request' | 'realization';
|
||||
selectedKandangs: {
|
||||
id?: number;
|
||||
name?: string;
|
||||
@@ -31,6 +32,7 @@ interface ExpenseKandangsTableProps {
|
||||
|
||||
const ExpenseKandangsTable = ({
|
||||
type,
|
||||
formType = 'request',
|
||||
locationId,
|
||||
selectedKandangs,
|
||||
onChange,
|
||||
@@ -172,69 +174,84 @@ const ExpenseKandangsTable = ({
|
||||
updateSortingFilter('picSort', picSortFilter);
|
||||
}, [sorting, updateSortingFilter]);
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={{
|
||||
wrapper: className?.wrapper,
|
||||
body: 'p-4 shadow',
|
||||
}}
|
||||
>
|
||||
<Collapse
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
title={
|
||||
<div className='card-actions p-4 justify-between items-center w-full'>
|
||||
<div className='card-title'>Pilih Kandang</div>
|
||||
// Tampilkan tabel jika:
|
||||
// 1. Mode request pertama kali (type='add' dan formType='request')
|
||||
// 2. Atau sudah ada kandang yang dipilih
|
||||
const shouldShowTable =
|
||||
(type === 'add' && formType === 'request') ||
|
||||
(selectedKandangs.length > 0 && selectedKandangs.some((k) => k.id));
|
||||
|
||||
<Icon
|
||||
icon='material-symbols:keyboard-arrow-down'
|
||||
width={24}
|
||||
height={24}
|
||||
className={cn('text-primary transition-transform', {
|
||||
'-rotate-180': open,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
className='w-full!'
|
||||
titleClassName='w-full p-0!'
|
||||
>
|
||||
<Table<Kandang>
|
||||
data={isResponseSuccess(kandangs) ? kandangs?.data : []}
|
||||
columns={kandangsColumns}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={isResponseSuccess(kandangs) ? kandangs?.meta?.page : 0}
|
||||
totalItems={
|
||||
isResponseSuccess(kandangs) ? kandangs?.meta?.total_results : 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
return (
|
||||
<>
|
||||
{shouldShowTable && (
|
||||
<Card
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
isResponseSuccess(kandangs) && kandangs?.data?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 first:flex first:flex-row first:justify-start',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 first:flex first:flex-row first:justify-start',
|
||||
paginationClassName: cn({
|
||||
hidden:
|
||||
isResponseSuccess(kandangs) &&
|
||||
kandangs?.meta?.total_pages === 1,
|
||||
}),
|
||||
wrapper: className?.wrapper,
|
||||
body: 'p-4 shadow',
|
||||
}}
|
||||
/>
|
||||
</Collapse>
|
||||
</Card>
|
||||
>
|
||||
<Collapse
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
title={
|
||||
<div className='card-actions p-4 justify-between items-center w-full'>
|
||||
<div className='card-title'>
|
||||
{formType === 'realization'
|
||||
? 'Kandang yang Direalisasikan'
|
||||
: 'Pilih Kandang'}
|
||||
</div>
|
||||
|
||||
<Icon
|
||||
icon='material-symbols:keyboard-arrow-down'
|
||||
width={24}
|
||||
height={24}
|
||||
className={cn('text-primary transition-transform', {
|
||||
'-rotate-180': open,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
className='w-full!'
|
||||
titleClassName='w-full p-0!'
|
||||
>
|
||||
<Table<Kandang>
|
||||
data={isResponseSuccess(kandangs) ? kandangs?.data : []}
|
||||
columns={kandangsColumns}
|
||||
pageSize={tableFilterState.pageSize}
|
||||
page={isResponseSuccess(kandangs) ? kandangs?.meta?.page : 0}
|
||||
totalItems={
|
||||
isResponseSuccess(kandangs) ? kandangs?.meta?.total_results : 0
|
||||
}
|
||||
onPageChange={setPage}
|
||||
isLoading={isLoading}
|
||||
sorting={sorting}
|
||||
setSorting={setSorting}
|
||||
rowSelection={rowSelection}
|
||||
setRowSelection={setRowSelection}
|
||||
className={{
|
||||
containerClassName: cn({
|
||||
'mb-20':
|
||||
isResponseSuccess(kandangs) && kandangs?.data?.length === 0,
|
||||
}),
|
||||
tableWrapperClassName: 'overflow-x-auto min-h-full!',
|
||||
tableClassName: 'font-inter w-full table-auto min-h-full!',
|
||||
headerRowClassName: 'border-b border-b-gray-200',
|
||||
headerColumnClassName:
|
||||
'px-6 py-3 text-xs font-semibold text-gray-500 first:flex first:flex-row first:justify-start',
|
||||
bodyRowClassName: 'border-b border-b-gray-200',
|
||||
bodyColumnClassName:
|
||||
'px-6 py-3 first:flex first:flex-row first:justify-start',
|
||||
paginationClassName: cn({
|
||||
hidden:
|
||||
isResponseSuccess(kandangs) &&
|
||||
kandangs?.meta?.total_pages === 1,
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</Collapse>
|
||||
</Card>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -73,7 +73,14 @@ export const ExpenseRealizationFormSchema: Yup.ObjectSchema<ExpenseRealizationFo
|
||||
realizations: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
kandang_id: Yup.number().min(1, 'Wajib memilih kandang!').optional(),
|
||||
kandang_id: Yup.number()
|
||||
.optional()
|
||||
.test('valid-kandang-id', 'Wajib memilih kandang!', (value) => {
|
||||
if (value === undefined || value === null || value === 0) {
|
||||
return true;
|
||||
}
|
||||
return value >= 1;
|
||||
}),
|
||||
cost_items: Yup.array()
|
||||
.of(
|
||||
Yup.object({
|
||||
@@ -130,7 +137,7 @@ export const getExpenseRealizationFormInitialValues = (
|
||||
? formatDate(initialValues?.realization_date, 'YYYY-MM-DD')
|
||||
: undefined,
|
||||
kandangs: initialValues?.kandangs.map((kandang) => ({
|
||||
id: kandang.kandang_id,
|
||||
id: kandang.id,
|
||||
name: kandang.name,
|
||||
})),
|
||||
supplier: initialValues?.supplier
|
||||
@@ -159,7 +166,7 @@ export const getExpenseRealizationFormInitialValues = (
|
||||
},
|
||||
quantity: realisasiItem.qty,
|
||||
price: realisasiItem.price,
|
||||
notes: realisasiItem.note,
|
||||
notes: realisasiItem.notes,
|
||||
};
|
||||
})
|
||||
: kandangExpense.pengajuans
|
||||
@@ -170,12 +177,12 @@ export const getExpenseRealizationFormInitialValues = (
|
||||
},
|
||||
quantity: expenseItem.qty,
|
||||
price: expenseItem.price,
|
||||
notes: expenseItem.note,
|
||||
notes: expenseItem.notes,
|
||||
}))
|
||||
: [];
|
||||
|
||||
return {
|
||||
kandang_id: kandangExpense.kandang_id,
|
||||
kandang_id: kandangExpense.id,
|
||||
cost_items: costItemsInitialValue,
|
||||
};
|
||||
})
|
||||
|
||||
@@ -17,6 +17,7 @@ import DropFileInput from '@/components/input/DropFileInput';
|
||||
import ExpenseKandangsTable from '@/components/pages/expense/form/ExpenseKandangsTable';
|
||||
import ExpenseRealizationKandangDetailExpense from '@/components/pages/expense/form/ExpenseRealizationKandangDetailExpense';
|
||||
import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
|
||||
import {
|
||||
CreateExpenseRealizationPayload,
|
||||
@@ -35,6 +36,7 @@ import { LocationApi, SupplierApi } from '@/services/api/master-data';
|
||||
import { Supplier } from '@/types/api/master-data/supplier';
|
||||
import { ACCEPTED_FILE_TYPE } from '@/config/constant';
|
||||
import { cn } from '@/lib/helper';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
|
||||
interface ExpenseRealizationFormProps {
|
||||
type?: 'add' | 'edit' | 'detail';
|
||||
@@ -99,13 +101,23 @@ const ExpenseRealizationForm = ({
|
||||
|
||||
values.realizations.forEach((realization) => {
|
||||
realization.cost_items.forEach((costItem) => {
|
||||
const realizationItem = {
|
||||
const realizationItem: {
|
||||
expense_nonstock_id: number;
|
||||
qty: number;
|
||||
price: number;
|
||||
notes: string;
|
||||
kandang_id?: number;
|
||||
} = {
|
||||
expense_nonstock_id: costItem.nonstock?.value as number,
|
||||
qty: parseFloat(String(costItem.quantity)) as number,
|
||||
price: parseFloat(String(costItem.price)) as number,
|
||||
notes: costItem.notes ?? '',
|
||||
};
|
||||
|
||||
if (realization.kandang_id && realization.kandang_id > 0) {
|
||||
realizationItem.kandang_id = realization.kandang_id;
|
||||
}
|
||||
|
||||
realizations.push(realizationItem);
|
||||
});
|
||||
});
|
||||
@@ -132,6 +144,7 @@ const ExpenseRealizationForm = ({
|
||||
});
|
||||
|
||||
const { setValues: formikSetValues } = formik;
|
||||
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||
|
||||
const {
|
||||
setInputValue: setLocationInputValue,
|
||||
@@ -246,7 +259,7 @@ const ExpenseRealizationForm = ({
|
||||
}, [formikSetValues, getExpenseRealizationFormInitialValues, initialValues]);
|
||||
|
||||
return (
|
||||
<section className='w-full max-w-5xl'>
|
||||
<section className='w-full'>
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button
|
||||
href='/expense'
|
||||
@@ -263,7 +276,7 @@ const ExpenseRealizationForm = ({
|
||||
</header>
|
||||
|
||||
<form
|
||||
onSubmit={formik.handleSubmit}
|
||||
onSubmit={handleFormSubmit}
|
||||
onReset={formik.handleReset}
|
||||
className='w-full mt-8 flex flex-col gap-6'
|
||||
>
|
||||
@@ -294,6 +307,7 @@ const ExpenseRealizationForm = ({
|
||||
|
||||
<ExpenseKandangsTable
|
||||
type='detail'
|
||||
formType='realization'
|
||||
locationId={formik.values.location?.value}
|
||||
selectedKandangs={formik.values.kandangs ?? []}
|
||||
onChange={kandangsChangeHandler}
|
||||
@@ -372,6 +386,8 @@ const ExpenseRealizationForm = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
|
||||
{expenseFormErrorMessage && (
|
||||
<div role='alert' className='alert alert-error w-full'>
|
||||
<Icon
|
||||
@@ -421,7 +437,7 @@ const ExpenseRealizationForm = ({
|
||||
type='submit'
|
||||
color='primary'
|
||||
isLoading={formik.isSubmitting}
|
||||
disabled={!formik.isValid || formik.isSubmitting}
|
||||
disabled={formik.isSubmitting}
|
||||
className='px-4'
|
||||
>
|
||||
Submit
|
||||
|
||||
@@ -30,7 +30,7 @@ interface ExpenseRealizationKandangDetailExpenseProps {
|
||||
|
||||
const ExpenseRealizationKandangDetailExpense: React.FC<
|
||||
ExpenseRealizationKandangDetailExpenseProps
|
||||
> = ({ type, formik, supplierId, location, className }) => {
|
||||
> = ({ formik, supplierId, location, className }) => {
|
||||
const {
|
||||
setInputValue: setNonstockInputValue,
|
||||
options: nonstockOptions,
|
||||
|
||||
@@ -41,22 +41,25 @@ type ExpenseFormSchemaType = {
|
||||
export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
|
||||
Yup.object({
|
||||
category: Yup.object({
|
||||
value: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
|
||||
label: Yup.string().oneOf(['BOP', 'NON-BOP']).required(),
|
||||
value: Yup.string()
|
||||
.oneOf(['BOP', 'NON-BOP'])
|
||||
.required('Kategori wajib diisi!'),
|
||||
label: Yup.string()
|
||||
.oneOf(['BOP', 'NON-BOP'])
|
||||
.required('Kategori wajib diisi!'),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
.required('Kategori wajib diisi!')
|
||||
.typeError('Kategori wajib diisi!'),
|
||||
|
||||
location: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
}).nullable(),
|
||||
|
||||
location_id: Yup.number()
|
||||
.required('Lokasi wajib diisi!')
|
||||
.min(1, 'Lokasi wajib diisi!')
|
||||
.required('Lokasi wajib diisi!')
|
||||
.typeError('Lokasi wajib diisi!'),
|
||||
|
||||
transaction_date: Yup.string().required('Tanggal transaksi wajib diisi!'),
|
||||
@@ -73,9 +76,7 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
|
||||
supplier: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
}).nullable(),
|
||||
|
||||
supplier_id: Yup.number()
|
||||
.required('Vendor wajib diisi!')
|
||||
@@ -104,9 +105,12 @@ export const ExpenseRequestFormSchema: Yup.ObjectSchema<ExpenseFormSchemaType> =
|
||||
.of(
|
||||
Yup.object({
|
||||
nonstock: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
value: Yup.number().min(1).required('Nonstock wajib diisi!'),
|
||||
label: Yup.string().required('Nonstock wajib diisi!'),
|
||||
})
|
||||
.nullable()
|
||||
.required('Nonstock wajib diisi!')
|
||||
.typeError('Nonstock wajib diisi!'),
|
||||
nonstock_id: Yup.number()
|
||||
.required('Nonstock wajib diisi!')
|
||||
.min(1, 'Nonstock wajib diisi!')
|
||||
@@ -204,7 +208,7 @@ export const getExpenseFormInitialValues = (
|
||||
nonstock_id: expenseItem.nonstock.id,
|
||||
quantity: expenseItem.qty,
|
||||
price: expenseItem.price,
|
||||
notes: expenseItem.note,
|
||||
notes: expenseItem.notes,
|
||||
}))
|
||||
: [],
|
||||
}))
|
||||
|
||||
@@ -190,30 +190,18 @@ const ExpenseRequestForm = ({
|
||||
formik.setFieldValue('category', val);
|
||||
};
|
||||
|
||||
const locationChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldTouched('location', true);
|
||||
formik.setFieldValue('location', val);
|
||||
const locationChangeHandler = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
const location = val as OptionType | null;
|
||||
const locationId = location ? Number(location.value) : 0;
|
||||
|
||||
const locationId = Array.isArray(val) ? val[0]?.value : val?.value;
|
||||
formik.setFieldValue('location_id', locationId);
|
||||
|
||||
formik.setFieldValue('kandangs', []);
|
||||
|
||||
// Auto-create expense item for location (without kandang)
|
||||
formik.setFieldValue('expense_nonstocks', [
|
||||
{
|
||||
cost_items: [
|
||||
{
|
||||
nonstock: null,
|
||||
nonstock_id: 0,
|
||||
quantity: undefined,
|
||||
price: undefined,
|
||||
notes: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
};
|
||||
formik.setFieldTouched('location', true);
|
||||
formik.setFieldValue('location', location);
|
||||
formik.setFieldTouched('location_id', true);
|
||||
formik.setFieldValue('location_id', locationId);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const kandangsChangeHandler = (
|
||||
kandangs: { id?: number; name?: string }[]
|
||||
@@ -268,6 +256,7 @@ const ExpenseRequestForm = ({
|
||||
|
||||
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldTouched('supplier', true);
|
||||
formik.setFieldTouched('supplier_id', true);
|
||||
formik.setFieldValue('supplier', val);
|
||||
|
||||
const supplierId = Array.isArray(val) ? val[0]?.value : val?.value;
|
||||
@@ -360,7 +349,7 @@ const ExpenseRequestForm = ({
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className='w-full max-w-5xl'>
|
||||
<section className='w-full'>
|
||||
<header className='flex flex-col gap-4'>
|
||||
<Button
|
||||
href='/expense'
|
||||
@@ -383,23 +372,6 @@ const ExpenseRequestForm = ({
|
||||
onReset={formik.handleReset}
|
||||
className='w-full mt-8 flex flex-col gap-6'
|
||||
>
|
||||
{expenseFormErrorMessage && (
|
||||
<div role='alert' className='alert alert-error'>
|
||||
<Icon
|
||||
icon='material-symbols:error-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
<span>{expenseFormErrorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{formErrorList.length > 0 && (
|
||||
<AlertErrorList
|
||||
formErrorList={formErrorList}
|
||||
onClose={() => setFormErrorList([])}
|
||||
/>
|
||||
)}
|
||||
<div className='grid grid-cols-12 gap-4'>
|
||||
<SelectInput
|
||||
label='Kategori'
|
||||
@@ -407,6 +379,16 @@ const ExpenseRequestForm = ({
|
||||
placeholder='Pilih Kategori'
|
||||
value={formik.values.category}
|
||||
onChange={categoryChangeHandler}
|
||||
isError={
|
||||
formik.touched.category && Boolean(formik.errors.category)
|
||||
}
|
||||
errorMessage={
|
||||
formik.touched.category && formik.errors.category
|
||||
? typeof formik.errors.category === 'object'
|
||||
? 'Kategori wajib diisi!'
|
||||
: (formik.errors.category as string)
|
||||
: undefined
|
||||
}
|
||||
options={[
|
||||
{
|
||||
value: 'BOP',
|
||||
@@ -427,8 +409,13 @@ const ExpenseRequestForm = ({
|
||||
value={formik.values.location}
|
||||
onChange={locationChangeHandler}
|
||||
options={locationOptions}
|
||||
isLoading={isLoadingLocationOptions}
|
||||
onInputChange={setLocationInputValue}
|
||||
isLoading={isLoadingLocationOptions}
|
||||
isError={
|
||||
formik.touched.location_id && Boolean(formik.errors.location_id)
|
||||
}
|
||||
errorMessage={formik.errors.location_id as string}
|
||||
isClearable
|
||||
className={{ wrapper: 'col-span-12 sm:col-span-4' }}
|
||||
/>
|
||||
|
||||
@@ -438,6 +425,12 @@ const ExpenseRequestForm = ({
|
||||
required
|
||||
value={formik.values.transaction_date}
|
||||
onChange={formik.handleChange}
|
||||
onBlur={formik.handleBlur}
|
||||
isError={
|
||||
formik.touched.transaction_date &&
|
||||
Boolean(formik.errors.transaction_date)
|
||||
}
|
||||
errorMessage={formik.errors.transaction_date as string}
|
||||
className={{
|
||||
wrapper: 'col-span-12 sm:col-span-4',
|
||||
}}
|
||||
@@ -460,8 +453,12 @@ const ExpenseRequestForm = ({
|
||||
value={formik.values.supplier}
|
||||
onChange={supplierChangeHandler}
|
||||
options={supplierOptions}
|
||||
isLoading={isLoadingVendorOptions}
|
||||
onInputChange={setVendorInputValue}
|
||||
isLoading={isLoadingVendorOptions}
|
||||
isError={
|
||||
formik.touched.supplier_id && Boolean(formik.errors.supplier_id)
|
||||
}
|
||||
errorMessage={formik.errors.supplier_id as string}
|
||||
className={{ wrapper: 'col-span-12' }}
|
||||
/>
|
||||
|
||||
@@ -543,6 +540,24 @@ const ExpenseRequestForm = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{expenseFormErrorMessage && (
|
||||
<div role='alert' className='alert alert-error'>
|
||||
<Icon
|
||||
icon='material-symbols:error-outline'
|
||||
width={24}
|
||||
height={24}
|
||||
/>
|
||||
<span>{expenseFormErrorMessage}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{formErrorList.length > 0 && (
|
||||
<AlertErrorList
|
||||
formErrorList={formErrorList}
|
||||
onClose={() => setFormErrorList([])}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className='flex flex-row justify-between gap-2 flex-wrap'>
|
||||
{type !== 'add' && (
|
||||
<div className='flex flex-row justify-start gap-2'>
|
||||
|
||||
@@ -55,6 +55,10 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock`,
|
||||
true
|
||||
);
|
||||
formik.setFieldTouched(
|
||||
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock_id`,
|
||||
true
|
||||
);
|
||||
formik.setFieldValue(
|
||||
`expense_nonstocks[${kandangExpenseIdx}].cost_items[${expenseIdx}].nonstock`,
|
||||
val
|
||||
@@ -96,7 +100,7 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
};
|
||||
|
||||
const isExpenseRepeaterInputError = (
|
||||
column: 'nonstock' | 'quantity' | 'price' | 'notes',
|
||||
column: 'nonstock_id' | 'quantity' | 'price' | 'notes',
|
||||
kandangExpenseIdx: number,
|
||||
expenseIdx: number
|
||||
) => {
|
||||
@@ -105,11 +109,14 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
expenseIdx
|
||||
]?.[column] &&
|
||||
Boolean(
|
||||
formik.errors.expense_nonstocks?.[kandangExpenseIdx] instanceof
|
||||
Object &&
|
||||
formik.errors.expense_nonstocks?.[kandangExpenseIdx] &&
|
||||
typeof formik.errors.expense_nonstocks?.[kandangExpenseIdx] ===
|
||||
'object' &&
|
||||
formik.errors.expense_nonstocks?.[kandangExpenseIdx].cost_items?.[
|
||||
expenseIdx
|
||||
] instanceof Object &&
|
||||
] &&
|
||||
typeof formik.errors.expense_nonstocks?.[kandangExpenseIdx]
|
||||
.cost_items?.[expenseIdx] === 'object' &&
|
||||
formik.errors.expense_nonstocks?.[kandangExpenseIdx].cost_items?.[
|
||||
expenseIdx
|
||||
]?.[column]
|
||||
@@ -117,6 +124,32 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
);
|
||||
};
|
||||
|
||||
const getExpenseRepeaterErrorMessage = (
|
||||
column: 'nonstock_id' | 'quantity' | 'price' | 'notes',
|
||||
kandangExpenseIdx: number,
|
||||
expenseIdx: number
|
||||
): string => {
|
||||
const kandangError = formik.errors.expense_nonstocks?.[kandangExpenseIdx];
|
||||
|
||||
if (!kandangError || typeof kandangError !== 'object') return '';
|
||||
|
||||
if (!('cost_items' in kandangError)) return '';
|
||||
|
||||
const costItemsError = kandangError.cost_items?.[expenseIdx];
|
||||
|
||||
if (!costItemsError || typeof costItemsError !== 'object') return '';
|
||||
|
||||
const fieldError = costItemsError[column as keyof typeof costItemsError];
|
||||
|
||||
if (!fieldError) return '';
|
||||
|
||||
if (typeof fieldError === 'object' && fieldError !== null) {
|
||||
return 'Nonstock wajib diisi!';
|
||||
}
|
||||
|
||||
return String(fieldError);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={{
|
||||
@@ -202,10 +235,21 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
val
|
||||
);
|
||||
}}
|
||||
isError={isExpenseRepeaterInputError(
|
||||
'nonstock_id',
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
errorMessage={getExpenseRepeaterErrorMessage(
|
||||
'nonstock_id',
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
options={nonstockOptions}
|
||||
isLoading={isLoadingNonstockOptions}
|
||||
onInputChange={setNonstockInputValue}
|
||||
className={{ wrapper: 'min-w-48' }}
|
||||
isClearable={true}
|
||||
/>
|
||||
</td>
|
||||
|
||||
@@ -226,6 +270,11 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
errorMessage={getExpenseRepeaterErrorMessage(
|
||||
'quantity',
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
className={{ wrapper: 'min-w-24' }}
|
||||
/>
|
||||
</td>
|
||||
@@ -246,6 +295,11 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
errorMessage={getExpenseRepeaterErrorMessage(
|
||||
'price',
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
inputPrefix={
|
||||
<span className='text-gray-600 font-medium'>
|
||||
Rp
|
||||
@@ -271,6 +325,11 @@ const ExpenseRequestKandangDetailExpense: React.FC<
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
errorMessage={getExpenseRepeaterErrorMessage(
|
||||
'notes',
|
||||
kandangExpenseIdx,
|
||||
expenseIdx
|
||||
)}
|
||||
className={{ wrapper: 'min-w-24' }}
|
||||
/>
|
||||
</td>
|
||||
|
||||
@@ -447,7 +447,7 @@ const ExpensePDF = ({ expense }: ExpensePDFProps) => {
|
||||
]}
|
||||
>
|
||||
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
|
||||
{pengajuan.note}
|
||||
{pengajuan.notes}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
@@ -607,7 +607,7 @@ const ExpensePDF = ({ expense }: ExpensePDFProps) => {
|
||||
]}
|
||||
>
|
||||
<Text style={ExpensePDFStyle.kandangExpenseLabelText}>
|
||||
{realisasi.note}
|
||||
{realisasi.notes}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -30,11 +30,11 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
|
||||
},
|
||||
{
|
||||
label: 'Jenis Transaksi',
|
||||
value: finance.transaction_type,
|
||||
value: formatTitleCase(finance.transaction_type.split('_').join(' ')),
|
||||
},
|
||||
{
|
||||
label: 'Pihak',
|
||||
value: finance.party.id ? finance.party.name : '-',
|
||||
value: finance.party?.id ? finance.party?.name : '-',
|
||||
},
|
||||
{
|
||||
label: 'Tanggal',
|
||||
@@ -56,25 +56,27 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
|
||||
},
|
||||
{
|
||||
label: 'Nomor Rekening',
|
||||
value: `${finance.bank.alias} - ${finance.bank.account_number} - ${finance.bank.owner}`,
|
||||
value: finance.bank?.alias
|
||||
? `${finance.bank?.alias} - ${finance.bank?.account_number} - ${finance.bank?.owner}`
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
label: `Rekening ${formatTitleCase(finance.party.type)}`,
|
||||
value: finance.party.account_number,
|
||||
label: `Rekening ${formatTitleCase(finance.party?.type)}`,
|
||||
value: finance.party?.account_number,
|
||||
},
|
||||
{
|
||||
label: 'Nominal',
|
||||
value: formatCurrency(finance.expense_amount),
|
||||
},
|
||||
{
|
||||
label: 'Sisa',
|
||||
value: formatCurrency(finance.income_amount),
|
||||
value: formatCurrency(
|
||||
finance.transaction_type === 'INJECTION'
|
||||
? finance.nominal
|
||||
: Math.abs(finance.nominal)
|
||||
),
|
||||
},
|
||||
].filter((item) => {
|
||||
// Hide party account number row if transaction type is INJECTION
|
||||
if (
|
||||
FINANCE_INJECTION_STATUS.includes(finance.transaction_type) &&
|
||||
item.label === `Rekening ${formatTitleCase(finance.party.type)}`
|
||||
item.label === `Rekening ${formatTitleCase(finance.party?.type)}`
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -148,18 +150,19 @@ const FinanceDetail = ({ finance }: { finance: Finance }) => {
|
||||
</Card>
|
||||
|
||||
<div className='flex flex-row gap-2 justify-end'>
|
||||
{FINANCE_TRANSACTION_STATUS.includes(finance.transaction_type) && (
|
||||
<RequirePermission permissions='lti.finance.payments.update'>
|
||||
<Button
|
||||
color='warning'
|
||||
className='min-w-24'
|
||||
href={`/finance/detail/edit?financeId=${finance.id}`}
|
||||
>
|
||||
<Icon icon='mdi:pencil-outline' />
|
||||
Edit
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
)}
|
||||
{FINANCE_TRANSACTION_STATUS.includes(finance.transaction_type) &&
|
||||
finance.party?.type !== 'SUPPLIER' && (
|
||||
<RequirePermission permissions='lti.finance.payments.update'>
|
||||
<Button
|
||||
color='warning'
|
||||
className='min-w-24'
|
||||
href={`/finance/detail/edit?financeId=${finance.id}`}
|
||||
>
|
||||
<Icon icon='mdi:pencil-outline' />
|
||||
Edit
|
||||
</Button>
|
||||
</RequirePermission>
|
||||
)}
|
||||
{FINANCE_INITIAL_BALANCE_STATUS.includes(finance.transaction_type) && (
|
||||
<RequirePermission permissions='lti.finance.initial_balances.update'>
|
||||
<Button
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import { ChangeEventHandler, useMemo, useState } from 'react';
|
||||
import { CellContext, Row } from '@tanstack/react-table';
|
||||
import {
|
||||
ChangeEventHandler,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { CellContext } from '@tanstack/react-table';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import useSWR from 'swr';
|
||||
|
||||
import Button from '@/components/Button';
|
||||
import Card from '@/components/Card';
|
||||
import Dropdown from '@/components/dropdown/Dropdown';
|
||||
import DateInput from '@/components/input/DateInput';
|
||||
import DebouncedTextInput from '@/components/input/DebouncedTextInput';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import Menu from '@/components/menu/Menu';
|
||||
import MenuItem from '@/components/menu/MenuItem';
|
||||
import Table from '@/components/Table';
|
||||
import Tooltip from '@/components/Tooltip';
|
||||
import { formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
|
||||
import { useTableFilter } from '@/services/hooks/useTableFilter';
|
||||
import { Finance } from '@/types/api/finance/finance';
|
||||
@@ -23,7 +25,7 @@ import {
|
||||
FINANCE_INITIAL_BALANCE_STATUS,
|
||||
FINANCE_INJECTION_STATUS,
|
||||
FINANCE_TRANSACTION_STATUS,
|
||||
ROWS_OPTIONS,
|
||||
FINANCE_TRANSACTION_TYPE_OPTIONS,
|
||||
} from '@/config/constant';
|
||||
import { FinanceApi } from '@/services/api/finance';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
@@ -37,6 +39,7 @@ import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import { Icon } from '@iconify/react';
|
||||
import RowDropdownOptions from '@/components/table/RowDropdownOptions';
|
||||
import RowCollapseOptions from '@/components/table/RowCollapseOptions';
|
||||
import { useUiStore } from '@/stores/ui/ui.store';
|
||||
|
||||
const RowOptionsMenu = ({
|
||||
type = 'dropdown',
|
||||
@@ -137,6 +140,9 @@ const RowOptionsMenu = ({
|
||||
};
|
||||
|
||||
const FinanceTable = () => {
|
||||
const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
|
||||
const previousPathRef = useRef<string | null>(null);
|
||||
|
||||
const {
|
||||
state: tableFilterState,
|
||||
updateFilter,
|
||||
@@ -145,10 +151,11 @@ const FinanceTable = () => {
|
||||
toQueryString: getTableFilterQueryString,
|
||||
} = useTableFilter({
|
||||
initial: {
|
||||
search: '',
|
||||
search: searchValue,
|
||||
transactionType: '',
|
||||
bankId: '',
|
||||
partyType: '',
|
||||
customerId: '',
|
||||
supplierId: '',
|
||||
sortBy: '',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
@@ -158,7 +165,8 @@ const FinanceTable = () => {
|
||||
pageSize: 'limit',
|
||||
transactionType: 'transaction_type',
|
||||
bankId: 'bank_id',
|
||||
partyType: 'party_type',
|
||||
customerId: 'customer_id',
|
||||
supplierId: 'supplier_id',
|
||||
sortBy: 'sort_date',
|
||||
startDate: 'start_date',
|
||||
endDate: 'end_date',
|
||||
@@ -169,20 +177,27 @@ const FinanceTable = () => {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const deleteModal = useModal();
|
||||
const [pendingFilters, setPendingFilters] = useState({
|
||||
search: '',
|
||||
search: searchValue,
|
||||
transactionType: '',
|
||||
bankId: '',
|
||||
partyType: '',
|
||||
customerId: '',
|
||||
supplierId: '',
|
||||
sortBy: '',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
});
|
||||
const [selectedTransactionType, setSelectedTransactionType] =
|
||||
useState<OptionType | null>(null);
|
||||
const [selectedBank, setSelectedBank] = useState<OptionType | null>(null);
|
||||
const [selectedPartyType, setSelectedPartyType] = useState<OptionType | null>(
|
||||
null
|
||||
);
|
||||
const [selectedTransactionType, setSelectedTransactionType] = useState<
|
||||
OptionType | OptionType[] | null
|
||||
>(null);
|
||||
const [selectedBank, setSelectedBank] = useState<
|
||||
OptionType | OptionType[] | null
|
||||
>(null);
|
||||
const [selectedCustomerId, setSelectedCustomerId] = useState<
|
||||
OptionType | OptionType[] | null
|
||||
>(null);
|
||||
const [selectedSupplierId, setSelectedSupplierId] = useState<
|
||||
OptionType | OptionType[] | null
|
||||
>(null);
|
||||
const [selectedSortBy, setSelectedSortBy] = useState<OptionType | null>(null);
|
||||
const [selectedFinance, setSelectedFinance] = useState<Finance | null>(null);
|
||||
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
|
||||
@@ -197,37 +212,30 @@ const FinanceTable = () => {
|
||||
FinanceApi.getAllFetcher
|
||||
);
|
||||
|
||||
// ===== Options =====
|
||||
const transactionTypeOptions = useMemo(() => {
|
||||
return [
|
||||
{ label: 'Transfer', value: 'TRANSFER' },
|
||||
{ label: 'Cash', value: 'CASH' },
|
||||
{ label: 'Card', value: 'CARD' },
|
||||
{ label: 'Cheque', value: 'CHEQUE' },
|
||||
{ label: 'Saldo', value: 'SALDO' },
|
||||
];
|
||||
}, []);
|
||||
const partyTypeOptions = useMemo(() => {
|
||||
return [
|
||||
{ label: 'Customer', value: 'CUSTOMER' },
|
||||
{ label: 'Supplier', value: 'SUPPLIER' },
|
||||
];
|
||||
}, []);
|
||||
const {
|
||||
options: customerOptions,
|
||||
isLoadingOptions: customerIsLoadingOptions,
|
||||
setInputValue: customerInputValue,
|
||||
loadMore: customerLoadMore,
|
||||
} = useSelect(CustomerApi.basePath, 'id', 'name');
|
||||
const {
|
||||
options: supplierOptions,
|
||||
isLoadingOptions: supplierIsLoadingOptions,
|
||||
setInputValue: supplierInputValue,
|
||||
loadMore: supplierLoadMore,
|
||||
} = useSelect(SupplierApi.basePath, 'id', 'name');
|
||||
const sortByOptions = useMemo(() => {
|
||||
return [
|
||||
{ label: 'Tanggal Pembayaran', value: 'payment_date' },
|
||||
{ label: 'Tanggal Dibuat', value: 'created_at' },
|
||||
];
|
||||
}, []);
|
||||
const { options: bankOptions, rawData: bankRawData } = useSelect<Bank>(
|
||||
BankApi.basePath,
|
||||
'id',
|
||||
'alias',
|
||||
'',
|
||||
{
|
||||
limit: 'limit',
|
||||
}
|
||||
);
|
||||
const {
|
||||
options: bankOptions,
|
||||
rawData: bankRawData,
|
||||
setInputValue: bankInputValue,
|
||||
loadMore: bankLoadMore,
|
||||
} = useSelect<Bank>(BankApi.basePath, 'id', 'alias');
|
||||
|
||||
// ===== Handler =====
|
||||
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
@@ -236,24 +244,47 @@ const FinanceTable = () => {
|
||||
const transactionTypeChangeHandler = (
|
||||
val: OptionType | OptionType[] | null
|
||||
) => {
|
||||
setSelectedTransactionType(val as OptionType);
|
||||
setSelectedTransactionType(val);
|
||||
setPendingFilters((prev) => ({
|
||||
...prev,
|
||||
transactionType: val ? ((val as OptionType).value as string) : '',
|
||||
transactionType: val
|
||||
? Array.isArray(val)
|
||||
? val.map((item) => item.value).join(',')
|
||||
: (val.value as string)
|
||||
: '',
|
||||
}));
|
||||
};
|
||||
const bankChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedBank(val as OptionType);
|
||||
setSelectedBank(val);
|
||||
setPendingFilters((prev) => ({
|
||||
...prev,
|
||||
bankId: val ? ((val as OptionType).value as string) : '',
|
||||
bankId: val
|
||||
? Array.isArray(val)
|
||||
? val.map((item) => item.value).join(',')
|
||||
: (val.value as string)
|
||||
: '',
|
||||
}));
|
||||
};
|
||||
const partyTypeChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedPartyType(val as OptionType);
|
||||
const customerIdChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedCustomerId(val);
|
||||
setPendingFilters((prev) => ({
|
||||
...prev,
|
||||
partyType: val ? ((val as OptionType).value as string) : '',
|
||||
customerId: val
|
||||
? Array.isArray(val)
|
||||
? val.map((item) => item.value).join(',')
|
||||
: (val.value as string)
|
||||
: '',
|
||||
}));
|
||||
};
|
||||
const supplierIdChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
setSelectedSupplierId(val);
|
||||
setPendingFilters((prev) => ({
|
||||
...prev,
|
||||
supplierId: val
|
||||
? Array.isArray(val)
|
||||
? val.map((item) => item.value).join(',')
|
||||
: (val.value as string)
|
||||
: '',
|
||||
}));
|
||||
};
|
||||
const sortByChangeHandler = (val: OptionType | OptionType[] | null) => {
|
||||
@@ -275,9 +306,11 @@ const FinanceTable = () => {
|
||||
};
|
||||
const submitFilterHandler = () => {
|
||||
updateFilter('search', pendingFilters.search);
|
||||
setSearchValue(pendingFilters.search);
|
||||
updateFilter('transactionType', pendingFilters.transactionType);
|
||||
updateFilter('bankId', pendingFilters.bankId);
|
||||
updateFilter('partyType', pendingFilters.partyType);
|
||||
updateFilter('customerId', pendingFilters.customerId);
|
||||
updateFilter('supplierId', pendingFilters.supplierId);
|
||||
updateFilter('sortBy', pendingFilters.sortBy);
|
||||
updateFilter('startDate', pendingFilters.startDate);
|
||||
updateFilter('endDate', pendingFilters.endDate);
|
||||
@@ -285,14 +318,16 @@ const FinanceTable = () => {
|
||||
const resetFilterHandler = () => {
|
||||
setSelectedTransactionType(null);
|
||||
setSelectedBank(null);
|
||||
setSelectedPartyType(null);
|
||||
setSelectedCustomerId(null);
|
||||
setSelectedSupplierId(null);
|
||||
setSelectedSortBy(null);
|
||||
|
||||
const emptyFilters = {
|
||||
search: '',
|
||||
transactionType: '',
|
||||
bankId: '',
|
||||
partyType: '',
|
||||
customerId: '',
|
||||
supplierId: '',
|
||||
sortBy: '',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
@@ -300,9 +335,11 @@ const FinanceTable = () => {
|
||||
setPendingFilters(emptyFilters);
|
||||
|
||||
updateFilter('search', '');
|
||||
resetSearchValue();
|
||||
updateFilter('transactionType', '');
|
||||
updateFilter('bankId', '');
|
||||
updateFilter('partyType', '');
|
||||
updateFilter('customerId', '');
|
||||
updateFilter('supplierId', '');
|
||||
updateFilter('sortBy', '');
|
||||
updateFilter('startDate', '');
|
||||
updateFilter('endDate', '');
|
||||
@@ -344,10 +381,10 @@ const FinanceTable = () => {
|
||||
},
|
||||
{
|
||||
header: 'Pihak',
|
||||
accessorFn: (finance: Finance) => finance.party.name,
|
||||
accessorFn: (finance: Finance) => finance.party?.name,
|
||||
cell: (props: CellContext<Finance, unknown>) => {
|
||||
if (props.row.original.party.id) {
|
||||
return <span>{props.row.original.party.name}</span>;
|
||||
if (props.row.original.party?.id) {
|
||||
return <span>{props.row.original.party?.name}</span>;
|
||||
}
|
||||
return <span>{'-'}</span>;
|
||||
},
|
||||
@@ -368,16 +405,19 @@ const FinanceTable = () => {
|
||||
{
|
||||
header: 'Bank',
|
||||
accessorFn: (finance: Finance) =>
|
||||
`${finance.bank.alias} - ${finance.bank.account_number} - ${finance.bank.owner}`,
|
||||
finance.bank
|
||||
? `${finance.bank?.alias} - ${finance.bank?.account_number} - ${finance.bank?.owner}`
|
||||
: '-',
|
||||
},
|
||||
{
|
||||
header: 'Pengeluaran (Rp)',
|
||||
accessorFn: (finance: Finance) =>
|
||||
formatCurrency(finance.expense_amount),
|
||||
formatCurrency(Math.abs(finance.expense_amount)),
|
||||
},
|
||||
{
|
||||
header: 'Pemasukan (Rp)',
|
||||
accessorFn: (finance: Finance) => formatCurrency(finance.income_amount),
|
||||
accessorFn: (finance: Finance) =>
|
||||
formatCurrency(Math.abs(finance.income_amount)),
|
||||
},
|
||||
{
|
||||
header: 'Aksi',
|
||||
@@ -422,6 +462,26 @@ const FinanceTable = () => {
|
||||
},
|
||||
];
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// Store current path on mount
|
||||
previousPathRef.current = window.location.pathname;
|
||||
|
||||
return () => {
|
||||
const currentPath = window.location.pathname;
|
||||
|
||||
// if both paths are within /finance module
|
||||
const isCurrentPathFinance = currentPath.includes('/finance');
|
||||
const isPreviousPathFinance =
|
||||
previousPathRef.current?.includes('/finance');
|
||||
|
||||
// reset if we outside finance module entirely
|
||||
if (isPreviousPathFinance && !isCurrentPathFinance) {
|
||||
resetSearchValue();
|
||||
}
|
||||
};
|
||||
}, [resetSearchValue]);
|
||||
|
||||
return (
|
||||
<section className='size-full p-6 flex flex-col gap-6'>
|
||||
<div className='flex justify-end gap-2'>
|
||||
@@ -475,47 +535,59 @@ const FinanceTable = () => {
|
||||
>
|
||||
<div className='grid grid-cols-4 gap-6'>
|
||||
<SelectInput
|
||||
options={transactionTypeOptions}
|
||||
options={FINANCE_TRANSACTION_TYPE_OPTIONS}
|
||||
label='Jenis Transaksi'
|
||||
value={selectedTransactionType}
|
||||
onChange={transactionTypeChangeHandler}
|
||||
isClearable
|
||||
isMulti
|
||||
/>
|
||||
<SelectInput
|
||||
options={customerOptions}
|
||||
label={'Customer'}
|
||||
value={selectedCustomerId}
|
||||
onChange={customerIdChangeHandler}
|
||||
onInputChange={customerInputValue}
|
||||
onMenuScrollToBottom={customerLoadMore}
|
||||
isLoading={customerIsLoadingOptions}
|
||||
isClearable
|
||||
isMulti
|
||||
/>
|
||||
<SelectInput
|
||||
options={supplierOptions}
|
||||
label={'Supplier'}
|
||||
value={selectedSupplierId}
|
||||
onChange={supplierIdChangeHandler}
|
||||
onInputChange={supplierInputValue}
|
||||
onMenuScrollToBottom={supplierLoadMore}
|
||||
isLoading={supplierIsLoadingOptions}
|
||||
isClearable
|
||||
isMulti
|
||||
/>
|
||||
<SelectInput
|
||||
options={
|
||||
isResponseSuccess(bankRawData)
|
||||
? bankOptions.map((bank) => ({
|
||||
label:
|
||||
bankRawData.data.find((data) => data.id === bank.value)
|
||||
bankRawData.data.find((data) => data.id === bank?.value)
|
||||
?.alias +
|
||||
' - ' +
|
||||
bankRawData.data.find((data) => data.id === bank.value)
|
||||
bankRawData.data.find((data) => data.id === bank?.value)
|
||||
?.account_number +
|
||||
' - ' +
|
||||
bankRawData.data.find((data) => data.id === bank.value)
|
||||
bankRawData.data.find((data) => data.id === bank?.value)
|
||||
?.owner,
|
||||
value: bank.value,
|
||||
value: bank?.value,
|
||||
}))
|
||||
: []
|
||||
}
|
||||
label='Bank'
|
||||
value={selectedBank}
|
||||
onChange={bankChangeHandler}
|
||||
onInputChange={bankInputValue}
|
||||
onMenuScrollToBottom={bankLoadMore}
|
||||
isClearable
|
||||
/>
|
||||
<SelectInput
|
||||
options={partyTypeOptions}
|
||||
label='Pihak'
|
||||
value={selectedPartyType}
|
||||
onChange={partyTypeChangeHandler}
|
||||
isClearable
|
||||
/>
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
label='Cari'
|
||||
placeholder='Cari'
|
||||
value={pendingFilters.search}
|
||||
onChange={searchChangeHandler}
|
||||
isMulti
|
||||
/>
|
||||
<SelectInput
|
||||
options={sortByOptions}
|
||||
@@ -536,6 +608,13 @@ const FinanceTable = () => {
|
||||
value={pendingFilters.endDate}
|
||||
onChange={endDateChangeHandler}
|
||||
/>
|
||||
<DebouncedTextInput
|
||||
name='search'
|
||||
label='Cari'
|
||||
placeholder='Cari'
|
||||
value={pendingFilters.search}
|
||||
onChange={searchChangeHandler}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
<Table<Finance>
|
||||
|
||||
@@ -32,8 +32,10 @@ import {
|
||||
import { Bank } from '@/types/api/master-data/bank';
|
||||
import { useFormik } from 'formik';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import Alert from '@/components/Alert';
|
||||
import { Icon } from '@iconify/react';
|
||||
|
||||
interface FormFinanceAddProps {
|
||||
type?: 'add' | 'edit';
|
||||
@@ -51,18 +53,19 @@ const FormFinanceAdd = ({
|
||||
initialValues,
|
||||
}: FormFinanceAddProps) => {
|
||||
const router = useRouter();
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState('');
|
||||
|
||||
// ===== Formik =====
|
||||
const formikInitialValues = useMemo((): FinanceFormValues => {
|
||||
return {
|
||||
party_type_option:
|
||||
FINANCE_PARTY_TYPE_OPTIONS.find(
|
||||
(option) => option.value === initialValues?.party.type
|
||||
(option) => option.value === initialValues?.party?.type
|
||||
) || null,
|
||||
party_id_option: initialValues?.party
|
||||
? {
|
||||
label: initialValues?.party.name || '',
|
||||
value: initialValues?.party.id || 0,
|
||||
label: initialValues?.party?.name || '',
|
||||
value: initialValues?.party?.id || 0,
|
||||
}
|
||||
: null,
|
||||
payment_date: initialValues?.payment_date || '',
|
||||
@@ -72,11 +75,11 @@ const FormFinanceAdd = ({
|
||||
) || null,
|
||||
bank_id_option: initialValues?.bank
|
||||
? {
|
||||
label: initialValues.bank.name,
|
||||
value: initialValues.bank.id,
|
||||
label: initialValues?.bank?.name,
|
||||
value: initialValues?.bank?.id,
|
||||
}
|
||||
: null,
|
||||
party_account_number: initialValues?.party.account_number || '',
|
||||
party_account_number: initialValues?.party?.account_number || '',
|
||||
reference_number: initialValues?.reference_number || '',
|
||||
nominal: initialValues?.nominal.toString() || '',
|
||||
notes: initialValues?.notes || '',
|
||||
@@ -113,20 +116,22 @@ const FormFinanceAdd = ({
|
||||
options: partyOptions,
|
||||
isLoadingOptions: isLoadingPartyOptions,
|
||||
rawData: partyRawData,
|
||||
setInputValue: setPartyInputValue,
|
||||
loadMore: loadMorePartyOptions,
|
||||
} = useSelect<PartyCommonProps>(
|
||||
formik.values.party_type_option?.value === 'CUSTOMER'
|
||||
? CustomerApi.basePath
|
||||
: SupplierApi.basePath,
|
||||
'id',
|
||||
'name',
|
||||
'',
|
||||
{ limit: 'limit' }
|
||||
'name'
|
||||
);
|
||||
const {
|
||||
options: bankOptions,
|
||||
rawData: bankRawData,
|
||||
isLoadingOptions: isLoadingBankOptions,
|
||||
} = useSelect<Bank>(BankApi.basePath, 'id', 'name', '', { limit: 'limit' });
|
||||
setInputValue: setBankInputValue,
|
||||
loadMore: loadMoreBankOptions,
|
||||
} = useSelect<Bank>(BankApi.basePath, 'id', 'name');
|
||||
|
||||
// ===== Helper Functions =====
|
||||
const transformFormValuesToPayload = (
|
||||
@@ -151,6 +156,7 @@ const FormFinanceAdd = ({
|
||||
|
||||
if (isResponseError(response)) {
|
||||
toast.error(response.message);
|
||||
setServerErrorMessage(response.message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -166,6 +172,7 @@ const FormFinanceAdd = ({
|
||||
|
||||
if (isResponseError(response)) {
|
||||
toast.error(response.message);
|
||||
setServerErrorMessage(response.message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -205,6 +212,7 @@ const FormFinanceAdd = ({
|
||||
? formik.errors.party_type_option
|
||||
: ''
|
||||
}
|
||||
isDisabled={type === 'edit'}
|
||||
required
|
||||
isClearable
|
||||
/>
|
||||
@@ -219,6 +227,8 @@ const FormFinanceAdd = ({
|
||||
placeholder={`Pilih ${formik.values.party_type_option?.value ? formatTitleCase(formik.values.party_type_option.value as string) : 'jenis transaksi dahulu'}`}
|
||||
options={partyOptions}
|
||||
value={formik.values.party_id_option}
|
||||
onInputChange={setPartyInputValue}
|
||||
onMenuScrollToBottom={loadMorePartyOptions}
|
||||
onChange={(value) => {
|
||||
formik.setFieldValue('party_id_option', value);
|
||||
if (isResponseSuccess(partyRawData) && value) {
|
||||
@@ -241,7 +251,11 @@ const FormFinanceAdd = ({
|
||||
}
|
||||
required
|
||||
isClearable
|
||||
isDisabled={!formik.values.party_type_option?.value}
|
||||
isDisabled={
|
||||
!formik.values.party_type_option?.value ||
|
||||
(type === 'edit' &&
|
||||
formik.values.party_type_option.value == 'SUPPLIER')
|
||||
}
|
||||
/>
|
||||
<DateInput
|
||||
label='Tanggal'
|
||||
@@ -304,6 +318,8 @@ const FormFinanceAdd = ({
|
||||
: []
|
||||
}
|
||||
value={formik.values.bank_id_option}
|
||||
onInputChange={setBankInputValue}
|
||||
onMenuScrollToBottom={loadMoreBankOptions}
|
||||
onChange={(value) => {
|
||||
formik.setFieldValue('bank_id_option', value);
|
||||
}}
|
||||
@@ -389,6 +405,15 @@ const FormFinanceAdd = ({
|
||||
required
|
||||
/>
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
{serverErrorMessage && (
|
||||
<Alert color='error'>
|
||||
<Icon icon='mdi:alert' />
|
||||
{serverErrorMessage}
|
||||
<Button color='error' onClick={() => setServerErrorMessage('')}>
|
||||
<Icon icon='mdi:close' />
|
||||
</Button>
|
||||
</Alert>
|
||||
)}
|
||||
<div className='flex justify-center gap-4'>
|
||||
<Button
|
||||
type='reset'
|
||||
@@ -402,7 +427,7 @@ const FormFinanceAdd = ({
|
||||
<Button
|
||||
type='submit'
|
||||
className='w-min-24'
|
||||
disabled={formik.isSubmitting || !formik.isValid}
|
||||
disabled={formik.isSubmitting}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
|
||||
+1
-7
@@ -27,13 +27,7 @@ export const InitialBalanceFormSchema = Yup.object().shape({
|
||||
'Pihak wajib diisi',
|
||||
(value) => value !== null && value !== undefined
|
||||
),
|
||||
bank_id_option: Yup.mixed()
|
||||
.nullable()
|
||||
.test(
|
||||
'is-valid-option',
|
||||
'Bank wajib diisi',
|
||||
(value) => value !== null && value !== undefined
|
||||
),
|
||||
bank_id_option: Yup.mixed().nullable(),
|
||||
reference_number: Yup.string().required('Nomor referensi wajib diisi'),
|
||||
initial_balance_type_option: Yup.mixed()
|
||||
.nullable()
|
||||
|
||||
@@ -29,8 +29,9 @@ import { Bank } from '@/types/api/master-data/bank';
|
||||
import { Icon } from '@iconify/react';
|
||||
import { useFormik } from 'formik';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import Alert from '@/components/Alert';
|
||||
|
||||
interface FormFinanceAddInitialBalanceProps {
|
||||
type?: 'add' | 'edit';
|
||||
@@ -42,6 +43,7 @@ const FormFinanceAddInitialBalance = ({
|
||||
initialValues,
|
||||
}: FormFinanceAddInitialBalanceProps) => {
|
||||
const router = useRouter();
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState('');
|
||||
|
||||
// ===== Formik =====
|
||||
const formikInitialValues = useMemo((): InitialBalanceFormValues => {
|
||||
@@ -53,18 +55,18 @@ const FormFinanceAddInitialBalance = ({
|
||||
return {
|
||||
party_type_option:
|
||||
FINANCE_PARTY_TYPE_OPTIONS.find(
|
||||
(option) => option.value === initialValues?.party.type
|
||||
(option) => option.value === initialValues?.party?.type
|
||||
) || null,
|
||||
party_id_option: initialValues?.party
|
||||
? {
|
||||
label: initialValues.party.name,
|
||||
value: initialValues.party.id,
|
||||
label: initialValues.party?.name,
|
||||
value: initialValues.party?.id,
|
||||
}
|
||||
: null,
|
||||
bank_id_option: initialValues?.bank
|
||||
? {
|
||||
label: initialValues.bank.name,
|
||||
value: initialValues.bank.id,
|
||||
label: initialValues.bank?.name,
|
||||
value: initialValues.bank?.id,
|
||||
}
|
||||
: null,
|
||||
reference_number: initialValues?.reference_number || '',
|
||||
@@ -104,21 +106,25 @@ const FormFinanceAddInitialBalance = ({
|
||||
});
|
||||
|
||||
// ===== Options =====
|
||||
const { options: partyOptions, isLoadingOptions: isLoadingPartyOptions } =
|
||||
useSelect(
|
||||
formik.values.party_type_option?.value === 'CUSTOMER'
|
||||
? CustomerApi.basePath
|
||||
: SupplierApi.basePath,
|
||||
'id',
|
||||
'name',
|
||||
'',
|
||||
{ limit: 'limit' }
|
||||
);
|
||||
const {
|
||||
options: partyOptions,
|
||||
isLoadingOptions: isLoadingPartyOptions,
|
||||
setInputValue: setPartyInputValue,
|
||||
loadMore: loadMorePartyOptions,
|
||||
} = useSelect(
|
||||
formik.values.party_type_option?.value === 'CUSTOMER'
|
||||
? CustomerApi.basePath
|
||||
: SupplierApi.basePath,
|
||||
'id',
|
||||
'name'
|
||||
);
|
||||
const {
|
||||
options: bankOptions,
|
||||
rawData: bankRawData,
|
||||
isLoadingOptions: isLoadingBankOptions,
|
||||
} = useSelect<Bank>(BankApi.basePath, 'id', 'name', '', { limit: 'limit' });
|
||||
setInputValue: setBankInputValue,
|
||||
loadMore: loadMoreBankOptions,
|
||||
} = useSelect<Bank>(BankApi.basePath, 'id', 'name');
|
||||
|
||||
// ===== Helper Functions =====
|
||||
const transformFormValuesToPayload = (
|
||||
@@ -143,6 +149,7 @@ const FormFinanceAddInitialBalance = ({
|
||||
|
||||
if (isResponseError(response)) {
|
||||
toast.error(response.message);
|
||||
setServerErrorMessage(response.message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -162,6 +169,7 @@ const FormFinanceAddInitialBalance = ({
|
||||
|
||||
if (isResponseError(response)) {
|
||||
toast.error(response.message);
|
||||
setServerErrorMessage(response.message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -189,6 +197,8 @@ const FormFinanceAddInitialBalance = ({
|
||||
placeholder='Pilih jenis pihak'
|
||||
options={FINANCE_PARTY_TYPE_OPTIONS}
|
||||
value={formik.values.party_type_option}
|
||||
onInputChange={setPartyInputValue}
|
||||
onMenuScrollToBottom={loadMorePartyOptions}
|
||||
onChange={(value) => {
|
||||
formik.setFieldValue('party_type_option', value);
|
||||
formik.setFieldValue('party_id_option', null);
|
||||
@@ -205,6 +215,7 @@ const FormFinanceAddInitialBalance = ({
|
||||
: ''
|
||||
}
|
||||
required
|
||||
isDisabled={type === 'edit'}
|
||||
isClearable
|
||||
/>
|
||||
<SelectInput
|
||||
@@ -218,6 +229,8 @@ const FormFinanceAddInitialBalance = ({
|
||||
placeholder={`Pilih ${formik.values.party_type_option?.value ? formatTitleCase(formik.values.party_type_option.value as string) : 'jenis pihak dahulu'}`}
|
||||
options={partyOptions}
|
||||
value={formik.values.party_id_option}
|
||||
onInputChange={setPartyInputValue}
|
||||
onMenuScrollToBottom={loadMorePartyOptions}
|
||||
onChange={(value) => {
|
||||
formik.setFieldValue('party_id_option', value);
|
||||
}}
|
||||
@@ -232,7 +245,11 @@ const FormFinanceAddInitialBalance = ({
|
||||
}
|
||||
required
|
||||
isClearable
|
||||
isDisabled={!formik.values.party_type_option?.value}
|
||||
isDisabled={
|
||||
!formik.values.party_type_option?.value ||
|
||||
(type === 'edit' &&
|
||||
formik.values.party_type_option?.value == 'SUPPLIER')
|
||||
}
|
||||
/>
|
||||
<SelectInput
|
||||
label='Bank'
|
||||
@@ -269,7 +286,6 @@ const FormFinanceAddInitialBalance = ({
|
||||
? formik.errors.bank_id_option
|
||||
: ''
|
||||
}
|
||||
required
|
||||
isClearable
|
||||
/>
|
||||
<TextInput
|
||||
@@ -311,6 +327,7 @@ const FormFinanceAddInitialBalance = ({
|
||||
}
|
||||
required
|
||||
isClearable
|
||||
isDisabled={type == 'edit'}
|
||||
/>
|
||||
<NumberInput
|
||||
label='Nominal'
|
||||
@@ -354,7 +371,18 @@ const FormFinanceAddInitialBalance = ({
|
||||
}
|
||||
required
|
||||
/>
|
||||
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
{serverErrorMessage && (
|
||||
<Alert color='error'>
|
||||
<Icon icon='mdi:alert' />
|
||||
{serverErrorMessage}
|
||||
<Button color='error' onClick={() => setServerErrorMessage('')}>
|
||||
<Icon icon='mdi:close' />
|
||||
</Button>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className='flex justify-center gap-4'>
|
||||
<Button
|
||||
type='reset'
|
||||
@@ -368,7 +396,7 @@ const FormFinanceAddInitialBalance = ({
|
||||
<Button
|
||||
type='submit'
|
||||
className='w-min-24'
|
||||
disabled={formik.isSubmitting || !formik.isValid}
|
||||
disabled={formik.isSubmitting}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Yup from 'yup';
|
||||
export type InjectionFormValues = {
|
||||
bank_id_option: OptionType | null;
|
||||
adjustment_date: string;
|
||||
injection_type?: OptionType | null | undefined;
|
||||
nominal: string;
|
||||
note: string;
|
||||
};
|
||||
@@ -18,6 +19,7 @@ export const InjectionFormSchema = Yup.object<InjectionFormValues>({
|
||||
(value) => value !== null && value !== undefined
|
||||
),
|
||||
adjustment_date: Yup.string().required('Tanggal penyesuaian wajib diisi'),
|
||||
injection_type: Yup.mixed().nullable().required('Tipe injeksi wajib diisi'),
|
||||
nominal: Yup.string().required('Nominal wajib diisi'),
|
||||
note: Yup.string().required('Catatan wajib diisi'),
|
||||
});
|
||||
|
||||
@@ -24,8 +24,14 @@ import {
|
||||
import { Bank } from '@/types/api/master-data/bank';
|
||||
import { useFormik } from 'formik';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import Alert from '@/components/Alert';
|
||||
import { Icon } from '@iconify/react';
|
||||
import {
|
||||
FINANCE_INJECTION_STATUS,
|
||||
FINANCE_INJECTION_TYPE_OPTIONS,
|
||||
} from '@/config/constant';
|
||||
|
||||
interface FormFinanceInjectionProps {
|
||||
type?: 'add' | 'edit';
|
||||
@@ -37,17 +43,23 @@ const FormFinanceInjection = ({
|
||||
initialValues,
|
||||
}: FormFinanceInjectionProps) => {
|
||||
const router = useRouter();
|
||||
const [serverErrorMessage, setServerErrorMessage] = useState('');
|
||||
|
||||
// ===== Formik =====
|
||||
const formikInitialValues = useMemo((): InjectionFormValues => {
|
||||
return {
|
||||
bank_id_option: initialValues?.bank
|
||||
? {
|
||||
label: initialValues.bank.name,
|
||||
value: initialValues.bank.id,
|
||||
label: initialValues.bank?.name,
|
||||
value: initialValues.bank?.id,
|
||||
}
|
||||
: null,
|
||||
adjustment_date: initialValues?.payment_date || '',
|
||||
injection_type: initialValues?.nominal
|
||||
? initialValues.nominal < 0
|
||||
? FINANCE_INJECTION_TYPE_OPTIONS[1]
|
||||
: FINANCE_INJECTION_TYPE_OPTIONS[0]
|
||||
: FINANCE_INJECTION_TYPE_OPTIONS[0],
|
||||
nominal: initialValues?.nominal?.toString() || '',
|
||||
note: initialValues?.notes || '',
|
||||
};
|
||||
@@ -80,7 +92,9 @@ const FormFinanceInjection = ({
|
||||
options: bankOptions,
|
||||
rawData: bankRawData,
|
||||
isLoadingOptions: isLoadingBankOptions,
|
||||
} = useSelect<Bank>(BankApi.basePath, 'id', 'name', '', { limit: 'limit' });
|
||||
setInputValue: setBankInputValue,
|
||||
loadMore: loadMoreBankOptions,
|
||||
} = useSelect<Bank>(BankApi.basePath, 'id', 'name');
|
||||
|
||||
// ===== Helper Functions =====
|
||||
const transformFormValuesToPayload = (
|
||||
@@ -89,7 +103,10 @@ const FormFinanceInjection = ({
|
||||
return {
|
||||
bank_id: Number(values.bank_id_option?.value) || 0,
|
||||
adjustment_date: formatDate(values.adjustment_date, 'YYYY-MM-DD'),
|
||||
nominal: Number(values.nominal.replace(/\D/g, '')) || 0,
|
||||
nominal:
|
||||
values.injection_type?.value == 'POSITIVE'
|
||||
? Math.abs(Number(values.nominal))
|
||||
: -Math.abs(Number(values.nominal)),
|
||||
notes: values.note,
|
||||
};
|
||||
};
|
||||
@@ -101,6 +118,7 @@ const FormFinanceInjection = ({
|
||||
|
||||
if (isResponseError(response)) {
|
||||
toast.error(response.message);
|
||||
setServerErrorMessage(response.message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -117,6 +135,7 @@ const FormFinanceInjection = ({
|
||||
|
||||
if (isResponseError(response)) {
|
||||
toast.error(response.message);
|
||||
setServerErrorMessage(response.message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -162,6 +181,8 @@ const FormFinanceInjection = ({
|
||||
: []
|
||||
}
|
||||
value={formik.values.bank_id_option}
|
||||
onInputChange={setBankInputValue}
|
||||
onMenuScrollToBottom={loadMoreBankOptions}
|
||||
onChange={(value) => {
|
||||
formik.setFieldValue('bank_id_option', value);
|
||||
}}
|
||||
@@ -194,6 +215,24 @@ const FormFinanceInjection = ({
|
||||
}
|
||||
required
|
||||
/>
|
||||
<SelectInput
|
||||
label='Tipe Injeksi'
|
||||
placeholder='Pilih tipe injeksi'
|
||||
options={FINANCE_INJECTION_TYPE_OPTIONS}
|
||||
value={formik.values.injection_type}
|
||||
onChange={(value) => {
|
||||
formik.setFieldValue('injection_type', value);
|
||||
}}
|
||||
isError={Boolean(
|
||||
formik.touched.injection_type && formik.errors.injection_type
|
||||
)}
|
||||
errorMessage={
|
||||
formik.touched.injection_type && formik.errors.injection_type
|
||||
? formik.errors.injection_type
|
||||
: ''
|
||||
}
|
||||
required
|
||||
/>
|
||||
<NumberInput
|
||||
label='Nominal'
|
||||
placeholder='Masukkan nominal'
|
||||
@@ -207,8 +246,17 @@ const FormFinanceInjection = ({
|
||||
? formik.errors.nominal
|
||||
: ''
|
||||
}
|
||||
allowNegative={true}
|
||||
allowNegative={false}
|
||||
required
|
||||
startAdornment={
|
||||
formik.values.injection_type?.value === 'POSITIVE' ? (
|
||||
<Icon icon='mdi:plus' />
|
||||
) : formik.values.injection_type?.value === 'NEGATIVE' ? (
|
||||
<Icon icon='mdi:minus' />
|
||||
) : (
|
||||
''
|
||||
)
|
||||
}
|
||||
/>
|
||||
<TextArea
|
||||
label='Catatan'
|
||||
@@ -226,6 +274,15 @@ const FormFinanceInjection = ({
|
||||
required
|
||||
/>
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
{serverErrorMessage && (
|
||||
<Alert color='error'>
|
||||
<Icon icon='mdi:alert' />
|
||||
{serverErrorMessage}
|
||||
<Button color='error' onClick={() => setServerErrorMessage('')}>
|
||||
<Icon icon='mdi:close' />
|
||||
</Button>
|
||||
</Alert>
|
||||
)}
|
||||
<div className='flex justify-center gap-4'>
|
||||
<Button
|
||||
type='reset'
|
||||
@@ -239,7 +296,7 @@ const FormFinanceInjection = ({
|
||||
<Button
|
||||
type='submit'
|
||||
className='w-min-24'
|
||||
disabled={formik.isSubmitting || !formik.isValid}
|
||||
disabled={formik.isSubmitting}
|
||||
>
|
||||
Submit
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { isResponseError } from '@/lib/api-helper';
|
||||
import { InventoryAdjustmentApi } from '@/services/api/inventory';
|
||||
import {
|
||||
CreateInventoryAdjustmentPayload,
|
||||
@@ -22,12 +22,18 @@ import {
|
||||
} from '@/services/api/master-data';
|
||||
import Button from '@/components/Button';
|
||||
import { Icon } from '@iconify/react';
|
||||
import SelectInput, { OptionType } from '@/components/input/SelectInput';
|
||||
import SelectInput, {
|
||||
OptionType,
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import TextInput from '@/components/input/TextInput';
|
||||
import { RadioGroup } from '@/components/input/RadioInput';
|
||||
import TextArea from '@/components/input/TextArea';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import { ProductCategory } from '@/types/api/master-data/product-category';
|
||||
import { Product } from '@/types/api/master-data/product';
|
||||
import { Warehouse } from '@/types/api/master-data/warehouse';
|
||||
|
||||
interface InventoryAdjustmentFormProps {
|
||||
type?: 'add' | 'edit' | 'detail';
|
||||
@@ -44,10 +50,7 @@ const InventoryAdjustmentForm = ({
|
||||
InventoryAdjustmentFormErrorMessage,
|
||||
setInventoryAdjustmentFormErrorMessage,
|
||||
] = useState('');
|
||||
const [selectedProductCategories, setSelectedProductCategories] =
|
||||
useState('');
|
||||
const [disabledProduct, setDisabledProduct] = useState(true);
|
||||
const [optionsProduct, setOptionsProduct] = useState<OptionType[]>([]);
|
||||
const [quantityLabel, setQuantityLabel] = useState('Tambah Stok');
|
||||
|
||||
// Submit Handler
|
||||
@@ -108,45 +111,30 @@ const InventoryAdjustmentForm = ({
|
||||
});
|
||||
|
||||
// Fetch Data
|
||||
const productCategoriesUrl = `${
|
||||
ProductCategoryApi.basePath
|
||||
}?${new URLSearchParams({
|
||||
search: '',
|
||||
}).toString()}`;
|
||||
const { data: productCategories, isLoading: isLoadingProductCategories } =
|
||||
useSWR(productCategoriesUrl, ProductCategoryApi.getAllFetcher);
|
||||
const {
|
||||
setInputValue: setProductCategoryInputValue,
|
||||
options: productCategoryOptions,
|
||||
isLoadingOptions: isLoadingProductCategoryOptions,
|
||||
loadMore: loadMoreProductCategories,
|
||||
} = useSelect<ProductCategory>(ProductCategoryApi.basePath, 'id', 'name');
|
||||
|
||||
const productUrl = `${ProductApi.basePath}?${new URLSearchParams({
|
||||
search: '',
|
||||
product_category_id: selectedProductCategories,
|
||||
}).toString()}`;
|
||||
const { data: products, isLoading: isLoadingProducts } = useSWR(
|
||||
productUrl,
|
||||
ProductApi.getAllFetcher
|
||||
);
|
||||
const {
|
||||
setInputValue: setProductInputValue,
|
||||
options: productOptions,
|
||||
isLoadingOptions: isLoadingProductOptions,
|
||||
loadMore: loadMoreProducts,
|
||||
} = useSelect<Product>(ProductApi.basePath, 'id', 'name', 'search', {
|
||||
product_category_id: formik.values.product_category_id
|
||||
? String(formik.values.product_category_id)
|
||||
: '',
|
||||
});
|
||||
|
||||
const warehouseUrl = `${WarehouseApi.basePath}?${new URLSearchParams({
|
||||
search: '',
|
||||
limit: '100',
|
||||
}).toString()}`;
|
||||
const { data: warehouses, isLoading: isLoadingWarehouses } = useSWR(
|
||||
warehouseUrl,
|
||||
WarehouseApi.getAllFetcher
|
||||
);
|
||||
|
||||
// Map Data to Options
|
||||
const optionsProductCategory = isResponseSuccess(productCategories)
|
||||
? productCategories?.data.map((productCategory) => ({
|
||||
value: productCategory.id,
|
||||
label: productCategory.name,
|
||||
}))
|
||||
: [];
|
||||
const optionsWarehouse = isResponseSuccess(warehouses)
|
||||
? warehouses?.data.map((warehouse) => ({
|
||||
value: warehouse.id,
|
||||
label: warehouse.name,
|
||||
}))
|
||||
: [];
|
||||
const {
|
||||
setInputValue: setWarehouseInputValue,
|
||||
options: warehouseOptions,
|
||||
isLoadingOptions: isLoadingWarehouseOptions,
|
||||
loadMore: loadMoreWarehouses,
|
||||
} = useSelect<Warehouse>(WarehouseApi.basePath, 'id', 'name');
|
||||
|
||||
// Options Handler
|
||||
const productCategoryChangeHandler = (
|
||||
@@ -157,7 +145,6 @@ const InventoryAdjustmentForm = ({
|
||||
|
||||
formik.setFieldValue('product_category', val);
|
||||
|
||||
setSelectedProductCategories((val as OptionType)?.value as string);
|
||||
const disabled = (val as OptionType)?.value == null;
|
||||
setDisabledProduct(disabled);
|
||||
formik.setFieldValue('product_id', 0);
|
||||
@@ -193,9 +180,6 @@ const InventoryAdjustmentForm = ({
|
||||
// Effect
|
||||
useEffect(() => {
|
||||
if (initialValues?.product_warehouse?.product?.id) {
|
||||
setSelectedProductCategories(
|
||||
String(initialValues.product_warehouse.product.id)
|
||||
);
|
||||
setDisabledProduct(false);
|
||||
formik.setFieldValue(
|
||||
'product_id',
|
||||
@@ -219,25 +203,10 @@ const InventoryAdjustmentForm = ({
|
||||
);
|
||||
formik.setFieldValue('note', initialValues.note);
|
||||
}
|
||||
}, [
|
||||
formik,
|
||||
initialValues,
|
||||
setQuantityLabel,
|
||||
setDisabledProduct,
|
||||
setSelectedProductCategories,
|
||||
]);
|
||||
}, [formik, initialValues, setQuantityLabel, setDisabledProduct]);
|
||||
useEffect(() => {
|
||||
formikSetValues(formikInitialValues as InventoryAdjustmentFormValues);
|
||||
}, [formikSetValues, formikInitialValues]);
|
||||
useEffect(() => {
|
||||
if (isResponseSuccess(products)) {
|
||||
const options = products.data.map((p) => ({
|
||||
value: p.id,
|
||||
label: p.name,
|
||||
}));
|
||||
setOptionsProduct(options);
|
||||
}
|
||||
}, [products]);
|
||||
|
||||
// Utils Function
|
||||
const formatNumber = (value: string) => {
|
||||
@@ -282,9 +251,10 @@ const InventoryAdjustmentForm = ({
|
||||
label='Kategori Produk'
|
||||
value={formik.values.product_category as OptionType}
|
||||
onChange={productCategoryChangeHandler}
|
||||
onInputChange={setSelectedProductCategories}
|
||||
options={optionsProductCategory}
|
||||
isLoading={isLoadingProductCategories}
|
||||
onInputChange={setProductCategoryInputValue}
|
||||
options={productCategoryOptions}
|
||||
onMenuScrollToBottom={loadMoreProductCategories}
|
||||
isLoading={isLoadingProductCategoryOptions}
|
||||
isError={
|
||||
formik.touched.product_category &&
|
||||
Boolean(formik.errors.product_category)
|
||||
@@ -300,8 +270,10 @@ const InventoryAdjustmentForm = ({
|
||||
label='Produk'
|
||||
value={formik.values.product as OptionType}
|
||||
onChange={productChangeHandler}
|
||||
options={optionsProduct}
|
||||
isLoading={isLoadingProducts}
|
||||
onInputChange={setProductInputValue}
|
||||
options={productOptions}
|
||||
onMenuScrollToBottom={loadMoreProducts}
|
||||
isLoading={isLoadingProductOptions}
|
||||
isError={formik.touched.product && Boolean(formik.errors.product)}
|
||||
errorMessage={formik.errors.product as string}
|
||||
isDisabled={type === 'detail' || disabledProduct}
|
||||
@@ -314,8 +286,10 @@ const InventoryAdjustmentForm = ({
|
||||
label='Warehouse'
|
||||
value={formik.values.warehouse as OptionType}
|
||||
onChange={warehouseChangeHandler}
|
||||
options={optionsWarehouse}
|
||||
isLoading={isLoadingWarehouses}
|
||||
onInputChange={setWarehouseInputValue}
|
||||
options={warehouseOptions}
|
||||
onMenuScrollToBottom={loadMoreWarehouses}
|
||||
isLoading={isLoadingWarehouseOptions}
|
||||
isError={
|
||||
formik.touched.warehouse && Boolean(formik.errors.warehouse)
|
||||
}
|
||||
|
||||
@@ -27,17 +27,17 @@ type MovementFormSchemaType = {
|
||||
product_qty: number | string;
|
||||
}[];
|
||||
deliveries: {
|
||||
delivery_cost?: number | string;
|
||||
delivery_cost_per_item?: number | string;
|
||||
delivery_cost?: number | string | null;
|
||||
delivery_cost_per_item?: number | string | null;
|
||||
document?: File | MovementDocument | null;
|
||||
document_path?: string | null;
|
||||
driver_name: string;
|
||||
vehicle_plate: string;
|
||||
driver_name?: string | null;
|
||||
vehicle_plate?: string | null;
|
||||
supplier?: {
|
||||
value: number;
|
||||
label: string;
|
||||
} | null;
|
||||
supplier_id: number;
|
||||
supplier_id?: number | null;
|
||||
products: {
|
||||
product?: {
|
||||
value: number;
|
||||
@@ -59,17 +59,17 @@ export type ProductSchema = {
|
||||
};
|
||||
|
||||
export type DeliverySchema = {
|
||||
delivery_cost?: number | string;
|
||||
delivery_cost_per_item?: number | string;
|
||||
delivery_cost?: number | string | null;
|
||||
delivery_cost_per_item?: number | string | null;
|
||||
document?: File | MovementDocument | null;
|
||||
document_path?: string | null;
|
||||
driver_name: string;
|
||||
vehicle_plate: string;
|
||||
driver_name?: string | null;
|
||||
vehicle_plate?: string | null;
|
||||
supplier?: {
|
||||
value: number;
|
||||
label: string;
|
||||
} | null;
|
||||
supplier_id: number;
|
||||
supplier_id?: number | null;
|
||||
products: {
|
||||
product?: {
|
||||
value: number;
|
||||
@@ -110,48 +110,82 @@ const DeliveryProductObjectSchema = Yup.object({
|
||||
.typeError('Qty harus berupa angka!'),
|
||||
});
|
||||
|
||||
const DeliveryDocumentSchema = Yup.mixed<File | MovementDocument>()
|
||||
.nullable()
|
||||
.test('fileSize', 'Ukuran dokumen maksimal 5 MB', (value): boolean => {
|
||||
if (!value) return true;
|
||||
if (value instanceof File) return value.size <= 5 * 1024 * 1024;
|
||||
return true;
|
||||
});
|
||||
|
||||
const DeliveryObjectSchema: Yup.ObjectSchema<DeliverySchema> = Yup.object({
|
||||
delivery_cost: Yup.number()
|
||||
.transform((value) => (isNaN(value) || value === 0 ? undefined : value))
|
||||
.min(1, 'Biaya minimal 1!')
|
||||
.typeError('Biaya harus berupa angka!')
|
||||
.test('one-of-cost-fields', 'Wajib diisi salah satu!', function (value) {
|
||||
const { delivery_cost_per_item } = this.parent;
|
||||
return (
|
||||
(value !== undefined && value > 0) ||
|
||||
(delivery_cost_per_item !== undefined && delivery_cost_per_item > 0)
|
||||
);
|
||||
.transform((value) =>
|
||||
isNaN(value) || value === '' || value === null ? undefined : value
|
||||
)
|
||||
.when('supplier_id', {
|
||||
is: (supplier_id: number | null | undefined) =>
|
||||
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
|
||||
then: (schema) =>
|
||||
schema
|
||||
.required('Biaya pengiriman wajib diisi!')
|
||||
.min(1, 'Biaya minimal 1!')
|
||||
.typeError('Biaya harus berupa angka!'),
|
||||
otherwise: (schema) =>
|
||||
schema
|
||||
.optional()
|
||||
.nullable()
|
||||
.min(1, 'Biaya minimal 1!')
|
||||
.typeError('Biaya harus berupa angka!'),
|
||||
}),
|
||||
delivery_cost_per_item: Yup.number()
|
||||
.transform((value) => (isNaN(value) || value === 0 ? undefined : value))
|
||||
.min(1, 'Biaya per item minimal 1!')
|
||||
.typeError('Biaya per item harus berupa angka!')
|
||||
.test('one-of-cost-fields', 'Wajib diisi salah satu!', function (value) {
|
||||
const { delivery_cost } = this.parent;
|
||||
return (
|
||||
(value !== undefined && value > 0) ||
|
||||
(delivery_cost !== undefined && delivery_cost > 0)
|
||||
);
|
||||
.transform((value) =>
|
||||
isNaN(value) || value === '' || value === null ? undefined : value
|
||||
)
|
||||
.when('supplier_id', {
|
||||
is: (supplier_id: number | null | undefined) =>
|
||||
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
|
||||
then: (schema) =>
|
||||
schema
|
||||
.required('Biaya per item wajib diisi!')
|
||||
.min(1, 'Biaya per item minimal 1!')
|
||||
.typeError('Biaya per item harus berupa angka!'),
|
||||
otherwise: (schema) =>
|
||||
schema
|
||||
.optional()
|
||||
.nullable()
|
||||
.min(1, 'Biaya per item minimal 1!')
|
||||
.typeError('Biaya per item harus berupa angka!'),
|
||||
}),
|
||||
document_path: Yup.string().nullable().optional(),
|
||||
document_index: Yup.number().optional(),
|
||||
document: Yup.mixed<File | MovementDocument>()
|
||||
.nullable()
|
||||
.test('fileSize', 'Ukuran dokumen maksimal 5 MB', (value) => {
|
||||
if (!value) return true;
|
||||
if (value instanceof File) return value.size <= 5 * 1024 * 1024;
|
||||
return true;
|
||||
}),
|
||||
driver_name: Yup.string().required('Nama sopir wajib diisi!'),
|
||||
vehicle_plate: Yup.string().required('Plat nomor wajib diisi!'),
|
||||
document: DeliveryDocumentSchema,
|
||||
driver_name: Yup.string().when('supplier_id', {
|
||||
is: (supplier_id: number | null | undefined) =>
|
||||
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
|
||||
then: (schema) =>
|
||||
schema
|
||||
.required('Nama sopir wajib diisi!')
|
||||
.min(1, 'Nama sopir wajib diisi!'),
|
||||
otherwise: (schema) => schema.optional().nullable(),
|
||||
}),
|
||||
vehicle_plate: Yup.string().when('supplier_id', {
|
||||
is: (supplier_id: number | null | undefined) =>
|
||||
supplier_id !== null && supplier_id !== undefined && supplier_id > 0,
|
||||
then: (schema) =>
|
||||
schema
|
||||
.required('Plat nomor wajib diisi!')
|
||||
.min(1, 'Plat nomor wajib diisi!'),
|
||||
otherwise: (schema) => schema.optional().nullable(),
|
||||
}),
|
||||
supplier: Yup.object({
|
||||
value: Yup.number().min(1).required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
supplier_id: Yup.number()
|
||||
.required('Supplier wajib diisi!')
|
||||
.min(1, 'Supplier wajib diisi!')
|
||||
.typeError('Supplier wajib diisi!'),
|
||||
.optional()
|
||||
.nullable()
|
||||
.typeError('Supplier harus berupa angka!'),
|
||||
products: Yup.array()
|
||||
.of(DeliveryProductObjectSchema)
|
||||
.min(1, 'Minimal harus ada 1 produk!')
|
||||
@@ -277,12 +311,12 @@ export const getMovementFormInitialValues = (
|
||||
}) ?? [],
|
||||
})) ?? [
|
||||
{
|
||||
delivery_cost: undefined,
|
||||
delivery_cost_per_item: undefined,
|
||||
delivery_cost: null,
|
||||
delivery_cost_per_item: null,
|
||||
document: null,
|
||||
document_path: null,
|
||||
driver_name: '',
|
||||
vehicle_plate: '',
|
||||
driver_name: null,
|
||||
vehicle_plate: null,
|
||||
supplier: null,
|
||||
supplier_id: 0,
|
||||
products: [
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -91,7 +91,7 @@ const InventoryProductDetail = ({
|
||||
<td>:</td>
|
||||
<td>
|
||||
{inventoryProduct?.tax
|
||||
? formatCurrency(inventoryProduct?.tax)
|
||||
? formatNumber(inventoryProduct?.tax) + '%'
|
||||
: '-'}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -16,7 +16,7 @@ import { TableRowSizeSelector } from '@/components/table/TableRowSizeSelector';
|
||||
import { TableToolbar } from '@/components/table/TableToolbar';
|
||||
import { ROWS_OPTIONS } from '@/config/constant';
|
||||
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/helper';
|
||||
import { cn, formatCurrency, formatDate, formatTitleCase } from '@/lib/helper';
|
||||
import {
|
||||
MarketingApi,
|
||||
SalesOrderApi,
|
||||
@@ -33,6 +33,7 @@ import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import { useAuth } from '@/services/hooks/useAuth';
|
||||
import { CustomerApi, ProductApi } from '@/services/api/master-data';
|
||||
import { MARKETING_APPROVAL_LINE } from '@/config/approval-line';
|
||||
import Badge from '@/components/Badge';
|
||||
|
||||
const RowsOptionsMenu = ({
|
||||
type = 'dropdown',
|
||||
@@ -184,12 +185,16 @@ const MarketingTable = () => {
|
||||
const {
|
||||
options: productsOptions,
|
||||
isLoadingOptions: isLoadingProductsOptions,
|
||||
setInputValue: setProductsInputValue,
|
||||
loadMore: loadMoreProducts,
|
||||
} = useSelect(ProductApi.basePath, 'id', 'name', '', {
|
||||
limit: 'limit',
|
||||
});
|
||||
const {
|
||||
options: customersOptions,
|
||||
isLoadingOptions: isLoadingCustomersOptions,
|
||||
setInputValue: setCustomersInputValue,
|
||||
loadMore: loadMoreCustomers,
|
||||
} = useSelect(CustomerApi.basePath, 'id', 'name', '', {
|
||||
limit: 'limit',
|
||||
});
|
||||
@@ -400,6 +405,8 @@ const MarketingTable = () => {
|
||||
.join(',') || ''
|
||||
)
|
||||
}
|
||||
onInputChange={setProductsInputValue}
|
||||
onMenuScrollToBottom={loadMoreProducts}
|
||||
isMulti
|
||||
/>
|
||||
{/* select status */}
|
||||
@@ -444,6 +451,8 @@ const MarketingTable = () => {
|
||||
(value as OptionType)?.value.toString() || ''
|
||||
)
|
||||
}
|
||||
onInputChange={setCustomersInputValue}
|
||||
onMenuScrollToBottom={loadMoreCustomers}
|
||||
/>
|
||||
</TableRowSizeSelector>
|
||||
</div>
|
||||
@@ -512,8 +521,53 @@ const MarketingTable = () => {
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'latest_approval.step_name',
|
||||
accessorKey: 'approval.step_name',
|
||||
header: 'Status',
|
||||
cell: (props) => {
|
||||
const approval = props.row.original.latest_approval;
|
||||
const isRejected = approval?.action == 'REJECTED';
|
||||
const isApproved = approval?.action == 'APPROVED';
|
||||
return (
|
||||
<Badge
|
||||
variant='soft'
|
||||
className={{
|
||||
badge:
|
||||
'rounded-lg px-2 w-full flex flex-row justify-start whitespace-nowrap',
|
||||
}}
|
||||
color={
|
||||
isRejected
|
||||
? 'error'
|
||||
: isApproved
|
||||
? approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
: 'neutral'
|
||||
: 'neutral'
|
||||
}
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:circle'
|
||||
width={12}
|
||||
height={12}
|
||||
color={
|
||||
approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
: 'neutral'
|
||||
}
|
||||
/>
|
||||
{isRejected
|
||||
? 'Ditolak'
|
||||
: formatTitleCase(approval?.step_name || '')}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: 'customer.name',
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
formatCurrency,
|
||||
formatDate,
|
||||
formatNumber,
|
||||
formatTitleCase,
|
||||
formatVechicleNumber,
|
||||
} from '@/lib/helper';
|
||||
import {
|
||||
@@ -34,6 +35,7 @@ import toast from 'react-hot-toast';
|
||||
import SalesOrderExport from '@/components/pages/marketing/pdf/SalesOrderExport';
|
||||
import DeliveryOrderExport from '@/components/pages/marketing/pdf/DeliveryOrderExport';
|
||||
import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import Badge from '@/components/Badge';
|
||||
|
||||
const MarketingDetail = ({
|
||||
initialValues,
|
||||
@@ -87,7 +89,6 @@ const MarketingDetail = ({
|
||||
deleteModal.closeModal();
|
||||
router.push('/marketing');
|
||||
toast.success(res?.message as string);
|
||||
refresh?.();
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
@@ -121,6 +122,10 @@ const MarketingDetail = ({
|
||||
);
|
||||
};
|
||||
|
||||
const approval = initialValues?.latest_approval;
|
||||
const isRejected = approval?.action == 'REJECTED';
|
||||
const isApproved = approval?.action == 'APPROVED';
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='flex flex-col w-full gap-4'>
|
||||
@@ -230,7 +235,46 @@ const MarketingDetail = ({
|
||||
<tr>
|
||||
<td className='font-semibold'>Status</td>
|
||||
<td>:</td>
|
||||
<td>{initialValues?.latest_approval?.step_name}</td>
|
||||
<td>
|
||||
<Badge
|
||||
variant='soft'
|
||||
className={{
|
||||
badge:
|
||||
'rounded-lg px-2 w-fit flex flex-row justify-start whitespace-nowrap',
|
||||
}}
|
||||
color={
|
||||
isRejected
|
||||
? 'error'
|
||||
: isApproved
|
||||
? approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
: 'neutral'
|
||||
: 'neutral'
|
||||
}
|
||||
>
|
||||
<Icon
|
||||
icon='mdi:circle'
|
||||
width={12}
|
||||
height={12}
|
||||
color={
|
||||
approval?.step_number == 1
|
||||
? 'neutral'
|
||||
: approval?.step_number == 2
|
||||
? 'primary'
|
||||
: approval?.step_number == 3
|
||||
? 'success'
|
||||
: 'neutral'
|
||||
}
|
||||
/>
|
||||
{isRejected
|
||||
? 'Ditolak'
|
||||
: formatTitleCase(approval?.step_name || '')}
|
||||
</Badge>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td className='font-semibold'>Tanggal Penjualan</td>
|
||||
|
||||
@@ -11,6 +11,13 @@ import {
|
||||
type MarketingSchemaType = {
|
||||
customer_id: number | undefined;
|
||||
sales_person_id: number | undefined;
|
||||
sales_person:
|
||||
| {
|
||||
value: number;
|
||||
label: string;
|
||||
}
|
||||
| undefined
|
||||
| null;
|
||||
customer:
|
||||
| {
|
||||
value: number;
|
||||
@@ -33,7 +40,11 @@ type DeliveryOrderSchemaType = {
|
||||
export const SalesOrderSchema: Yup.ObjectSchema<SalesOrderSchemaType> =
|
||||
Yup.object({
|
||||
customer_id: Yup.number().required('Customer wajib diisi!'),
|
||||
sales_person_id: Yup.number().required('Sales Person wajib diisi!'),
|
||||
sales_person_id: Yup.number().required('Sales wajib diisi!'),
|
||||
sales_person: Yup.object({
|
||||
value: Yup.number().required(),
|
||||
label: Yup.string().required(),
|
||||
}).nullable(),
|
||||
customer: Yup.object({
|
||||
value: Yup.number().required(),
|
||||
label: Yup.string().required(),
|
||||
|
||||
@@ -50,6 +50,8 @@ import { DeliveryOrderProductFormValues } from '@/components/pages/marketing/for
|
||||
import RequirePermission from '@/components/helper/RequirePermission';
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import { CreatedUser } from '@/types/api/api-general';
|
||||
import { UserApi } from '@/services/api/user';
|
||||
|
||||
const MemoizedSalesOrderProductTable = memo(SalesOrderProductTable);
|
||||
const MemoizedSalesOrderProductForm = memo(SalesOrderProductForm);
|
||||
@@ -244,7 +246,15 @@ const MarketingForm = ({
|
||||
const {
|
||||
options: customerOptions,
|
||||
isLoadingOptions: isLoadingCustomerOptions,
|
||||
setInputValue: setInputCustomerValue,
|
||||
loadMore: loadMoreCustomer,
|
||||
} = useSelect<Customer>(CustomerApi.basePath, 'id', 'name');
|
||||
const {
|
||||
options: salesOptions,
|
||||
isLoadingOptions: isLoadingSalesOptions,
|
||||
setInputValue: setInputSalesValue,
|
||||
loadMore: loadMoreSales,
|
||||
} = useSelect<CreatedUser>(UserApi.basePath, 'id', 'name');
|
||||
|
||||
// ================== SETUP FORMIK ==================
|
||||
const formikInitialValues = useMemo<
|
||||
@@ -255,6 +265,12 @@ const MarketingForm = ({
|
||||
notes: initialValues?.notes || undefined,
|
||||
customer_id: initialValues?.customer?.id || undefined,
|
||||
sales_person_id: initialValues?.sales_person?.id || 1,
|
||||
sales_person: initialValues?.sales_person
|
||||
? {
|
||||
value: initialValues.sales_person.id,
|
||||
label: initialValues.sales_person.name,
|
||||
}
|
||||
: null,
|
||||
customer: initialValues?.customer
|
||||
? {
|
||||
value: initialValues.customer.id,
|
||||
@@ -345,6 +361,8 @@ const MarketingForm = ({
|
||||
},
|
||||
});
|
||||
|
||||
const memoSalesOrder = formik.values.sales_order;
|
||||
|
||||
// ================== FORM REPEATER HANDLER ==================
|
||||
const createMarketingHandler = async (values: CreateSalesOrderPayload) => {
|
||||
setIsLoading(true);
|
||||
@@ -443,18 +461,37 @@ const MarketingForm = ({
|
||||
},
|
||||
[]
|
||||
);
|
||||
const handleChangeSalesPerson = useCallback(
|
||||
(val: OptionType | OptionType[] | null) => {
|
||||
formik.setFieldValue('sales_person_id', (val as OptionType)?.value);
|
||||
formik.setFieldValue('sales_person', val as OptionType);
|
||||
},
|
||||
[]
|
||||
);
|
||||
const handleDelete = useCallback(() => {
|
||||
deleteModal.openModal();
|
||||
}, [deleteModal]);
|
||||
|
||||
// ================== SALES ORDER HANDLER ==================
|
||||
const handleDeleteSO = useCallback((id: number) => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
formik.setFieldValue(
|
||||
'sales_order',
|
||||
currentProducts.filter((p) => p.id != id)
|
||||
);
|
||||
}, []);
|
||||
const handleDeleteSO = useCallback(
|
||||
(id: number) => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
formik.setFieldValue(
|
||||
'sales_order',
|
||||
currentProducts.filter((p) => p.id != id)
|
||||
);
|
||||
},
|
||||
[memoSalesOrder]
|
||||
);
|
||||
const handleEditSO = useCallback(
|
||||
(id: number) => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
const selectedProduct = currentProducts.find((p) => p.id == id);
|
||||
setSelectedMarketingProduct(selectedProduct ?? null);
|
||||
addSOModal.openModal();
|
||||
},
|
||||
[memoSalesOrder]
|
||||
);
|
||||
const handleBulkDeleteSO = useCallback(() => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
formik.setFieldValue(
|
||||
@@ -464,13 +501,13 @@ const MarketingForm = ({
|
||||
)
|
||||
);
|
||||
setRowSOSelection({});
|
||||
}, [selectedRowSOIds]);
|
||||
}, [selectedRowSOIds, memoSalesOrder]);
|
||||
const handleAddSOClick = useCallback(() => {
|
||||
setSelectedMarketingProduct(null);
|
||||
addSOModal.openModal();
|
||||
}, [addSOModal]);
|
||||
const handleAddSubmitSO = useCallback(
|
||||
async (values: SalesOrderProductFormValues) => {
|
||||
async (values: SalesOrderProductFormValues, id?: number) => {
|
||||
const currentProducts = formik.values.sales_order;
|
||||
|
||||
const newValues = {
|
||||
@@ -478,18 +515,12 @@ const MarketingForm = ({
|
||||
id: values.id ?? Date.now(),
|
||||
};
|
||||
|
||||
const existingIndex = currentProducts.findIndex(
|
||||
(item) =>
|
||||
item.kandang_id === newValues.kandang_id &&
|
||||
item.product_warehouse_id === newValues.product_warehouse_id
|
||||
);
|
||||
|
||||
let updatedProducts = [];
|
||||
|
||||
if (existingIndex !== -1) {
|
||||
if (id) {
|
||||
// Overwrite
|
||||
updatedProducts = currentProducts.map((item, index) =>
|
||||
index === existingIndex ? newValues : item
|
||||
updatedProducts = currentProducts.map((item) =>
|
||||
item.id === id ? newValues : item
|
||||
);
|
||||
} else {
|
||||
// Add new item
|
||||
@@ -500,7 +531,7 @@ const MarketingForm = ({
|
||||
|
||||
addSOModal.closeModal();
|
||||
},
|
||||
[addSOModal]
|
||||
[addSOModal, memoSalesOrder]
|
||||
);
|
||||
|
||||
// ================== DELIVERY ORDER HANDLER ==================
|
||||
@@ -545,8 +576,30 @@ const MarketingForm = ({
|
||||
},
|
||||
[addDOModal]
|
||||
);
|
||||
|
||||
const memoSalesOrder = formik.values.sales_order;
|
||||
const handleDeleteDO = useCallback(
|
||||
async (id: number) => {
|
||||
setDeliveryOrderValues((prev) =>
|
||||
prev.map((product) =>
|
||||
product.id === id
|
||||
? {
|
||||
...product,
|
||||
...{
|
||||
unit_price: '',
|
||||
total_weight: '',
|
||||
qty: '',
|
||||
avg_weight: '',
|
||||
total_price: '',
|
||||
delivery_date: '',
|
||||
},
|
||||
}
|
||||
: product
|
||||
)
|
||||
);
|
||||
addDOModal.closeModal();
|
||||
setSelectedDeliveryProduct(null);
|
||||
},
|
||||
[addDOModal]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
formik.setFieldValue('delivery_order', deliveryOrderValues);
|
||||
@@ -580,6 +633,7 @@ const MarketingForm = ({
|
||||
className={{
|
||||
wrapper: 'bg-white w-full',
|
||||
}}
|
||||
variant='bordered'
|
||||
>
|
||||
<div className='grid sm:grid-cols-2 gap-3 mt-3'>
|
||||
<SelectInput
|
||||
@@ -588,6 +642,8 @@ const MarketingForm = ({
|
||||
isLoading={isLoadingCustomerOptions}
|
||||
value={formik.values.customer}
|
||||
onChange={handleChangeCustomer}
|
||||
onInputChange={setInputCustomerValue}
|
||||
onMenuScrollToBottom={loadMoreCustomer}
|
||||
isError={
|
||||
formik.touched.customer_id && Boolean(formik.errors.customer_id)
|
||||
}
|
||||
@@ -595,7 +651,9 @@ const MarketingForm = ({
|
||||
isClearable
|
||||
placeholder='Pilih Pelanggan'
|
||||
isDisabled={
|
||||
formType === 'add_deliver' || formType === 'edit_deliver'
|
||||
formType === 'add_deliver' ||
|
||||
formType === 'edit_deliver' ||
|
||||
formType === 'edit'
|
||||
}
|
||||
/>
|
||||
<DateInput
|
||||
@@ -617,6 +675,7 @@ const MarketingForm = ({
|
||||
className={{
|
||||
wrapper: 'bg-white w-full',
|
||||
}}
|
||||
variant='bordered'
|
||||
>
|
||||
<MemoizedSalesOrderProductTable
|
||||
formType={formType}
|
||||
@@ -625,6 +684,7 @@ const MarketingForm = ({
|
||||
setRowSelection={setRowSOSelection}
|
||||
selectedRowIds={selectedRowSOIds}
|
||||
onDelete={handleDeleteSO}
|
||||
onEdit={handleEditSO}
|
||||
onBulkDelete={handleBulkDeleteSO}
|
||||
onAddProductClick={handleAddSOClick}
|
||||
/>
|
||||
@@ -644,6 +704,7 @@ const MarketingForm = ({
|
||||
formType={formType}
|
||||
data={deliveryOrderValues}
|
||||
onEdit={handleEditDO}
|
||||
onDelete={handleDeleteDO}
|
||||
onAddProductClick={handleAddDOClick}
|
||||
/>
|
||||
</Card>
|
||||
@@ -651,19 +712,42 @@ const MarketingForm = ({
|
||||
|
||||
{/* Input Notes */}
|
||||
<div className='grid sm:grid-cols-2 gap-3'>
|
||||
<DebouncedTextArea
|
||||
required
|
||||
name='notes'
|
||||
label='Catatan'
|
||||
rows={3}
|
||||
placeholder='Masukan catatan penjualan'
|
||||
value={formik.values.notes}
|
||||
onChange={formik.handleChange}
|
||||
isError={formik.touched.notes && Boolean(formik.errors.notes)}
|
||||
errorMessage={formik.errors.notes}
|
||||
disabled={formType === 'add_deliver' || formType === 'edit_deliver'}
|
||||
/>
|
||||
<div className='flex flex-col h-full justify-between items-end py-6'>
|
||||
<div className='flex flex-col h-full items-end gap-3'>
|
||||
<SelectInput
|
||||
label='Sales'
|
||||
options={salesOptions}
|
||||
isLoading={isLoadingSalesOptions}
|
||||
value={formik.values.sales_person}
|
||||
onChange={handleChangeSalesPerson}
|
||||
onInputChange={setInputSalesValue}
|
||||
onMenuScrollToBottom={loadMoreSales}
|
||||
isError={
|
||||
formik.touched.sales_person_id &&
|
||||
Boolean(formik.errors.sales_person_id)
|
||||
}
|
||||
errorMessage={formik.errors.sales_person_id}
|
||||
isClearable
|
||||
placeholder='Pilih Sales'
|
||||
isDisabled={
|
||||
formType === 'add_deliver' || formType === 'edit_deliver'
|
||||
}
|
||||
/>
|
||||
<DebouncedTextArea
|
||||
required
|
||||
name='notes'
|
||||
label='Catatan'
|
||||
rows={3}
|
||||
placeholder='Masukan catatan penjualan'
|
||||
value={formik.values.notes}
|
||||
onChange={formik.handleChange}
|
||||
isError={formik.touched.notes && Boolean(formik.errors.notes)}
|
||||
errorMessage={formik.errors.notes}
|
||||
disabled={
|
||||
formType === 'add_deliver' || formType === 'edit_deliver'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex flex-col h-full justify-end items-end'>
|
||||
<span>Total Penjualan</span>
|
||||
<span className='text-lg font-semibold'>
|
||||
{formatCurrency(grandTotal)}{' '}
|
||||
|
||||
+120
-36
@@ -18,6 +18,11 @@ import * as Yup from 'yup';
|
||||
import { isResponseSuccess } from '@/lib/api-helper';
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import useSWR from 'swr';
|
||||
import { ProductApi } from '@/services/api/master-data';
|
||||
|
||||
const roundWeight = (value: number) => Number(value.toFixed(2));
|
||||
const roundPrice = (value: number) => Math.round(value);
|
||||
|
||||
const DeliveryOrderProductForm = ({
|
||||
formState,
|
||||
@@ -43,6 +48,17 @@ const DeliveryOrderProductForm = ({
|
||||
);
|
||||
const [currentInput, setCurrentInput] = useState<string>('');
|
||||
|
||||
// ============ Fetch Data ============
|
||||
const { data: productData } = useSWR(
|
||||
selectedProduct?.value
|
||||
? ProductApi.basePath + '/' + selectedProduct?.value
|
||||
: null,
|
||||
() =>
|
||||
selectedProduct?.value
|
||||
? ProductApi.getSingle(Number(selectedProduct?.value))
|
||||
: undefined
|
||||
);
|
||||
|
||||
const salesOrder = salesOrders.find(
|
||||
(item) => item.id === initialValues?.marketing_product_id
|
||||
);
|
||||
@@ -90,6 +106,7 @@ const DeliveryOrderProductForm = ({
|
||||
await onUpdateForm?.(values.marketing_product_id as number, values);
|
||||
}
|
||||
handleResetForm();
|
||||
setSelectedProduct(null);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -108,27 +125,84 @@ const DeliveryOrderProductForm = ({
|
||||
marketing_product: undefined,
|
||||
},
|
||||
});
|
||||
setSelectedProduct(null);
|
||||
// setSelectedProduct(null);
|
||||
};
|
||||
|
||||
const handleBlurField = (field: string) => {
|
||||
setCurrentInput(field);
|
||||
const { qty, unit_price, total_price, avg_weight, total_weight } =
|
||||
formik.values;
|
||||
|
||||
if (field === 'unit_price' || field === 'total_price' || field === 'qty') {
|
||||
if (qty && unit_price && (field === 'unit_price' || field === 'qty')) {
|
||||
formik.setFieldValue('total_price', Number(qty) * Number(unit_price));
|
||||
} else if (qty && total_price && field === 'total_price') {
|
||||
formik.setFieldValue('unit_price', Number(total_price) / Number(qty));
|
||||
const qty = Number(formik.values.qty || 0);
|
||||
const avgWeight = Number(formik.values.avg_weight || 0);
|
||||
const totalWeight = Number(formik.values.total_weight || 0);
|
||||
const unitPrice = Number(formik.values.unit_price || 0);
|
||||
const totalPrice = Number(formik.values.total_price || 0);
|
||||
|
||||
if (qty <= 0) return;
|
||||
|
||||
switch (field) {
|
||||
// ===== SOURCE FIELDS =====
|
||||
case 'qty': {
|
||||
if (avgWeight > 0) {
|
||||
const tw = roundWeight(qty * avgWeight);
|
||||
formik.setFieldValue('total_weight', tw);
|
||||
|
||||
// Hitung total_price berdasarkan unit_price × total_weight
|
||||
if (unitPrice > 0) {
|
||||
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (field === 'avg_weight' || field === 'total_weight' || field === 'qty') {
|
||||
if (qty && avg_weight && (field === 'avg_weight' || field === 'qty')) {
|
||||
formik.setFieldValue('total_weight', Number(qty) * Number(avg_weight));
|
||||
} else if (qty && total_weight && field === 'total_weight') {
|
||||
formik.setFieldValue('avg_weight', Number(total_weight) / Number(qty));
|
||||
case 'avg_weight': {
|
||||
if (avgWeight > 0) {
|
||||
const tw = roundWeight(qty * avgWeight);
|
||||
formik.setFieldValue('total_weight', tw);
|
||||
|
||||
// Hitung total_price berdasarkan unit_price × total_weight
|
||||
if (unitPrice > 0) {
|
||||
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'unit_price': {
|
||||
if (unitPrice > 0 && totalWeight > 0) {
|
||||
// Hitung total_price berdasarkan unit_price × total_weight
|
||||
formik.setFieldValue(
|
||||
'total_price',
|
||||
roundPrice(unitPrice * totalWeight)
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// ===== TOTAL EDITABLE =====
|
||||
case 'total_weight': {
|
||||
if (totalWeight > 0) {
|
||||
formik.setFieldValue('avg_weight', roundWeight(totalWeight / qty));
|
||||
|
||||
// Hitung ulang total_price berdasarkan unit_price × total_weight
|
||||
if (unitPrice > 0) {
|
||||
formik.setFieldValue(
|
||||
'total_price',
|
||||
roundPrice(unitPrice * totalWeight)
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'total_price': {
|
||||
if (totalPrice > 0 && totalWeight > 0) {
|
||||
// Hitung unit_price berdasarkan total_price / total_weight
|
||||
formik.setFieldValue(
|
||||
'unit_price',
|
||||
roundPrice(totalPrice / totalWeight)
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -183,7 +257,7 @@ const DeliveryOrderProductForm = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className='grid sm:grid-cols-2 gap-4'>
|
||||
<div className='grid sm:grid-cols-3 gap-4'>
|
||||
<SelectInput
|
||||
options={options}
|
||||
label='Produk'
|
||||
@@ -287,7 +361,9 @@ const DeliveryOrderProductForm = ({
|
||||
isError={Boolean(formik.errors.vehicle_number)}
|
||||
errorMessage={formik.errors.vehicle_number}
|
||||
/>
|
||||
|
||||
</div>
|
||||
<div className='divider my-6'></div>
|
||||
<div className='grid sm:grid-cols-3 gap-4'>
|
||||
<NumberInput
|
||||
required
|
||||
label='Kuantitas'
|
||||
@@ -301,18 +377,42 @@ const DeliveryOrderProductForm = ({
|
||||
isError={Boolean(formik.errors.qty)}
|
||||
errorMessage={formik.errors.qty}
|
||||
placeholder='Masukan Kuantitas'
|
||||
endAdornment={
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-sm text-gray-500'>
|
||||
{isResponseSuccess(productData)
|
||||
? productData?.data?.uom.name
|
||||
: ''}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
bottomLabel={
|
||||
formik.values.marketing_product_id
|
||||
? 'Stok dijual: ' +
|
||||
salesOrders?.find(
|
||||
(item) => item.id === formik.values.marketing_product_id
|
||||
)?.qty
|
||||
)?.qty +
|
||||
' ' +
|
||||
(isResponseSuccess(productData)
|
||||
? productData?.data?.uom.name
|
||||
: '')
|
||||
: ''
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className='divider my-6'></div>
|
||||
<div className='grid sm:grid-cols-2 gap-4'>
|
||||
<NumberInput
|
||||
required
|
||||
label={`Harga / ${isResponseSuccess(productData) ? productData?.data?.uom?.name : 'Produk'} (Rp)`}
|
||||
name='unit_price'
|
||||
value={formik.values.unit_price}
|
||||
onChange={(e) => {
|
||||
formik.handleChange(e);
|
||||
setCurrentInput(e.target.name);
|
||||
}}
|
||||
onBlur={() => handleBlurField('unit_price')}
|
||||
isError={Boolean(formik.errors.unit_price)}
|
||||
errorMessage={formik.errors.unit_price}
|
||||
placeholder='Masukan Harga Satuan'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Avg. Bobot (Kg)'
|
||||
@@ -327,22 +427,6 @@ const DeliveryOrderProductForm = ({
|
||||
errorMessage={formik.errors.avg_weight}
|
||||
placeholder='Masukan Bobot Rata-rata'
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
required
|
||||
label='Harga Satuan (Rp)'
|
||||
name='unit_price'
|
||||
value={formik.values.unit_price}
|
||||
onChange={(e) => {
|
||||
formik.handleChange(e);
|
||||
setCurrentInput(e.target.name);
|
||||
}}
|
||||
onBlur={() => handleBlurField('unit_price')}
|
||||
isError={Boolean(formik.errors.unit_price)}
|
||||
errorMessage={formik.errors.unit_price}
|
||||
placeholder='Masukan Harga Satuan'
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
required
|
||||
label='Total Bobot (Kg)'
|
||||
|
||||
@@ -18,6 +18,7 @@ type SalesOrderProductSchemaType = {
|
||||
avg_weight: string | number | undefined;
|
||||
total_price: string | number | undefined;
|
||||
vehicle_number?: string | undefined;
|
||||
uom?: string | null | undefined;
|
||||
};
|
||||
|
||||
export const SalesOrderProductSchema: Yup.ObjectSchema<SalesOrderProductSchemaType> =
|
||||
@@ -57,6 +58,7 @@ export const SalesOrderProductSchema: Yup.ObjectSchema<SalesOrderProductSchemaTy
|
||||
total_price: Yup.number()
|
||||
.min(1, 'Total Penjualan wajib diisi!')
|
||||
.required('Total Penjualan wajib diisi!'),
|
||||
uom: Yup.string().nullable().optional().notRequired(),
|
||||
});
|
||||
|
||||
export type SalesOrderProductFormValues = Yup.InferType<
|
||||
|
||||
+178
-64
@@ -11,7 +11,7 @@ import SelectInput, {
|
||||
useSelect,
|
||||
} from '@/components/input/SelectInput';
|
||||
import { Kandang } from '@/types/api/master-data/kandang';
|
||||
import { WarehouseApi } from '@/services/api/master-data';
|
||||
import { ProductApi, UomApi, WarehouseApi } from '@/services/api/master-data';
|
||||
import { ProductWarehouse } from '@/types/api/inventory/product-warehouse';
|
||||
import { ProductWarehouseApi } from '@/services/api/inventory';
|
||||
import NumberInput from '@/components/input/NumberInput';
|
||||
@@ -26,6 +26,10 @@ import PatternInput from '@/components/input/PatternInput';
|
||||
import Alert from '@/components/Alert';
|
||||
import AlertErrorList from '@/components/helper/form/FormErrors';
|
||||
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
|
||||
import useSWR from 'swr';
|
||||
|
||||
const roundWeight = (value: number) => Number(value.toFixed(2));
|
||||
const roundPrice = (value: number) => Math.round(value);
|
||||
|
||||
const SalesOrderProductForm = ({
|
||||
initialValues,
|
||||
@@ -35,30 +39,36 @@ const SalesOrderProductForm = ({
|
||||
initialValues?: SalesOrderProductFormValues;
|
||||
exisitingValues?: SalesOrderProductFormValues[];
|
||||
modalRef?: RefObject<HTMLDialogElement | null>;
|
||||
onSubmitForm?: (value: SalesOrderProductFormValues) => Promise<void>;
|
||||
onSubmitForm?: (
|
||||
value: SalesOrderProductFormValues,
|
||||
id?: number
|
||||
) => Promise<void>;
|
||||
}) => {
|
||||
const [formErrorMessage, setFormErrorMessage] = useState('');
|
||||
const [currentInput, setCurrentInput] = useState<string>('');
|
||||
const [selectedProductWarehouse, setSelectedProductWarehouse] =
|
||||
useState<ProductWarehouse | null>(null);
|
||||
|
||||
// ============ Formik ============
|
||||
const formik = useFormik<SalesOrderProductFormValues>({
|
||||
enableReinitialize: true,
|
||||
initialValues: {
|
||||
vehicle_number: initialValues?.vehicle_number || undefined,
|
||||
vehicle_number: initialValues?.vehicle_number || '',
|
||||
kandang_id: initialValues?.kandang_id || undefined,
|
||||
kandang: initialValues?.kandang || undefined,
|
||||
product_warehouse: initialValues?.product_warehouse || undefined,
|
||||
kandang: initialValues?.kandang || null,
|
||||
product_warehouse: initialValues?.product_warehouse || null,
|
||||
product_warehouse_id: initialValues?.product_warehouse_id || undefined,
|
||||
unit_price: initialValues?.unit_price || undefined,
|
||||
total_weight: initialValues?.total_weight || undefined,
|
||||
qty: initialValues?.qty || undefined,
|
||||
avg_weight: initialValues?.avg_weight || undefined,
|
||||
total_price: initialValues?.total_price || undefined,
|
||||
unit_price: initialValues?.unit_price || '',
|
||||
total_weight: initialValues?.total_weight || '',
|
||||
qty: initialValues?.qty || '',
|
||||
avg_weight: initialValues?.avg_weight || '',
|
||||
total_price: initialValues?.total_price || '',
|
||||
uom: initialValues?.uom || '',
|
||||
},
|
||||
validationSchema: SalesOrderProductSchema,
|
||||
onSubmit: async (values) => {
|
||||
setFormErrorMessage('');
|
||||
onSubmitForm?.(values);
|
||||
onSubmitForm?.(values, initialValues?.id);
|
||||
handleResetForm();
|
||||
},
|
||||
validateOnBlur: true,
|
||||
@@ -69,17 +79,21 @@ const SalesOrderProductForm = ({
|
||||
const {
|
||||
options: kandangSourceOptions,
|
||||
isLoadingOptions: isLoadingKandangSourceOptions,
|
||||
setInputValue: setKandangInputValue,
|
||||
loadMore: loadMoreKandang,
|
||||
} = useSelect<Kandang>(WarehouseApi.basePath, 'id', 'name');
|
||||
|
||||
const {
|
||||
options: warehouseSourceOptions,
|
||||
rawData: warehouseSourceRawData,
|
||||
isLoadingOptions: isLoadingWarehouseSourceOptions,
|
||||
setInputValue: setWarehouseInputValue,
|
||||
loadMore: loadMoreWarehouse,
|
||||
} = useSelect<ProductWarehouse>(
|
||||
ProductWarehouseApi.basePath,
|
||||
'id',
|
||||
'product.name',
|
||||
'search',
|
||||
'',
|
||||
{
|
||||
warehouse_id: formik.values.kandang_id?.toString() ?? '',
|
||||
}
|
||||
@@ -112,6 +126,7 @@ const SalesOrderProductForm = ({
|
||||
const productWarehouse = warehouseSourceRawData?.data.find(
|
||||
(item: ProductWarehouse) => item.id === newId
|
||||
);
|
||||
setSelectedProductWarehouse(productWarehouse || null);
|
||||
formik.setFieldValue('qty', productWarehouse?.quantity);
|
||||
handleBlurField('qty');
|
||||
} else {
|
||||
@@ -139,40 +154,130 @@ const SalesOrderProductForm = ({
|
||||
|
||||
const handleBlurField = (field: string) => {
|
||||
setCurrentInput(field);
|
||||
const { qty, unit_price, total_price, avg_weight, total_weight } =
|
||||
formik.values;
|
||||
|
||||
if (field === 'unit_price' || field === 'total_price' || field === 'qty') {
|
||||
if (qty && unit_price && (field === 'unit_price' || field === 'qty')) {
|
||||
formik.setFieldValue(
|
||||
'total_price',
|
||||
(qty as number) * (unit_price as number)
|
||||
);
|
||||
} else if (qty && total_price && field === 'total_price') {
|
||||
formik.setFieldValue(
|
||||
'unit_price',
|
||||
(total_price as number) / (qty as number)
|
||||
);
|
||||
const qty = Number(formik.values.qty || 0);
|
||||
const avgWeight = Number(formik.values.avg_weight || 0);
|
||||
const totalWeight = Number(formik.values.total_weight || 0);
|
||||
const unitPrice = Number(formik.values.unit_price || 0);
|
||||
const totalPrice = Number(formik.values.total_price || 0);
|
||||
|
||||
if (qty <= 0) return;
|
||||
|
||||
// Cek apakah produk memiliki flag OVK atau PAKAN
|
||||
const productFlags = selectedProductWarehouse?.product?.flags || [];
|
||||
const isOvkOrPakan =
|
||||
productFlags.includes('OVK') || productFlags.includes('PAKAN');
|
||||
|
||||
switch (field) {
|
||||
// ===== SOURCE FIELDS =====
|
||||
case 'qty': {
|
||||
if (avgWeight > 0) {
|
||||
const tw = roundWeight(qty * avgWeight);
|
||||
formik.setFieldValue('total_weight', tw);
|
||||
|
||||
// Hitung total_price berdasarkan flag produk
|
||||
if (unitPrice > 0) {
|
||||
if (isOvkOrPakan) {
|
||||
// Untuk OVK/PAKAN: total_price = qty × unit_price
|
||||
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
|
||||
} else {
|
||||
// Untuk produk lain: total_price = unit_price × total_weight
|
||||
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (field === 'avg_weight' || field === 'total_weight' || field === 'qty') {
|
||||
if (qty && avg_weight && (field === 'avg_weight' || field === 'qty')) {
|
||||
formik.setFieldValue(
|
||||
'total_weight',
|
||||
(qty as number) * (avg_weight as number)
|
||||
);
|
||||
} else if (qty && total_weight && field === 'total_weight') {
|
||||
formik.setFieldValue(
|
||||
'avg_weight',
|
||||
(total_weight as number) / (qty as number)
|
||||
);
|
||||
case 'avg_weight': {
|
||||
if (avgWeight > 0) {
|
||||
const tw = roundWeight(qty * avgWeight);
|
||||
formik.setFieldValue('total_weight', tw);
|
||||
|
||||
// Hitung total_price berdasarkan flag produk
|
||||
if (unitPrice > 0) {
|
||||
if (isOvkOrPakan) {
|
||||
// Untuk OVK/PAKAN: total_price = qty × unit_price
|
||||
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
|
||||
} else {
|
||||
// Untuk produk lain: total_price = unit_price × total_weight
|
||||
formik.setFieldValue('total_price', roundPrice(unitPrice * tw));
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'unit_price': {
|
||||
if (unitPrice > 0) {
|
||||
if (isOvkOrPakan) {
|
||||
// Untuk OVK/PAKAN: total_price = qty × unit_price
|
||||
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
|
||||
} else if (totalWeight > 0) {
|
||||
// Untuk produk lain: total_price = unit_price × total_weight
|
||||
formik.setFieldValue(
|
||||
'total_price',
|
||||
roundPrice(unitPrice * totalWeight)
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// ===== TOTAL EDITABLE =====
|
||||
case 'total_weight': {
|
||||
if (totalWeight > 0) {
|
||||
formik.setFieldValue('avg_weight', roundWeight(totalWeight / qty));
|
||||
|
||||
// Hitung ulang total_price berdasarkan flag produk
|
||||
if (unitPrice > 0) {
|
||||
if (isOvkOrPakan) {
|
||||
// Untuk OVK/PAKAN: total_price = qty × unit_price
|
||||
formik.setFieldValue('total_price', roundPrice(qty * unitPrice));
|
||||
} else {
|
||||
// Untuk produk lain: total_price = unit_price × total_weight
|
||||
formik.setFieldValue(
|
||||
'total_price',
|
||||
roundPrice(unitPrice * totalWeight)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'total_price': {
|
||||
if (totalPrice > 0) {
|
||||
if (isOvkOrPakan && qty > 0) {
|
||||
// Untuk OVK/PAKAN: unit_price = total_price / qty
|
||||
formik.setFieldValue('unit_price', roundPrice(totalPrice / qty));
|
||||
} else if (totalWeight > 0) {
|
||||
// Untuk produk lain: unit_price = total_price / total_weight
|
||||
formik.setFieldValue(
|
||||
'unit_price',
|
||||
roundPrice(totalPrice / totalWeight)
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ===== Formik Error List =====
|
||||
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);
|
||||
const { formErrorList, close, handleFormSubmit } = useFormikErrorList(
|
||||
formik,
|
||||
{
|
||||
onBeforeSubmit(e) {
|
||||
e.preventDefault();
|
||||
handleBlurField(currentInput);
|
||||
formik.setFieldValue(
|
||||
'uom',
|
||||
selectedProductWarehouse?.product?.uom?.name
|
||||
);
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -188,7 +293,7 @@ const SalesOrderProductForm = ({
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
<div className='grid sm:grid-cols-2 gap-4 z-200'>
|
||||
<div className='grid sm:grid-cols-3 gap-4 z-200'>
|
||||
<PatternInput
|
||||
name='vehicle_number'
|
||||
label='No. Polisi'
|
||||
@@ -215,6 +320,8 @@ const SalesOrderProductForm = ({
|
||||
value={formik.values.kandang}
|
||||
onChange={kandangChangeHandler}
|
||||
isClearable
|
||||
onInputChange={setKandangInputValue}
|
||||
onMenuScrollToBottom={loadMoreKandang}
|
||||
isError={
|
||||
formik.touched.kandang_id && Boolean(formik.errors.kandang_id)
|
||||
}
|
||||
@@ -228,6 +335,8 @@ const SalesOrderProductForm = ({
|
||||
isLoading={isLoadingWarehouseSourceOptions}
|
||||
value={formik.values.product_warehouse}
|
||||
onChange={warehouseChangeHandler}
|
||||
onInputChange={setWarehouseInputValue}
|
||||
onMenuScrollToBottom={loadMoreWarehouse}
|
||||
isClearable
|
||||
placeholder={
|
||||
formik.values.kandang_id
|
||||
@@ -243,6 +352,9 @@ const SalesOrderProductForm = ({
|
||||
}
|
||||
errorMessage={formik.errors.product_warehouse_id}
|
||||
/>
|
||||
</div>
|
||||
<div className='divider my-6'></div>
|
||||
<div className='grid sm:grid-cols-3 gap-4 z-200'>
|
||||
<NumberInput
|
||||
required
|
||||
label='Kuantitas'
|
||||
@@ -256,6 +368,13 @@ const SalesOrderProductForm = ({
|
||||
isError={formik.touched.qty && Boolean(formik.errors.qty)}
|
||||
errorMessage={formik.errors.qty}
|
||||
placeholder='Masukan Kuantitas'
|
||||
endAdornment={
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-sm text-gray-500'>
|
||||
{selectedProductWarehouse?.product?.uom?.name}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
bottomLabel={
|
||||
isResponseSuccess(warehouseSourceRawData) &&
|
||||
formik.values.product_warehouse_id
|
||||
@@ -263,17 +382,26 @@ const SalesOrderProductForm = ({
|
||||
warehouseSourceRawData?.data?.find(
|
||||
(item) => item.id === formik.values.product_warehouse_id
|
||||
)?.quantity ?? 0
|
||||
)} ${
|
||||
warehouseSourceRawData?.data?.find(
|
||||
(item) => item.id === formik.values.product_warehouse_id
|
||||
)?.product?.uom?.name ?? ''
|
||||
}`
|
||||
)} ${selectedProductWarehouse?.product?.uom?.name}`
|
||||
: ''
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className='divider my-6'></div>
|
||||
<div className='grid sm:grid-cols-2 gap-4 z-200'>
|
||||
<NumberInput
|
||||
required
|
||||
label={`Harga / ${selectedProductWarehouse?.product?.uom?.name ?? 'Produk'} (Rp)`}
|
||||
name='unit_price'
|
||||
value={formik.values.unit_price}
|
||||
onChange={(e) => {
|
||||
formik.handleChange(e);
|
||||
setCurrentInput(e.target.name);
|
||||
}}
|
||||
onBlur={() => handleBlurField('unit_price')}
|
||||
isError={
|
||||
formik.touched.unit_price && Boolean(formik.errors.unit_price)
|
||||
}
|
||||
errorMessage={formik.errors.unit_price}
|
||||
placeholder='Masukan Harga Satuan'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Avg. Bobot (Kg)'
|
||||
@@ -290,22 +418,6 @@ const SalesOrderProductForm = ({
|
||||
errorMessage={formik.errors.avg_weight}
|
||||
placeholder='Masukan Bobot Rata-rata'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Harga Satuan (Rp)'
|
||||
name='unit_price'
|
||||
value={formik.values.unit_price}
|
||||
onChange={(e) => {
|
||||
formik.handleChange(e);
|
||||
setCurrentInput(e.target.name);
|
||||
}}
|
||||
onBlur={() => handleBlurField('unit_price')}
|
||||
isError={
|
||||
formik.touched.unit_price && Boolean(formik.errors.unit_price)
|
||||
}
|
||||
errorMessage={formik.errors.unit_price}
|
||||
placeholder='Masukan Harga Satuan'
|
||||
/>
|
||||
<NumberInput
|
||||
required
|
||||
label='Total Bobot (Kg)'
|
||||
@@ -340,7 +452,9 @@ const SalesOrderProductForm = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
<div className='mt-4'>
|
||||
<AlertErrorList formErrorList={formErrorList} onClose={close} />
|
||||
</div>
|
||||
|
||||
<div className='flex flex-row justify-end gap-3 mt-4'>
|
||||
<Button type='reset' color='warning' onClick={handleResetForm}>
|
||||
|
||||
@@ -16,6 +16,7 @@ type DeliveryOrderProductTableProps = {
|
||||
data: DeliveryOrderProductFormValues[];
|
||||
formType?: 'add' | 'edit' | 'add_deliver' | 'edit_deliver';
|
||||
onEdit: (id: number) => void;
|
||||
onDelete: (id: number) => void;
|
||||
onAddProductClick: () => void;
|
||||
};
|
||||
|
||||
@@ -23,10 +24,13 @@ const DeliveryOrderProductTable = ({
|
||||
data,
|
||||
formType,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAddProductClick,
|
||||
}: DeliveryOrderProductTableProps) => {
|
||||
const onEditRef = useRef(onEdit);
|
||||
onEditRef.current = onEdit;
|
||||
const onDeleteRef = useRef(onDelete);
|
||||
onDeleteRef.current = onDelete;
|
||||
|
||||
const canAddData = data.filter((item) => !Boolean(item.qty));
|
||||
|
||||
@@ -144,16 +148,29 @@ const DeliveryOrderProductTable = ({
|
||||
<div className='flex flex-row gap-1 items-center justify-end h-full mt-2'>
|
||||
<>
|
||||
{props.row.original.qty && (
|
||||
<Button
|
||||
color='warning'
|
||||
className='px-2 py-1 text-sm'
|
||||
onClick={() =>
|
||||
onEditRef.current(props.row.original.id as number)
|
||||
}
|
||||
type='button'
|
||||
>
|
||||
<Icon icon='mdi:edit' width={16} height={16} /> Edit
|
||||
</Button>
|
||||
<>
|
||||
<Button
|
||||
color='warning'
|
||||
className='px-2 py-1 text-sm'
|
||||
onClick={() =>
|
||||
onEditRef.current(props.row.original.id as number)
|
||||
}
|
||||
type='button'
|
||||
>
|
||||
<Icon icon='mdi:edit' width={16} height={16} /> Edit
|
||||
</Button>
|
||||
<Button
|
||||
color='error'
|
||||
className='px-2 py-1 text-sm'
|
||||
onClick={() =>
|
||||
onDeleteRef.current(props.row.original.id as number)
|
||||
}
|
||||
type='button'
|
||||
disabled={!!props.row.original.do_number}
|
||||
>
|
||||
<Icon icon='mdi:delete' width={16} height={16} /> Hapus
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{!props.row.original.qty && '-'}
|
||||
</>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user